repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
mik9/android_kernel_acclaim | drivers/media/dvb/mantis/mantis_evm.c | 1032 | 3800 | /*
Mantis PCI bridge driver
Copyright (C) Manu Abraham (abraham.manu@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; 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/signal.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb_net.h"
#include "mantis_common.h"
#include "mantis_link.h"
#include "mantis_hif.h"
#include "mantis_reg.h"
static void mantis_hifevm_work(struct work_struct *work)
{
struct mantis_ca *ca = container_of(work, struct mantis_ca, hif_evm_work);
struct mantis_pci *mantis = ca->ca_priv;
u32 gpif_stat, gpif_mask;
gpif_stat = mmread(MANTIS_GPIF_STATUS);
gpif_mask = mmread(MANTIS_GPIF_IRQCFG);
if (gpif_stat & MANTIS_GPIF_DETSTAT) {
if (gpif_stat & MANTIS_CARD_PLUGIN) {
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): CAM Plugin", mantis->num);
mmwrite(0xdada0000, MANTIS_CARD_RESET);
mantis_event_cam_plugin(ca);
dvb_ca_en50221_camchange_irq(&ca->en50221,
0,
DVB_CA_EN50221_CAMCHANGE_INSERTED);
}
} else {
if (gpif_stat & MANTIS_CARD_PLUGOUT) {
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): CAM Unplug", mantis->num);
mmwrite(0xdada0000, MANTIS_CARD_RESET);
mantis_event_cam_unplug(ca);
dvb_ca_en50221_camchange_irq(&ca->en50221,
0,
DVB_CA_EN50221_CAMCHANGE_REMOVED);
}
}
if (mantis->gpif_status & MANTIS_GPIF_EXTIRQ)
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): Ext IRQ", mantis->num);
if (mantis->gpif_status & MANTIS_SBUF_WSTO)
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): Smart Buffer Timeout", mantis->num);
if (mantis->gpif_status & MANTIS_GPIF_OTHERR)
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): Alignment Error", mantis->num);
if (gpif_stat & MANTIS_SBUF_OVFLW)
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): Smart Buffer Overflow", mantis->num);
if (gpif_stat & MANTIS_GPIF_BRRDY)
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): Smart Buffer Read Ready", mantis->num);
if (gpif_stat & MANTIS_GPIF_INTSTAT)
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): GPIF IRQ", mantis->num);
if (gpif_stat & MANTIS_SBUF_EMPTY)
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): Smart Buffer Empty", mantis->num);
if (gpif_stat & MANTIS_SBUF_OPDONE) {
dprintk(MANTIS_DEBUG, 1, "Event Mgr: Adapter(%d) Slot(0): Smart Buffer operation complete", mantis->num);
ca->sbuf_status = MANTIS_SBUF_DATA_AVAIL;
ca->hif_event = MANTIS_SBUF_OPDONE;
wake_up(&ca->hif_opdone_wq);
}
}
int mantis_evmgr_init(struct mantis_ca *ca)
{
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Initializing Mantis Host I/F Event manager");
INIT_WORK(&ca->hif_evm_work, mantis_hifevm_work);
mantis_pcmcia_init(ca);
schedule_work(&ca->hif_evm_work);
mantis_hif_init(ca);
return 0;
}
void mantis_evmgr_exit(struct mantis_ca *ca)
{
struct mantis_pci *mantis = ca->ca_priv;
dprintk(MANTIS_DEBUG, 1, "Mantis Host I/F Event manager exiting");
flush_scheduled_work();
mantis_hif_exit(ca);
mantis_pcmcia_exit(ca);
}
| gpl-2.0 |
caoyuhua/Linux-3.10.28 | drivers/hwmon/gpio-fan.c | 1288 | 14833 | /*
* gpio-fan.c - Hwmon driver for fans connected to GPIO lines.
*
* Copyright (C) 2010 LaCie
*
* Author: Simon Guinot <sguinot@lacie.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/hwmon.h>
#include <linux/gpio.h>
#include <linux/gpio-fan.h>
#include <linux/of_platform.h>
#include <linux/of_gpio.h>
struct gpio_fan_data {
struct platform_device *pdev;
struct device *hwmon_dev;
struct mutex lock; /* lock GPIOs operations. */
int num_ctrl;
unsigned *ctrl;
int num_speed;
struct gpio_fan_speed *speed;
int speed_index;
#ifdef CONFIG_PM_SLEEP
int resume_speed;
#endif
bool pwm_enable;
struct gpio_fan_alarm *alarm;
struct work_struct alarm_work;
};
/*
* Alarm GPIO.
*/
static void fan_alarm_notify(struct work_struct *ws)
{
struct gpio_fan_data *fan_data =
container_of(ws, struct gpio_fan_data, alarm_work);
sysfs_notify(&fan_data->pdev->dev.kobj, NULL, "fan1_alarm");
kobject_uevent(&fan_data->pdev->dev.kobj, KOBJ_CHANGE);
}
static irqreturn_t fan_alarm_irq_handler(int irq, void *dev_id)
{
struct gpio_fan_data *fan_data = dev_id;
schedule_work(&fan_data->alarm_work);
return IRQ_NONE;
}
static ssize_t show_fan_alarm(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
struct gpio_fan_alarm *alarm = fan_data->alarm;
int value = gpio_get_value(alarm->gpio);
if (alarm->active_low)
value = !value;
return sprintf(buf, "%d\n", value);
}
static DEVICE_ATTR(fan1_alarm, S_IRUGO, show_fan_alarm, NULL);
static int fan_alarm_init(struct gpio_fan_data *fan_data,
struct gpio_fan_alarm *alarm)
{
int err;
int alarm_irq;
struct platform_device *pdev = fan_data->pdev;
fan_data->alarm = alarm;
err = devm_gpio_request(&pdev->dev, alarm->gpio, "GPIO fan alarm");
if (err)
return err;
err = gpio_direction_input(alarm->gpio);
if (err)
return err;
/*
* If the alarm GPIO don't support interrupts, just leave
* without initializing the fail notification support.
*/
alarm_irq = gpio_to_irq(alarm->gpio);
if (alarm_irq < 0)
return 0;
INIT_WORK(&fan_data->alarm_work, fan_alarm_notify);
irq_set_irq_type(alarm_irq, IRQ_TYPE_EDGE_BOTH);
err = devm_request_irq(&pdev->dev, alarm_irq, fan_alarm_irq_handler,
IRQF_SHARED, "GPIO fan alarm", fan_data);
return err;
}
/*
* Control GPIOs.
*/
/* Must be called with fan_data->lock held, except during initialization. */
static void __set_fan_ctrl(struct gpio_fan_data *fan_data, int ctrl_val)
{
int i;
for (i = 0; i < fan_data->num_ctrl; i++)
gpio_set_value(fan_data->ctrl[i], (ctrl_val >> i) & 1);
}
static int __get_fan_ctrl(struct gpio_fan_data *fan_data)
{
int i;
int ctrl_val = 0;
for (i = 0; i < fan_data->num_ctrl; i++) {
int value;
value = gpio_get_value(fan_data->ctrl[i]);
ctrl_val |= (value << i);
}
return ctrl_val;
}
/* Must be called with fan_data->lock held, except during initialization. */
static void set_fan_speed(struct gpio_fan_data *fan_data, int speed_index)
{
if (fan_data->speed_index == speed_index)
return;
__set_fan_ctrl(fan_data, fan_data->speed[speed_index].ctrl_val);
fan_data->speed_index = speed_index;
}
static int get_fan_speed_index(struct gpio_fan_data *fan_data)
{
int ctrl_val = __get_fan_ctrl(fan_data);
int i;
for (i = 0; i < fan_data->num_speed; i++)
if (fan_data->speed[i].ctrl_val == ctrl_val)
return i;
dev_warn(&fan_data->pdev->dev,
"missing speed array entry for GPIO value 0x%x\n", ctrl_val);
return -EINVAL;
}
static int rpm_to_speed_index(struct gpio_fan_data *fan_data, int rpm)
{
struct gpio_fan_speed *speed = fan_data->speed;
int i;
for (i = 0; i < fan_data->num_speed; i++)
if (speed[i].rpm >= rpm)
return i;
return fan_data->num_speed - 1;
}
static ssize_t show_pwm(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
u8 pwm = fan_data->speed_index * 255 / (fan_data->num_speed - 1);
return sprintf(buf, "%d\n", pwm);
}
static ssize_t set_pwm(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
unsigned long pwm;
int speed_index;
int ret = count;
if (kstrtoul(buf, 10, &pwm) || pwm > 255)
return -EINVAL;
mutex_lock(&fan_data->lock);
if (!fan_data->pwm_enable) {
ret = -EPERM;
goto exit_unlock;
}
speed_index = DIV_ROUND_UP(pwm * (fan_data->num_speed - 1), 255);
set_fan_speed(fan_data, speed_index);
exit_unlock:
mutex_unlock(&fan_data->lock);
return ret;
}
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", fan_data->pwm_enable);
}
static ssize_t set_pwm_enable(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
unsigned long val;
if (kstrtoul(buf, 10, &val) || val > 1)
return -EINVAL;
if (fan_data->pwm_enable == val)
return count;
mutex_lock(&fan_data->lock);
fan_data->pwm_enable = val;
/* Disable manual control mode: set fan at full speed. */
if (val == 0)
set_fan_speed(fan_data, fan_data->num_speed - 1);
mutex_unlock(&fan_data->lock);
return count;
}
static ssize_t show_pwm_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "0\n");
}
static ssize_t show_rpm_min(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", fan_data->speed[0].rpm);
}
static ssize_t show_rpm_max(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
return sprintf(buf, "%d\n",
fan_data->speed[fan_data->num_speed - 1].rpm);
}
static ssize_t show_rpm(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", fan_data->speed[fan_data->speed_index].rpm);
}
static ssize_t set_rpm(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
unsigned long rpm;
int ret = count;
if (kstrtoul(buf, 10, &rpm))
return -EINVAL;
mutex_lock(&fan_data->lock);
if (!fan_data->pwm_enable) {
ret = -EPERM;
goto exit_unlock;
}
set_fan_speed(fan_data, rpm_to_speed_index(fan_data, rpm));
exit_unlock:
mutex_unlock(&fan_data->lock);
return ret;
}
static ssize_t show_name(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "gpio-fan\n");
}
static DEVICE_ATTR(pwm1, S_IRUGO | S_IWUSR, show_pwm, set_pwm);
static DEVICE_ATTR(pwm1_enable, S_IRUGO | S_IWUSR,
show_pwm_enable, set_pwm_enable);
static DEVICE_ATTR(pwm1_mode, S_IRUGO, show_pwm_mode, NULL);
static DEVICE_ATTR(fan1_min, S_IRUGO, show_rpm_min, NULL);
static DEVICE_ATTR(fan1_max, S_IRUGO, show_rpm_max, NULL);
static DEVICE_ATTR(fan1_input, S_IRUGO, show_rpm, NULL);
static DEVICE_ATTR(fan1_target, S_IRUGO | S_IWUSR, show_rpm, set_rpm);
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
static umode_t gpio_fan_is_visible(struct kobject *kobj,
struct attribute *attr, int index)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct gpio_fan_data *data = dev_get_drvdata(dev);
if (index == 1 && !data->alarm)
return 0;
if (index > 1 && !data->ctrl)
return 0;
return attr->mode;
}
static struct attribute *gpio_fan_attributes[] = {
&dev_attr_name.attr,
&dev_attr_fan1_alarm.attr, /* 1 */
&dev_attr_pwm1.attr, /* 2 */
&dev_attr_pwm1_enable.attr,
&dev_attr_pwm1_mode.attr,
&dev_attr_fan1_input.attr,
&dev_attr_fan1_target.attr,
&dev_attr_fan1_min.attr,
&dev_attr_fan1_max.attr,
NULL
};
static const struct attribute_group gpio_fan_group = {
.attrs = gpio_fan_attributes,
.is_visible = gpio_fan_is_visible,
};
static int fan_ctrl_init(struct gpio_fan_data *fan_data,
struct gpio_fan_platform_data *pdata)
{
struct platform_device *pdev = fan_data->pdev;
int num_ctrl = pdata->num_ctrl;
unsigned *ctrl = pdata->ctrl;
int i, err;
for (i = 0; i < num_ctrl; i++) {
err = devm_gpio_request(&pdev->dev, ctrl[i],
"GPIO fan control");
if (err)
return err;
err = gpio_direction_output(ctrl[i], gpio_get_value(ctrl[i]));
if (err)
return err;
}
fan_data->num_ctrl = num_ctrl;
fan_data->ctrl = ctrl;
fan_data->num_speed = pdata->num_speed;
fan_data->speed = pdata->speed;
fan_data->pwm_enable = true; /* Enable manual fan speed control. */
fan_data->speed_index = get_fan_speed_index(fan_data);
if (fan_data->speed_index < 0)
return -ENODEV;
return 0;
}
#ifdef CONFIG_OF_GPIO
/*
* Translate OpenFirmware node properties into platform_data
*/
static int gpio_fan_get_of_pdata(struct device *dev,
struct gpio_fan_platform_data *pdata)
{
struct device_node *node;
struct gpio_fan_speed *speed;
unsigned *ctrl;
unsigned i;
u32 u;
struct property *prop;
const __be32 *p;
node = dev->of_node;
/* Fill GPIO pin array */
pdata->num_ctrl = of_gpio_count(node);
if (pdata->num_ctrl <= 0) {
dev_err(dev, "gpios DT property empty / missing");
return -ENODEV;
}
ctrl = devm_kzalloc(dev, pdata->num_ctrl * sizeof(unsigned),
GFP_KERNEL);
if (!ctrl)
return -ENOMEM;
for (i = 0; i < pdata->num_ctrl; i++) {
int val;
val = of_get_gpio(node, i);
if (val < 0)
return val;
ctrl[i] = val;
}
pdata->ctrl = ctrl;
/* Get number of RPM/ctrl_val pairs in speed map */
prop = of_find_property(node, "gpio-fan,speed-map", &i);
if (!prop) {
dev_err(dev, "gpio-fan,speed-map DT property missing");
return -ENODEV;
}
i = i / sizeof(u32);
if (i == 0 || i & 1) {
dev_err(dev, "gpio-fan,speed-map contains zero/odd number of entries");
return -ENODEV;
}
pdata->num_speed = i / 2;
/*
* Populate speed map
* Speed map is in the form <RPM ctrl_val RPM ctrl_val ...>
* this needs splitting into pairs to create gpio_fan_speed structs
*/
speed = devm_kzalloc(dev,
pdata->num_speed * sizeof(struct gpio_fan_speed),
GFP_KERNEL);
if (!speed)
return -ENOMEM;
p = NULL;
for (i = 0; i < pdata->num_speed; i++) {
p = of_prop_next_u32(prop, p, &u);
if (!p)
return -ENODEV;
speed[i].rpm = u;
p = of_prop_next_u32(prop, p, &u);
if (!p)
return -ENODEV;
speed[i].ctrl_val = u;
}
pdata->speed = speed;
/* Alarm GPIO if one exists */
if (of_gpio_named_count(node, "alarm-gpios") > 0) {
struct gpio_fan_alarm *alarm;
int val;
enum of_gpio_flags flags;
alarm = devm_kzalloc(dev, sizeof(struct gpio_fan_alarm),
GFP_KERNEL);
if (!alarm)
return -ENOMEM;
val = of_get_named_gpio_flags(node, "alarm-gpios", 0, &flags);
if (val < 0)
return val;
alarm->gpio = val;
alarm->active_low = flags & OF_GPIO_ACTIVE_LOW;
pdata->alarm = alarm;
}
return 0;
}
static struct of_device_id of_gpio_fan_match[] = {
{ .compatible = "gpio-fan", },
{},
};
#endif /* CONFIG_OF_GPIO */
static int gpio_fan_probe(struct platform_device *pdev)
{
int err;
struct gpio_fan_data *fan_data;
struct gpio_fan_platform_data *pdata = pdev->dev.platform_data;
#ifdef CONFIG_OF_GPIO
if (!pdata) {
pdata = devm_kzalloc(&pdev->dev,
sizeof(struct gpio_fan_platform_data),
GFP_KERNEL);
if (!pdata)
return -ENOMEM;
err = gpio_fan_get_of_pdata(&pdev->dev, pdata);
if (err)
return err;
}
#else /* CONFIG_OF_GPIO */
if (!pdata)
return -EINVAL;
#endif /* CONFIG_OF_GPIO */
fan_data = devm_kzalloc(&pdev->dev, sizeof(struct gpio_fan_data),
GFP_KERNEL);
if (!fan_data)
return -ENOMEM;
fan_data->pdev = pdev;
platform_set_drvdata(pdev, fan_data);
mutex_init(&fan_data->lock);
/* Configure alarm GPIO if available. */
if (pdata->alarm) {
err = fan_alarm_init(fan_data, pdata->alarm);
if (err)
return err;
}
/* Configure control GPIOs if available. */
if (pdata->ctrl && pdata->num_ctrl > 0) {
if (!pdata->speed || pdata->num_speed <= 1)
return -EINVAL;
err = fan_ctrl_init(fan_data, pdata);
if (err)
return err;
}
err = sysfs_create_group(&pdev->dev.kobj, &gpio_fan_group);
if (err)
return err;
/* Make this driver part of hwmon class. */
fan_data->hwmon_dev = hwmon_device_register(&pdev->dev);
if (IS_ERR(fan_data->hwmon_dev)) {
err = PTR_ERR(fan_data->hwmon_dev);
goto err_remove;
}
dev_info(&pdev->dev, "GPIO fan initialized\n");
return 0;
err_remove:
sysfs_remove_group(&pdev->dev.kobj, &gpio_fan_group);
return err;
}
static int gpio_fan_remove(struct platform_device *pdev)
{
struct gpio_fan_data *fan_data = platform_get_drvdata(pdev);
hwmon_device_unregister(fan_data->hwmon_dev);
sysfs_remove_group(&pdev->dev.kobj, &gpio_fan_group);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int gpio_fan_suspend(struct device *dev)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
if (fan_data->ctrl) {
fan_data->resume_speed = fan_data->speed_index;
set_fan_speed(fan_data, 0);
}
return 0;
}
static int gpio_fan_resume(struct device *dev)
{
struct gpio_fan_data *fan_data = dev_get_drvdata(dev);
if (fan_data->ctrl)
set_fan_speed(fan_data, fan_data->resume_speed);
return 0;
}
static SIMPLE_DEV_PM_OPS(gpio_fan_pm, gpio_fan_suspend, gpio_fan_resume);
#define GPIO_FAN_PM (&gpio_fan_pm)
#else
#define GPIO_FAN_PM NULL
#endif
static struct platform_driver gpio_fan_driver = {
.probe = gpio_fan_probe,
.remove = gpio_fan_remove,
.driver = {
.name = "gpio-fan",
.pm = GPIO_FAN_PM,
#ifdef CONFIG_OF_GPIO
.of_match_table = of_match_ptr(of_gpio_fan_match),
#endif
},
};
module_platform_driver(gpio_fan_driver);
MODULE_AUTHOR("Simon Guinot <sguinot@lacie.com>");
MODULE_DESCRIPTION("GPIO FAN driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:gpio-fan");
| gpl-2.0 |
sammy44nts/linux-kernel | drivers/staging/ozwpan/ozurbparanoia.c | 1544 | 1321 | /* -----------------------------------------------------------------------------
* Copyright (c) 2011 Ozmo Inc
* Released under the GNU General Public License Version 2 (GPLv2).
* -----------------------------------------------------------------------------
*/
#include <linux/usb.h>
#include "ozdbg.h"
#ifdef WANT_URB_PARANOIA
#include "ozurbparanoia.h"
#define OZ_MAX_URBS 1000
struct urb *g_urb_memory[OZ_MAX_URBS];
int g_nb_urbs;
DEFINE_SPINLOCK(g_urb_mem_lock);
void oz_remember_urb(struct urb *urb)
{
unsigned long irq_state;
spin_lock_irqsave(&g_urb_mem_lock, irq_state);
if (g_nb_urbs < OZ_MAX_URBS) {
g_urb_memory[g_nb_urbs++] = urb;
oz_dbg(ON, "urb up = %d %p\n", g_nb_urbs, urb);
} else {
oz_dbg(ON, "ERROR urb buffer full\n");
}
spin_unlock_irqrestore(&g_urb_mem_lock, irq_state);
}
/*
*/
int oz_forget_urb(struct urb *urb)
{
unsigned long irq_state;
int i;
int rc = -1;
spin_lock_irqsave(&g_urb_mem_lock, irq_state);
for (i = 0; i < g_nb_urbs; i++) {
if (g_urb_memory[i] == urb) {
rc = 0;
if (--g_nb_urbs > i)
memcpy(&g_urb_memory[i], &g_urb_memory[i+1],
(g_nb_urbs - i) * sizeof(struct urb *));
oz_dbg(ON, "urb down = %d %p\n", g_nb_urbs, urb);
}
}
spin_unlock_irqrestore(&g_urb_mem_lock, irq_state);
return rc;
}
#endif /* #ifdef WANT_URB_PARANOIA */
| gpl-2.0 |
thiz11/kernel_common | drivers/staging/rtl8187se/r8180_wx.c | 2312 | 33821 | /*
This file contains wireless extension handlers.
This is part of rtl8180 OpenSource driver.
Copyright (C) Andrea Merello 2004-2005 <andreamrl@tiscali.it>
Released under the terms of GPL (General Public Licence)
Parts of this driver are based on the GPL part
of the official realtek driver.
Parts of this driver are based on the rtl8180 driver skeleton
from Patric Schenke & Andres Salomon.
Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver.
We want to thanks the Authors of those projects and the Ndiswrapper
project Authors.
*/
#include "r8180.h"
#include "r8180_hw.h"
#include "ieee80211/dot11d.h"
u32 rtl8180_rates[] = {1000000, 2000000, 5500000, 11000000,
6000000, 9000000, 12000000, 18000000, 24000000, 36000000, 48000000, 54000000};
#define RATE_COUNT ARRAY_SIZE(rtl8180_rates)
static CHANNEL_LIST DefaultChannelPlan[] = {
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 36, 40, 44, 48, 52, 56, 60, 64}, 19}, /* FCC */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 11}, /* IC */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 36, 40, 44, 48, 52, 56, 60, 64}, 21}, /* ETSI */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 36, 40, 44, 48, 52, 56, 60, 64}, 21}, /* Spain. Change to ETSI. */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 36, 40, 44, 48, 52, 56, 60, 64}, 21}, /* France. Change to ETSI. */
{{14, 36, 40, 44, 48, 52, 56, 60, 64}, 9}, /* MKK */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 36, 40, 44, 48, 52, 56, 60, 64}, 22}, /* MKK1 */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 36, 40, 44, 48, 52, 56, 60, 64}, 21}, /* Israel */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 34, 38, 42, 46}, 17}, /* For 11a , TELEC */
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}, 14} /* For Global Domain. 1-11:active scan, 12-14 passive scan.*/ /* +YJ, 080626 */
};
static int r8180_wx_get_freq(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct r8180_priv *priv = ieee80211_priv(dev);
return ieee80211_wx_get_freq(priv->ieee80211, a, wrqu, b);
}
int r8180_wx_set_key(struct net_device *dev, struct iw_request_info *info,
union iwreq_data *wrqu, char *key)
{
struct r8180_priv *priv = ieee80211_priv(dev);
struct iw_point *erq = &(wrqu->encoding);
if (priv->ieee80211->bHwRadioOff)
return 0;
if (erq->length > 0) {
u32* tkey = (u32*) key;
priv->key0[0] = tkey[0];
priv->key0[1] = tkey[1];
priv->key0[2] = tkey[2];
priv->key0[3] = tkey[3] & 0xff;
DMESG("Setting wep key to %x %x %x %x",
tkey[0], tkey[1], tkey[2], tkey[3]);
rtl8180_set_hw_wep(dev);
}
return 0;
}
static int r8180_wx_set_beaconinterval(struct net_device *dev, struct iw_request_info *aa,
union iwreq_data *wrqu, char *b)
{
int *parms = (int *)b;
int bi = parms[0];
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
DMESG("setting beacon interval to %x", bi);
priv->ieee80211->current_network.beacon_interval = bi;
rtl8180_commit(dev);
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_get_mode(struct net_device *dev, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct r8180_priv *priv = ieee80211_priv(dev);
return ieee80211_wx_get_mode(priv->ieee80211, a, wrqu, b);
}
static int r8180_wx_get_rate(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
return ieee80211_wx_get_rate(priv->ieee80211, info, wrqu, extra);
}
static int r8180_wx_set_rate(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret;
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
ret = ieee80211_wx_set_rate(priv->ieee80211, info, wrqu, extra);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_crcmon(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int *parms = (int *)extra;
int enable = (parms[0] > 0);
short prev = priv->crcmon;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (enable)
priv->crcmon = 1;
else
priv->crcmon = 0;
DMESG("bad CRC in monitor mode are %s",
priv->crcmon ? "accepted" : "rejected");
if (prev != priv->crcmon && priv->up) {
rtl8180_down(dev);
rtl8180_up(dev);
}
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_set_mode(struct net_device *dev, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (priv->bInactivePs) {
if (wrqu->mode == IW_MODE_ADHOC)
IPSLeave(dev);
}
ret = ieee80211_wx_set_mode(priv->ieee80211, a, wrqu, b);
up(&priv->wx_sem);
return ret;
}
/* YJ,add,080819,for hidden ap */
struct iw_range_with_scan_capa {
/* Informative stuff (to choose between different interface) */
__u32 throughput; /* To give an idea... */
/* In theory this value should be the maximum benchmarked
* TCP/IP throughput, because with most of these devices the
* bit rate is meaningless (overhead an co) to estimate how
* fast the connection will go and pick the fastest one.
* I suggest people to play with Netperf or any benchmark...
*/
/* NWID (or domain id) */
__u32 min_nwid; /* Minimal NWID we are able to set */
__u32 max_nwid; /* Maximal NWID we are able to set */
/* Old Frequency (backward compat - moved lower ) */
__u16 old_num_channels;
__u8 old_num_frequency;
/* Scan capabilities */
__u8 scan_capa;
};
/* YJ,add,080819,for hidden ap */
static int rtl8180_wx_get_range(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct iw_range *range = (struct iw_range *)extra;
struct r8180_priv *priv = ieee80211_priv(dev);
u16 val;
int i;
wrqu->data.length = sizeof(*range);
memset(range, 0, sizeof(*range));
/* Let's try to keep this struct in the same order as in
* linux/include/wireless.h
*/
/* TODO: See what values we can set, and remove the ones we can't
* set, or fill them with some default data.
*/
/* ~5 Mb/s real (802.11b) */
range->throughput = 5 * 1000 * 1000;
/* TODO: Not used in 802.11b? */
/* range->min_nwid; */ /* Minimal NWID we are able to set */
/* TODO: Not used in 802.11b? */
/* range->max_nwid; */ /* Maximal NWID we are able to set */
/* Old Frequency (backward compat - moved lower ) */
/* range->old_num_channels; */
/* range->old_num_frequency; */
/* range->old_freq[6]; */ /* Filler to keep "version" at the same offset */
if (priv->rf_set_sens != NULL)
range->sensitivity = priv->max_sens; /* signal level threshold range */
range->max_qual.qual = 100;
/* TODO: Find real max RSSI and stick here */
range->max_qual.level = 0;
range->max_qual.noise = -98;
range->max_qual.updated = 7; /* Updated all three */
range->avg_qual.qual = 92; /* > 8% missed beacons is 'bad' */
/* TODO: Find real 'good' to 'bad' threshold value for RSSI */
range->avg_qual.level = 20 + -98;
range->avg_qual.noise = 0;
range->avg_qual.updated = 7; /* Updated all three */
range->num_bitrates = RATE_COUNT;
for (i = 0; i < RATE_COUNT && i < IW_MAX_BITRATES; i++)
range->bitrate[i] = rtl8180_rates[i];
range->min_frag = MIN_FRAG_THRESHOLD;
range->max_frag = MAX_FRAG_THRESHOLD;
range->pm_capa = 0;
range->we_version_compiled = WIRELESS_EXT;
range->we_version_source = 16;
range->num_channels = 14;
for (i = 0, val = 0; i < 14; i++) {
/* Include only legal frequencies for some countries */
if ((GET_DOT11D_INFO(priv->ieee80211)->channel_map)[i+1]) {
range->freq[val].i = i + 1;
range->freq[val].m = ieee80211_wlan_frequencies[i] * 100000;
range->freq[val].e = 1;
val++;
} else {
/* FIXME: do we need to set anything for channels */
/* we don't use ? */
}
if (val == IW_MAX_FREQUENCIES)
break;
}
range->num_frequency = val;
range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_WPA2 |
IW_ENC_CAPA_CIPHER_TKIP | IW_ENC_CAPA_CIPHER_CCMP;
return 0;
}
static int r8180_wx_set_scan(struct net_device *dev, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret;
struct ieee80211_device* ieee = priv->ieee80211;
if (priv->ieee80211->bHwRadioOff)
return 0;
if (wrqu->data.flags & IW_SCAN_THIS_ESSID) {
struct iw_scan_req* req = (struct iw_scan_req*)b;
if (req->essid_len) {
ieee->current_network.ssid_len = req->essid_len;
memcpy(ieee->current_network.ssid, req->essid, req->essid_len);
}
}
down(&priv->wx_sem);
if (priv->up) {
priv->ieee80211->actscanning = true;
if (priv->bInactivePs && (priv->ieee80211->state != IEEE80211_LINKED)) {
IPSLeave(dev);
ieee80211_softmac_ips_scan_syncro(priv->ieee80211);
ret = 0;
} else {
/* prevent scan in BusyTraffic */
/* FIXME: Need to consider last scan time */
if ((priv->link_detect.bBusyTraffic) && (true)) {
ret = 0;
printk("Now traffic is busy, please try later!\n");
} else
/* prevent scan in BusyTraffic,end */
ret = ieee80211_wx_set_scan(priv->ieee80211, a, wrqu, b);
}
} else
ret = -1;
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_scan(struct net_device *dev, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
int ret;
struct r8180_priv *priv = ieee80211_priv(dev);
down(&priv->wx_sem);
if (priv->up)
ret = ieee80211_wx_get_scan(priv->ieee80211, a, wrqu, b);
else
ret = -1;
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_essid(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (priv->bInactivePs)
IPSLeave(dev);
ret = ieee80211_wx_set_essid(priv->ieee80211, a, wrqu, b);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_essid(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
int ret;
struct r8180_priv *priv = ieee80211_priv(dev);
down(&priv->wx_sem);
ret = ieee80211_wx_get_essid(priv->ieee80211, a, wrqu, b);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_freq(struct net_device *dev, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
int ret;
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
ret = ieee80211_wx_set_freq(priv->ieee80211, a, wrqu, b);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_name(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
return ieee80211_wx_get_name(priv->ieee80211, info, wrqu, extra);
}
static int r8180_wx_set_frag(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
if (wrqu->frag.disabled)
priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
else {
if (wrqu->frag.value < MIN_FRAG_THRESHOLD ||
wrqu->frag.value > MAX_FRAG_THRESHOLD)
return -EINVAL;
priv->ieee80211->fts = wrqu->frag.value & ~0x1;
}
return 0;
}
static int r8180_wx_get_frag(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
wrqu->frag.value = priv->ieee80211->fts;
wrqu->frag.fixed = 0; /* no auto select */
wrqu->frag.disabled = (wrqu->frag.value == DEFAULT_FRAG_THRESHOLD);
return 0;
}
static int r8180_wx_set_wap(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *awrq,
char *extra)
{
int ret;
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
ret = ieee80211_wx_set_wap(priv->ieee80211, info, awrq, extra);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_wap(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
return ieee80211_wx_get_wap(priv->ieee80211, info, wrqu, extra);
}
static int r8180_wx_set_enc(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *key)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (priv->hw_wep) ret = r8180_wx_set_key(dev, info, wrqu, key);
else {
DMESG("Setting SW wep key");
ret = ieee80211_wx_set_encode(priv->ieee80211, info, wrqu, key);
}
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_enc(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *key)
{
struct r8180_priv *priv = ieee80211_priv(dev);
return ieee80211_wx_get_encode(priv->ieee80211, info, wrqu, key);
}
static int r8180_wx_set_scan_type(struct net_device *dev, struct iw_request_info *aa, union
iwreq_data *wrqu, char *p) {
struct r8180_priv *priv = ieee80211_priv(dev);
int *parms = (int*)p;
int mode = parms[0];
if (priv->ieee80211->bHwRadioOff)
return 0;
priv->ieee80211->active_scan = mode;
return 1;
}
static int r8180_wx_set_retry(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int err = 0;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (wrqu->retry.flags & IW_RETRY_LIFETIME ||
wrqu->retry.disabled) {
err = -EINVAL;
goto exit;
}
if (!(wrqu->retry.flags & IW_RETRY_LIMIT)) {
err = -EINVAL;
goto exit;
}
if (wrqu->retry.value > R8180_MAX_RETRY) {
err = -EINVAL;
goto exit;
}
if (wrqu->retry.flags & IW_RETRY_MAX) {
priv->retry_rts = wrqu->retry.value;
DMESG("Setting retry for RTS/CTS data to %d", wrqu->retry.value);
} else {
priv->retry_data = wrqu->retry.value;
DMESG("Setting retry for non RTS/CTS data to %d", wrqu->retry.value);
}
/* FIXME !
* We might try to write directly the TX config register
* or to restart just the (R)TX process.
* I'm unsure if whole reset is really needed
*/
rtl8180_commit(dev);
exit:
up(&priv->wx_sem);
return err;
}
static int r8180_wx_get_retry(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
wrqu->retry.disabled = 0; /* can't be disabled */
if ((wrqu->retry.flags & IW_RETRY_TYPE) ==
IW_RETRY_LIFETIME)
return -EINVAL;
if (wrqu->retry.flags & IW_RETRY_MAX) {
wrqu->retry.flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
wrqu->retry.value = priv->retry_rts;
} else {
wrqu->retry.flags = IW_RETRY_LIMIT | IW_RETRY_MIN;
wrqu->retry.value = priv->retry_data;
}
return 0;
}
static int r8180_wx_get_sens(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->rf_set_sens == NULL)
return -1; /* we have not this support for this radio */
wrqu->sens.value = priv->sens;
return 0;
}
static int r8180_wx_set_sens(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
short err = 0;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (priv->rf_set_sens == NULL) {
err = -1; /* we have not this support for this radio */
goto exit;
}
if (priv->rf_set_sens(dev, wrqu->sens.value) == 0)
priv->sens = wrqu->sens.value;
else
err = -EINVAL;
exit:
up(&priv->wx_sem);
return err;
}
static int r8180_wx_set_rawtx(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
ret = ieee80211_wx_set_rawtx(priv->ieee80211, info, wrqu, extra);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_power(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret;
struct r8180_priv *priv = ieee80211_priv(dev);
down(&priv->wx_sem);
ret = ieee80211_wx_get_power(priv->ieee80211, info, wrqu, extra);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_power(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret;
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
printk("=>>>>>>>>>>=============================>set power:%d, %d!\n", wrqu->power.disabled, wrqu->power.flags);
if (wrqu->power.disabled == 0) {
wrqu->power.flags |= IW_POWER_ALL_R;
wrqu->power.flags |= IW_POWER_TIMEOUT;
wrqu->power.value = 1000;
}
ret = ieee80211_wx_set_power(priv->ieee80211, info, wrqu, extra);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_rts(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
if (wrqu->rts.disabled)
priv->rts = DEFAULT_RTS_THRESHOLD;
else {
if (wrqu->rts.value < MIN_RTS_THRESHOLD ||
wrqu->rts.value > MAX_RTS_THRESHOLD)
return -EINVAL;
priv->rts = wrqu->rts.value;
}
return 0;
}
static int r8180_wx_get_rts(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
wrqu->rts.value = priv->rts;
wrqu->rts.fixed = 0; /* no auto select */
wrqu->rts.disabled = (wrqu->rts.value == 0);
return 0;
}
static int dummy(struct net_device *dev, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
return -1;
}
static int r8180_wx_get_iwmode(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
struct ieee80211_device *ieee;
int ret = 0;
down(&priv->wx_sem);
ieee = priv->ieee80211;
strcpy(extra, "802.11");
if (ieee->modulation & IEEE80211_CCK_MODULATION) {
strcat(extra, "b");
if (ieee->modulation & IEEE80211_OFDM_MODULATION)
strcat(extra, "/g");
} else if (ieee->modulation & IEEE80211_OFDM_MODULATION)
strcat(extra, "g");
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_iwmode(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
struct ieee80211_device *ieee = priv->ieee80211;
int *param = (int *)extra;
int ret = 0;
int modulation = 0, mode = 0;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (*param == 1) {
modulation |= IEEE80211_CCK_MODULATION;
mode = IEEE_B;
printk(KERN_INFO "B mode!\n");
} else if (*param == 2) {
modulation |= IEEE80211_OFDM_MODULATION;
mode = IEEE_G;
printk(KERN_INFO "G mode!\n");
} else if (*param == 3) {
modulation |= IEEE80211_CCK_MODULATION;
modulation |= IEEE80211_OFDM_MODULATION;
mode = IEEE_B|IEEE_G;
printk(KERN_INFO "B/G mode!\n");
}
if (ieee->proto_started) {
ieee80211_stop_protocol(ieee);
ieee->mode = mode;
ieee->modulation = modulation;
ieee80211_start_protocol(ieee);
} else {
ieee->mode = mode;
ieee->modulation = modulation;
}
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_preamble(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
down(&priv->wx_sem);
*extra = (char) priv->plcp_preamble_mode; /* 0:auto 1:short 2:long */
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_set_preamble(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret = 0;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
if (*extra < 0 || *extra > 2)
ret = -1;
else
priv->plcp_preamble_mode = *((short *)extra) ;
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_siglevel(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret = 0;
down(&priv->wx_sem);
/* Modify by hikaru 6.5 */
*((int *)extra) = priv->wstats.qual.level;/*for interface test ,it should be the priv->wstats.qual.level; */
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_get_sigqual(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret = 0;
down(&priv->wx_sem);
/* Modify by hikaru 6.5 */
*((int *)extra) = priv->wstats.qual.qual;/* for interface test ,it should be the priv->wstats.qual.qual; */
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_reset_stats(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
down(&priv->wx_sem);
priv->stats.txrdu = 0;
priv->stats.rxrdu = 0;
priv->stats.rxnolast = 0;
priv->stats.rxnodata = 0;
priv->stats.rxnopointer = 0;
priv->stats.txnperr = 0;
priv->stats.txresumed = 0;
priv->stats.rxerr = 0;
priv->stats.rxoverflow = 0;
priv->stats.rxint = 0;
priv->stats.txnpokint = 0;
priv->stats.txhpokint = 0;
priv->stats.txhperr = 0;
priv->stats.ints = 0;
priv->stats.shints = 0;
priv->stats.txoverflow = 0;
priv->stats.rxdmafail = 0;
priv->stats.txbeacon = 0;
priv->stats.txbeaconerr = 0;
priv->stats.txlpokint = 0;
priv->stats.txlperr = 0;
priv->stats.txretry = 0;/* 20060601 */
priv->stats.rxcrcerrmin = 0 ;
priv->stats.rxcrcerrmid = 0;
priv->stats.rxcrcerrmax = 0;
priv->stats.rxicverr = 0;
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_radio_on(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
priv->rf_wakeup(dev);
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_radio_off(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
priv->rf_sleep(dev);
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_get_channelplan(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
down(&priv->wx_sem);
*extra = priv->channel_plan;
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_set_channelplan(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int *val = (int *)extra;
int i;
printk("-----in fun %s\n", __func__);
if (priv->ieee80211->bHwRadioOff)
return 0;
/* unsigned long flags; */
down(&priv->wx_sem);
if (DefaultChannelPlan[*val].Len != 0) {
priv->channel_plan = *val;
/* Clear old channel map 8 */
for (i = 1; i <= MAX_CHANNEL_NUMBER; i++)
GET_DOT11D_INFO(priv->ieee80211)->channel_map[i] = 0;
/* Set new channel map */
for (i = 1; i <= DefaultChannelPlan[*val].Len; i++)
GET_DOT11D_INFO(priv->ieee80211)->channel_map[DefaultChannelPlan[*val].Channel[i-1]] = 1;
}
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_get_version(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
/* struct ieee80211_device *ieee; */
down(&priv->wx_sem);
strcpy(extra, "1020.0808");
up(&priv->wx_sem);
return 0;
}
/* added by amy 080818 */
/*receive datarate from user typing valid rate is from 2 to 108 (1 - 54M), if input 0, return to normal rate adaptive. */
static int r8180_wx_set_forcerate(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
u8 forcerate = *extra;
down(&priv->wx_sem);
printk("==============>%s(): forcerate is %d\n", __func__, forcerate);
if ((forcerate == 2) || (forcerate == 4) || (forcerate == 11) || (forcerate == 22) || (forcerate == 12) ||
(forcerate == 18) || (forcerate == 24) || (forcerate == 36) || (forcerate == 48) || (forcerate == 72) ||
(forcerate == 96) || (forcerate == 108))
{
priv->ForcedDataRate = 1;
priv->ieee80211->rate = forcerate * 5;
} else if (forcerate == 0) {
priv->ForcedDataRate = 0;
printk("OK! return rate adaptive\n");
} else
printk("ERR: wrong rate\n");
up(&priv->wx_sem);
return 0;
}
static int r8180_wx_set_enc_ext(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret = 0;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
ret = ieee80211_wx_set_encode_ext(priv->ieee80211, info, wrqu, extra);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_auth(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct r8180_priv *priv = ieee80211_priv(dev);
int ret = 0;
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
ret = ieee80211_wx_set_auth(priv->ieee80211, info, &wrqu->param, extra);
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_mlme(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret = 0;
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
#if 1
ret = ieee80211_wx_set_mlme(priv->ieee80211, info, wrqu, extra);
#endif
up(&priv->wx_sem);
return ret;
}
static int r8180_wx_set_gen_ie(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret = 0;
struct r8180_priv *priv = ieee80211_priv(dev);
if (priv->ieee80211->bHwRadioOff)
return 0;
down(&priv->wx_sem);
#if 1
ret = ieee80211_wx_set_gen_ie(priv->ieee80211, extra, wrqu->data.length);
#endif
up(&priv->wx_sem);
return ret;
}
static iw_handler r8180_wx_handlers[] = {
NULL, /* SIOCSIWCOMMIT */
r8180_wx_get_name, /* SIOCGIWNAME */
dummy, /* SIOCSIWNWID */
dummy, /* SIOCGIWNWID */
r8180_wx_set_freq, /* SIOCSIWFREQ */
r8180_wx_get_freq, /* SIOCGIWFREQ */
r8180_wx_set_mode, /* SIOCSIWMODE */
r8180_wx_get_mode, /* SIOCGIWMODE */
r8180_wx_set_sens, /* SIOCSIWSENS */
r8180_wx_get_sens, /* SIOCGIWSENS */
NULL, /* SIOCSIWRANGE */
rtl8180_wx_get_range, /* SIOCGIWRANGE */
NULL, /* SIOCSIWPRIV */
NULL, /* SIOCGIWPRIV */
NULL, /* SIOCSIWSTATS */
NULL, /* SIOCGIWSTATS */
dummy, /* SIOCSIWSPY */
dummy, /* SIOCGIWSPY */
NULL, /* SIOCGIWTHRSPY */
NULL, /* SIOCWIWTHRSPY */
r8180_wx_set_wap, /* SIOCSIWAP */
r8180_wx_get_wap, /* SIOCGIWAP */
r8180_wx_set_mlme, /* SIOCSIWMLME*/
dummy, /* SIOCGIWAPLIST -- deprecated */
r8180_wx_set_scan, /* SIOCSIWSCAN */
r8180_wx_get_scan, /* SIOCGIWSCAN */
r8180_wx_set_essid, /* SIOCSIWESSID */
r8180_wx_get_essid, /* SIOCGIWESSID */
dummy, /* SIOCSIWNICKN */
dummy, /* SIOCGIWNICKN */
NULL, /* -- hole -- */
NULL, /* -- hole -- */
r8180_wx_set_rate, /* SIOCSIWRATE */
r8180_wx_get_rate, /* SIOCGIWRATE */
r8180_wx_set_rts, /* SIOCSIWRTS */
r8180_wx_get_rts, /* SIOCGIWRTS */
r8180_wx_set_frag, /* SIOCSIWFRAG */
r8180_wx_get_frag, /* SIOCGIWFRAG */
dummy, /* SIOCSIWTXPOW */
dummy, /* SIOCGIWTXPOW */
r8180_wx_set_retry, /* SIOCSIWRETRY */
r8180_wx_get_retry, /* SIOCGIWRETRY */
r8180_wx_set_enc, /* SIOCSIWENCODE */
r8180_wx_get_enc, /* SIOCGIWENCODE */
r8180_wx_set_power, /* SIOCSIWPOWER */
r8180_wx_get_power, /* SIOCGIWPOWER */
NULL, /*---hole---*/
NULL, /*---hole---*/
r8180_wx_set_gen_ie, /* SIOCSIWGENIE */
NULL, /* SIOCSIWGENIE */
r8180_wx_set_auth, /* SIOCSIWAUTH */
NULL, /* SIOCSIWAUTH */
r8180_wx_set_enc_ext, /* SIOCSIWENCODEEXT */
NULL, /* SIOCSIWENCODEEXT */
NULL, /* SIOCSIWPMKSA */
NULL, /*---hole---*/
};
static const struct iw_priv_args r8180_private_args[] = {
{
SIOCIWFIRSTPRIV + 0x0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "badcrc"
},
{ SIOCIWFIRSTPRIV + 0x1,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0x2,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "beaconint"
},
{ SIOCIWFIRSTPRIV + 0x3,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0x4,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "activescan"
},
{ SIOCIWFIRSTPRIV + 0x5,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0x6,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "rawtx"
},
{ SIOCIWFIRSTPRIV + 0x7,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0x8,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "setiwmode"
},
{
SIOCIWFIRSTPRIV + 0x9,
0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 32, "getiwmode"
},
{
SIOCIWFIRSTPRIV + 0xA,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "setpreamble"
},
{
SIOCIWFIRSTPRIV + 0xB,
0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getpreamble"
},
{ SIOCIWFIRSTPRIV + 0xC,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0xD,
0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getrssi"
},
{ SIOCIWFIRSTPRIV + 0xE,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0xF,
0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getlinkqual"
},
{
SIOCIWFIRSTPRIV + 0x10,
0, 0, "resetstats"
},
{
SIOCIWFIRSTPRIV + 0x11,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0x12,
0, 0, "radioon"
},
{
SIOCIWFIRSTPRIV + 0x13,
0, 0, "radiooff"
},
{
SIOCIWFIRSTPRIV + 0x14,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "setchannel"
},
{
SIOCIWFIRSTPRIV + 0x15,
0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "getchannel"
},
{
SIOCIWFIRSTPRIV + 0x16,
0, 0, "dummy"
},
{
SIOCIWFIRSTPRIV + 0x17,
0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 32, "getversion"
},
{
SIOCIWFIRSTPRIV + 0x18,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "setrate"
},
};
static iw_handler r8180_private_handler[] = {
r8180_wx_set_crcmon, /*SIOCIWSECONDPRIV*/
dummy,
r8180_wx_set_beaconinterval,
dummy,
/* r8180_wx_set_monitor_type, */
r8180_wx_set_scan_type,
dummy,
r8180_wx_set_rawtx,
dummy,
r8180_wx_set_iwmode,
r8180_wx_get_iwmode,
r8180_wx_set_preamble,
r8180_wx_get_preamble,
dummy,
r8180_wx_get_siglevel,
dummy,
r8180_wx_get_sigqual,
r8180_wx_reset_stats,
dummy,/* r8180_wx_get_stats */
r8180_wx_radio_on,
r8180_wx_radio_off,
r8180_wx_set_channelplan,
r8180_wx_get_channelplan,
dummy,
r8180_wx_get_version,
r8180_wx_set_forcerate,
};
static inline int is_same_network(struct ieee80211_network *src,
struct ieee80211_network *dst,
struct ieee80211_device *ieee)
{
/* A network is only a duplicate if the channel, BSSID, ESSID
* and the capability field (in particular IBSS and BSS) all match.
* We treat all <hidden> with the same BSSID and channel
* as one network
*/
return (((src->ssid_len == dst->ssid_len) || (ieee->iw_mode == IW_MODE_INFRA)) && /* YJ,mod, 080819,for hidden ap */
(src->channel == dst->channel) &&
!memcmp(src->bssid, dst->bssid, ETH_ALEN) &&
(!memcmp(src->ssid, dst->ssid, src->ssid_len) || (ieee->iw_mode == IW_MODE_INFRA)) && /* YJ,mod, 080819,for hidden ap */
((src->capability & WLAN_CAPABILITY_IBSS) ==
(dst->capability & WLAN_CAPABILITY_IBSS)) &&
((src->capability & WLAN_CAPABILITY_BSS) ==
(dst->capability & WLAN_CAPABILITY_BSS)));
}
/* WB modified to show signal to GUI on 18-01-2008 */
static struct iw_statistics *r8180_get_wireless_stats(struct net_device *dev)
{
struct r8180_priv *priv = ieee80211_priv(dev);
struct ieee80211_device* ieee = priv->ieee80211;
struct iw_statistics* wstats = &priv->wstats;
int tmp_level = 0;
int tmp_qual = 0;
int tmp_noise = 0;
if (ieee->state < IEEE80211_LINKED) {
wstats->qual.qual = 0;
wstats->qual.level = 0;
wstats->qual.noise = 0;
wstats->qual.updated = IW_QUAL_ALL_UPDATED | IW_QUAL_DBM;
return wstats;
}
tmp_level = (&ieee->current_network)->stats.signal;
tmp_qual = (&ieee->current_network)->stats.signalstrength;
tmp_noise = (&ieee->current_network)->stats.noise;
wstats->qual.level = tmp_level;
wstats->qual.qual = tmp_qual;
wstats->qual.noise = tmp_noise;
wstats->qual.updated = IW_QUAL_ALL_UPDATED | IW_QUAL_DBM;
return wstats;
}
struct iw_handler_def r8180_wx_handlers_def = {
.standard = r8180_wx_handlers,
.num_standard = ARRAY_SIZE(r8180_wx_handlers),
.private = r8180_private_handler,
.num_private = ARRAY_SIZE(r8180_private_handler),
.num_private_args = sizeof(r8180_private_args) / sizeof(struct iw_priv_args),
.get_wireless_stats = r8180_get_wireless_stats,
.private_args = (struct iw_priv_args *)r8180_private_args,
};
| gpl-2.0 |
neonicus/Paralax | drivers/staging/iio/accel/adis16201_trigger.c | 2312 | 1730 | #include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/sysfs.h>
#include <linux/spi/spi.h>
#include "../iio.h"
#include "../sysfs.h"
#include "../trigger.h"
#include "adis16201.h"
/**
* adis16201_data_rdy_trigger_set_state() set datardy interrupt state
**/
static int adis16201_data_rdy_trigger_set_state(struct iio_trigger *trig,
bool state)
{
struct adis16201_state *st = trig->private_data;
struct iio_dev *indio_dev = st->indio_dev;
dev_dbg(&indio_dev->dev, "%s (%d)\n", __func__, state);
return adis16201_set_irq(st->indio_dev, state);
}
int adis16201_probe_trigger(struct iio_dev *indio_dev)
{
int ret;
struct adis16201_state *st = indio_dev->dev_data;
st->trig = iio_allocate_trigger("adis16201-dev%d", indio_dev->id);
if (st->trig == NULL) {
ret = -ENOMEM;
goto error_ret;
}
ret = request_irq(st->us->irq,
&iio_trigger_generic_data_rdy_poll,
IRQF_TRIGGER_RISING,
"adis16201",
st->trig);
if (ret)
goto error_free_trig;
st->trig->dev.parent = &st->us->dev;
st->trig->owner = THIS_MODULE;
st->trig->private_data = st;
st->trig->set_trigger_state = &adis16201_data_rdy_trigger_set_state;
ret = iio_trigger_register(st->trig);
/* select default trigger */
indio_dev->trig = st->trig;
if (ret)
goto error_free_irq;
return 0;
error_free_irq:
free_irq(st->us->irq, st->trig);
error_free_trig:
iio_free_trigger(st->trig);
error_ret:
return ret;
}
void adis16201_remove_trigger(struct iio_dev *indio_dev)
{
struct adis16201_state *state = indio_dev->dev_data;
iio_trigger_unregister(state->trig);
free_irq(state->us->irq, state->trig);
iio_free_trigger(state->trig);
}
| gpl-2.0 |
Fusion-Devices/android_kernel_cyanogen_msm8916 | drivers/gpu/drm/nouveau/core/subdev/vm/nv50.c | 2312 | 5969 | /*
* Copyright 2010 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include <core/device.h>
#include <core/gpuobj.h>
#include <subdev/timer.h>
#include <subdev/fb.h>
#include <subdev/vm.h>
struct nv50_vmmgr_priv {
struct nouveau_vmmgr base;
spinlock_t lock;
};
static void
nv50_vm_map_pgt(struct nouveau_gpuobj *pgd, u32 pde,
struct nouveau_gpuobj *pgt[2])
{
u64 phys = 0xdeadcafe00000000ULL;
u32 coverage = 0;
if (pgt[0]) {
phys = 0x00000003 | pgt[0]->addr; /* present, 4KiB pages */
coverage = (pgt[0]->size >> 3) << 12;
} else
if (pgt[1]) {
phys = 0x00000001 | pgt[1]->addr; /* present */
coverage = (pgt[1]->size >> 3) << 16;
}
if (phys & 1) {
if (coverage <= 32 * 1024 * 1024)
phys |= 0x60;
else if (coverage <= 64 * 1024 * 1024)
phys |= 0x40;
else if (coverage <= 128 * 1024 * 1024)
phys |= 0x20;
}
nv_wo32(pgd, (pde * 8) + 0, lower_32_bits(phys));
nv_wo32(pgd, (pde * 8) + 4, upper_32_bits(phys));
}
static inline u64
vm_addr(struct nouveau_vma *vma, u64 phys, u32 memtype, u32 target)
{
phys |= 1; /* present */
phys |= (u64)memtype << 40;
phys |= target << 4;
if (vma->access & NV_MEM_ACCESS_SYS)
phys |= (1 << 6);
if (!(vma->access & NV_MEM_ACCESS_WO))
phys |= (1 << 3);
return phys;
}
static void
nv50_vm_map(struct nouveau_vma *vma, struct nouveau_gpuobj *pgt,
struct nouveau_mem *mem, u32 pte, u32 cnt, u64 phys, u64 delta)
{
u32 comp = (mem->memtype & 0x180) >> 7;
u32 block, target;
int i;
/* IGPs don't have real VRAM, re-target to stolen system memory */
target = 0;
if (nouveau_fb(vma->vm->vmm)->ram.stolen) {
phys += nouveau_fb(vma->vm->vmm)->ram.stolen;
target = 3;
}
phys = vm_addr(vma, phys, mem->memtype, target);
pte <<= 3;
cnt <<= 3;
while (cnt) {
u32 offset_h = upper_32_bits(phys);
u32 offset_l = lower_32_bits(phys);
for (i = 7; i >= 0; i--) {
block = 1 << (i + 3);
if (cnt >= block && !(pte & (block - 1)))
break;
}
offset_l |= (i << 7);
phys += block << (vma->node->type - 3);
cnt -= block;
if (comp) {
u32 tag = mem->tag->offset + ((delta >> 16) * comp);
offset_h |= (tag << 17);
delta += block << (vma->node->type - 3);
}
while (block) {
nv_wo32(pgt, pte + 0, offset_l);
nv_wo32(pgt, pte + 4, offset_h);
pte += 8;
block -= 8;
}
}
}
static void
nv50_vm_map_sg(struct nouveau_vma *vma, struct nouveau_gpuobj *pgt,
struct nouveau_mem *mem, u32 pte, u32 cnt, dma_addr_t *list)
{
u32 target = (vma->access & NV_MEM_ACCESS_NOSNOOP) ? 3 : 2;
pte <<= 3;
while (cnt--) {
u64 phys = vm_addr(vma, (u64)*list++, mem->memtype, target);
nv_wo32(pgt, pte + 0, lower_32_bits(phys));
nv_wo32(pgt, pte + 4, upper_32_bits(phys));
pte += 8;
}
}
static void
nv50_vm_unmap(struct nouveau_gpuobj *pgt, u32 pte, u32 cnt)
{
pte <<= 3;
while (cnt--) {
nv_wo32(pgt, pte + 0, 0x00000000);
nv_wo32(pgt, pte + 4, 0x00000000);
pte += 8;
}
}
static void
nv50_vm_flush(struct nouveau_vm *vm)
{
struct nouveau_engine *engine;
int i;
for (i = 0; i < NVDEV_SUBDEV_NR; i++) {
if (atomic_read(&vm->engref[i])) {
engine = nouveau_engine(vm->vmm, i);
if (engine && engine->tlb_flush)
engine->tlb_flush(engine);
}
}
}
void
nv50_vm_flush_engine(struct nouveau_subdev *subdev, int engine)
{
struct nv50_vmmgr_priv *priv = (void *)nouveau_vmmgr(subdev);
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
nv_wr32(subdev, 0x100c80, (engine << 16) | 1);
if (!nv_wait(subdev, 0x100c80, 0x00000001, 0x00000000))
nv_error(subdev, "vm flush timeout: engine %d\n", engine);
spin_unlock_irqrestore(&priv->lock, flags);
}
static int
nv50_vm_create(struct nouveau_vmmgr *vmm, u64 offset, u64 length,
u64 mm_offset, struct nouveau_vm **pvm)
{
u32 block = (1 << (vmm->pgt_bits + 12));
if (block > length)
block = length;
return nouveau_vm_create(vmm, offset, length, mm_offset, block, pvm);
}
static int
nv50_vmmgr_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nv50_vmmgr_priv *priv;
int ret;
ret = nouveau_vmmgr_create(parent, engine, oclass, "VM", "vm", &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
priv->base.limit = 1ULL << 40;
priv->base.dma_bits = 40;
priv->base.pgt_bits = 29 - 12;
priv->base.spg_shift = 12;
priv->base.lpg_shift = 16;
priv->base.create = nv50_vm_create;
priv->base.map_pgt = nv50_vm_map_pgt;
priv->base.map = nv50_vm_map;
priv->base.map_sg = nv50_vm_map_sg;
priv->base.unmap = nv50_vm_unmap;
priv->base.flush = nv50_vm_flush;
spin_lock_init(&priv->lock);
return 0;
}
struct nouveau_oclass
nv50_vmmgr_oclass = {
.handle = NV_SUBDEV(VM, 0x50),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv50_vmmgr_ctor,
.dtor = _nouveau_vmmgr_dtor,
.init = _nouveau_vmmgr_init,
.fini = _nouveau_vmmgr_fini,
},
};
| gpl-2.0 |
Tesla-Redux-Devices/hells-Core-N6 | drivers/message/fusion/mptsas.c | 2312 | 150912 | /*
* linux/drivers/message/fusion/mptsas.c
* For use with LSI PCI chip/adapter(s)
* running LSI Fusion MPT (Message Passing Technology) firmware.
*
* Copyright (c) 1999-2008 LSI Corporation
* (mailto:DL-MPTFusionLinux@lsi.com)
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
NO WARRANTY
THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
solely responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement, including but not limited to
the risks and costs of program errors, damage to or loss of data,
programs or equipment, and unavailability or interruption of operations.
DISCLAIMER OF LIABILITY
NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/jiffies.h>
#include <linux/workqueue.h>
#include <linux/delay.h> /* for mdelay */
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_sas.h>
#include <scsi/scsi_transport.h>
#include <scsi/scsi_dbg.h>
#include "mptbase.h"
#include "mptscsih.h"
#include "mptsas.h"
#define my_NAME "Fusion MPT SAS Host driver"
#define my_VERSION MPT_LINUX_VERSION_COMMON
#define MYNAM "mptsas"
/*
* Reserved channel for integrated raid
*/
#define MPTSAS_RAID_CHANNEL 1
#define SAS_CONFIG_PAGE_TIMEOUT 30
MODULE_AUTHOR(MODULEAUTHOR);
MODULE_DESCRIPTION(my_NAME);
MODULE_LICENSE("GPL");
MODULE_VERSION(my_VERSION);
static int mpt_pt_clear;
module_param(mpt_pt_clear, int, 0);
MODULE_PARM_DESC(mpt_pt_clear,
" Clear persistency table: enable=1 "
"(default=MPTSCSIH_PT_CLEAR=0)");
/* scsi-mid layer global parmeter is max_report_luns, which is 511 */
#define MPTSAS_MAX_LUN (16895)
static int max_lun = MPTSAS_MAX_LUN;
module_param(max_lun, int, 0);
MODULE_PARM_DESC(max_lun, " max lun, default=16895 ");
static int mpt_loadtime_max_sectors = 8192;
module_param(mpt_loadtime_max_sectors, int, 0);
MODULE_PARM_DESC(mpt_loadtime_max_sectors,
" Maximum sector define for Host Bus Adaptor.Range 64 to 8192 default=8192");
static u8 mptsasDoneCtx = MPT_MAX_PROTOCOL_DRIVERS;
static u8 mptsasTaskCtx = MPT_MAX_PROTOCOL_DRIVERS;
static u8 mptsasInternalCtx = MPT_MAX_PROTOCOL_DRIVERS; /* Used only for internal commands */
static u8 mptsasMgmtCtx = MPT_MAX_PROTOCOL_DRIVERS;
static u8 mptsasDeviceResetCtx = MPT_MAX_PROTOCOL_DRIVERS;
static void mptsas_firmware_event_work(struct work_struct *work);
static void mptsas_send_sas_event(struct fw_event_work *fw_event);
static void mptsas_send_raid_event(struct fw_event_work *fw_event);
static void mptsas_send_ir2_event(struct fw_event_work *fw_event);
static void mptsas_parse_device_info(struct sas_identify *identify,
struct mptsas_devinfo *device_info);
static inline void mptsas_set_rphy(MPT_ADAPTER *ioc,
struct mptsas_phyinfo *phy_info, struct sas_rphy *rphy);
static struct mptsas_phyinfo *mptsas_find_phyinfo_by_sas_address
(MPT_ADAPTER *ioc, u64 sas_address);
static int mptsas_sas_device_pg0(MPT_ADAPTER *ioc,
struct mptsas_devinfo *device_info, u32 form, u32 form_specific);
static int mptsas_sas_enclosure_pg0(MPT_ADAPTER *ioc,
struct mptsas_enclosure *enclosure, u32 form, u32 form_specific);
static int mptsas_add_end_device(MPT_ADAPTER *ioc,
struct mptsas_phyinfo *phy_info);
static void mptsas_del_end_device(MPT_ADAPTER *ioc,
struct mptsas_phyinfo *phy_info);
static void mptsas_send_link_status_event(struct fw_event_work *fw_event);
static struct mptsas_portinfo *mptsas_find_portinfo_by_sas_address
(MPT_ADAPTER *ioc, u64 sas_address);
static void mptsas_expander_delete(MPT_ADAPTER *ioc,
struct mptsas_portinfo *port_info, u8 force);
static void mptsas_send_expander_event(struct fw_event_work *fw_event);
static void mptsas_not_responding_devices(MPT_ADAPTER *ioc);
static void mptsas_scan_sas_topology(MPT_ADAPTER *ioc);
static void mptsas_broadcast_primative_work(struct fw_event_work *fw_event);
static void mptsas_handle_queue_full_event(struct fw_event_work *fw_event);
static void mptsas_volume_delete(MPT_ADAPTER *ioc, u8 id);
void mptsas_schedule_target_reset(void *ioc);
static void mptsas_print_phy_data(MPT_ADAPTER *ioc,
MPI_SAS_IO_UNIT0_PHY_DATA *phy_data)
{
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"---- IO UNIT PAGE 0 ------------\n", ioc->name));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Handle=0x%X\n",
ioc->name, le16_to_cpu(phy_data->AttachedDeviceHandle)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Controller Handle=0x%X\n",
ioc->name, le16_to_cpu(phy_data->ControllerDevHandle)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Port=0x%X\n",
ioc->name, phy_data->Port));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Port Flags=0x%X\n",
ioc->name, phy_data->PortFlags));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "PHY Flags=0x%X\n",
ioc->name, phy_data->PhyFlags));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Negotiated Link Rate=0x%X\n",
ioc->name, phy_data->NegotiatedLinkRate));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Controller PHY Device Info=0x%X\n", ioc->name,
le32_to_cpu(phy_data->ControllerPhyDeviceInfo)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "DiscoveryStatus=0x%X\n\n",
ioc->name, le32_to_cpu(phy_data->DiscoveryStatus)));
}
static void mptsas_print_phy_pg0(MPT_ADAPTER *ioc, SasPhyPage0_t *pg0)
{
__le64 sas_address;
memcpy(&sas_address, &pg0->SASAddress, sizeof(__le64));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"---- SAS PHY PAGE 0 ------------\n", ioc->name));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Attached Device Handle=0x%X\n", ioc->name,
le16_to_cpu(pg0->AttachedDevHandle)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "SAS Address=0x%llX\n",
ioc->name, (unsigned long long)le64_to_cpu(sas_address)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Attached PHY Identifier=0x%X\n", ioc->name,
pg0->AttachedPhyIdentifier));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Attached Device Info=0x%X\n",
ioc->name, le32_to_cpu(pg0->AttachedDeviceInfo)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Programmed Link Rate=0x%X\n",
ioc->name, pg0->ProgrammedLinkRate));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Change Count=0x%X\n",
ioc->name, pg0->ChangeCount));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "PHY Info=0x%X\n\n",
ioc->name, le32_to_cpu(pg0->PhyInfo)));
}
static void mptsas_print_phy_pg1(MPT_ADAPTER *ioc, SasPhyPage1_t *pg1)
{
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"---- SAS PHY PAGE 1 ------------\n", ioc->name));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Invalid Dword Count=0x%x\n",
ioc->name, pg1->InvalidDwordCount));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Running Disparity Error Count=0x%x\n", ioc->name,
pg1->RunningDisparityErrorCount));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Loss Dword Synch Count=0x%x\n", ioc->name,
pg1->LossDwordSynchCount));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"PHY Reset Problem Count=0x%x\n\n", ioc->name,
pg1->PhyResetProblemCount));
}
static void mptsas_print_device_pg0(MPT_ADAPTER *ioc, SasDevicePage0_t *pg0)
{
__le64 sas_address;
memcpy(&sas_address, &pg0->SASAddress, sizeof(__le64));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"---- SAS DEVICE PAGE 0 ---------\n", ioc->name));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Handle=0x%X\n",
ioc->name, le16_to_cpu(pg0->DevHandle)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Parent Handle=0x%X\n",
ioc->name, le16_to_cpu(pg0->ParentDevHandle)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Enclosure Handle=0x%X\n",
ioc->name, le16_to_cpu(pg0->EnclosureHandle)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Slot=0x%X\n",
ioc->name, le16_to_cpu(pg0->Slot)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "SAS Address=0x%llX\n",
ioc->name, (unsigned long long)le64_to_cpu(sas_address)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Target ID=0x%X\n",
ioc->name, pg0->TargetID));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Bus=0x%X\n",
ioc->name, pg0->Bus));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Parent Phy Num=0x%X\n",
ioc->name, pg0->PhyNum));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Access Status=0x%X\n",
ioc->name, le16_to_cpu(pg0->AccessStatus)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Device Info=0x%X\n",
ioc->name, le32_to_cpu(pg0->DeviceInfo)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Flags=0x%X\n",
ioc->name, le16_to_cpu(pg0->Flags)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Physical Port=0x%X\n\n",
ioc->name, pg0->PhysicalPort));
}
static void mptsas_print_expander_pg1(MPT_ADAPTER *ioc, SasExpanderPage1_t *pg1)
{
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"---- SAS EXPANDER PAGE 1 ------------\n", ioc->name));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Physical Port=0x%X\n",
ioc->name, pg1->PhysicalPort));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "PHY Identifier=0x%X\n",
ioc->name, pg1->PhyIdentifier));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Negotiated Link Rate=0x%X\n",
ioc->name, pg1->NegotiatedLinkRate));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Programmed Link Rate=0x%X\n",
ioc->name, pg1->ProgrammedLinkRate));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Hardware Link Rate=0x%X\n",
ioc->name, pg1->HwLinkRate));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Owner Device Handle=0x%X\n",
ioc->name, le16_to_cpu(pg1->OwnerDevHandle)));
dsasprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Attached Device Handle=0x%X\n\n", ioc->name,
le16_to_cpu(pg1->AttachedDevHandle)));
}
/* inhibit sas firmware event handling */
static void
mptsas_fw_event_off(MPT_ADAPTER *ioc)
{
unsigned long flags;
spin_lock_irqsave(&ioc->fw_event_lock, flags);
ioc->fw_events_off = 1;
ioc->sas_discovery_quiesce_io = 0;
spin_unlock_irqrestore(&ioc->fw_event_lock, flags);
}
/* enable sas firmware event handling */
static void
mptsas_fw_event_on(MPT_ADAPTER *ioc)
{
unsigned long flags;
spin_lock_irqsave(&ioc->fw_event_lock, flags);
ioc->fw_events_off = 0;
spin_unlock_irqrestore(&ioc->fw_event_lock, flags);
}
/* queue a sas firmware event */
static void
mptsas_add_fw_event(MPT_ADAPTER *ioc, struct fw_event_work *fw_event,
unsigned long delay)
{
unsigned long flags;
spin_lock_irqsave(&ioc->fw_event_lock, flags);
list_add_tail(&fw_event->list, &ioc->fw_event_list);
INIT_DELAYED_WORK(&fw_event->work, mptsas_firmware_event_work);
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s: add (fw_event=0x%p)"
"on cpuid %d\n", ioc->name, __func__,
fw_event, smp_processor_id()));
queue_delayed_work_on(smp_processor_id(), ioc->fw_event_q,
&fw_event->work, delay);
spin_unlock_irqrestore(&ioc->fw_event_lock, flags);
}
/* requeue a sas firmware event */
static void
mptsas_requeue_fw_event(MPT_ADAPTER *ioc, struct fw_event_work *fw_event,
unsigned long delay)
{
unsigned long flags;
spin_lock_irqsave(&ioc->fw_event_lock, flags);
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s: reschedule task "
"(fw_event=0x%p)on cpuid %d\n", ioc->name, __func__,
fw_event, smp_processor_id()));
fw_event->retries++;
queue_delayed_work_on(smp_processor_id(), ioc->fw_event_q,
&fw_event->work, msecs_to_jiffies(delay));
spin_unlock_irqrestore(&ioc->fw_event_lock, flags);
}
/* free memory associated to a sas firmware event */
static void
mptsas_free_fw_event(MPT_ADAPTER *ioc, struct fw_event_work *fw_event)
{
unsigned long flags;
spin_lock_irqsave(&ioc->fw_event_lock, flags);
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s: kfree (fw_event=0x%p)\n",
ioc->name, __func__, fw_event));
list_del(&fw_event->list);
kfree(fw_event);
spin_unlock_irqrestore(&ioc->fw_event_lock, flags);
}
/* walk the firmware event queue, and either stop or wait for
* outstanding events to complete */
static void
mptsas_cleanup_fw_event_q(MPT_ADAPTER *ioc)
{
struct fw_event_work *fw_event, *next;
struct mptsas_target_reset_event *target_reset_list, *n;
MPT_SCSI_HOST *hd = shost_priv(ioc->sh);
/* flush the target_reset_list */
if (!list_empty(&hd->target_reset_list)) {
list_for_each_entry_safe(target_reset_list, n,
&hd->target_reset_list, list) {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: removing target reset for id=%d\n",
ioc->name, __func__,
target_reset_list->sas_event_data.TargetID));
list_del(&target_reset_list->list);
kfree(target_reset_list);
}
}
if (list_empty(&ioc->fw_event_list) ||
!ioc->fw_event_q || in_interrupt())
return;
list_for_each_entry_safe(fw_event, next, &ioc->fw_event_list, list) {
if (cancel_delayed_work(&fw_event->work))
mptsas_free_fw_event(ioc, fw_event);
}
}
static inline MPT_ADAPTER *phy_to_ioc(struct sas_phy *phy)
{
struct Scsi_Host *shost = dev_to_shost(phy->dev.parent);
return ((MPT_SCSI_HOST *)shost->hostdata)->ioc;
}
static inline MPT_ADAPTER *rphy_to_ioc(struct sas_rphy *rphy)
{
struct Scsi_Host *shost = dev_to_shost(rphy->dev.parent->parent);
return ((MPT_SCSI_HOST *)shost->hostdata)->ioc;
}
/*
* mptsas_find_portinfo_by_handle
*
* This function should be called with the sas_topology_mutex already held
*/
static struct mptsas_portinfo *
mptsas_find_portinfo_by_handle(MPT_ADAPTER *ioc, u16 handle)
{
struct mptsas_portinfo *port_info, *rc=NULL;
int i;
list_for_each_entry(port_info, &ioc->sas_topology, list)
for (i = 0; i < port_info->num_phys; i++)
if (port_info->phy_info[i].identify.handle == handle) {
rc = port_info;
goto out;
}
out:
return rc;
}
/**
* mptsas_find_portinfo_by_sas_address -
* @ioc: Pointer to MPT_ADAPTER structure
* @handle:
*
* This function should be called with the sas_topology_mutex already held
*
**/
static struct mptsas_portinfo *
mptsas_find_portinfo_by_sas_address(MPT_ADAPTER *ioc, u64 sas_address)
{
struct mptsas_portinfo *port_info, *rc = NULL;
int i;
if (sas_address >= ioc->hba_port_sas_addr &&
sas_address < (ioc->hba_port_sas_addr +
ioc->hba_port_num_phy))
return ioc->hba_port_info;
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry(port_info, &ioc->sas_topology, list)
for (i = 0; i < port_info->num_phys; i++)
if (port_info->phy_info[i].identify.sas_address ==
sas_address) {
rc = port_info;
goto out;
}
out:
mutex_unlock(&ioc->sas_topology_mutex);
return rc;
}
/*
* Returns true if there is a scsi end device
*/
static inline int
mptsas_is_end_device(struct mptsas_devinfo * attached)
{
if ((attached->sas_address) &&
(attached->device_info &
MPI_SAS_DEVICE_INFO_END_DEVICE) &&
((attached->device_info &
MPI_SAS_DEVICE_INFO_SSP_TARGET) |
(attached->device_info &
MPI_SAS_DEVICE_INFO_STP_TARGET) |
(attached->device_info &
MPI_SAS_DEVICE_INFO_SATA_DEVICE)))
return 1;
else
return 0;
}
/* no mutex */
static void
mptsas_port_delete(MPT_ADAPTER *ioc, struct mptsas_portinfo_details * port_details)
{
struct mptsas_portinfo *port_info;
struct mptsas_phyinfo *phy_info;
u8 i;
if (!port_details)
return;
port_info = port_details->port_info;
phy_info = port_info->phy_info;
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s: [%p]: num_phys=%02d "
"bitmask=0x%016llX\n", ioc->name, __func__, port_details,
port_details->num_phys, (unsigned long long)
port_details->phy_bitmask));
for (i = 0; i < port_info->num_phys; i++, phy_info++) {
if(phy_info->port_details != port_details)
continue;
memset(&phy_info->attached, 0, sizeof(struct mptsas_devinfo));
mptsas_set_rphy(ioc, phy_info, NULL);
phy_info->port_details = NULL;
}
kfree(port_details);
}
static inline struct sas_rphy *
mptsas_get_rphy(struct mptsas_phyinfo *phy_info)
{
if (phy_info->port_details)
return phy_info->port_details->rphy;
else
return NULL;
}
static inline void
mptsas_set_rphy(MPT_ADAPTER *ioc, struct mptsas_phyinfo *phy_info, struct sas_rphy *rphy)
{
if (phy_info->port_details) {
phy_info->port_details->rphy = rphy;
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT "sas_rphy_add: rphy=%p\n",
ioc->name, rphy));
}
if (rphy) {
dsaswideprintk(ioc, dev_printk(KERN_DEBUG,
&rphy->dev, MYIOC_s_FMT "add:", ioc->name));
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT "rphy=%p release=%p\n",
ioc->name, rphy, rphy->dev.release));
}
}
static inline struct sas_port *
mptsas_get_port(struct mptsas_phyinfo *phy_info)
{
if (phy_info->port_details)
return phy_info->port_details->port;
else
return NULL;
}
static inline void
mptsas_set_port(MPT_ADAPTER *ioc, struct mptsas_phyinfo *phy_info, struct sas_port *port)
{
if (phy_info->port_details)
phy_info->port_details->port = port;
if (port) {
dsaswideprintk(ioc, dev_printk(KERN_DEBUG,
&port->dev, MYIOC_s_FMT "add:", ioc->name));
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT "port=%p release=%p\n",
ioc->name, port, port->dev.release));
}
}
static inline struct scsi_target *
mptsas_get_starget(struct mptsas_phyinfo *phy_info)
{
if (phy_info->port_details)
return phy_info->port_details->starget;
else
return NULL;
}
static inline void
mptsas_set_starget(struct mptsas_phyinfo *phy_info, struct scsi_target *
starget)
{
if (phy_info->port_details)
phy_info->port_details->starget = starget;
}
/**
* mptsas_add_device_component -
* @ioc: Pointer to MPT_ADAPTER structure
* @channel: fw mapped id's
* @id:
* @sas_address:
* @device_info:
*
**/
static void
mptsas_add_device_component(MPT_ADAPTER *ioc, u8 channel, u8 id,
u64 sas_address, u32 device_info, u16 slot, u64 enclosure_logical_id)
{
struct mptsas_device_info *sas_info, *next;
struct scsi_device *sdev;
struct scsi_target *starget;
struct sas_rphy *rphy;
/*
* Delete all matching devices out of the list
*/
mutex_lock(&ioc->sas_device_info_mutex);
list_for_each_entry_safe(sas_info, next, &ioc->sas_device_info_list,
list) {
if (!sas_info->is_logical_volume &&
(sas_info->sas_address == sas_address ||
(sas_info->fw.channel == channel &&
sas_info->fw.id == id))) {
list_del(&sas_info->list);
kfree(sas_info);
}
}
sas_info = kzalloc(sizeof(struct mptsas_device_info), GFP_KERNEL);
if (!sas_info)
goto out;
/*
* Set Firmware mapping
*/
sas_info->fw.id = id;
sas_info->fw.channel = channel;
sas_info->sas_address = sas_address;
sas_info->device_info = device_info;
sas_info->slot = slot;
sas_info->enclosure_logical_id = enclosure_logical_id;
INIT_LIST_HEAD(&sas_info->list);
list_add_tail(&sas_info->list, &ioc->sas_device_info_list);
/*
* Set OS mapping
*/
shost_for_each_device(sdev, ioc->sh) {
starget = scsi_target(sdev);
rphy = dev_to_rphy(starget->dev.parent);
if (rphy->identify.sas_address == sas_address) {
sas_info->os.id = starget->id;
sas_info->os.channel = starget->channel;
}
}
out:
mutex_unlock(&ioc->sas_device_info_mutex);
return;
}
/**
* mptsas_add_device_component_by_fw -
* @ioc: Pointer to MPT_ADAPTER structure
* @channel: fw mapped id's
* @id:
*
**/
static void
mptsas_add_device_component_by_fw(MPT_ADAPTER *ioc, u8 channel, u8 id)
{
struct mptsas_devinfo sas_device;
struct mptsas_enclosure enclosure_info;
int rc;
rc = mptsas_sas_device_pg0(ioc, &sas_device,
(MPI_SAS_DEVICE_PGAD_FORM_BUS_TARGET_ID <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
(channel << 8) + id);
if (rc)
return;
memset(&enclosure_info, 0, sizeof(struct mptsas_enclosure));
mptsas_sas_enclosure_pg0(ioc, &enclosure_info,
(MPI_SAS_ENCLOS_PGAD_FORM_HANDLE <<
MPI_SAS_ENCLOS_PGAD_FORM_SHIFT),
sas_device.handle_enclosure);
mptsas_add_device_component(ioc, sas_device.channel,
sas_device.id, sas_device.sas_address, sas_device.device_info,
sas_device.slot, enclosure_info.enclosure_logical_id);
}
/**
* mptsas_add_device_component_starget_ir - Handle Integrated RAID, adding each individual device to list
* @ioc: Pointer to MPT_ADAPTER structure
* @channel: fw mapped id's
* @id:
*
**/
static void
mptsas_add_device_component_starget_ir(MPT_ADAPTER *ioc,
struct scsi_target *starget)
{
CONFIGPARMS cfg;
ConfigPageHeader_t hdr;
dma_addr_t dma_handle;
pRaidVolumePage0_t buffer = NULL;
int i;
RaidPhysDiskPage0_t phys_disk;
struct mptsas_device_info *sas_info, *next;
memset(&cfg, 0 , sizeof(CONFIGPARMS));
memset(&hdr, 0 , sizeof(ConfigPageHeader_t));
hdr.PageType = MPI_CONFIG_PAGETYPE_RAID_VOLUME;
/* assumption that all volumes on channel = 0 */
cfg.pageAddr = starget->id;
cfg.cfghdr.hdr = &hdr;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
if (mpt_config(ioc, &cfg) != 0)
goto out;
if (!hdr.PageLength)
goto out;
buffer = pci_alloc_consistent(ioc->pcidev, hdr.PageLength * 4,
&dma_handle);
if (!buffer)
goto out;
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
if (mpt_config(ioc, &cfg) != 0)
goto out;
if (!buffer->NumPhysDisks)
goto out;
/*
* Adding entry for hidden components
*/
for (i = 0; i < buffer->NumPhysDisks; i++) {
if (mpt_raid_phys_disk_pg0(ioc,
buffer->PhysDisk[i].PhysDiskNum, &phys_disk) != 0)
continue;
mptsas_add_device_component_by_fw(ioc, phys_disk.PhysDiskBus,
phys_disk.PhysDiskID);
mutex_lock(&ioc->sas_device_info_mutex);
list_for_each_entry(sas_info, &ioc->sas_device_info_list,
list) {
if (!sas_info->is_logical_volume &&
(sas_info->fw.channel == phys_disk.PhysDiskBus &&
sas_info->fw.id == phys_disk.PhysDiskID)) {
sas_info->is_hidden_raid_component = 1;
sas_info->volume_id = starget->id;
}
}
mutex_unlock(&ioc->sas_device_info_mutex);
}
/*
* Delete all matching devices out of the list
*/
mutex_lock(&ioc->sas_device_info_mutex);
list_for_each_entry_safe(sas_info, next, &ioc->sas_device_info_list,
list) {
if (sas_info->is_logical_volume && sas_info->fw.id ==
starget->id) {
list_del(&sas_info->list);
kfree(sas_info);
}
}
sas_info = kzalloc(sizeof(struct mptsas_device_info), GFP_KERNEL);
if (sas_info) {
sas_info->fw.id = starget->id;
sas_info->os.id = starget->id;
sas_info->os.channel = starget->channel;
sas_info->is_logical_volume = 1;
INIT_LIST_HEAD(&sas_info->list);
list_add_tail(&sas_info->list, &ioc->sas_device_info_list);
}
mutex_unlock(&ioc->sas_device_info_mutex);
out:
if (buffer)
pci_free_consistent(ioc->pcidev, hdr.PageLength * 4, buffer,
dma_handle);
}
/**
* mptsas_add_device_component_starget -
* @ioc: Pointer to MPT_ADAPTER structure
* @starget:
*
**/
static void
mptsas_add_device_component_starget(MPT_ADAPTER *ioc,
struct scsi_target *starget)
{
VirtTarget *vtarget;
struct sas_rphy *rphy;
struct mptsas_phyinfo *phy_info = NULL;
struct mptsas_enclosure enclosure_info;
rphy = dev_to_rphy(starget->dev.parent);
vtarget = starget->hostdata;
phy_info = mptsas_find_phyinfo_by_sas_address(ioc,
rphy->identify.sas_address);
if (!phy_info)
return;
memset(&enclosure_info, 0, sizeof(struct mptsas_enclosure));
mptsas_sas_enclosure_pg0(ioc, &enclosure_info,
(MPI_SAS_ENCLOS_PGAD_FORM_HANDLE <<
MPI_SAS_ENCLOS_PGAD_FORM_SHIFT),
phy_info->attached.handle_enclosure);
mptsas_add_device_component(ioc, phy_info->attached.channel,
phy_info->attached.id, phy_info->attached.sas_address,
phy_info->attached.device_info,
phy_info->attached.slot, enclosure_info.enclosure_logical_id);
}
/**
* mptsas_del_device_component_by_os - Once a device has been removed, we mark the entry in the list as being cached
* @ioc: Pointer to MPT_ADAPTER structure
* @channel: os mapped id's
* @id:
*
**/
static void
mptsas_del_device_component_by_os(MPT_ADAPTER *ioc, u8 channel, u8 id)
{
struct mptsas_device_info *sas_info, *next;
/*
* Set is_cached flag
*/
list_for_each_entry_safe(sas_info, next, &ioc->sas_device_info_list,
list) {
if (sas_info->os.channel == channel && sas_info->os.id == id)
sas_info->is_cached = 1;
}
}
/**
* mptsas_del_device_components - Cleaning the list
* @ioc: Pointer to MPT_ADAPTER structure
*
**/
static void
mptsas_del_device_components(MPT_ADAPTER *ioc)
{
struct mptsas_device_info *sas_info, *next;
mutex_lock(&ioc->sas_device_info_mutex);
list_for_each_entry_safe(sas_info, next, &ioc->sas_device_info_list,
list) {
list_del(&sas_info->list);
kfree(sas_info);
}
mutex_unlock(&ioc->sas_device_info_mutex);
}
/*
* mptsas_setup_wide_ports
*
* Updates for new and existing narrow/wide port configuration
* in the sas_topology
*/
static void
mptsas_setup_wide_ports(MPT_ADAPTER *ioc, struct mptsas_portinfo *port_info)
{
struct mptsas_portinfo_details * port_details;
struct mptsas_phyinfo *phy_info, *phy_info_cmp;
u64 sas_address;
int i, j;
mutex_lock(&ioc->sas_topology_mutex);
phy_info = port_info->phy_info;
for (i = 0 ; i < port_info->num_phys ; i++, phy_info++) {
if (phy_info->attached.handle)
continue;
port_details = phy_info->port_details;
if (!port_details)
continue;
if (port_details->num_phys < 2)
continue;
/*
* Removing a phy from a port, letting the last
* phy be removed by firmware events.
*/
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: [%p]: deleting phy = %d\n",
ioc->name, __func__, port_details, i));
port_details->num_phys--;
port_details->phy_bitmask &= ~ (1 << phy_info->phy_id);
memset(&phy_info->attached, 0, sizeof(struct mptsas_devinfo));
if (phy_info->phy) {
devtprintk(ioc, dev_printk(KERN_DEBUG,
&phy_info->phy->dev, MYIOC_s_FMT
"delete phy %d, phy-obj (0x%p)\n", ioc->name,
phy_info->phy_id, phy_info->phy));
sas_port_delete_phy(port_details->port, phy_info->phy);
}
phy_info->port_details = NULL;
}
/*
* Populate and refresh the tree
*/
phy_info = port_info->phy_info;
for (i = 0 ; i < port_info->num_phys ; i++, phy_info++) {
sas_address = phy_info->attached.sas_address;
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT "phy_id=%d sas_address=0x%018llX\n",
ioc->name, i, (unsigned long long)sas_address));
if (!sas_address)
continue;
port_details = phy_info->port_details;
/*
* Forming a port
*/
if (!port_details) {
port_details = kzalloc(sizeof(struct
mptsas_portinfo_details), GFP_KERNEL);
if (!port_details)
goto out;
port_details->num_phys = 1;
port_details->port_info = port_info;
if (phy_info->phy_id < 64 )
port_details->phy_bitmask |=
(1 << phy_info->phy_id);
phy_info->sas_port_add_phy=1;
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT "\t\tForming port\n\t\t"
"phy_id=%d sas_address=0x%018llX\n",
ioc->name, i, (unsigned long long)sas_address));
phy_info->port_details = port_details;
}
if (i == port_info->num_phys - 1)
continue;
phy_info_cmp = &port_info->phy_info[i + 1];
for (j = i + 1 ; j < port_info->num_phys ; j++,
phy_info_cmp++) {
if (!phy_info_cmp->attached.sas_address)
continue;
if (sas_address != phy_info_cmp->attached.sas_address)
continue;
if (phy_info_cmp->port_details == port_details )
continue;
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"\t\tphy_id=%d sas_address=0x%018llX\n",
ioc->name, j, (unsigned long long)
phy_info_cmp->attached.sas_address));
if (phy_info_cmp->port_details) {
port_details->rphy =
mptsas_get_rphy(phy_info_cmp);
port_details->port =
mptsas_get_port(phy_info_cmp);
port_details->starget =
mptsas_get_starget(phy_info_cmp);
port_details->num_phys =
phy_info_cmp->port_details->num_phys;
if (!phy_info_cmp->port_details->num_phys)
kfree(phy_info_cmp->port_details);
} else
phy_info_cmp->sas_port_add_phy=1;
/*
* Adding a phy to a port
*/
phy_info_cmp->port_details = port_details;
if (phy_info_cmp->phy_id < 64 )
port_details->phy_bitmask |=
(1 << phy_info_cmp->phy_id);
port_details->num_phys++;
}
}
out:
for (i = 0; i < port_info->num_phys; i++) {
port_details = port_info->phy_info[i].port_details;
if (!port_details)
continue;
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: [%p]: phy_id=%02d num_phys=%02d "
"bitmask=0x%016llX\n", ioc->name, __func__,
port_details, i, port_details->num_phys,
(unsigned long long)port_details->phy_bitmask));
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT "\t\tport = %p rphy=%p\n",
ioc->name, port_details->port, port_details->rphy));
}
dsaswideprintk(ioc, printk("\n"));
mutex_unlock(&ioc->sas_topology_mutex);
}
/**
* csmisas_find_vtarget
*
* @ioc
* @volume_id
* @volume_bus
*
**/
static VirtTarget *
mptsas_find_vtarget(MPT_ADAPTER *ioc, u8 channel, u8 id)
{
struct scsi_device *sdev;
VirtDevice *vdevice;
VirtTarget *vtarget = NULL;
shost_for_each_device(sdev, ioc->sh) {
vdevice = sdev->hostdata;
if ((vdevice == NULL) ||
(vdevice->vtarget == NULL))
continue;
if ((vdevice->vtarget->tflags &
MPT_TARGET_FLAGS_RAID_COMPONENT ||
vdevice->vtarget->raidVolume))
continue;
if (vdevice->vtarget->id == id &&
vdevice->vtarget->channel == channel)
vtarget = vdevice->vtarget;
}
return vtarget;
}
static void
mptsas_queue_device_delete(MPT_ADAPTER *ioc,
MpiEventDataSasDeviceStatusChange_t *sas_event_data)
{
struct fw_event_work *fw_event;
int sz;
sz = offsetof(struct fw_event_work, event_data) +
sizeof(MpiEventDataSasDeviceStatusChange_t);
fw_event = kzalloc(sz, GFP_ATOMIC);
if (!fw_event) {
printk(MYIOC_s_WARN_FMT "%s: failed at (line=%d)\n",
ioc->name, __func__, __LINE__);
return;
}
memcpy(fw_event->event_data, sas_event_data,
sizeof(MpiEventDataSasDeviceStatusChange_t));
fw_event->event = MPI_EVENT_SAS_DEVICE_STATUS_CHANGE;
fw_event->ioc = ioc;
mptsas_add_fw_event(ioc, fw_event, msecs_to_jiffies(1));
}
static void
mptsas_queue_rescan(MPT_ADAPTER *ioc)
{
struct fw_event_work *fw_event;
int sz;
sz = offsetof(struct fw_event_work, event_data);
fw_event = kzalloc(sz, GFP_ATOMIC);
if (!fw_event) {
printk(MYIOC_s_WARN_FMT "%s: failed at (line=%d)\n",
ioc->name, __func__, __LINE__);
return;
}
fw_event->event = -1;
fw_event->ioc = ioc;
mptsas_add_fw_event(ioc, fw_event, msecs_to_jiffies(1));
}
/**
* mptsas_target_reset
*
* Issues TARGET_RESET to end device using handshaking method
*
* @ioc
* @channel
* @id
*
* Returns (1) success
* (0) failure
*
**/
static int
mptsas_target_reset(MPT_ADAPTER *ioc, u8 channel, u8 id)
{
MPT_FRAME_HDR *mf;
SCSITaskMgmt_t *pScsiTm;
if (mpt_set_taskmgmt_in_progress_flag(ioc) != 0)
return 0;
mf = mpt_get_msg_frame(mptsasDeviceResetCtx, ioc);
if (mf == NULL) {
dfailprintk(ioc, printk(MYIOC_s_WARN_FMT
"%s, no msg frames @%d!!\n", ioc->name,
__func__, __LINE__));
goto out_fail;
}
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT "TaskMgmt request (mf=%p)\n",
ioc->name, mf));
/* Format the Request
*/
pScsiTm = (SCSITaskMgmt_t *) mf;
memset (pScsiTm, 0, sizeof(SCSITaskMgmt_t));
pScsiTm->TargetID = id;
pScsiTm->Bus = channel;
pScsiTm->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
pScsiTm->TaskType = MPI_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
pScsiTm->MsgFlags = MPI_SCSITASKMGMT_MSGFLAGS_LIPRESET_RESET_OPTION;
DBG_DUMP_TM_REQUEST_FRAME(ioc, (u32 *)mf);
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt type=%d (sas device delete) fw_channel = %d fw_id = %d)\n",
ioc->name, MPI_SCSITASKMGMT_TASKTYPE_TARGET_RESET, channel, id));
mpt_put_msg_frame_hi_pri(mptsasDeviceResetCtx, ioc, mf);
return 1;
out_fail:
mpt_clear_taskmgmt_in_progress_flag(ioc);
return 0;
}
static void
mptsas_block_io_sdev(struct scsi_device *sdev, void *data)
{
scsi_device_set_state(sdev, SDEV_BLOCK);
}
static void
mptsas_block_io_starget(struct scsi_target *starget)
{
if (starget)
starget_for_each_device(starget, NULL, mptsas_block_io_sdev);
}
/**
* mptsas_target_reset_queue
*
* Receive request for TARGET_RESET after receiving an firmware
* event NOT_RESPONDING_EVENT, then put command in link list
* and queue if task_queue already in use.
*
* @ioc
* @sas_event_data
*
**/
static void
mptsas_target_reset_queue(MPT_ADAPTER *ioc,
EVENT_DATA_SAS_DEVICE_STATUS_CHANGE *sas_event_data)
{
MPT_SCSI_HOST *hd = shost_priv(ioc->sh);
VirtTarget *vtarget = NULL;
struct mptsas_target_reset_event *target_reset_list;
u8 id, channel;
id = sas_event_data->TargetID;
channel = sas_event_data->Bus;
vtarget = mptsas_find_vtarget(ioc, channel, id);
if (vtarget) {
mptsas_block_io_starget(vtarget->starget);
vtarget->deleted = 1; /* block IO */
}
target_reset_list = kzalloc(sizeof(struct mptsas_target_reset_event),
GFP_ATOMIC);
if (!target_reset_list) {
dfailprintk(ioc, printk(MYIOC_s_WARN_FMT
"%s, failed to allocate mem @%d..!!\n",
ioc->name, __func__, __LINE__));
return;
}
memcpy(&target_reset_list->sas_event_data, sas_event_data,
sizeof(*sas_event_data));
list_add_tail(&target_reset_list->list, &hd->target_reset_list);
target_reset_list->time_count = jiffies;
if (mptsas_target_reset(ioc, channel, id)) {
target_reset_list->target_reset_issued = 1;
}
}
/**
* mptsas_schedule_target_reset- send pending target reset
* @iocp: per adapter object
*
* This function will delete scheduled target reset from the list and
* try to send next target reset. This will be called from completion
* context of any Task management command.
*/
void
mptsas_schedule_target_reset(void *iocp)
{
MPT_ADAPTER *ioc = (MPT_ADAPTER *)(iocp);
MPT_SCSI_HOST *hd = shost_priv(ioc->sh);
struct list_head *head = &hd->target_reset_list;
struct mptsas_target_reset_event *target_reset_list;
u8 id, channel;
/*
* issue target reset to next device in the queue
*/
head = &hd->target_reset_list;
if (list_empty(head))
return;
target_reset_list = list_entry(head->next,
struct mptsas_target_reset_event, list);
id = target_reset_list->sas_event_data.TargetID;
channel = target_reset_list->sas_event_data.Bus;
target_reset_list->time_count = jiffies;
if (mptsas_target_reset(ioc, channel, id))
target_reset_list->target_reset_issued = 1;
return;
}
/**
* mptsas_taskmgmt_complete - complete SAS task management function
* @ioc: Pointer to MPT_ADAPTER structure
*
* Completion for TARGET_RESET after NOT_RESPONDING_EVENT, enable work
* queue to finish off removing device from upper layers. then send next
* TARGET_RESET in the queue.
**/
static int
mptsas_taskmgmt_complete(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *mr)
{
MPT_SCSI_HOST *hd = shost_priv(ioc->sh);
struct list_head *head = &hd->target_reset_list;
u8 id, channel;
struct mptsas_target_reset_event *target_reset_list;
SCSITaskMgmtReply_t *pScsiTmReply;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT "TaskMgmt completed: "
"(mf = %p, mr = %p)\n", ioc->name, mf, mr));
pScsiTmReply = (SCSITaskMgmtReply_t *)mr;
if (pScsiTmReply) {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"\tTaskMgmt completed: fw_channel = %d, fw_id = %d,\n"
"\ttask_type = 0x%02X, iocstatus = 0x%04X "
"loginfo = 0x%08X,\n\tresponse_code = 0x%02X, "
"term_cmnds = %d\n", ioc->name,
pScsiTmReply->Bus, pScsiTmReply->TargetID,
pScsiTmReply->TaskType,
le16_to_cpu(pScsiTmReply->IOCStatus),
le32_to_cpu(pScsiTmReply->IOCLogInfo),
pScsiTmReply->ResponseCode,
le32_to_cpu(pScsiTmReply->TerminationCount)));
if (pScsiTmReply->ResponseCode)
mptscsih_taskmgmt_response_code(ioc,
pScsiTmReply->ResponseCode);
}
if (pScsiTmReply && (pScsiTmReply->TaskType ==
MPI_SCSITASKMGMT_TASKTYPE_QUERY_TASK || pScsiTmReply->TaskType ==
MPI_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET)) {
ioc->taskmgmt_cmds.status |= MPT_MGMT_STATUS_COMMAND_GOOD;
ioc->taskmgmt_cmds.status |= MPT_MGMT_STATUS_RF_VALID;
memcpy(ioc->taskmgmt_cmds.reply, mr,
min(MPT_DEFAULT_FRAME_SIZE, 4 * mr->u.reply.MsgLength));
if (ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_PENDING) {
ioc->taskmgmt_cmds.status &= ~MPT_MGMT_STATUS_PENDING;
complete(&ioc->taskmgmt_cmds.done);
return 1;
}
return 0;
}
mpt_clear_taskmgmt_in_progress_flag(ioc);
if (list_empty(head))
return 1;
target_reset_list = list_entry(head->next,
struct mptsas_target_reset_event, list);
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt: completed (%d seconds)\n",
ioc->name, jiffies_to_msecs(jiffies -
target_reset_list->time_count)/1000));
id = pScsiTmReply->TargetID;
channel = pScsiTmReply->Bus;
target_reset_list->time_count = jiffies;
/*
* retry target reset
*/
if (!target_reset_list->target_reset_issued) {
if (mptsas_target_reset(ioc, channel, id))
target_reset_list->target_reset_issued = 1;
return 1;
}
/*
* enable work queue to remove device from upper layers
*/
list_del(&target_reset_list->list);
if (!ioc->fw_events_off)
mptsas_queue_device_delete(ioc,
&target_reset_list->sas_event_data);
ioc->schedule_target_reset(ioc);
return 1;
}
/**
* mptscsih_ioc_reset
*
* @ioc
* @reset_phase
*
**/
static int
mptsas_ioc_reset(MPT_ADAPTER *ioc, int reset_phase)
{
MPT_SCSI_HOST *hd;
int rc;
rc = mptscsih_ioc_reset(ioc, reset_phase);
if ((ioc->bus_type != SAS) || (!rc))
return rc;
hd = shost_priv(ioc->sh);
if (!hd->ioc)
goto out;
switch (reset_phase) {
case MPT_IOC_SETUP_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_SETUP_RESET\n", ioc->name, __func__));
mptsas_fw_event_off(ioc);
break;
case MPT_IOC_PRE_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_PRE_RESET\n", ioc->name, __func__));
break;
case MPT_IOC_POST_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_POST_RESET\n", ioc->name, __func__));
if (ioc->sas_mgmt.status & MPT_MGMT_STATUS_PENDING) {
ioc->sas_mgmt.status |= MPT_MGMT_STATUS_DID_IOCRESET;
complete(&ioc->sas_mgmt.done);
}
mptsas_cleanup_fw_event_q(ioc);
mptsas_queue_rescan(ioc);
break;
default:
break;
}
out:
return rc;
}
/**
* enum device_state -
* @DEVICE_RETRY: need to retry the TUR
* @DEVICE_ERROR: TUR return error, don't add device
* @DEVICE_READY: device can be added
*
*/
enum device_state{
DEVICE_RETRY,
DEVICE_ERROR,
DEVICE_READY,
};
static int
mptsas_sas_enclosure_pg0(MPT_ADAPTER *ioc, struct mptsas_enclosure *enclosure,
u32 form, u32 form_specific)
{
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasEnclosurePage0_t *buffer;
dma_addr_t dma_handle;
int error;
__le64 le_identifier;
memset(&hdr, 0, sizeof(hdr));
hdr.PageVersion = MPI_SASENCLOSURE0_PAGEVERSION;
hdr.PageNumber = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
hdr.ExtPageType = MPI_CONFIG_EXTPAGETYPE_ENCLOSURE;
cfg.cfghdr.ehdr = &hdr;
cfg.physAddr = -1;
cfg.pageAddr = form + form_specific;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
error = mpt_config(ioc, &cfg);
if (error)
goto out;
if (!hdr.ExtPageLength) {
error = -ENXIO;
goto out;
}
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer) {
error = -ENOMEM;
goto out;
}
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error)
goto out_free_consistent;
/* save config data */
memcpy(&le_identifier, &buffer->EnclosureLogicalID, sizeof(__le64));
enclosure->enclosure_logical_id = le64_to_cpu(le_identifier);
enclosure->enclosure_handle = le16_to_cpu(buffer->EnclosureHandle);
enclosure->flags = le16_to_cpu(buffer->Flags);
enclosure->num_slot = le16_to_cpu(buffer->NumSlots);
enclosure->start_slot = le16_to_cpu(buffer->StartSlot);
enclosure->start_id = buffer->StartTargetID;
enclosure->start_channel = buffer->StartBus;
enclosure->sep_id = buffer->SEPTargetID;
enclosure->sep_channel = buffer->SEPBus;
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
out:
return error;
}
/**
* mptsas_add_end_device - report a new end device to sas transport layer
* @ioc: Pointer to MPT_ADAPTER structure
* @phy_info: describes attached device
*
* return (0) success (1) failure
*
**/
static int
mptsas_add_end_device(MPT_ADAPTER *ioc, struct mptsas_phyinfo *phy_info)
{
struct sas_rphy *rphy;
struct sas_port *port;
struct sas_identify identify;
char *ds = NULL;
u8 fw_id;
if (!phy_info) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: exit at line=%d\n", ioc->name,
__func__, __LINE__));
return 1;
}
fw_id = phy_info->attached.id;
if (mptsas_get_rphy(phy_info)) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, fw_id, __LINE__));
return 2;
}
port = mptsas_get_port(phy_info);
if (!port) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, fw_id, __LINE__));
return 3;
}
if (phy_info->attached.device_info &
MPI_SAS_DEVICE_INFO_SSP_TARGET)
ds = "ssp";
if (phy_info->attached.device_info &
MPI_SAS_DEVICE_INFO_STP_TARGET)
ds = "stp";
if (phy_info->attached.device_info &
MPI_SAS_DEVICE_INFO_SATA_DEVICE)
ds = "sata";
printk(MYIOC_s_INFO_FMT "attaching %s device: fw_channel %d, fw_id %d,"
" phy %d, sas_addr 0x%llx\n", ioc->name, ds,
phy_info->attached.channel, phy_info->attached.id,
phy_info->attached.phy_id, (unsigned long long)
phy_info->attached.sas_address);
mptsas_parse_device_info(&identify, &phy_info->attached);
rphy = sas_end_device_alloc(port);
if (!rphy) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, fw_id, __LINE__));
return 5; /* non-fatal: an rphy can be added later */
}
rphy->identify = identify;
if (sas_rphy_add(rphy)) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, fw_id, __LINE__));
sas_rphy_free(rphy);
return 6;
}
mptsas_set_rphy(ioc, phy_info, rphy);
return 0;
}
/**
* mptsas_del_end_device - report a deleted end device to sas transport layer
* @ioc: Pointer to MPT_ADAPTER structure
* @phy_info: describes attached device
*
**/
static void
mptsas_del_end_device(MPT_ADAPTER *ioc, struct mptsas_phyinfo *phy_info)
{
struct sas_rphy *rphy;
struct sas_port *port;
struct mptsas_portinfo *port_info;
struct mptsas_phyinfo *phy_info_parent;
int i;
char *ds = NULL;
u8 fw_id;
u64 sas_address;
if (!phy_info)
return;
fw_id = phy_info->attached.id;
sas_address = phy_info->attached.sas_address;
if (!phy_info->port_details) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, fw_id, __LINE__));
return;
}
rphy = mptsas_get_rphy(phy_info);
if (!rphy) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, fw_id, __LINE__));
return;
}
if (phy_info->attached.device_info & MPI_SAS_DEVICE_INFO_SSP_INITIATOR
|| phy_info->attached.device_info
& MPI_SAS_DEVICE_INFO_SMP_INITIATOR
|| phy_info->attached.device_info
& MPI_SAS_DEVICE_INFO_STP_INITIATOR)
ds = "initiator";
if (phy_info->attached.device_info &
MPI_SAS_DEVICE_INFO_SSP_TARGET)
ds = "ssp";
if (phy_info->attached.device_info &
MPI_SAS_DEVICE_INFO_STP_TARGET)
ds = "stp";
if (phy_info->attached.device_info &
MPI_SAS_DEVICE_INFO_SATA_DEVICE)
ds = "sata";
dev_printk(KERN_DEBUG, &rphy->dev, MYIOC_s_FMT
"removing %s device: fw_channel %d, fw_id %d, phy %d,"
"sas_addr 0x%llx\n", ioc->name, ds, phy_info->attached.channel,
phy_info->attached.id, phy_info->attached.phy_id,
(unsigned long long) sas_address);
port = mptsas_get_port(phy_info);
if (!port) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, fw_id, __LINE__));
return;
}
port_info = phy_info->portinfo;
phy_info_parent = port_info->phy_info;
for (i = 0; i < port_info->num_phys; i++, phy_info_parent++) {
if (!phy_info_parent->phy)
continue;
if (phy_info_parent->attached.sas_address !=
sas_address)
continue;
dev_printk(KERN_DEBUG, &phy_info_parent->phy->dev,
MYIOC_s_FMT "delete phy %d, phy-obj (0x%p)\n",
ioc->name, phy_info_parent->phy_id,
phy_info_parent->phy);
sas_port_delete_phy(port, phy_info_parent->phy);
}
dev_printk(KERN_DEBUG, &port->dev, MYIOC_s_FMT
"delete port %d, sas_addr (0x%llx)\n", ioc->name,
port->port_identifier, (unsigned long long)sas_address);
sas_port_delete(port);
mptsas_set_port(ioc, phy_info, NULL);
mptsas_port_delete(ioc, phy_info->port_details);
}
struct mptsas_phyinfo *
mptsas_refreshing_device_handles(MPT_ADAPTER *ioc,
struct mptsas_devinfo *sas_device)
{
struct mptsas_phyinfo *phy_info;
struct mptsas_portinfo *port_info;
int i;
phy_info = mptsas_find_phyinfo_by_sas_address(ioc,
sas_device->sas_address);
if (!phy_info)
goto out;
port_info = phy_info->portinfo;
if (!port_info)
goto out;
mutex_lock(&ioc->sas_topology_mutex);
for (i = 0; i < port_info->num_phys; i++) {
if (port_info->phy_info[i].attached.sas_address !=
sas_device->sas_address)
continue;
port_info->phy_info[i].attached.channel = sas_device->channel;
port_info->phy_info[i].attached.id = sas_device->id;
port_info->phy_info[i].attached.sas_address =
sas_device->sas_address;
port_info->phy_info[i].attached.handle = sas_device->handle;
port_info->phy_info[i].attached.handle_parent =
sas_device->handle_parent;
port_info->phy_info[i].attached.handle_enclosure =
sas_device->handle_enclosure;
}
mutex_unlock(&ioc->sas_topology_mutex);
out:
return phy_info;
}
/**
* mptsas_firmware_event_work - work thread for processing fw events
* @work: work queue payload containing info describing the event
* Context: user
*
*/
static void
mptsas_firmware_event_work(struct work_struct *work)
{
struct fw_event_work *fw_event =
container_of(work, struct fw_event_work, work.work);
MPT_ADAPTER *ioc = fw_event->ioc;
/* special rescan topology handling */
if (fw_event->event == -1) {
if (ioc->in_rescan) {
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: rescan ignored as it is in progress\n",
ioc->name, __func__));
return;
}
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s: rescan after "
"reset\n", ioc->name, __func__));
ioc->in_rescan = 1;
mptsas_not_responding_devices(ioc);
mptsas_scan_sas_topology(ioc);
ioc->in_rescan = 0;
mptsas_free_fw_event(ioc, fw_event);
mptsas_fw_event_on(ioc);
return;
}
/* events handling turned off during host reset */
if (ioc->fw_events_off) {
mptsas_free_fw_event(ioc, fw_event);
return;
}
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s: fw_event=(0x%p), "
"event = (0x%02x)\n", ioc->name, __func__, fw_event,
(fw_event->event & 0xFF)));
switch (fw_event->event) {
case MPI_EVENT_SAS_DEVICE_STATUS_CHANGE:
mptsas_send_sas_event(fw_event);
break;
case MPI_EVENT_INTEGRATED_RAID:
mptsas_send_raid_event(fw_event);
break;
case MPI_EVENT_IR2:
mptsas_send_ir2_event(fw_event);
break;
case MPI_EVENT_PERSISTENT_TABLE_FULL:
mptbase_sas_persist_operation(ioc,
MPI_SAS_OP_CLEAR_NOT_PRESENT);
mptsas_free_fw_event(ioc, fw_event);
break;
case MPI_EVENT_SAS_BROADCAST_PRIMITIVE:
mptsas_broadcast_primative_work(fw_event);
break;
case MPI_EVENT_SAS_EXPANDER_STATUS_CHANGE:
mptsas_send_expander_event(fw_event);
break;
case MPI_EVENT_SAS_PHY_LINK_STATUS:
mptsas_send_link_status_event(fw_event);
break;
case MPI_EVENT_QUEUE_FULL:
mptsas_handle_queue_full_event(fw_event);
break;
}
}
static int
mptsas_slave_configure(struct scsi_device *sdev)
{
struct Scsi_Host *host = sdev->host;
MPT_SCSI_HOST *hd = shost_priv(host);
MPT_ADAPTER *ioc = hd->ioc;
VirtDevice *vdevice = sdev->hostdata;
if (vdevice->vtarget->deleted) {
sdev_printk(KERN_INFO, sdev, "clearing deleted flag\n");
vdevice->vtarget->deleted = 0;
}
/*
* RAID volumes placed beyond the last expected port.
* Ignore sending sas mode pages in that case..
*/
if (sdev->channel == MPTSAS_RAID_CHANNEL) {
mptsas_add_device_component_starget_ir(ioc, scsi_target(sdev));
goto out;
}
sas_read_port_mode_page(sdev);
mptsas_add_device_component_starget(ioc, scsi_target(sdev));
out:
return mptscsih_slave_configure(sdev);
}
static int
mptsas_target_alloc(struct scsi_target *starget)
{
struct Scsi_Host *host = dev_to_shost(&starget->dev);
MPT_SCSI_HOST *hd = shost_priv(host);
VirtTarget *vtarget;
u8 id, channel;
struct sas_rphy *rphy;
struct mptsas_portinfo *p;
int i;
MPT_ADAPTER *ioc = hd->ioc;
vtarget = kzalloc(sizeof(VirtTarget), GFP_KERNEL);
if (!vtarget)
return -ENOMEM;
vtarget->starget = starget;
vtarget->ioc_id = ioc->id;
vtarget->tflags = MPT_TARGET_FLAGS_Q_YES;
id = starget->id;
channel = 0;
/*
* RAID volumes placed beyond the last expected port.
*/
if (starget->channel == MPTSAS_RAID_CHANNEL) {
if (!ioc->raid_data.pIocPg2) {
kfree(vtarget);
return -ENXIO;
}
for (i = 0; i < ioc->raid_data.pIocPg2->NumActiveVolumes; i++) {
if (id == ioc->raid_data.pIocPg2->
RaidVolume[i].VolumeID) {
channel = ioc->raid_data.pIocPg2->
RaidVolume[i].VolumeBus;
}
}
vtarget->raidVolume = 1;
goto out;
}
rphy = dev_to_rphy(starget->dev.parent);
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry(p, &ioc->sas_topology, list) {
for (i = 0; i < p->num_phys; i++) {
if (p->phy_info[i].attached.sas_address !=
rphy->identify.sas_address)
continue;
id = p->phy_info[i].attached.id;
channel = p->phy_info[i].attached.channel;
mptsas_set_starget(&p->phy_info[i], starget);
/*
* Exposing hidden raid components
*/
if (mptscsih_is_phys_disk(ioc, channel, id)) {
id = mptscsih_raid_id_to_num(ioc,
channel, id);
vtarget->tflags |=
MPT_TARGET_FLAGS_RAID_COMPONENT;
p->phy_info[i].attached.phys_disk_num = id;
}
mutex_unlock(&ioc->sas_topology_mutex);
goto out;
}
}
mutex_unlock(&ioc->sas_topology_mutex);
kfree(vtarget);
return -ENXIO;
out:
vtarget->id = id;
vtarget->channel = channel;
starget->hostdata = vtarget;
return 0;
}
static void
mptsas_target_destroy(struct scsi_target *starget)
{
struct Scsi_Host *host = dev_to_shost(&starget->dev);
MPT_SCSI_HOST *hd = shost_priv(host);
struct sas_rphy *rphy;
struct mptsas_portinfo *p;
int i;
MPT_ADAPTER *ioc = hd->ioc;
VirtTarget *vtarget;
if (!starget->hostdata)
return;
vtarget = starget->hostdata;
mptsas_del_device_component_by_os(ioc, starget->channel,
starget->id);
if (starget->channel == MPTSAS_RAID_CHANNEL)
goto out;
rphy = dev_to_rphy(starget->dev.parent);
list_for_each_entry(p, &ioc->sas_topology, list) {
for (i = 0; i < p->num_phys; i++) {
if (p->phy_info[i].attached.sas_address !=
rphy->identify.sas_address)
continue;
starget_printk(KERN_INFO, starget, MYIOC_s_FMT
"delete device: fw_channel %d, fw_id %d, phy %d, "
"sas_addr 0x%llx\n", ioc->name,
p->phy_info[i].attached.channel,
p->phy_info[i].attached.id,
p->phy_info[i].attached.phy_id, (unsigned long long)
p->phy_info[i].attached.sas_address);
mptsas_set_starget(&p->phy_info[i], NULL);
}
}
out:
vtarget->starget = NULL;
kfree(starget->hostdata);
starget->hostdata = NULL;
}
static int
mptsas_slave_alloc(struct scsi_device *sdev)
{
struct Scsi_Host *host = sdev->host;
MPT_SCSI_HOST *hd = shost_priv(host);
struct sas_rphy *rphy;
struct mptsas_portinfo *p;
VirtDevice *vdevice;
struct scsi_target *starget;
int i;
MPT_ADAPTER *ioc = hd->ioc;
vdevice = kzalloc(sizeof(VirtDevice), GFP_KERNEL);
if (!vdevice) {
printk(MYIOC_s_ERR_FMT "slave_alloc kzalloc(%zd) FAILED!\n",
ioc->name, sizeof(VirtDevice));
return -ENOMEM;
}
starget = scsi_target(sdev);
vdevice->vtarget = starget->hostdata;
if (sdev->channel == MPTSAS_RAID_CHANNEL)
goto out;
rphy = dev_to_rphy(sdev->sdev_target->dev.parent);
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry(p, &ioc->sas_topology, list) {
for (i = 0; i < p->num_phys; i++) {
if (p->phy_info[i].attached.sas_address !=
rphy->identify.sas_address)
continue;
vdevice->lun = sdev->lun;
/*
* Exposing hidden raid components
*/
if (mptscsih_is_phys_disk(ioc,
p->phy_info[i].attached.channel,
p->phy_info[i].attached.id))
sdev->no_uld_attach = 1;
mutex_unlock(&ioc->sas_topology_mutex);
goto out;
}
}
mutex_unlock(&ioc->sas_topology_mutex);
kfree(vdevice);
return -ENXIO;
out:
vdevice->vtarget->num_luns++;
sdev->hostdata = vdevice;
return 0;
}
static int
mptsas_qcmd_lck(struct scsi_cmnd *SCpnt, void (*done)(struct scsi_cmnd *))
{
MPT_SCSI_HOST *hd;
MPT_ADAPTER *ioc;
VirtDevice *vdevice = SCpnt->device->hostdata;
if (!vdevice || !vdevice->vtarget || vdevice->vtarget->deleted) {
SCpnt->result = DID_NO_CONNECT << 16;
done(SCpnt);
return 0;
}
hd = shost_priv(SCpnt->device->host);
ioc = hd->ioc;
if (ioc->sas_discovery_quiesce_io)
return SCSI_MLQUEUE_HOST_BUSY;
if (ioc->debug_level & MPT_DEBUG_SCSI)
scsi_print_command(SCpnt);
return mptscsih_qcmd(SCpnt,done);
}
static DEF_SCSI_QCMD(mptsas_qcmd)
/**
* mptsas_mptsas_eh_timed_out - resets the scsi_cmnd timeout
* if the device under question is currently in the
* device removal delay.
* @sc: scsi command that the midlayer is about to time out
*
**/
static enum blk_eh_timer_return mptsas_eh_timed_out(struct scsi_cmnd *sc)
{
MPT_SCSI_HOST *hd;
MPT_ADAPTER *ioc;
VirtDevice *vdevice;
enum blk_eh_timer_return rc = BLK_EH_NOT_HANDLED;
hd = shost_priv(sc->device->host);
if (hd == NULL) {
printk(KERN_ERR MYNAM ": %s: Can't locate host! (sc=%p)\n",
__func__, sc);
goto done;
}
ioc = hd->ioc;
if (ioc->bus_type != SAS) {
printk(KERN_ERR MYNAM ": %s: Wrong bus type (sc=%p)\n",
__func__, sc);
goto done;
}
/* In case if IOC is in reset from internal context.
* Do not execute EEH for the same IOC. SML should to reset timer.
*/
if (ioc->ioc_reset_in_progress) {
dtmprintk(ioc, printk(MYIOC_s_WARN_FMT ": %s: ioc is in reset,"
"SML need to reset the timer (sc=%p)\n",
ioc->name, __func__, sc));
rc = BLK_EH_RESET_TIMER;
}
vdevice = sc->device->hostdata;
if (vdevice && vdevice->vtarget && (vdevice->vtarget->inDMD
|| vdevice->vtarget->deleted)) {
dtmprintk(ioc, printk(MYIOC_s_WARN_FMT ": %s: target removed "
"or in device removal delay (sc=%p)\n",
ioc->name, __func__, sc));
rc = BLK_EH_RESET_TIMER;
goto done;
}
done:
return rc;
}
static struct scsi_host_template mptsas_driver_template = {
.module = THIS_MODULE,
.proc_name = "mptsas",
.show_info = mptscsih_show_info,
.name = "MPT SAS Host",
.info = mptscsih_info,
.queuecommand = mptsas_qcmd,
.target_alloc = mptsas_target_alloc,
.slave_alloc = mptsas_slave_alloc,
.slave_configure = mptsas_slave_configure,
.target_destroy = mptsas_target_destroy,
.slave_destroy = mptscsih_slave_destroy,
.change_queue_depth = mptscsih_change_queue_depth,
.eh_abort_handler = mptscsih_abort,
.eh_device_reset_handler = mptscsih_dev_reset,
.eh_host_reset_handler = mptscsih_host_reset,
.bios_param = mptscsih_bios_param,
.can_queue = MPT_SAS_CAN_QUEUE,
.this_id = -1,
.sg_tablesize = MPT_SCSI_SG_DEPTH,
.max_sectors = 8192,
.cmd_per_lun = 7,
.use_clustering = ENABLE_CLUSTERING,
.shost_attrs = mptscsih_host_attrs,
};
static int mptsas_get_linkerrors(struct sas_phy *phy)
{
MPT_ADAPTER *ioc = phy_to_ioc(phy);
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasPhyPage1_t *buffer;
dma_addr_t dma_handle;
int error;
/* FIXME: only have link errors on local phys */
if (!scsi_is_sas_phy_local(phy))
return -EINVAL;
hdr.PageVersion = MPI_SASPHY1_PAGEVERSION;
hdr.ExtPageLength = 0;
hdr.PageNumber = 1 /* page number 1*/;
hdr.Reserved1 = 0;
hdr.Reserved2 = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
hdr.ExtPageType = MPI_CONFIG_EXTPAGETYPE_SAS_PHY;
cfg.cfghdr.ehdr = &hdr;
cfg.physAddr = -1;
cfg.pageAddr = phy->identify.phy_identifier;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
error = mpt_config(ioc, &cfg);
if (error)
return error;
if (!hdr.ExtPageLength)
return -ENXIO;
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer)
return -ENOMEM;
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error)
goto out_free_consistent;
mptsas_print_phy_pg1(ioc, buffer);
phy->invalid_dword_count = le32_to_cpu(buffer->InvalidDwordCount);
phy->running_disparity_error_count =
le32_to_cpu(buffer->RunningDisparityErrorCount);
phy->loss_of_dword_sync_count =
le32_to_cpu(buffer->LossDwordSynchCount);
phy->phy_reset_problem_count =
le32_to_cpu(buffer->PhyResetProblemCount);
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
return error;
}
static int mptsas_mgmt_done(MPT_ADAPTER *ioc, MPT_FRAME_HDR *req,
MPT_FRAME_HDR *reply)
{
ioc->sas_mgmt.status |= MPT_MGMT_STATUS_COMMAND_GOOD;
if (reply != NULL) {
ioc->sas_mgmt.status |= MPT_MGMT_STATUS_RF_VALID;
memcpy(ioc->sas_mgmt.reply, reply,
min(ioc->reply_sz, 4 * reply->u.reply.MsgLength));
}
if (ioc->sas_mgmt.status & MPT_MGMT_STATUS_PENDING) {
ioc->sas_mgmt.status &= ~MPT_MGMT_STATUS_PENDING;
complete(&ioc->sas_mgmt.done);
return 1;
}
return 0;
}
static int mptsas_phy_reset(struct sas_phy *phy, int hard_reset)
{
MPT_ADAPTER *ioc = phy_to_ioc(phy);
SasIoUnitControlRequest_t *req;
SasIoUnitControlReply_t *reply;
MPT_FRAME_HDR *mf;
MPIHeader_t *hdr;
unsigned long timeleft;
int error = -ERESTARTSYS;
/* FIXME: fusion doesn't allow non-local phy reset */
if (!scsi_is_sas_phy_local(phy))
return -EINVAL;
/* not implemented for expanders */
if (phy->identify.target_port_protocols & SAS_PROTOCOL_SMP)
return -ENXIO;
if (mutex_lock_interruptible(&ioc->sas_mgmt.mutex))
goto out;
mf = mpt_get_msg_frame(mptsasMgmtCtx, ioc);
if (!mf) {
error = -ENOMEM;
goto out_unlock;
}
hdr = (MPIHeader_t *) mf;
req = (SasIoUnitControlRequest_t *)mf;
memset(req, 0, sizeof(SasIoUnitControlRequest_t));
req->Function = MPI_FUNCTION_SAS_IO_UNIT_CONTROL;
req->MsgContext = hdr->MsgContext;
req->Operation = hard_reset ?
MPI_SAS_OP_PHY_HARD_RESET : MPI_SAS_OP_PHY_LINK_RESET;
req->PhyNum = phy->identify.phy_identifier;
INITIALIZE_MGMT_STATUS(ioc->sas_mgmt.status)
mpt_put_msg_frame(mptsasMgmtCtx, ioc, mf);
timeleft = wait_for_completion_timeout(&ioc->sas_mgmt.done,
10 * HZ);
if (!(ioc->sas_mgmt.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
error = -ETIME;
mpt_free_msg_frame(ioc, mf);
if (ioc->sas_mgmt.status & MPT_MGMT_STATUS_DID_IOCRESET)
goto out_unlock;
if (!timeleft)
mpt_Soft_Hard_ResetHandler(ioc, CAN_SLEEP);
goto out_unlock;
}
/* a reply frame is expected */
if ((ioc->sas_mgmt.status &
MPT_MGMT_STATUS_RF_VALID) == 0) {
error = -ENXIO;
goto out_unlock;
}
/* process the completed Reply Message Frame */
reply = (SasIoUnitControlReply_t *)ioc->sas_mgmt.reply;
if (reply->IOCStatus != MPI_IOCSTATUS_SUCCESS) {
printk(MYIOC_s_INFO_FMT "%s: IOCStatus=0x%X IOCLogInfo=0x%X\n",
ioc->name, __func__, reply->IOCStatus, reply->IOCLogInfo);
error = -ENXIO;
goto out_unlock;
}
error = 0;
out_unlock:
CLEAR_MGMT_STATUS(ioc->sas_mgmt.status)
mutex_unlock(&ioc->sas_mgmt.mutex);
out:
return error;
}
static int
mptsas_get_enclosure_identifier(struct sas_rphy *rphy, u64 *identifier)
{
MPT_ADAPTER *ioc = rphy_to_ioc(rphy);
int i, error;
struct mptsas_portinfo *p;
struct mptsas_enclosure enclosure_info;
u64 enclosure_handle;
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry(p, &ioc->sas_topology, list) {
for (i = 0; i < p->num_phys; i++) {
if (p->phy_info[i].attached.sas_address ==
rphy->identify.sas_address) {
enclosure_handle = p->phy_info[i].
attached.handle_enclosure;
goto found_info;
}
}
}
mutex_unlock(&ioc->sas_topology_mutex);
return -ENXIO;
found_info:
mutex_unlock(&ioc->sas_topology_mutex);
memset(&enclosure_info, 0, sizeof(struct mptsas_enclosure));
error = mptsas_sas_enclosure_pg0(ioc, &enclosure_info,
(MPI_SAS_ENCLOS_PGAD_FORM_HANDLE <<
MPI_SAS_ENCLOS_PGAD_FORM_SHIFT), enclosure_handle);
if (!error)
*identifier = enclosure_info.enclosure_logical_id;
return error;
}
static int
mptsas_get_bay_identifier(struct sas_rphy *rphy)
{
MPT_ADAPTER *ioc = rphy_to_ioc(rphy);
struct mptsas_portinfo *p;
int i, rc;
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry(p, &ioc->sas_topology, list) {
for (i = 0; i < p->num_phys; i++) {
if (p->phy_info[i].attached.sas_address ==
rphy->identify.sas_address) {
rc = p->phy_info[i].attached.slot;
goto out;
}
}
}
rc = -ENXIO;
out:
mutex_unlock(&ioc->sas_topology_mutex);
return rc;
}
static int mptsas_smp_handler(struct Scsi_Host *shost, struct sas_rphy *rphy,
struct request *req)
{
MPT_ADAPTER *ioc = ((MPT_SCSI_HOST *) shost->hostdata)->ioc;
MPT_FRAME_HDR *mf;
SmpPassthroughRequest_t *smpreq;
struct request *rsp = req->next_rq;
int ret;
int flagsLength;
unsigned long timeleft;
char *psge;
dma_addr_t dma_addr_in = 0;
dma_addr_t dma_addr_out = 0;
u64 sas_address = 0;
if (!rsp) {
printk(MYIOC_s_ERR_FMT "%s: the smp response space is missing\n",
ioc->name, __func__);
return -EINVAL;
}
/* do we need to support multiple segments? */
if (bio_segments(req->bio) > 1 || bio_segments(rsp->bio) > 1) {
printk(MYIOC_s_ERR_FMT "%s: multiple segments req %u %u, rsp %u %u\n",
ioc->name, __func__, bio_segments(req->bio), blk_rq_bytes(req),
bio_segments(rsp->bio), blk_rq_bytes(rsp));
return -EINVAL;
}
ret = mutex_lock_interruptible(&ioc->sas_mgmt.mutex);
if (ret)
goto out;
mf = mpt_get_msg_frame(mptsasMgmtCtx, ioc);
if (!mf) {
ret = -ENOMEM;
goto out_unlock;
}
smpreq = (SmpPassthroughRequest_t *)mf;
memset(smpreq, 0, sizeof(*smpreq));
smpreq->RequestDataLength = cpu_to_le16(blk_rq_bytes(req) - 4);
smpreq->Function = MPI_FUNCTION_SMP_PASSTHROUGH;
if (rphy)
sas_address = rphy->identify.sas_address;
else {
struct mptsas_portinfo *port_info;
mutex_lock(&ioc->sas_topology_mutex);
port_info = ioc->hba_port_info;
if (port_info && port_info->phy_info)
sas_address =
port_info->phy_info[0].phy->identify.sas_address;
mutex_unlock(&ioc->sas_topology_mutex);
}
*((u64 *)&smpreq->SASAddress) = cpu_to_le64(sas_address);
psge = (char *)
(((int *) mf) + (offsetof(SmpPassthroughRequest_t, SGL) / 4));
/* request */
flagsLength = (MPI_SGE_FLAGS_SIMPLE_ELEMENT |
MPI_SGE_FLAGS_END_OF_BUFFER |
MPI_SGE_FLAGS_DIRECTION)
<< MPI_SGE_FLAGS_SHIFT;
flagsLength |= (blk_rq_bytes(req) - 4);
dma_addr_out = pci_map_single(ioc->pcidev, bio_data(req->bio),
blk_rq_bytes(req), PCI_DMA_BIDIRECTIONAL);
if (!dma_addr_out)
goto put_mf;
ioc->add_sge(psge, flagsLength, dma_addr_out);
psge += ioc->SGE_size;
/* response */
flagsLength = MPI_SGE_FLAGS_SIMPLE_ELEMENT |
MPI_SGE_FLAGS_SYSTEM_ADDRESS |
MPI_SGE_FLAGS_IOC_TO_HOST |
MPI_SGE_FLAGS_END_OF_BUFFER;
flagsLength = flagsLength << MPI_SGE_FLAGS_SHIFT;
flagsLength |= blk_rq_bytes(rsp) + 4;
dma_addr_in = pci_map_single(ioc->pcidev, bio_data(rsp->bio),
blk_rq_bytes(rsp), PCI_DMA_BIDIRECTIONAL);
if (!dma_addr_in)
goto unmap;
ioc->add_sge(psge, flagsLength, dma_addr_in);
INITIALIZE_MGMT_STATUS(ioc->sas_mgmt.status)
mpt_put_msg_frame(mptsasMgmtCtx, ioc, mf);
timeleft = wait_for_completion_timeout(&ioc->sas_mgmt.done, 10 * HZ);
if (!(ioc->sas_mgmt.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
ret = -ETIME;
mpt_free_msg_frame(ioc, mf);
mf = NULL;
if (ioc->sas_mgmt.status & MPT_MGMT_STATUS_DID_IOCRESET)
goto unmap;
if (!timeleft)
mpt_Soft_Hard_ResetHandler(ioc, CAN_SLEEP);
goto unmap;
}
mf = NULL;
if (ioc->sas_mgmt.status & MPT_MGMT_STATUS_RF_VALID) {
SmpPassthroughReply_t *smprep;
smprep = (SmpPassthroughReply_t *)ioc->sas_mgmt.reply;
memcpy(req->sense, smprep, sizeof(*smprep));
req->sense_len = sizeof(*smprep);
req->resid_len = 0;
rsp->resid_len -= smprep->ResponseDataLength;
} else {
printk(MYIOC_s_ERR_FMT
"%s: smp passthru reply failed to be returned\n",
ioc->name, __func__);
ret = -ENXIO;
}
unmap:
if (dma_addr_out)
pci_unmap_single(ioc->pcidev, dma_addr_out, blk_rq_bytes(req),
PCI_DMA_BIDIRECTIONAL);
if (dma_addr_in)
pci_unmap_single(ioc->pcidev, dma_addr_in, blk_rq_bytes(rsp),
PCI_DMA_BIDIRECTIONAL);
put_mf:
if (mf)
mpt_free_msg_frame(ioc, mf);
out_unlock:
CLEAR_MGMT_STATUS(ioc->sas_mgmt.status)
mutex_unlock(&ioc->sas_mgmt.mutex);
out:
return ret;
}
static struct sas_function_template mptsas_transport_functions = {
.get_linkerrors = mptsas_get_linkerrors,
.get_enclosure_identifier = mptsas_get_enclosure_identifier,
.get_bay_identifier = mptsas_get_bay_identifier,
.phy_reset = mptsas_phy_reset,
.smp_handler = mptsas_smp_handler,
};
static struct scsi_transport_template *mptsas_transport_template;
static int
mptsas_sas_io_unit_pg0(MPT_ADAPTER *ioc, struct mptsas_portinfo *port_info)
{
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasIOUnitPage0_t *buffer;
dma_addr_t dma_handle;
int error, i;
hdr.PageVersion = MPI_SASIOUNITPAGE0_PAGEVERSION;
hdr.ExtPageLength = 0;
hdr.PageNumber = 0;
hdr.Reserved1 = 0;
hdr.Reserved2 = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
hdr.ExtPageType = MPI_CONFIG_EXTPAGETYPE_SAS_IO_UNIT;
cfg.cfghdr.ehdr = &hdr;
cfg.physAddr = -1;
cfg.pageAddr = 0;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
error = mpt_config(ioc, &cfg);
if (error)
goto out;
if (!hdr.ExtPageLength) {
error = -ENXIO;
goto out;
}
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer) {
error = -ENOMEM;
goto out;
}
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error)
goto out_free_consistent;
port_info->num_phys = buffer->NumPhys;
port_info->phy_info = kcalloc(port_info->num_phys,
sizeof(struct mptsas_phyinfo), GFP_KERNEL);
if (!port_info->phy_info) {
error = -ENOMEM;
goto out_free_consistent;
}
ioc->nvdata_version_persistent =
le16_to_cpu(buffer->NvdataVersionPersistent);
ioc->nvdata_version_default =
le16_to_cpu(buffer->NvdataVersionDefault);
for (i = 0; i < port_info->num_phys; i++) {
mptsas_print_phy_data(ioc, &buffer->PhyData[i]);
port_info->phy_info[i].phy_id = i;
port_info->phy_info[i].port_id =
buffer->PhyData[i].Port;
port_info->phy_info[i].negotiated_link_rate =
buffer->PhyData[i].NegotiatedLinkRate;
port_info->phy_info[i].portinfo = port_info;
port_info->phy_info[i].handle =
le16_to_cpu(buffer->PhyData[i].ControllerDevHandle);
}
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
out:
return error;
}
static int
mptsas_sas_io_unit_pg1(MPT_ADAPTER *ioc)
{
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasIOUnitPage1_t *buffer;
dma_addr_t dma_handle;
int error;
u8 device_missing_delay;
memset(&hdr, 0, sizeof(ConfigExtendedPageHeader_t));
memset(&cfg, 0, sizeof(CONFIGPARMS));
cfg.cfghdr.ehdr = &hdr;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
cfg.cfghdr.ehdr->PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
cfg.cfghdr.ehdr->ExtPageType = MPI_CONFIG_EXTPAGETYPE_SAS_IO_UNIT;
cfg.cfghdr.ehdr->PageVersion = MPI_SASIOUNITPAGE1_PAGEVERSION;
cfg.cfghdr.ehdr->PageNumber = 1;
error = mpt_config(ioc, &cfg);
if (error)
goto out;
if (!hdr.ExtPageLength) {
error = -ENXIO;
goto out;
}
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer) {
error = -ENOMEM;
goto out;
}
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error)
goto out_free_consistent;
ioc->io_missing_delay =
le16_to_cpu(buffer->IODeviceMissingDelay);
device_missing_delay = buffer->ReportDeviceMissingDelay;
ioc->device_missing_delay = (device_missing_delay & MPI_SAS_IOUNIT1_REPORT_MISSING_UNIT_16) ?
(device_missing_delay & MPI_SAS_IOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16 :
device_missing_delay & MPI_SAS_IOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
out:
return error;
}
static int
mptsas_sas_phy_pg0(MPT_ADAPTER *ioc, struct mptsas_phyinfo *phy_info,
u32 form, u32 form_specific)
{
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasPhyPage0_t *buffer;
dma_addr_t dma_handle;
int error;
hdr.PageVersion = MPI_SASPHY0_PAGEVERSION;
hdr.ExtPageLength = 0;
hdr.PageNumber = 0;
hdr.Reserved1 = 0;
hdr.Reserved2 = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
hdr.ExtPageType = MPI_CONFIG_EXTPAGETYPE_SAS_PHY;
cfg.cfghdr.ehdr = &hdr;
cfg.dir = 0; /* read */
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
/* Get Phy Pg 0 for each Phy. */
cfg.physAddr = -1;
cfg.pageAddr = form + form_specific;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
error = mpt_config(ioc, &cfg);
if (error)
goto out;
if (!hdr.ExtPageLength) {
error = -ENXIO;
goto out;
}
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer) {
error = -ENOMEM;
goto out;
}
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error)
goto out_free_consistent;
mptsas_print_phy_pg0(ioc, buffer);
phy_info->hw_link_rate = buffer->HwLinkRate;
phy_info->programmed_link_rate = buffer->ProgrammedLinkRate;
phy_info->identify.handle = le16_to_cpu(buffer->OwnerDevHandle);
phy_info->attached.handle = le16_to_cpu(buffer->AttachedDevHandle);
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
out:
return error;
}
static int
mptsas_sas_device_pg0(MPT_ADAPTER *ioc, struct mptsas_devinfo *device_info,
u32 form, u32 form_specific)
{
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasDevicePage0_t *buffer;
dma_addr_t dma_handle;
__le64 sas_address;
int error=0;
hdr.PageVersion = MPI_SASDEVICE0_PAGEVERSION;
hdr.ExtPageLength = 0;
hdr.PageNumber = 0;
hdr.Reserved1 = 0;
hdr.Reserved2 = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
hdr.ExtPageType = MPI_CONFIG_EXTPAGETYPE_SAS_DEVICE;
cfg.cfghdr.ehdr = &hdr;
cfg.pageAddr = form + form_specific;
cfg.physAddr = -1;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
memset(device_info, 0, sizeof(struct mptsas_devinfo));
error = mpt_config(ioc, &cfg);
if (error)
goto out;
if (!hdr.ExtPageLength) {
error = -ENXIO;
goto out;
}
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer) {
error = -ENOMEM;
goto out;
}
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error == MPI_IOCSTATUS_CONFIG_INVALID_PAGE) {
error = -ENODEV;
goto out_free_consistent;
}
if (error)
goto out_free_consistent;
mptsas_print_device_pg0(ioc, buffer);
memset(device_info, 0, sizeof(struct mptsas_devinfo));
device_info->handle = le16_to_cpu(buffer->DevHandle);
device_info->handle_parent = le16_to_cpu(buffer->ParentDevHandle);
device_info->handle_enclosure =
le16_to_cpu(buffer->EnclosureHandle);
device_info->slot = le16_to_cpu(buffer->Slot);
device_info->phy_id = buffer->PhyNum;
device_info->port_id = buffer->PhysicalPort;
device_info->id = buffer->TargetID;
device_info->phys_disk_num = ~0;
device_info->channel = buffer->Bus;
memcpy(&sas_address, &buffer->SASAddress, sizeof(__le64));
device_info->sas_address = le64_to_cpu(sas_address);
device_info->device_info =
le32_to_cpu(buffer->DeviceInfo);
device_info->flags = le16_to_cpu(buffer->Flags);
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
out:
return error;
}
static int
mptsas_sas_expander_pg0(MPT_ADAPTER *ioc, struct mptsas_portinfo *port_info,
u32 form, u32 form_specific)
{
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasExpanderPage0_t *buffer;
dma_addr_t dma_handle;
int i, error;
__le64 sas_address;
memset(port_info, 0, sizeof(struct mptsas_portinfo));
hdr.PageVersion = MPI_SASEXPANDER0_PAGEVERSION;
hdr.ExtPageLength = 0;
hdr.PageNumber = 0;
hdr.Reserved1 = 0;
hdr.Reserved2 = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
hdr.ExtPageType = MPI_CONFIG_EXTPAGETYPE_SAS_EXPANDER;
cfg.cfghdr.ehdr = &hdr;
cfg.physAddr = -1;
cfg.pageAddr = form + form_specific;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
memset(port_info, 0, sizeof(struct mptsas_portinfo));
error = mpt_config(ioc, &cfg);
if (error)
goto out;
if (!hdr.ExtPageLength) {
error = -ENXIO;
goto out;
}
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer) {
error = -ENOMEM;
goto out;
}
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error == MPI_IOCSTATUS_CONFIG_INVALID_PAGE) {
error = -ENODEV;
goto out_free_consistent;
}
if (error)
goto out_free_consistent;
/* save config data */
port_info->num_phys = (buffer->NumPhys) ? buffer->NumPhys : 1;
port_info->phy_info = kcalloc(port_info->num_phys,
sizeof(struct mptsas_phyinfo), GFP_KERNEL);
if (!port_info->phy_info) {
error = -ENOMEM;
goto out_free_consistent;
}
memcpy(&sas_address, &buffer->SASAddress, sizeof(__le64));
for (i = 0; i < port_info->num_phys; i++) {
port_info->phy_info[i].portinfo = port_info;
port_info->phy_info[i].handle =
le16_to_cpu(buffer->DevHandle);
port_info->phy_info[i].identify.sas_address =
le64_to_cpu(sas_address);
port_info->phy_info[i].identify.handle_parent =
le16_to_cpu(buffer->ParentDevHandle);
}
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
out:
return error;
}
static int
mptsas_sas_expander_pg1(MPT_ADAPTER *ioc, struct mptsas_phyinfo *phy_info,
u32 form, u32 form_specific)
{
ConfigExtendedPageHeader_t hdr;
CONFIGPARMS cfg;
SasExpanderPage1_t *buffer;
dma_addr_t dma_handle;
int error=0;
hdr.PageVersion = MPI_SASEXPANDER1_PAGEVERSION;
hdr.ExtPageLength = 0;
hdr.PageNumber = 1;
hdr.Reserved1 = 0;
hdr.Reserved2 = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
hdr.ExtPageType = MPI_CONFIG_EXTPAGETYPE_SAS_EXPANDER;
cfg.cfghdr.ehdr = &hdr;
cfg.physAddr = -1;
cfg.pageAddr = form + form_specific;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
error = mpt_config(ioc, &cfg);
if (error)
goto out;
if (!hdr.ExtPageLength) {
error = -ENXIO;
goto out;
}
buffer = pci_alloc_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
&dma_handle);
if (!buffer) {
error = -ENOMEM;
goto out;
}
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
error = mpt_config(ioc, &cfg);
if (error == MPI_IOCSTATUS_CONFIG_INVALID_PAGE) {
error = -ENODEV;
goto out_free_consistent;
}
if (error)
goto out_free_consistent;
mptsas_print_expander_pg1(ioc, buffer);
/* save config data */
phy_info->phy_id = buffer->PhyIdentifier;
phy_info->port_id = buffer->PhysicalPort;
phy_info->negotiated_link_rate = buffer->NegotiatedLinkRate;
phy_info->programmed_link_rate = buffer->ProgrammedLinkRate;
phy_info->hw_link_rate = buffer->HwLinkRate;
phy_info->identify.handle = le16_to_cpu(buffer->OwnerDevHandle);
phy_info->attached.handle = le16_to_cpu(buffer->AttachedDevHandle);
out_free_consistent:
pci_free_consistent(ioc->pcidev, hdr.ExtPageLength * 4,
buffer, dma_handle);
out:
return error;
}
struct rep_manu_request{
u8 smp_frame_type;
u8 function;
u8 reserved;
u8 request_length;
};
struct rep_manu_reply{
u8 smp_frame_type; /* 0x41 */
u8 function; /* 0x01 */
u8 function_result;
u8 response_length;
u16 expander_change_count;
u8 reserved0[2];
u8 sas_format:1;
u8 reserved1:7;
u8 reserved2[3];
u8 vendor_id[SAS_EXPANDER_VENDOR_ID_LEN];
u8 product_id[SAS_EXPANDER_PRODUCT_ID_LEN];
u8 product_rev[SAS_EXPANDER_PRODUCT_REV_LEN];
u8 component_vendor_id[SAS_EXPANDER_COMPONENT_VENDOR_ID_LEN];
u16 component_id;
u8 component_revision_id;
u8 reserved3;
u8 vendor_specific[8];
};
/**
* mptsas_exp_repmanufacture_info -
* @ioc: per adapter object
* @sas_address: expander sas address
* @edev: the sas_expander_device object
*
* Fills in the sas_expander_device object when SMP port is created.
*
* Returns 0 for success, non-zero for failure.
*/
static int
mptsas_exp_repmanufacture_info(MPT_ADAPTER *ioc,
u64 sas_address, struct sas_expander_device *edev)
{
MPT_FRAME_HDR *mf;
SmpPassthroughRequest_t *smpreq;
SmpPassthroughReply_t *smprep;
struct rep_manu_reply *manufacture_reply;
struct rep_manu_request *manufacture_request;
int ret;
int flagsLength;
unsigned long timeleft;
char *psge;
unsigned long flags;
void *data_out = NULL;
dma_addr_t data_out_dma = 0;
u32 sz;
spin_lock_irqsave(&ioc->taskmgmt_lock, flags);
if (ioc->ioc_reset_in_progress) {
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
printk(MYIOC_s_INFO_FMT "%s: host reset in progress!\n",
__func__, ioc->name);
return -EFAULT;
}
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
ret = mutex_lock_interruptible(&ioc->sas_mgmt.mutex);
if (ret)
goto out;
mf = mpt_get_msg_frame(mptsasMgmtCtx, ioc);
if (!mf) {
ret = -ENOMEM;
goto out_unlock;
}
smpreq = (SmpPassthroughRequest_t *)mf;
memset(smpreq, 0, sizeof(*smpreq));
sz = sizeof(struct rep_manu_request) + sizeof(struct rep_manu_reply);
data_out = pci_alloc_consistent(ioc->pcidev, sz, &data_out_dma);
if (!data_out) {
printk(KERN_ERR "Memory allocation failure at %s:%d/%s()!\n",
__FILE__, __LINE__, __func__);
ret = -ENOMEM;
goto put_mf;
}
manufacture_request = data_out;
manufacture_request->smp_frame_type = 0x40;
manufacture_request->function = 1;
manufacture_request->reserved = 0;
manufacture_request->request_length = 0;
smpreq->Function = MPI_FUNCTION_SMP_PASSTHROUGH;
smpreq->PhysicalPort = 0xFF;
*((u64 *)&smpreq->SASAddress) = cpu_to_le64(sas_address);
smpreq->RequestDataLength = sizeof(struct rep_manu_request);
psge = (char *)
(((int *) mf) + (offsetof(SmpPassthroughRequest_t, SGL) / 4));
flagsLength = MPI_SGE_FLAGS_SIMPLE_ELEMENT |
MPI_SGE_FLAGS_SYSTEM_ADDRESS |
MPI_SGE_FLAGS_HOST_TO_IOC |
MPI_SGE_FLAGS_END_OF_BUFFER;
flagsLength = flagsLength << MPI_SGE_FLAGS_SHIFT;
flagsLength |= sizeof(struct rep_manu_request);
ioc->add_sge(psge, flagsLength, data_out_dma);
psge += ioc->SGE_size;
flagsLength = MPI_SGE_FLAGS_SIMPLE_ELEMENT |
MPI_SGE_FLAGS_SYSTEM_ADDRESS |
MPI_SGE_FLAGS_IOC_TO_HOST |
MPI_SGE_FLAGS_END_OF_BUFFER;
flagsLength = flagsLength << MPI_SGE_FLAGS_SHIFT;
flagsLength |= sizeof(struct rep_manu_reply);
ioc->add_sge(psge, flagsLength, data_out_dma +
sizeof(struct rep_manu_request));
INITIALIZE_MGMT_STATUS(ioc->sas_mgmt.status)
mpt_put_msg_frame(mptsasMgmtCtx, ioc, mf);
timeleft = wait_for_completion_timeout(&ioc->sas_mgmt.done, 10 * HZ);
if (!(ioc->sas_mgmt.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
ret = -ETIME;
mpt_free_msg_frame(ioc, mf);
mf = NULL;
if (ioc->sas_mgmt.status & MPT_MGMT_STATUS_DID_IOCRESET)
goto out_free;
if (!timeleft)
mpt_Soft_Hard_ResetHandler(ioc, CAN_SLEEP);
goto out_free;
}
mf = NULL;
if (ioc->sas_mgmt.status & MPT_MGMT_STATUS_RF_VALID) {
u8 *tmp;
smprep = (SmpPassthroughReply_t *)ioc->sas_mgmt.reply;
if (le16_to_cpu(smprep->ResponseDataLength) !=
sizeof(struct rep_manu_reply))
goto out_free;
manufacture_reply = data_out + sizeof(struct rep_manu_request);
strncpy(edev->vendor_id, manufacture_reply->vendor_id,
SAS_EXPANDER_VENDOR_ID_LEN);
strncpy(edev->product_id, manufacture_reply->product_id,
SAS_EXPANDER_PRODUCT_ID_LEN);
strncpy(edev->product_rev, manufacture_reply->product_rev,
SAS_EXPANDER_PRODUCT_REV_LEN);
edev->level = manufacture_reply->sas_format;
if (manufacture_reply->sas_format) {
strncpy(edev->component_vendor_id,
manufacture_reply->component_vendor_id,
SAS_EXPANDER_COMPONENT_VENDOR_ID_LEN);
tmp = (u8 *)&manufacture_reply->component_id;
edev->component_id = tmp[0] << 8 | tmp[1];
edev->component_revision_id =
manufacture_reply->component_revision_id;
}
} else {
printk(MYIOC_s_ERR_FMT
"%s: smp passthru reply failed to be returned\n",
ioc->name, __func__);
ret = -ENXIO;
}
out_free:
if (data_out_dma)
pci_free_consistent(ioc->pcidev, sz, data_out, data_out_dma);
put_mf:
if (mf)
mpt_free_msg_frame(ioc, mf);
out_unlock:
CLEAR_MGMT_STATUS(ioc->sas_mgmt.status)
mutex_unlock(&ioc->sas_mgmt.mutex);
out:
return ret;
}
static void
mptsas_parse_device_info(struct sas_identify *identify,
struct mptsas_devinfo *device_info)
{
u16 protocols;
identify->sas_address = device_info->sas_address;
identify->phy_identifier = device_info->phy_id;
/*
* Fill in Phy Initiator Port Protocol.
* Bits 6:3, more than one bit can be set, fall through cases.
*/
protocols = device_info->device_info & 0x78;
identify->initiator_port_protocols = 0;
if (protocols & MPI_SAS_DEVICE_INFO_SSP_INITIATOR)
identify->initiator_port_protocols |= SAS_PROTOCOL_SSP;
if (protocols & MPI_SAS_DEVICE_INFO_STP_INITIATOR)
identify->initiator_port_protocols |= SAS_PROTOCOL_STP;
if (protocols & MPI_SAS_DEVICE_INFO_SMP_INITIATOR)
identify->initiator_port_protocols |= SAS_PROTOCOL_SMP;
if (protocols & MPI_SAS_DEVICE_INFO_SATA_HOST)
identify->initiator_port_protocols |= SAS_PROTOCOL_SATA;
/*
* Fill in Phy Target Port Protocol.
* Bits 10:7, more than one bit can be set, fall through cases.
*/
protocols = device_info->device_info & 0x780;
identify->target_port_protocols = 0;
if (protocols & MPI_SAS_DEVICE_INFO_SSP_TARGET)
identify->target_port_protocols |= SAS_PROTOCOL_SSP;
if (protocols & MPI_SAS_DEVICE_INFO_STP_TARGET)
identify->target_port_protocols |= SAS_PROTOCOL_STP;
if (protocols & MPI_SAS_DEVICE_INFO_SMP_TARGET)
identify->target_port_protocols |= SAS_PROTOCOL_SMP;
if (protocols & MPI_SAS_DEVICE_INFO_SATA_DEVICE)
identify->target_port_protocols |= SAS_PROTOCOL_SATA;
/*
* Fill in Attached device type.
*/
switch (device_info->device_info &
MPI_SAS_DEVICE_INFO_MASK_DEVICE_TYPE) {
case MPI_SAS_DEVICE_INFO_NO_DEVICE:
identify->device_type = SAS_PHY_UNUSED;
break;
case MPI_SAS_DEVICE_INFO_END_DEVICE:
identify->device_type = SAS_END_DEVICE;
break;
case MPI_SAS_DEVICE_INFO_EDGE_EXPANDER:
identify->device_type = SAS_EDGE_EXPANDER_DEVICE;
break;
case MPI_SAS_DEVICE_INFO_FANOUT_EXPANDER:
identify->device_type = SAS_FANOUT_EXPANDER_DEVICE;
break;
}
}
static int mptsas_probe_one_phy(struct device *dev,
struct mptsas_phyinfo *phy_info, int index, int local)
{
MPT_ADAPTER *ioc;
struct sas_phy *phy;
struct sas_port *port;
int error = 0;
VirtTarget *vtarget;
if (!dev) {
error = -ENODEV;
goto out;
}
if (!phy_info->phy) {
phy = sas_phy_alloc(dev, index);
if (!phy) {
error = -ENOMEM;
goto out;
}
} else
phy = phy_info->phy;
mptsas_parse_device_info(&phy->identify, &phy_info->identify);
/*
* Set Negotiated link rate.
*/
switch (phy_info->negotiated_link_rate) {
case MPI_SAS_IOUNIT0_RATE_PHY_DISABLED:
phy->negotiated_linkrate = SAS_PHY_DISABLED;
break;
case MPI_SAS_IOUNIT0_RATE_FAILED_SPEED_NEGOTIATION:
phy->negotiated_linkrate = SAS_LINK_RATE_FAILED;
break;
case MPI_SAS_IOUNIT0_RATE_1_5:
phy->negotiated_linkrate = SAS_LINK_RATE_1_5_GBPS;
break;
case MPI_SAS_IOUNIT0_RATE_3_0:
phy->negotiated_linkrate = SAS_LINK_RATE_3_0_GBPS;
break;
case MPI_SAS_IOUNIT0_RATE_6_0:
phy->negotiated_linkrate = SAS_LINK_RATE_6_0_GBPS;
break;
case MPI_SAS_IOUNIT0_RATE_SATA_OOB_COMPLETE:
case MPI_SAS_IOUNIT0_RATE_UNKNOWN:
default:
phy->negotiated_linkrate = SAS_LINK_RATE_UNKNOWN;
break;
}
/*
* Set Max hardware link rate.
*/
switch (phy_info->hw_link_rate & MPI_SAS_PHY0_PRATE_MAX_RATE_MASK) {
case MPI_SAS_PHY0_HWRATE_MAX_RATE_1_5:
phy->maximum_linkrate_hw = SAS_LINK_RATE_1_5_GBPS;
break;
case MPI_SAS_PHY0_PRATE_MAX_RATE_3_0:
phy->maximum_linkrate_hw = SAS_LINK_RATE_3_0_GBPS;
break;
default:
break;
}
/*
* Set Max programmed link rate.
*/
switch (phy_info->programmed_link_rate &
MPI_SAS_PHY0_PRATE_MAX_RATE_MASK) {
case MPI_SAS_PHY0_PRATE_MAX_RATE_1_5:
phy->maximum_linkrate = SAS_LINK_RATE_1_5_GBPS;
break;
case MPI_SAS_PHY0_PRATE_MAX_RATE_3_0:
phy->maximum_linkrate = SAS_LINK_RATE_3_0_GBPS;
break;
default:
break;
}
/*
* Set Min hardware link rate.
*/
switch (phy_info->hw_link_rate & MPI_SAS_PHY0_HWRATE_MIN_RATE_MASK) {
case MPI_SAS_PHY0_HWRATE_MIN_RATE_1_5:
phy->minimum_linkrate_hw = SAS_LINK_RATE_1_5_GBPS;
break;
case MPI_SAS_PHY0_PRATE_MIN_RATE_3_0:
phy->minimum_linkrate_hw = SAS_LINK_RATE_3_0_GBPS;
break;
default:
break;
}
/*
* Set Min programmed link rate.
*/
switch (phy_info->programmed_link_rate &
MPI_SAS_PHY0_PRATE_MIN_RATE_MASK) {
case MPI_SAS_PHY0_PRATE_MIN_RATE_1_5:
phy->minimum_linkrate = SAS_LINK_RATE_1_5_GBPS;
break;
case MPI_SAS_PHY0_PRATE_MIN_RATE_3_0:
phy->minimum_linkrate = SAS_LINK_RATE_3_0_GBPS;
break;
default:
break;
}
if (!phy_info->phy) {
error = sas_phy_add(phy);
if (error) {
sas_phy_free(phy);
goto out;
}
phy_info->phy = phy;
}
if (!phy_info->attached.handle ||
!phy_info->port_details)
goto out;
port = mptsas_get_port(phy_info);
ioc = phy_to_ioc(phy_info->phy);
if (phy_info->sas_port_add_phy) {
if (!port) {
port = sas_port_alloc_num(dev);
if (!port) {
error = -ENOMEM;
goto out;
}
error = sas_port_add(port);
if (error) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: exit at line=%d\n", ioc->name,
__func__, __LINE__));
goto out;
}
mptsas_set_port(ioc, phy_info, port);
devtprintk(ioc, dev_printk(KERN_DEBUG, &port->dev,
MYIOC_s_FMT "add port %d, sas_addr (0x%llx)\n",
ioc->name, port->port_identifier,
(unsigned long long)phy_info->
attached.sas_address));
}
dsaswideprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"sas_port_add_phy: phy_id=%d\n",
ioc->name, phy_info->phy_id));
sas_port_add_phy(port, phy_info->phy);
phy_info->sas_port_add_phy = 0;
devtprintk(ioc, dev_printk(KERN_DEBUG, &phy_info->phy->dev,
MYIOC_s_FMT "add phy %d, phy-obj (0x%p)\n", ioc->name,
phy_info->phy_id, phy_info->phy));
}
if (!mptsas_get_rphy(phy_info) && port && !port->rphy) {
struct sas_rphy *rphy;
struct device *parent;
struct sas_identify identify;
parent = dev->parent->parent;
/*
* Let the hotplug_work thread handle processing
* the adding/removing of devices that occur
* after start of day.
*/
if (mptsas_is_end_device(&phy_info->attached) &&
phy_info->attached.handle_parent) {
goto out;
}
mptsas_parse_device_info(&identify, &phy_info->attached);
if (scsi_is_host_device(parent)) {
struct mptsas_portinfo *port_info;
int i;
port_info = ioc->hba_port_info;
for (i = 0; i < port_info->num_phys; i++)
if (port_info->phy_info[i].identify.sas_address ==
identify.sas_address) {
sas_port_mark_backlink(port);
goto out;
}
} else if (scsi_is_sas_rphy(parent)) {
struct sas_rphy *parent_rphy = dev_to_rphy(parent);
if (identify.sas_address ==
parent_rphy->identify.sas_address) {
sas_port_mark_backlink(port);
goto out;
}
}
switch (identify.device_type) {
case SAS_END_DEVICE:
rphy = sas_end_device_alloc(port);
break;
case SAS_EDGE_EXPANDER_DEVICE:
case SAS_FANOUT_EXPANDER_DEVICE:
rphy = sas_expander_alloc(port, identify.device_type);
break;
default:
rphy = NULL;
break;
}
if (!rphy) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: exit at line=%d\n", ioc->name,
__func__, __LINE__));
goto out;
}
rphy->identify = identify;
error = sas_rphy_add(rphy);
if (error) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: exit at line=%d\n", ioc->name,
__func__, __LINE__));
sas_rphy_free(rphy);
goto out;
}
mptsas_set_rphy(ioc, phy_info, rphy);
if (identify.device_type == SAS_EDGE_EXPANDER_DEVICE ||
identify.device_type == SAS_FANOUT_EXPANDER_DEVICE)
mptsas_exp_repmanufacture_info(ioc,
identify.sas_address,
rphy_to_expander_device(rphy));
}
/* If the device exists,verify it wasn't previously flagged
as a missing device. If so, clear it */
vtarget = mptsas_find_vtarget(ioc,
phy_info->attached.channel,
phy_info->attached.id);
if (vtarget && vtarget->inDMD) {
printk(KERN_INFO "Device returned, unsetting inDMD\n");
vtarget->inDMD = 0;
}
out:
return error;
}
static int
mptsas_probe_hba_phys(MPT_ADAPTER *ioc)
{
struct mptsas_portinfo *port_info, *hba;
int error = -ENOMEM, i;
hba = kzalloc(sizeof(struct mptsas_portinfo), GFP_KERNEL);
if (! hba)
goto out;
error = mptsas_sas_io_unit_pg0(ioc, hba);
if (error)
goto out_free_port_info;
mptsas_sas_io_unit_pg1(ioc);
mutex_lock(&ioc->sas_topology_mutex);
port_info = ioc->hba_port_info;
if (!port_info) {
ioc->hba_port_info = port_info = hba;
ioc->hba_port_num_phy = port_info->num_phys;
list_add_tail(&port_info->list, &ioc->sas_topology);
} else {
for (i = 0; i < hba->num_phys; i++) {
port_info->phy_info[i].negotiated_link_rate =
hba->phy_info[i].negotiated_link_rate;
port_info->phy_info[i].handle =
hba->phy_info[i].handle;
port_info->phy_info[i].port_id =
hba->phy_info[i].port_id;
}
kfree(hba->phy_info);
kfree(hba);
hba = NULL;
}
mutex_unlock(&ioc->sas_topology_mutex);
#if defined(CPQ_CIM)
ioc->num_ports = port_info->num_phys;
#endif
for (i = 0; i < port_info->num_phys; i++) {
mptsas_sas_phy_pg0(ioc, &port_info->phy_info[i],
(MPI_SAS_PHY_PGAD_FORM_PHY_NUMBER <<
MPI_SAS_PHY_PGAD_FORM_SHIFT), i);
port_info->phy_info[i].identify.handle =
port_info->phy_info[i].handle;
mptsas_sas_device_pg0(ioc, &port_info->phy_info[i].identify,
(MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
port_info->phy_info[i].identify.handle);
if (!ioc->hba_port_sas_addr)
ioc->hba_port_sas_addr =
port_info->phy_info[i].identify.sas_address;
port_info->phy_info[i].identify.phy_id =
port_info->phy_info[i].phy_id = i;
if (port_info->phy_info[i].attached.handle)
mptsas_sas_device_pg0(ioc,
&port_info->phy_info[i].attached,
(MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
port_info->phy_info[i].attached.handle);
}
mptsas_setup_wide_ports(ioc, port_info);
for (i = 0; i < port_info->num_phys; i++, ioc->sas_index++)
mptsas_probe_one_phy(&ioc->sh->shost_gendev,
&port_info->phy_info[i], ioc->sas_index, 1);
return 0;
out_free_port_info:
kfree(hba);
out:
return error;
}
static void
mptsas_expander_refresh(MPT_ADAPTER *ioc, struct mptsas_portinfo *port_info)
{
struct mptsas_portinfo *parent;
struct device *parent_dev;
struct sas_rphy *rphy;
int i;
u64 sas_address; /* expander sas address */
u32 handle;
handle = port_info->phy_info[0].handle;
sas_address = port_info->phy_info[0].identify.sas_address;
for (i = 0; i < port_info->num_phys; i++) {
mptsas_sas_expander_pg1(ioc, &port_info->phy_info[i],
(MPI_SAS_EXPAND_PGAD_FORM_HANDLE_PHY_NUM <<
MPI_SAS_EXPAND_PGAD_FORM_SHIFT), (i << 16) + handle);
mptsas_sas_device_pg0(ioc,
&port_info->phy_info[i].identify,
(MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
port_info->phy_info[i].identify.handle);
port_info->phy_info[i].identify.phy_id =
port_info->phy_info[i].phy_id;
if (port_info->phy_info[i].attached.handle) {
mptsas_sas_device_pg0(ioc,
&port_info->phy_info[i].attached,
(MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
port_info->phy_info[i].attached.handle);
port_info->phy_info[i].attached.phy_id =
port_info->phy_info[i].phy_id;
}
}
mutex_lock(&ioc->sas_topology_mutex);
parent = mptsas_find_portinfo_by_handle(ioc,
port_info->phy_info[0].identify.handle_parent);
if (!parent) {
mutex_unlock(&ioc->sas_topology_mutex);
return;
}
for (i = 0, parent_dev = NULL; i < parent->num_phys && !parent_dev;
i++) {
if (parent->phy_info[i].attached.sas_address == sas_address) {
rphy = mptsas_get_rphy(&parent->phy_info[i]);
parent_dev = &rphy->dev;
}
}
mutex_unlock(&ioc->sas_topology_mutex);
mptsas_setup_wide_ports(ioc, port_info);
for (i = 0; i < port_info->num_phys; i++, ioc->sas_index++)
mptsas_probe_one_phy(parent_dev, &port_info->phy_info[i],
ioc->sas_index, 0);
}
static void
mptsas_expander_event_add(MPT_ADAPTER *ioc,
MpiEventDataSasExpanderStatusChange_t *expander_data)
{
struct mptsas_portinfo *port_info;
int i;
__le64 sas_address;
port_info = kzalloc(sizeof(struct mptsas_portinfo), GFP_KERNEL);
if (!port_info)
BUG();
port_info->num_phys = (expander_data->NumPhys) ?
expander_data->NumPhys : 1;
port_info->phy_info = kcalloc(port_info->num_phys,
sizeof(struct mptsas_phyinfo), GFP_KERNEL);
if (!port_info->phy_info)
BUG();
memcpy(&sas_address, &expander_data->SASAddress, sizeof(__le64));
for (i = 0; i < port_info->num_phys; i++) {
port_info->phy_info[i].portinfo = port_info;
port_info->phy_info[i].handle =
le16_to_cpu(expander_data->DevHandle);
port_info->phy_info[i].identify.sas_address =
le64_to_cpu(sas_address);
port_info->phy_info[i].identify.handle_parent =
le16_to_cpu(expander_data->ParentDevHandle);
}
mutex_lock(&ioc->sas_topology_mutex);
list_add_tail(&port_info->list, &ioc->sas_topology);
mutex_unlock(&ioc->sas_topology_mutex);
printk(MYIOC_s_INFO_FMT "add expander: num_phys %d, "
"sas_addr (0x%llx)\n", ioc->name, port_info->num_phys,
(unsigned long long)sas_address);
mptsas_expander_refresh(ioc, port_info);
}
/**
* mptsas_delete_expander_siblings - remove siblings attached to expander
* @ioc: Pointer to MPT_ADAPTER structure
* @parent: the parent port_info object
* @expander: the expander port_info object
**/
static void
mptsas_delete_expander_siblings(MPT_ADAPTER *ioc, struct mptsas_portinfo
*parent, struct mptsas_portinfo *expander)
{
struct mptsas_phyinfo *phy_info;
struct mptsas_portinfo *port_info;
struct sas_rphy *rphy;
int i;
phy_info = expander->phy_info;
for (i = 0; i < expander->num_phys; i++, phy_info++) {
rphy = mptsas_get_rphy(phy_info);
if (!rphy)
continue;
if (rphy->identify.device_type == SAS_END_DEVICE)
mptsas_del_end_device(ioc, phy_info);
}
phy_info = expander->phy_info;
for (i = 0; i < expander->num_phys; i++, phy_info++) {
rphy = mptsas_get_rphy(phy_info);
if (!rphy)
continue;
if (rphy->identify.device_type ==
MPI_SAS_DEVICE_INFO_EDGE_EXPANDER ||
rphy->identify.device_type ==
MPI_SAS_DEVICE_INFO_FANOUT_EXPANDER) {
port_info = mptsas_find_portinfo_by_sas_address(ioc,
rphy->identify.sas_address);
if (!port_info)
continue;
if (port_info == parent) /* backlink rphy */
continue;
/*
Delete this expander even if the expdevpage is exists
because the parent expander is already deleted
*/
mptsas_expander_delete(ioc, port_info, 1);
}
}
}
/**
* mptsas_expander_delete - remove this expander
* @ioc: Pointer to MPT_ADAPTER structure
* @port_info: expander port_info struct
* @force: Flag to forcefully delete the expander
*
**/
static void mptsas_expander_delete(MPT_ADAPTER *ioc,
struct mptsas_portinfo *port_info, u8 force)
{
struct mptsas_portinfo *parent;
int i;
u64 expander_sas_address;
struct mptsas_phyinfo *phy_info;
struct mptsas_portinfo buffer;
struct mptsas_portinfo_details *port_details;
struct sas_port *port;
if (!port_info)
return;
/* see if expander is still there before deleting */
mptsas_sas_expander_pg0(ioc, &buffer,
(MPI_SAS_EXPAND_PGAD_FORM_HANDLE <<
MPI_SAS_EXPAND_PGAD_FORM_SHIFT),
port_info->phy_info[0].identify.handle);
if (buffer.num_phys) {
kfree(buffer.phy_info);
if (!force)
return;
}
/*
* Obtain the port_info instance to the parent port
*/
port_details = NULL;
expander_sas_address =
port_info->phy_info[0].identify.sas_address;
parent = mptsas_find_portinfo_by_handle(ioc,
port_info->phy_info[0].identify.handle_parent);
mptsas_delete_expander_siblings(ioc, parent, port_info);
if (!parent)
goto out;
/*
* Delete rphys in the parent that point
* to this expander.
*/
phy_info = parent->phy_info;
port = NULL;
for (i = 0; i < parent->num_phys; i++, phy_info++) {
if (!phy_info->phy)
continue;
if (phy_info->attached.sas_address !=
expander_sas_address)
continue;
if (!port) {
port = mptsas_get_port(phy_info);
port_details = phy_info->port_details;
}
dev_printk(KERN_DEBUG, &phy_info->phy->dev,
MYIOC_s_FMT "delete phy %d, phy-obj (0x%p)\n", ioc->name,
phy_info->phy_id, phy_info->phy);
sas_port_delete_phy(port, phy_info->phy);
}
if (port) {
dev_printk(KERN_DEBUG, &port->dev,
MYIOC_s_FMT "delete port %d, sas_addr (0x%llx)\n",
ioc->name, port->port_identifier,
(unsigned long long)expander_sas_address);
sas_port_delete(port);
mptsas_port_delete(ioc, port_details);
}
out:
printk(MYIOC_s_INFO_FMT "delete expander: num_phys %d, "
"sas_addr (0x%llx)\n", ioc->name, port_info->num_phys,
(unsigned long long)expander_sas_address);
/*
* free link
*/
list_del(&port_info->list);
kfree(port_info->phy_info);
kfree(port_info);
}
/**
* mptsas_send_expander_event - expanders events
* @ioc: Pointer to MPT_ADAPTER structure
* @expander_data: event data
*
*
* This function handles adding, removing, and refreshing
* device handles within the expander objects.
*/
static void
mptsas_send_expander_event(struct fw_event_work *fw_event)
{
MPT_ADAPTER *ioc;
MpiEventDataSasExpanderStatusChange_t *expander_data;
struct mptsas_portinfo *port_info;
__le64 sas_address;
int i;
ioc = fw_event->ioc;
expander_data = (MpiEventDataSasExpanderStatusChange_t *)
fw_event->event_data;
memcpy(&sas_address, &expander_data->SASAddress, sizeof(__le64));
sas_address = le64_to_cpu(sas_address);
port_info = mptsas_find_portinfo_by_sas_address(ioc, sas_address);
if (expander_data->ReasonCode == MPI_EVENT_SAS_EXP_RC_ADDED) {
if (port_info) {
for (i = 0; i < port_info->num_phys; i++) {
port_info->phy_info[i].portinfo = port_info;
port_info->phy_info[i].handle =
le16_to_cpu(expander_data->DevHandle);
port_info->phy_info[i].identify.sas_address =
le64_to_cpu(sas_address);
port_info->phy_info[i].identify.handle_parent =
le16_to_cpu(expander_data->ParentDevHandle);
}
mptsas_expander_refresh(ioc, port_info);
} else if (!port_info && expander_data->NumPhys)
mptsas_expander_event_add(ioc, expander_data);
} else if (expander_data->ReasonCode ==
MPI_EVENT_SAS_EXP_RC_NOT_RESPONDING)
mptsas_expander_delete(ioc, port_info, 0);
mptsas_free_fw_event(ioc, fw_event);
}
/**
* mptsas_expander_add -
* @ioc: Pointer to MPT_ADAPTER structure
* @handle:
*
*/
struct mptsas_portinfo *
mptsas_expander_add(MPT_ADAPTER *ioc, u16 handle)
{
struct mptsas_portinfo buffer, *port_info;
int i;
if ((mptsas_sas_expander_pg0(ioc, &buffer,
(MPI_SAS_EXPAND_PGAD_FORM_HANDLE <<
MPI_SAS_EXPAND_PGAD_FORM_SHIFT), handle)))
return NULL;
port_info = kzalloc(sizeof(struct mptsas_portinfo), GFP_ATOMIC);
if (!port_info) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: exit at line=%d\n", ioc->name,
__func__, __LINE__));
return NULL;
}
port_info->num_phys = buffer.num_phys;
port_info->phy_info = buffer.phy_info;
for (i = 0; i < port_info->num_phys; i++)
port_info->phy_info[i].portinfo = port_info;
mutex_lock(&ioc->sas_topology_mutex);
list_add_tail(&port_info->list, &ioc->sas_topology);
mutex_unlock(&ioc->sas_topology_mutex);
printk(MYIOC_s_INFO_FMT "add expander: num_phys %d, "
"sas_addr (0x%llx)\n", ioc->name, port_info->num_phys,
(unsigned long long)buffer.phy_info[0].identify.sas_address);
mptsas_expander_refresh(ioc, port_info);
return port_info;
}
static void
mptsas_send_link_status_event(struct fw_event_work *fw_event)
{
MPT_ADAPTER *ioc;
MpiEventDataSasPhyLinkStatus_t *link_data;
struct mptsas_portinfo *port_info;
struct mptsas_phyinfo *phy_info = NULL;
__le64 sas_address;
u8 phy_num;
u8 link_rate;
ioc = fw_event->ioc;
link_data = (MpiEventDataSasPhyLinkStatus_t *)fw_event->event_data;
memcpy(&sas_address, &link_data->SASAddress, sizeof(__le64));
sas_address = le64_to_cpu(sas_address);
link_rate = link_data->LinkRates >> 4;
phy_num = link_data->PhyNum;
port_info = mptsas_find_portinfo_by_sas_address(ioc, sas_address);
if (port_info) {
phy_info = &port_info->phy_info[phy_num];
if (phy_info)
phy_info->negotiated_link_rate = link_rate;
}
if (link_rate == MPI_SAS_IOUNIT0_RATE_1_5 ||
link_rate == MPI_SAS_IOUNIT0_RATE_3_0 ||
link_rate == MPI_SAS_IOUNIT0_RATE_6_0) {
if (!port_info) {
if (ioc->old_sas_discovery_protocal) {
port_info = mptsas_expander_add(ioc,
le16_to_cpu(link_data->DevHandle));
if (port_info)
goto out;
}
goto out;
}
if (port_info == ioc->hba_port_info)
mptsas_probe_hba_phys(ioc);
else
mptsas_expander_refresh(ioc, port_info);
} else if (phy_info && phy_info->phy) {
if (link_rate == MPI_SAS_IOUNIT0_RATE_PHY_DISABLED)
phy_info->phy->negotiated_linkrate =
SAS_PHY_DISABLED;
else if (link_rate ==
MPI_SAS_IOUNIT0_RATE_FAILED_SPEED_NEGOTIATION)
phy_info->phy->negotiated_linkrate =
SAS_LINK_RATE_FAILED;
else {
phy_info->phy->negotiated_linkrate =
SAS_LINK_RATE_UNKNOWN;
if (ioc->device_missing_delay &&
mptsas_is_end_device(&phy_info->attached)) {
struct scsi_device *sdev;
VirtDevice *vdevice;
u8 channel, id;
id = phy_info->attached.id;
channel = phy_info->attached.channel;
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Link down for fw_id %d:fw_channel %d\n",
ioc->name, phy_info->attached.id,
phy_info->attached.channel));
shost_for_each_device(sdev, ioc->sh) {
vdevice = sdev->hostdata;
if ((vdevice == NULL) ||
(vdevice->vtarget == NULL))
continue;
if ((vdevice->vtarget->tflags &
MPT_TARGET_FLAGS_RAID_COMPONENT ||
vdevice->vtarget->raidVolume))
continue;
if (vdevice->vtarget->id == id &&
vdevice->vtarget->channel ==
channel)
devtprintk(ioc,
printk(MYIOC_s_DEBUG_FMT
"SDEV OUTSTANDING CMDS"
"%d\n", ioc->name,
sdev->device_busy));
}
}
}
}
out:
mptsas_free_fw_event(ioc, fw_event);
}
static void
mptsas_not_responding_devices(MPT_ADAPTER *ioc)
{
struct mptsas_portinfo buffer, *port_info;
struct mptsas_device_info *sas_info;
struct mptsas_devinfo sas_device;
u32 handle;
VirtTarget *vtarget = NULL;
struct mptsas_phyinfo *phy_info;
u8 found_expander;
int retval, retry_count;
unsigned long flags;
mpt_findImVolumes(ioc);
spin_lock_irqsave(&ioc->taskmgmt_lock, flags);
if (ioc->ioc_reset_in_progress) {
dfailprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: exiting due to a parallel reset \n", ioc->name,
__func__));
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
return;
}
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
/* devices, logical volumes */
mutex_lock(&ioc->sas_device_info_mutex);
redo_device_scan:
list_for_each_entry(sas_info, &ioc->sas_device_info_list, list) {
if (sas_info->is_cached)
continue;
if (!sas_info->is_logical_volume) {
sas_device.handle = 0;
retry_count = 0;
retry_page:
retval = mptsas_sas_device_pg0(ioc, &sas_device,
(MPI_SAS_DEVICE_PGAD_FORM_BUS_TARGET_ID
<< MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
(sas_info->fw.channel << 8) +
sas_info->fw.id);
if (sas_device.handle)
continue;
if (retval == -EBUSY) {
spin_lock_irqsave(&ioc->taskmgmt_lock, flags);
if (ioc->ioc_reset_in_progress) {
dfailprintk(ioc,
printk(MYIOC_s_DEBUG_FMT
"%s: exiting due to reset\n",
ioc->name, __func__));
spin_unlock_irqrestore
(&ioc->taskmgmt_lock, flags);
mutex_unlock(&ioc->
sas_device_info_mutex);
return;
}
spin_unlock_irqrestore(&ioc->taskmgmt_lock,
flags);
}
if (retval && (retval != -ENODEV)) {
if (retry_count < 10) {
retry_count++;
goto retry_page;
} else {
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: Config page retry exceeded retry "
"count deleting device 0x%llx\n",
ioc->name, __func__,
sas_info->sas_address));
}
}
/* delete device */
vtarget = mptsas_find_vtarget(ioc,
sas_info->fw.channel, sas_info->fw.id);
if (vtarget)
vtarget->deleted = 1;
phy_info = mptsas_find_phyinfo_by_sas_address(ioc,
sas_info->sas_address);
if (phy_info) {
mptsas_del_end_device(ioc, phy_info);
goto redo_device_scan;
}
} else
mptsas_volume_delete(ioc, sas_info->fw.id);
}
mutex_unlock(&ioc->sas_device_info_mutex);
/* expanders */
mutex_lock(&ioc->sas_topology_mutex);
redo_expander_scan:
list_for_each_entry(port_info, &ioc->sas_topology, list) {
if (port_info->phy_info &&
(!(port_info->phy_info[0].identify.device_info &
MPI_SAS_DEVICE_INFO_SMP_TARGET)))
continue;
found_expander = 0;
handle = 0xFFFF;
while (!mptsas_sas_expander_pg0(ioc, &buffer,
(MPI_SAS_EXPAND_PGAD_FORM_GET_NEXT_HANDLE <<
MPI_SAS_EXPAND_PGAD_FORM_SHIFT), handle) &&
!found_expander) {
handle = buffer.phy_info[0].handle;
if (buffer.phy_info[0].identify.sas_address ==
port_info->phy_info[0].identify.sas_address) {
found_expander = 1;
}
kfree(buffer.phy_info);
}
if (!found_expander) {
mptsas_expander_delete(ioc, port_info, 0);
goto redo_expander_scan;
}
}
mutex_unlock(&ioc->sas_topology_mutex);
}
/**
* mptsas_probe_expanders - adding expanders
* @ioc: Pointer to MPT_ADAPTER structure
*
**/
static void
mptsas_probe_expanders(MPT_ADAPTER *ioc)
{
struct mptsas_portinfo buffer, *port_info;
u32 handle;
int i;
handle = 0xFFFF;
while (!mptsas_sas_expander_pg0(ioc, &buffer,
(MPI_SAS_EXPAND_PGAD_FORM_GET_NEXT_HANDLE <<
MPI_SAS_EXPAND_PGAD_FORM_SHIFT), handle)) {
handle = buffer.phy_info[0].handle;
port_info = mptsas_find_portinfo_by_sas_address(ioc,
buffer.phy_info[0].identify.sas_address);
if (port_info) {
/* refreshing handles */
for (i = 0; i < buffer.num_phys; i++) {
port_info->phy_info[i].handle = handle;
port_info->phy_info[i].identify.handle_parent =
buffer.phy_info[0].identify.handle_parent;
}
mptsas_expander_refresh(ioc, port_info);
kfree(buffer.phy_info);
continue;
}
port_info = kzalloc(sizeof(struct mptsas_portinfo), GFP_KERNEL);
if (!port_info) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: exit at line=%d\n", ioc->name,
__func__, __LINE__));
return;
}
port_info->num_phys = buffer.num_phys;
port_info->phy_info = buffer.phy_info;
for (i = 0; i < port_info->num_phys; i++)
port_info->phy_info[i].portinfo = port_info;
mutex_lock(&ioc->sas_topology_mutex);
list_add_tail(&port_info->list, &ioc->sas_topology);
mutex_unlock(&ioc->sas_topology_mutex);
printk(MYIOC_s_INFO_FMT "add expander: num_phys %d, "
"sas_addr (0x%llx)\n", ioc->name, port_info->num_phys,
(unsigned long long)buffer.phy_info[0].identify.sas_address);
mptsas_expander_refresh(ioc, port_info);
}
}
static void
mptsas_probe_devices(MPT_ADAPTER *ioc)
{
u16 handle;
struct mptsas_devinfo sas_device;
struct mptsas_phyinfo *phy_info;
handle = 0xFFFF;
while (!(mptsas_sas_device_pg0(ioc, &sas_device,
MPI_SAS_DEVICE_PGAD_FORM_GET_NEXT_HANDLE, handle))) {
handle = sas_device.handle;
if ((sas_device.device_info &
(MPI_SAS_DEVICE_INFO_SSP_TARGET |
MPI_SAS_DEVICE_INFO_STP_TARGET |
MPI_SAS_DEVICE_INFO_SATA_DEVICE)) == 0)
continue;
/* If there is no FW B_T mapping for this device then continue
* */
if (!(sas_device.flags & MPI_SAS_DEVICE0_FLAGS_DEVICE_PRESENT)
|| !(sas_device.flags &
MPI_SAS_DEVICE0_FLAGS_DEVICE_MAPPED))
continue;
phy_info = mptsas_refreshing_device_handles(ioc, &sas_device);
if (!phy_info)
continue;
if (mptsas_get_rphy(phy_info))
continue;
mptsas_add_end_device(ioc, phy_info);
}
}
/**
* mptsas_scan_sas_topology -
* @ioc: Pointer to MPT_ADAPTER structure
* @sas_address:
*
**/
static void
mptsas_scan_sas_topology(MPT_ADAPTER *ioc)
{
struct scsi_device *sdev;
int i;
mptsas_probe_hba_phys(ioc);
mptsas_probe_expanders(ioc);
mptsas_probe_devices(ioc);
/*
Reporting RAID volumes.
*/
if (!ioc->ir_firmware || !ioc->raid_data.pIocPg2 ||
!ioc->raid_data.pIocPg2->NumActiveVolumes)
return;
for (i = 0; i < ioc->raid_data.pIocPg2->NumActiveVolumes; i++) {
sdev = scsi_device_lookup(ioc->sh, MPTSAS_RAID_CHANNEL,
ioc->raid_data.pIocPg2->RaidVolume[i].VolumeID, 0);
if (sdev) {
scsi_device_put(sdev);
continue;
}
printk(MYIOC_s_INFO_FMT "attaching raid volume, channel %d, "
"id %d\n", ioc->name, MPTSAS_RAID_CHANNEL,
ioc->raid_data.pIocPg2->RaidVolume[i].VolumeID);
scsi_add_device(ioc->sh, MPTSAS_RAID_CHANNEL,
ioc->raid_data.pIocPg2->RaidVolume[i].VolumeID, 0);
}
}
static void
mptsas_handle_queue_full_event(struct fw_event_work *fw_event)
{
MPT_ADAPTER *ioc;
EventDataQueueFull_t *qfull_data;
struct mptsas_device_info *sas_info;
struct scsi_device *sdev;
int depth;
int id = -1;
int channel = -1;
int fw_id, fw_channel;
u16 current_depth;
ioc = fw_event->ioc;
qfull_data = (EventDataQueueFull_t *)fw_event->event_data;
fw_id = qfull_data->TargetID;
fw_channel = qfull_data->Bus;
current_depth = le16_to_cpu(qfull_data->CurrentDepth);
/* if hidden raid component, look for the volume id */
mutex_lock(&ioc->sas_device_info_mutex);
if (mptscsih_is_phys_disk(ioc, fw_channel, fw_id)) {
list_for_each_entry(sas_info, &ioc->sas_device_info_list,
list) {
if (sas_info->is_cached ||
sas_info->is_logical_volume)
continue;
if (sas_info->is_hidden_raid_component &&
(sas_info->fw.channel == fw_channel &&
sas_info->fw.id == fw_id)) {
id = sas_info->volume_id;
channel = MPTSAS_RAID_CHANNEL;
goto out;
}
}
} else {
list_for_each_entry(sas_info, &ioc->sas_device_info_list,
list) {
if (sas_info->is_cached ||
sas_info->is_hidden_raid_component ||
sas_info->is_logical_volume)
continue;
if (sas_info->fw.channel == fw_channel &&
sas_info->fw.id == fw_id) {
id = sas_info->os.id;
channel = sas_info->os.channel;
goto out;
}
}
}
out:
mutex_unlock(&ioc->sas_device_info_mutex);
if (id != -1) {
shost_for_each_device(sdev, ioc->sh) {
if (sdev->id == id && sdev->channel == channel) {
if (current_depth > sdev->queue_depth) {
sdev_printk(KERN_INFO, sdev,
"strange observation, the queue "
"depth is (%d) meanwhile fw queue "
"depth (%d)\n", sdev->queue_depth,
current_depth);
continue;
}
depth = scsi_track_queue_full(sdev,
current_depth - 1);
if (depth > 0)
sdev_printk(KERN_INFO, sdev,
"Queue depth reduced to (%d)\n",
depth);
else if (depth < 0)
sdev_printk(KERN_INFO, sdev,
"Tagged Command Queueing is being "
"disabled\n");
else if (depth == 0)
sdev_printk(KERN_INFO, sdev,
"Queue depth not changed yet\n");
}
}
}
mptsas_free_fw_event(ioc, fw_event);
}
static struct mptsas_phyinfo *
mptsas_find_phyinfo_by_sas_address(MPT_ADAPTER *ioc, u64 sas_address)
{
struct mptsas_portinfo *port_info;
struct mptsas_phyinfo *phy_info = NULL;
int i;
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry(port_info, &ioc->sas_topology, list) {
for (i = 0; i < port_info->num_phys; i++) {
if (!mptsas_is_end_device(
&port_info->phy_info[i].attached))
continue;
if (port_info->phy_info[i].attached.sas_address
!= sas_address)
continue;
phy_info = &port_info->phy_info[i];
break;
}
}
mutex_unlock(&ioc->sas_topology_mutex);
return phy_info;
}
/**
* mptsas_find_phyinfo_by_phys_disk_num -
* @ioc: Pointer to MPT_ADAPTER structure
* @phys_disk_num:
* @channel:
* @id:
*
**/
static struct mptsas_phyinfo *
mptsas_find_phyinfo_by_phys_disk_num(MPT_ADAPTER *ioc, u8 phys_disk_num,
u8 channel, u8 id)
{
struct mptsas_phyinfo *phy_info = NULL;
struct mptsas_portinfo *port_info;
RaidPhysDiskPage1_t *phys_disk = NULL;
int num_paths;
u64 sas_address = 0;
int i;
phy_info = NULL;
if (!ioc->raid_data.pIocPg3)
return NULL;
/* dual port support */
num_paths = mpt_raid_phys_disk_get_num_paths(ioc, phys_disk_num);
if (!num_paths)
goto out;
phys_disk = kzalloc(offsetof(RaidPhysDiskPage1_t, Path) +
(num_paths * sizeof(RAID_PHYS_DISK1_PATH)), GFP_KERNEL);
if (!phys_disk)
goto out;
mpt_raid_phys_disk_pg1(ioc, phys_disk_num, phys_disk);
for (i = 0; i < num_paths; i++) {
if ((phys_disk->Path[i].Flags & 1) != 0)
/* entry no longer valid */
continue;
if ((id == phys_disk->Path[i].PhysDiskID) &&
(channel == phys_disk->Path[i].PhysDiskBus)) {
memcpy(&sas_address, &phys_disk->Path[i].WWID,
sizeof(u64));
phy_info = mptsas_find_phyinfo_by_sas_address(ioc,
sas_address);
goto out;
}
}
out:
kfree(phys_disk);
if (phy_info)
return phy_info;
/*
* Extra code to handle RAID0 case, where the sas_address is not updated
* in phys_disk_page_1 when hotswapped
*/
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry(port_info, &ioc->sas_topology, list) {
for (i = 0; i < port_info->num_phys && !phy_info; i++) {
if (!mptsas_is_end_device(
&port_info->phy_info[i].attached))
continue;
if (port_info->phy_info[i].attached.phys_disk_num == ~0)
continue;
if ((port_info->phy_info[i].attached.phys_disk_num ==
phys_disk_num) &&
(port_info->phy_info[i].attached.id == id) &&
(port_info->phy_info[i].attached.channel ==
channel))
phy_info = &port_info->phy_info[i];
}
}
mutex_unlock(&ioc->sas_topology_mutex);
return phy_info;
}
static void
mptsas_reprobe_lun(struct scsi_device *sdev, void *data)
{
int rc;
sdev->no_uld_attach = data ? 1 : 0;
rc = scsi_device_reprobe(sdev);
}
static void
mptsas_reprobe_target(struct scsi_target *starget, int uld_attach)
{
starget_for_each_device(starget, uld_attach ? (void *)1 : NULL,
mptsas_reprobe_lun);
}
static void
mptsas_adding_inactive_raid_components(MPT_ADAPTER *ioc, u8 channel, u8 id)
{
CONFIGPARMS cfg;
ConfigPageHeader_t hdr;
dma_addr_t dma_handle;
pRaidVolumePage0_t buffer = NULL;
RaidPhysDiskPage0_t phys_disk;
int i;
struct mptsas_phyinfo *phy_info;
struct mptsas_devinfo sas_device;
memset(&cfg, 0 , sizeof(CONFIGPARMS));
memset(&hdr, 0 , sizeof(ConfigPageHeader_t));
hdr.PageType = MPI_CONFIG_PAGETYPE_RAID_VOLUME;
cfg.pageAddr = (channel << 8) + id;
cfg.cfghdr.hdr = &hdr;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.timeout = SAS_CONFIG_PAGE_TIMEOUT;
if (mpt_config(ioc, &cfg) != 0)
goto out;
if (!hdr.PageLength)
goto out;
buffer = pci_alloc_consistent(ioc->pcidev, hdr.PageLength * 4,
&dma_handle);
if (!buffer)
goto out;
cfg.physAddr = dma_handle;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
if (mpt_config(ioc, &cfg) != 0)
goto out;
if (!(buffer->VolumeStatus.Flags &
MPI_RAIDVOL0_STATUS_FLAG_VOLUME_INACTIVE))
goto out;
if (!buffer->NumPhysDisks)
goto out;
for (i = 0; i < buffer->NumPhysDisks; i++) {
if (mpt_raid_phys_disk_pg0(ioc,
buffer->PhysDisk[i].PhysDiskNum, &phys_disk) != 0)
continue;
if (mptsas_sas_device_pg0(ioc, &sas_device,
(MPI_SAS_DEVICE_PGAD_FORM_BUS_TARGET_ID <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
(phys_disk.PhysDiskBus << 8) +
phys_disk.PhysDiskID))
continue;
/* If there is no FW B_T mapping for this device then continue
* */
if (!(sas_device.flags & MPI_SAS_DEVICE0_FLAGS_DEVICE_PRESENT)
|| !(sas_device.flags &
MPI_SAS_DEVICE0_FLAGS_DEVICE_MAPPED))
continue;
phy_info = mptsas_find_phyinfo_by_sas_address(ioc,
sas_device.sas_address);
mptsas_add_end_device(ioc, phy_info);
}
out:
if (buffer)
pci_free_consistent(ioc->pcidev, hdr.PageLength * 4, buffer,
dma_handle);
}
/*
* Work queue thread to handle SAS hotplug events
*/
static void
mptsas_hotplug_work(MPT_ADAPTER *ioc, struct fw_event_work *fw_event,
struct mptsas_hotplug_event *hot_plug_info)
{
struct mptsas_phyinfo *phy_info;
struct scsi_target * starget;
struct mptsas_devinfo sas_device;
VirtTarget *vtarget;
int i;
struct mptsas_portinfo *port_info;
switch (hot_plug_info->event_type) {
case MPTSAS_ADD_PHYSDISK:
if (!ioc->raid_data.pIocPg2)
break;
for (i = 0; i < ioc->raid_data.pIocPg2->NumActiveVolumes; i++) {
if (ioc->raid_data.pIocPg2->RaidVolume[i].VolumeID ==
hot_plug_info->id) {
printk(MYIOC_s_WARN_FMT "firmware bug: unable "
"to add hidden disk - target_id matchs "
"volume_id\n", ioc->name);
mptsas_free_fw_event(ioc, fw_event);
return;
}
}
mpt_findImVolumes(ioc);
case MPTSAS_ADD_DEVICE:
memset(&sas_device, 0, sizeof(struct mptsas_devinfo));
mptsas_sas_device_pg0(ioc, &sas_device,
(MPI_SAS_DEVICE_PGAD_FORM_BUS_TARGET_ID <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
(hot_plug_info->channel << 8) +
hot_plug_info->id);
/* If there is no FW B_T mapping for this device then break
* */
if (!(sas_device.flags & MPI_SAS_DEVICE0_FLAGS_DEVICE_PRESENT)
|| !(sas_device.flags &
MPI_SAS_DEVICE0_FLAGS_DEVICE_MAPPED))
break;
if (!sas_device.handle)
return;
phy_info = mptsas_refreshing_device_handles(ioc, &sas_device);
/* Only For SATA Device ADD */
if (!phy_info && (sas_device.device_info &
MPI_SAS_DEVICE_INFO_SATA_DEVICE)) {
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s %d SATA HOT PLUG: "
"parent handle of device %x\n", ioc->name,
__func__, __LINE__, sas_device.handle_parent));
port_info = mptsas_find_portinfo_by_handle(ioc,
sas_device.handle_parent);
if (port_info == ioc->hba_port_info)
mptsas_probe_hba_phys(ioc);
else if (port_info)
mptsas_expander_refresh(ioc, port_info);
else {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s %d port info is NULL\n",
ioc->name, __func__, __LINE__));
break;
}
phy_info = mptsas_refreshing_device_handles
(ioc, &sas_device);
}
if (!phy_info) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s %d phy info is NULL\n",
ioc->name, __func__, __LINE__));
break;
}
if (mptsas_get_rphy(phy_info))
break;
mptsas_add_end_device(ioc, phy_info);
break;
case MPTSAS_DEL_DEVICE:
phy_info = mptsas_find_phyinfo_by_sas_address(ioc,
hot_plug_info->sas_address);
mptsas_del_end_device(ioc, phy_info);
break;
case MPTSAS_DEL_PHYSDISK:
mpt_findImVolumes(ioc);
phy_info = mptsas_find_phyinfo_by_phys_disk_num(
ioc, hot_plug_info->phys_disk_num,
hot_plug_info->channel,
hot_plug_info->id);
mptsas_del_end_device(ioc, phy_info);
break;
case MPTSAS_ADD_PHYSDISK_REPROBE:
if (mptsas_sas_device_pg0(ioc, &sas_device,
(MPI_SAS_DEVICE_PGAD_FORM_BUS_TARGET_ID <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
(hot_plug_info->channel << 8) + hot_plug_info->id)) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
/* If there is no FW B_T mapping for this device then break
* */
if (!(sas_device.flags & MPI_SAS_DEVICE0_FLAGS_DEVICE_PRESENT)
|| !(sas_device.flags &
MPI_SAS_DEVICE0_FLAGS_DEVICE_MAPPED))
break;
phy_info = mptsas_find_phyinfo_by_sas_address(
ioc, sas_device.sas_address);
if (!phy_info) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
starget = mptsas_get_starget(phy_info);
if (!starget) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
vtarget = starget->hostdata;
if (!vtarget) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
mpt_findImVolumes(ioc);
starget_printk(KERN_INFO, starget, MYIOC_s_FMT "RAID Hidding: "
"fw_channel=%d, fw_id=%d, physdsk %d, sas_addr 0x%llx\n",
ioc->name, hot_plug_info->channel, hot_plug_info->id,
hot_plug_info->phys_disk_num, (unsigned long long)
sas_device.sas_address);
vtarget->id = hot_plug_info->phys_disk_num;
vtarget->tflags |= MPT_TARGET_FLAGS_RAID_COMPONENT;
phy_info->attached.phys_disk_num = hot_plug_info->phys_disk_num;
mptsas_reprobe_target(starget, 1);
break;
case MPTSAS_DEL_PHYSDISK_REPROBE:
if (mptsas_sas_device_pg0(ioc, &sas_device,
(MPI_SAS_DEVICE_PGAD_FORM_BUS_TARGET_ID <<
MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
(hot_plug_info->channel << 8) + hot_plug_info->id)) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n",
ioc->name, __func__,
hot_plug_info->id, __LINE__));
break;
}
/* If there is no FW B_T mapping for this device then break
* */
if (!(sas_device.flags & MPI_SAS_DEVICE0_FLAGS_DEVICE_PRESENT)
|| !(sas_device.flags &
MPI_SAS_DEVICE0_FLAGS_DEVICE_MAPPED))
break;
phy_info = mptsas_find_phyinfo_by_sas_address(ioc,
sas_device.sas_address);
if (!phy_info) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
starget = mptsas_get_starget(phy_info);
if (!starget) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
vtarget = starget->hostdata;
if (!vtarget) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
if (!(vtarget->tflags & MPT_TARGET_FLAGS_RAID_COMPONENT)) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"%s: fw_id=%d exit at line=%d\n", ioc->name,
__func__, hot_plug_info->id, __LINE__));
break;
}
mpt_findImVolumes(ioc);
starget_printk(KERN_INFO, starget, MYIOC_s_FMT "RAID Exposing:"
" fw_channel=%d, fw_id=%d, physdsk %d, sas_addr 0x%llx\n",
ioc->name, hot_plug_info->channel, hot_plug_info->id,
hot_plug_info->phys_disk_num, (unsigned long long)
sas_device.sas_address);
vtarget->tflags &= ~MPT_TARGET_FLAGS_RAID_COMPONENT;
vtarget->id = hot_plug_info->id;
phy_info->attached.phys_disk_num = ~0;
mptsas_reprobe_target(starget, 0);
mptsas_add_device_component_by_fw(ioc,
hot_plug_info->channel, hot_plug_info->id);
break;
case MPTSAS_ADD_RAID:
mpt_findImVolumes(ioc);
printk(MYIOC_s_INFO_FMT "attaching raid volume, channel %d, "
"id %d\n", ioc->name, MPTSAS_RAID_CHANNEL,
hot_plug_info->id);
scsi_add_device(ioc->sh, MPTSAS_RAID_CHANNEL,
hot_plug_info->id, 0);
break;
case MPTSAS_DEL_RAID:
mpt_findImVolumes(ioc);
printk(MYIOC_s_INFO_FMT "removing raid volume, channel %d, "
"id %d\n", ioc->name, MPTSAS_RAID_CHANNEL,
hot_plug_info->id);
scsi_remove_device(hot_plug_info->sdev);
scsi_device_put(hot_plug_info->sdev);
break;
case MPTSAS_ADD_INACTIVE_VOLUME:
mpt_findImVolumes(ioc);
mptsas_adding_inactive_raid_components(ioc,
hot_plug_info->channel, hot_plug_info->id);
break;
default:
break;
}
mptsas_free_fw_event(ioc, fw_event);
}
static void
mptsas_send_sas_event(struct fw_event_work *fw_event)
{
MPT_ADAPTER *ioc;
struct mptsas_hotplug_event hot_plug_info;
EVENT_DATA_SAS_DEVICE_STATUS_CHANGE *sas_event_data;
u32 device_info;
u64 sas_address;
ioc = fw_event->ioc;
sas_event_data = (EVENT_DATA_SAS_DEVICE_STATUS_CHANGE *)
fw_event->event_data;
device_info = le32_to_cpu(sas_event_data->DeviceInfo);
if ((device_info &
(MPI_SAS_DEVICE_INFO_SSP_TARGET |
MPI_SAS_DEVICE_INFO_STP_TARGET |
MPI_SAS_DEVICE_INFO_SATA_DEVICE)) == 0) {
mptsas_free_fw_event(ioc, fw_event);
return;
}
if (sas_event_data->ReasonCode ==
MPI_EVENT_SAS_DEV_STAT_RC_NO_PERSIST_ADDED) {
mptbase_sas_persist_operation(ioc,
MPI_SAS_OP_CLEAR_NOT_PRESENT);
mptsas_free_fw_event(ioc, fw_event);
return;
}
switch (sas_event_data->ReasonCode) {
case MPI_EVENT_SAS_DEV_STAT_RC_NOT_RESPONDING:
case MPI_EVENT_SAS_DEV_STAT_RC_ADDED:
memset(&hot_plug_info, 0, sizeof(struct mptsas_hotplug_event));
hot_plug_info.handle = le16_to_cpu(sas_event_data->DevHandle);
hot_plug_info.channel = sas_event_data->Bus;
hot_plug_info.id = sas_event_data->TargetID;
hot_plug_info.phy_id = sas_event_data->PhyNum;
memcpy(&sas_address, &sas_event_data->SASAddress,
sizeof(u64));
hot_plug_info.sas_address = le64_to_cpu(sas_address);
hot_plug_info.device_info = device_info;
if (sas_event_data->ReasonCode &
MPI_EVENT_SAS_DEV_STAT_RC_ADDED)
hot_plug_info.event_type = MPTSAS_ADD_DEVICE;
else
hot_plug_info.event_type = MPTSAS_DEL_DEVICE;
mptsas_hotplug_work(ioc, fw_event, &hot_plug_info);
break;
case MPI_EVENT_SAS_DEV_STAT_RC_NO_PERSIST_ADDED:
mptbase_sas_persist_operation(ioc,
MPI_SAS_OP_CLEAR_NOT_PRESENT);
mptsas_free_fw_event(ioc, fw_event);
break;
case MPI_EVENT_SAS_DEV_STAT_RC_SMART_DATA:
/* TODO */
case MPI_EVENT_SAS_DEV_STAT_RC_INTERNAL_DEVICE_RESET:
/* TODO */
default:
mptsas_free_fw_event(ioc, fw_event);
break;
}
}
static void
mptsas_send_raid_event(struct fw_event_work *fw_event)
{
MPT_ADAPTER *ioc;
EVENT_DATA_RAID *raid_event_data;
struct mptsas_hotplug_event hot_plug_info;
int status;
int state;
struct scsi_device *sdev = NULL;
VirtDevice *vdevice = NULL;
RaidPhysDiskPage0_t phys_disk;
ioc = fw_event->ioc;
raid_event_data = (EVENT_DATA_RAID *)fw_event->event_data;
status = le32_to_cpu(raid_event_data->SettingsStatus);
state = (status >> 8) & 0xff;
memset(&hot_plug_info, 0, sizeof(struct mptsas_hotplug_event));
hot_plug_info.id = raid_event_data->VolumeID;
hot_plug_info.channel = raid_event_data->VolumeBus;
hot_plug_info.phys_disk_num = raid_event_data->PhysDiskNum;
if (raid_event_data->ReasonCode == MPI_EVENT_RAID_RC_VOLUME_DELETED ||
raid_event_data->ReasonCode == MPI_EVENT_RAID_RC_VOLUME_CREATED ||
raid_event_data->ReasonCode ==
MPI_EVENT_RAID_RC_VOLUME_STATUS_CHANGED) {
sdev = scsi_device_lookup(ioc->sh, MPTSAS_RAID_CHANNEL,
hot_plug_info.id, 0);
hot_plug_info.sdev = sdev;
if (sdev)
vdevice = sdev->hostdata;
}
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Entering %s: "
"ReasonCode=%02x\n", ioc->name, __func__,
raid_event_data->ReasonCode));
switch (raid_event_data->ReasonCode) {
case MPI_EVENT_RAID_RC_PHYSDISK_DELETED:
hot_plug_info.event_type = MPTSAS_DEL_PHYSDISK_REPROBE;
break;
case MPI_EVENT_RAID_RC_PHYSDISK_CREATED:
hot_plug_info.event_type = MPTSAS_ADD_PHYSDISK_REPROBE;
break;
case MPI_EVENT_RAID_RC_PHYSDISK_STATUS_CHANGED:
switch (state) {
case MPI_PD_STATE_ONLINE:
case MPI_PD_STATE_NOT_COMPATIBLE:
mpt_raid_phys_disk_pg0(ioc,
raid_event_data->PhysDiskNum, &phys_disk);
hot_plug_info.id = phys_disk.PhysDiskID;
hot_plug_info.channel = phys_disk.PhysDiskBus;
hot_plug_info.event_type = MPTSAS_ADD_PHYSDISK;
break;
case MPI_PD_STATE_FAILED:
case MPI_PD_STATE_MISSING:
case MPI_PD_STATE_OFFLINE_AT_HOST_REQUEST:
case MPI_PD_STATE_FAILED_AT_HOST_REQUEST:
case MPI_PD_STATE_OFFLINE_FOR_ANOTHER_REASON:
hot_plug_info.event_type = MPTSAS_DEL_PHYSDISK;
break;
default:
break;
}
break;
case MPI_EVENT_RAID_RC_VOLUME_DELETED:
if (!sdev)
break;
vdevice->vtarget->deleted = 1; /* block IO */
hot_plug_info.event_type = MPTSAS_DEL_RAID;
break;
case MPI_EVENT_RAID_RC_VOLUME_CREATED:
if (sdev) {
scsi_device_put(sdev);
break;
}
hot_plug_info.event_type = MPTSAS_ADD_RAID;
break;
case MPI_EVENT_RAID_RC_VOLUME_STATUS_CHANGED:
if (!(status & MPI_RAIDVOL0_STATUS_FLAG_ENABLED)) {
if (!sdev)
break;
vdevice->vtarget->deleted = 1; /* block IO */
hot_plug_info.event_type = MPTSAS_DEL_RAID;
break;
}
switch (state) {
case MPI_RAIDVOL0_STATUS_STATE_FAILED:
case MPI_RAIDVOL0_STATUS_STATE_MISSING:
if (!sdev)
break;
vdevice->vtarget->deleted = 1; /* block IO */
hot_plug_info.event_type = MPTSAS_DEL_RAID;
break;
case MPI_RAIDVOL0_STATUS_STATE_OPTIMAL:
case MPI_RAIDVOL0_STATUS_STATE_DEGRADED:
if (sdev) {
scsi_device_put(sdev);
break;
}
hot_plug_info.event_type = MPTSAS_ADD_RAID;
break;
default:
break;
}
break;
default:
break;
}
if (hot_plug_info.event_type != MPTSAS_IGNORE_EVENT)
mptsas_hotplug_work(ioc, fw_event, &hot_plug_info);
else
mptsas_free_fw_event(ioc, fw_event);
}
/**
* mptsas_issue_tm - send mptsas internal tm request
* @ioc: Pointer to MPT_ADAPTER structure
* @type: Task Management type
* @channel: channel number for task management
* @id: Logical Target ID for reset (if appropriate)
* @lun: Logical unit for reset (if appropriate)
* @task_context: Context for the task to be aborted
* @timeout: timeout for task management control
*
* return 0 on success and -1 on failure:
*
*/
static int
mptsas_issue_tm(MPT_ADAPTER *ioc, u8 type, u8 channel, u8 id, u64 lun,
int task_context, ulong timeout, u8 *issue_reset)
{
MPT_FRAME_HDR *mf;
SCSITaskMgmt_t *pScsiTm;
int retval;
unsigned long timeleft;
*issue_reset = 0;
mf = mpt_get_msg_frame(mptsasDeviceResetCtx, ioc);
if (mf == NULL) {
retval = -1; /* return failure */
dtmprintk(ioc, printk(MYIOC_s_WARN_FMT "TaskMgmt request: no "
"msg frames!!\n", ioc->name));
goto out;
}
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT "TaskMgmt request: mr = %p, "
"task_type = 0x%02X,\n\t timeout = %ld, fw_channel = %d, "
"fw_id = %d, lun = %lld,\n\t task_context = 0x%x\n", ioc->name, mf,
type, timeout, channel, id, (unsigned long long)lun,
task_context));
pScsiTm = (SCSITaskMgmt_t *) mf;
memset(pScsiTm, 0, sizeof(SCSITaskMgmt_t));
pScsiTm->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
pScsiTm->TaskType = type;
pScsiTm->MsgFlags = 0;
pScsiTm->TargetID = id;
pScsiTm->Bus = channel;
pScsiTm->ChainOffset = 0;
pScsiTm->Reserved = 0;
pScsiTm->Reserved1 = 0;
pScsiTm->TaskMsgContext = task_context;
int_to_scsilun(lun, (struct scsi_lun *)pScsiTm->LUN);
INITIALIZE_MGMT_STATUS(ioc->taskmgmt_cmds.status)
CLEAR_MGMT_STATUS(ioc->internal_cmds.status)
retval = 0;
mpt_put_msg_frame_hi_pri(mptsasDeviceResetCtx, ioc, mf);
/* Now wait for the command to complete */
timeleft = wait_for_completion_timeout(&ioc->taskmgmt_cmds.done,
timeout*HZ);
if (!(ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
retval = -1; /* return failure */
dtmprintk(ioc, printk(MYIOC_s_ERR_FMT
"TaskMgmt request: TIMED OUT!(mr=%p)\n", ioc->name, mf));
mpt_free_msg_frame(ioc, mf);
if (ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET)
goto out;
*issue_reset = 1;
goto out;
}
if (!(ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_RF_VALID)) {
retval = -1; /* return failure */
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt request: failed with no reply\n", ioc->name));
goto out;
}
out:
CLEAR_MGMT_STATUS(ioc->taskmgmt_cmds.status)
return retval;
}
/**
* mptsas_broadcast_primative_work - Handle broadcast primitives
* @work: work queue payload containing info describing the event
*
* this will be handled in workqueue context.
*/
static void
mptsas_broadcast_primative_work(struct fw_event_work *fw_event)
{
MPT_ADAPTER *ioc = fw_event->ioc;
MPT_FRAME_HDR *mf;
VirtDevice *vdevice;
int ii;
struct scsi_cmnd *sc;
SCSITaskMgmtReply_t *pScsiTmReply;
u8 issue_reset;
int task_context;
u8 channel, id;
int lun;
u32 termination_count;
u32 query_count;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s - enter\n", ioc->name, __func__));
mutex_lock(&ioc->taskmgmt_cmds.mutex);
if (mpt_set_taskmgmt_in_progress_flag(ioc) != 0) {
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
mptsas_requeue_fw_event(ioc, fw_event, 1000);
return;
}
issue_reset = 0;
termination_count = 0;
query_count = 0;
mpt_findImVolumes(ioc);
pScsiTmReply = (SCSITaskMgmtReply_t *) ioc->taskmgmt_cmds.reply;
for (ii = 0; ii < ioc->req_depth; ii++) {
if (ioc->fw_events_off)
goto out;
sc = mptscsih_get_scsi_lookup(ioc, ii);
if (!sc)
continue;
mf = MPT_INDEX_2_MFPTR(ioc, ii);
if (!mf)
continue;
task_context = mf->u.frame.hwhdr.msgctxu.MsgContext;
vdevice = sc->device->hostdata;
if (!vdevice || !vdevice->vtarget)
continue;
if (vdevice->vtarget->tflags & MPT_TARGET_FLAGS_RAID_COMPONENT)
continue; /* skip hidden raid components */
if (vdevice->vtarget->raidVolume)
continue; /* skip hidden raid components */
channel = vdevice->vtarget->channel;
id = vdevice->vtarget->id;
lun = vdevice->lun;
if (mptsas_issue_tm(ioc, MPI_SCSITASKMGMT_TASKTYPE_QUERY_TASK,
channel, id, (u64)lun, task_context, 30, &issue_reset))
goto out;
query_count++;
termination_count +=
le32_to_cpu(pScsiTmReply->TerminationCount);
if ((pScsiTmReply->IOCStatus == MPI_IOCSTATUS_SUCCESS) &&
(pScsiTmReply->ResponseCode ==
MPI_SCSITASKMGMT_RSP_TM_SUCCEEDED ||
pScsiTmReply->ResponseCode ==
MPI_SCSITASKMGMT_RSP_IO_QUEUED_ON_IOC))
continue;
if (mptsas_issue_tm(ioc,
MPI_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET,
channel, id, (u64)lun, 0, 30, &issue_reset))
goto out;
termination_count +=
le32_to_cpu(pScsiTmReply->TerminationCount);
}
out:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s - exit, query_count = %d termination_count = %d\n",
ioc->name, __func__, query_count, termination_count));
ioc->broadcast_aen_busy = 0;
mpt_clear_taskmgmt_in_progress_flag(ioc);
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
if (issue_reset) {
printk(MYIOC_s_WARN_FMT
"Issuing Reset from %s!! doorbell=0x%08x\n",
ioc->name, __func__, mpt_GetIocState(ioc, 0));
mpt_Soft_Hard_ResetHandler(ioc, CAN_SLEEP);
}
mptsas_free_fw_event(ioc, fw_event);
}
/*
* mptsas_send_ir2_event - handle exposing hidden disk when
* an inactive raid volume is added
*
* @ioc: Pointer to MPT_ADAPTER structure
* @ir2_data
*
*/
static void
mptsas_send_ir2_event(struct fw_event_work *fw_event)
{
MPT_ADAPTER *ioc;
struct mptsas_hotplug_event hot_plug_info;
MPI_EVENT_DATA_IR2 *ir2_data;
u8 reasonCode;
RaidPhysDiskPage0_t phys_disk;
ioc = fw_event->ioc;
ir2_data = (MPI_EVENT_DATA_IR2 *)fw_event->event_data;
reasonCode = ir2_data->ReasonCode;
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Entering %s: "
"ReasonCode=%02x\n", ioc->name, __func__, reasonCode));
memset(&hot_plug_info, 0, sizeof(struct mptsas_hotplug_event));
hot_plug_info.id = ir2_data->TargetID;
hot_plug_info.channel = ir2_data->Bus;
switch (reasonCode) {
case MPI_EVENT_IR2_RC_FOREIGN_CFG_DETECTED:
hot_plug_info.event_type = MPTSAS_ADD_INACTIVE_VOLUME;
break;
case MPI_EVENT_IR2_RC_DUAL_PORT_REMOVED:
hot_plug_info.phys_disk_num = ir2_data->PhysDiskNum;
hot_plug_info.event_type = MPTSAS_DEL_PHYSDISK;
break;
case MPI_EVENT_IR2_RC_DUAL_PORT_ADDED:
hot_plug_info.phys_disk_num = ir2_data->PhysDiskNum;
mpt_raid_phys_disk_pg0(ioc,
ir2_data->PhysDiskNum, &phys_disk);
hot_plug_info.id = phys_disk.PhysDiskID;
hot_plug_info.event_type = MPTSAS_ADD_PHYSDISK;
break;
default:
mptsas_free_fw_event(ioc, fw_event);
return;
}
mptsas_hotplug_work(ioc, fw_event, &hot_plug_info);
}
static int
mptsas_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *reply)
{
u32 event = le32_to_cpu(reply->Event);
int sz, event_data_sz;
struct fw_event_work *fw_event;
unsigned long delay;
if (ioc->bus_type != SAS)
return 0;
/* events turned off due to host reset or driver unloading */
if (ioc->fw_events_off)
return 0;
delay = msecs_to_jiffies(1);
switch (event) {
case MPI_EVENT_SAS_BROADCAST_PRIMITIVE:
{
EVENT_DATA_SAS_BROADCAST_PRIMITIVE *broadcast_event_data =
(EVENT_DATA_SAS_BROADCAST_PRIMITIVE *)reply->Data;
if (broadcast_event_data->Primitive !=
MPI_EVENT_PRIMITIVE_ASYNCHRONOUS_EVENT)
return 0;
if (ioc->broadcast_aen_busy)
return 0;
ioc->broadcast_aen_busy = 1;
break;
}
case MPI_EVENT_SAS_DEVICE_STATUS_CHANGE:
{
EVENT_DATA_SAS_DEVICE_STATUS_CHANGE *sas_event_data =
(EVENT_DATA_SAS_DEVICE_STATUS_CHANGE *)reply->Data;
u16 ioc_stat;
ioc_stat = le16_to_cpu(reply->IOCStatus);
if (sas_event_data->ReasonCode ==
MPI_EVENT_SAS_DEV_STAT_RC_NOT_RESPONDING) {
mptsas_target_reset_queue(ioc, sas_event_data);
return 0;
}
if (sas_event_data->ReasonCode ==
MPI_EVENT_SAS_DEV_STAT_RC_INTERNAL_DEVICE_RESET &&
ioc->device_missing_delay &&
(ioc_stat & MPI_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)) {
VirtTarget *vtarget = NULL;
u8 id, channel;
id = sas_event_data->TargetID;
channel = sas_event_data->Bus;
vtarget = mptsas_find_vtarget(ioc, channel, id);
if (vtarget) {
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"LogInfo (0x%x) available for "
"INTERNAL_DEVICE_RESET"
"fw_id %d fw_channel %d\n", ioc->name,
le32_to_cpu(reply->IOCLogInfo),
id, channel));
if (vtarget->raidVolume) {
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Skipping Raid Volume for inDMD\n",
ioc->name));
} else {
devtprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Setting device flag inDMD\n",
ioc->name));
vtarget->inDMD = 1;
}
}
}
break;
}
case MPI_EVENT_SAS_EXPANDER_STATUS_CHANGE:
{
MpiEventDataSasExpanderStatusChange_t *expander_data =
(MpiEventDataSasExpanderStatusChange_t *)reply->Data;
if (ioc->old_sas_discovery_protocal)
return 0;
if (expander_data->ReasonCode ==
MPI_EVENT_SAS_EXP_RC_NOT_RESPONDING &&
ioc->device_missing_delay)
delay = HZ * ioc->device_missing_delay;
break;
}
case MPI_EVENT_SAS_DISCOVERY:
{
u32 discovery_status;
EventDataSasDiscovery_t *discovery_data =
(EventDataSasDiscovery_t *)reply->Data;
discovery_status = le32_to_cpu(discovery_data->DiscoveryStatus);
ioc->sas_discovery_quiesce_io = discovery_status ? 1 : 0;
if (ioc->old_sas_discovery_protocal && !discovery_status)
mptsas_queue_rescan(ioc);
return 0;
}
case MPI_EVENT_INTEGRATED_RAID:
case MPI_EVENT_PERSISTENT_TABLE_FULL:
case MPI_EVENT_IR2:
case MPI_EVENT_SAS_PHY_LINK_STATUS:
case MPI_EVENT_QUEUE_FULL:
break;
default:
return 0;
}
event_data_sz = ((reply->MsgLength * 4) -
offsetof(EventNotificationReply_t, Data));
sz = offsetof(struct fw_event_work, event_data) + event_data_sz;
fw_event = kzalloc(sz, GFP_ATOMIC);
if (!fw_event) {
printk(MYIOC_s_WARN_FMT "%s: failed at (line=%d)\n", ioc->name,
__func__, __LINE__);
return 0;
}
memcpy(fw_event->event_data, reply->Data, event_data_sz);
fw_event->event = event;
fw_event->ioc = ioc;
mptsas_add_fw_event(ioc, fw_event, delay);
return 0;
}
/* Delete a volume when no longer listed in ioc pg2
*/
static void mptsas_volume_delete(MPT_ADAPTER *ioc, u8 id)
{
struct scsi_device *sdev;
int i;
sdev = scsi_device_lookup(ioc->sh, MPTSAS_RAID_CHANNEL, id, 0);
if (!sdev)
return;
if (!ioc->raid_data.pIocPg2)
goto out;
if (!ioc->raid_data.pIocPg2->NumActiveVolumes)
goto out;
for (i = 0; i < ioc->raid_data.pIocPg2->NumActiveVolumes; i++)
if (ioc->raid_data.pIocPg2->RaidVolume[i].VolumeID == id)
goto release_sdev;
out:
printk(MYIOC_s_INFO_FMT "removing raid volume, channel %d, "
"id %d\n", ioc->name, MPTSAS_RAID_CHANNEL, id);
scsi_remove_device(sdev);
release_sdev:
scsi_device_put(sdev);
}
static int
mptsas_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct Scsi_Host *sh;
MPT_SCSI_HOST *hd;
MPT_ADAPTER *ioc;
unsigned long flags;
int ii;
int numSGE = 0;
int scale;
int ioc_cap;
int error=0;
int r;
r = mpt_attach(pdev,id);
if (r)
return r;
ioc = pci_get_drvdata(pdev);
mptsas_fw_event_off(ioc);
ioc->DoneCtx = mptsasDoneCtx;
ioc->TaskCtx = mptsasTaskCtx;
ioc->InternalCtx = mptsasInternalCtx;
ioc->schedule_target_reset = &mptsas_schedule_target_reset;
ioc->schedule_dead_ioc_flush_running_cmds =
&mptscsih_flush_running_cmds;
/* Added sanity check on readiness of the MPT adapter.
*/
if (ioc->last_state != MPI_IOC_STATE_OPERATIONAL) {
printk(MYIOC_s_WARN_FMT
"Skipping because it's not operational!\n",
ioc->name);
error = -ENODEV;
goto out_mptsas_probe;
}
if (!ioc->active) {
printk(MYIOC_s_WARN_FMT "Skipping because it's disabled!\n",
ioc->name);
error = -ENODEV;
goto out_mptsas_probe;
}
/* Sanity check - ensure at least 1 port is INITIATOR capable
*/
ioc_cap = 0;
for (ii = 0; ii < ioc->facts.NumberOfPorts; ii++) {
if (ioc->pfacts[ii].ProtocolFlags &
MPI_PORTFACTS_PROTOCOL_INITIATOR)
ioc_cap++;
}
if (!ioc_cap) {
printk(MYIOC_s_WARN_FMT
"Skipping ioc=%p because SCSI Initiator mode "
"is NOT enabled!\n", ioc->name, ioc);
return 0;
}
sh = scsi_host_alloc(&mptsas_driver_template, sizeof(MPT_SCSI_HOST));
if (!sh) {
printk(MYIOC_s_WARN_FMT
"Unable to register controller with SCSI subsystem\n",
ioc->name);
error = -1;
goto out_mptsas_probe;
}
spin_lock_irqsave(&ioc->FreeQlock, flags);
/* Attach the SCSI Host to the IOC structure
*/
ioc->sh = sh;
sh->io_port = 0;
sh->n_io_port = 0;
sh->irq = 0;
/* set 16 byte cdb's */
sh->max_cmd_len = 16;
sh->can_queue = min_t(int, ioc->req_depth - 10, sh->can_queue);
sh->max_id = -1;
sh->max_lun = max_lun;
sh->transportt = mptsas_transport_template;
/* Required entry.
*/
sh->unique_id = ioc->id;
INIT_LIST_HEAD(&ioc->sas_topology);
mutex_init(&ioc->sas_topology_mutex);
mutex_init(&ioc->sas_discovery_mutex);
mutex_init(&ioc->sas_mgmt.mutex);
init_completion(&ioc->sas_mgmt.done);
/* Verify that we won't exceed the maximum
* number of chain buffers
* We can optimize: ZZ = req_sz/sizeof(SGE)
* For 32bit SGE's:
* numSGE = 1 + (ZZ-1)*(maxChain -1) + ZZ
* + (req_sz - 64)/sizeof(SGE)
* A slightly different algorithm is required for
* 64bit SGEs.
*/
scale = ioc->req_sz/ioc->SGE_size;
if (ioc->sg_addr_size == sizeof(u64)) {
numSGE = (scale - 1) *
(ioc->facts.MaxChainDepth-1) + scale +
(ioc->req_sz - 60) / ioc->SGE_size;
} else {
numSGE = 1 + (scale - 1) *
(ioc->facts.MaxChainDepth-1) + scale +
(ioc->req_sz - 64) / ioc->SGE_size;
}
if (numSGE < sh->sg_tablesize) {
/* Reset this value */
dprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Resetting sg_tablesize to %d from %d\n",
ioc->name, numSGE, sh->sg_tablesize));
sh->sg_tablesize = numSGE;
}
if (mpt_loadtime_max_sectors) {
if (mpt_loadtime_max_sectors < 64 ||
mpt_loadtime_max_sectors > 8192) {
printk(MYIOC_s_INFO_FMT "Invalid value passed for"
"mpt_loadtime_max_sectors %d."
"Range from 64 to 8192\n", ioc->name,
mpt_loadtime_max_sectors);
}
mpt_loadtime_max_sectors &= 0xFFFFFFFE;
dprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Resetting max sector to %d from %d\n",
ioc->name, mpt_loadtime_max_sectors, sh->max_sectors));
sh->max_sectors = mpt_loadtime_max_sectors;
}
hd = shost_priv(sh);
hd->ioc = ioc;
/* SCSI needs scsi_cmnd lookup table!
* (with size equal to req_depth*PtrSz!)
*/
ioc->ScsiLookup = kcalloc(ioc->req_depth, sizeof(void *), GFP_ATOMIC);
if (!ioc->ScsiLookup) {
error = -ENOMEM;
spin_unlock_irqrestore(&ioc->FreeQlock, flags);
goto out_mptsas_probe;
}
spin_lock_init(&ioc->scsi_lookup_lock);
dprintk(ioc, printk(MYIOC_s_DEBUG_FMT "ScsiLookup @ %p\n",
ioc->name, ioc->ScsiLookup));
ioc->sas_data.ptClear = mpt_pt_clear;
hd->last_queue_full = 0;
INIT_LIST_HEAD(&hd->target_reset_list);
INIT_LIST_HEAD(&ioc->sas_device_info_list);
mutex_init(&ioc->sas_device_info_mutex);
spin_unlock_irqrestore(&ioc->FreeQlock, flags);
if (ioc->sas_data.ptClear==1) {
mptbase_sas_persist_operation(
ioc, MPI_SAS_OP_CLEAR_ALL_PERSISTENT);
}
error = scsi_add_host(sh, &ioc->pcidev->dev);
if (error) {
dprintk(ioc, printk(MYIOC_s_ERR_FMT
"scsi_add_host failed\n", ioc->name));
goto out_mptsas_probe;
}
/* older firmware doesn't support expander events */
if ((ioc->facts.HeaderVersion >> 8) < 0xE)
ioc->old_sas_discovery_protocal = 1;
mptsas_scan_sas_topology(ioc);
mptsas_fw_event_on(ioc);
return 0;
out_mptsas_probe:
mptscsih_remove(pdev);
return error;
}
void
mptsas_shutdown(struct pci_dev *pdev)
{
MPT_ADAPTER *ioc = pci_get_drvdata(pdev);
mptsas_fw_event_off(ioc);
mptsas_cleanup_fw_event_q(ioc);
}
static void mptsas_remove(struct pci_dev *pdev)
{
MPT_ADAPTER *ioc = pci_get_drvdata(pdev);
struct mptsas_portinfo *p, *n;
int i;
if (!ioc->sh) {
printk(MYIOC_s_INFO_FMT "IOC is in Target mode\n", ioc->name);
mpt_detach(pdev);
return;
}
mptsas_shutdown(pdev);
mptsas_del_device_components(ioc);
ioc->sas_discovery_ignore_events = 1;
sas_remove_host(ioc->sh);
mutex_lock(&ioc->sas_topology_mutex);
list_for_each_entry_safe(p, n, &ioc->sas_topology, list) {
list_del(&p->list);
for (i = 0 ; i < p->num_phys ; i++)
mptsas_port_delete(ioc, p->phy_info[i].port_details);
kfree(p->phy_info);
kfree(p);
}
mutex_unlock(&ioc->sas_topology_mutex);
ioc->hba_port_info = NULL;
mptscsih_remove(pdev);
}
static struct pci_device_id mptsas_pci_table[] = {
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVID_SAS1064,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVID_SAS1068,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVID_SAS1064E,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVID_SAS1068E,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVID_SAS1078,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVID_SAS1068_820XELP,
PCI_ANY_ID, PCI_ANY_ID },
{0} /* Terminating entry */
};
MODULE_DEVICE_TABLE(pci, mptsas_pci_table);
static struct pci_driver mptsas_driver = {
.name = "mptsas",
.id_table = mptsas_pci_table,
.probe = mptsas_probe,
.remove = mptsas_remove,
.shutdown = mptsas_shutdown,
#ifdef CONFIG_PM
.suspend = mptscsih_suspend,
.resume = mptscsih_resume,
#endif
};
static int __init
mptsas_init(void)
{
int error;
show_mptmod_ver(my_NAME, my_VERSION);
mptsas_transport_template =
sas_attach_transport(&mptsas_transport_functions);
if (!mptsas_transport_template)
return -ENODEV;
mptsas_transport_template->eh_timed_out = mptsas_eh_timed_out;
mptsasDoneCtx = mpt_register(mptscsih_io_done, MPTSAS_DRIVER,
"mptscsih_io_done");
mptsasTaskCtx = mpt_register(mptscsih_taskmgmt_complete, MPTSAS_DRIVER,
"mptscsih_taskmgmt_complete");
mptsasInternalCtx =
mpt_register(mptscsih_scandv_complete, MPTSAS_DRIVER,
"mptscsih_scandv_complete");
mptsasMgmtCtx = mpt_register(mptsas_mgmt_done, MPTSAS_DRIVER,
"mptsas_mgmt_done");
mptsasDeviceResetCtx =
mpt_register(mptsas_taskmgmt_complete, MPTSAS_DRIVER,
"mptsas_taskmgmt_complete");
mpt_event_register(mptsasDoneCtx, mptsas_event_process);
mpt_reset_register(mptsasDoneCtx, mptsas_ioc_reset);
error = pci_register_driver(&mptsas_driver);
if (error)
sas_release_transport(mptsas_transport_template);
return error;
}
static void __exit
mptsas_exit(void)
{
pci_unregister_driver(&mptsas_driver);
sas_release_transport(mptsas_transport_template);
mpt_reset_deregister(mptsasDoneCtx);
mpt_event_deregister(mptsasDoneCtx);
mpt_deregister(mptsasMgmtCtx);
mpt_deregister(mptsasInternalCtx);
mpt_deregister(mptsasTaskCtx);
mpt_deregister(mptsasDoneCtx);
mpt_deregister(mptsasDeviceResetCtx);
}
module_init(mptsas_init);
module_exit(mptsas_exit);
| gpl-2.0 |
MSM8916-Samsung/android_kernel_samsung_a7lte | drivers/mfd/da9055-i2c.c | 2312 | 2025 | /* I2C access for DA9055 PMICs.
*
* Copyright(c) 2012 Dialog Semiconductor Ltd.
*
* Author: David Dajun Chen <dchen@diasemi.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include <linux/module.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/mfd/da9055/core.h>
static int da9055_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct da9055 *da9055;
int ret;
da9055 = devm_kzalloc(&i2c->dev, sizeof(struct da9055), GFP_KERNEL);
if (!da9055)
return -ENOMEM;
da9055->regmap = devm_regmap_init_i2c(i2c, &da9055_regmap_config);
if (IS_ERR(da9055->regmap)) {
ret = PTR_ERR(da9055->regmap);
dev_err(&i2c->dev, "Failed to allocate register map: %d\n",
ret);
return ret;
}
da9055->dev = &i2c->dev;
da9055->chip_irq = i2c->irq;
i2c_set_clientdata(i2c, da9055);
return da9055_device_init(da9055);
}
static int da9055_i2c_remove(struct i2c_client *i2c)
{
struct da9055 *da9055 = i2c_get_clientdata(i2c);
da9055_device_exit(da9055);
return 0;
}
static struct i2c_device_id da9055_i2c_id[] = {
{"da9055-pmic", 0},
{ }
};
static struct i2c_driver da9055_i2c_driver = {
.probe = da9055_i2c_probe,
.remove = da9055_i2c_remove,
.id_table = da9055_i2c_id,
.driver = {
.name = "da9055",
.owner = THIS_MODULE,
},
};
static int __init da9055_i2c_init(void)
{
int ret;
ret = i2c_add_driver(&da9055_i2c_driver);
if (ret != 0) {
pr_err("DA9055 I2C registration failed %d\n", ret);
return ret;
}
return 0;
}
subsys_initcall(da9055_i2c_init);
static void __exit da9055_i2c_exit(void)
{
i2c_del_driver(&da9055_i2c_driver);
}
module_exit(da9055_i2c_exit);
MODULE_AUTHOR("David Dajun Chen <dchen@diasemi.com>");
MODULE_DESCRIPTION("I2C driver for Dialog DA9055 PMIC");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ezeeyahoo/android_kernel_motorola_msm8916 | fs/hfsplus/attributes.c | 2568 | 9319 | /*
* linux/fs/hfsplus/attributes.c
*
* Vyacheslav Dubeyko <slava@dubeyko.com>
*
* Handling of records in attributes tree
*/
#include "hfsplus_fs.h"
#include "hfsplus_raw.h"
static struct kmem_cache *hfsplus_attr_tree_cachep;
int hfsplus_create_attr_tree_cache(void)
{
if (hfsplus_attr_tree_cachep)
return -EEXIST;
hfsplus_attr_tree_cachep =
kmem_cache_create("hfsplus_attr_cache",
sizeof(hfsplus_attr_entry), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!hfsplus_attr_tree_cachep)
return -ENOMEM;
return 0;
}
void hfsplus_destroy_attr_tree_cache(void)
{
kmem_cache_destroy(hfsplus_attr_tree_cachep);
}
int hfsplus_attr_bin_cmp_key(const hfsplus_btree_key *k1,
const hfsplus_btree_key *k2)
{
__be32 k1_cnid, k2_cnid;
k1_cnid = k1->attr.cnid;
k2_cnid = k2->attr.cnid;
if (k1_cnid != k2_cnid)
return be32_to_cpu(k1_cnid) < be32_to_cpu(k2_cnid) ? -1 : 1;
return hfsplus_strcmp(
(const struct hfsplus_unistr *)&k1->attr.key_name,
(const struct hfsplus_unistr *)&k2->attr.key_name);
}
int hfsplus_attr_build_key(struct super_block *sb, hfsplus_btree_key *key,
u32 cnid, const char *name)
{
int len;
memset(key, 0, sizeof(struct hfsplus_attr_key));
key->attr.cnid = cpu_to_be32(cnid);
if (name) {
len = strlen(name);
if (len > HFSPLUS_ATTR_MAX_STRLEN) {
pr_err("invalid xattr name's length\n");
return -EINVAL;
}
hfsplus_asc2uni(sb,
(struct hfsplus_unistr *)&key->attr.key_name,
HFSPLUS_ATTR_MAX_STRLEN, name, len);
len = be16_to_cpu(key->attr.key_name.length);
} else {
key->attr.key_name.length = 0;
len = 0;
}
/* The length of the key, as stored in key_len field, does not include
* the size of the key_len field itself.
* So, offsetof(hfsplus_attr_key, key_name) is a trick because
* it takes into consideration key_len field (__be16) of
* hfsplus_attr_key structure instead of length field (__be16) of
* hfsplus_attr_unistr structure.
*/
key->key_len =
cpu_to_be16(offsetof(struct hfsplus_attr_key, key_name) +
2 * len);
return 0;
}
void hfsplus_attr_build_key_uni(hfsplus_btree_key *key,
u32 cnid,
struct hfsplus_attr_unistr *name)
{
int ustrlen;
memset(key, 0, sizeof(struct hfsplus_attr_key));
ustrlen = be16_to_cpu(name->length);
key->attr.cnid = cpu_to_be32(cnid);
key->attr.key_name.length = cpu_to_be16(ustrlen);
ustrlen *= 2;
memcpy(key->attr.key_name.unicode, name->unicode, ustrlen);
/* The length of the key, as stored in key_len field, does not include
* the size of the key_len field itself.
* So, offsetof(hfsplus_attr_key, key_name) is a trick because
* it takes into consideration key_len field (__be16) of
* hfsplus_attr_key structure instead of length field (__be16) of
* hfsplus_attr_unistr structure.
*/
key->key_len =
cpu_to_be16(offsetof(struct hfsplus_attr_key, key_name) +
ustrlen);
}
hfsplus_attr_entry *hfsplus_alloc_attr_entry(void)
{
return kmem_cache_alloc(hfsplus_attr_tree_cachep, GFP_KERNEL);
}
void hfsplus_destroy_attr_entry(hfsplus_attr_entry *entry)
{
if (entry)
kmem_cache_free(hfsplus_attr_tree_cachep, entry);
}
#define HFSPLUS_INVALID_ATTR_RECORD -1
static int hfsplus_attr_build_record(hfsplus_attr_entry *entry, int record_type,
u32 cnid, const void *value, size_t size)
{
if (record_type == HFSPLUS_ATTR_FORK_DATA) {
/*
* Mac OS X supports only inline data attributes.
* Do nothing
*/
memset(entry, 0, sizeof(*entry));
return sizeof(struct hfsplus_attr_fork_data);
} else if (record_type == HFSPLUS_ATTR_EXTENTS) {
/*
* Mac OS X supports only inline data attributes.
* Do nothing.
*/
memset(entry, 0, sizeof(*entry));
return sizeof(struct hfsplus_attr_extents);
} else if (record_type == HFSPLUS_ATTR_INLINE_DATA) {
u16 len;
memset(entry, 0, sizeof(struct hfsplus_attr_inline_data));
entry->inline_data.record_type = cpu_to_be32(record_type);
if (size <= HFSPLUS_MAX_INLINE_DATA_SIZE)
len = size;
else
return HFSPLUS_INVALID_ATTR_RECORD;
entry->inline_data.length = cpu_to_be16(len);
memcpy(entry->inline_data.raw_bytes, value, len);
/*
* Align len on two-byte boundary.
* It needs to add pad byte if we have odd len.
*/
len = round_up(len, 2);
return offsetof(struct hfsplus_attr_inline_data, raw_bytes) +
len;
} else /* invalid input */
memset(entry, 0, sizeof(*entry));
return HFSPLUS_INVALID_ATTR_RECORD;
}
int hfsplus_find_attr(struct super_block *sb, u32 cnid,
const char *name, struct hfs_find_data *fd)
{
int err = 0;
hfs_dbg(ATTR_MOD, "find_attr: %s,%d\n", name ? name : NULL, cnid);
if (!HFSPLUS_SB(sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
if (name) {
err = hfsplus_attr_build_key(sb, fd->search_key, cnid, name);
if (err)
goto failed_find_attr;
err = hfs_brec_find(fd, hfs_find_rec_by_key);
if (err)
goto failed_find_attr;
} else {
err = hfsplus_attr_build_key(sb, fd->search_key, cnid, NULL);
if (err)
goto failed_find_attr;
err = hfs_brec_find(fd, hfs_find_1st_rec_by_cnid);
if (err)
goto failed_find_attr;
}
failed_find_attr:
return err;
}
int hfsplus_attr_exists(struct inode *inode, const char *name)
{
int err = 0;
struct super_block *sb = inode->i_sb;
struct hfs_find_data fd;
if (!HFSPLUS_SB(sb)->attr_tree)
return 0;
err = hfs_find_init(HFSPLUS_SB(sb)->attr_tree, &fd);
if (err)
return 0;
err = hfsplus_find_attr(sb, inode->i_ino, name, &fd);
if (err)
goto attr_not_found;
hfs_find_exit(&fd);
return 1;
attr_not_found:
hfs_find_exit(&fd);
return 0;
}
int hfsplus_create_attr(struct inode *inode,
const char *name,
const void *value, size_t size)
{
struct super_block *sb = inode->i_sb;
struct hfs_find_data fd;
hfsplus_attr_entry *entry_ptr;
int entry_size;
int err;
hfs_dbg(ATTR_MOD, "create_attr: %s,%ld\n",
name ? name : NULL, inode->i_ino);
if (!HFSPLUS_SB(sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
entry_ptr = hfsplus_alloc_attr_entry();
if (!entry_ptr)
return -ENOMEM;
err = hfs_find_init(HFSPLUS_SB(sb)->attr_tree, &fd);
if (err)
goto failed_init_create_attr;
if (name) {
err = hfsplus_attr_build_key(sb, fd.search_key,
inode->i_ino, name);
if (err)
goto failed_create_attr;
} else {
err = -EINVAL;
goto failed_create_attr;
}
/* Mac OS X supports only inline data attributes. */
entry_size = hfsplus_attr_build_record(entry_ptr,
HFSPLUS_ATTR_INLINE_DATA,
inode->i_ino,
value, size);
if (entry_size == HFSPLUS_INVALID_ATTR_RECORD) {
err = -EINVAL;
goto failed_create_attr;
}
err = hfs_brec_find(&fd, hfs_find_rec_by_key);
if (err != -ENOENT) {
if (!err)
err = -EEXIST;
goto failed_create_attr;
}
err = hfs_brec_insert(&fd, entry_ptr, entry_size);
if (err)
goto failed_create_attr;
hfsplus_mark_inode_dirty(inode, HFSPLUS_I_ATTR_DIRTY);
failed_create_attr:
hfs_find_exit(&fd);
failed_init_create_attr:
hfsplus_destroy_attr_entry(entry_ptr);
return err;
}
static int __hfsplus_delete_attr(struct inode *inode, u32 cnid,
struct hfs_find_data *fd)
{
int err = 0;
__be32 found_cnid, record_type;
hfs_bnode_read(fd->bnode, &found_cnid,
fd->keyoffset +
offsetof(struct hfsplus_attr_key, cnid),
sizeof(__be32));
if (cnid != be32_to_cpu(found_cnid))
return -ENOENT;
hfs_bnode_read(fd->bnode, &record_type,
fd->entryoffset, sizeof(record_type));
switch (be32_to_cpu(record_type)) {
case HFSPLUS_ATTR_INLINE_DATA:
/* All is OK. Do nothing. */
break;
case HFSPLUS_ATTR_FORK_DATA:
case HFSPLUS_ATTR_EXTENTS:
pr_err("only inline data xattr are supported\n");
return -EOPNOTSUPP;
default:
pr_err("invalid extended attribute record\n");
return -ENOENT;
}
err = hfs_brec_remove(fd);
if (err)
return err;
hfsplus_mark_inode_dirty(inode, HFSPLUS_I_ATTR_DIRTY);
return err;
}
int hfsplus_delete_attr(struct inode *inode, const char *name)
{
int err = 0;
struct super_block *sb = inode->i_sb;
struct hfs_find_data fd;
hfs_dbg(ATTR_MOD, "delete_attr: %s,%ld\n",
name ? name : NULL, inode->i_ino);
if (!HFSPLUS_SB(sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
err = hfs_find_init(HFSPLUS_SB(sb)->attr_tree, &fd);
if (err)
return err;
if (name) {
err = hfsplus_attr_build_key(sb, fd.search_key,
inode->i_ino, name);
if (err)
goto out;
} else {
pr_err("invalid extended attribute name\n");
err = -EINVAL;
goto out;
}
err = hfs_brec_find(&fd, hfs_find_rec_by_key);
if (err)
goto out;
err = __hfsplus_delete_attr(inode, inode->i_ino, &fd);
if (err)
goto out;
out:
hfs_find_exit(&fd);
return err;
}
int hfsplus_delete_all_attrs(struct inode *dir, u32 cnid)
{
int err = 0;
struct hfs_find_data fd;
hfs_dbg(ATTR_MOD, "delete_all_attrs: %d\n", cnid);
if (!HFSPLUS_SB(dir->i_sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
err = hfs_find_init(HFSPLUS_SB(dir->i_sb)->attr_tree, &fd);
if (err)
return err;
for (;;) {
err = hfsplus_find_attr(dir->i_sb, cnid, NULL, &fd);
if (err) {
if (err != -ENOENT)
pr_err("xattr search failed\n");
goto end_delete_all;
}
err = __hfsplus_delete_attr(dir, cnid, &fd);
if (err)
goto end_delete_all;
}
end_delete_all:
hfs_find_exit(&fd);
return err;
}
| gpl-2.0 |
XxXPachaXxX/PachaRX-VS4-3.0.16 | drivers/net/wireless/orinoco/orinoco_usb.c | 2568 | 46382 | /*
* USB Orinoco driver
*
* Copyright (c) 2003 Manuel Estrada Sainz
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License
* at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and
* limitations under the License.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License version 2 (the "GPL"), in
* which case the provisions of the GPL are applicable instead of the
* above. If you wish to allow the use of your version of this file
* only under the terms of the GPL and not to allow others to use your
* version of this file under the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and
* other provisions required by the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file
* under either the MPL or the GPL.
*
* Queueing code based on linux-wlan-ng 0.2.1-pre5
*
* Copyright (C) 1999 AbsoluteValue Systems, Inc. All Rights Reserved.
*
* The license is the same as above.
*
* Initialy based on USB Skeleton driver - 0.7
*
* Copyright (c) 2001 Greg Kroah-Hartman (greg@kroah.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* NOTE: The original USB Skeleton driver is GPL, but all that code is
* gone so MPL/GPL applies.
*/
#define DRIVER_NAME "orinoco_usb"
#define PFX DRIVER_NAME ": "
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/usb.h>
#include <linux/timer.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include <linux/wireless.h>
#include <linux/firmware.h>
#include "mic.h"
#include "orinoco.h"
#ifndef URB_ASYNC_UNLINK
#define URB_ASYNC_UNLINK 0
#endif
/* 802.2 LLC/SNAP header used for Ethernet encapsulation over 802.11 */
static const u8 encaps_hdr[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
#define ENCAPS_OVERHEAD (sizeof(encaps_hdr) + 2)
struct header_struct {
/* 802.3 */
u8 dest[ETH_ALEN];
u8 src[ETH_ALEN];
__be16 len;
/* 802.2 */
u8 dsap;
u8 ssap;
u8 ctrl;
/* SNAP */
u8 oui[3];
__be16 ethertype;
} __packed;
struct ez_usb_fw {
u16 size;
const u8 *code;
};
static struct ez_usb_fw firmware = {
.size = 0,
.code = NULL,
};
#ifdef CONFIG_USB_DEBUG
static int debug = 1;
#else
static int debug;
#endif
/* Debugging macros */
#undef dbg
#define dbg(format, arg...) \
do { if (debug) printk(KERN_DEBUG PFX "%s: " format "\n", \
__func__ , ## arg); } while (0)
#undef err
#define err(format, arg...) \
do { printk(KERN_ERR PFX format "\n", ## arg); } while (0)
/* Module paramaters */
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug enabled or not");
MODULE_FIRMWARE("orinoco_ezusb_fw");
/*
* Under some conditions, the card gets stuck and stops paying attention
* to the world (i.e. data communication stalls) until we do something to
* it. Sending an INQ_TALLIES command seems to be enough and should be
* harmless otherwise. This behaviour has been observed when using the
* driver on a systemimager client during installation. In the past a
* timer was used to send INQ_TALLIES commands when there was no other
* activity, but it was troublesome and was removed.
*/
#define USB_COMPAQ_VENDOR_ID 0x049f /* Compaq Computer Corp. */
#define USB_COMPAQ_WL215_ID 0x001f /* Compaq WL215 USB Adapter */
#define USB_COMPAQ_W200_ID 0x0076 /* Compaq W200 USB Adapter */
#define USB_HP_WL215_ID 0x0082 /* Compaq WL215 USB Adapter */
#define USB_MELCO_VENDOR_ID 0x0411
#define USB_BUFFALO_L11_ID 0x0006 /* BUFFALO WLI-USB-L11 */
#define USB_BUFFALO_L11G_WR_ID 0x000B /* BUFFALO WLI-USB-L11G-WR */
#define USB_BUFFALO_L11G_ID 0x000D /* BUFFALO WLI-USB-L11G */
#define USB_LUCENT_VENDOR_ID 0x047E /* Lucent Technologies */
#define USB_LUCENT_ORINOCO_ID 0x0300 /* Lucent/Agere Orinoco USB Client */
#define USB_AVAYA8_VENDOR_ID 0x0D98
#define USB_AVAYAE_VENDOR_ID 0x0D9E
#define USB_AVAYA_WIRELESS_ID 0x0300 /* Avaya Wireless USB Card */
#define USB_AGERE_VENDOR_ID 0x0D4E /* Agere Systems */
#define USB_AGERE_MODEL0801_ID 0x1000 /* Wireless USB Card Model 0801 */
#define USB_AGERE_MODEL0802_ID 0x1001 /* Wireless USB Card Model 0802 */
#define USB_AGERE_REBRANDED_ID 0x047A /* WLAN USB Card */
#define USB_ELSA_VENDOR_ID 0x05CC
#define USB_ELSA_AIRLANCER_ID 0x3100 /* ELSA AirLancer USB-11 */
#define USB_LEGEND_VENDOR_ID 0x0E7C
#define USB_LEGEND_JOYNET_ID 0x0300 /* Joynet WLAN USB Card */
#define USB_SAMSUNG_VENDOR_ID 0x04E8
#define USB_SAMSUNG_SEW2001U1_ID 0x5002 /* Samsung SEW-2001u Card */
#define USB_SAMSUNG_SEW2001U2_ID 0x5B11 /* Samsung SEW-2001u Card */
#define USB_SAMSUNG_SEW2003U_ID 0x7011 /* Samsung SEW-2003U Card */
#define USB_IGATE_VENDOR_ID 0x0681
#define USB_IGATE_IGATE_11M_ID 0x0012 /* I-GATE 11M USB Card */
#define USB_FUJITSU_VENDOR_ID 0x0BF8
#define USB_FUJITSU_E1100_ID 0x1002 /* connect2AIR WLAN E-1100 USB */
#define USB_2WIRE_VENDOR_ID 0x1630
#define USB_2WIRE_WIRELESS_ID 0xff81 /* 2Wire Wireless USB adapter */
#define EZUSB_REQUEST_FW_TRANS 0xA0
#define EZUSB_REQUEST_TRIGER 0xAA
#define EZUSB_REQUEST_TRIG_AC 0xAC
#define EZUSB_CPUCS_REG 0x7F92
#define EZUSB_RID_TX 0x0700
#define EZUSB_RID_RX 0x0701
#define EZUSB_RID_INIT1 0x0702
#define EZUSB_RID_ACK 0x0710
#define EZUSB_RID_READ_PDA 0x0800
#define EZUSB_RID_PROG_INIT 0x0852
#define EZUSB_RID_PROG_SET_ADDR 0x0853
#define EZUSB_RID_PROG_BYTES 0x0854
#define EZUSB_RID_PROG_END 0x0855
#define EZUSB_RID_DOCMD 0x0860
/* Recognize info frames */
#define EZUSB_IS_INFO(id) ((id >= 0xF000) && (id <= 0xF2FF))
#define EZUSB_MAGIC 0x0210
#define EZUSB_FRAME_DATA 1
#define EZUSB_FRAME_CONTROL 2
#define DEF_TIMEOUT (3*HZ)
#define BULK_BUF_SIZE 2048
#define MAX_DL_SIZE (BULK_BUF_SIZE - sizeof(struct ezusb_packet))
#define FW_BUF_SIZE 64
#define FW_VAR_OFFSET_PTR 0x359
#define FW_VAR_VALUE 0
#define FW_HOLE_START 0x100
#define FW_HOLE_END 0x300
struct ezusb_packet {
__le16 magic; /* 0x0210 */
u8 req_reply_count;
u8 ans_reply_count;
__le16 frame_type; /* 0x01 for data frames, 0x02 otherwise */
__le16 size; /* transport size */
__le16 crc; /* CRC up to here */
__le16 hermes_len;
__le16 hermes_rid;
u8 data[0];
} __packed;
/* Table of devices that work or may work with this driver */
static struct usb_device_id ezusb_table[] = {
{USB_DEVICE(USB_COMPAQ_VENDOR_ID, USB_COMPAQ_WL215_ID)},
{USB_DEVICE(USB_COMPAQ_VENDOR_ID, USB_HP_WL215_ID)},
{USB_DEVICE(USB_COMPAQ_VENDOR_ID, USB_COMPAQ_W200_ID)},
{USB_DEVICE(USB_MELCO_VENDOR_ID, USB_BUFFALO_L11_ID)},
{USB_DEVICE(USB_MELCO_VENDOR_ID, USB_BUFFALO_L11G_WR_ID)},
{USB_DEVICE(USB_MELCO_VENDOR_ID, USB_BUFFALO_L11G_ID)},
{USB_DEVICE(USB_LUCENT_VENDOR_ID, USB_LUCENT_ORINOCO_ID)},
{USB_DEVICE(USB_AVAYA8_VENDOR_ID, USB_AVAYA_WIRELESS_ID)},
{USB_DEVICE(USB_AVAYAE_VENDOR_ID, USB_AVAYA_WIRELESS_ID)},
{USB_DEVICE(USB_AGERE_VENDOR_ID, USB_AGERE_MODEL0801_ID)},
{USB_DEVICE(USB_AGERE_VENDOR_ID, USB_AGERE_MODEL0802_ID)},
{USB_DEVICE(USB_ELSA_VENDOR_ID, USB_ELSA_AIRLANCER_ID)},
{USB_DEVICE(USB_LEGEND_VENDOR_ID, USB_LEGEND_JOYNET_ID)},
{USB_DEVICE_VER(USB_SAMSUNG_VENDOR_ID, USB_SAMSUNG_SEW2001U1_ID,
0, 0)},
{USB_DEVICE(USB_SAMSUNG_VENDOR_ID, USB_SAMSUNG_SEW2001U2_ID)},
{USB_DEVICE(USB_SAMSUNG_VENDOR_ID, USB_SAMSUNG_SEW2003U_ID)},
{USB_DEVICE(USB_IGATE_VENDOR_ID, USB_IGATE_IGATE_11M_ID)},
{USB_DEVICE(USB_FUJITSU_VENDOR_ID, USB_FUJITSU_E1100_ID)},
{USB_DEVICE(USB_2WIRE_VENDOR_ID, USB_2WIRE_WIRELESS_ID)},
{USB_DEVICE(USB_AGERE_VENDOR_ID, USB_AGERE_REBRANDED_ID)},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, ezusb_table);
/* Structure to hold all of our device specific stuff */
struct ezusb_priv {
struct usb_device *udev;
struct net_device *dev;
struct mutex mtx;
spinlock_t req_lock;
struct list_head req_pending;
struct list_head req_active;
spinlock_t reply_count_lock;
u16 hermes_reg_fake[0x40];
u8 *bap_buf;
struct urb *read_urb;
int read_pipe;
int write_pipe;
u8 reply_count;
};
enum ezusb_state {
EZUSB_CTX_START,
EZUSB_CTX_QUEUED,
EZUSB_CTX_REQ_SUBMITTED,
EZUSB_CTX_REQ_COMPLETE,
EZUSB_CTX_RESP_RECEIVED,
EZUSB_CTX_REQ_TIMEOUT,
EZUSB_CTX_REQ_FAILED,
EZUSB_CTX_RESP_TIMEOUT,
EZUSB_CTX_REQSUBMIT_FAIL,
EZUSB_CTX_COMPLETE,
};
struct request_context {
struct list_head list;
atomic_t refcount;
struct completion done; /* Signals that CTX is dead */
int killed;
struct urb *outurb; /* OUT for req pkt */
struct ezusb_priv *upriv;
struct ezusb_packet *buf;
int buf_length;
struct timer_list timer; /* Timeout handling */
enum ezusb_state state; /* Current state */
/* the RID that we will wait for */
u16 out_rid;
u16 in_rid;
};
/* Forward declarations */
static void ezusb_ctx_complete(struct request_context *ctx);
static void ezusb_req_queue_run(struct ezusb_priv *upriv);
static void ezusb_bulk_in_callback(struct urb *urb);
static inline u8 ezusb_reply_inc(u8 count)
{
if (count < 0x7F)
return count + 1;
else
return 1;
}
static void ezusb_request_context_put(struct request_context *ctx)
{
if (!atomic_dec_and_test(&ctx->refcount))
return;
WARN_ON(!ctx->done.done);
BUG_ON(ctx->outurb->status == -EINPROGRESS);
BUG_ON(timer_pending(&ctx->timer));
usb_free_urb(ctx->outurb);
kfree(ctx->buf);
kfree(ctx);
}
static inline void ezusb_mod_timer(struct ezusb_priv *upriv,
struct timer_list *timer,
unsigned long expire)
{
if (!upriv->udev)
return;
mod_timer(timer, expire);
}
static void ezusb_request_timerfn(u_long _ctx)
{
struct request_context *ctx = (void *) _ctx;
ctx->outurb->transfer_flags |= URB_ASYNC_UNLINK;
if (usb_unlink_urb(ctx->outurb) == -EINPROGRESS) {
ctx->state = EZUSB_CTX_REQ_TIMEOUT;
} else {
ctx->state = EZUSB_CTX_RESP_TIMEOUT;
dbg("couldn't unlink");
atomic_inc(&ctx->refcount);
ctx->killed = 1;
ezusb_ctx_complete(ctx);
ezusb_request_context_put(ctx);
}
};
static struct request_context *ezusb_alloc_ctx(struct ezusb_priv *upriv,
u16 out_rid, u16 in_rid)
{
struct request_context *ctx;
ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
if (!ctx)
return NULL;
ctx->buf = kmalloc(BULK_BUF_SIZE, GFP_ATOMIC);
if (!ctx->buf) {
kfree(ctx);
return NULL;
}
ctx->outurb = usb_alloc_urb(0, GFP_ATOMIC);
if (!ctx->outurb) {
kfree(ctx->buf);
kfree(ctx);
return NULL;
}
ctx->upriv = upriv;
ctx->state = EZUSB_CTX_START;
ctx->out_rid = out_rid;
ctx->in_rid = in_rid;
atomic_set(&ctx->refcount, 1);
init_completion(&ctx->done);
init_timer(&ctx->timer);
ctx->timer.function = ezusb_request_timerfn;
ctx->timer.data = (u_long) ctx;
return ctx;
}
/* Hopefully the real complete_all will soon be exported, in the mean
* while this should work. */
static inline void ezusb_complete_all(struct completion *comp)
{
complete(comp);
complete(comp);
complete(comp);
complete(comp);
}
static void ezusb_ctx_complete(struct request_context *ctx)
{
struct ezusb_priv *upriv = ctx->upriv;
unsigned long flags;
spin_lock_irqsave(&upriv->req_lock, flags);
list_del_init(&ctx->list);
if (upriv->udev) {
spin_unlock_irqrestore(&upriv->req_lock, flags);
ezusb_req_queue_run(upriv);
spin_lock_irqsave(&upriv->req_lock, flags);
}
switch (ctx->state) {
case EZUSB_CTX_COMPLETE:
case EZUSB_CTX_REQSUBMIT_FAIL:
case EZUSB_CTX_REQ_FAILED:
case EZUSB_CTX_REQ_TIMEOUT:
case EZUSB_CTX_RESP_TIMEOUT:
spin_unlock_irqrestore(&upriv->req_lock, flags);
if ((ctx->out_rid == EZUSB_RID_TX) && upriv->dev) {
struct net_device *dev = upriv->dev;
struct orinoco_private *priv = ndev_priv(dev);
struct net_device_stats *stats = &priv->stats;
if (ctx->state != EZUSB_CTX_COMPLETE)
stats->tx_errors++;
else
stats->tx_packets++;
netif_wake_queue(dev);
}
ezusb_complete_all(&ctx->done);
ezusb_request_context_put(ctx);
break;
default:
spin_unlock_irqrestore(&upriv->req_lock, flags);
if (!upriv->udev) {
/* This is normal, as all request contexts get flushed
* when the device is disconnected */
err("Called, CTX not terminating, but device gone");
ezusb_complete_all(&ctx->done);
ezusb_request_context_put(ctx);
break;
}
err("Called, CTX not in terminating state.");
/* Things are really bad if this happens. Just leak
* the CTX because it may still be linked to the
* queue or the OUT urb may still be active.
* Just leaking at least prevents an Oops or Panic.
*/
break;
}
}
/**
* ezusb_req_queue_run:
* Description:
* Note: Only one active CTX at any one time, because there's no
* other (reliable) way to match the response URB to the correct
* CTX.
**/
static void ezusb_req_queue_run(struct ezusb_priv *upriv)
{
unsigned long flags;
struct request_context *ctx;
int result;
spin_lock_irqsave(&upriv->req_lock, flags);
if (!list_empty(&upriv->req_active))
goto unlock;
if (list_empty(&upriv->req_pending))
goto unlock;
ctx =
list_entry(upriv->req_pending.next, struct request_context,
list);
if (!ctx->upriv->udev)
goto unlock;
/* We need to split this off to avoid a race condition */
list_move_tail(&ctx->list, &upriv->req_active);
if (ctx->state == EZUSB_CTX_QUEUED) {
atomic_inc(&ctx->refcount);
result = usb_submit_urb(ctx->outurb, GFP_ATOMIC);
if (result) {
ctx->state = EZUSB_CTX_REQSUBMIT_FAIL;
spin_unlock_irqrestore(&upriv->req_lock, flags);
err("Fatal, failed to submit command urb."
" error=%d\n", result);
ezusb_ctx_complete(ctx);
ezusb_request_context_put(ctx);
goto done;
}
ctx->state = EZUSB_CTX_REQ_SUBMITTED;
ezusb_mod_timer(ctx->upriv, &ctx->timer,
jiffies + DEF_TIMEOUT);
}
unlock:
spin_unlock_irqrestore(&upriv->req_lock, flags);
done:
return;
}
static void ezusb_req_enqueue_run(struct ezusb_priv *upriv,
struct request_context *ctx)
{
unsigned long flags;
spin_lock_irqsave(&upriv->req_lock, flags);
if (!ctx->upriv->udev) {
spin_unlock_irqrestore(&upriv->req_lock, flags);
goto done;
}
atomic_inc(&ctx->refcount);
list_add_tail(&ctx->list, &upriv->req_pending);
spin_unlock_irqrestore(&upriv->req_lock, flags);
ctx->state = EZUSB_CTX_QUEUED;
ezusb_req_queue_run(upriv);
done:
return;
}
static void ezusb_request_out_callback(struct urb *urb)
{
unsigned long flags;
enum ezusb_state state;
struct request_context *ctx = urb->context;
struct ezusb_priv *upriv = ctx->upriv;
spin_lock_irqsave(&upriv->req_lock, flags);
del_timer(&ctx->timer);
if (ctx->killed) {
spin_unlock_irqrestore(&upriv->req_lock, flags);
pr_warning("interrupt called with dead ctx");
goto out;
}
state = ctx->state;
if (urb->status == 0) {
switch (state) {
case EZUSB_CTX_REQ_SUBMITTED:
if (ctx->in_rid) {
ctx->state = EZUSB_CTX_REQ_COMPLETE;
/* reply URB still pending */
ezusb_mod_timer(upriv, &ctx->timer,
jiffies + DEF_TIMEOUT);
spin_unlock_irqrestore(&upriv->req_lock,
flags);
break;
}
/* fall through */
case EZUSB_CTX_RESP_RECEIVED:
/* IN already received before this OUT-ACK */
ctx->state = EZUSB_CTX_COMPLETE;
spin_unlock_irqrestore(&upriv->req_lock, flags);
ezusb_ctx_complete(ctx);
break;
default:
spin_unlock_irqrestore(&upriv->req_lock, flags);
err("Unexpected state(0x%x, %d) in OUT URB",
state, urb->status);
break;
}
} else {
/* If someone cancels the OUT URB then its status
* should be either -ECONNRESET or -ENOENT.
*/
switch (state) {
case EZUSB_CTX_REQ_SUBMITTED:
case EZUSB_CTX_RESP_RECEIVED:
ctx->state = EZUSB_CTX_REQ_FAILED;
/* fall through */
case EZUSB_CTX_REQ_FAILED:
case EZUSB_CTX_REQ_TIMEOUT:
spin_unlock_irqrestore(&upriv->req_lock, flags);
ezusb_ctx_complete(ctx);
break;
default:
spin_unlock_irqrestore(&upriv->req_lock, flags);
err("Unexpected state(0x%x, %d) in OUT URB",
state, urb->status);
break;
}
}
out:
ezusb_request_context_put(ctx);
}
static void ezusb_request_in_callback(struct ezusb_priv *upriv,
struct urb *urb)
{
struct ezusb_packet *ans = urb->transfer_buffer;
struct request_context *ctx = NULL;
enum ezusb_state state;
unsigned long flags;
/* Find the CTX on the active queue that requested this URB */
spin_lock_irqsave(&upriv->req_lock, flags);
if (upriv->udev) {
struct list_head *item;
list_for_each(item, &upriv->req_active) {
struct request_context *c;
int reply_count;
c = list_entry(item, struct request_context, list);
reply_count =
ezusb_reply_inc(c->buf->req_reply_count);
if ((ans->ans_reply_count == reply_count)
&& (le16_to_cpu(ans->hermes_rid) == c->in_rid)) {
ctx = c;
break;
}
dbg("Skipped (0x%x/0x%x) (%d/%d)",
le16_to_cpu(ans->hermes_rid),
c->in_rid, ans->ans_reply_count, reply_count);
}
}
if (ctx == NULL) {
spin_unlock_irqrestore(&upriv->req_lock, flags);
err("%s: got unexpected RID: 0x%04X", __func__,
le16_to_cpu(ans->hermes_rid));
ezusb_req_queue_run(upriv);
return;
}
/* The data we want is in the in buffer, exchange */
urb->transfer_buffer = ctx->buf;
ctx->buf = (void *) ans;
ctx->buf_length = urb->actual_length;
state = ctx->state;
switch (state) {
case EZUSB_CTX_REQ_SUBMITTED:
/* We have received our response URB before
* our request has been acknowledged. Do NOT
* destroy our CTX yet, because our OUT URB
* is still alive ...
*/
ctx->state = EZUSB_CTX_RESP_RECEIVED;
spin_unlock_irqrestore(&upriv->req_lock, flags);
/* Let the machine continue running. */
break;
case EZUSB_CTX_REQ_COMPLETE:
/* This is the usual path: our request
* has already been acknowledged, and
* we have now received the reply.
*/
ctx->state = EZUSB_CTX_COMPLETE;
/* Stop the intimer */
del_timer(&ctx->timer);
spin_unlock_irqrestore(&upriv->req_lock, flags);
/* Call the completion handler */
ezusb_ctx_complete(ctx);
break;
default:
spin_unlock_irqrestore(&upriv->req_lock, flags);
pr_warning("Matched IN URB, unexpected context state(0x%x)",
state);
/* Throw this CTX away and try submitting another */
del_timer(&ctx->timer);
ctx->outurb->transfer_flags |= URB_ASYNC_UNLINK;
usb_unlink_urb(ctx->outurb);
ezusb_req_queue_run(upriv);
break;
} /* switch */
}
static void ezusb_req_ctx_wait(struct ezusb_priv *upriv,
struct request_context *ctx)
{
switch (ctx->state) {
case EZUSB_CTX_QUEUED:
case EZUSB_CTX_REQ_SUBMITTED:
case EZUSB_CTX_REQ_COMPLETE:
case EZUSB_CTX_RESP_RECEIVED:
if (in_softirq()) {
/* If we get called from a timer, timeout timers don't
* get the chance to run themselves. So we make sure
* that we don't sleep for ever */
int msecs = DEF_TIMEOUT * (1000 / HZ);
while (!ctx->done.done && msecs--)
udelay(1000);
} else {
wait_event_interruptible(ctx->done.wait,
ctx->done.done);
}
break;
default:
/* Done or failed - nothing to wait for */
break;
}
}
static inline u16 build_crc(struct ezusb_packet *data)
{
u16 crc = 0;
u8 *bytes = (u8 *)data;
int i;
for (i = 0; i < 8; i++)
crc = (crc << 1) + bytes[i];
return crc;
}
/**
* ezusb_fill_req:
*
* if data == NULL and length > 0 the data is assumed to be already in
* the target buffer and only the header is filled.
*
*/
static int ezusb_fill_req(struct ezusb_packet *req, u16 length, u16 rid,
const void *data, u16 frame_type, u8 reply_count)
{
int total_size = sizeof(*req) + length;
BUG_ON(total_size > BULK_BUF_SIZE);
req->magic = cpu_to_le16(EZUSB_MAGIC);
req->req_reply_count = reply_count;
req->ans_reply_count = 0;
req->frame_type = cpu_to_le16(frame_type);
req->size = cpu_to_le16(length + 4);
req->crc = cpu_to_le16(build_crc(req));
req->hermes_len = cpu_to_le16(HERMES_BYTES_TO_RECLEN(length));
req->hermes_rid = cpu_to_le16(rid);
if (data)
memcpy(req->data, data, length);
return total_size;
}
static int ezusb_submit_in_urb(struct ezusb_priv *upriv)
{
int retval = 0;
void *cur_buf = upriv->read_urb->transfer_buffer;
if (upriv->read_urb->status == -EINPROGRESS) {
dbg("urb busy, not resubmiting");
retval = -EBUSY;
goto exit;
}
usb_fill_bulk_urb(upriv->read_urb, upriv->udev, upriv->read_pipe,
cur_buf, BULK_BUF_SIZE,
ezusb_bulk_in_callback, upriv);
upriv->read_urb->transfer_flags = 0;
retval = usb_submit_urb(upriv->read_urb, GFP_ATOMIC);
if (retval)
err("%s submit failed %d", __func__, retval);
exit:
return retval;
}
static inline int ezusb_8051_cpucs(struct ezusb_priv *upriv, int reset)
{
u8 res_val = reset; /* avoid argument promotion */
if (!upriv->udev) {
err("%s: !upriv->udev", __func__);
return -EFAULT;
}
return usb_control_msg(upriv->udev,
usb_sndctrlpipe(upriv->udev, 0),
EZUSB_REQUEST_FW_TRANS,
USB_TYPE_VENDOR | USB_RECIP_DEVICE |
USB_DIR_OUT, EZUSB_CPUCS_REG, 0, &res_val,
sizeof(res_val), DEF_TIMEOUT);
}
static int ezusb_firmware_download(struct ezusb_priv *upriv,
struct ez_usb_fw *fw)
{
u8 fw_buffer[FW_BUF_SIZE];
int retval, addr;
int variant_offset;
/*
* This byte is 1 and should be replaced with 0. The offset is
* 0x10AD in version 0.0.6. The byte in question should follow
* the end of the code pointed to by the jump in the beginning
* of the firmware. Also, it is read by code located at 0x358.
*/
variant_offset = be16_to_cpup((__be16 *) &fw->code[FW_VAR_OFFSET_PTR]);
if (variant_offset >= fw->size) {
printk(KERN_ERR PFX "Invalid firmware variant offset: "
"0x%04x\n", variant_offset);
retval = -EINVAL;
goto fail;
}
retval = ezusb_8051_cpucs(upriv, 1);
if (retval < 0)
goto fail;
for (addr = 0; addr < fw->size; addr += FW_BUF_SIZE) {
/* 0x100-0x300 should be left alone, it contains card
* specific data, like USB enumeration information */
if ((addr >= FW_HOLE_START) && (addr < FW_HOLE_END))
continue;
memcpy(fw_buffer, &fw->code[addr], FW_BUF_SIZE);
if (variant_offset >= addr &&
variant_offset < addr + FW_BUF_SIZE) {
dbg("Patching card_variant byte at 0x%04X",
variant_offset);
fw_buffer[variant_offset - addr] = FW_VAR_VALUE;
}
retval = usb_control_msg(upriv->udev,
usb_sndctrlpipe(upriv->udev, 0),
EZUSB_REQUEST_FW_TRANS,
USB_TYPE_VENDOR | USB_RECIP_DEVICE
| USB_DIR_OUT,
addr, 0x0,
fw_buffer, FW_BUF_SIZE,
DEF_TIMEOUT);
if (retval < 0)
goto fail;
}
retval = ezusb_8051_cpucs(upriv, 0);
if (retval < 0)
goto fail;
goto exit;
fail:
printk(KERN_ERR PFX "Firmware download failed, error %d\n",
retval);
exit:
return retval;
}
static int ezusb_access_ltv(struct ezusb_priv *upriv,
struct request_context *ctx,
u16 length, const void *data, u16 frame_type,
void *ans_buff, int ans_size, u16 *ans_length)
{
int req_size;
int retval = 0;
enum ezusb_state state;
BUG_ON(in_irq());
if (!upriv->udev) {
dbg("Device disconnected");
return -ENODEV;
}
if (upriv->read_urb->status != -EINPROGRESS)
err("%s: in urb not pending", __func__);
/* protect upriv->reply_count, guarantee sequential numbers */
spin_lock_bh(&upriv->reply_count_lock);
req_size = ezusb_fill_req(ctx->buf, length, ctx->out_rid, data,
frame_type, upriv->reply_count);
usb_fill_bulk_urb(ctx->outurb, upriv->udev, upriv->write_pipe,
ctx->buf, req_size,
ezusb_request_out_callback, ctx);
if (ctx->in_rid)
upriv->reply_count = ezusb_reply_inc(upriv->reply_count);
ezusb_req_enqueue_run(upriv, ctx);
spin_unlock_bh(&upriv->reply_count_lock);
if (ctx->in_rid)
ezusb_req_ctx_wait(upriv, ctx);
state = ctx->state;
switch (state) {
case EZUSB_CTX_COMPLETE:
retval = ctx->outurb->status;
break;
case EZUSB_CTX_QUEUED:
case EZUSB_CTX_REQ_SUBMITTED:
if (!ctx->in_rid)
break;
default:
err("%s: Unexpected context state %d", __func__,
state);
/* fall though */
case EZUSB_CTX_REQ_TIMEOUT:
case EZUSB_CTX_REQ_FAILED:
case EZUSB_CTX_RESP_TIMEOUT:
case EZUSB_CTX_REQSUBMIT_FAIL:
printk(KERN_ERR PFX "Access failed, resetting (state %d,"
" reply_count %d)\n", state, upriv->reply_count);
upriv->reply_count = 0;
if (state == EZUSB_CTX_REQ_TIMEOUT
|| state == EZUSB_CTX_RESP_TIMEOUT) {
printk(KERN_ERR PFX "ctx timed out\n");
retval = -ETIMEDOUT;
} else {
printk(KERN_ERR PFX "ctx failed\n");
retval = -EFAULT;
}
goto exit;
break;
}
if (ctx->in_rid) {
struct ezusb_packet *ans = ctx->buf;
int exp_len;
if (ans->hermes_len != 0)
exp_len = le16_to_cpu(ans->hermes_len) * 2 + 12;
else
exp_len = 14;
if (exp_len != ctx->buf_length) {
err("%s: length mismatch for RID 0x%04x: "
"expected %d, got %d", __func__,
ctx->in_rid, exp_len, ctx->buf_length);
retval = -EIO;
goto exit;
}
if (ans_buff)
memcpy(ans_buff, ans->data,
min_t(int, exp_len, ans_size));
if (ans_length)
*ans_length = le16_to_cpu(ans->hermes_len);
}
exit:
ezusb_request_context_put(ctx);
return retval;
}
static int ezusb_write_ltv(hermes_t *hw, int bap, u16 rid,
u16 length, const void *data)
{
struct ezusb_priv *upriv = hw->priv;
u16 frame_type;
struct request_context *ctx;
if (length == 0)
return -EINVAL;
length = HERMES_RECLEN_TO_BYTES(length);
/* On memory mapped devices HERMES_RID_CNFGROUPADDRESSES can be
* set to be empty, but the USB bridge doesn't like it */
if (length == 0)
return 0;
ctx = ezusb_alloc_ctx(upriv, rid, EZUSB_RID_ACK);
if (!ctx)
return -ENOMEM;
if (rid == EZUSB_RID_TX)
frame_type = EZUSB_FRAME_DATA;
else
frame_type = EZUSB_FRAME_CONTROL;
return ezusb_access_ltv(upriv, ctx, length, data, frame_type,
NULL, 0, NULL);
}
static int ezusb_read_ltv(hermes_t *hw, int bap, u16 rid,
unsigned bufsize, u16 *length, void *buf)
{
struct ezusb_priv *upriv = hw->priv;
struct request_context *ctx;
if ((bufsize < 0) || (bufsize % 2))
return -EINVAL;
ctx = ezusb_alloc_ctx(upriv, rid, rid);
if (!ctx)
return -ENOMEM;
return ezusb_access_ltv(upriv, ctx, 0, NULL, EZUSB_FRAME_CONTROL,
buf, bufsize, length);
}
static int ezusb_doicmd_wait(hermes_t *hw, u16 cmd, u16 parm0, u16 parm1,
u16 parm2, struct hermes_response *resp)
{
struct ezusb_priv *upriv = hw->priv;
struct request_context *ctx;
__le16 data[4] = {
cpu_to_le16(cmd),
cpu_to_le16(parm0),
cpu_to_le16(parm1),
cpu_to_le16(parm2),
};
dbg("0x%04X, parm0 0x%04X, parm1 0x%04X, parm2 0x%04X",
cmd, parm0, parm1, parm2);
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_DOCMD, EZUSB_RID_ACK);
if (!ctx)
return -ENOMEM;
return ezusb_access_ltv(upriv, ctx, sizeof(data), &data,
EZUSB_FRAME_CONTROL, NULL, 0, NULL);
}
static int ezusb_docmd_wait(hermes_t *hw, u16 cmd, u16 parm0,
struct hermes_response *resp)
{
struct ezusb_priv *upriv = hw->priv;
struct request_context *ctx;
__le16 data[4] = {
cpu_to_le16(cmd),
cpu_to_le16(parm0),
0,
0,
};
dbg("0x%04X, parm0 0x%04X", cmd, parm0);
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_DOCMD, EZUSB_RID_ACK);
if (!ctx)
return -ENOMEM;
return ezusb_access_ltv(upriv, ctx, sizeof(data), &data,
EZUSB_FRAME_CONTROL, NULL, 0, NULL);
}
static int ezusb_bap_pread(struct hermes *hw, int bap,
void *buf, int len, u16 id, u16 offset)
{
struct ezusb_priv *upriv = hw->priv;
struct ezusb_packet *ans = (void *) upriv->read_urb->transfer_buffer;
int actual_length = upriv->read_urb->actual_length;
if (id == EZUSB_RID_RX) {
if ((sizeof(*ans) + offset + len) > actual_length) {
printk(KERN_ERR PFX "BAP read beyond buffer end "
"in rx frame\n");
return -EINVAL;
}
memcpy(buf, ans->data + offset, len);
return 0;
}
if (EZUSB_IS_INFO(id)) {
/* Include 4 bytes for length/type */
if ((sizeof(*ans) + offset + len - 4) > actual_length) {
printk(KERN_ERR PFX "BAP read beyond buffer end "
"in info frame\n");
return -EFAULT;
}
memcpy(buf, ans->data + offset - 4, len);
} else {
printk(KERN_ERR PFX "Unexpected fid 0x%04x\n", id);
return -EINVAL;
}
return 0;
}
static int ezusb_read_pda(struct hermes *hw, __le16 *pda,
u32 pda_addr, u16 pda_len)
{
struct ezusb_priv *upriv = hw->priv;
struct request_context *ctx;
__le16 data[] = {
cpu_to_le16(pda_addr & 0xffff),
cpu_to_le16(pda_len - 4)
};
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_READ_PDA, EZUSB_RID_READ_PDA);
if (!ctx)
return -ENOMEM;
/* wl_lkm does not include PDA size in the PDA area.
* We will pad the information into pda, so other routines
* don't have to be modified */
pda[0] = cpu_to_le16(pda_len - 2);
/* Includes CFG_PROD_DATA but not itself */
pda[1] = cpu_to_le16(0x0800); /* CFG_PROD_DATA */
return ezusb_access_ltv(upriv, ctx, sizeof(data), &data,
EZUSB_FRAME_CONTROL, &pda[2], pda_len - 4,
NULL);
}
static int ezusb_program_init(struct hermes *hw, u32 entry_point)
{
struct ezusb_priv *upriv = hw->priv;
struct request_context *ctx;
__le32 data = cpu_to_le32(entry_point);
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_PROG_INIT, EZUSB_RID_ACK);
if (!ctx)
return -ENOMEM;
return ezusb_access_ltv(upriv, ctx, sizeof(data), &data,
EZUSB_FRAME_CONTROL, NULL, 0, NULL);
}
static int ezusb_program_end(struct hermes *hw)
{
struct ezusb_priv *upriv = hw->priv;
struct request_context *ctx;
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_PROG_END, EZUSB_RID_ACK);
if (!ctx)
return -ENOMEM;
return ezusb_access_ltv(upriv, ctx, 0, NULL,
EZUSB_FRAME_CONTROL, NULL, 0, NULL);
}
static int ezusb_program_bytes(struct hermes *hw, const char *buf,
u32 addr, u32 len)
{
struct ezusb_priv *upriv = hw->priv;
struct request_context *ctx;
__le32 data = cpu_to_le32(addr);
int err;
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_PROG_SET_ADDR, EZUSB_RID_ACK);
if (!ctx)
return -ENOMEM;
err = ezusb_access_ltv(upriv, ctx, sizeof(data), &data,
EZUSB_FRAME_CONTROL, NULL, 0, NULL);
if (err)
return err;
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_PROG_BYTES, EZUSB_RID_ACK);
if (!ctx)
return -ENOMEM;
return ezusb_access_ltv(upriv, ctx, len, buf,
EZUSB_FRAME_CONTROL, NULL, 0, NULL);
}
static int ezusb_program(struct hermes *hw, const char *buf,
u32 addr, u32 len)
{
u32 ch_addr;
u32 ch_len;
int err = 0;
/* We can only send 2048 bytes out of the bulk xmit at a time,
* so we have to split any programming into chunks of <2048
* bytes. */
ch_len = (len < MAX_DL_SIZE) ? len : MAX_DL_SIZE;
ch_addr = addr;
while (ch_addr < (addr + len)) {
pr_debug("Programming subblock of length %d "
"to address 0x%08x. Data @ %p\n",
ch_len, ch_addr, &buf[ch_addr - addr]);
err = ezusb_program_bytes(hw, &buf[ch_addr - addr],
ch_addr, ch_len);
if (err)
break;
ch_addr += ch_len;
ch_len = ((addr + len - ch_addr) < MAX_DL_SIZE) ?
(addr + len - ch_addr) : MAX_DL_SIZE;
}
return err;
}
static netdev_tx_t ezusb_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct orinoco_private *priv = ndev_priv(dev);
struct net_device_stats *stats = &priv->stats;
struct ezusb_priv *upriv = priv->card;
u8 mic[MICHAEL_MIC_LEN+1];
int err = 0;
int tx_control;
unsigned long flags;
struct request_context *ctx;
u8 *buf;
int tx_size;
if (!netif_running(dev)) {
printk(KERN_ERR "%s: Tx on stopped device!\n",
dev->name);
return NETDEV_TX_BUSY;
}
if (netif_queue_stopped(dev)) {
printk(KERN_DEBUG "%s: Tx while transmitter busy!\n",
dev->name);
return NETDEV_TX_BUSY;
}
if (orinoco_lock(priv, &flags) != 0) {
printk(KERN_ERR
"%s: ezusb_xmit() called while hw_unavailable\n",
dev->name);
return NETDEV_TX_BUSY;
}
if (!netif_carrier_ok(dev) ||
(priv->iw_mode == NL80211_IFTYPE_MONITOR)) {
/* Oops, the firmware hasn't established a connection,
silently drop the packet (this seems to be the
safest approach). */
goto drop;
}
/* Check packet length */
if (skb->len < ETH_HLEN)
goto drop;
ctx = ezusb_alloc_ctx(upriv, EZUSB_RID_TX, 0);
if (!ctx)
goto busy;
memset(ctx->buf, 0, BULK_BUF_SIZE);
buf = ctx->buf->data;
tx_control = 0;
err = orinoco_process_xmit_skb(skb, dev, priv, &tx_control,
&mic[0]);
if (err)
goto drop;
{
__le16 *tx_cntl = (__le16 *)buf;
*tx_cntl = cpu_to_le16(tx_control);
buf += sizeof(*tx_cntl);
}
memcpy(buf, skb->data, skb->len);
buf += skb->len;
if (tx_control & HERMES_TXCTRL_MIC) {
u8 *m = mic;
/* Mic has been offset so it can be copied to an even
* address. We're copying eveything anyway, so we
* don't need to copy that first byte. */
if (skb->len % 2)
m++;
memcpy(buf, m, MICHAEL_MIC_LEN);
buf += MICHAEL_MIC_LEN;
}
/* Finally, we actually initiate the send */
netif_stop_queue(dev);
/* The card may behave better if we send evenly sized usb transfers */
tx_size = ALIGN(buf - ctx->buf->data, 2);
err = ezusb_access_ltv(upriv, ctx, tx_size, NULL,
EZUSB_FRAME_DATA, NULL, 0, NULL);
if (err) {
netif_start_queue(dev);
if (net_ratelimit())
printk(KERN_ERR "%s: Error %d transmitting packet\n",
dev->name, err);
goto busy;
}
dev->trans_start = jiffies;
stats->tx_bytes += skb->len;
goto ok;
drop:
stats->tx_errors++;
stats->tx_dropped++;
ok:
orinoco_unlock(priv, &flags);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
busy:
orinoco_unlock(priv, &flags);
return NETDEV_TX_BUSY;
}
static int ezusb_allocate(struct hermes *hw, u16 size, u16 *fid)
{
*fid = EZUSB_RID_TX;
return 0;
}
static int ezusb_hard_reset(struct orinoco_private *priv)
{
struct ezusb_priv *upriv = priv->card;
int retval = ezusb_8051_cpucs(upriv, 1);
if (retval < 0) {
err("Failed to reset");
return retval;
}
retval = ezusb_8051_cpucs(upriv, 0);
if (retval < 0) {
err("Failed to unreset");
return retval;
}
dbg("sending control message");
retval = usb_control_msg(upriv->udev,
usb_sndctrlpipe(upriv->udev, 0),
EZUSB_REQUEST_TRIGER,
USB_TYPE_VENDOR | USB_RECIP_DEVICE |
USB_DIR_OUT, 0x0, 0x0, NULL, 0,
DEF_TIMEOUT);
if (retval < 0) {
err("EZUSB_REQUEST_TRIGER failed retval %d", retval);
return retval;
}
#if 0
dbg("Sending EZUSB_REQUEST_TRIG_AC");
retval = usb_control_msg(upriv->udev,
usb_sndctrlpipe(upriv->udev, 0),
EZUSB_REQUEST_TRIG_AC,
USB_TYPE_VENDOR | USB_RECIP_DEVICE |
USB_DIR_OUT, 0x00FA, 0x0, NULL, 0,
DEF_TIMEOUT);
if (retval < 0) {
err("EZUSB_REQUEST_TRIG_AC failed retval %d", retval);
return retval;
}
#endif
return 0;
}
static int ezusb_init(hermes_t *hw)
{
struct ezusb_priv *upriv = hw->priv;
int retval;
BUG_ON(in_interrupt());
BUG_ON(!upriv);
upriv->reply_count = 0;
/* Write the MAGIC number on the simulated registers to keep
* orinoco.c happy */
hermes_write_regn(hw, SWSUPPORT0, HERMES_MAGIC);
hermes_write_regn(hw, RXFID, EZUSB_RID_RX);
usb_kill_urb(upriv->read_urb);
ezusb_submit_in_urb(upriv);
retval = ezusb_write_ltv(hw, 0, EZUSB_RID_INIT1,
HERMES_BYTES_TO_RECLEN(2), "\x10\x00");
if (retval < 0) {
printk(KERN_ERR PFX "EZUSB_RID_INIT1 error %d\n", retval);
return retval;
}
retval = ezusb_docmd_wait(hw, HERMES_CMD_INIT, 0, NULL);
if (retval < 0) {
printk(KERN_ERR PFX "HERMES_CMD_INIT error %d\n", retval);
return retval;
}
return 0;
}
static void ezusb_bulk_in_callback(struct urb *urb)
{
struct ezusb_priv *upriv = (struct ezusb_priv *) urb->context;
struct ezusb_packet *ans = urb->transfer_buffer;
u16 crc;
u16 hermes_rid;
if (upriv->udev == NULL) {
dbg("disconnected");
return;
}
if (urb->status == -ETIMEDOUT) {
/* When a device gets unplugged we get this every time
* we resubmit, flooding the logs. Since we don't use
* USB timeouts, it shouldn't happen any other time*/
pr_warning("%s: urb timed out, not resubmiting", __func__);
return;
}
if (urb->status == -ECONNABORTED) {
pr_warning("%s: connection abort, resubmiting urb",
__func__);
goto resubmit;
}
if ((urb->status == -EILSEQ)
|| (urb->status == -ENOENT)
|| (urb->status == -ECONNRESET)) {
dbg("status %d, not resubmiting", urb->status);
return;
}
if (urb->status)
dbg("status: %d length: %d",
urb->status, urb->actual_length);
if (urb->actual_length < sizeof(*ans)) {
err("%s: short read, ignoring", __func__);
goto resubmit;
}
crc = build_crc(ans);
if (le16_to_cpu(ans->crc) != crc) {
err("CRC error, ignoring packet");
goto resubmit;
}
hermes_rid = le16_to_cpu(ans->hermes_rid);
if ((hermes_rid != EZUSB_RID_RX) && !EZUSB_IS_INFO(hermes_rid)) {
ezusb_request_in_callback(upriv, urb);
} else if (upriv->dev) {
struct net_device *dev = upriv->dev;
struct orinoco_private *priv = ndev_priv(dev);
hermes_t *hw = &priv->hw;
if (hermes_rid == EZUSB_RID_RX) {
__orinoco_ev_rx(dev, hw);
} else {
hermes_write_regn(hw, INFOFID,
le16_to_cpu(ans->hermes_rid));
__orinoco_ev_info(dev, hw);
}
}
resubmit:
if (upriv->udev)
ezusb_submit_in_urb(upriv);
}
static inline void ezusb_delete(struct ezusb_priv *upriv)
{
struct net_device *dev;
struct list_head *item;
struct list_head *tmp_item;
unsigned long flags;
BUG_ON(in_interrupt());
BUG_ON(!upriv);
dev = upriv->dev;
mutex_lock(&upriv->mtx);
upriv->udev = NULL; /* No timer will be rearmed from here */
usb_kill_urb(upriv->read_urb);
spin_lock_irqsave(&upriv->req_lock, flags);
list_for_each_safe(item, tmp_item, &upriv->req_active) {
struct request_context *ctx;
int err;
ctx = list_entry(item, struct request_context, list);
atomic_inc(&ctx->refcount);
ctx->outurb->transfer_flags |= URB_ASYNC_UNLINK;
err = usb_unlink_urb(ctx->outurb);
spin_unlock_irqrestore(&upriv->req_lock, flags);
if (err == -EINPROGRESS)
wait_for_completion(&ctx->done);
del_timer_sync(&ctx->timer);
/* FIXME: there is an slight chance for the irq handler to
* be running */
if (!list_empty(&ctx->list))
ezusb_ctx_complete(ctx);
ezusb_request_context_put(ctx);
spin_lock_irqsave(&upriv->req_lock, flags);
}
spin_unlock_irqrestore(&upriv->req_lock, flags);
list_for_each_safe(item, tmp_item, &upriv->req_pending)
ezusb_ctx_complete(list_entry(item,
struct request_context, list));
if (upriv->read_urb && upriv->read_urb->status == -EINPROGRESS)
printk(KERN_ERR PFX "Some URB in progress\n");
mutex_unlock(&upriv->mtx);
if (upriv->read_urb) {
kfree(upriv->read_urb->transfer_buffer);
usb_free_urb(upriv->read_urb);
}
kfree(upriv->bap_buf);
if (upriv->dev) {
struct orinoco_private *priv = ndev_priv(upriv->dev);
orinoco_if_del(priv);
free_orinocodev(priv);
}
}
static void ezusb_lock_irqsave(spinlock_t *lock,
unsigned long *flags) __acquires(lock)
{
spin_lock_bh(lock);
}
static void ezusb_unlock_irqrestore(spinlock_t *lock,
unsigned long *flags) __releases(lock)
{
spin_unlock_bh(lock);
}
static void ezusb_lock_irq(spinlock_t *lock) __acquires(lock)
{
spin_lock_bh(lock);
}
static void ezusb_unlock_irq(spinlock_t *lock) __releases(lock)
{
spin_unlock_bh(lock);
}
static const struct hermes_ops ezusb_ops = {
.init = ezusb_init,
.cmd_wait = ezusb_docmd_wait,
.init_cmd_wait = ezusb_doicmd_wait,
.allocate = ezusb_allocate,
.read_ltv = ezusb_read_ltv,
.write_ltv = ezusb_write_ltv,
.bap_pread = ezusb_bap_pread,
.read_pda = ezusb_read_pda,
.program_init = ezusb_program_init,
.program_end = ezusb_program_end,
.program = ezusb_program,
.lock_irqsave = ezusb_lock_irqsave,
.unlock_irqrestore = ezusb_unlock_irqrestore,
.lock_irq = ezusb_lock_irq,
.unlock_irq = ezusb_unlock_irq,
};
static const struct net_device_ops ezusb_netdev_ops = {
.ndo_open = orinoco_open,
.ndo_stop = orinoco_stop,
.ndo_start_xmit = ezusb_xmit,
.ndo_set_multicast_list = orinoco_set_multicast_list,
.ndo_change_mtu = orinoco_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_tx_timeout = orinoco_tx_timeout,
.ndo_get_stats = orinoco_get_stats,
};
static int ezusb_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct orinoco_private *priv;
hermes_t *hw;
struct ezusb_priv *upriv = NULL;
struct usb_interface_descriptor *iface_desc;
struct usb_endpoint_descriptor *ep;
const struct firmware *fw_entry;
int retval = 0;
int i;
priv = alloc_orinocodev(sizeof(*upriv), &udev->dev,
ezusb_hard_reset, NULL);
if (!priv) {
err("Couldn't allocate orinocodev");
goto exit;
}
hw = &priv->hw;
upriv = priv->card;
mutex_init(&upriv->mtx);
spin_lock_init(&upriv->reply_count_lock);
spin_lock_init(&upriv->req_lock);
INIT_LIST_HEAD(&upriv->req_pending);
INIT_LIST_HEAD(&upriv->req_active);
upriv->udev = udev;
hw->iobase = (void __force __iomem *) &upriv->hermes_reg_fake;
hw->reg_spacing = HERMES_16BIT_REGSPACING;
hw->priv = upriv;
hw->ops = &ezusb_ops;
/* set up the endpoint information */
/* check out the endpoints */
iface_desc = &interface->altsetting[0].desc;
for (i = 0; i < iface_desc->bNumEndpoints; ++i) {
ep = &interface->altsetting[0].endpoint[i].desc;
if (((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
== USB_DIR_IN) &&
((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_BULK)) {
/* we found a bulk in endpoint */
if (upriv->read_urb != NULL) {
pr_warning("Found a second bulk in ep, ignored");
continue;
}
upriv->read_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!upriv->read_urb) {
err("No free urbs available");
goto error;
}
if (le16_to_cpu(ep->wMaxPacketSize) != 64)
pr_warning("bulk in: wMaxPacketSize!= 64");
if (ep->bEndpointAddress != (2 | USB_DIR_IN))
pr_warning("bulk in: bEndpointAddress: %d",
ep->bEndpointAddress);
upriv->read_pipe = usb_rcvbulkpipe(udev,
ep->
bEndpointAddress);
upriv->read_urb->transfer_buffer =
kmalloc(BULK_BUF_SIZE, GFP_KERNEL);
if (!upriv->read_urb->transfer_buffer) {
err("Couldn't allocate IN buffer");
goto error;
}
}
if (((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
== USB_DIR_OUT) &&
((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_BULK)) {
/* we found a bulk out endpoint */
if (upriv->bap_buf != NULL) {
pr_warning("Found a second bulk out ep, ignored");
continue;
}
if (le16_to_cpu(ep->wMaxPacketSize) != 64)
pr_warning("bulk out: wMaxPacketSize != 64");
if (ep->bEndpointAddress != 2)
pr_warning("bulk out: bEndpointAddress: %d",
ep->bEndpointAddress);
upriv->write_pipe = usb_sndbulkpipe(udev,
ep->
bEndpointAddress);
upriv->bap_buf = kmalloc(BULK_BUF_SIZE, GFP_KERNEL);
if (!upriv->bap_buf) {
err("Couldn't allocate bulk_out_buffer");
goto error;
}
}
}
if (!upriv->bap_buf || !upriv->read_urb) {
err("Didn't find the required bulk endpoints");
goto error;
}
if (request_firmware(&fw_entry, "orinoco_ezusb_fw",
&interface->dev) == 0) {
firmware.size = fw_entry->size;
firmware.code = fw_entry->data;
}
if (firmware.size && firmware.code) {
ezusb_firmware_download(upriv, &firmware);
} else {
err("No firmware to download");
goto error;
}
if (ezusb_hard_reset(priv) < 0) {
err("Cannot reset the device");
goto error;
}
/* If the firmware is already downloaded orinoco.c will call
* ezusb_init but if the firmware is not already there, that will make
* the kernel very unstable, so we try initializing here and quit in
* case of error */
if (ezusb_init(hw) < 0) {
err("Couldn't initialize the device");
err("Firmware may not be downloaded or may be wrong.");
goto error;
}
/* Initialise the main driver */
if (orinoco_init(priv) != 0) {
err("orinoco_init() failed\n");
goto error;
}
if (orinoco_if_add(priv, 0, 0, &ezusb_netdev_ops) != 0) {
upriv->dev = NULL;
err("%s: orinoco_if_add() failed", __func__);
goto error;
}
upriv->dev = priv->ndev;
goto exit;
error:
ezusb_delete(upriv);
if (upriv->dev) {
/* upriv->dev was 0, so ezusb_delete() didn't free it */
free_orinocodev(priv);
}
upriv = NULL;
retval = -EFAULT;
exit:
if (fw_entry) {
firmware.code = NULL;
firmware.size = 0;
release_firmware(fw_entry);
}
usb_set_intfdata(interface, upriv);
return retval;
}
static void ezusb_disconnect(struct usb_interface *intf)
{
struct ezusb_priv *upriv = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
ezusb_delete(upriv);
printk(KERN_INFO PFX "Disconnected\n");
}
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver orinoco_driver = {
.name = DRIVER_NAME,
.probe = ezusb_probe,
.disconnect = ezusb_disconnect,
.id_table = ezusb_table,
};
/* Can't be declared "const" or the whole __initdata section will
* become const */
static char version[] __initdata = DRIVER_NAME " " DRIVER_VERSION
" (Manuel Estrada Sainz)";
static int __init ezusb_module_init(void)
{
int err;
printk(KERN_DEBUG "%s\n", version);
/* register this driver with the USB subsystem */
err = usb_register(&orinoco_driver);
if (err < 0) {
printk(KERN_ERR PFX "usb_register failed, error %d\n",
err);
return err;
}
return 0;
}
static void __exit ezusb_module_exit(void)
{
/* deregister this driver with the USB subsystem */
usb_deregister(&orinoco_driver);
}
module_init(ezusb_module_init);
module_exit(ezusb_module_exit);
MODULE_AUTHOR("Manuel Estrada Sainz");
MODULE_DESCRIPTION
("Driver for Orinoco wireless LAN cards using EZUSB bridge");
MODULE_LICENSE("Dual MPL/GPL");
| gpl-2.0 |
for811/Ubuntu_kernel_golfu | arch/arm/mach-mxs/devices/platform-mxs-mmc.c | 3080 | 1878 | /*
* Copyright (C) 2010 Pengutronix
* Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>
*
* Copyright 2011 Freescale Semiconductor, 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 version 2 as published by the
* Free Software Foundation.
*/
#include <linux/compiler.h>
#include <linux/err.h>
#include <linux/init.h>
#include <mach/mx23.h>
#include <mach/mx28.h>
#include <mach/devices-common.h>
#define mxs_mxs_mmc_data_entry_single(soc, _id, hwid) \
{ \
.id = _id, \
.iobase = soc ## _SSP ## hwid ## _BASE_ADDR, \
.dma = soc ## _DMA_SSP ## hwid, \
.irq_err = soc ## _INT_SSP ## hwid ## _ERROR, \
.irq_dma = soc ## _INT_SSP ## hwid ## _DMA, \
}
#define mxs_mxs_mmc_data_entry(soc, _id, hwid) \
[_id] = mxs_mxs_mmc_data_entry_single(soc, _id, hwid)
#ifdef CONFIG_SOC_IMX23
const struct mxs_mxs_mmc_data mx23_mxs_mmc_data[] __initconst = {
mxs_mxs_mmc_data_entry(MX23, 0, 1),
mxs_mxs_mmc_data_entry(MX23, 1, 2),
};
#endif
#ifdef CONFIG_SOC_IMX28
const struct mxs_mxs_mmc_data mx28_mxs_mmc_data[] __initconst = {
mxs_mxs_mmc_data_entry(MX28, 0, 0),
mxs_mxs_mmc_data_entry(MX28, 1, 1),
};
#endif
struct platform_device *__init mxs_add_mxs_mmc(
const struct mxs_mxs_mmc_data *data,
const struct mxs_mmc_platform_data *pdata)
{
struct resource res[] = {
{
.start = data->iobase,
.end = data->iobase + SZ_8K - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->dma,
.end = data->dma,
.flags = IORESOURCE_DMA,
}, {
.start = data->irq_err,
.end = data->irq_err,
.flags = IORESOURCE_IRQ,
}, {
.start = data->irq_dma,
.end = data->irq_dma,
.flags = IORESOURCE_IRQ,
},
};
return mxs_add_platform_device("mxs-mmc", data->id,
res, ARRAY_SIZE(res), pdata, sizeof(*pdata));
}
| gpl-2.0 |
skeevy420/android_kernel_lge_d850 | drivers/infiniband/ulp/ipoib/ipoib_main.c | 3336 | 34982 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) 2004 Voltaire, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "ipoib.h"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/vmalloc.h>
#include <linux/if_arp.h> /* For ARPHRD_xxx */
#include <linux/ip.h>
#include <linux/in.h>
#include <net/dst.h>
MODULE_AUTHOR("Roland Dreier");
MODULE_DESCRIPTION("IP-over-InfiniBand net driver");
MODULE_LICENSE("Dual BSD/GPL");
int ipoib_sendq_size __read_mostly = IPOIB_TX_RING_SIZE;
int ipoib_recvq_size __read_mostly = IPOIB_RX_RING_SIZE;
module_param_named(send_queue_size, ipoib_sendq_size, int, 0444);
MODULE_PARM_DESC(send_queue_size, "Number of descriptors in send queue");
module_param_named(recv_queue_size, ipoib_recvq_size, int, 0444);
MODULE_PARM_DESC(recv_queue_size, "Number of descriptors in receive queue");
#ifdef CONFIG_INFINIBAND_IPOIB_DEBUG
int ipoib_debug_level;
module_param_named(debug_level, ipoib_debug_level, int, 0644);
MODULE_PARM_DESC(debug_level, "Enable debug tracing if > 0");
#endif
struct ipoib_path_iter {
struct net_device *dev;
struct ipoib_path path;
};
static const u8 ipv4_bcast_addr[] = {
0x00, 0xff, 0xff, 0xff,
0xff, 0x12, 0x40, 0x1b, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff
};
struct workqueue_struct *ipoib_workqueue;
struct ib_sa_client ipoib_sa_client;
static void ipoib_add_one(struct ib_device *device);
static void ipoib_remove_one(struct ib_device *device);
static struct ib_client ipoib_client = {
.name = "ipoib",
.add = ipoib_add_one,
.remove = ipoib_remove_one
};
int ipoib_open(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg(priv, "bringing up interface\n");
set_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags);
if (ipoib_pkey_dev_delay_open(dev))
return 0;
if (ipoib_ib_dev_open(dev))
goto err_disable;
if (ipoib_ib_dev_up(dev))
goto err_stop;
if (!test_bit(IPOIB_FLAG_SUBINTERFACE, &priv->flags)) {
struct ipoib_dev_priv *cpriv;
/* Bring up any child interfaces too */
mutex_lock(&priv->vlan_mutex);
list_for_each_entry(cpriv, &priv->child_intfs, list) {
int flags;
flags = cpriv->dev->flags;
if (flags & IFF_UP)
continue;
dev_change_flags(cpriv->dev, flags | IFF_UP);
}
mutex_unlock(&priv->vlan_mutex);
}
netif_start_queue(dev);
return 0;
err_stop:
ipoib_ib_dev_stop(dev, 1);
err_disable:
clear_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags);
return -EINVAL;
}
static int ipoib_stop(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg(priv, "stopping interface\n");
clear_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags);
netif_stop_queue(dev);
ipoib_ib_dev_down(dev, 0);
ipoib_ib_dev_stop(dev, 0);
if (!test_bit(IPOIB_FLAG_SUBINTERFACE, &priv->flags)) {
struct ipoib_dev_priv *cpriv;
/* Bring down any child interfaces too */
mutex_lock(&priv->vlan_mutex);
list_for_each_entry(cpriv, &priv->child_intfs, list) {
int flags;
flags = cpriv->dev->flags;
if (!(flags & IFF_UP))
continue;
dev_change_flags(cpriv->dev, flags & ~IFF_UP);
}
mutex_unlock(&priv->vlan_mutex);
}
return 0;
}
static netdev_features_t ipoib_fix_features(struct net_device *dev, netdev_features_t features)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
if (test_bit(IPOIB_FLAG_ADMIN_CM, &priv->flags))
features &= ~(NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_TSO);
return features;
}
static int ipoib_change_mtu(struct net_device *dev, int new_mtu)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
/* dev->mtu > 2K ==> connected mode */
if (ipoib_cm_admin_enabled(dev)) {
if (new_mtu > ipoib_cm_max_mtu(dev))
return -EINVAL;
if (new_mtu > priv->mcast_mtu)
ipoib_warn(priv, "mtu > %d will cause multicast packet drops.\n",
priv->mcast_mtu);
dev->mtu = new_mtu;
return 0;
}
if (new_mtu > IPOIB_UD_MTU(priv->max_ib_mtu))
return -EINVAL;
priv->admin_mtu = new_mtu;
dev->mtu = min(priv->mcast_mtu, priv->admin_mtu);
return 0;
}
static struct ipoib_path *__path_find(struct net_device *dev, void *gid)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct rb_node *n = priv->path_tree.rb_node;
struct ipoib_path *path;
int ret;
while (n) {
path = rb_entry(n, struct ipoib_path, rb_node);
ret = memcmp(gid, path->pathrec.dgid.raw,
sizeof (union ib_gid));
if (ret < 0)
n = n->rb_left;
else if (ret > 0)
n = n->rb_right;
else
return path;
}
return NULL;
}
static int __path_add(struct net_device *dev, struct ipoib_path *path)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct rb_node **n = &priv->path_tree.rb_node;
struct rb_node *pn = NULL;
struct ipoib_path *tpath;
int ret;
while (*n) {
pn = *n;
tpath = rb_entry(pn, struct ipoib_path, rb_node);
ret = memcmp(path->pathrec.dgid.raw, tpath->pathrec.dgid.raw,
sizeof (union ib_gid));
if (ret < 0)
n = &pn->rb_left;
else if (ret > 0)
n = &pn->rb_right;
else
return -EEXIST;
}
rb_link_node(&path->rb_node, pn, n);
rb_insert_color(&path->rb_node, &priv->path_tree);
list_add_tail(&path->list, &priv->path_list);
return 0;
}
static void path_free(struct net_device *dev, struct ipoib_path *path)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_neigh *neigh, *tn;
struct sk_buff *skb;
unsigned long flags;
while ((skb = __skb_dequeue(&path->queue)))
dev_kfree_skb_irq(skb);
spin_lock_irqsave(&priv->lock, flags);
list_for_each_entry_safe(neigh, tn, &path->neigh_list, list) {
/*
* It's safe to call ipoib_put_ah() inside priv->lock
* here, because we know that path->ah will always
* hold one more reference, so ipoib_put_ah() will
* never do more than decrement the ref count.
*/
if (neigh->ah)
ipoib_put_ah(neigh->ah);
ipoib_neigh_free(dev, neigh);
}
spin_unlock_irqrestore(&priv->lock, flags);
if (path->ah)
ipoib_put_ah(path->ah);
kfree(path);
}
#ifdef CONFIG_INFINIBAND_IPOIB_DEBUG
struct ipoib_path_iter *ipoib_path_iter_init(struct net_device *dev)
{
struct ipoib_path_iter *iter;
iter = kmalloc(sizeof *iter, GFP_KERNEL);
if (!iter)
return NULL;
iter->dev = dev;
memset(iter->path.pathrec.dgid.raw, 0, 16);
if (ipoib_path_iter_next(iter)) {
kfree(iter);
return NULL;
}
return iter;
}
int ipoib_path_iter_next(struct ipoib_path_iter *iter)
{
struct ipoib_dev_priv *priv = netdev_priv(iter->dev);
struct rb_node *n;
struct ipoib_path *path;
int ret = 1;
spin_lock_irq(&priv->lock);
n = rb_first(&priv->path_tree);
while (n) {
path = rb_entry(n, struct ipoib_path, rb_node);
if (memcmp(iter->path.pathrec.dgid.raw, path->pathrec.dgid.raw,
sizeof (union ib_gid)) < 0) {
iter->path = *path;
ret = 0;
break;
}
n = rb_next(n);
}
spin_unlock_irq(&priv->lock);
return ret;
}
void ipoib_path_iter_read(struct ipoib_path_iter *iter,
struct ipoib_path *path)
{
*path = iter->path;
}
#endif /* CONFIG_INFINIBAND_IPOIB_DEBUG */
void ipoib_mark_paths_invalid(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_path *path, *tp;
spin_lock_irq(&priv->lock);
list_for_each_entry_safe(path, tp, &priv->path_list, list) {
ipoib_dbg(priv, "mark path LID 0x%04x GID %pI6 invalid\n",
be16_to_cpu(path->pathrec.dlid),
path->pathrec.dgid.raw);
path->valid = 0;
}
spin_unlock_irq(&priv->lock);
}
void ipoib_flush_paths(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_path *path, *tp;
LIST_HEAD(remove_list);
unsigned long flags;
netif_tx_lock_bh(dev);
spin_lock_irqsave(&priv->lock, flags);
list_splice_init(&priv->path_list, &remove_list);
list_for_each_entry(path, &remove_list, list)
rb_erase(&path->rb_node, &priv->path_tree);
list_for_each_entry_safe(path, tp, &remove_list, list) {
if (path->query)
ib_sa_cancel_query(path->query_id, path->query);
spin_unlock_irqrestore(&priv->lock, flags);
netif_tx_unlock_bh(dev);
wait_for_completion(&path->done);
path_free(dev, path);
netif_tx_lock_bh(dev);
spin_lock_irqsave(&priv->lock, flags);
}
spin_unlock_irqrestore(&priv->lock, flags);
netif_tx_unlock_bh(dev);
}
static void path_rec_completion(int status,
struct ib_sa_path_rec *pathrec,
void *path_ptr)
{
struct ipoib_path *path = path_ptr;
struct net_device *dev = path->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_ah *ah = NULL;
struct ipoib_ah *old_ah = NULL;
struct ipoib_neigh *neigh, *tn;
struct sk_buff_head skqueue;
struct sk_buff *skb;
unsigned long flags;
if (!status)
ipoib_dbg(priv, "PathRec LID 0x%04x for GID %pI6\n",
be16_to_cpu(pathrec->dlid), pathrec->dgid.raw);
else
ipoib_dbg(priv, "PathRec status %d for GID %pI6\n",
status, path->pathrec.dgid.raw);
skb_queue_head_init(&skqueue);
if (!status) {
struct ib_ah_attr av;
if (!ib_init_ah_from_path(priv->ca, priv->port, pathrec, &av))
ah = ipoib_create_ah(dev, priv->pd, &av);
}
spin_lock_irqsave(&priv->lock, flags);
if (!IS_ERR_OR_NULL(ah)) {
path->pathrec = *pathrec;
old_ah = path->ah;
path->ah = ah;
ipoib_dbg(priv, "created address handle %p for LID 0x%04x, SL %d\n",
ah, be16_to_cpu(pathrec->dlid), pathrec->sl);
while ((skb = __skb_dequeue(&path->queue)))
__skb_queue_tail(&skqueue, skb);
list_for_each_entry_safe(neigh, tn, &path->neigh_list, list) {
if (neigh->ah) {
WARN_ON(neigh->ah != old_ah);
/*
* Dropping the ah reference inside
* priv->lock is safe here, because we
* will hold one more reference from
* the original value of path->ah (ie
* old_ah).
*/
ipoib_put_ah(neigh->ah);
}
kref_get(&path->ah->ref);
neigh->ah = path->ah;
memcpy(&neigh->dgid.raw, &path->pathrec.dgid.raw,
sizeof(union ib_gid));
if (ipoib_cm_enabled(dev, neigh->neighbour)) {
if (!ipoib_cm_get(neigh))
ipoib_cm_set(neigh, ipoib_cm_create_tx(dev,
path,
neigh));
if (!ipoib_cm_get(neigh)) {
list_del(&neigh->list);
if (neigh->ah)
ipoib_put_ah(neigh->ah);
ipoib_neigh_free(dev, neigh);
continue;
}
}
while ((skb = __skb_dequeue(&neigh->queue)))
__skb_queue_tail(&skqueue, skb);
}
path->valid = 1;
}
path->query = NULL;
complete(&path->done);
spin_unlock_irqrestore(&priv->lock, flags);
if (old_ah)
ipoib_put_ah(old_ah);
while ((skb = __skb_dequeue(&skqueue))) {
skb->dev = dev;
if (dev_queue_xmit(skb))
ipoib_warn(priv, "dev_queue_xmit failed "
"to requeue packet\n");
}
}
static struct ipoib_path *path_rec_create(struct net_device *dev, void *gid)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_path *path;
if (!priv->broadcast)
return NULL;
path = kzalloc(sizeof *path, GFP_ATOMIC);
if (!path)
return NULL;
path->dev = dev;
skb_queue_head_init(&path->queue);
INIT_LIST_HEAD(&path->neigh_list);
memcpy(path->pathrec.dgid.raw, gid, sizeof (union ib_gid));
path->pathrec.sgid = priv->local_gid;
path->pathrec.pkey = cpu_to_be16(priv->pkey);
path->pathrec.numb_path = 1;
path->pathrec.traffic_class = priv->broadcast->mcmember.traffic_class;
return path;
}
static int path_rec_start(struct net_device *dev,
struct ipoib_path *path)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg(priv, "Start path record lookup for %pI6\n",
path->pathrec.dgid.raw);
init_completion(&path->done);
path->query_id =
ib_sa_path_rec_get(&ipoib_sa_client, priv->ca, priv->port,
&path->pathrec,
IB_SA_PATH_REC_DGID |
IB_SA_PATH_REC_SGID |
IB_SA_PATH_REC_NUMB_PATH |
IB_SA_PATH_REC_TRAFFIC_CLASS |
IB_SA_PATH_REC_PKEY,
1000, GFP_ATOMIC,
path_rec_completion,
path, &path->query);
if (path->query_id < 0) {
ipoib_warn(priv, "ib_sa_path_rec_get failed: %d\n", path->query_id);
path->query = NULL;
complete(&path->done);
return path->query_id;
}
return 0;
}
/* called with rcu_read_lock */
static void neigh_add_path(struct sk_buff *skb, struct neighbour *n, struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_path *path;
struct ipoib_neigh *neigh;
unsigned long flags;
neigh = ipoib_neigh_alloc(n, skb->dev);
if (!neigh) {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
return;
}
spin_lock_irqsave(&priv->lock, flags);
path = __path_find(dev, n->ha + 4);
if (!path) {
path = path_rec_create(dev, n->ha + 4);
if (!path)
goto err_path;
__path_add(dev, path);
}
list_add_tail(&neigh->list, &path->neigh_list);
if (path->ah) {
kref_get(&path->ah->ref);
neigh->ah = path->ah;
memcpy(&neigh->dgid.raw, &path->pathrec.dgid.raw,
sizeof(union ib_gid));
if (ipoib_cm_enabled(dev, neigh->neighbour)) {
if (!ipoib_cm_get(neigh))
ipoib_cm_set(neigh, ipoib_cm_create_tx(dev, path, neigh));
if (!ipoib_cm_get(neigh)) {
list_del(&neigh->list);
if (neigh->ah)
ipoib_put_ah(neigh->ah);
ipoib_neigh_free(dev, neigh);
goto err_drop;
}
if (skb_queue_len(&neigh->queue) < IPOIB_MAX_PATH_REC_QUEUE)
__skb_queue_tail(&neigh->queue, skb);
else {
ipoib_warn(priv, "queue length limit %d. Packet drop.\n",
skb_queue_len(&neigh->queue));
goto err_drop;
}
} else {
spin_unlock_irqrestore(&priv->lock, flags);
ipoib_send(dev, skb, path->ah, IPOIB_QPN(n->ha));
return;
}
} else {
neigh->ah = NULL;
if (!path->query && path_rec_start(dev, path))
goto err_list;
__skb_queue_tail(&neigh->queue, skb);
}
spin_unlock_irqrestore(&priv->lock, flags);
return;
err_list:
list_del(&neigh->list);
err_path:
ipoib_neigh_free(dev, neigh);
err_drop:
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
spin_unlock_irqrestore(&priv->lock, flags);
}
/* called with rcu_read_lock */
static void ipoib_path_lookup(struct sk_buff *skb, struct neighbour *n, struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(skb->dev);
/* Look up path record for unicasts */
if (n->ha[4] != 0xff) {
neigh_add_path(skb, n, dev);
return;
}
/* Add in the P_Key for multicasts */
n->ha[8] = (priv->pkey >> 8) & 0xff;
n->ha[9] = priv->pkey & 0xff;
ipoib_mcast_send(dev, n->ha + 4, skb);
}
static void unicast_arp_send(struct sk_buff *skb, struct net_device *dev,
struct ipoib_cb *cb)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_path *path;
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
path = __path_find(dev, cb->hwaddr + 4);
if (!path || !path->valid) {
int new_path = 0;
if (!path) {
path = path_rec_create(dev, cb->hwaddr + 4);
new_path = 1;
}
if (path) {
__skb_queue_tail(&path->queue, skb);
if (!path->query && path_rec_start(dev, path)) {
spin_unlock_irqrestore(&priv->lock, flags);
if (new_path)
path_free(dev, path);
return;
} else
__path_add(dev, path);
} else {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
}
spin_unlock_irqrestore(&priv->lock, flags);
return;
}
if (path->ah) {
ipoib_dbg(priv, "Send unicast ARP to %04x\n",
be16_to_cpu(path->pathrec.dlid));
spin_unlock_irqrestore(&priv->lock, flags);
ipoib_send(dev, skb, path->ah, IPOIB_QPN(cb->hwaddr));
return;
} else if ((path->query || !path_rec_start(dev, path)) &&
skb_queue_len(&path->queue) < IPOIB_MAX_PATH_REC_QUEUE) {
__skb_queue_tail(&path->queue, skb);
} else {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
}
spin_unlock_irqrestore(&priv->lock, flags);
}
static int ipoib_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_neigh *neigh;
struct neighbour *n = NULL;
unsigned long flags;
rcu_read_lock();
if (likely(skb_dst(skb))) {
n = dst_get_neighbour_noref(skb_dst(skb));
if (!n) {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
goto unlock;
}
}
if (likely(n)) {
if (unlikely(!*to_ipoib_neigh(n))) {
ipoib_path_lookup(skb, n, dev);
goto unlock;
}
neigh = *to_ipoib_neigh(n);
if (unlikely((memcmp(&neigh->dgid.raw,
n->ha + 4,
sizeof(union ib_gid))) ||
(neigh->dev != dev))) {
spin_lock_irqsave(&priv->lock, flags);
/*
* It's safe to call ipoib_put_ah() inside
* priv->lock here, because we know that
* path->ah will always hold one more reference,
* so ipoib_put_ah() will never do more than
* decrement the ref count.
*/
if (neigh->ah)
ipoib_put_ah(neigh->ah);
list_del(&neigh->list);
ipoib_neigh_free(dev, neigh);
spin_unlock_irqrestore(&priv->lock, flags);
ipoib_path_lookup(skb, n, dev);
goto unlock;
}
if (ipoib_cm_get(neigh)) {
if (ipoib_cm_up(neigh)) {
ipoib_cm_send(dev, skb, ipoib_cm_get(neigh));
goto unlock;
}
} else if (neigh->ah) {
ipoib_send(dev, skb, neigh->ah, IPOIB_QPN(n->ha));
goto unlock;
}
if (skb_queue_len(&neigh->queue) < IPOIB_MAX_PATH_REC_QUEUE) {
spin_lock_irqsave(&priv->lock, flags);
__skb_queue_tail(&neigh->queue, skb);
spin_unlock_irqrestore(&priv->lock, flags);
} else {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
}
} else {
struct ipoib_cb *cb = (struct ipoib_cb *) skb->cb;
if (cb->hwaddr[4] == 0xff) {
/* Add in the P_Key for multicast*/
cb->hwaddr[8] = (priv->pkey >> 8) & 0xff;
cb->hwaddr[9] = priv->pkey & 0xff;
ipoib_mcast_send(dev, cb->hwaddr + 4, skb);
} else {
/* unicast GID -- should be ARP or RARP reply */
if ((be16_to_cpup((__be16 *) skb->data) != ETH_P_ARP) &&
(be16_to_cpup((__be16 *) skb->data) != ETH_P_RARP)) {
ipoib_warn(priv, "Unicast, no %s: type %04x, QPN %06x %pI6\n",
skb_dst(skb) ? "neigh" : "dst",
be16_to_cpup((__be16 *) skb->data),
IPOIB_QPN(cb->hwaddr),
cb->hwaddr + 4);
dev_kfree_skb_any(skb);
++dev->stats.tx_dropped;
goto unlock;
}
unicast_arp_send(skb, dev, cb);
}
}
unlock:
rcu_read_unlock();
return NETDEV_TX_OK;
}
static void ipoib_timeout(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_warn(priv, "transmit timeout: latency %d msecs\n",
jiffies_to_msecs(jiffies - dev->trans_start));
ipoib_warn(priv, "queue stopped %d, tx_head %u, tx_tail %u\n",
netif_queue_stopped(dev),
priv->tx_head, priv->tx_tail);
/* XXX reset QP, etc. */
}
static int ipoib_hard_header(struct sk_buff *skb,
struct net_device *dev,
unsigned short type,
const void *daddr, const void *saddr, unsigned len)
{
struct ipoib_header *header;
header = (struct ipoib_header *) skb_push(skb, sizeof *header);
header->proto = htons(type);
header->reserved = 0;
/*
* If we don't have a dst_entry structure, stuff the
* destination address into skb->cb so we can figure out where
* to send the packet later.
*/
if (!skb_dst(skb)) {
struct ipoib_cb *cb = (struct ipoib_cb *) skb->cb;
memcpy(cb->hwaddr, daddr, INFINIBAND_ALEN);
}
return 0;
}
static void ipoib_set_mcast_list(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
if (!test_bit(IPOIB_FLAG_OPER_UP, &priv->flags)) {
ipoib_dbg(priv, "IPOIB_FLAG_OPER_UP not set");
return;
}
queue_work(ipoib_workqueue, &priv->restart_task);
}
static void ipoib_neigh_cleanup(struct neighbour *n)
{
struct ipoib_neigh *neigh;
struct ipoib_dev_priv *priv = netdev_priv(n->dev);
unsigned long flags;
struct ipoib_ah *ah = NULL;
neigh = *to_ipoib_neigh(n);
if (neigh)
priv = netdev_priv(neigh->dev);
else
return;
ipoib_dbg(priv,
"neigh_cleanup for %06x %pI6\n",
IPOIB_QPN(n->ha),
n->ha + 4);
spin_lock_irqsave(&priv->lock, flags);
if (neigh->ah)
ah = neigh->ah;
list_del(&neigh->list);
ipoib_neigh_free(n->dev, neigh);
spin_unlock_irqrestore(&priv->lock, flags);
if (ah)
ipoib_put_ah(ah);
}
struct ipoib_neigh *ipoib_neigh_alloc(struct neighbour *neighbour,
struct net_device *dev)
{
struct ipoib_neigh *neigh;
neigh = kmalloc(sizeof *neigh, GFP_ATOMIC);
if (!neigh)
return NULL;
neigh->neighbour = neighbour;
neigh->dev = dev;
memset(&neigh->dgid.raw, 0, sizeof (union ib_gid));
*to_ipoib_neigh(neighbour) = neigh;
skb_queue_head_init(&neigh->queue);
ipoib_cm_set(neigh, NULL);
return neigh;
}
void ipoib_neigh_free(struct net_device *dev, struct ipoib_neigh *neigh)
{
struct sk_buff *skb;
*to_ipoib_neigh(neigh->neighbour) = NULL;
while ((skb = __skb_dequeue(&neigh->queue))) {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
}
if (ipoib_cm_get(neigh))
ipoib_cm_destroy_tx(ipoib_cm_get(neigh));
kfree(neigh);
}
static int ipoib_neigh_setup_dev(struct net_device *dev, struct neigh_parms *parms)
{
parms->neigh_cleanup = ipoib_neigh_cleanup;
return 0;
}
int ipoib_dev_init(struct net_device *dev, struct ib_device *ca, int port)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
/* Allocate RX/TX "rings" to hold queued skbs */
priv->rx_ring = kzalloc(ipoib_recvq_size * sizeof *priv->rx_ring,
GFP_KERNEL);
if (!priv->rx_ring) {
printk(KERN_WARNING "%s: failed to allocate RX ring (%d entries)\n",
ca->name, ipoib_recvq_size);
goto out;
}
priv->tx_ring = vzalloc(ipoib_sendq_size * sizeof *priv->tx_ring);
if (!priv->tx_ring) {
printk(KERN_WARNING "%s: failed to allocate TX ring (%d entries)\n",
ca->name, ipoib_sendq_size);
goto out_rx_ring_cleanup;
}
/* priv->tx_head, tx_tail & tx_outstanding are already 0 */
if (ipoib_ib_dev_init(dev, ca, port))
goto out_tx_ring_cleanup;
return 0;
out_tx_ring_cleanup:
vfree(priv->tx_ring);
out_rx_ring_cleanup:
kfree(priv->rx_ring);
out:
return -ENOMEM;
}
void ipoib_dev_cleanup(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev), *cpriv, *tcpriv;
ipoib_delete_debug_files(dev);
/* Delete any child interfaces first */
list_for_each_entry_safe(cpriv, tcpriv, &priv->child_intfs, list) {
unregister_netdev(cpriv->dev);
ipoib_dev_cleanup(cpriv->dev);
free_netdev(cpriv->dev);
}
ipoib_ib_dev_cleanup(dev);
kfree(priv->rx_ring);
vfree(priv->tx_ring);
priv->rx_ring = NULL;
priv->tx_ring = NULL;
}
static const struct header_ops ipoib_header_ops = {
.create = ipoib_hard_header,
};
static const struct net_device_ops ipoib_netdev_ops = {
.ndo_open = ipoib_open,
.ndo_stop = ipoib_stop,
.ndo_change_mtu = ipoib_change_mtu,
.ndo_fix_features = ipoib_fix_features,
.ndo_start_xmit = ipoib_start_xmit,
.ndo_tx_timeout = ipoib_timeout,
.ndo_set_rx_mode = ipoib_set_mcast_list,
.ndo_neigh_setup = ipoib_neigh_setup_dev,
};
static void ipoib_setup(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
dev->netdev_ops = &ipoib_netdev_ops;
dev->header_ops = &ipoib_header_ops;
ipoib_set_ethtool_ops(dev);
netif_napi_add(dev, &priv->napi, ipoib_poll, 100);
dev->watchdog_timeo = HZ;
dev->flags |= IFF_BROADCAST | IFF_MULTICAST;
dev->hard_header_len = IPOIB_ENCAP_LEN;
dev->addr_len = INFINIBAND_ALEN;
dev->type = ARPHRD_INFINIBAND;
dev->tx_queue_len = ipoib_sendq_size * 2;
dev->features = (NETIF_F_VLAN_CHALLENGED |
NETIF_F_HIGHDMA);
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
memcpy(dev->broadcast, ipv4_bcast_addr, INFINIBAND_ALEN);
netif_carrier_off(dev);
priv->dev = dev;
spin_lock_init(&priv->lock);
mutex_init(&priv->vlan_mutex);
INIT_LIST_HEAD(&priv->path_list);
INIT_LIST_HEAD(&priv->child_intfs);
INIT_LIST_HEAD(&priv->dead_ahs);
INIT_LIST_HEAD(&priv->multicast_list);
INIT_DELAYED_WORK(&priv->pkey_poll_task, ipoib_pkey_poll);
INIT_DELAYED_WORK(&priv->mcast_task, ipoib_mcast_join_task);
INIT_WORK(&priv->carrier_on_task, ipoib_mcast_carrier_on_task);
INIT_WORK(&priv->flush_light, ipoib_ib_dev_flush_light);
INIT_WORK(&priv->flush_normal, ipoib_ib_dev_flush_normal);
INIT_WORK(&priv->flush_heavy, ipoib_ib_dev_flush_heavy);
INIT_WORK(&priv->restart_task, ipoib_mcast_restart_task);
INIT_DELAYED_WORK(&priv->ah_reap_task, ipoib_reap_ah);
}
struct ipoib_dev_priv *ipoib_intf_alloc(const char *name)
{
struct net_device *dev;
dev = alloc_netdev((int) sizeof (struct ipoib_dev_priv), name,
ipoib_setup);
if (!dev)
return NULL;
return netdev_priv(dev);
}
static ssize_t show_pkey(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ipoib_dev_priv *priv = netdev_priv(to_net_dev(dev));
return sprintf(buf, "0x%04x\n", priv->pkey);
}
static DEVICE_ATTR(pkey, S_IRUGO, show_pkey, NULL);
static ssize_t show_umcast(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ipoib_dev_priv *priv = netdev_priv(to_net_dev(dev));
return sprintf(buf, "%d\n", test_bit(IPOIB_FLAG_UMCAST, &priv->flags));
}
static ssize_t set_umcast(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ipoib_dev_priv *priv = netdev_priv(to_net_dev(dev));
unsigned long umcast_val = simple_strtoul(buf, NULL, 0);
if (umcast_val > 0) {
set_bit(IPOIB_FLAG_UMCAST, &priv->flags);
ipoib_warn(priv, "ignoring multicast groups joined directly "
"by userspace\n");
} else
clear_bit(IPOIB_FLAG_UMCAST, &priv->flags);
return count;
}
static DEVICE_ATTR(umcast, S_IWUSR | S_IRUGO, show_umcast, set_umcast);
int ipoib_add_umcast_attr(struct net_device *dev)
{
return device_create_file(&dev->dev, &dev_attr_umcast);
}
static ssize_t create_child(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int pkey;
int ret;
if (sscanf(buf, "%i", &pkey) != 1)
return -EINVAL;
if (pkey < 0 || pkey > 0xffff)
return -EINVAL;
/*
* Set the full membership bit, so that we join the right
* broadcast group, etc.
*/
pkey |= 0x8000;
ret = ipoib_vlan_add(to_net_dev(dev), pkey);
return ret ? ret : count;
}
static DEVICE_ATTR(create_child, S_IWUSR, NULL, create_child);
static ssize_t delete_child(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int pkey;
int ret;
if (sscanf(buf, "%i", &pkey) != 1)
return -EINVAL;
if (pkey < 0 || pkey > 0xffff)
return -EINVAL;
ret = ipoib_vlan_delete(to_net_dev(dev), pkey);
return ret ? ret : count;
}
static DEVICE_ATTR(delete_child, S_IWUSR, NULL, delete_child);
int ipoib_add_pkey_attr(struct net_device *dev)
{
return device_create_file(&dev->dev, &dev_attr_pkey);
}
int ipoib_set_dev_features(struct ipoib_dev_priv *priv, struct ib_device *hca)
{
struct ib_device_attr *device_attr;
int result = -ENOMEM;
device_attr = kmalloc(sizeof *device_attr, GFP_KERNEL);
if (!device_attr) {
printk(KERN_WARNING "%s: allocation of %zu bytes failed\n",
hca->name, sizeof *device_attr);
return result;
}
result = ib_query_device(hca, device_attr);
if (result) {
printk(KERN_WARNING "%s: ib_query_device failed (ret = %d)\n",
hca->name, result);
kfree(device_attr);
return result;
}
priv->hca_caps = device_attr->device_cap_flags;
kfree(device_attr);
if (priv->hca_caps & IB_DEVICE_UD_IP_CSUM) {
priv->dev->hw_features = NETIF_F_SG |
NETIF_F_IP_CSUM | NETIF_F_RXCSUM;
if (priv->hca_caps & IB_DEVICE_UD_TSO)
priv->dev->hw_features |= NETIF_F_TSO;
priv->dev->features |= priv->dev->hw_features;
}
return 0;
}
static struct net_device *ipoib_add_port(const char *format,
struct ib_device *hca, u8 port)
{
struct ipoib_dev_priv *priv;
struct ib_port_attr attr;
int result = -ENOMEM;
priv = ipoib_intf_alloc(format);
if (!priv)
goto alloc_mem_failed;
SET_NETDEV_DEV(priv->dev, hca->dma_device);
priv->dev->dev_id = port - 1;
if (!ib_query_port(hca, port, &attr))
priv->max_ib_mtu = ib_mtu_enum_to_int(attr.max_mtu);
else {
printk(KERN_WARNING "%s: ib_query_port %d failed\n",
hca->name, port);
goto device_init_failed;
}
/* MTU will be reset when mcast join happens */
priv->dev->mtu = IPOIB_UD_MTU(priv->max_ib_mtu);
priv->mcast_mtu = priv->admin_mtu = priv->dev->mtu;
priv->dev->neigh_priv_len = sizeof(struct ipoib_neigh);
result = ib_query_pkey(hca, port, 0, &priv->pkey);
if (result) {
printk(KERN_WARNING "%s: ib_query_pkey port %d failed (ret = %d)\n",
hca->name, port, result);
goto device_init_failed;
}
if (ipoib_set_dev_features(priv, hca))
goto device_init_failed;
/*
* Set the full membership bit, so that we join the right
* broadcast group, etc.
*/
priv->pkey |= 0x8000;
priv->dev->broadcast[8] = priv->pkey >> 8;
priv->dev->broadcast[9] = priv->pkey & 0xff;
result = ib_query_gid(hca, port, 0, &priv->local_gid);
if (result) {
printk(KERN_WARNING "%s: ib_query_gid port %d failed (ret = %d)\n",
hca->name, port, result);
goto device_init_failed;
} else
memcpy(priv->dev->dev_addr + 4, priv->local_gid.raw, sizeof (union ib_gid));
result = ipoib_dev_init(priv->dev, hca, port);
if (result < 0) {
printk(KERN_WARNING "%s: failed to initialize port %d (ret = %d)\n",
hca->name, port, result);
goto device_init_failed;
}
INIT_IB_EVENT_HANDLER(&priv->event_handler,
priv->ca, ipoib_event);
result = ib_register_event_handler(&priv->event_handler);
if (result < 0) {
printk(KERN_WARNING "%s: ib_register_event_handler failed for "
"port %d (ret = %d)\n",
hca->name, port, result);
goto event_failed;
}
result = register_netdev(priv->dev);
if (result) {
printk(KERN_WARNING "%s: couldn't register ipoib port %d; error %d\n",
hca->name, port, result);
goto register_failed;
}
ipoib_create_debug_files(priv->dev);
if (ipoib_cm_add_mode_attr(priv->dev))
goto sysfs_failed;
if (ipoib_add_pkey_attr(priv->dev))
goto sysfs_failed;
if (ipoib_add_umcast_attr(priv->dev))
goto sysfs_failed;
if (device_create_file(&priv->dev->dev, &dev_attr_create_child))
goto sysfs_failed;
if (device_create_file(&priv->dev->dev, &dev_attr_delete_child))
goto sysfs_failed;
return priv->dev;
sysfs_failed:
ipoib_delete_debug_files(priv->dev);
unregister_netdev(priv->dev);
register_failed:
ib_unregister_event_handler(&priv->event_handler);
flush_workqueue(ipoib_workqueue);
event_failed:
ipoib_dev_cleanup(priv->dev);
device_init_failed:
free_netdev(priv->dev);
alloc_mem_failed:
return ERR_PTR(result);
}
static void ipoib_add_one(struct ib_device *device)
{
struct list_head *dev_list;
struct net_device *dev;
struct ipoib_dev_priv *priv;
int s, e, p;
if (rdma_node_get_transport(device->node_type) != RDMA_TRANSPORT_IB)
return;
dev_list = kmalloc(sizeof *dev_list, GFP_KERNEL);
if (!dev_list)
return;
INIT_LIST_HEAD(dev_list);
if (device->node_type == RDMA_NODE_IB_SWITCH) {
s = 0;
e = 0;
} else {
s = 1;
e = device->phys_port_cnt;
}
for (p = s; p <= e; ++p) {
if (rdma_port_get_link_layer(device, p) != IB_LINK_LAYER_INFINIBAND)
continue;
dev = ipoib_add_port("ib%d", device, p);
if (!IS_ERR(dev)) {
priv = netdev_priv(dev);
list_add_tail(&priv->list, dev_list);
}
}
ib_set_client_data(device, &ipoib_client, dev_list);
}
static void ipoib_remove_one(struct ib_device *device)
{
struct ipoib_dev_priv *priv, *tmp;
struct list_head *dev_list;
if (rdma_node_get_transport(device->node_type) != RDMA_TRANSPORT_IB)
return;
dev_list = ib_get_client_data(device, &ipoib_client);
list_for_each_entry_safe(priv, tmp, dev_list, list) {
ib_unregister_event_handler(&priv->event_handler);
rtnl_lock();
dev_change_flags(priv->dev, priv->dev->flags & ~IFF_UP);
rtnl_unlock();
flush_workqueue(ipoib_workqueue);
unregister_netdev(priv->dev);
ipoib_dev_cleanup(priv->dev);
free_netdev(priv->dev);
}
kfree(dev_list);
}
static int __init ipoib_init_module(void)
{
int ret;
ipoib_recvq_size = roundup_pow_of_two(ipoib_recvq_size);
ipoib_recvq_size = min(ipoib_recvq_size, IPOIB_MAX_QUEUE_SIZE);
ipoib_recvq_size = max(ipoib_recvq_size, IPOIB_MIN_QUEUE_SIZE);
ipoib_sendq_size = roundup_pow_of_two(ipoib_sendq_size);
ipoib_sendq_size = min(ipoib_sendq_size, IPOIB_MAX_QUEUE_SIZE);
ipoib_sendq_size = max3(ipoib_sendq_size, 2 * MAX_SEND_CQE, IPOIB_MIN_QUEUE_SIZE);
#ifdef CONFIG_INFINIBAND_IPOIB_CM
ipoib_max_conn_qp = min(ipoib_max_conn_qp, IPOIB_CM_MAX_CONN_QP);
#endif
/*
* When copying small received packets, we only copy from the
* linear data part of the SKB, so we rely on this condition.
*/
BUILD_BUG_ON(IPOIB_CM_COPYBREAK > IPOIB_CM_HEAD_SIZE);
ret = ipoib_register_debugfs();
if (ret)
return ret;
/*
* We create our own workqueue mainly because we want to be
* able to flush it when devices are being removed. We can't
* use schedule_work()/flush_scheduled_work() because both
* unregister_netdev() and linkwatch_event take the rtnl lock,
* so flush_scheduled_work() can deadlock during device
* removal.
*/
ipoib_workqueue = create_singlethread_workqueue("ipoib");
if (!ipoib_workqueue) {
ret = -ENOMEM;
goto err_fs;
}
ib_sa_register_client(&ipoib_sa_client);
ret = ib_register_client(&ipoib_client);
if (ret)
goto err_sa;
return 0;
err_sa:
ib_sa_unregister_client(&ipoib_sa_client);
destroy_workqueue(ipoib_workqueue);
err_fs:
ipoib_unregister_debugfs();
return ret;
}
static void __exit ipoib_cleanup_module(void)
{
ib_unregister_client(&ipoib_client);
ib_sa_unregister_client(&ipoib_sa_client);
ipoib_unregister_debugfs();
destroy_workqueue(ipoib_workqueue);
}
module_init(ipoib_init_module);
module_exit(ipoib_cleanup_module);
| gpl-2.0 |
Seagate/SMR_FS-EXT4 | kernel/drivers/media/pci/cx18/cx18-av-vbi.c | 4616 | 8979 | /*
* cx18 ADEC VBI functions
*
* Derived from cx25840-vbi.c
*
* Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "cx18-driver.h"
/*
* For sliced VBI output, we set up to use VIP-1.1, 8-bit mode,
* NN counts 1 byte Dwords, an IDID with the VBI line # in it.
* Thus, according to the VIP-2 Spec, our VBI ancillary data lines
* (should!) look like:
* 4 byte EAV code: 0xff 0x00 0x00 0xRP
* unknown number of possible idle bytes
* 3 byte Anc data preamble: 0x00 0xff 0xff
* 1 byte data identifier: ne010iii (parity bits, 010, DID bits)
* 1 byte secondary data id: nessssss (parity bits, SDID bits)
* 1 byte data word count: necccccc (parity bits, NN Dword count)
* 2 byte Internal DID: VBI-line-# 0x80
* NN data bytes
* 1 byte checksum
* Fill bytes needed to fil out to 4*NN bytes of payload
*
* The RP codes for EAVs when in VIP-1.1 mode, not in raw mode, &
* in the vertical blanking interval are:
* 0xb0 (Task 0 VerticalBlank HorizontalBlank 0 0 0 0)
* 0xf0 (Task EvenField VerticalBlank HorizontalBlank 0 0 0 0)
*
* Since the V bit is only allowed to toggle in the EAV RP code, just
* before the first active region line and for active lines, they are:
* 0x90 (Task 0 0 HorizontalBlank 0 0 0 0)
* 0xd0 (Task EvenField 0 HorizontalBlank 0 0 0 0)
*
* The user application DID bytes we care about are:
* 0x91 (1 0 010 0 !ActiveLine AncDataPresent)
* 0x55 (0 1 010 2ndField !ActiveLine AncDataPresent)
*
*/
static const u8 sliced_vbi_did[2] = { 0x91, 0x55 };
struct vbi_anc_data {
/* u8 eav[4]; */
/* u8 idle[]; Variable number of idle bytes */
u8 preamble[3];
u8 did;
u8 sdid;
u8 data_count;
u8 idid[2];
u8 payload[1]; /* data_count of payload */
/* u8 checksum; */
/* u8 fill[]; Variable number of fill bytes */
};
static int odd_parity(u8 c)
{
c ^= (c >> 4);
c ^= (c >> 2);
c ^= (c >> 1);
return c & 1;
}
static int decode_vps(u8 *dst, u8 *p)
{
static const u8 biphase_tbl[] = {
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
0xd2, 0x5a, 0x52, 0xd2, 0x96, 0x1e, 0x16, 0x96,
0x92, 0x1a, 0x12, 0x92, 0xd2, 0x5a, 0x52, 0xd2,
0xd0, 0x58, 0x50, 0xd0, 0x94, 0x1c, 0x14, 0x94,
0x90, 0x18, 0x10, 0x90, 0xd0, 0x58, 0x50, 0xd0,
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
0xe1, 0x69, 0x61, 0xe1, 0xa5, 0x2d, 0x25, 0xa5,
0xa1, 0x29, 0x21, 0xa1, 0xe1, 0x69, 0x61, 0xe1,
0xc3, 0x4b, 0x43, 0xc3, 0x87, 0x0f, 0x07, 0x87,
0x83, 0x0b, 0x03, 0x83, 0xc3, 0x4b, 0x43, 0xc3,
0xc1, 0x49, 0x41, 0xc1, 0x85, 0x0d, 0x05, 0x85,
0x81, 0x09, 0x01, 0x81, 0xc1, 0x49, 0x41, 0xc1,
0xe1, 0x69, 0x61, 0xe1, 0xa5, 0x2d, 0x25, 0xa5,
0xa1, 0x29, 0x21, 0xa1, 0xe1, 0x69, 0x61, 0xe1,
0xe0, 0x68, 0x60, 0xe0, 0xa4, 0x2c, 0x24, 0xa4,
0xa0, 0x28, 0x20, 0xa0, 0xe0, 0x68, 0x60, 0xe0,
0xc2, 0x4a, 0x42, 0xc2, 0x86, 0x0e, 0x06, 0x86,
0x82, 0x0a, 0x02, 0x82, 0xc2, 0x4a, 0x42, 0xc2,
0xc0, 0x48, 0x40, 0xc0, 0x84, 0x0c, 0x04, 0x84,
0x80, 0x08, 0x00, 0x80, 0xc0, 0x48, 0x40, 0xc0,
0xe0, 0x68, 0x60, 0xe0, 0xa4, 0x2c, 0x24, 0xa4,
0xa0, 0x28, 0x20, 0xa0, 0xe0, 0x68, 0x60, 0xe0,
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
0xd2, 0x5a, 0x52, 0xd2, 0x96, 0x1e, 0x16, 0x96,
0x92, 0x1a, 0x12, 0x92, 0xd2, 0x5a, 0x52, 0xd2,
0xd0, 0x58, 0x50, 0xd0, 0x94, 0x1c, 0x14, 0x94,
0x90, 0x18, 0x10, 0x90, 0xd0, 0x58, 0x50, 0xd0,
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
};
u8 c, err = 0;
int i;
for (i = 0; i < 2 * 13; i += 2) {
err |= biphase_tbl[p[i]] | biphase_tbl[p[i + 1]];
c = (biphase_tbl[p[i + 1]] & 0xf) |
((biphase_tbl[p[i]] & 0xf) << 4);
dst[i / 2] = c;
}
return err & 0xf0;
}
int cx18_av_g_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi)
{
struct cx18 *cx = v4l2_get_subdevdata(sd);
struct cx18_av_state *state = &cx->av_state;
static const u16 lcr2vbi[] = {
0, V4L2_SLICED_TELETEXT_B, 0, /* 1 */
0, V4L2_SLICED_WSS_625, 0, /* 4 */
V4L2_SLICED_CAPTION_525, /* 6 */
0, 0, V4L2_SLICED_VPS, 0, 0, /* 9 */
0, 0, 0, 0
};
int is_pal = !(state->std & V4L2_STD_525_60);
int i;
memset(svbi->service_lines, 0, sizeof(svbi->service_lines));
svbi->service_set = 0;
/* we're done if raw VBI is active */
if ((cx18_av_read(cx, 0x404) & 0x10) == 0)
return 0;
if (is_pal) {
for (i = 7; i <= 23; i++) {
u8 v = cx18_av_read(cx, 0x424 + i - 7);
svbi->service_lines[0][i] = lcr2vbi[v >> 4];
svbi->service_lines[1][i] = lcr2vbi[v & 0xf];
svbi->service_set |= svbi->service_lines[0][i] |
svbi->service_lines[1][i];
}
} else {
for (i = 10; i <= 21; i++) {
u8 v = cx18_av_read(cx, 0x424 + i - 10);
svbi->service_lines[0][i] = lcr2vbi[v >> 4];
svbi->service_lines[1][i] = lcr2vbi[v & 0xf];
svbi->service_set |= svbi->service_lines[0][i] |
svbi->service_lines[1][i];
}
}
return 0;
}
int cx18_av_s_raw_fmt(struct v4l2_subdev *sd, struct v4l2_vbi_format *fmt)
{
struct cx18 *cx = v4l2_get_subdevdata(sd);
struct cx18_av_state *state = &cx->av_state;
/* Setup standard */
cx18_av_std_setup(cx);
/* VBI Offset */
cx18_av_write(cx, 0x47f, state->slicer_line_delay);
cx18_av_write(cx, 0x404, 0x2e);
return 0;
}
int cx18_av_s_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi)
{
struct cx18 *cx = v4l2_get_subdevdata(sd);
struct cx18_av_state *state = &cx->av_state;
int is_pal = !(state->std & V4L2_STD_525_60);
int i, x;
u8 lcr[24];
for (x = 0; x <= 23; x++)
lcr[x] = 0x00;
/* Setup standard */
cx18_av_std_setup(cx);
/* Sliced VBI */
cx18_av_write(cx, 0x404, 0x32); /* Ancillary data */
cx18_av_write(cx, 0x406, 0x13);
cx18_av_write(cx, 0x47f, state->slicer_line_delay);
/* Force impossible lines to 0 */
if (is_pal) {
for (i = 0; i <= 6; i++)
svbi->service_lines[0][i] =
svbi->service_lines[1][i] = 0;
} else {
for (i = 0; i <= 9; i++)
svbi->service_lines[0][i] =
svbi->service_lines[1][i] = 0;
for (i = 22; i <= 23; i++)
svbi->service_lines[0][i] =
svbi->service_lines[1][i] = 0;
}
/* Build register values for requested service lines */
for (i = 7; i <= 23; i++) {
for (x = 0; x <= 1; x++) {
switch (svbi->service_lines[1-x][i]) {
case V4L2_SLICED_TELETEXT_B:
lcr[i] |= 1 << (4 * x);
break;
case V4L2_SLICED_WSS_625:
lcr[i] |= 4 << (4 * x);
break;
case V4L2_SLICED_CAPTION_525:
lcr[i] |= 6 << (4 * x);
break;
case V4L2_SLICED_VPS:
lcr[i] |= 9 << (4 * x);
break;
}
}
}
if (is_pal) {
for (x = 1, i = 0x424; i <= 0x434; i++, x++)
cx18_av_write(cx, i, lcr[6 + x]);
} else {
for (x = 1, i = 0x424; i <= 0x430; i++, x++)
cx18_av_write(cx, i, lcr[9 + x]);
for (i = 0x431; i <= 0x434; i++)
cx18_av_write(cx, i, 0);
}
cx18_av_write(cx, 0x43c, 0x16);
/* Should match vblank set in cx18_av_std_setup() */
cx18_av_write(cx, 0x474, is_pal ? 38 : 26);
return 0;
}
int cx18_av_decode_vbi_line(struct v4l2_subdev *sd,
struct v4l2_decode_vbi_line *vbi)
{
struct cx18 *cx = v4l2_get_subdevdata(sd);
struct cx18_av_state *state = &cx->av_state;
struct vbi_anc_data *anc = (struct vbi_anc_data *)vbi->p;
u8 *p;
int did, sdid, l, err = 0;
/*
* Check for the ancillary data header for sliced VBI
*/
if (anc->preamble[0] ||
anc->preamble[1] != 0xff || anc->preamble[2] != 0xff ||
(anc->did != sliced_vbi_did[0] &&
anc->did != sliced_vbi_did[1])) {
vbi->line = vbi->type = 0;
return 0;
}
did = anc->did;
sdid = anc->sdid & 0xf;
l = anc->idid[0] & 0x3f;
l += state->slicer_line_offset;
p = anc->payload;
/* Decode the SDID set by the slicer */
switch (sdid) {
case 1:
sdid = V4L2_SLICED_TELETEXT_B;
break;
case 4:
sdid = V4L2_SLICED_WSS_625;
break;
case 6:
sdid = V4L2_SLICED_CAPTION_525;
err = !odd_parity(p[0]) || !odd_parity(p[1]);
break;
case 9:
sdid = V4L2_SLICED_VPS;
if (decode_vps(p, p) != 0)
err = 1;
break;
default:
sdid = 0;
err = 1;
break;
}
vbi->type = err ? 0 : sdid;
vbi->line = err ? 0 : l;
vbi->is_second_field = err ? 0 : (did == sliced_vbi_did[1]);
vbi->p = p;
return 0;
}
| gpl-2.0 |
ManhIT-CMB/SpaceX-Kernel-Exynos7420 | net/x25/sysctl_net_x25.c | 4616 | 1991 | /* -*- linux-c -*-
* sysctl_net_x25.c: sysctl interface to net X.25 subsystem.
*
* Begun April 1, 1996, Mike Shaver.
* Added /proc/sys/net/x25 directory entry (empty =) ). [MS]
*/
#include <linux/sysctl.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/netdevice.h>
#include <linux/init.h>
#include <net/x25.h>
static int min_timer[] = { 1 * HZ };
static int max_timer[] = { 300 * HZ };
static struct ctl_table_header *x25_table_header;
static struct ctl_table x25_table[] = {
{
.procname = "restart_request_timeout",
.data = &sysctl_x25_restart_request_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_timer,
.extra2 = &max_timer,
},
{
.procname = "call_request_timeout",
.data = &sysctl_x25_call_request_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_timer,
.extra2 = &max_timer,
},
{
.procname = "reset_request_timeout",
.data = &sysctl_x25_reset_request_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_timer,
.extra2 = &max_timer,
},
{
.procname = "clear_request_timeout",
.data = &sysctl_x25_clear_request_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_timer,
.extra2 = &max_timer,
},
{
.procname = "acknowledgement_hold_back_timeout",
.data = &sysctl_x25_ack_holdback_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_timer,
.extra2 = &max_timer,
},
{
.procname = "x25_forward",
.data = &sysctl_x25_forward,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ 0, },
};
void __init x25_register_sysctl(void)
{
x25_table_header = register_net_sysctl(&init_net, "net/x25", x25_table);
}
void x25_unregister_sysctl(void)
{
unregister_net_sysctl_table(x25_table_header);
}
| gpl-2.0 |
alexax66/LP-Kernel-a3ltexx | drivers/pcmcia/sa1100_shannon.c | 4616 | 2494 | /*
* drivers/pcmcia/sa1100_shannon.c
*
* PCMCIA implementation routines for Shannon
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <mach/shannon.h>
#include <asm/irq.h>
#include "sa1100_generic.h"
static int shannon_pcmcia_hw_init(struct soc_pcmcia_socket *skt)
{
/* All those are inputs */
GAFR &= ~(GPIO_GPIO(SHANNON_GPIO_EJECT_0) |
GPIO_GPIO(SHANNON_GPIO_EJECT_1) |
GPIO_GPIO(SHANNON_GPIO_RDY_0) |
GPIO_GPIO(SHANNON_GPIO_RDY_1));
if (skt->nr == 0) {
skt->stat[SOC_STAT_CD].gpio = SHANNON_GPIO_EJECT_0;
skt->stat[SOC_STAT_CD].name = "PCMCIA_CD_0";
skt->stat[SOC_STAT_RDY].gpio = SHANNON_GPIO_RDY_0;
skt->stat[SOC_STAT_RDY].name = "PCMCIA_RDY_0";
} else {
skt->stat[SOC_STAT_CD].gpio = SHANNON_GPIO_EJECT_1;
skt->stat[SOC_STAT_CD].name = "PCMCIA_CD_1";
skt->stat[SOC_STAT_RDY].gpio = SHANNON_GPIO_RDY_1;
skt->stat[SOC_STAT_RDY].name = "PCMCIA_RDY_1";
}
return 0;
}
static void
shannon_pcmcia_socket_state(struct soc_pcmcia_socket *skt,
struct pcmcia_state *state)
{
switch (skt->nr) {
case 0:
state->bvd1 = 1;
state->bvd2 = 1;
state->vs_3v = 1; /* FIXME Can only apply 3.3V on Shannon. */
state->vs_Xv = 0;
break;
case 1:
state->bvd1 = 1;
state->bvd2 = 1;
state->vs_3v = 1; /* FIXME Can only apply 3.3V on Shannon. */
state->vs_Xv = 0;
break;
}
}
static int
shannon_pcmcia_configure_socket(struct soc_pcmcia_socket *skt,
const socket_state_t *state)
{
switch (state->Vcc) {
case 0: /* power off */
printk(KERN_WARNING "%s(): CS asked for 0V, still applying 3.3V..\n", __func__);
break;
case 50:
printk(KERN_WARNING "%s(): CS asked for 5V, applying 3.3V..\n", __func__);
case 33:
break;
default:
printk(KERN_ERR "%s(): unrecognized Vcc %u\n",
__func__, state->Vcc);
return -1;
}
printk(KERN_WARNING "%s(): Warning, Can't perform reset\n", __func__);
/* Silently ignore Vpp, output enable, speaker enable. */
return 0;
}
static struct pcmcia_low_level shannon_pcmcia_ops = {
.owner = THIS_MODULE,
.hw_init = shannon_pcmcia_hw_init,
.socket_state = shannon_pcmcia_socket_state,
.configure_socket = shannon_pcmcia_configure_socket,
};
int pcmcia_shannon_init(struct device *dev)
{
int ret = -ENODEV;
if (machine_is_shannon())
ret = sa11xx_drv_pcmcia_probe(dev, &shannon_pcmcia_ops, 0, 2);
return ret;
}
| gpl-2.0 |
SudaMod-devices/android_kernel_google_msm | drivers/net/wireless/iwlwifi/iwl-io.c | 4872 | 8863 | /******************************************************************************
*
* Copyright(c) 2003 - 2012 Intel Corporation. All rights reserved.
*
* Portions of this file are derived from the ipw3945 project.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
*****************************************************************************/
#include <linux/delay.h>
#include <linux/device.h>
#include "iwl-io.h"
#include"iwl-csr.h"
#include "iwl-debug.h"
#define IWL_POLL_INTERVAL 10 /* microseconds */
static inline void __iwl_set_bit(struct iwl_trans *trans, u32 reg, u32 mask)
{
iwl_write32(trans, reg, iwl_read32(trans, reg) | mask);
}
static inline void __iwl_clear_bit(struct iwl_trans *trans, u32 reg, u32 mask)
{
iwl_write32(trans, reg, iwl_read32(trans, reg) & ~mask);
}
void iwl_set_bit(struct iwl_trans *trans, u32 reg, u32 mask)
{
unsigned long flags;
spin_lock_irqsave(&trans->reg_lock, flags);
__iwl_set_bit(trans, reg, mask);
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
void iwl_clear_bit(struct iwl_trans *trans, u32 reg, u32 mask)
{
unsigned long flags;
spin_lock_irqsave(&trans->reg_lock, flags);
__iwl_clear_bit(trans, reg, mask);
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
int iwl_poll_bit(struct iwl_trans *trans, u32 addr,
u32 bits, u32 mask, int timeout)
{
int t = 0;
do {
if ((iwl_read32(trans, addr) & mask) == (bits & mask))
return t;
udelay(IWL_POLL_INTERVAL);
t += IWL_POLL_INTERVAL;
} while (t < timeout);
return -ETIMEDOUT;
}
int iwl_grab_nic_access_silent(struct iwl_trans *trans)
{
int ret;
lockdep_assert_held(&trans->reg_lock);
/* this bit wakes up the NIC */
__iwl_set_bit(trans, CSR_GP_CNTRL,
CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
/*
* These bits say the device is running, and should keep running for
* at least a short while (at least as long as MAC_ACCESS_REQ stays 1),
* but they do not indicate that embedded SRAM is restored yet;
* 3945 and 4965 have volatile SRAM, and must save/restore contents
* to/from host DRAM when sleeping/waking for power-saving.
* Each direction takes approximately 1/4 millisecond; with this
* overhead, it's a good idea to grab and hold MAC_ACCESS_REQUEST if a
* series of register accesses are expected (e.g. reading Event Log),
* to keep device from sleeping.
*
* CSR_UCODE_DRV_GP1 register bit MAC_SLEEP == 0 indicates that
* SRAM is okay/restored. We don't check that here because this call
* is just for hardware register access; but GP1 MAC_SLEEP check is a
* good idea before accessing 3945/4965 SRAM (e.g. reading Event Log).
*
* 5000 series and later (including 1000 series) have non-volatile SRAM,
* and do not save/restore SRAM when power cycling.
*/
ret = iwl_poll_bit(trans, CSR_GP_CNTRL,
CSR_GP_CNTRL_REG_VAL_MAC_ACCESS_EN,
(CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY |
CSR_GP_CNTRL_REG_FLAG_GOING_TO_SLEEP), 15000);
if (ret < 0) {
iwl_write32(trans, CSR_RESET, CSR_RESET_REG_FLAG_FORCE_NMI);
return -EIO;
}
return 0;
}
bool iwl_grab_nic_access(struct iwl_trans *trans)
{
int ret = iwl_grab_nic_access_silent(trans);
if (unlikely(ret)) {
u32 val = iwl_read32(trans, CSR_GP_CNTRL);
WARN_ONCE(1, "Timeout waiting for hardware access "
"(CSR_GP_CNTRL 0x%08x)\n", val);
return false;
}
return true;
}
void iwl_release_nic_access(struct iwl_trans *trans)
{
lockdep_assert_held(&trans->reg_lock);
__iwl_clear_bit(trans, CSR_GP_CNTRL,
CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
/*
* Above we read the CSR_GP_CNTRL register, which will flush
* any previous writes, but we need the write that clears the
* MAC_ACCESS_REQ bit to be performed before any other writes
* scheduled on different CPUs (after we drop reg_lock).
*/
mmiowb();
}
u32 iwl_read_direct32(struct iwl_trans *trans, u32 reg)
{
u32 value;
unsigned long flags;
spin_lock_irqsave(&trans->reg_lock, flags);
iwl_grab_nic_access(trans);
value = iwl_read32(trans, reg);
iwl_release_nic_access(trans);
spin_unlock_irqrestore(&trans->reg_lock, flags);
return value;
}
void iwl_write_direct32(struct iwl_trans *trans, u32 reg, u32 value)
{
unsigned long flags;
spin_lock_irqsave(&trans->reg_lock, flags);
if (likely(iwl_grab_nic_access(trans))) {
iwl_write32(trans, reg, value);
iwl_release_nic_access(trans);
}
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
int iwl_poll_direct_bit(struct iwl_trans *trans, u32 addr, u32 mask,
int timeout)
{
int t = 0;
do {
if ((iwl_read_direct32(trans, addr) & mask) == mask)
return t;
udelay(IWL_POLL_INTERVAL);
t += IWL_POLL_INTERVAL;
} while (t < timeout);
return -ETIMEDOUT;
}
static inline u32 __iwl_read_prph(struct iwl_trans *trans, u32 reg)
{
iwl_write32(trans, HBUS_TARG_PRPH_RADDR, reg | (3 << 24));
return iwl_read32(trans, HBUS_TARG_PRPH_RDAT);
}
static inline void __iwl_write_prph(struct iwl_trans *trans, u32 addr, u32 val)
{
iwl_write32(trans, HBUS_TARG_PRPH_WADDR,
((addr & 0x0000FFFF) | (3 << 24)));
iwl_write32(trans, HBUS_TARG_PRPH_WDAT, val);
}
u32 iwl_read_prph(struct iwl_trans *trans, u32 reg)
{
unsigned long flags;
u32 val;
spin_lock_irqsave(&trans->reg_lock, flags);
iwl_grab_nic_access(trans);
val = __iwl_read_prph(trans, reg);
iwl_release_nic_access(trans);
spin_unlock_irqrestore(&trans->reg_lock, flags);
return val;
}
void iwl_write_prph(struct iwl_trans *trans, u32 addr, u32 val)
{
unsigned long flags;
spin_lock_irqsave(&trans->reg_lock, flags);
if (likely(iwl_grab_nic_access(trans))) {
__iwl_write_prph(trans, addr, val);
iwl_release_nic_access(trans);
}
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
void iwl_set_bits_prph(struct iwl_trans *trans, u32 reg, u32 mask)
{
unsigned long flags;
spin_lock_irqsave(&trans->reg_lock, flags);
if (likely(iwl_grab_nic_access(trans))) {
__iwl_write_prph(trans, reg,
__iwl_read_prph(trans, reg) | mask);
iwl_release_nic_access(trans);
}
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
void iwl_set_bits_mask_prph(struct iwl_trans *trans, u32 reg,
u32 bits, u32 mask)
{
unsigned long flags;
spin_lock_irqsave(&trans->reg_lock, flags);
if (likely(iwl_grab_nic_access(trans))) {
__iwl_write_prph(trans, reg,
(__iwl_read_prph(trans, reg) & mask) | bits);
iwl_release_nic_access(trans);
}
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
void iwl_clear_bits_prph(struct iwl_trans *trans, u32 reg, u32 mask)
{
unsigned long flags;
u32 val;
spin_lock_irqsave(&trans->reg_lock, flags);
if (likely(iwl_grab_nic_access(trans))) {
val = __iwl_read_prph(trans, reg);
__iwl_write_prph(trans, reg, (val & ~mask));
iwl_release_nic_access(trans);
}
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
void _iwl_read_targ_mem_words(struct iwl_trans *trans, u32 addr,
void *buf, int words)
{
unsigned long flags;
int offs;
u32 *vals = buf;
spin_lock_irqsave(&trans->reg_lock, flags);
if (likely(iwl_grab_nic_access(trans))) {
iwl_write32(trans, HBUS_TARG_MEM_RADDR, addr);
for (offs = 0; offs < words; offs++)
vals[offs] = iwl_read32(trans, HBUS_TARG_MEM_RDAT);
iwl_release_nic_access(trans);
}
spin_unlock_irqrestore(&trans->reg_lock, flags);
}
u32 iwl_read_targ_mem(struct iwl_trans *trans, u32 addr)
{
u32 value;
_iwl_read_targ_mem_words(trans, addr, &value, 1);
return value;
}
int _iwl_write_targ_mem_words(struct iwl_trans *trans, u32 addr,
void *buf, int words)
{
unsigned long flags;
int offs, result = 0;
u32 *vals = buf;
spin_lock_irqsave(&trans->reg_lock, flags);
if (likely(iwl_grab_nic_access(trans))) {
iwl_write32(trans, HBUS_TARG_MEM_WADDR, addr);
for (offs = 0; offs < words; offs++)
iwl_write32(trans, HBUS_TARG_MEM_WDAT, vals[offs]);
iwl_release_nic_access(trans);
} else
result = -EBUSY;
spin_unlock_irqrestore(&trans->reg_lock, flags);
return result;
}
int iwl_write_targ_mem(struct iwl_trans *trans, u32 addr, u32 val)
{
return _iwl_write_targ_mem_words(trans, addr, &val, 1);
}
| gpl-2.0 |
M1cha/lge-kernel-lproj | net/netfilter/xt_connlimit.c | 7688 | 8223 | /*
* netfilter module to limit the number of parallel tcp
* connections per IP address.
* (c) 2000 Gerd Knorr <kraxel@bytesex.org>
* Nov 2002: Martin Bene <martin.bene@icomedias.com>:
* only ignore TIME_WAIT or gone connections
* (C) CC Computer Consultants GmbH, 2007
*
* based on ...
*
* Kernel module to match connection tracking information.
* GPL (C) 1999 Rusty Russell (rusty@rustcorp.com.au).
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/jhash.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/netfilter/nf_conntrack_tcp.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_connlimit.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_tuple.h>
#include <net/netfilter/nf_conntrack_zones.h>
/* we will save the tuples of all connections we care about */
struct xt_connlimit_conn {
struct hlist_node node;
struct nf_conntrack_tuple tuple;
union nf_inet_addr addr;
};
struct xt_connlimit_data {
struct hlist_head iphash[256];
spinlock_t lock;
};
static u_int32_t connlimit_rnd __read_mostly;
static inline unsigned int connlimit_iphash(__be32 addr)
{
return jhash_1word((__force __u32)addr, connlimit_rnd) & 0xFF;
}
static inline unsigned int
connlimit_iphash6(const union nf_inet_addr *addr,
const union nf_inet_addr *mask)
{
union nf_inet_addr res;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(addr->ip6); ++i)
res.ip6[i] = addr->ip6[i] & mask->ip6[i];
return jhash2((u32 *)res.ip6, ARRAY_SIZE(res.ip6), connlimit_rnd) & 0xFF;
}
static inline bool already_closed(const struct nf_conn *conn)
{
if (nf_ct_protonum(conn) == IPPROTO_TCP)
return conn->proto.tcp.state == TCP_CONNTRACK_TIME_WAIT ||
conn->proto.tcp.state == TCP_CONNTRACK_CLOSE;
else
return 0;
}
static inline unsigned int
same_source_net(const union nf_inet_addr *addr,
const union nf_inet_addr *mask,
const union nf_inet_addr *u3, u_int8_t family)
{
if (family == NFPROTO_IPV4) {
return (addr->ip & mask->ip) == (u3->ip & mask->ip);
} else {
union nf_inet_addr lh, rh;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(addr->ip6); ++i) {
lh.ip6[i] = addr->ip6[i] & mask->ip6[i];
rh.ip6[i] = u3->ip6[i] & mask->ip6[i];
}
return memcmp(&lh.ip6, &rh.ip6, sizeof(lh.ip6)) == 0;
}
}
static int count_them(struct net *net,
struct xt_connlimit_data *data,
const struct nf_conntrack_tuple *tuple,
const union nf_inet_addr *addr,
const union nf_inet_addr *mask,
u_int8_t family)
{
const struct nf_conntrack_tuple_hash *found;
struct xt_connlimit_conn *conn;
struct hlist_node *pos, *n;
struct nf_conn *found_ct;
struct hlist_head *hash;
bool addit = true;
int matches = 0;
if (family == NFPROTO_IPV6)
hash = &data->iphash[connlimit_iphash6(addr, mask)];
else
hash = &data->iphash[connlimit_iphash(addr->ip & mask->ip)];
rcu_read_lock();
/* check the saved connections */
hlist_for_each_entry_safe(conn, pos, n, hash, node) {
found = nf_conntrack_find_get(net, NF_CT_DEFAULT_ZONE,
&conn->tuple);
found_ct = NULL;
if (found != NULL)
found_ct = nf_ct_tuplehash_to_ctrack(found);
if (found_ct != NULL &&
nf_ct_tuple_equal(&conn->tuple, tuple) &&
!already_closed(found_ct))
/*
* Just to be sure we have it only once in the list.
* We should not see tuples twice unless someone hooks
* this into a table without "-p tcp --syn".
*/
addit = false;
if (found == NULL) {
/* this one is gone */
hlist_del(&conn->node);
kfree(conn);
continue;
}
if (already_closed(found_ct)) {
/*
* we do not care about connections which are
* closed already -> ditch it
*/
nf_ct_put(found_ct);
hlist_del(&conn->node);
kfree(conn);
continue;
}
if (same_source_net(addr, mask, &conn->addr, family))
/* same source network -> be counted! */
++matches;
nf_ct_put(found_ct);
}
rcu_read_unlock();
if (addit) {
/* save the new connection in our list */
conn = kmalloc(sizeof(*conn), GFP_ATOMIC);
if (conn == NULL)
return -ENOMEM;
conn->tuple = *tuple;
conn->addr = *addr;
hlist_add_head(&conn->node, hash);
++matches;
}
return matches;
}
static bool
connlimit_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
struct net *net = dev_net(par->in ? par->in : par->out);
const struct xt_connlimit_info *info = par->matchinfo;
union nf_inet_addr addr;
struct nf_conntrack_tuple tuple;
const struct nf_conntrack_tuple *tuple_ptr = &tuple;
enum ip_conntrack_info ctinfo;
const struct nf_conn *ct;
int connections;
ct = nf_ct_get(skb, &ctinfo);
if (ct != NULL)
tuple_ptr = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
else if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
par->family, &tuple))
goto hotdrop;
if (par->family == NFPROTO_IPV6) {
const struct ipv6hdr *iph = ipv6_hdr(skb);
memcpy(&addr.ip6, (info->flags & XT_CONNLIMIT_DADDR) ?
&iph->daddr : &iph->saddr, sizeof(addr.ip6));
} else {
const struct iphdr *iph = ip_hdr(skb);
addr.ip = (info->flags & XT_CONNLIMIT_DADDR) ?
iph->daddr : iph->saddr;
}
spin_lock_bh(&info->data->lock);
connections = count_them(net, info->data, tuple_ptr, &addr,
&info->mask, par->family);
spin_unlock_bh(&info->data->lock);
if (connections < 0)
/* kmalloc failed, drop it entirely */
goto hotdrop;
return (connections > info->limit) ^
!!(info->flags & XT_CONNLIMIT_INVERT);
hotdrop:
par->hotdrop = true;
return false;
}
static int connlimit_mt_check(const struct xt_mtchk_param *par)
{
struct xt_connlimit_info *info = par->matchinfo;
unsigned int i;
int ret;
if (unlikely(!connlimit_rnd)) {
u_int32_t rand;
do {
get_random_bytes(&rand, sizeof(rand));
} while (!rand);
cmpxchg(&connlimit_rnd, 0, rand);
}
ret = nf_ct_l3proto_try_module_get(par->family);
if (ret < 0) {
pr_info("cannot load conntrack support for "
"address family %u\n", par->family);
return ret;
}
/* init private data */
info->data = kmalloc(sizeof(struct xt_connlimit_data), GFP_KERNEL);
if (info->data == NULL) {
nf_ct_l3proto_module_put(par->family);
return -ENOMEM;
}
spin_lock_init(&info->data->lock);
for (i = 0; i < ARRAY_SIZE(info->data->iphash); ++i)
INIT_HLIST_HEAD(&info->data->iphash[i]);
return 0;
}
static void connlimit_mt_destroy(const struct xt_mtdtor_param *par)
{
const struct xt_connlimit_info *info = par->matchinfo;
struct xt_connlimit_conn *conn;
struct hlist_node *pos, *n;
struct hlist_head *hash = info->data->iphash;
unsigned int i;
nf_ct_l3proto_module_put(par->family);
for (i = 0; i < ARRAY_SIZE(info->data->iphash); ++i) {
hlist_for_each_entry_safe(conn, pos, n, &hash[i], node) {
hlist_del(&conn->node);
kfree(conn);
}
}
kfree(info->data);
}
static struct xt_match connlimit_mt_reg[] __read_mostly = {
{
.name = "connlimit",
.revision = 0,
.family = NFPROTO_UNSPEC,
.checkentry = connlimit_mt_check,
.match = connlimit_mt,
.matchsize = sizeof(struct xt_connlimit_info),
.destroy = connlimit_mt_destroy,
.me = THIS_MODULE,
},
{
.name = "connlimit",
.revision = 1,
.family = NFPROTO_UNSPEC,
.checkentry = connlimit_mt_check,
.match = connlimit_mt,
.matchsize = sizeof(struct xt_connlimit_info),
.destroy = connlimit_mt_destroy,
.me = THIS_MODULE,
},
};
static int __init connlimit_mt_init(void)
{
return xt_register_matches(connlimit_mt_reg,
ARRAY_SIZE(connlimit_mt_reg));
}
static void __exit connlimit_mt_exit(void)
{
xt_unregister_matches(connlimit_mt_reg, ARRAY_SIZE(connlimit_mt_reg));
}
module_init(connlimit_mt_init);
module_exit(connlimit_mt_exit);
MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
MODULE_DESCRIPTION("Xtables: Number of connections matching");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_connlimit");
MODULE_ALIAS("ip6t_connlimit");
| gpl-2.0 |
3EleVen/android_kernel_motorola_ghost | arch/sh/boards/mach-lboxre2/setup.c | 8456 | 2009 | /*
* linux/arch/sh/boards/lbox/setup.c
*
* Copyright (C) 2007 Nobuhiro Iwamatsu
*
* NTT COMWARE L-BOX RE2 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.
*
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/ata_platform.h>
#include <asm/machvec.h>
#include <asm/addrspace.h>
#include <mach/lboxre2.h>
#include <asm/io.h>
static struct resource cf_ide_resources[] = {
[0] = {
.start = 0x1f0,
.end = 0x1f0 + 8 ,
.flags = IORESOURCE_IO,
},
[1] = {
.start = 0x1f0 + 0x206,
.end = 0x1f0 +8 + 0x206 + 8,
.flags = IORESOURCE_IO,
},
[2] = {
.start = IRQ_CF0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cf_ide_device = {
.name = "pata_platform",
.id = -1,
.num_resources = ARRAY_SIZE(cf_ide_resources),
.resource = cf_ide_resources,
};
static struct platform_device *lboxre2_devices[] __initdata = {
&cf_ide_device,
};
static int __init lboxre2_devices_setup(void)
{
u32 cf0_io_base; /* Boot CF base address */
pgprot_t prot;
unsigned long paddrbase, psize;
/* open I/O area window */
paddrbase = virt_to_phys((void*)PA_AREA5_IO);
psize = PAGE_SIZE;
prot = PAGE_KERNEL_PCC(1, _PAGE_PCC_IO16);
cf0_io_base = (u32)ioremap_prot(paddrbase, psize, pgprot_val(prot));
if (!cf0_io_base) {
printk(KERN_ERR "%s : can't open CF I/O window!\n" , __func__ );
return -ENOMEM;
}
cf_ide_resources[0].start += cf0_io_base ;
cf_ide_resources[0].end += cf0_io_base ;
cf_ide_resources[1].start += cf0_io_base ;
cf_ide_resources[1].end += cf0_io_base ;
return platform_add_devices(lboxre2_devices,
ARRAY_SIZE(lboxre2_devices));
}
device_initcall(lboxre2_devices_setup);
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_lboxre2 __initmv = {
.mv_name = "L-BOX RE2",
.mv_nr_irqs = 72,
.mv_init_irq = init_lboxre2_IRQ,
};
| gpl-2.0 |
rinrin-/cygwin-alternative | winsup/testsuite/winsup.api/ltp/time01.c | 9 | 6231 | /*
* Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/* $Id: time01.c,v 1.3 2003/01/24 01:09:39 cgf Exp $ */
/**********************************************************
*
* OS Test - Silicon Graphics, Inc.
*
* TEST IDENTIFIER : time01
*
* EXECUTED BY : anyone
*
* TEST TITLE : Basic test for time(2)
*
* PARENT DOCUMENT : usctpl01
*
* TEST CASE TOTAL : 1
*
* WALL CLOCK TIME : 1
*
* CPU TYPES : ALL
*
* AUTHOR : William Roske
*
* CO-PILOT : Dave Fenner
*
* DATE STARTED : 03/30/92
*
* INITIAL RELEASE : UNICOS 7.0
*
* TEST CASES
*
* 1.) time(2) returns...(See Description)
*
* INPUT SPECIFICATIONS
* The standard options for system call tests are accepted.
* (See the parse_opts(3) man page).
*
* OUTPUT SPECIFICATIONS
*
* DURATION
* Terminates - with frequency and infinite modes.
*
* SIGNALS
* Uses SIGUSR1 to pause before test if option set.
* (See the parse_opts(3) man page).
*
* RESOURCES
* None
*
* ENVIRONMENTAL NEEDS
* No run-time environmental needs.
*
* SPECIAL PROCEDURAL REQUIREMENTS
* None
*
* INTERCASE DEPENDENCIES
* None
*
* DETAILED DESCRIPTION
* This is a Phase I test for the time(2) system call. It is intended
* to provide a limited exposure of the system call, for now. It
* should/will be extended when full functional tests are written for
* time(2).
*
* Setup:
* Setup signal handling.
* Pause for SIGUSR1 if option specified.
*
* Test:
* Loop if the proper options are given.
* Execute system call
* Check return code, if system call failed (return=-1)
* Log the errno and Issue a FAIL message.
* Otherwise, Issue a PASS message.
*
* Cleanup:
* Print errno log and/or timing stats if options given
*
*
*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include "test.h"
#include "usctest.h"
extern void setup();
extern void cleanup();
const char *TCID="time01"; /* Test program identifier. */
int TST_TOTAL=1; /* Total number of test cases. */
extern int Tst_count; /* Test Case counter for tst_* routines */
int exp_enos[]={0, 0};
int
main(int ac, char **av)
{
int lc; /* loop counter */
const char *msg; /* message returned from parse_opts */
/***************************************************************
* parse standard options
***************************************************************/
if ( (msg=parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *) NULL )
tst_brkm(TBROK, cleanup, "OPTION PARSING ERROR - %s", msg);
/***************************************************************
* perform global setup for test
***************************************************************/
setup();
/* set the expected errnos... */
TEST_EXP_ENOS(exp_enos);
/***************************************************************
* check looping state if -c option given
***************************************************************/
for (lc=0; TEST_LOOPING(lc); lc++) {
/* reset Tst_count in case we are looping. */
Tst_count=0;
/*
* Call time(2)
*/
TEST(time(0));
/* check return code */
if ( TEST_RETURN == -1 ) {
TEST_ERROR_LOG(TEST_ERRNO);
tst_resm(TFAIL, "time(0) Failed, errno=%d : %s",
TEST_ERRNO, strerror(TEST_ERRNO));
} else {
/***************************************************************
* only perform functional verification if flag set (-f not given)
***************************************************************/
if ( STD_FUNCTIONAL_TEST ) {
/* No Verification test, yet... */
tst_resm(TPASS, "time(0) returned %d", TEST_RETURN);
}
}
} /* End for TEST_LOOPING */
/***************************************************************
* cleanup and exit
***************************************************************/
cleanup();
return 0;
} /* End main */
/***************************************************************
* setup() - performs all ONE TIME setup for this test.
***************************************************************/
void
setup()
{
void trapper();
/* capture signals */
tst_sig(NOFORK, DEF_HANDLER, cleanup);
/* Pause if that option was specified */
TEST_PAUSE;
} /* End setup() */
/***************************************************************
* cleanup() - performs all ONE TIME cleanup for this test at
* completion or premature exit.
***************************************************************/
void
cleanup()
{
/*
* print timing stats if that option was specified.
* print errno log if that option was specified.
*/
TEST_CLEANUP;
/* exit with return code appropriate for results */
tst_exit();
} /* End cleanup() */
| gpl-2.0 |
imaginegit/melody_kernel | drivers/misc/mediatek/combo_mt66xx/wmt/platform/vendor/wmt_plat.c | 9 | 28916 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/*! \file
\brief Declaration of library functions
Any definitions in this file will be shared among GLUE Layer and internal Driver Stack.
*/
/*******************************************************************************
* Copyright (c) 2009 MediaTek Inc.
*
* All rights reserved. Copying, compilation, modification, distribution
* or any other use whatsoever of this material is strictly prohibited
* except in accordance with a Software License Agreement with
* MediaTek Inc.
********************************************************************************
*/
/*******************************************************************************
* LEGAL DISCLAIMER
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND
* AGREES THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK
* SOFTWARE") RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE
* PROVIDED TO BUYER ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY
* DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE
* ANY WARRANTY WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY
* WHICH MAY BE USED BY, INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK
* SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY
* WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE
* FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION OR TO
* CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL
* BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT
* ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY
* BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT
* OF LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING
* THEREOF AND RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN
* FRANCISCO, CA, UNDER THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE
* (ICC).
********************************************************************************
*/
/*******************************************************************************
* C O M P I L E R F L A G S
********************************************************************************
*/
/*******************************************************************************
* M A C R O S
********************************************************************************
*/
#include <asm/mach-types.h>
#include <linux/delay.h>
#include <mach/gpio.h>
#include <mach/io.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/combo_mt66xx.h>
#if CONFIG_HAS_WAKELOCK
#include <linux/wakelock.h>
#define CFG_WMT_WAKELOCK_SUPPORT 1
#endif
#ifdef DFT_TAG
#undef DFT_TAG
#endif
#define DFT_TAG "[WMT-PLAT]"
/*******************************************************************************
* E X T E R N A L R E F E R E N C E S
********************************************************************************
*/
/*header files*/
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/spinlock.h>
/* MTK_WCN_COMBO header files */
#include "wmt_plat.h"
#include "wmt_exp.h"
#include "mtk_wcn_cmb_hw.h"
/*******************************************************************************
* C O N S T A N T S
********************************************************************************
*/
/*******************************************************************************
* D A T A T Y P E S
********************************************************************************
*/
/*******************************************************************************
* F U N C T I O N D E C L A R A T I O N S
********************************************************************************
*/
static VOID wmt_plat_bgf_eirq_cb (VOID);
static INT32 wmt_plat_ldo_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_pmu_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_rtc_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_rst_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_bgf_eint_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_wifi_eint_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_all_eint_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_uart_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_pcm_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_i2s_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_sdio_pin_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_gps_sync_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_gps_lna_ctrl (ENUM_PIN_STATE state);
static INT32 wmt_plat_dump_pin_conf (VOID);
extern int rk29sdk_wifi_power(int on);
extern int rk29sdk_wifi_set_carddetect(int val);
/*******************************************************************************
* P U B L I C D A T A
********************************************************************************
*/
UINT32 gWmtDbgLvl = WMT_LOG_ERR;//WMT_LOG_DBG;//xbw
unsigned int g_bgf_irq = -1;//bgf eint number
unsigned int g_sdio_irq = -1;//bgf eint number
static struct mtk_wmt_platform_data wmt_pdata;
/*******************************************************************************
* P R I V A T E D A T A
********************************************************************************
*/
#if CFG_WMT_WAKELOCK_SUPPORT
static OSAL_SLEEPABLE_LOCK gOsSLock;
static struct wake_lock wmtWakeLock;
#endif
irq_cb wmt_plat_bgf_irq_cb = NULL;
device_audio_if_cb wmt_plat_audio_if_cb = NULL;
const static fp_set_pin gfp_set_pin_table[] =
{
[PIN_LDO] = wmt_plat_ldo_ctrl,
[PIN_PMU] = wmt_plat_pmu_ctrl,
[PIN_RTC] = wmt_plat_rtc_ctrl,
[PIN_RST] = wmt_plat_rst_ctrl,
[PIN_BGF_EINT] = wmt_plat_bgf_eint_ctrl,
[PIN_WIFI_EINT] = wmt_plat_wifi_eint_ctrl,
[PIN_ALL_EINT] = wmt_plat_all_eint_ctrl,
[PIN_UART_GRP] = wmt_plat_uart_ctrl,
[PIN_PCM_GRP] = wmt_plat_pcm_ctrl,
[PIN_I2S_GRP] = wmt_plat_i2s_ctrl,
[PIN_SDIO_GRP] = wmt_plat_sdio_pin_ctrl,
[PIN_GPS_SYNC] = wmt_plat_gps_sync_ctrl,
[PIN_GPS_LNA] = wmt_plat_gps_lna_ctrl,
};
/*******************************************************************************
* F U N C T I O N S
********************************************************************************
*/
/*!
* \brief audio control callback function for CMB_STUB on ALPS
*
* A platform function required for dynamic binding with CMB_STUB on ALPS.
*
* \param state desired audio interface state to use
* \param flag audio interface control options
*
* \retval 0 operation success
* \retval -1 invalid parameters
* \retval < 0 error for operation fail
*/
INT32 wmt_plat_audio_ctrl (CMB_STUB_AIF_X state, CMB_STUB_AIF_CTRL ctrl)
{
INT32 iRet = 0;
UINT32 pinShare;
/* input sanity check */
if ( (CMB_STUB_AIF_MAX <= state)
|| (CMB_STUB_AIF_CTRL_MAX <= ctrl) ) {
iRet = -1;
WMT_ERR_FUNC("WMT-PLAT: invalid para, state(%d), ctrl(%d),iRet(%d) \n", state, ctrl, iRet);
return iRet;
}
if (0/*I2S/PCM share pin*/) {
// TODO: [FixMe][GeorgeKuo] how about MT6575? The following is applied to MT6573E1 only!!
pinShare = 1;
WMT_INFO_FUNC( "PCM/I2S pin share\n");
}
else{ //E1 later
pinShare = 0;
WMT_INFO_FUNC( "PCM/I2S pin seperate\n");
}
iRet = 0;
/* set host side first */
switch (state) {
case CMB_STUB_AIF_0:
/* BT_PCM_OFF & FM line in/out */
iRet += wmt_plat_gpio_ctrl(PIN_PCM_GRP, PIN_STA_DEINIT);
iRet += wmt_plat_gpio_ctrl(PIN_I2S_GRP, PIN_STA_DEINIT);
break;
case CMB_STUB_AIF_1:
iRet += wmt_plat_gpio_ctrl(PIN_PCM_GRP, PIN_STA_INIT);
iRet += wmt_plat_gpio_ctrl(PIN_I2S_GRP, PIN_STA_DEINIT);
break;
case CMB_STUB_AIF_2:
iRet += wmt_plat_gpio_ctrl(PIN_PCM_GRP, PIN_STA_DEINIT);
iRet += wmt_plat_gpio_ctrl(PIN_I2S_GRP, PIN_STA_INIT);
break;
case CMB_STUB_AIF_3:
iRet += wmt_plat_gpio_ctrl(PIN_PCM_GRP, PIN_STA_INIT);
iRet += wmt_plat_gpio_ctrl(PIN_I2S_GRP, PIN_STA_INIT);
break;
default:
/* FIXME: move to cust folder? */
WMT_ERR_FUNC("invalid state [%d]\n", state);
return -1;
break;
}
if (CMB_STUB_AIF_CTRL_EN == ctrl) {
WMT_INFO_FUNC("call chip aif setting \n");
/* need to control chip side GPIO */
//iRet += wmt_lib_set_aif(state, (pinShare) ? MTK_WCN_BOOL_TRUE : MTK_WCN_BOOL_FALSE);
if (NULL != wmt_plat_audio_if_cb)
{
iRet += (*wmt_plat_audio_if_cb)(state, (pinShare) ? MTK_WCN_BOOL_TRUE : MTK_WCN_BOOL_FALSE);
}
else
{
WMT_WARN_FUNC("wmt_plat_audio_if_cb is not registered \n");
iRet -= 1;
}
}
else {
WMT_INFO_FUNC("skip chip aif setting \n");
}
return iRet;
}
#if CFG_WMT_PS_SUPPORT
irqreturn_t bgf_irq_handler(int i, void *arg)
{
wmt_plat_bgf_eirq_cb();
return IRQ_HANDLED;
}
#endif
static VOID
wmt_plat_bgf_eirq_cb (VOID)
{
#if CFG_WMT_PS_SUPPORT
//#error "need to disable EINT here"
//wmt_lib_ps_irq_cb();
if (NULL != wmt_plat_bgf_irq_cb)
{
(*(wmt_plat_bgf_irq_cb))();
}
else
{
WMT_WARN_FUNC("WMT-PLAT: wmt_plat_bgf_irq_cb not registered\n");
}
#else
return;
#endif
}
VOID wmt_lib_plat_irq_cb_reg (irq_cb bgf_irq_cb)
{
wmt_plat_bgf_irq_cb = bgf_irq_cb;
}
VOID wmt_lib_plat_aif_cb_reg (device_audio_if_cb aif_ctrl_cb)
{
wmt_plat_audio_if_cb = aif_ctrl_cb;
}
void wmt_plat_gpio_init(struct platform_device *pdev)
{
struct mtk_wmt_platform_data *p = pdev->dev.platform_data;
wmt_pdata.pmu = p->pmu;
wmt_pdata.rst = p->rst;
wmt_pdata.bgf_int = p->bgf_int;
wmt_pdata.urt_cts = p->urt_cts;
wmt_pdata.rtc = p->rtc;
wmt_pdata.gps_sync = p->gps_sync;
wmt_pdata.gps_lna = p->gps_lna;
wmt_plat_dump_pin_conf();
}
INT32
wmt_plat_init (P_PWR_SEQ_TIME pPwrSeqTime)
{
//CMB_STUB_CB stub_cb;
/*PWR_SEQ_TIME pwr_seq_time;*/
INT32 iret = 0;
//stub_cb.aif_ctrl_cb = wmt_plat_audio_ctrl;
//stub_cb.func_ctrl_cb = wmt_plat_func_ctrl;
//stub_cb.size = sizeof(stub_cb);
/* register to cmb_stub */
//iret = mtk_wcn_cmb_stub_reg(&stub_cb);
/* init cmb_hw */
iret += mtk_wcn_cmb_hw_init(pPwrSeqTime);
/*init wmt function ctrl wakelock if wake lock is supported by host platform*/
#ifdef CFG_WMT_WAKELOCK_SUPPORT
wake_lock_init(&wmtWakeLock, WAKE_LOCK_SUSPEND, "wmtFuncCtrl");
osal_sleepable_lock_init(&gOsSLock);
#endif
WMT_DBG_FUNC("WMT-PLAT: ALPS platform init (%d)\n", iret);
return iret;
}
INT32
wmt_plat_deinit (VOID)
{
INT32 iret;
/* 1. de-init cmb_hw */
iret = mtk_wcn_cmb_hw_deinit();
/* 2. unreg to cmb_stub */
iret += mtk_wcn_cmb_stub_unreg();
/*3. wmt wakelock deinit*/
#ifdef CFG_WMT_WAKELOCK_SUPPORT
wake_lock_destroy(&wmtWakeLock);
osal_sleepable_lock_deinit(&gOsSLock);
WMT_DBG_FUNC("destroy wmtWakeLock\n");
#endif
WMT_DBG_FUNC("WMT-PLAT: ALPS platform init (%d)\n", iret);
return 0;
}
INT32 wmt_plat_sdio_ctrl (WMT_SDIO_SLOT_NUM sdioPortType, ENUM_FUNC_STATE on)
{
int ret = 0;
if (FUNC_OFF == on) {
/* add control logic here to generate SDIO CARD REMOVAL event to mmc/sd
* controller. SDIO card removal operation and remove success messages
* are expected.
*/
rk29sdk_wifi_power(0);
rk29sdk_wifi_set_carddetect(0);
}
else {
/* add control logic here to generate SDIO CARD INSERTION event to mmc/sd
* controller. SDIO card detection operation and detect success messages
* are expected.
*/
rk29sdk_wifi_power(1);
rk29sdk_wifi_set_carddetect(1);
}
//extern int omap_mmc_update_mtk_card_status(int state);
// ret = omap_mmc_update_mtk_card_status((FUNC_OFF == on)? 0: 1);
WMT_INFO_FUNC(KERN_INFO "%s, on=%d, ret=%d\n", __FUNCTION__, on, ret);
return ret;
}
#if 0
INT32
wmt_plat_irq_ctrl (
ENUM_FUNC_STATE state
)
{
return -1;
}
#endif
static INT32
wmt_plat_dump_pin_conf (VOID)
{
WMT_INFO_FUNC( "WMT pin configuration [pmu: %d, rst: %d, bgf: %d, cts: %d, rtc: %d, gps_lna:%d, gps_sync:%d]\n",
wmt_pdata.pmu,
wmt_pdata.rst,
wmt_pdata.bgf_int,
wmt_pdata.urt_cts,
wmt_pdata.rtc,
wmt_pdata.gps_lna,
wmt_pdata.gps_sync );
return 0;
}
INT32 wmt_plat_pwr_ctrl (
ENUM_FUNC_STATE state
)
{
INT32 ret = -1;
switch (state) {
case FUNC_ON:
// TODO:[ChangeFeature][George] always output this or by request throuth /proc or sysfs?
ret = mtk_wcn_cmb_hw_pwr_on();
break;
case FUNC_OFF:
ret = mtk_wcn_cmb_hw_pwr_off();
break;
case FUNC_RST:
ret = mtk_wcn_cmb_hw_rst();
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) in pwr_ctrl\n", state);
break;
}
return ret;
}
INT32 wmt_plat_ps_ctrl (ENUM_FUNC_STATE state)
{
return -1;
}
INT32
wmt_plat_eirq_ctrl (
ENUM_PIN_ID id,
ENUM_PIN_STATE state
)
{
INT32 iRet = 0;
int gpio_value=0;
// TODO: [ChangeFeature][GeorgeKuo]: use another function to handle this, as done in gpio_ctrls
if ( (PIN_STA_INIT != state )
&& (PIN_STA_DEINIT != state )
&& (PIN_STA_EINT_EN != state )
&& (PIN_STA_EINT_DIS != state ) ) {
iRet = -1;
WMT_WARN_FUNC("WMT-PLAT:invalid PIN_STATE(%d) in eirq_ctrl for PIN(%d), ret(%d) \n", state, id, iRet);
return iRet;
}
switch (id) {
case PIN_BGF_EINT:
if (PIN_STA_INIT == state) {
//iRet = request_irq(g_bgf_irq, bgf_irq_handler, IRQF_TRIGGER_LOW | IRQF_DISABLED, "MTK6620_BT", NULL);
gpio_value = gpio_get_value(g_bgf_irq);
printk("%d..%s: BGF_INT gpio_init value = %d ====mt6620===\n", __LINE__, __FUNCTION__, gpio_value );
iRet = request_irq(g_bgf_irq, bgf_irq_handler,
//(gpio_get_value(MT6620_GPIO_BGF_INT_B))?IRQF_TRIGGER_FALLING : IRQF_TRIGGER_RISING,
( (gpio_value)?IRQF_TRIGGER_LOW : IRQF_TRIGGER_HIGH ) |IRQF_DISABLED,
"MTK6620_BT", NULL);
if (iRet) {
WMT_INFO_FUNC("WMT-PLAT: request IRQ fail for BGF IRQ : %d\n", g_bgf_irq);
} else {
enable_irq_wake(g_bgf_irq);
}
WMT_INFO_FUNC("WMT-PLAT:BGF Int requested...%s, iRet=%d\n", iRet?"fail":"success.", iRet);
} else if (PIN_STA_EINT_EN == state) {
enable_irq(g_bgf_irq);
} else if (PIN_STA_EINT_DIS == state) {
disable_irq_nosync(g_bgf_irq);
} else {
disable_irq_wake(g_bgf_irq);
free_irq(g_bgf_irq,NULL);
WMT_INFO_FUNC("WMT-PLAT:BGFInt (deinit) \n");
}
break;
case PIN_ALL_EINT:
break;
case PIN_WIFI_EINT:
break;
default:
WMT_WARN_FUNC("WMT-PLAT:unsupported EIRQ(PIN_ID:%d) in eirq_ctrl\n", id);
break;
}
return iRet;
}
INT32 wmt_plat_gpio_ctrl (
ENUM_PIN_ID id,
ENUM_PIN_STATE state
)
{
if ( (PIN_ID_MAX > id)
&& (PIN_STA_MAX > state) ) {
// TODO: [FixMe][GeorgeKuo] do sanity check to const function table when init and skip checking here
if (gfp_set_pin_table[id]) {
return (*(gfp_set_pin_table[id]))(state); /* .handler */
}
else {
WMT_WARN_FUNC("WMT-PLAT: null fp for gpio_ctrl(%d)\n", id);
return -2;
}
}
WMT_ERR_FUNC("WMT-PLAT:[out of range] id(%d), state (%d)\n", id, state);
return -1;
}
INT32
wmt_plat_ldo_ctrl (
ENUM_PIN_STATE state
)
{
switch(state)
{
case PIN_STA_INIT:
/*set to gpio output low, disable pull*/
WMT_DBG_FUNC("WMT-PLAT:LDO init (out 0) \n");
break;
case PIN_STA_OUT_H:
WMT_DBG_FUNC("WMT-PLAT:LDO (out 1) \n");
break;
case PIN_STA_OUT_L:
WMT_DBG_FUNC("WMT-PLAT:LDO (out 0) \n");
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
/*set to gpio input low, pull down enable*/
WMT_DBG_FUNC("WMT-PLAT:LDO deinit (in pd) \n");
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on LDO\n", state);
break;
}
return 0;
}
INT32
wmt_plat_pmu_ctrl (
ENUM_PIN_STATE state
)
{
INT32 ret = 0;
switch(state)
{
case PIN_STA_INIT:
if (gpio_is_valid(wmt_pdata.pmu)) {
ret = gpio_request(wmt_pdata.pmu, "MT66XX PMUEN");
if (ret) {
WMT_INFO_FUNC("PMU gpio_request %d failed", ret);
} else {
gpio_direction_output(wmt_pdata.pmu, 0);
WMT_INFO_FUNC("WMT-PLAT:PMU init (out 0) \n");
}
} else {
WMT_INFO_FUNC("WMT-PLAT:invalid GPIo num for PMU EN, gpio:%d\n", wmt_pdata.pmu);
}
break;
case PIN_STA_OUT_H:
if (gpio_is_valid(wmt_pdata.pmu)) {
gpio_direction_output(wmt_pdata.pmu, 1);
WMT_INFO_FUNC("WMT-PLAT:PMU (out_h %d) \n", gpio_get_value(wmt_pdata.pmu));
} else {
WMT_INFO_FUNC("WMT-PLAT:PMU H invalid GPIO number: %d\n", wmt_pdata.pmu);
}
break;
case PIN_STA_OUT_L:
if (gpio_is_valid(wmt_pdata.pmu)) {
gpio_direction_output(wmt_pdata.pmu, 0);
WMT_INFO_FUNC("WMT-PLAT:PMU (out_h %d) \n", gpio_get_value(wmt_pdata.pmu));
} else {
WMT_INFO_FUNC("WMT-PLAT:PMU L invalid GPIO number: %d\n", wmt_pdata.pmu);
}
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
if (gpio_is_valid(wmt_pdata.pmu)) {
gpio_direction_output(wmt_pdata.pmu, 0);
gpio_free(wmt_pdata.pmu);
WMT_INFO_FUNC("WMT-PLAT:PMU deinit (in pd) \n");
} else {
WMT_INFO_FUNC("WMT-PLAT:PMU deinit invalid GPIO: %d \n", wmt_pdata.pmu);
}
break;
default:
WMT_INFO_FUNC("WMT-PLAT:Warnning, invalid state(%d) on PMU\n", state);
break;
}
return ret;
}
INT32
wmt_plat_rtc_ctrl (
ENUM_PIN_STATE state
)
{
switch(state)
{
case PIN_STA_INIT:
WMT_DBG_FUNC("WMT-PLAT:RTC init \n");
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on RTC\n", state);
break;
}
return 0;
}
INT32
wmt_plat_rst_ctrl (
ENUM_PIN_STATE state
)
{
int ret = 0;
switch(state)
{
case PIN_STA_INIT:
if (gpio_is_valid(wmt_pdata.rst)) {
ret = gpio_request(wmt_pdata.rst, "MT66XX SYSRST");
if (ret) {
WMT_INFO_FUNC("WMT-PLAT: request GPIO for RST failed. gpio:%d, ret:%d\n",wmt_pdata.rst, ret);
} else {
gpio_direction_output(wmt_pdata.rst, 0);
WMT_INFO_FUNC("WMT-PLAT:RST init (out 0) \n");
}
} else {
WMT_INFO_FUNC("WMT-PLAT: invalid GPIO for RST: %d\n", wmt_pdata.rst);
}
break;
case PIN_STA_OUT_H:
if (gpio_is_valid(wmt_pdata.rst)) {
gpio_direction_output(wmt_pdata.rst, 1);
WMT_INFO_FUNC("WMT-PLAT:RST (out_h %d) \n", gpio_get_value(wmt_pdata.rst));
} else {
WMT_INFO_FUNC("WMT-PLAT:RST H invalid GPIO number: %d\n", wmt_pdata.pmu);
}
break;
case PIN_STA_OUT_L:
if (gpio_is_valid(wmt_pdata.rst)) {
gpio_direction_output(wmt_pdata.rst, 0);
WMT_INFO_FUNC("WMT-PLAT:RST (out_h %d) \n", gpio_get_value(wmt_pdata.rst));
} else {
WMT_INFO_FUNC("WMT-PLAT:RST L invalid GPIO number: %d\n", wmt_pdata.pmu);
}
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
/*set to gpio input low, pull down enable*/
if (gpio_is_valid(wmt_pdata.rst)) {
gpio_direction_output(wmt_pdata.rst, 0);
gpio_free(wmt_pdata.rst);
WMT_INFO_FUNC("WMT-PLAT:RST deinit (in pd) \n");
} else {
WMT_INFO_FUNC("WMT-PLAT:RST deinit invalid GPIO: %d \n", wmt_pdata.rst);
}
break;
default:
WMT_INFO_FUNC("WMT-PLAT:Warnning, invalid state(%d) on RST\n", state);
break;
}
return ret;
}
INT32
wmt_plat_bgf_eint_ctrl (
ENUM_PIN_STATE state
)
{
int ret = 0;
switch(state)
{
case PIN_STA_INIT:
if (gpio_is_valid(wmt_pdata.bgf_int)) {
ret = gpio_request(wmt_pdata.bgf_int, "MT66XX BGF EINT");
if (ret) {
WMT_INFO_FUNC("BGF_EINT gpio request fail, ret = %d\n", ret);
}
} else {
WMT_INFO_FUNC("invalid BGF_EINT gpio: %d\n", wmt_pdata.bgf_int);
}
break;
case PIN_STA_MUX:
g_bgf_irq = gpio_to_irq(wmt_pdata.bgf_int);
WMT_INFO_FUNC("WMT-PLAT: bgf irq num is: %d\n", g_bgf_irq);
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
if (gpio_is_valid(wmt_pdata.bgf_int)) {
gpio_free(wmt_pdata.bgf_int);
}
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on BGF EINT\n", state);
break;
}
return ret;
}
INT32 wmt_plat_wifi_eint_ctrl(ENUM_PIN_STATE state)
{
WMT_INFO_FUNC("WMT-PLAT:WIFI EINT is controlled by MSDC driver or SDIO EINT.\n");
return 0;
}
INT32
wmt_plat_all_eint_ctrl (
ENUM_PIN_STATE state
)
{
switch(state)
{
case PIN_STA_INIT:
/*set to gpio input low, pull down eanble*/
WMT_DBG_FUNC("WMT-PLAT:ALLInt init(in pd) \n");
break;
case PIN_STA_MUX:
/*set to gpio EINT mode, pull down enable*/
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
/*set to gpio input low, pull down enable*/
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on ALL EINT\n", state);
break;
}
return 0;
}
/*
in this function, we will ctrl host UART CTS pin to output mode, and out high /low to control the 662x chip to COMMON sdio mod
step
1. control the CTS to gpio mode
2. contorl the CTS to output mode
3. control the CTS to output high/low
*/
INT32 wmt_plat_uart_cts_ctrl(INT32 high)
{
INT32 ret;
if (wmt_pdata.urt_cts == -EINVAL)
return 0;
if (high) {
ret = gpio_request(wmt_pdata.urt_cts, "MT66XX UART CTS");
if(ret<0) {
WMT_INFO_FUNC( "UART CTS request fail:%d\n",ret);
}
ret = gpio_direction_output(wmt_pdata.urt_cts, 1);
WMT_INFO_FUNC( "UART CTS out high --> common sdio mode,ret:%d \n",ret);
} else {
ret = gpio_direction_input(wmt_pdata.urt_cts);
WMT_INFO_FUNC( "UART CTS out high --> common sdio mode \n");
gpio_free(wmt_pdata.urt_cts);
}
return 0;
}
INT32 wmt_plat_uart_ctrl(ENUM_PIN_STATE state)
{
switch(state)
{
case PIN_STA_MUX:
case PIN_STA_INIT:
WMT_INFO_FUNC("WMT-PLAT:UART init (mode_01, uart) \n");
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
WMT_INFO_FUNC("WMT-PLAT:UART deinit (out 0) \n");
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on UART Group\n", state);
break;
}
return 0;
}
INT32 wmt_plat_pcm_ctrl(ENUM_PIN_STATE state)
{
switch(state)
{
case PIN_STA_MUX:
case PIN_STA_INIT:
/*set to PCM function*/
WMT_DBG_FUNC("WMT-PLAT:PCM init (pcm) \n");
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
WMT_DBG_FUNC("WMT-PLAT:PCM deinit (out 0) \n");
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on PCM Group\n", state);
break;
}
return 0;
}
INT32 wmt_plat_i2s_ctrl(ENUM_PIN_STATE state)
{
#ifndef FM_ANALOG_INPUT
switch(state)
{
case PIN_STA_INIT:
case PIN_STA_MUX:
/*set to I2S function*/
WMT_DBG_FUNC("WMT-PLAT:I2S init \n");
break;
case PIN_STA_IN_L:
case PIN_STA_DEINIT:
/*set to gpio input low, pull down enable*/
WMT_DBG_FUNC("WMT-PLAT:I2S deinit (out 0) \n");
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on I2S Group\n", state);
break;
}
#else
WMT_INFO_FUNC( "[MT6620]warnning:FM analog mode is set, no I2S GPIO settings should be modified by combo driver\n");
#endif
return 0;
}
INT32
wmt_plat_sdio_pin_ctrl (
ENUM_PIN_STATE state
)
{
switch (state) {
case PIN_STA_INIT:
case PIN_STA_MUX:
break;
case PIN_STA_DEINIT:
break;
default:
WMT_WARN_FUNC("WMT-PLAT:Warnning, invalid state(%d) on SDIO Group\n", state);
break;
}
return 0;
}
static INT32
wmt_plat_gps_sync_ctrl (
ENUM_PIN_STATE state
)
{
switch (state) {
case PIN_STA_INIT:
case PIN_STA_DEINIT:
/*set GPS_SYNC GPIO to GPIO mode, pull disable,output low*/
break;
case PIN_STA_MUX:
/*set GPS_SYNC GPIO to GPS_SYNC function*/
break;
default:
break;
}
return 0;
}
static INT32
wmt_plat_gps_lna_ctrl (
ENUM_PIN_STATE state
)
{
switch (state) {
case PIN_STA_INIT:
case PIN_STA_DEINIT:
/*set GPS_LNA GPIO to GPIO mode, pull disable,output low*/
break;
case PIN_STA_OUT_H:
/*set GPS_LNA GPIO to GPIO mode, pull disable,output high*/
break;
case PIN_STA_OUT_L:
/*set GPS_LNA GPIO to GPIO mode, pull disable,output low*/
break;
default:
WMT_WARN_FUNC("%d mode not defined for gps lna pin !!!\n", state);
break;
}
return 0;
}
INT32 wmt_plat_wake_lock_ctrl(ENUM_WL_OP opId)
{
#ifdef CFG_WMT_WAKELOCK_SUPPORT
static INT32 counter = 0;
osal_lock_sleepable_lock( &gOsSLock);
if (WL_OP_GET == opId)
{
++counter;
}else if (WL_OP_PUT == opId)
{
--counter;
}
osal_unlock_sleepable_lock( &gOsSLock);
if (WL_OP_GET == opId && counter == 1)
{
wake_lock(&wmtWakeLock);
WMT_DBG_FUNC("WMT-PLAT: after wake_lock(%d), counter(%d)\n", wake_lock_active(&wmtWakeLock), counter);
}
else if (WL_OP_PUT == opId && counter == 0)
{
wake_unlock(&wmtWakeLock);
WMT_DBG_FUNC("WMT-PLAT: after wake_unlock(%d), counter(%d)\n", wake_lock_active(&wmtWakeLock), counter);
}
else
{
WMT_WARN_FUNC("WMT-PLAT: wakelock status(%d), counter(%d)\n", wake_lock_active(&wmtWakeLock), counter);
}
return 0;
#else
WMT_WARN_FUNC("WMT-PLAT: host awake function is not supported.");
return 0;
#endif
}
| gpl-2.0 |
matheusmcardoso/WoWRenewal | src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp | 9 | 37201 | /*
* Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CreatureTextMgr.h"
#include "LFGMgr.h"
#include "ScriptedGossip.h"
#include "ScriptedCreature.h"
#include "ScriptMgr.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "the_slave_pens.h"
enum Spells
{
// Ahune
SPELL_SYNCH_HEALTH = 46430,
SPELL_AHUNES_SHIELD = 45954,
SPELL_STAY_SUBMERGED = 46981,
SPELL_AHUNE_SELF_STUN = 46416,
SPELL_AHUNE_ACHIEVEMENT = 62043,
SPELL_AHUNE_SPANKY_HANDS = 46146,
SPELL_COLD_SLAP = 46145,
SPELL_RESURFACE = 46402,
SPELL_SUBMERGED = 37751,
SPELL_STAND = 37752,
//Earther Ring Flamecaller
SPELL_FIND_OPENING_VISUAL = 45964,
SPELL_FIND_OPENING_BEAM_END = 46333,
SPELL_FIND_OPENING_TRIGGER = 46341,
SPELL_FIND_OPENING_CHANNEL = 46345,
SPELL_BONFIRE_VISUAL = 46339,
SPELL_FOUND_OPENING = 46421,
//Ahune Bunny
SPELL_SUMMON_COLDWEAVE = 46143,
SPELL_SUMMON_FROSTWIND = 46382,
SPELL_SUMMON_HAILSTONE = 46176,
SPELL_SUMMONING_VISUAL_1 = 45937,
SPELL_SUMMONING_RHYME_AURA = 45926,
SPELL_SUMMONING_RHYME_BONFIRE = 45930,
SPELL_FORCE_WHISP_FLIGHT = 46603,
SPELL_SHAMANS_LOOK_FOR_OPENING = 46422,
SPELL_CLOSE_OPENING_VISUAL = 46236,
SPELL_ICE_BOMBARD = 46397,
SPELL_ICE_BOMBARDMENT_DEST_PICKER = 46398,
SPELL_ICE_BOMBARDMENT = 46396,
// Ice Spear
SPELL_SUMMON_ICE_SPEAR_BUNNY = 46359,
SPELL_ICE_SPEAR_KNOCKBACK = 46360,
SPELL_SUMMON_ICE_SPEAR_GO = 46369,
SPELL_ICE_SPEAR_AURA = 46371,
SPELL_ICE_SPEAR_TARGET_PICKER = 46372,
SPELL_ICE_SPEAR_DELAY = 46878,
SPELL_ICE_SPEAR_VISUAL = 75498,
// Slippery Floor
SPELL_SLIPPERY_FLOOR_AMBIENT = 46314,
SPELL_SLIPPERY_FLOOR_PERIODIC = 46320,
SPELL_SLIPPERY_FLOOR_SLIP = 45947,
SPELL_SLIPPERY_FLOOR_YOU_SLIPPED = 45946,
// Frozen Core
SPELL_SUICIDE = 45254,
SPELL_SUMMON_LOOT_MISSILE = 45941,
SPELL_FROZEN_CORE_GETS_HIT = 46810,
SPELL_MINION_DESPAWNER = 46843,
SPELL_GHOST_DISGUISE = 46786
};
enum Emotes
{
EMOTE_EARTHEN_ASSAULT = 0,
EMOTE_RETREAT = 0,
EMOTE_RESURFACE = 1
};
enum Says
{
SAY_PLAYER_TEXT_1 = 0,
SAY_PLAYER_TEXT_2 = 1,
SAY_PLAYER_TEXT_3 = 2
};
enum Events
{
EVENT_EMERGE = 1,
EVENT_INITIAL_EMERGE = 2,
EVENT_SYNCH_HEALTH = 3,
EVENT_LOOKFOROPENING_0 = 4,
EVENT_LOOKFOROPENING_1 = 5,
EVENT_LOOKFOROPENING_2 = 6,
EVENT_SUMMON_HAILSTONE = 7,
EVENT_SUMMON_COLDWEAVE = 8,
EVENT_SUMMON_FROSTWIND = 9,
EVENT_SUMMON_AHUNE = 10,
EVENT_CLOSE_OPENING = 11,
EVENT_AHUNE_PHASE_ONE = 12,
EVENT_AHUNE_PHASE_TWO = 13,
EVENT_START_LOOKING_FOR_OPENING = 14,
EVENT_STOP_LOOKING_FOR_OPENING = 15
};
enum Actions
{
ACTION_START_EVENT = -2574500,
ACTION_AHUNE_RETREAT = -2586500,
ACTION_AHUNE_RESURFACE = -2586501,
ACTION_EMOTE_RESURFACE = -2575400
};
enum Phases
{
PHASE_ONE = 0,
PHASE_TWO = 1
};
enum Points
{
POINT_FLAMECALLER_000,
POINT_FLAMECALLER_001,
POINT_FLAMECALLER_002
};
enum Misc
{
MAX_FLAMECALLERS = 3
};
Position const SummonPositions[] =
{
{ -99.1021f, -233.7526f, -1.22307f, 1.588250f }, // Ahune
{ -98.0151f, -230.4555f, -1.21089f, 1.797689f }, // Frozen Core
{ -143.172f, -147.6801f, -3.16113f, 4.852015f }, // Bonfire Bunny 000
{ -134.304f, -145.7803f, -1.70332f, 4.677482f }, // Bonfire Bunny 001
{ -125.036f, -144.2065f, -1.91660f, 4.991642f }, // Bonfire Bunny 002
{ -69.8121f, -162.4954f, -2.30451f, 1.710423f }, // Wisp Source Bunny
{ -98.1029f, -230.7864f, -10.8085f, 1.448623f } // Wisp Dest Bunny
};
Position const FlameCallerSpots[] =
{
{ -145.2233f, -137.5543f, -1.59056f, 5.427049f },
{ -137.4383f, -136.4050f, -1.72384f, 5.336747f },
{ -129.0413f, -132.1494f, -2.09285f, 5.460842f }
};
class boss_ahune : public CreatureScript
{
public:
boss_ahune() : CreatureScript("boss_ahune") { }
struct boss_ahuneAI : public BossAI
{
boss_ahuneAI(Creature* creature) : BossAI(creature, DATA_AHUNE)
{
me->SetControlled(true, UNIT_STATE_ROOT);
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_INITIAL_EMERGE, Milliseconds(4));
events.ScheduleEvent(EVENT_SYNCH_HEALTH, Seconds(3));
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
if (Creature* ahuneBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AHUNE_BUNNY)))
ahuneBunny->AI()->EnterEvadeMode();
summons.DespawnAll();
me->DespawnOrUnsummon();
}
void JustDied(Unit* /*killer*/) override
{
instance->DoCastSpellOnPlayers(SPELL_AHUNE_ACHIEVEMENT);
if (Creature* ahuneBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AHUNE_BUNNY)))
me->Kill(ahuneBunny);
if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE)))
me->Kill(frozenCore);
Map::PlayerList const& players = me->GetMap()->GetPlayers();
if (!players.isEmpty())
{
if (Group* group = players.begin()->GetSource()->GetGroup())
if (group->isLFGGroup())
sLFGMgr->FinishDungeon(group->GetGUID(), 286, me->GetMap());
}
_JustDied();
}
void DoAction(int32 action) override
{
if (action == ACTION_AHUNE_RETREAT)
{
Submerge();
events.ScheduleEvent(EVENT_EMERGE, Seconds(35));
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_INITIAL_EMERGE:
DoCast(me, SPELL_STAND);
DoCast(me, SPELL_AHUNE_SPANKY_HANDS);
DoCast(me, SPELL_AHUNES_SHIELD);
break;
case EVENT_EMERGE:
Emerge();
break;
case EVENT_SYNCH_HEALTH:
if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE)))
DoCast(frozenCore, SPELL_SYNCH_HEALTH, true);
else
DoCast(me, SPELL_SUICIDE);
events.Repeat(Seconds(3));
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
void Emerge()
{
if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE)))
frozenCore->AI()->DoAction(ACTION_AHUNE_RESURFACE);
DoCast(me, SPELL_AHUNES_SHIELD);
me->RemoveAurasDueToSpell(SPELL_AHUNE_SELF_STUN);
me->RemoveAurasDueToSpell(SPELL_STAY_SUBMERGED);
DoCast(me, SPELL_STAND);
DoCast(me, SPELL_RESURFACE, true);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
events.ScheduleEvent(EVENT_SYNCH_HEALTH, Seconds(3));
}
void Submerge()
{
if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE)))
frozenCore->AI()->DoAction(ACTION_AHUNE_RETREAT);
me->RemoveAurasDueToSpell(SPELL_AHUNES_SHIELD);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_31);
DoCast(me, SPELL_SUBMERGED, true);
DoCast(me, SPELL_AHUNE_SELF_STUN, true);
DoCast(me, SPELL_STAY_SUBMERGED, true);
me->HandleEmoteCommand(EMOTE_ONESHOT_SUBMERGE);
events.Reset();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_ahuneAI>(creature);
}
};
class npc_frozen_core : public CreatureScript
{
public:
npc_frozen_core() : CreatureScript("npc_frozen_core") { }
struct npc_frozen_coreAI : public ScriptedAI
{
npc_frozen_coreAI(Creature* creature) : ScriptedAI(creature)
{
_instance = me->GetInstanceScript();
Initialize();
}
void Initialize()
{
me->SetReactState(REACT_PASSIVE);
me->setRegeneratingHealth(false);
DoCast(me, SPELL_FROZEN_CORE_GETS_HIT);
DoCast(me, SPELL_ICE_SPEAR_AURA);
}
void JustDied(Unit* /*killer*/) override
{
if (Creature* ahune = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AHUNE)))
me->Kill(ahune);
DoCast(SPELL_SUMMON_LOOT_MISSILE);
DoCast(SPELL_MINION_DESPAWNER);
}
void DoAction(int32 action) override
{
if (action == ACTION_AHUNE_RETREAT)
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC);
me->RemoveAurasDueToSpell(SPELL_ICE_SPEAR_AURA);
_events.ScheduleEvent(EVENT_SYNCH_HEALTH, Seconds(3), 0, PHASE_TWO);
}
else if (action == ACTION_AHUNE_RESURFACE)
{
_events.Reset();
DoCast(me, SPELL_ICE_SPEAR_AURA);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC);
}
}
void UpdateAI(uint32 diff) override
{
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SYNCH_HEALTH:
if (Creature* ahune = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AHUNE)))
DoCast(ahune, SPELL_SYNCH_HEALTH, true);
else
DoCast(me, SPELL_SUICIDE);
_events.Repeat(Seconds(3));
break;
default:
break;
}
}
}
private:
InstanceScript* _instance;
EventMap _events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_frozen_coreAI>(creature);
}
};
class npc_ahune_bunny : public CreatureScript
{
public:
npc_ahune_bunny() : CreatureScript("npc_ahune_bunny") { }
struct npc_ahune_bunnyAI : public ScriptedAI
{
npc_ahune_bunnyAI(Creature* creature) : ScriptedAI(creature), _summons(me)
{
_instance = me->GetInstanceScript();
_submerged = false;
}
void JustSummoned(Creature* summon) override
{
if (summon->GetEntry() == NPC_AHUNE)
return;
summon->SetInCombatWithZone();
_summons.Summon(summon);
}
void JustDied(Unit* /*killer*/) override
{
_summons.DespawnAll();
ResetFlameCallers();
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
_EnterEvadeMode();
_summons.DespawnAll();
ResetFlameCallers();
me->SummonGameObject(GO_ICE_STONE, -69.90455f, -162.2449f, -2.366563f, 2.426008f, G3D::Quat(0.0f, 0.0f, 0.9366722f, 0.3502074f), 0);
}
void DoAction(int32 action) override
{
if (action == ACTION_START_EVENT)
{
DoCast(me, SPELL_SUMMONING_VISUAL_1);
me->SummonCreature(NPC_WHISP_SOURCE_BUNNY, SummonPositions[5], TEMPSUMMON_MANUAL_DESPAWN);
me->SummonCreature(NPC_WHISP_DEST_BUNNY, SummonPositions[6], TEMPSUMMON_MANUAL_DESPAWN);
me->SummonCreature(NPC_SHAMAN_BONFIRE_BUNNY_000, SummonPositions[2], TEMPSUMMON_MANUAL_DESPAWN);
me->SummonCreature(NPC_SHAMAN_BONFIRE_BUNNY_001, SummonPositions[3], TEMPSUMMON_MANUAL_DESPAWN);
me->SummonCreature(NPC_SHAMAN_BONFIRE_BUNNY_002, SummonPositions[4], TEMPSUMMON_MANUAL_DESPAWN);
for (uint8 counter = 0; counter < MAX_FLAMECALLERS; ++counter)
if (Creature* flameCaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000 + counter)))
flameCaller->GetMotionMaster()->MovePoint(counter, FlameCallerSpots[counter].GetPosition());
_submerged = false;
_events.Reset();
_events.SetPhase(PHASE_ONE);
_events.ScheduleEvent(EVENT_SUMMON_AHUNE, Seconds(10));
_events.ScheduleEvent(EVENT_START_LOOKING_FOR_OPENING, Seconds(14), 0, PHASE_ONE);
_events.ScheduleEvent(EVENT_SUMMON_COLDWEAVE, Seconds(22), 0, PHASE_ONE);
_events.ScheduleEvent(EVENT_SUMMON_HAILSTONE, Seconds(14), 0, PHASE_ONE);
_events.ScheduleEvent(EVENT_AHUNE_PHASE_TWO, Seconds(108), 0, PHASE_ONE);
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_START_LOOKING_FOR_OPENING:
Talk(EMOTE_EARTHEN_ASSAULT);
for (uint8 counter = 0; counter < MAX_FLAMECALLERS; ++counter)
if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000 + counter)))
DoCast(flamecaller, SPELL_SHAMANS_LOOK_FOR_OPENING, true);
break;
case EVENT_SUMMON_HAILSTONE:
DoCast(SPELL_SUMMON_HAILSTONE);
break;
case EVENT_SUMMON_COLDWEAVE:
DoCast(SPELL_SUMMON_COLDWEAVE);
DoCast(SPELL_SUMMON_COLDWEAVE);
_events.Repeat(Seconds(8));
if (_submerged)
_events.ScheduleEvent(EVENT_SUMMON_FROSTWIND, Seconds(4), 0, PHASE_ONE);
break;
case EVENT_SUMMON_FROSTWIND:
DoCast(SPELL_SUMMON_FROSTWIND);
break;
case EVENT_SUMMON_AHUNE:
if (TempSummon* ahune = me->SummonCreature(NPC_AHUNE, SummonPositions[0], TEMPSUMMON_DEAD_DESPAWN))
{
ahune->SummonCreature(NPC_FROZEN_CORE, SummonPositions[1], TEMPSUMMON_CORPSE_DESPAWN);
ahune->SetInCombatWithZone();
DoCast(ahune, SPELL_RESURFACE);
}
break;
case EVENT_CLOSE_OPENING:
if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000)))
flamecaller->AI()->DoAction(ACTION_EMOTE_RESURFACE);
DoCast(SPELL_CLOSE_OPENING_VISUAL);
DoCast(me, SPELL_ICE_BOMBARD);
break;
case EVENT_AHUNE_PHASE_TWO:
if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000)))
DoCast(flamecaller, SPELL_FOUND_OPENING);
if (Creature* ahune = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AHUNE)))
ahune->AI()->DoAction(ACTION_AHUNE_RETREAT);
_events.Reset();
_events.SetPhase(PHASE_TWO);
_events.ScheduleEvent(EVENT_CLOSE_OPENING, Seconds(25), 0, PHASE_TWO);
_events.ScheduleEvent(EVENT_AHUNE_PHASE_ONE, Seconds(35), 0, PHASE_TWO);
break;
case EVENT_AHUNE_PHASE_ONE:
_submerged = true;
_events.Reset();
_events.SetPhase(PHASE_ONE);
_events.ScheduleEvent(EVENT_SUMMON_COLDWEAVE, Seconds(8), 0, PHASE_ONE);
_events.ScheduleEvent(EVENT_SUMMON_HAILSTONE, Seconds(5), 0, PHASE_ONE);
_events.ScheduleEvent(EVENT_START_LOOKING_FOR_OPENING, Seconds(5), 0, PHASE_ONE);
_events.ScheduleEvent(EVENT_AHUNE_PHASE_TWO, Seconds(100), 0, PHASE_ONE);
break;
default:
break;
}
}
}
void ResetFlameCallers()
{
for (uint8 counter = 0; counter < MAX_FLAMECALLERS; ++counter)
if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000 + counter)))
flamecaller->AI()->EnterEvadeMode();
}
private:
InstanceScript* _instance;
EventMap _events;
SummonList _summons;
bool _submerged;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_ahune_bunnyAI>(creature);
}
};
class npc_earthen_ring_flamecaller : public CreatureScript
{
public:
npc_earthen_ring_flamecaller() : CreatureScript("npc_earthen_ring_flamecaller") { }
struct npc_earthen_ring_flamecallerAI : public ScriptedAI
{
npc_earthen_ring_flamecallerAI(Creature* creature) : ScriptedAI(creature)
{
_instance = me->GetInstanceScript();
_mySpot = 0;
}
void Reset() override
{
_events.Reset();
}
void MovementInform(uint32 motionType, uint32 pointId) override
{
if (motionType != POINT_MOTION_TYPE)
return;
switch (pointId)
{
case POINT_FLAMECALLER_000:
_mySpot = POINT_FLAMECALLER_000;
me->SetOrientation(FlameCallerSpots[_mySpot].GetOrientation());
break;
case POINT_FLAMECALLER_001:
_mySpot = POINT_FLAMECALLER_001;
me->SetOrientation(FlameCallerSpots[_mySpot].GetOrientation());
break;
case POINT_FLAMECALLER_002:
_mySpot = POINT_FLAMECALLER_002;
me->SetOrientation(FlameCallerSpots[_mySpot].GetOrientation());
break;
default:
break;
}
DoCast(me, SPELL_FIND_OPENING_CHANNEL);
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spellInfo) override
{
switch (spellInfo->Id)
{
case SPELL_SHAMANS_LOOK_FOR_OPENING:
_events.ScheduleEvent(EVENT_LOOKFOROPENING_0, Seconds(17));
break;
case SPELL_FOUND_OPENING:
Talk(EMOTE_RETREAT);
break;
default:
break;
}
}
void DoAction(int action) override
{
if (action == ACTION_EMOTE_RESURFACE)
Talk(EMOTE_RESURFACE);
}
void UpdateAI(uint32 diff) override
{
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_LOOKFOROPENING_0:
LookOpening(true, 0);
_events.ScheduleEvent(EVENT_LOOKFOROPENING_1, Seconds(26));
break;
case EVENT_LOOKFOROPENING_1:
LookOpening(true, 1);
_events.ScheduleEvent(EVENT_LOOKFOROPENING_2, Seconds(25));
break;
case EVENT_LOOKFOROPENING_2:
LookOpening(true, 2);
_events.ScheduleEvent(EVENT_STOP_LOOKING_FOR_OPENING, Seconds(27));
break;
case EVENT_STOP_LOOKING_FOR_OPENING:
LookOpening(false, _mySpot);
break;
default:
break;
}
}
}
void LookOpening(bool activate, uint8 spot)
{
if (_mySpot != spot)
return;
if (Creature* bonfireBunny = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BONFIRE_BUNNY_000 + spot)))
if (Creature* beamBunny = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BEAM_BUNNY_000 + spot)))
{
if (activate)
{
DoCast(bonfireBunny, SPELL_FIND_OPENING_TRIGGER);
bonfireBunny->CastSpell(beamBunny, SPELL_FIND_OPENING_VISUAL, true);
}
else
{
DoCast(me, SPELL_FIND_OPENING_CHANNEL);
bonfireBunny->CastStop();
beamBunny->RemoveAurasDueToSpell(SPELL_FIND_OPENING_BEAM_END);
}
}
}
private:
EventMap _events;
InstanceScript* _instance;
uint8 _mySpot;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_earthen_ring_flamecallerAI>(creature);
}
};
class go_ahune_ice_stone : public GameObjectScript
{
public:
go_ahune_ice_stone() : GameObjectScript("go_ahune_ice_stone") { }
bool OnGossipSelect(Player* player, GameObject* go, uint32 /*sender*/, uint32 /*action*/)
{
InstanceScript* instance = go->GetInstanceScript();
if (!instance)
return false;
ClearGossipMenuFor(player);
if (Creature* ahuneBunny = ObjectAccessor::GetCreature(*go, instance->GetGuidData(DATA_AHUNE_BUNNY)))
{
ahuneBunny->AI()->DoAction(ACTION_START_EVENT);
ahuneBunny->SetInCombatWithZone();
}
if (Creature* luma = ObjectAccessor::GetCreature(*go, instance->GetGuidData(DATA_LUMA_SKYMOTHER)))
luma->CastSpell(player, SPELL_SUMMONING_RHYME_AURA, true);
CloseGossipMenuFor(player);
go->Delete();
return true;
}
};
// 46430 - Synch Health
class spell_ahune_synch_health : public SpellScriptLoader
{
public:
spell_ahune_synch_health() : SpellScriptLoader("spell_ahune_synch_health") { }
class spell_ahune_synch_health_SpellScript : public SpellScript
{
PrepareSpellScript(spell_ahune_synch_health_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_SYNCH_HEALTH))
return false;
return true;
}
void HandleScript(SpellEffIndex /*effIndex*/)
{
if (Unit* target = GetHitUnit())
if (Unit* caster = GetCaster())
target->SetHealth(caster->GetHealth());
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_ahune_synch_health_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_ahune_synch_health_SpellScript();
}
};
// 45926 - Summoning Rhyme Aura
class spell_summoning_rhyme_aura : public SpellScriptLoader
{
public:
spell_summoning_rhyme_aura() : SpellScriptLoader("spell_summoning_rhyme_aura") { }
class spell_summoning_rhyme_aura_AuraScript : public AuraScript
{
PrepareAuraScript(spell_summoning_rhyme_aura_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_WHISP_FLIGHT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMONING_RHYME_BONFIRE))
return false;
return true;
}
void PeriodicTick(AuraEffect const* aurEff)
{
Creature* caster = GetCaster()->ToCreature();
Player* player = GetTarget()->ToPlayer();
if (!caster || !player)
return;
player->CastSpell(player, SPELL_FORCE_WHISP_FLIGHT);
switch (aurEff->GetTickNumber())
{
case 1:
sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_1, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player);
player->CastSpell(player, SPELL_SUMMONING_RHYME_BONFIRE, true);
break;
case 2:
sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_2, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player);
break;
case 3:
sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_3, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player);
Remove();
break;
}
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_summoning_rhyme_aura_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_summoning_rhyme_aura_AuraScript();
}
};
// 46878 - Summon Ice Spear Delayer
class spell_summon_ice_spear_delayer : public SpellScriptLoader
{
public:
spell_summon_ice_spear_delayer() : SpellScriptLoader("spell_summon_ice_spear_delayer") { }
class spell_summon_ice_spear_delayer_AuraScript : public AuraScript
{
PrepareAuraScript(spell_summon_ice_spear_delayer_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_GO) || !sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_KNOCKBACK))
return false;
return true;
}
void PeriodicTick(AuraEffect const* aurEff)
{
if (Unit* tmpCaster = GetCaster())
if (Creature* caster = tmpCaster->ToCreature())
switch (aurEff->GetTickNumber())
{
case 1:
caster->CastSpell(caster, SPELL_SUMMON_ICE_SPEAR_GO);
break;
case 3:
if (GameObject* spike = caster->FindNearestGameObject(GO_ICE_SPEAR, 3.0f))
spike->UseDoorOrButton();
caster->AI()->DoCastAOE(SPELL_ICE_SPEAR_KNOCKBACK, true);
break;
case 5:
if (GameObject* spike = caster->FindNearestGameObject(GO_ICE_SPEAR, 3.0f))
spike->Delete();
caster->DespawnOrUnsummon();
break;
default:
break;
}
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_summon_ice_spear_delayer_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_summon_ice_spear_delayer_AuraScript();
}
};
// 46371 - Ice Spear Control Aura
class spell_ice_spear_control_aura : public SpellScriptLoader
{
public:
spell_ice_spear_control_aura() : SpellScriptLoader("spell_ice_spear_control_aura") { }
class spell_ice_spear_control_aura_AuraScript : public AuraScript
{
PrepareAuraScript(spell_ice_spear_control_aura_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_TARGET_PICKER))
return false;
return true;
}
void PeriodicTick(AuraEffect const* /*aurEff*/)
{
if (Unit* caster = GetCaster())
caster->CastSpell(caster, SPELL_ICE_SPEAR_TARGET_PICKER);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_ice_spear_control_aura_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_ice_spear_control_aura_AuraScript();
}
};
// 46372 - Ice Spear Target Picker
class spell_ice_spear_target_picker : public SpellScriptLoader
{
public:
spell_ice_spear_target_picker() : SpellScriptLoader("spell_ice_spear_target_picker") { }
class spell_ice_spear_target_picker_SpellScript : public SpellScript
{
PrepareSpellScript(spell_ice_spear_target_picker_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_BUNNY))
return false;
return true;
}
void FilterTargets(std::list<WorldObject*>& targets)
{
if (targets.empty())
return;
WorldObject* target = Trinity::Containers::SelectRandomContainerElement(targets);
targets.clear();
targets.push_back(target);
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_ICE_SPEAR_BUNNY, true);
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ice_spear_target_picker_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY);
OnEffectHitTarget += SpellEffectFn(spell_ice_spear_target_picker_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_ice_spear_target_picker_SpellScript();
}
};
// 46320 - Spell Slippery Floor Periodic
class spell_slippery_floor_periodic : public SpellScriptLoader
{
public:
spell_slippery_floor_periodic() : SpellScriptLoader("spell_slippery_floor_periodic") { }
class spell_slippery_floor_periodic_SpellScript : public SpellScript
{
PrepareSpellScript(spell_slippery_floor_periodic_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_SLIPPERY_FLOOR_SLIP))
return false;
return true;
}
void HandleScriptEffect(SpellEffIndex /*effIndex*/)
{
if (Unit* target = GetHitUnit())
if (target->isMoving())
{
target->CastSpell(target, SPELL_SLIPPERY_FLOOR_SLIP, true);
target->CastSpell(target, SPELL_SLIPPERY_FLOOR_YOU_SLIPPED, true);
}
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_slippery_floor_periodic_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_slippery_floor_periodic_SpellScript();
}
};
// 46146 - Ahune Spanky Hands
class spell_ahune_spanky_hands : public SpellScriptLoader
{
public:
spell_ahune_spanky_hands() : SpellScriptLoader("spell_ahune_spanky_hands") { }
class spell_ahune_spanky_hands_AuraScript : public AuraScript
{
PrepareAuraScript(spell_ahune_spanky_hands_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_COLD_SLAP))
return false;
return true;
}
void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_COLD_SLAP, true);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_ahune_spanky_hands_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_ahune_spanky_hands_AuraScript();
}
};
class spell_ahune_minion_despawner : public SpellScriptLoader
{
public:
spell_ahune_minion_despawner() : SpellScriptLoader("spell_ahune_minion_despawner") { }
class spell_ahune_minion_despawner_SpellScript : public SpellScript
{
PrepareSpellScript(spell_ahune_minion_despawner_SpellScript);
void HandleScript(SpellEffIndex /*effIndex*/)
{
if (GetHitCreature())
GetHitCreature()->DespawnOrUnsummon();
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_ahune_minion_despawner_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_APPLY_AURA);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_ahune_minion_despawner_SpellScript();
}
};
// 46398 - Spell Ice Bombardment Dest Picker
class spell_ice_bombardment_dest_picker : public SpellScriptLoader
{
public:
spell_ice_bombardment_dest_picker() : SpellScriptLoader("spell_ice_bombardment_dest_picker") { }
class spell_ice_bombardment_dest_picker_SpellScript : public SpellScript
{
PrepareSpellScript(spell_ice_bombardment_dest_picker_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_ICE_BOMBARDMENT))
return false;
return true;
}
void HandleScriptEffect(SpellEffIndex /*effIndex*/)
{
GetCaster()->CastSpell(GetHitDest()->GetPositionX(), GetHitDest()->GetPositionY(), GetHitDest()->GetPositionZ(), SPELL_ICE_BOMBARDMENT, true);
}
void Register() override
{
OnEffectHit += SpellEffectFn(spell_ice_bombardment_dest_picker_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_ice_bombardment_dest_picker_SpellScript();
}
};
void AddSC_boss_ahune()
{
new boss_ahune();
new npc_frozen_core();
new npc_earthen_ring_flamecaller();
new npc_ahune_bunny();
new go_ahune_ice_stone();
new spell_ahune_synch_health();
new spell_summoning_rhyme_aura();
new spell_summon_ice_spear_delayer();
new spell_ice_spear_control_aura();
new spell_slippery_floor_periodic();
new spell_ahune_spanky_hands();
new spell_ahune_minion_despawner();
new spell_ice_spear_target_picker();
new spell_ice_bombardment_dest_picker();
}
| gpl-2.0 |
gazoo74/linux | net/rxrpc/peer_event.c | 9 | 11538 | /* Peer event handling, typically ICMP messages.
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/errqueue.h>
#include <linux/udp.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/icmp.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include <net/ip.h>
#include "ar-internal.h"
static void rxrpc_store_error(struct rxrpc_peer *, struct sock_exterr_skb *);
static void rxrpc_distribute_error(struct rxrpc_peer *, int,
enum rxrpc_call_completion);
/*
* Find the peer associated with an ICMP packet.
*/
static struct rxrpc_peer *rxrpc_lookup_peer_icmp_rcu(struct rxrpc_local *local,
const struct sk_buff *skb,
struct sockaddr_rxrpc *srx)
{
struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
_enter("");
memset(srx, 0, sizeof(*srx));
srx->transport_type = local->srx.transport_type;
srx->transport_len = local->srx.transport_len;
srx->transport.family = local->srx.transport.family;
/* Can we see an ICMP4 packet on an ICMP6 listening socket? and vice
* versa?
*/
switch (srx->transport.family) {
case AF_INET:
srx->transport_len = sizeof(srx->transport.sin);
srx->transport.family = AF_INET;
srx->transport.sin.sin_port = serr->port;
switch (serr->ee.ee_origin) {
case SO_EE_ORIGIN_ICMP:
_net("Rx ICMP");
memcpy(&srx->transport.sin.sin_addr,
skb_network_header(skb) + serr->addr_offset,
sizeof(struct in_addr));
break;
case SO_EE_ORIGIN_ICMP6:
_net("Rx ICMP6 on v4 sock");
memcpy(&srx->transport.sin.sin_addr,
skb_network_header(skb) + serr->addr_offset + 12,
sizeof(struct in_addr));
break;
default:
memcpy(&srx->transport.sin.sin_addr, &ip_hdr(skb)->saddr,
sizeof(struct in_addr));
break;
}
break;
#ifdef CONFIG_AF_RXRPC_IPV6
case AF_INET6:
switch (serr->ee.ee_origin) {
case SO_EE_ORIGIN_ICMP6:
_net("Rx ICMP6");
srx->transport.sin6.sin6_port = serr->port;
memcpy(&srx->transport.sin6.sin6_addr,
skb_network_header(skb) + serr->addr_offset,
sizeof(struct in6_addr));
break;
case SO_EE_ORIGIN_ICMP:
_net("Rx ICMP on v6 sock");
srx->transport_len = sizeof(srx->transport.sin);
srx->transport.family = AF_INET;
srx->transport.sin.sin_port = serr->port;
memcpy(&srx->transport.sin.sin_addr,
skb_network_header(skb) + serr->addr_offset,
sizeof(struct in_addr));
break;
default:
memcpy(&srx->transport.sin6.sin6_addr,
&ipv6_hdr(skb)->saddr,
sizeof(struct in6_addr));
break;
}
break;
#endif
default:
BUG();
}
return rxrpc_lookup_peer_rcu(local, srx);
}
/*
* Handle an MTU/fragmentation problem.
*/
static void rxrpc_adjust_mtu(struct rxrpc_peer *peer, struct sock_exterr_skb *serr)
{
u32 mtu = serr->ee.ee_info;
_net("Rx ICMP Fragmentation Needed (%d)", mtu);
/* wind down the local interface MTU */
if (mtu > 0 && peer->if_mtu == 65535 && mtu < peer->if_mtu) {
peer->if_mtu = mtu;
_net("I/F MTU %u", mtu);
}
if (mtu == 0) {
/* they didn't give us a size, estimate one */
mtu = peer->if_mtu;
if (mtu > 1500) {
mtu >>= 1;
if (mtu < 1500)
mtu = 1500;
} else {
mtu -= 100;
if (mtu < peer->hdrsize)
mtu = peer->hdrsize + 4;
}
}
if (mtu < peer->mtu) {
spin_lock_bh(&peer->lock);
peer->mtu = mtu;
peer->maxdata = peer->mtu - peer->hdrsize;
spin_unlock_bh(&peer->lock);
_net("Net MTU %u (maxdata %u)",
peer->mtu, peer->maxdata);
}
}
/*
* Handle an error received on the local endpoint.
*/
void rxrpc_error_report(struct sock *sk)
{
struct sock_exterr_skb *serr;
struct sockaddr_rxrpc srx;
struct rxrpc_local *local = sk->sk_user_data;
struct rxrpc_peer *peer;
struct sk_buff *skb;
_enter("%p{%d}", sk, local->debug_id);
/* Clear the outstanding error value on the socket so that it doesn't
* cause kernel_sendmsg() to return it later.
*/
sock_error(sk);
skb = sock_dequeue_err_skb(sk);
if (!skb) {
_leave("UDP socket errqueue empty");
return;
}
rxrpc_new_skb(skb, rxrpc_skb_rx_received);
serr = SKB_EXT_ERR(skb);
if (!skb->len && serr->ee.ee_origin == SO_EE_ORIGIN_TIMESTAMPING) {
_leave("UDP empty message");
rxrpc_free_skb(skb, rxrpc_skb_rx_freed);
return;
}
rcu_read_lock();
peer = rxrpc_lookup_peer_icmp_rcu(local, skb, &srx);
if (peer && !rxrpc_get_peer_maybe(peer))
peer = NULL;
if (!peer) {
rcu_read_unlock();
rxrpc_free_skb(skb, rxrpc_skb_rx_freed);
_leave(" [no peer]");
return;
}
trace_rxrpc_rx_icmp(peer, &serr->ee, &srx);
if ((serr->ee.ee_origin == SO_EE_ORIGIN_ICMP &&
serr->ee.ee_type == ICMP_DEST_UNREACH &&
serr->ee.ee_code == ICMP_FRAG_NEEDED)) {
rxrpc_adjust_mtu(peer, serr);
rcu_read_unlock();
rxrpc_free_skb(skb, rxrpc_skb_rx_freed);
rxrpc_put_peer(peer);
_leave(" [MTU update]");
return;
}
rxrpc_store_error(peer, serr);
rcu_read_unlock();
rxrpc_free_skb(skb, rxrpc_skb_rx_freed);
rxrpc_put_peer(peer);
_leave("");
}
/*
* Map an error report to error codes on the peer record.
*/
static void rxrpc_store_error(struct rxrpc_peer *peer,
struct sock_exterr_skb *serr)
{
enum rxrpc_call_completion compl = RXRPC_CALL_NETWORK_ERROR;
struct sock_extended_err *ee;
int err;
_enter("");
ee = &serr->ee;
err = ee->ee_errno;
switch (ee->ee_origin) {
case SO_EE_ORIGIN_ICMP:
switch (ee->ee_type) {
case ICMP_DEST_UNREACH:
switch (ee->ee_code) {
case ICMP_NET_UNREACH:
_net("Rx Received ICMP Network Unreachable");
break;
case ICMP_HOST_UNREACH:
_net("Rx Received ICMP Host Unreachable");
break;
case ICMP_PORT_UNREACH:
_net("Rx Received ICMP Port Unreachable");
break;
case ICMP_NET_UNKNOWN:
_net("Rx Received ICMP Unknown Network");
break;
case ICMP_HOST_UNKNOWN:
_net("Rx Received ICMP Unknown Host");
break;
default:
_net("Rx Received ICMP DestUnreach code=%u",
ee->ee_code);
break;
}
break;
case ICMP_TIME_EXCEEDED:
_net("Rx Received ICMP TTL Exceeded");
break;
default:
_proto("Rx Received ICMP error { type=%u code=%u }",
ee->ee_type, ee->ee_code);
break;
}
break;
case SO_EE_ORIGIN_NONE:
case SO_EE_ORIGIN_LOCAL:
_proto("Rx Received local error { error=%d }", err);
compl = RXRPC_CALL_LOCAL_ERROR;
break;
case SO_EE_ORIGIN_ICMP6:
default:
_proto("Rx Received error report { orig=%u }", ee->ee_origin);
break;
}
rxrpc_distribute_error(peer, err, compl);
}
/*
* Distribute an error that occurred on a peer.
*/
static void rxrpc_distribute_error(struct rxrpc_peer *peer, int error,
enum rxrpc_call_completion compl)
{
struct rxrpc_call *call;
hlist_for_each_entry_rcu(call, &peer->error_targets, error_link) {
rxrpc_see_call(call);
if (call->state < RXRPC_CALL_COMPLETE &&
rxrpc_set_call_completion(call, compl, 0, -error))
rxrpc_notify_socket(call);
}
}
/*
* Add RTT information to cache. This is called in softirq mode and has
* exclusive access to the peer RTT data.
*/
void rxrpc_peer_add_rtt(struct rxrpc_call *call, enum rxrpc_rtt_rx_trace why,
rxrpc_serial_t send_serial, rxrpc_serial_t resp_serial,
ktime_t send_time, ktime_t resp_time)
{
struct rxrpc_peer *peer = call->peer;
s64 rtt;
u64 sum = peer->rtt_sum, avg;
u8 cursor = peer->rtt_cursor, usage = peer->rtt_usage;
rtt = ktime_to_ns(ktime_sub(resp_time, send_time));
if (rtt < 0)
return;
spin_lock(&peer->rtt_input_lock);
/* Replace the oldest datum in the RTT buffer */
sum -= peer->rtt_cache[cursor];
sum += rtt;
peer->rtt_cache[cursor] = rtt;
peer->rtt_cursor = (cursor + 1) & (RXRPC_RTT_CACHE_SIZE - 1);
peer->rtt_sum = sum;
if (usage < RXRPC_RTT_CACHE_SIZE) {
usage++;
peer->rtt_usage = usage;
}
spin_unlock(&peer->rtt_input_lock);
/* Now recalculate the average */
if (usage == RXRPC_RTT_CACHE_SIZE) {
avg = sum / RXRPC_RTT_CACHE_SIZE;
} else {
avg = sum;
do_div(avg, usage);
}
/* Don't need to update this under lock */
peer->rtt = avg;
trace_rxrpc_rtt_rx(call, why, send_serial, resp_serial, rtt,
usage, avg);
}
/*
* Perform keep-alive pings.
*/
static void rxrpc_peer_keepalive_dispatch(struct rxrpc_net *rxnet,
struct list_head *collector,
time64_t base,
u8 cursor)
{
struct rxrpc_peer *peer;
const u8 mask = ARRAY_SIZE(rxnet->peer_keepalive) - 1;
time64_t keepalive_at;
int slot;
spin_lock_bh(&rxnet->peer_hash_lock);
while (!list_empty(collector)) {
peer = list_entry(collector->next,
struct rxrpc_peer, keepalive_link);
list_del_init(&peer->keepalive_link);
if (!rxrpc_get_peer_maybe(peer))
continue;
spin_unlock_bh(&rxnet->peer_hash_lock);
keepalive_at = peer->last_tx_at + RXRPC_KEEPALIVE_TIME;
slot = keepalive_at - base;
_debug("%02x peer %u t=%d {%pISp}",
cursor, peer->debug_id, slot, &peer->srx.transport);
if (keepalive_at <= base ||
keepalive_at > base + RXRPC_KEEPALIVE_TIME) {
rxrpc_send_keepalive(peer);
slot = RXRPC_KEEPALIVE_TIME;
}
/* A transmission to this peer occurred since last we examined
* it so put it into the appropriate future bucket.
*/
slot += cursor;
slot &= mask;
spin_lock_bh(&rxnet->peer_hash_lock);
list_add_tail(&peer->keepalive_link,
&rxnet->peer_keepalive[slot & mask]);
rxrpc_put_peer(peer);
}
spin_unlock_bh(&rxnet->peer_hash_lock);
}
/*
* Perform keep-alive pings with VERSION packets to keep any NAT alive.
*/
void rxrpc_peer_keepalive_worker(struct work_struct *work)
{
struct rxrpc_net *rxnet =
container_of(work, struct rxrpc_net, peer_keepalive_work);
const u8 mask = ARRAY_SIZE(rxnet->peer_keepalive) - 1;
time64_t base, now, delay;
u8 cursor, stop;
LIST_HEAD(collector);
now = ktime_get_seconds();
base = rxnet->peer_keepalive_base;
cursor = rxnet->peer_keepalive_cursor;
_enter("%lld,%u", base - now, cursor);
if (!rxnet->live)
return;
/* Remove to a temporary list all the peers that are currently lodged
* in expired buckets plus all new peers.
*
* Everything in the bucket at the cursor is processed this
* second; the bucket at cursor + 1 goes at now + 1s and so
* on...
*/
spin_lock_bh(&rxnet->peer_hash_lock);
list_splice_init(&rxnet->peer_keepalive_new, &collector);
stop = cursor + ARRAY_SIZE(rxnet->peer_keepalive);
while (base <= now && (s8)(cursor - stop) < 0) {
list_splice_tail_init(&rxnet->peer_keepalive[cursor & mask],
&collector);
base++;
cursor++;
}
base = now;
spin_unlock_bh(&rxnet->peer_hash_lock);
rxnet->peer_keepalive_base = base;
rxnet->peer_keepalive_cursor = cursor;
rxrpc_peer_keepalive_dispatch(rxnet, &collector, base, cursor);
ASSERT(list_empty(&collector));
/* Schedule the timer for the next occupied timeslot. */
cursor = rxnet->peer_keepalive_cursor;
stop = cursor + RXRPC_KEEPALIVE_TIME - 1;
for (; (s8)(cursor - stop) < 0; cursor++) {
if (!list_empty(&rxnet->peer_keepalive[cursor & mask]))
break;
base++;
}
now = ktime_get_seconds();
delay = base - now;
if (delay < 1)
delay = 1;
delay *= HZ;
if (rxnet->live)
timer_reduce(&rxnet->peer_keepalive_timer, jiffies + delay);
_leave("");
}
| gpl-2.0 |
RazorX2012/TrinityCore | src/server/scripts/EasternKingdoms/ZulGurub/boss_jeklik.cpp | 9 | 11036 | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Jeklik
SD%Complete: 85
SDComment: Problem in finding the right flying batriders for spawning and making them fly.
SDCategory: Zul'Gurub
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulgurub.h"
enum Jeklik
{
SAY_AGGRO = 0,
SAY_RAIN_FIRE = 1,
SAY_DEATH = 2,
SPELL_CHARGE = 22911,
SPELL_SONICBURST = 23918,
SPELL_SCREECH = 6605,
SPELL_SHADOW_WORD_PAIN = 23952,
SPELL_MIND_FLAY = 23953,
SPELL_CHAIN_MIND_FLAY = 26044, //Right ID unknown. So disabled
SPELL_GREATERHEAL = 23954,
SPELL_BAT_FORM = 23966,
// Batriders Spell
SPELL_BOMB = 40332 //Wrong ID but Magmadars bomb is not working...
};
class boss_jeklik : public CreatureScript
{
public:
boss_jeklik()
: CreatureScript("boss_jeklik")
{
}
struct boss_jeklikAI : public ScriptedAI
{
boss_jeklikAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
uint32 Charge_Timer;
uint32 SonicBurst_Timer;
uint32 Screech_Timer;
uint32 SpawnBats_Timer;
uint32 ShadowWordPain_Timer;
uint32 MindFlay_Timer;
uint32 ChainMindFlay_Timer;
uint32 GreaterHeal_Timer;
uint32 SpawnFlyingBats_Timer;
bool PhaseTwo;
void Reset()
{
Charge_Timer = 20000;
SonicBurst_Timer = 8000;
Screech_Timer = 13000;
SpawnBats_Timer = 60000;
ShadowWordPain_Timer = 6000;
MindFlay_Timer = 11000;
ChainMindFlay_Timer = 26000;
GreaterHeal_Timer = 50000;
SpawnFlyingBats_Timer = 10000;
PhaseTwo = false;
}
void EnterCombat(Unit* /*who*/)
{
Talk(SAY_AGGRO);
DoCast(me, SPELL_BAT_FORM);
}
void JustDied(Unit* /*killer*/)
{
Talk(SAY_DEATH);
if (instance)
instance->SetData(DATA_JEKLIK, DONE);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (me->getVictim() && me->isAlive())
{
if (HealthAbovePct(50))
{
if (Charge_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
{
DoCast(target, SPELL_CHARGE);
AttackStart(target);
}
Charge_Timer = urand(15000, 30000);
} else Charge_Timer -= diff;
if (SonicBurst_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SONICBURST);
SonicBurst_Timer = urand(8000, 13000);
} else SonicBurst_Timer -= diff;
if (Screech_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_SCREECH);
Screech_Timer = urand(18000, 26000);
} else Screech_Timer -= diff;
if (SpawnBats_Timer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0);
Creature* Bat = NULL;
Bat = me->SummonCreature(11368, -12291.6220f, -1380.2640f, 144.8304f, 5.483f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
if (target && Bat) Bat ->AI()->AttackStart(target);
Bat = me->SummonCreature(11368, -12289.6220f, -1380.2640f, 144.8304f, 5.483f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
if (target && Bat) Bat ->AI()->AttackStart(target);
Bat = me->SummonCreature(11368, -12293.6220f, -1380.2640f, 144.8304f, 5.483f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
if (target && Bat) Bat ->AI()->AttackStart(target);
Bat = me->SummonCreature(11368, -12291.6220f, -1380.2640f, 144.8304f, 5.483f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
if (target && Bat) Bat ->AI()->AttackStart(target);
Bat = me->SummonCreature(11368, -12289.6220f, -1380.2640f, 144.8304f, 5.483f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
if (target && Bat) Bat ->AI()->AttackStart(target);
Bat = me->SummonCreature(11368, -12293.6220f, -1380.2640f, 144.8304f, 5.483f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
if (target && Bat) Bat ->AI()->AttackStart(target);
SpawnBats_Timer = 60000;
} else SpawnBats_Timer -= diff;
}
else
{
if (PhaseTwo)
{
if (PhaseTwo && ShadowWordPain_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
{
DoCast(target, SPELL_SHADOW_WORD_PAIN);
ShadowWordPain_Timer = urand(12000, 18000);
}
}ShadowWordPain_Timer -=diff;
if (MindFlay_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_MIND_FLAY);
MindFlay_Timer = 16000;
}MindFlay_Timer -=diff;
if (ChainMindFlay_Timer <= diff)
{
me->InterruptNonMeleeSpells(false);
DoCast(me->getVictim(), SPELL_CHAIN_MIND_FLAY);
ChainMindFlay_Timer = urand(15000, 30000);
}ChainMindFlay_Timer -=diff;
if (GreaterHeal_Timer <= diff)
{
me->InterruptNonMeleeSpells(false);
DoCast(me, SPELL_GREATERHEAL);
GreaterHeal_Timer = urand(25000, 35000);
}GreaterHeal_Timer -=diff;
if (SpawnFlyingBats_Timer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0);
if (!target)
return;
Creature* FlyingBat = me->SummonCreature(14965, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()+15, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000);
if (FlyingBat)
FlyingBat->AI()->AttackStart(target);
SpawnFlyingBats_Timer = urand(10000, 15000);
} else SpawnFlyingBats_Timer -=diff;
}
else
{
me->SetDisplayId(15219);
DoResetThreat();
PhaseTwo = true;
}
}
DoMeleeAttackIfReady();
}
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_jeklikAI(creature);
}
};
//Flying Bat
class mob_batrider : public CreatureScript
{
public:
mob_batrider()
: CreatureScript("mob_batrider")
{
}
struct mob_batriderAI : public ScriptedAI
{
mob_batriderAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
uint32 Bomb_Timer;
uint32 Check_Timer;
void Reset()
{
Bomb_Timer = 2000;
Check_Timer = 1000;
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
void EnterCombat(Unit* /*who*/) {}
void UpdateAI (const uint32 diff)
{
if (!UpdateVictim())
return;
//Bomb_Timer
if (Bomb_Timer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
{
DoCast(target, SPELL_BOMB);
Bomb_Timer = 5000;
}
} else Bomb_Timer -= diff;
//Check_Timer
if (Check_Timer <= diff)
{
if (instance)
{
if (instance->GetData(DATA_JEKLIK) == DONE)
{
me->setDeathState(JUST_DIED);
me->RemoveCorpse();
return;
}
}
Check_Timer = 1000;
} else Check_Timer -= diff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new mob_batriderAI(creature);
}
};
void AddSC_boss_jeklik()
{
new boss_jeklik();
new mob_batrider();
}
| gpl-2.0 |
codie72/TrinityCore | src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp | 9 | 10049 | /*
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "vault_of_archavon.h"
enum Events
{
// Koralon
EVENT_BURNING_BREATH = 1,
EVENT_BURNING_FURY = 2,
EVENT_FLAME_CINDER = 3,
EVENT_METEOR_FISTS = 4,
// Flame Warder
EVENT_FW_LAVA_BIRST = 5,
EVENT_FW_METEOR_FISTS = 6
};
enum Spells
{
// Spells Koralon
SPELL_BURNING_BREATH = 66665,
SPELL_BURNING_FURY = 66721,
SPELL_FLAME_CINDER_A = 66684,
SPELL_FLAME_CINDER_B = 66681, // don't know the real relation to SPELL_FLAME_CINDER_A atm.
SPELL_METEOR_FISTS = 66725,
SPELL_METEOR_FISTS_DAMAGE = 66765,
// Spells Flame Warder
SPELL_FW_LAVA_BIRST = 66813,
SPELL_FW_METEOR_FISTS = 66808,
SPELL_FW_METEOR_FISTS_DAMAGE = 66809
};
class boss_koralon : public CreatureScript
{
public:
boss_koralon() : CreatureScript("boss_koralon") { }
struct boss_koralonAI : public BossAI
{
boss_koralonAI(Creature* creature) : BossAI(creature, DATA_KORALON)
{
}
void EnterCombat(Unit* /*who*/) override
{
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000); /// @todo check timer
events.ScheduleEvent(EVENT_BURNING_BREATH, 15000); // 1st after 15sec, then every 45sec
events.ScheduleEvent(EVENT_METEOR_FISTS, 75000); // 1st after 75sec, then every 45sec
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000); /// @todo check timer
_EnterCombat();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BURNING_FURY:
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000);
break;
case EVENT_BURNING_BREATH:
DoCast(me, SPELL_BURNING_BREATH);
events.ScheduleEvent(EVENT_BURNING_BREATH, 45000);
break;
case EVENT_METEOR_FISTS:
DoCast(me, SPELL_METEOR_FISTS);
events.ScheduleEvent(EVENT_METEOR_FISTS, 45000);
break;
case EVENT_FLAME_CINDER:
DoCast(me, SPELL_FLAME_CINDER_A);
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000);
break;
default:
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_koralonAI(creature);
}
};
/*######
## Npc Flame Warder
######*/
class npc_flame_warder : public CreatureScript
{
public:
npc_flame_warder() : CreatureScript("npc_flame_warder") { }
struct npc_flame_warderAI : public ScriptedAI
{
npc_flame_warderAI(Creature* creature) : ScriptedAI(creature)
{
}
void Reset() override
{
events.Reset();
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 5000);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 10000);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FW_LAVA_BIRST:
DoCastVictim(SPELL_FW_LAVA_BIRST);
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 15000);
break;
case EVENT_FW_METEOR_FISTS:
DoCast(me, SPELL_FW_METEOR_FISTS);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 20000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_flame_warderAI(creature);
}
};
class spell_koralon_meteor_fists : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists() : SpellScriptLoader("spell_koralon_meteor_fists") { }
class spell_koralon_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_koralon_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_koralon_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_koralon_meteor_fists_AuraScript();
}
};
class spell_koralon_meteor_fists_damage : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists_damage() : SpellScriptLoader("spell_koralon_meteor_fists_damage") { }
class spell_koralon_meteor_fists_damage_SpellScript : public SpellScript
{
PrepareSpellScript(spell_koralon_meteor_fists_damage_SpellScript);
public:
spell_koralon_meteor_fists_damage_SpellScript()
{
_chainTargets = 0;
}
private:
void FilterTargets(std::list<WorldObject*>& targets)
{
_chainTargets = targets.size();
}
void CalculateSplitDamage()
{
if (_chainTargets)
SetHitDamage(GetHitDamage() / (_chainTargets + 1));
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_koralon_meteor_fists_damage_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_TARGET_ENEMY);
OnHit += SpellHitFn(spell_koralon_meteor_fists_damage_SpellScript::CalculateSplitDamage);
}
private:
uint8 _chainTargets;
};
SpellScript* GetSpellScript() const override
{
return new spell_koralon_meteor_fists_damage_SpellScript();
}
};
class spell_flame_warder_meteor_fists : public SpellScriptLoader
{
public:
spell_flame_warder_meteor_fists() : SpellScriptLoader("spell_flame_warder_meteor_fists") { }
class spell_flame_warder_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_flame_warder_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_FW_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_flame_warder_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_flame_warder_meteor_fists_AuraScript();
}
};
void AddSC_boss_koralon()
{
new boss_koralon();
new npc_flame_warder();
new spell_koralon_meteor_fists();
new spell_koralon_meteor_fists_damage();
new spell_flame_warder_meteor_fists();
}
| gpl-2.0 |
rhuitl/uClinux | user/nessus/nessus-libraries/libnessus/resolve.c | 9 | 2142 | /* Nessuslib -- the Nessus Library
* Copyright (C) 1998 Renaud Deraison
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Hostname resolver.
*/
#define EXPORTING
#include <includes.h>
#include "resolve.h"
#ifndef __u32
#define __u32 unsigned long
#endif
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif
ExtFunc int
host2ip(name, ip)
char * name;
struct in_addr * ip;
{
#undef HAVE_GETHOSTBYNAME_R
#ifdef HAVE_GETHOSTBYNAME_R
int Errno = 0;
char * buf = emalloc(4096);
struct hostent * res = NULL;
struct hostent * t = NULL;
struct hostent * myhostent;
myhostent = emalloc(sizeof(struct hostent));
#undef HAVE_SOLARIS_GETHOSTBYNAME_R
#ifdef HAVE_SOLARIS_GETHOSTBYNAME_R
gethostbyname_r(name, myhostent, buf, 4096, &Errno);
if(Errno){
efree(&myhostent);
efree(&buf);
return -1;
}
#else
gethostbyname_r(name, myhostent, buf, 4096, &res, &Errno);
t = myhostent;
myhostent = res;
#endif /* HAVE_SOLARIS_... */
memcpy(ip, myhostent->h_addr, myhostent->h_length);
efree(&myhostent);
efree(&buf);
return 0;
#else
struct hostent * ent;
ent = gethostbyname(name);
if(!ent)
return -1;
else if(ip) memcpy(ip, ent->h_addr, ent->h_length);
return 0; /* success */
#endif /* defined(GETHOSTBYNAME_R) */
}
struct in_addr
nn_resolve(name)
const char * name;
{
struct in_addr ret;
if(host2ip(name, &ret) < 0)
{
ret.s_addr = INADDR_NONE;
}
return ret;
}
| gpl-2.0 |
kaltsi/valgrind | none/tests/s390x/fpconv.c | 9 | 8391 | /* basic float <-> signed int conversions available since z900 */
#include <float.h>
#include <stdio.h>
#include "opcodes.h"
#define I2F(insn, initial, target,round) \
({ \
register unsigned long source asm("2") = initial; \
register typeof(target) _t asm("f0"); \
asm volatile(insn " 0,2\n\t" :"=f" (_t):"d"(source)); \
_t; \
})
#define F2L(insn, initial, type, round, cc) \
({ \
register type source asm("f0") = initial; \
register unsigned long target asm ("2") = 0; \
asm volatile(insn " 2," #round ",0\n\t" \
"ipm %1\n\t" \
"srl %1,28\n\t" \
:"=d" (target), "=d" (cc) :"f"(source):"cc"); \
target; \
})
#define DO_INSN_I2F32(insn, round) \
({ \
float f32; \
printf(#insn " %f\n", I2F(insn, 0, f32, round)); \
printf(#insn " %f\n", I2F(insn, 1, f32, round)); \
printf(#insn " %f\n", I2F(insn, 0xffffffffUL, f32, round)); \
printf(#insn " %f\n", I2F(insn, 0x80000000UL, f32, round)); \
printf(#insn " %f\n", I2F(insn, 0x7fffffffUL, f32, round)); \
printf(#insn " %f\n", I2F(insn, 0x100000000UL, f32, round)); \
printf(#insn " %f\n", I2F(insn, 0xffffffffffffffffUL, f32, round)); \
printf(#insn " %f\n", I2F(insn, 0x8000000000000000UL, f32, round)); \
printf(#insn " %f\n", I2F(insn, 0x7fffffffffffffffUL, f32, round)); \
})
#define DO_INSN_I2F64(insn, round) \
({ \
double f64; \
printf(#insn " %f\n", I2F(insn, 0, f64, round)); \
printf(#insn " %f\n", I2F(insn, 1, f64, round)); \
printf(#insn " %f\n", I2F(insn, 0xffffffffUL, f64, round)); \
printf(#insn " %f\n", I2F(insn, 0x80000000UL, f64, round)); \
printf(#insn " %f\n", I2F(insn, 0x7fffffffUL, f64, round)); \
printf(#insn " %f\n", I2F(insn, 0x100000000UL, f64, round)); \
printf(#insn " %f\n", I2F(insn, 0xffffffffffffffffUL, f64, round)); \
printf(#insn " %f\n", I2F(insn, 0x8000000000000000UL, f64, round)); \
printf(#insn " %f\n", I2F(insn, 0x7fffffffffffffffUL, f64, round)); \
})
#define DO_INSN_I2F128(insn, round) \
({ \
long double f128; \
printf(#insn " %Lf\n", I2F(insn, 0, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 1, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 0xffffffffUL, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 0x80000000UL, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 0x7fffffffUL, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 0x100000000UL, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 0xffffffffffffffffUL, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 0x8000000000000000UL, f128, round)); \
printf(#insn " %Lf\n", I2F(insn, 0x7fffffffffffffffUL, f128, round)); \
})
#define DO_INSN_F2L(insn, round, type) \
({ \
int cc; \
printf(#insn " %ld ", F2L(insn, -1.1, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 0, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.4, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.5, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6E+4, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6E+8, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6E+12, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6E+20, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6E+200, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6E+2000L, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, 1.6E-4, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, FLT_MIN, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, FLT_MAX, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, DBL_MIN, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, DBL_MAX, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, LDBL_MIN, type, round, cc)); \
printf("cc=%d\n", cc); \
printf(#insn " %ld ", F2L(insn, LDBL_MAX, type, round, cc)); \
printf("cc=%d\n", cc); \
})
#define DO_I2F(round) \
({ \
DO_INSN_I2F32("cefbr", round); \
DO_INSN_I2F32("cegbr", round); \
DO_INSN_I2F64("cdfbr", round); \
DO_INSN_I2F64("cdgbr", round); \
DO_INSN_I2F128("cxfbr", round); \
DO_INSN_I2F128("cxgbr", round); \
})
#define DO_F2L(round) \
({ \
DO_INSN_F2L("cfebr", round, float); \
DO_INSN_F2L("cgebr", round, float); \
DO_INSN_F2L("cfdbr", round, double); \
DO_INSN_F2L("cgdbr", round, double); \
DO_INSN_F2L("cfxbr", round, long double); \
DO_INSN_F2L("cgxbr", round, long double); \
})
int main()
{
DO_I2F(4);
DO_F2L(4);
DO_I2F(5);
DO_F2L(5);
DO_I2F(6);
DO_F2L(6);
DO_I2F(7);
DO_F2L(7);
return 0;
}
| gpl-2.0 |
Phoenix-CJ23/stockkernel | arch/arm/mach-msm/restart.c | 9 | 10098 | /* Copyright (c) 2010-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/reboot.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/cpu.h>
#include <linux/interrupt.h>
#include <linux/mfd/pmic8058.h>
#include <linux/mfd/pmic8901.h>
#include <linux/mfd/pm8xxx/misc.h>
#include <linux/qpnp/power-on.h>
#include <asm/mach-types.h>
#include <asm/cacheflush.h>
#include <mach/msm_iomap.h>
#include <mach/restart.h>
#include <mach/socinfo.h>
#include <mach/irqs.h>
#include <mach/scm.h>
#include "msm_watchdog.h"
#include "timer.h"
#include "wdog_debug.h"
#ifdef CONFIG_LGE_HANDLE_PANIC
#include <mach/lge_handle_panic.h>
#include <mach/board_lge.h>
#endif
#define WDT0_RST 0x38
#define WDT0_EN 0x40
#define WDT0_BARK_TIME 0x4C
#define WDT0_BITE_TIME 0x5C
#define PSHOLD_CTL_SU (MSM_TLMM_BASE + 0x820)
#define RESTART_REASON_ADDR 0x65C
#define DLOAD_MODE_ADDR 0x0
#define EMERGENCY_DLOAD_MODE_ADDR 0xFE0
#define EMERGENCY_DLOAD_MAGIC1 0x322A4F99
#define EMERGENCY_DLOAD_MAGIC2 0xC67E4350
#define EMERGENCY_DLOAD_MAGIC3 0x77777777
#define SCM_IO_DISABLE_PMIC_ARBITER 1
#ifdef CONFIG_MSM_RESTART_V2
#define use_restart_v2() 1
#else
#define use_restart_v2() 0
#endif
static int restart_mode;
void *restart_reason;
int pmic_reset_irq;
static void __iomem *msm_tmr0_base;
#ifdef CONFIG_MSM_DLOAD_MODE
static int in_panic;
static void *dload_mode_addr;
static bool dload_mode_enabled;
static void *emergency_dload_mode_addr;
/* Download mode master kill-switch */
static int dload_set(const char *val, struct kernel_param *kp);
static int download_mode;
module_param_call(download_mode, dload_set, param_get_int,
&download_mode, 0644);
static int panic_prep_restart(struct notifier_block *this,
unsigned long event, void *ptr)
{
in_panic = 1;
return NOTIFY_DONE;
}
static struct notifier_block panic_blk = {
.notifier_call = panic_prep_restart,
};
static void set_dload_mode(int on)
{
if (dload_mode_addr) {
__raw_writel(on ? 0xE47B337D : 0, dload_mode_addr);
__raw_writel(on ? 0xCE14091A : 0,
dload_mode_addr + sizeof(unsigned int));
mb();
dload_mode_enabled = on;
}
}
static bool get_dload_mode(void)
{
return dload_mode_enabled;
}
static void enable_emergency_dload_mode(void)
{
if (emergency_dload_mode_addr) {
__raw_writel(EMERGENCY_DLOAD_MAGIC1,
emergency_dload_mode_addr);
__raw_writel(EMERGENCY_DLOAD_MAGIC2,
emergency_dload_mode_addr +
sizeof(unsigned int));
__raw_writel(EMERGENCY_DLOAD_MAGIC3,
emergency_dload_mode_addr +
(2 * sizeof(unsigned int)));
mb();
}
}
static int dload_set(const char *val, struct kernel_param *kp)
{
int ret;
int old_val = download_mode;
ret = param_set_int(val, kp);
if (ret)
return ret;
/* If download_mode is not zero or one, ignore. */
if (download_mode >> 1) {
download_mode = old_val;
return -EINVAL;
}
#ifdef CONFIG_LGE_HANDLE_PANIC
if (lge_get_laf_mode() == LGE_LAF_MODE_LAF)
download_mode = 1;
#endif
set_dload_mode(download_mode);
return 0;
}
#else
#define set_dload_mode(x) do {} while (0)
static void enable_emergency_dload_mode(void)
{
printk(KERN_ERR "dload mode is not enabled on target\n");
}
static bool get_dload_mode(void)
{
return false;
}
#endif
void msm_set_restart_mode(int mode)
{
restart_mode = mode;
}
EXPORT_SYMBOL(msm_set_restart_mode);
static bool scm_pmic_arbiter_disable_supported;
/*
* Force the SPMI PMIC arbiter to shutdown so that no more SPMI transactions
* are sent from the MSM to the PMIC. This is required in order to avoid an
* SPMI lockup on certain PMIC chips if PS_HOLD is lowered in the middle of
* an SPMI transaction.
*/
static void halt_spmi_pmic_arbiter(void)
{
if (scm_pmic_arbiter_disable_supported) {
pr_crit("Calling SCM to disable SPMI PMIC arbiter\n");
scm_call_atomic1(SCM_SVC_PWR, SCM_IO_DISABLE_PMIC_ARBITER, 0);
}
}
static void __msm_power_off(int lower_pshold)
{
printk(KERN_CRIT "Powering off the SoC\n");
#ifdef CONFIG_MSM_DLOAD_MODE
set_dload_mode(0);
#endif
pm8xxx_reset_pwr_off(0);
qpnp_pon_system_pwr_off(PON_POWER_OFF_SHUTDOWN);
if (lower_pshold) {
if (!use_restart_v2()) {
__raw_writel(0, PSHOLD_CTL_SU);
} else {
halt_spmi_pmic_arbiter();
__raw_writel(0, MSM_MPM2_PSHOLD_BASE);
}
mdelay(10000);
printk(KERN_ERR "Powering off has failed\n");
}
return;
}
static void msm_power_off(void)
{
/* MSM initiated power off, lower ps_hold */
__msm_power_off(1);
}
static void cpu_power_off(void *data)
{
int rc;
pr_err("PMIC Initiated shutdown %s cpu=%d\n", __func__,
smp_processor_id());
if (smp_processor_id() == 0) {
/*
* PMIC initiated power off, do not lower ps_hold, pmic will
* shut msm down
*/
__msm_power_off(0);
pet_watchdog();
pr_err("Calling scm to disable arbiter\n");
/* call secure manager to disable arbiter and never return */
rc = scm_call_atomic1(SCM_SVC_PWR,
SCM_IO_DISABLE_PMIC_ARBITER, 1);
pr_err("SCM returned even when asked to busy loop rc=%d\n", rc);
pr_err("waiting on pmic to shut msm down\n");
}
preempt_disable();
while (1)
;
}
static irqreturn_t resout_irq_handler(int irq, void *dev_id)
{
pr_warn("%s PMIC Initiated shutdown\n", __func__);
oops_in_progress = 1;
smp_call_function_many(cpu_online_mask, cpu_power_off, NULL, 0);
if (smp_processor_id() == 0)
cpu_power_off(NULL);
preempt_disable();
while (1)
;
return IRQ_HANDLED;
}
static void msm_restart_prepare(const char *cmd)
{
#ifdef CONFIG_MSM_DLOAD_MODE
/* This looks like a normal reboot at this point. */
set_dload_mode(0);
/* Write download mode flags if we're panic'ing */
set_dload_mode(in_panic);
#ifndef CONFIG_LGE_HANDLE_PANIC
/* Write download mode flags if restart_mode says so */
if (restart_mode == RESTART_DLOAD)
set_dload_mode(1);
#endif
/* Kill download mode if master-kill switch is set */
if (!download_mode)
set_dload_mode(0);
#endif
pm8xxx_reset_pwr_off(1);
/* Hard reset the PMIC unless memory contents must be maintained. */
/* LGE_CHANGE : there's no reason to forcing a hard reset on reboot request */
if (true || get_dload_mode() || (cmd != NULL && cmd[0] != '\0'))
qpnp_pon_system_pwr_off(PON_POWER_OFF_WARM_RESET);
else
qpnp_pon_system_pwr_off(PON_POWER_OFF_HARD_RESET);
if (cmd != NULL) {
if (!strncmp(cmd, "bootloader", 10)) {
__raw_writel(0x77665500, restart_reason);
} else if (!strncmp(cmd, "recovery", 8)) {
__raw_writel(0x77665502, restart_reason);
#ifdef CONFIG_LGE_BNR_RECOVERY_REBOOT
/* PC Sync B&R : Add restart reason */
} else if (!strncmp(cmd, "--bnr_recovery", 14)) {
__raw_writel(0x77665555, restart_reason);
#endif
} else if (!strncmp(cmd, "oem-", 4)) {
/*
* oem-10 : used diag comand 250-105-1 power off
* oem-11 : battery remove insert irq restart
* oem-52 : laf download restart
*/
unsigned long code;
code = simple_strtoul(cmd + 4, NULL, 16) & 0xff;
__raw_writel(0x6f656d00 | code, restart_reason);
} else if (!strncmp(cmd, "edl", 3)) {
enable_emergency_dload_mode();
} else {
__raw_writel(0x77665501, restart_reason);
}
}
#ifdef CONFIG_LGE_HANDLE_PANIC
else
__raw_writel(0x77665503, restart_reason);
if (restart_mode == RESTART_DLOAD)
lge_set_restart_reason(LAF_DLOAD_MODE);
if (in_panic)
lge_set_panic_reason();
#endif
flush_cache_all();
outer_flush_all();
}
void msm_restart(char mode, const char *cmd)
{
printk(KERN_NOTICE "Going down for restart now\n");
msm_restart_prepare(cmd);
if (!use_restart_v2()) {
__raw_writel(0, msm_tmr0_base + WDT0_EN);
if (!(machine_is_msm8x60_fusion() ||
machine_is_msm8x60_fusn_ffa())) {
mb();
/* Actually reset the chip */
__raw_writel(0, PSHOLD_CTL_SU);
mdelay(5000);
pr_notice("PS_HOLD didn't work, falling back to watchdog\n");
}
__raw_writel(1, msm_tmr0_base + WDT0_RST);
__raw_writel(5*0x31F3, msm_tmr0_base + WDT0_BARK_TIME);
__raw_writel(0x31F3, msm_tmr0_base + WDT0_BITE_TIME);
__raw_writel(1, msm_tmr0_base + WDT0_EN);
} else {
/* Needed to bypass debug image on some chips */
msm_disable_wdog_debug();
halt_spmi_pmic_arbiter();
__raw_writel(0, MSM_MPM2_PSHOLD_BASE);
}
mdelay(10000);
printk(KERN_ERR "Restarting has failed\n");
}
static int __init msm_pmic_restart_init(void)
{
int rc;
if (use_restart_v2())
return 0;
if (pmic_reset_irq != 0) {
rc = request_any_context_irq(pmic_reset_irq,
resout_irq_handler, IRQF_TRIGGER_HIGH,
"restart_from_pmic", NULL);
if (rc < 0)
pr_err("pmic restart irq fail rc = %d\n", rc);
} else {
pr_warn("no pmic restart interrupt specified\n");
}
return 0;
}
late_initcall(msm_pmic_restart_init);
static int __init msm_restart_init(void)
{
#ifdef CONFIG_LGE_HANDLE_PANIC
/* Set default restart_reason to TZ crash.
* If can't be set explicit, it causes by TZ */
lge_set_restart_reason(LGE_RB_MAGIC | LGE_ERR_TZ);
if (lge_get_laf_mode() == LGE_LAF_MODE_LAF)
download_mode = 1;
#endif
#ifdef CONFIG_MSM_DLOAD_MODE
atomic_notifier_chain_register(&panic_notifier_list, &panic_blk);
dload_mode_addr = MSM_IMEM_BASE + DLOAD_MODE_ADDR;
emergency_dload_mode_addr = MSM_IMEM_BASE +
EMERGENCY_DLOAD_MODE_ADDR;
set_dload_mode(download_mode);
#endif
msm_tmr0_base = msm_timer_get_timer0_base();
restart_reason = MSM_IMEM_BASE + RESTART_REASON_ADDR;
pm_power_off = msm_power_off;
if (scm_is_call_available(SCM_SVC_PWR, SCM_IO_DISABLE_PMIC_ARBITER) > 0)
scm_pmic_arbiter_disable_supported = true;
return 0;
}
early_initcall(msm_restart_init);
| gpl-2.0 |
yixia/x264 | encoder/cabac.c | 9 | 48744 | /*****************************************************************************
* cabac.c: cabac bitstream writing
*****************************************************************************
* Copyright (C) 2003-2013 x264 project
*
* Authors: Laurent Aimar <fenrir@via.ecp.fr>
* Loren Merritt <lorenm@u.washington.edu>
* Jason Garrett-Glaser <darkshikari@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
*
* This program is also available under a commercial proprietary license.
* For more information, contact us at licensing@x264.com.
*****************************************************************************/
#include "common/common.h"
#include "macroblock.h"
#ifndef RDO_SKIP_BS
#define RDO_SKIP_BS 0
#endif
static inline void x264_cabac_mb_type_intra( x264_t *h, x264_cabac_t *cb, int i_mb_type,
int ctx0, int ctx1, int ctx2, int ctx3, int ctx4, int ctx5 )
{
if( i_mb_type == I_4x4 || i_mb_type == I_8x8 )
{
x264_cabac_encode_decision_noup( cb, ctx0, 0 );
}
#if !RDO_SKIP_BS
else if( i_mb_type == I_PCM )
{
x264_cabac_encode_decision_noup( cb, ctx0, 1 );
x264_cabac_encode_flush( h, cb );
}
#endif
else
{
int i_pred = x264_mb_pred_mode16x16_fix[h->mb.i_intra16x16_pred_mode];
x264_cabac_encode_decision_noup( cb, ctx0, 1 );
x264_cabac_encode_terminal( cb );
x264_cabac_encode_decision_noup( cb, ctx1, !!h->mb.i_cbp_luma );
if( h->mb.i_cbp_chroma == 0 )
x264_cabac_encode_decision_noup( cb, ctx2, 0 );
else
{
x264_cabac_encode_decision( cb, ctx2, 1 );
x264_cabac_encode_decision_noup( cb, ctx3, h->mb.i_cbp_chroma>>1 );
}
x264_cabac_encode_decision( cb, ctx4, i_pred>>1 );
x264_cabac_encode_decision_noup( cb, ctx5, i_pred&1 );
}
}
#if !RDO_SKIP_BS
static void x264_cabac_field_decoding_flag( x264_t *h, x264_cabac_t *cb )
{
int ctx = 0;
ctx += h->mb.field_decoding_flag & !!h->mb.i_mb_x;
ctx += (h->mb.i_mb_top_mbpair_xy >= 0
&& h->mb.slice_table[h->mb.i_mb_top_mbpair_xy] == h->sh.i_first_mb
&& h->mb.field[h->mb.i_mb_top_mbpair_xy]);
x264_cabac_encode_decision_noup( cb, 70 + ctx, MB_INTERLACED );
h->mb.field_decoding_flag = MB_INTERLACED;
}
#endif
static void x264_cabac_intra4x4_pred_mode( x264_cabac_t *cb, int i_pred, int i_mode )
{
if( i_pred == i_mode )
x264_cabac_encode_decision( cb, 68, 1 );
else
{
x264_cabac_encode_decision( cb, 68, 0 );
if( i_mode > i_pred )
i_mode--;
x264_cabac_encode_decision( cb, 69, (i_mode )&0x01 );
x264_cabac_encode_decision( cb, 69, (i_mode >> 1)&0x01 );
x264_cabac_encode_decision( cb, 69, (i_mode >> 2) );
}
}
static void x264_cabac_intra_chroma_pred_mode( x264_t *h, x264_cabac_t *cb )
{
int i_mode = x264_mb_chroma_pred_mode_fix[h->mb.i_chroma_pred_mode];
int ctx = 0;
/* No need to test for I4x4 or I_16x16 as cache_save handle that */
if( (h->mb.i_neighbour & MB_LEFT) && h->mb.chroma_pred_mode[h->mb.i_mb_left_xy[0]] != 0 )
ctx++;
if( (h->mb.i_neighbour & MB_TOP) && h->mb.chroma_pred_mode[h->mb.i_mb_top_xy] != 0 )
ctx++;
x264_cabac_encode_decision_noup( cb, 64 + ctx, i_mode > 0 );
if( i_mode > 0 )
{
x264_cabac_encode_decision( cb, 64 + 3, i_mode > 1 );
if( i_mode > 1 )
x264_cabac_encode_decision_noup( cb, 64 + 3, i_mode > 2 );
}
}
static void x264_cabac_cbp_luma( x264_t *h, x264_cabac_t *cb )
{
int cbp = h->mb.i_cbp_luma;
int cbp_l = h->mb.cache.i_cbp_left;
int cbp_t = h->mb.cache.i_cbp_top;
x264_cabac_encode_decision ( cb, 76 - ((cbp_l >> 1) & 1) - ((cbp_t >> 1) & 2), (cbp >> 0) & 1 );
x264_cabac_encode_decision ( cb, 76 - ((cbp >> 0) & 1) - ((cbp_t >> 2) & 2), (cbp >> 1) & 1 );
x264_cabac_encode_decision ( cb, 76 - ((cbp_l >> 3) & 1) - ((cbp << 1) & 2), (cbp >> 2) & 1 );
x264_cabac_encode_decision_noup( cb, 76 - ((cbp >> 2) & 1) - ((cbp >> 0) & 2), (cbp >> 3) & 1 );
}
static void x264_cabac_cbp_chroma( x264_t *h, x264_cabac_t *cb )
{
int cbp_a = h->mb.cache.i_cbp_left & 0x30;
int cbp_b = h->mb.cache.i_cbp_top & 0x30;
int ctx = 0;
if( cbp_a && h->mb.cache.i_cbp_left != -1 ) ctx++;
if( cbp_b && h->mb.cache.i_cbp_top != -1 ) ctx+=2;
if( h->mb.i_cbp_chroma == 0 )
x264_cabac_encode_decision_noup( cb, 77 + ctx, 0 );
else
{
x264_cabac_encode_decision_noup( cb, 77 + ctx, 1 );
ctx = 4;
if( cbp_a == 0x20 ) ctx++;
if( cbp_b == 0x20 ) ctx += 2;
x264_cabac_encode_decision_noup( cb, 77 + ctx, h->mb.i_cbp_chroma >> 1 );
}
}
static void x264_cabac_qp_delta( x264_t *h, x264_cabac_t *cb )
{
int i_dqp = h->mb.i_qp - h->mb.i_last_qp;
int ctx;
/* Avoid writing a delta quant if we have an empty i16x16 block, e.g. in a completely
* flat background area. Don't do this if it would raise the quantizer, since that could
* cause unexpected deblocking artifacts. */
if( h->mb.i_type == I_16x16 && !h->mb.cbp[h->mb.i_mb_xy] && h->mb.i_qp > h->mb.i_last_qp )
{
#if !RDO_SKIP_BS
h->mb.i_qp = h->mb.i_last_qp;
#endif
i_dqp = 0;
}
ctx = h->mb.i_last_dqp && (h->mb.type[h->mb.i_mb_prev_xy] == I_16x16 || (h->mb.cbp[h->mb.i_mb_prev_xy]&0x3f));
if( i_dqp != 0 )
{
/* Faster than (i_dqp <= 0 ? (-2*i_dqp) : (2*i_dqp-1)).
* If you so much as sneeze on these lines, gcc will compile this suboptimally. */
i_dqp *= 2;
int val = 1 - i_dqp;
if( val < 0 ) val = i_dqp;
val--;
/* dqp is interpreted modulo (QP_MAX_SPEC+1) */
if( val >= QP_MAX_SPEC && val != QP_MAX_SPEC+1 )
val = 2*QP_MAX_SPEC+1 - val;
do
{
x264_cabac_encode_decision( cb, 60 + ctx, 1 );
ctx = 2+(ctx>>1);
} while( --val );
}
x264_cabac_encode_decision_noup( cb, 60 + ctx, 0 );
}
#if !RDO_SKIP_BS
void x264_cabac_mb_skip( x264_t *h, int b_skip )
{
int ctx = h->mb.cache.i_neighbour_skip + 11;
if( h->sh.i_type != SLICE_TYPE_P )
ctx += 13;
x264_cabac_encode_decision( &h->cabac, ctx, b_skip );
}
#endif
static inline void x264_cabac_subpartition_p( x264_cabac_t *cb, int i_sub )
{
if( i_sub == D_L0_8x8 )
{
x264_cabac_encode_decision( cb, 21, 1 );
return;
}
x264_cabac_encode_decision( cb, 21, 0 );
if( i_sub == D_L0_8x4 )
x264_cabac_encode_decision( cb, 22, 0 );
else
{
x264_cabac_encode_decision( cb, 22, 1 );
x264_cabac_encode_decision( cb, 23, i_sub == D_L0_4x8 );
}
}
static ALWAYS_INLINE void x264_cabac_subpartition_b( x264_cabac_t *cb, int i_sub )
{
if( i_sub == D_DIRECT_8x8 )
{
x264_cabac_encode_decision( cb, 36, 0 );
return;
}
x264_cabac_encode_decision( cb, 36, 1 );
if( i_sub == D_BI_8x8 )
{
x264_cabac_encode_decision( cb, 37, 1 );
x264_cabac_encode_decision( cb, 38, 0 );
x264_cabac_encode_decision( cb, 39, 0 );
x264_cabac_encode_decision( cb, 39, 0 );
return;
}
x264_cabac_encode_decision( cb, 37, 0 );
x264_cabac_encode_decision( cb, 39, i_sub == D_L1_8x8 );
}
static ALWAYS_INLINE void x264_cabac_transform_size( x264_t *h, x264_cabac_t *cb )
{
int ctx = 399 + h->mb.cache.i_neighbour_transform_size;
x264_cabac_encode_decision_noup( cb, ctx, h->mb.b_transform_8x8 );
}
static ALWAYS_INLINE void x264_cabac_ref_internal( x264_t *h, x264_cabac_t *cb, int i_list, int idx, int bframe )
{
const int i8 = x264_scan8[idx];
const int i_refa = h->mb.cache.ref[i_list][i8 - 1];
const int i_refb = h->mb.cache.ref[i_list][i8 - 8];
int ctx = 0;
if( i_refa > 0 && (!bframe || !h->mb.cache.skip[i8 - 1]) )
ctx++;
if( i_refb > 0 && (!bframe || !h->mb.cache.skip[i8 - 8]) )
ctx += 2;
for( int i_ref = h->mb.cache.ref[i_list][i8]; i_ref > 0; i_ref-- )
{
x264_cabac_encode_decision( cb, 54 + ctx, 1 );
ctx = (ctx>>2)+4;
}
x264_cabac_encode_decision( cb, 54 + ctx, 0 );
}
static NOINLINE void x264_cabac_ref_p( x264_t *h, x264_cabac_t *cb, int idx )
{
x264_cabac_ref_internal( h, cb, 0, idx, 0 );
}
static NOINLINE void x264_cabac_ref_b( x264_t *h, x264_cabac_t *cb, int i_list, int idx )
{
x264_cabac_ref_internal( h, cb, i_list, idx, 1 );
}
static ALWAYS_INLINE int x264_cabac_mvd_cpn( x264_t *h, x264_cabac_t *cb, int i_list, int idx, int l, int mvd, int ctx )
{
int ctxbase = l ? 47 : 40;
if( mvd == 0 )
{
x264_cabac_encode_decision( cb, ctxbase + ctx, 0 );
return 0;
}
int i_abs = abs( mvd );
x264_cabac_encode_decision( cb, ctxbase + ctx, 1 );
#if RDO_SKIP_BS
if( i_abs <= 3 )
{
for( int i = 1; i < i_abs; i++ )
x264_cabac_encode_decision( cb, ctxbase + i + 2, 1 );
x264_cabac_encode_decision( cb, ctxbase + i_abs + 2, 0 );
x264_cabac_encode_bypass( cb, mvd >> 31 );
}
else
{
x264_cabac_encode_decision( cb, ctxbase + 3, 1 );
x264_cabac_encode_decision( cb, ctxbase + 4, 1 );
x264_cabac_encode_decision( cb, ctxbase + 5, 1 );
if( i_abs < 9 )
{
cb->f8_bits_encoded += x264_cabac_size_unary[i_abs - 3][cb->state[ctxbase+6]];
cb->state[ctxbase+6] = x264_cabac_transition_unary[i_abs - 3][cb->state[ctxbase+6]];
}
else
{
cb->f8_bits_encoded += cabac_size_5ones[cb->state[ctxbase+6]];
cb->state[ctxbase+6] = cabac_transition_5ones[cb->state[ctxbase+6]];
x264_cabac_encode_ue_bypass( cb, 3, i_abs - 9 );
}
}
#else
static const uint8_t ctxes[8] = { 3,4,5,6,6,6,6,6 };
if( i_abs < 9 )
{
for( int i = 1; i < i_abs; i++ )
x264_cabac_encode_decision( cb, ctxbase + ctxes[i-1], 1 );
x264_cabac_encode_decision( cb, ctxbase + ctxes[i_abs-1], 0 );
}
else
{
for( int i = 1; i < 9; i++ )
x264_cabac_encode_decision( cb, ctxbase + ctxes[i-1], 1 );
x264_cabac_encode_ue_bypass( cb, 3, i_abs - 9 );
}
x264_cabac_encode_bypass( cb, mvd >> 31 );
#endif
/* Since we don't need to keep track of MVDs larger than 66, just cap the value.
* This lets us store MVDs as 8-bit values instead of 16-bit. */
return X264_MIN( i_abs, 66 );
}
static NOINLINE uint16_t x264_cabac_mvd( x264_t *h, x264_cabac_t *cb, int i_list, int idx, int width )
{
ALIGNED_4( int16_t mvp[2] );
int mdx, mdy;
/* Calculate mvd */
x264_mb_predict_mv( h, i_list, idx, width, mvp );
mdx = h->mb.cache.mv[i_list][x264_scan8[idx]][0] - mvp[0];
mdy = h->mb.cache.mv[i_list][x264_scan8[idx]][1] - mvp[1];
uint16_t amvd = x264_cabac_mvd_sum(h->mb.cache.mvd[i_list][x264_scan8[idx] - 1],
h->mb.cache.mvd[i_list][x264_scan8[idx] - 8]);
/* encode */
mdx = x264_cabac_mvd_cpn( h, cb, i_list, idx, 0, mdx, amvd&0xFF );
mdy = x264_cabac_mvd_cpn( h, cb, i_list, idx, 1, mdy, amvd>>8 );
return pack8to16(mdx,mdy);
}
#define x264_cabac_mvd(h,cb,i_list,idx,width,height)\
do\
{\
uint16_t mvd = x264_cabac_mvd(h,cb,i_list,idx,width);\
x264_macroblock_cache_mvd( h, block_idx_x[idx], block_idx_y[idx], width, height, i_list, mvd );\
} while(0)
static inline void x264_cabac_8x8_mvd( x264_t *h, x264_cabac_t *cb, int i )
{
switch( h->mb.i_sub_partition[i] )
{
case D_L0_8x8:
x264_cabac_mvd( h, cb, 0, 4*i, 2, 2 );
break;
case D_L0_8x4:
x264_cabac_mvd( h, cb, 0, 4*i+0, 2, 1 );
x264_cabac_mvd( h, cb, 0, 4*i+2, 2, 1 );
break;
case D_L0_4x8:
x264_cabac_mvd( h, cb, 0, 4*i+0, 1, 2 );
x264_cabac_mvd( h, cb, 0, 4*i+1, 1, 2 );
break;
case D_L0_4x4:
x264_cabac_mvd( h, cb, 0, 4*i+0, 1, 1 );
x264_cabac_mvd( h, cb, 0, 4*i+1, 1, 1 );
x264_cabac_mvd( h, cb, 0, 4*i+2, 1, 1 );
x264_cabac_mvd( h, cb, 0, 4*i+3, 1, 1 );
break;
default:
assert(0);
}
}
static ALWAYS_INLINE void x264_cabac_mb_header_i( x264_t *h, x264_cabac_t *cb, int i_mb_type, int slice_type, int chroma )
{
if( slice_type == SLICE_TYPE_I )
{
int ctx = 0;
if( (h->mb.i_neighbour & MB_LEFT) && h->mb.i_mb_type_left[0] != I_4x4 )
ctx++;
if( (h->mb.i_neighbour & MB_TOP) && h->mb.i_mb_type_top != I_4x4 )
ctx++;
x264_cabac_mb_type_intra( h, cb, i_mb_type, 3+ctx, 3+3, 3+4, 3+5, 3+6, 3+7 );
}
else if( slice_type == SLICE_TYPE_P )
{
/* prefix */
x264_cabac_encode_decision_noup( cb, 14, 1 );
/* suffix */
x264_cabac_mb_type_intra( h, cb, i_mb_type, 17+0, 17+1, 17+2, 17+2, 17+3, 17+3 );
}
else if( slice_type == SLICE_TYPE_B )
{
/* prefix */
x264_cabac_encode_decision_noup( cb, 27+3, 1 );
x264_cabac_encode_decision_noup( cb, 27+4, 1 );
x264_cabac_encode_decision( cb, 27+5, 1 );
x264_cabac_encode_decision( cb, 27+5, 0 );
x264_cabac_encode_decision( cb, 27+5, 1 );
/* suffix */
x264_cabac_mb_type_intra( h, cb, i_mb_type, 32+0, 32+1, 32+2, 32+2, 32+3, 32+3 );
}
if( i_mb_type == I_PCM )
return;
if( i_mb_type != I_16x16 )
{
if( h->pps->b_transform_8x8_mode )
x264_cabac_transform_size( h, cb );
int di = h->mb.b_transform_8x8 ? 4 : 1;
for( int i = 0; i < 16; i += di )
{
const int i_pred = x264_mb_predict_intra4x4_mode( h, i );
const int i_mode = x264_mb_pred_mode4x4_fix( h->mb.cache.intra4x4_pred_mode[x264_scan8[i]] );
x264_cabac_intra4x4_pred_mode( cb, i_pred, i_mode );
}
}
if( chroma )
x264_cabac_intra_chroma_pred_mode( h, cb );
}
static ALWAYS_INLINE void x264_cabac_mb_header_p( x264_t *h, x264_cabac_t *cb, int i_mb_type, int chroma )
{
if( i_mb_type == P_L0 )
{
x264_cabac_encode_decision_noup( cb, 14, 0 );
if( h->mb.i_partition == D_16x16 )
{
x264_cabac_encode_decision_noup( cb, 15, 0 );
x264_cabac_encode_decision_noup( cb, 16, 0 );
if( h->mb.pic.i_fref[0] > 1 )
x264_cabac_ref_p( h, cb, 0 );
x264_cabac_mvd( h, cb, 0, 0, 4, 4 );
}
else if( h->mb.i_partition == D_16x8 )
{
x264_cabac_encode_decision_noup( cb, 15, 1 );
x264_cabac_encode_decision_noup( cb, 17, 1 );
if( h->mb.pic.i_fref[0] > 1 )
{
x264_cabac_ref_p( h, cb, 0 );
x264_cabac_ref_p( h, cb, 8 );
}
x264_cabac_mvd( h, cb, 0, 0, 4, 2 );
x264_cabac_mvd( h, cb, 0, 8, 4, 2 );
}
else //if( h->mb.i_partition == D_8x16 )
{
x264_cabac_encode_decision_noup( cb, 15, 1 );
x264_cabac_encode_decision_noup( cb, 17, 0 );
if( h->mb.pic.i_fref[0] > 1 )
{
x264_cabac_ref_p( h, cb, 0 );
x264_cabac_ref_p( h, cb, 4 );
}
x264_cabac_mvd( h, cb, 0, 0, 2, 4 );
x264_cabac_mvd( h, cb, 0, 4, 2, 4 );
}
}
else if( i_mb_type == P_8x8 )
{
x264_cabac_encode_decision_noup( cb, 14, 0 );
x264_cabac_encode_decision_noup( cb, 15, 0 );
x264_cabac_encode_decision_noup( cb, 16, 1 );
/* sub mb type */
for( int i = 0; i < 4; i++ )
x264_cabac_subpartition_p( cb, h->mb.i_sub_partition[i] );
/* ref 0 */
if( h->mb.pic.i_fref[0] > 1 )
{
x264_cabac_ref_p( h, cb, 0 );
x264_cabac_ref_p( h, cb, 4 );
x264_cabac_ref_p( h, cb, 8 );
x264_cabac_ref_p( h, cb, 12 );
}
for( int i = 0; i < 4; i++ )
x264_cabac_8x8_mvd( h, cb, i );
}
else /* intra */
x264_cabac_mb_header_i( h, cb, i_mb_type, SLICE_TYPE_P, chroma );
}
static ALWAYS_INLINE void x264_cabac_mb_header_b( x264_t *h, x264_cabac_t *cb, int i_mb_type, int chroma )
{
int ctx = 0;
if( (h->mb.i_neighbour & MB_LEFT) && h->mb.i_mb_type_left[0] != B_SKIP && h->mb.i_mb_type_left[0] != B_DIRECT )
ctx++;
if( (h->mb.i_neighbour & MB_TOP) && h->mb.i_mb_type_top != B_SKIP && h->mb.i_mb_type_top != B_DIRECT )
ctx++;
if( i_mb_type == B_DIRECT )
{
x264_cabac_encode_decision_noup( cb, 27+ctx, 0 );
return;
}
x264_cabac_encode_decision_noup( cb, 27+ctx, 1 );
if( i_mb_type == B_8x8 )
{
x264_cabac_encode_decision_noup( cb, 27+3, 1 );
x264_cabac_encode_decision_noup( cb, 27+4, 1 );
x264_cabac_encode_decision( cb, 27+5, 1 );
x264_cabac_encode_decision( cb, 27+5, 1 );
x264_cabac_encode_decision_noup( cb, 27+5, 1 );
/* sub mb type */
for( int i = 0; i < 4; i++ )
x264_cabac_subpartition_b( cb, h->mb.i_sub_partition[i] );
/* ref */
if( h->mb.pic.i_fref[0] > 1 )
for( int i = 0; i < 4; i++ )
if( x264_mb_partition_listX_table[0][ h->mb.i_sub_partition[i] ] )
x264_cabac_ref_b( h, cb, 0, 4*i );
if( h->mb.pic.i_fref[1] > 1 )
for( int i = 0; i < 4; i++ )
if( x264_mb_partition_listX_table[1][ h->mb.i_sub_partition[i] ] )
x264_cabac_ref_b( h, cb, 1, 4*i );
for( int i = 0; i < 4; i++ )
if( x264_mb_partition_listX_table[0][ h->mb.i_sub_partition[i] ] )
x264_cabac_mvd( h, cb, 0, 4*i, 2, 2 );
for( int i = 0; i < 4; i++ )
if( x264_mb_partition_listX_table[1][ h->mb.i_sub_partition[i] ] )
x264_cabac_mvd( h, cb, 1, 4*i, 2, 2 );
}
else if( i_mb_type >= B_L0_L0 && i_mb_type <= B_BI_BI )
{
/* All B modes */
static const uint8_t i_mb_bits[9*3] =
{
0x31, 0x29, 0x4, /* L0 L0 */
0x35, 0x2d, 0, /* L0 L1 */
0x43, 0x63, 0, /* L0 BI */
0x3d, 0x2f, 0, /* L1 L0 */
0x39, 0x25, 0x6, /* L1 L1 */
0x53, 0x73, 0, /* L1 BI */
0x4b, 0x6b, 0, /* BI L0 */
0x5b, 0x7b, 0, /* BI L1 */
0x47, 0x67, 0x21 /* BI BI */
};
const int idx = (i_mb_type - B_L0_L0) * 3 + (h->mb.i_partition - D_16x8);
int bits = i_mb_bits[idx];
x264_cabac_encode_decision_noup( cb, 27+3, bits&1 );
x264_cabac_encode_decision( cb, 27+5-(bits&1), (bits>>1)&1 ); bits >>= 2;
if( bits != 1 )
{
x264_cabac_encode_decision( cb, 27+5, bits&1 ); bits >>= 1;
x264_cabac_encode_decision( cb, 27+5, bits&1 ); bits >>= 1;
x264_cabac_encode_decision( cb, 27+5, bits&1 ); bits >>= 1;
if( bits != 1 )
x264_cabac_encode_decision_noup( cb, 27+5, bits&1 );
}
const uint8_t (*b_list)[2] = x264_mb_type_list_table[i_mb_type];
if( h->mb.pic.i_fref[0] > 1 )
{
if( b_list[0][0] )
x264_cabac_ref_b( h, cb, 0, 0 );
if( b_list[0][1] && h->mb.i_partition != D_16x16 )
x264_cabac_ref_b( h, cb, 0, 8 >> (h->mb.i_partition == D_8x16) );
}
if( h->mb.pic.i_fref[1] > 1 )
{
if( b_list[1][0] )
x264_cabac_ref_b( h, cb, 1, 0 );
if( b_list[1][1] && h->mb.i_partition != D_16x16 )
x264_cabac_ref_b( h, cb, 1, 8 >> (h->mb.i_partition == D_8x16) );
}
for( int i_list = 0; i_list < 2; i_list++ )
{
if( h->mb.i_partition == D_16x16 )
{
if( b_list[i_list][0] ) x264_cabac_mvd( h, cb, i_list, 0, 4, 4 );
}
else if( h->mb.i_partition == D_16x8 )
{
if( b_list[i_list][0] ) x264_cabac_mvd( h, cb, i_list, 0, 4, 2 );
if( b_list[i_list][1] ) x264_cabac_mvd( h, cb, i_list, 8, 4, 2 );
}
else //if( h->mb.i_partition == D_8x16 )
{
if( b_list[i_list][0] ) x264_cabac_mvd( h, cb, i_list, 0, 2, 4 );
if( b_list[i_list][1] ) x264_cabac_mvd( h, cb, i_list, 4, 2, 4 );
}
}
}
else /* intra */
x264_cabac_mb_header_i( h, cb, i_mb_type, SLICE_TYPE_B, chroma );
}
static int ALWAYS_INLINE x264_cabac_cbf_ctxidxinc( x264_t *h, int i_cat, int i_idx, int b_intra, int b_dc )
{
static const uint16_t base_ctx[14] = {85,89,93,97,101,1012,460,464,468,1016,472,476,480,1020};
if( b_dc )
{
i_idx -= LUMA_DC;
if( i_cat == DCT_CHROMA_DC )
{
int i_nza = h->mb.cache.i_cbp_left != -1 ? (h->mb.cache.i_cbp_left >> (8 + i_idx)) & 1 : b_intra;
int i_nzb = h->mb.cache.i_cbp_top != -1 ? (h->mb.cache.i_cbp_top >> (8 + i_idx)) & 1 : b_intra;
return base_ctx[i_cat] + 2*i_nzb + i_nza;
}
else
{
int i_nza = (h->mb.cache.i_cbp_left >> (8 + i_idx)) & 1;
int i_nzb = (h->mb.cache.i_cbp_top >> (8 + i_idx)) & 1;
return base_ctx[i_cat] + 2*i_nzb + i_nza;
}
}
else
{
int i_nza = h->mb.cache.non_zero_count[x264_scan8[i_idx] - 1];
int i_nzb = h->mb.cache.non_zero_count[x264_scan8[i_idx] - 8];
if( x264_constant_p(b_intra) && !b_intra )
return base_ctx[i_cat] + ((2*i_nzb + i_nza)&0x7f);
else
{
i_nza &= 0x7f + (b_intra << 7);
i_nzb &= 0x7f + (b_intra << 7);
return base_ctx[i_cat] + 2*!!i_nzb + !!i_nza;
}
}
}
#if !RDO_SKIP_BS
extern const uint8_t x264_significant_coeff_flag_offset_8x8[2][64];
extern const uint8_t x264_last_coeff_flag_offset_8x8[63];
extern const uint8_t x264_coeff_flag_offset_chroma_422_dc[7];
extern const uint16_t x264_significant_coeff_flag_offset[2][16];
extern const uint16_t x264_last_coeff_flag_offset[2][16];
extern const uint16_t x264_coeff_abs_level_m1_offset[16];
extern const uint8_t x264_count_cat_m1[14];
#else
/* Padded to [64] for easier addressing */
const uint8_t x264_significant_coeff_flag_offset_8x8[2][64] =
{{
0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5,
4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9,10, 9, 8, 7,
7, 6,11,12,13,11, 6, 7, 8, 9,14,10, 9, 8, 6,11,
12,13,11, 6, 9,14,10, 9,11,12,13,11,14,10,12
},{
0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5,
6, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11,
9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,13,13, 9,
9,10,10, 8,13,13, 9, 9,10,10,14,14,14,14,14
}};
const uint8_t x264_last_coeff_flag_offset_8x8[63] =
{
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8
};
const uint8_t x264_coeff_flag_offset_chroma_422_dc[7] = { 0, 0, 1, 1, 2, 2, 2 }; /* MIN( i/2, 2 ) */
const uint16_t x264_significant_coeff_flag_offset[2][16] =
{
{ 105+0, 105+15, 105+29, 105+44, 105+47, 402, 484+0, 484+15, 484+29, 660, 528+0, 528+15, 528+29, 718, 0, 0 },
{ 277+0, 277+15, 277+29, 277+44, 277+47, 436, 776+0, 776+15, 776+29, 675, 820+0, 820+15, 820+29, 733, 0, 0 }
};
const uint16_t x264_last_coeff_flag_offset[2][16] =
{
{ 166+0, 166+15, 166+29, 166+44, 166+47, 417, 572+0, 572+15, 572+29, 690, 616+0, 616+15, 616+29, 748, 0, 0 },
{ 338+0, 338+15, 338+29, 338+44, 338+47, 451, 864+0, 864+15, 864+29, 699, 908+0, 908+15, 908+29, 757, 0, 0 }
};
const uint16_t x264_coeff_abs_level_m1_offset[16] =
{
227+0, 227+10, 227+20, 227+30, 227+39, 426, 952+0, 952+10, 952+20, 708, 982+0, 982+10, 982+20, 766
};
const uint8_t x264_count_cat_m1[14] = {15, 14, 15, 3, 14, 63, 15, 14, 15, 63, 15, 14, 15, 63};
#endif
// node ctx: 0..3: abslevel1 (with abslevelgt1 == 0).
// 4..7: abslevelgt1 + 3 (and abslevel1 doesn't matter).
/* map node ctx => cabac ctx for level=1 */
static const uint8_t coeff_abs_level1_ctx[8] = { 1, 2, 3, 4, 0, 0, 0, 0 };
/* map node ctx => cabac ctx for level>1 */
static const uint8_t coeff_abs_levelgt1_ctx[8] = { 5, 5, 5, 5, 6, 7, 8, 9 };
/* 4:2:2 chroma dc uses a slightly different state machine for some reason, also note that
* 4:2:0 chroma dc doesn't use the last state so it has identical output with both arrays. */
static const uint8_t coeff_abs_levelgt1_ctx_chroma_dc[8] = { 5, 5, 5, 5, 6, 7, 8, 8 };
static const uint8_t coeff_abs_level_transition[2][8] = {
/* update node ctx after coding a level=1 */
{ 1, 2, 3, 3, 4, 5, 6, 7 },
/* update node ctx after coding a level>1 */
{ 4, 4, 4, 4, 5, 6, 7, 7 }
};
#if !RDO_SKIP_BS
static ALWAYS_INLINE void x264_cabac_block_residual_internal( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l, int chroma422dc )
{
int ctx_sig = x264_significant_coeff_flag_offset[MB_INTERLACED][ctx_block_cat];
int ctx_last = x264_last_coeff_flag_offset[MB_INTERLACED][ctx_block_cat];
int ctx_level = x264_coeff_abs_level_m1_offset[ctx_block_cat];
int coeff_idx = -1, node_ctx = 0;
int last = h->quantf.coeff_last[ctx_block_cat]( l );
const uint8_t *levelgt1_ctx = chroma422dc ? coeff_abs_levelgt1_ctx_chroma_dc : coeff_abs_levelgt1_ctx;
dctcoef coeffs[64];
#define WRITE_SIGMAP( sig_off, last_off )\
{\
int i = 0;\
while( 1 )\
{\
if( l[i] )\
{\
coeffs[++coeff_idx] = l[i];\
x264_cabac_encode_decision( cb, ctx_sig + sig_off, 1 );\
if( i == last )\
{\
x264_cabac_encode_decision( cb, ctx_last + last_off, 1 );\
break;\
}\
else\
x264_cabac_encode_decision( cb, ctx_last + last_off, 0 );\
}\
else\
x264_cabac_encode_decision( cb, ctx_sig + sig_off, 0 );\
if( ++i == count_m1 )\
{\
coeffs[++coeff_idx] = l[i];\
break;\
}\
}\
}
if( chroma422dc )
{
int count_m1 = 7;
WRITE_SIGMAP( x264_coeff_flag_offset_chroma_422_dc[i], x264_coeff_flag_offset_chroma_422_dc[i] )
}
else
{
int count_m1 = x264_count_cat_m1[ctx_block_cat];
if( count_m1 == 63 )
{
const uint8_t *sig_offset = x264_significant_coeff_flag_offset_8x8[MB_INTERLACED];
WRITE_SIGMAP( sig_offset[i], x264_last_coeff_flag_offset_8x8[i] )
}
else
WRITE_SIGMAP( i, i )
}
do
{
/* write coeff_abs - 1 */
int coeff = coeffs[coeff_idx];
int abs_coeff = abs(coeff);
int coeff_sign = coeff >> 31;
int ctx = coeff_abs_level1_ctx[node_ctx] + ctx_level;
if( abs_coeff > 1 )
{
x264_cabac_encode_decision( cb, ctx, 1 );
ctx = levelgt1_ctx[node_ctx] + ctx_level;
for( int i = X264_MIN( abs_coeff, 15 ) - 2; i > 0; i-- )
x264_cabac_encode_decision( cb, ctx, 1 );
if( abs_coeff < 15 )
x264_cabac_encode_decision( cb, ctx, 0 );
else
x264_cabac_encode_ue_bypass( cb, 0, abs_coeff - 15 );
node_ctx = coeff_abs_level_transition[1][node_ctx];
}
else
{
x264_cabac_encode_decision( cb, ctx, 0 );
node_ctx = coeff_abs_level_transition[0][node_ctx];
}
x264_cabac_encode_bypass( cb, coeff_sign );
} while( --coeff_idx >= 0 );
}
void x264_cabac_block_residual_c( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
x264_cabac_block_residual_internal( h, cb, ctx_block_cat, l, 0 );
}
static void ALWAYS_INLINE x264_cabac_block_residual( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
#if ARCH_X86_64 && HAVE_MMX
h->bsf.cabac_block_residual_internal( l, MB_INTERLACED, ctx_block_cat, cb );
#else
x264_cabac_block_residual_c( h, cb, ctx_block_cat, l );
#endif
}
static void x264_cabac_block_residual_422_dc( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
/* Template a version specifically for chroma 4:2:2 DC in order to avoid
* slowing down everything else due to the added complexity. */
x264_cabac_block_residual_internal( h, cb, DCT_CHROMA_DC, l, 1 );
}
#define x264_cabac_block_residual_8x8( h, cb, cat, l ) x264_cabac_block_residual( h, cb, cat, l )
#else
/* Faster RDO by merging sigmap and level coding. Note that for 8x8dct and chroma 4:2:2 dc this is
* slightly incorrect because the sigmap is not reversible (contexts are repeated). However, there
* is nearly no quality penalty for this (~0.001db) and the speed boost (~30%) is worth it. */
static void ALWAYS_INLINE x264_cabac_block_residual_internal( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l, int b_8x8, int chroma422dc )
{
const uint8_t *sig_offset = x264_significant_coeff_flag_offset_8x8[MB_INTERLACED];
int ctx_sig = x264_significant_coeff_flag_offset[MB_INTERLACED][ctx_block_cat];
int ctx_last = x264_last_coeff_flag_offset[MB_INTERLACED][ctx_block_cat];
int ctx_level = x264_coeff_abs_level_m1_offset[ctx_block_cat];
int last = h->quantf.coeff_last[ctx_block_cat]( l );
int coeff_abs = abs(l[last]);
int ctx = coeff_abs_level1_ctx[0] + ctx_level;
int node_ctx;
const uint8_t *levelgt1_ctx = chroma422dc ? coeff_abs_levelgt1_ctx_chroma_dc : coeff_abs_levelgt1_ctx;
if( last != (b_8x8 ? 63 : chroma422dc ? 7 : x264_count_cat_m1[ctx_block_cat]) )
{
x264_cabac_encode_decision( cb, ctx_sig + (b_8x8 ? sig_offset[last] :
chroma422dc ? x264_coeff_flag_offset_chroma_422_dc[last] : last), 1 );
x264_cabac_encode_decision( cb, ctx_last + (b_8x8 ? x264_last_coeff_flag_offset_8x8[last] :
chroma422dc ? x264_coeff_flag_offset_chroma_422_dc[last] : last), 1 );
}
if( coeff_abs > 1 )
{
x264_cabac_encode_decision( cb, ctx, 1 );
ctx = levelgt1_ctx[0] + ctx_level;
if( coeff_abs < 15 )
{
cb->f8_bits_encoded += x264_cabac_size_unary[coeff_abs-1][cb->state[ctx]];
cb->state[ctx] = x264_cabac_transition_unary[coeff_abs-1][cb->state[ctx]];
}
else
{
cb->f8_bits_encoded += x264_cabac_size_unary[14][cb->state[ctx]];
cb->state[ctx] = x264_cabac_transition_unary[14][cb->state[ctx]];
x264_cabac_encode_ue_bypass( cb, 0, coeff_abs - 15 );
}
node_ctx = coeff_abs_level_transition[1][0];
}
else
{
x264_cabac_encode_decision( cb, ctx, 0 );
node_ctx = coeff_abs_level_transition[0][0];
x264_cabac_encode_bypass( cb, 0 ); // sign
}
for( int i = last-1 ; i >= 0; i-- )
{
if( l[i] )
{
coeff_abs = abs(l[i]);
x264_cabac_encode_decision( cb, ctx_sig + (b_8x8 ? sig_offset[i] :
chroma422dc ? x264_coeff_flag_offset_chroma_422_dc[i] : i), 1 );
x264_cabac_encode_decision( cb, ctx_last + (b_8x8 ? x264_last_coeff_flag_offset_8x8[i] :
chroma422dc ? x264_coeff_flag_offset_chroma_422_dc[i] : i), 0 );
ctx = coeff_abs_level1_ctx[node_ctx] + ctx_level;
if( coeff_abs > 1 )
{
x264_cabac_encode_decision( cb, ctx, 1 );
ctx = levelgt1_ctx[node_ctx] + ctx_level;
if( coeff_abs < 15 )
{
cb->f8_bits_encoded += x264_cabac_size_unary[coeff_abs-1][cb->state[ctx]];
cb->state[ctx] = x264_cabac_transition_unary[coeff_abs-1][cb->state[ctx]];
}
else
{
cb->f8_bits_encoded += x264_cabac_size_unary[14][cb->state[ctx]];
cb->state[ctx] = x264_cabac_transition_unary[14][cb->state[ctx]];
x264_cabac_encode_ue_bypass( cb, 0, coeff_abs - 15 );
}
node_ctx = coeff_abs_level_transition[1][node_ctx];
}
else
{
x264_cabac_encode_decision( cb, ctx, 0 );
node_ctx = coeff_abs_level_transition[0][node_ctx];
x264_cabac_encode_bypass( cb, 0 );
}
}
else
x264_cabac_encode_decision( cb, ctx_sig + (b_8x8 ? sig_offset[i] :
chroma422dc ? x264_coeff_flag_offset_chroma_422_dc[i] : i), 0 );
}
}
void x264_cabac_block_residual_8x8_rd_c( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
x264_cabac_block_residual_internal( h, cb, ctx_block_cat, l, 1, 0 );
}
void x264_cabac_block_residual_rd_c( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
x264_cabac_block_residual_internal( h, cb, ctx_block_cat, l, 0, 0 );
}
static ALWAYS_INLINE void x264_cabac_block_residual_8x8( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
#if ARCH_X86_64 && HAVE_MMX
h->bsf.cabac_block_residual_8x8_rd_internal( l, MB_INTERLACED, ctx_block_cat, cb );
#else
x264_cabac_block_residual_8x8_rd_c( h, cb, ctx_block_cat, l );
#endif
}
static ALWAYS_INLINE void x264_cabac_block_residual( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
#if ARCH_X86_64 && HAVE_MMX
h->bsf.cabac_block_residual_rd_internal( l, MB_INTERLACED, ctx_block_cat, cb );
#else
x264_cabac_block_residual_rd_c( h, cb, ctx_block_cat, l );
#endif
}
static void x264_cabac_block_residual_422_dc( x264_t *h, x264_cabac_t *cb, int ctx_block_cat, dctcoef *l )
{
x264_cabac_block_residual_internal( h, cb, DCT_CHROMA_DC, l, 0, 1 );
}
#endif
#define x264_cabac_block_residual_cbf_internal( h, cb, ctx_block_cat, i_idx, l, b_intra, b_dc, name )\
do\
{\
int ctxidxinc = x264_cabac_cbf_ctxidxinc( h, ctx_block_cat, i_idx, b_intra, b_dc );\
if( h->mb.cache.non_zero_count[x264_scan8[i_idx]] )\
{\
x264_cabac_encode_decision( cb, ctxidxinc, 1 );\
x264_cabac_block_residual##name( h, cb, ctx_block_cat, l );\
}\
else\
x264_cabac_encode_decision( cb, ctxidxinc, 0 );\
} while(0)
#define x264_cabac_block_residual_dc_cbf( h, cb, ctx_block_cat, i_idx, l, b_intra )\
x264_cabac_block_residual_cbf_internal( h, cb, ctx_block_cat, i_idx, l, b_intra, 1, )
#define x264_cabac_block_residual_cbf( h, cb, ctx_block_cat, i_idx, l, b_intra )\
x264_cabac_block_residual_cbf_internal( h, cb, ctx_block_cat, i_idx, l, b_intra, 0, )
#define x264_cabac_block_residual_8x8_cbf( h, cb, ctx_block_cat, i_idx, l, b_intra )\
x264_cabac_block_residual_cbf_internal( h, cb, ctx_block_cat, i_idx, l, b_intra, 0, _8x8 )
#define x264_cabac_block_residual_422_dc_cbf( h, cb, ch, b_intra )\
x264_cabac_block_residual_cbf_internal( h, cb, DCT_CHROMA_DC, CHROMA_DC+(ch), h->dct.chroma_dc[ch], b_intra, 1, _422_dc )
static ALWAYS_INLINE void x264_macroblock_write_cabac_internal( x264_t *h, x264_cabac_t *cb, int plane_count, int chroma )
{
const int i_mb_type = h->mb.i_type;
#if !RDO_SKIP_BS
const int i_mb_pos_start = x264_cabac_pos( cb );
int i_mb_pos_tex;
if( SLICE_MBAFF &&
(!(h->mb.i_mb_y & 1) || IS_SKIP(h->mb.type[h->mb.i_mb_xy - h->mb.i_mb_stride])) )
{
x264_cabac_field_decoding_flag( h, cb );
}
#endif
if( h->sh.i_type == SLICE_TYPE_P )
x264_cabac_mb_header_p( h, cb, i_mb_type, chroma );
else if( h->sh.i_type == SLICE_TYPE_B )
x264_cabac_mb_header_b( h, cb, i_mb_type, chroma );
else //if( h->sh.i_type == SLICE_TYPE_I )
x264_cabac_mb_header_i( h, cb, i_mb_type, SLICE_TYPE_I, chroma );
#if !RDO_SKIP_BS
i_mb_pos_tex = x264_cabac_pos( cb );
h->stat.frame.i_mv_bits += i_mb_pos_tex - i_mb_pos_start;
if( i_mb_type == I_PCM )
{
bs_t s;
bs_init( &s, cb->p, cb->p_end - cb->p );
for( int p = 0; p < plane_count; p++ )
for( int i = 0; i < 256; i++ )
bs_write( &s, BIT_DEPTH, h->mb.pic.p_fenc[p][i] );
if( chroma )
for( int ch = 1; ch < 3; ch++ )
for( int i = 0; i < 16>>CHROMA_V_SHIFT; i++ )
for( int j = 0; j < 8; j++ )
bs_write( &s, BIT_DEPTH, h->mb.pic.p_fenc[ch][i*FENC_STRIDE+j] );
bs_flush( &s );
cb->p = s.p;
x264_cabac_encode_init_core( cb );
h->stat.frame.i_tex_bits += x264_cabac_pos( cb ) - i_mb_pos_tex;
return;
}
#endif
if( i_mb_type != I_16x16 )
{
x264_cabac_cbp_luma( h, cb );
if( chroma )
x264_cabac_cbp_chroma( h, cb );
}
if( x264_mb_transform_8x8_allowed( h ) && h->mb.i_cbp_luma )
{
x264_cabac_transform_size( h, cb );
}
if( h->mb.i_cbp_luma || (chroma && h->mb.i_cbp_chroma) || i_mb_type == I_16x16 )
{
const int b_intra = IS_INTRA( i_mb_type );
x264_cabac_qp_delta( h, cb );
/* write residual */
if( i_mb_type == I_16x16 )
{
/* DC Luma */
for( int p = 0; p < plane_count; p++ )
{
x264_cabac_block_residual_dc_cbf( h, cb, ctx_cat_plane[DCT_LUMA_DC][p], LUMA_DC+p, h->dct.luma16x16_dc[p], 1 );
/* AC Luma */
if( h->mb.i_cbp_luma )
for( int i = p*16; i < p*16+16; i++ )
x264_cabac_block_residual_cbf( h, cb, ctx_cat_plane[DCT_LUMA_AC][p], i, h->dct.luma4x4[i]+1, 1 );
}
}
else if( h->mb.b_transform_8x8 )
{
if( plane_count == 3 )
{
ALIGNED_4( uint8_t nnzbak[3][8] );
/* Stupid nnz munging in the case that neighbors don't have
* 8x8 transform enabled. */
#define BACKUP( dst, src, res )\
dst = src;\
src = res;
#define RESTORE( dst, src, res )\
src = dst;
#define MUNGE_8x8_NNZ( MUNGE )\
if( (h->mb.i_neighbour & MB_LEFT) && !h->mb.mb_transform_size[h->mb.i_mb_left_xy[0]] )\
{\
MUNGE( nnzbak[0][0], h->mb.cache.non_zero_count[x264_scan8[16*0+ 0] - 1], 0x80 )\
MUNGE( nnzbak[0][1], h->mb.cache.non_zero_count[x264_scan8[16*0+ 2] - 1], 0x80 )\
MUNGE( nnzbak[1][0], h->mb.cache.non_zero_count[x264_scan8[16*1+ 0] - 1], 0x80 )\
MUNGE( nnzbak[1][1], h->mb.cache.non_zero_count[x264_scan8[16*1+ 2] - 1], 0x80 )\
MUNGE( nnzbak[2][0], h->mb.cache.non_zero_count[x264_scan8[16*2+ 0] - 1], 0x80 )\
MUNGE( nnzbak[2][1], h->mb.cache.non_zero_count[x264_scan8[16*2+ 2] - 1], 0x80 )\
}\
if( (h->mb.i_neighbour & MB_LEFT) && !h->mb.mb_transform_size[h->mb.i_mb_left_xy[1]] )\
{\
MUNGE( nnzbak[0][2], h->mb.cache.non_zero_count[x264_scan8[16*0+ 8] - 1], 0x80 )\
MUNGE( nnzbak[0][3], h->mb.cache.non_zero_count[x264_scan8[16*0+10] - 1], 0x80 )\
MUNGE( nnzbak[1][2], h->mb.cache.non_zero_count[x264_scan8[16*1+ 8] - 1], 0x80 )\
MUNGE( nnzbak[1][3], h->mb.cache.non_zero_count[x264_scan8[16*1+10] - 1], 0x80 )\
MUNGE( nnzbak[2][2], h->mb.cache.non_zero_count[x264_scan8[16*2+ 8] - 1], 0x80 )\
MUNGE( nnzbak[2][3], h->mb.cache.non_zero_count[x264_scan8[16*2+10] - 1], 0x80 )\
}\
if( (h->mb.i_neighbour & MB_TOP) && !h->mb.mb_transform_size[h->mb.i_mb_top_xy] )\
{\
MUNGE( M32( &nnzbak[0][4] ), M32( &h->mb.cache.non_zero_count[x264_scan8[16*0] - 8] ), 0x80808080U )\
MUNGE( M32( &nnzbak[1][4] ), M32( &h->mb.cache.non_zero_count[x264_scan8[16*1] - 8] ), 0x80808080U )\
MUNGE( M32( &nnzbak[2][4] ), M32( &h->mb.cache.non_zero_count[x264_scan8[16*2] - 8] ), 0x80808080U )\
}
MUNGE_8x8_NNZ( BACKUP )
for( int p = 0; p < 3; p++ )
FOREACH_BIT( i, 0, h->mb.i_cbp_luma )
x264_cabac_block_residual_8x8_cbf( h, cb, ctx_cat_plane[DCT_LUMA_8x8][p], i*4+p*16, h->dct.luma8x8[i+p*4], b_intra );
MUNGE_8x8_NNZ( RESTORE )
}
else
{
FOREACH_BIT( i, 0, h->mb.i_cbp_luma )
x264_cabac_block_residual_8x8( h, cb, DCT_LUMA_8x8, h->dct.luma8x8[i] );
}
}
else
{
for( int p = 0; p < plane_count; p++ )
FOREACH_BIT( i8x8, 0, h->mb.i_cbp_luma )
for( int i = 0; i < 4; i++ )
x264_cabac_block_residual_cbf( h, cb, ctx_cat_plane[DCT_LUMA_4x4][p], i+i8x8*4+p*16, h->dct.luma4x4[i+i8x8*4+p*16], b_intra );
}
if( chroma && h->mb.i_cbp_chroma ) /* Chroma DC residual present */
{
if( CHROMA_FORMAT == CHROMA_422 )
{
x264_cabac_block_residual_422_dc_cbf( h, cb, 0, b_intra );
x264_cabac_block_residual_422_dc_cbf( h, cb, 1, b_intra );
}
else
{
x264_cabac_block_residual_dc_cbf( h, cb, DCT_CHROMA_DC, CHROMA_DC+0, h->dct.chroma_dc[0], b_intra );
x264_cabac_block_residual_dc_cbf( h, cb, DCT_CHROMA_DC, CHROMA_DC+1, h->dct.chroma_dc[1], b_intra );
}
if( h->mb.i_cbp_chroma == 2 ) /* Chroma AC residual present */
{
int step = 8 << CHROMA_V_SHIFT;
for( int i = 16; i < 3*16; i += step )
for( int j = i; j < i+4; j++ )
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, j, h->dct.luma4x4[j]+1, b_intra );
}
}
}
#if !RDO_SKIP_BS
h->stat.frame.i_tex_bits += x264_cabac_pos( cb ) - i_mb_pos_tex;
#endif
}
void x264_macroblock_write_cabac( x264_t *h, x264_cabac_t *cb )
{
if( CHROMA444 )
x264_macroblock_write_cabac_internal( h, cb, 3, 0 );
else
x264_macroblock_write_cabac_internal( h, cb, 1, 1 );
}
#if RDO_SKIP_BS
/*****************************************************************************
* RD only; doesn't generate a valid bitstream
* doesn't write cbp or chroma dc (I don't know how much this matters)
* doesn't write ref (never varies between calls, so no point in doing so)
* only writes subpartition for p8x8, needed for sub-8x8 mode decision RDO
* works on all partition sizes except 16x16
*****************************************************************************/
static void x264_partition_size_cabac( x264_t *h, x264_cabac_t *cb, int i8, int i_pixel )
{
const int i_mb_type = h->mb.i_type;
int b_8x16 = h->mb.i_partition == D_8x16;
int plane_count = CHROMA444 ? 3 : 1;
if( i_mb_type == P_8x8 )
{
x264_cabac_8x8_mvd( h, cb, i8 );
x264_cabac_subpartition_p( cb, h->mb.i_sub_partition[i8] );
}
else if( i_mb_type == P_L0 )
x264_cabac_mvd( h, cb, 0, 4*i8, 4>>b_8x16, 2<<b_8x16 );
else if( i_mb_type > B_DIRECT && i_mb_type < B_8x8 )
{
if( x264_mb_type_list_table[ i_mb_type ][0][!!i8] ) x264_cabac_mvd( h, cb, 0, 4*i8, 4>>b_8x16, 2<<b_8x16 );
if( x264_mb_type_list_table[ i_mb_type ][1][!!i8] ) x264_cabac_mvd( h, cb, 1, 4*i8, 4>>b_8x16, 2<<b_8x16 );
}
else //if( i_mb_type == B_8x8 )
{
if( x264_mb_partition_listX_table[0][ h->mb.i_sub_partition[i8] ] )
x264_cabac_mvd( h, cb, 0, 4*i8, 2, 2 );
if( x264_mb_partition_listX_table[1][ h->mb.i_sub_partition[i8] ] )
x264_cabac_mvd( h, cb, 1, 4*i8, 2, 2 );
}
for( int j = (i_pixel < PIXEL_8x8); j >= 0; j-- )
{
if( h->mb.i_cbp_luma & (1 << i8) )
{
if( h->mb.b_transform_8x8 )
{
if( CHROMA444 )
for( int p = 0; p < 3; p++ )
x264_cabac_block_residual_8x8_cbf( h, cb, ctx_cat_plane[DCT_LUMA_8x8][p], i8*4+p*16, h->dct.luma8x8[i8+p*4], 0 );
else
x264_cabac_block_residual_8x8( h, cb, DCT_LUMA_8x8, h->dct.luma8x8[i8] );
}
else
for( int p = 0; p < plane_count; p++ )
for( int i4 = 0; i4 < 4; i4++ )
x264_cabac_block_residual_cbf( h, cb, ctx_cat_plane[DCT_LUMA_4x4][p], i4+i8*4+p*16, h->dct.luma4x4[i4+i8*4+p*16], 0 );
}
if( h->mb.i_cbp_chroma )
{
if( CHROMA_FORMAT == CHROMA_422 )
{
int offset = (5*i8) & 0x09;
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, 16+offset, h->dct.luma4x4[16+offset]+1, 0 );
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, 18+offset, h->dct.luma4x4[18+offset]+1, 0 );
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, 32+offset, h->dct.luma4x4[32+offset]+1, 0 );
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, 34+offset, h->dct.luma4x4[34+offset]+1, 0 );
}
else
{
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, 16+i8, h->dct.luma4x4[16+i8]+1, 0 );
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, 32+i8, h->dct.luma4x4[32+i8]+1, 0 );
}
}
i8 += x264_pixel_size[i_pixel].h >> 3;
}
}
static void x264_subpartition_size_cabac( x264_t *h, x264_cabac_t *cb, int i4, int i_pixel )
{
int b_8x4 = i_pixel == PIXEL_8x4;
int plane_count = CHROMA444 ? 3 : 1;
if( i_pixel == PIXEL_4x4 )
x264_cabac_mvd( h, cb, 0, i4, 1, 1 );
else
x264_cabac_mvd( h, cb, 0, i4, 1+b_8x4, 2-b_8x4 );
for( int p = 0; p < plane_count; p++ )
{
x264_cabac_block_residual_cbf( h, cb, ctx_cat_plane[DCT_LUMA_4x4][p], p*16+i4, h->dct.luma4x4[p*16+i4], 0 );
if( i_pixel != PIXEL_4x4 )
x264_cabac_block_residual_cbf( h, cb, ctx_cat_plane[DCT_LUMA_4x4][p], p*16+i4+2-b_8x4, h->dct.luma4x4[p*16+i4+2-b_8x4], 0 );
}
}
static void x264_partition_i8x8_size_cabac( x264_t *h, x264_cabac_t *cb, int i8, int i_mode )
{
const int i_pred = x264_mb_predict_intra4x4_mode( h, 4*i8 );
i_mode = x264_mb_pred_mode4x4_fix( i_mode );
x264_cabac_intra4x4_pred_mode( cb, i_pred, i_mode );
x264_cabac_cbp_luma( h, cb );
if( h->mb.i_cbp_luma & (1 << i8) )
{
if( CHROMA444 )
for( int p = 0; p < 3; p++ )
x264_cabac_block_residual_8x8_cbf( h, cb, ctx_cat_plane[DCT_LUMA_8x8][p], i8*4+p*16, h->dct.luma8x8[i8+p*4], 1 );
else
x264_cabac_block_residual_8x8( h, cb, DCT_LUMA_8x8, h->dct.luma8x8[i8] );
}
}
static void x264_partition_i4x4_size_cabac( x264_t *h, x264_cabac_t *cb, int i4, int i_mode )
{
const int i_pred = x264_mb_predict_intra4x4_mode( h, i4 );
int plane_count = CHROMA444 ? 3 : 1;
i_mode = x264_mb_pred_mode4x4_fix( i_mode );
x264_cabac_intra4x4_pred_mode( cb, i_pred, i_mode );
for( int p = 0; p < plane_count; p++ )
x264_cabac_block_residual_cbf( h, cb, ctx_cat_plane[DCT_LUMA_4x4][p], i4+p*16, h->dct.luma4x4[i4+p*16], 1 );
}
static void x264_chroma_size_cabac( x264_t *h, x264_cabac_t *cb )
{
x264_cabac_intra_chroma_pred_mode( h, cb );
x264_cabac_cbp_chroma( h, cb );
if( h->mb.i_cbp_chroma )
{
if( CHROMA_FORMAT == CHROMA_422 )
{
x264_cabac_block_residual_422_dc_cbf( h, cb, 0, 1 );
x264_cabac_block_residual_422_dc_cbf( h, cb, 1, 1 );
}
else
{
x264_cabac_block_residual_dc_cbf( h, cb, DCT_CHROMA_DC, CHROMA_DC+0, h->dct.chroma_dc[0], 1 );
x264_cabac_block_residual_dc_cbf( h, cb, DCT_CHROMA_DC, CHROMA_DC+1, h->dct.chroma_dc[1], 1 );
}
if( h->mb.i_cbp_chroma == 2 )
{
int step = 8 << CHROMA_V_SHIFT;
for( int i = 16; i < 3*16; i += step )
for( int j = i; j < i+4; j++ )
x264_cabac_block_residual_cbf( h, cb, DCT_CHROMA_AC, j, h->dct.luma4x4[j]+1, 1 );
}
}
}
#endif
| gpl-2.0 |
Happy-Ferret/Kernel-Experiments | arch/powerpc/oprofile/common.c | 521 | 6253 | /*
* PPC 64 oprofile support:
* Copyright (C) 2004 Anton Blanchard <anton@au.ibm.com>, IBM
* PPC 32 oprofile support: (based on PPC 64 support)
* Copyright (C) Freescale Semiconductor, Inc 2004
* Author: Andy Fleming
*
* Based on alpha version.
*
* 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/oprofile.h>
#include <linux/init.h>
#include <linux/smp.h>
#include <linux/errno.h>
#include <asm/ptrace.h>
#include <asm/pmc.h>
#include <asm/cputable.h>
#include <asm/oprofile_impl.h>
#include <asm/firmware.h>
static struct op_powerpc_model *model;
static struct op_counter_config ctr[OP_MAX_COUNTER];
static struct op_system_config sys;
static int op_per_cpu_rc;
static void op_handle_interrupt(struct pt_regs *regs)
{
model->handle_interrupt(regs, ctr);
}
static void op_powerpc_cpu_setup(void *dummy)
{
int ret;
ret = model->cpu_setup(ctr);
if (ret != 0)
op_per_cpu_rc = ret;
}
static int op_powerpc_setup(void)
{
int err;
op_per_cpu_rc = 0;
/* Grab the hardware */
err = reserve_pmc_hardware(op_handle_interrupt);
if (err)
return err;
/* Pre-compute the values to stuff in the hardware registers. */
op_per_cpu_rc = model->reg_setup(ctr, &sys, model->num_counters);
if (op_per_cpu_rc)
goto out;
/* Configure the registers on all cpus. If an error occurs on one
* of the cpus, op_per_cpu_rc will be set to the error */
on_each_cpu(op_powerpc_cpu_setup, NULL, 1);
out: if (op_per_cpu_rc) {
/* error on setup release the performance counter hardware */
release_pmc_hardware();
}
return op_per_cpu_rc;
}
static void op_powerpc_shutdown(void)
{
release_pmc_hardware();
}
static void op_powerpc_cpu_start(void *dummy)
{
/* If any of the cpus have return an error, set the
* global flag to the error so it can be returned
* to the generic OProfile caller.
*/
int ret;
ret = model->start(ctr);
if (ret != 0)
op_per_cpu_rc = ret;
}
static int op_powerpc_start(void)
{
op_per_cpu_rc = 0;
if (model->global_start)
return model->global_start(ctr);
if (model->start) {
on_each_cpu(op_powerpc_cpu_start, NULL, 1);
return op_per_cpu_rc;
}
return -EIO; /* No start function is defined for this
power architecture */
}
static inline void op_powerpc_cpu_stop(void *dummy)
{
model->stop();
}
static void op_powerpc_stop(void)
{
if (model->stop)
on_each_cpu(op_powerpc_cpu_stop, NULL, 1);
if (model->global_stop)
model->global_stop();
}
static int op_powerpc_create_files(struct dentry *root)
{
int i;
#ifdef CONFIG_PPC64
/*
* There is one mmcr0, mmcr1 and mmcra for setting the events for
* all of the counters.
*/
oprofilefs_create_ulong(root, "mmcr0", &sys.mmcr0);
oprofilefs_create_ulong(root, "mmcr1", &sys.mmcr1);
oprofilefs_create_ulong(root, "mmcra", &sys.mmcra);
#ifdef CONFIG_OPROFILE_CELL
/* create a file the user tool can check to see what level of profiling
* support exits with this kernel. Initialize bit mask to indicate
* what support the kernel has:
* bit 0 - Supports SPU event profiling in addition to PPU
* event and cycles; and SPU cycle profiling
* bits 1-31 - Currently unused.
*
* If the file does not exist, then the kernel only supports SPU
* cycle profiling, PPU event and cycle profiling.
*/
oprofilefs_create_ulong(root, "cell_support", &sys.cell_support);
sys.cell_support = 0x1; /* Note, the user OProfile tool must check
* that this bit is set before attempting to
* user SPU event profiling. Older kernels
* will not have this file, hence the user
* tool is not allowed to do SPU event
* profiling on older kernels. Older kernels
* will accept SPU events but collected data
* is garbage.
*/
#endif
#endif
for (i = 0; i < model->num_counters; ++i) {
struct dentry *dir;
char buf[4];
snprintf(buf, sizeof buf, "%d", i);
dir = oprofilefs_mkdir(root, buf);
oprofilefs_create_ulong(dir, "enabled", &ctr[i].enabled);
oprofilefs_create_ulong(dir, "event", &ctr[i].event);
oprofilefs_create_ulong(dir, "count", &ctr[i].count);
/*
* Classic PowerPC doesn't support per-counter
* control like this, but the options are
* expected, so they remain. For Freescale
* Book-E style performance monitors, we do
* support them.
*/
oprofilefs_create_ulong(dir, "kernel", &ctr[i].kernel);
oprofilefs_create_ulong(dir, "user", &ctr[i].user);
oprofilefs_create_ulong(dir, "unit_mask", &ctr[i].unit_mask);
}
oprofilefs_create_ulong(root, "enable_kernel", &sys.enable_kernel);
oprofilefs_create_ulong(root, "enable_user", &sys.enable_user);
/* Default to tracing both kernel and user */
sys.enable_kernel = 1;
sys.enable_user = 1;
return 0;
}
int __init oprofile_arch_init(struct oprofile_operations *ops)
{
if (!cur_cpu_spec->oprofile_cpu_type)
return -ENODEV;
switch (cur_cpu_spec->oprofile_type) {
#ifdef CONFIG_PPC_BOOK3S_64
#ifdef CONFIG_OPROFILE_CELL
case PPC_OPROFILE_CELL:
if (firmware_has_feature(FW_FEATURE_LPAR))
return -ENODEV;
model = &op_model_cell;
ops->sync_start = model->sync_start;
ops->sync_stop = model->sync_stop;
break;
#endif
case PPC_OPROFILE_RS64:
model = &op_model_rs64;
break;
case PPC_OPROFILE_POWER4:
model = &op_model_power4;
break;
case PPC_OPROFILE_PA6T:
model = &op_model_pa6t;
break;
#endif
#ifdef CONFIG_6xx
case PPC_OPROFILE_G4:
model = &op_model_7450;
break;
#endif
#if defined(CONFIG_FSL_EMB_PERFMON)
case PPC_OPROFILE_FSL_EMB:
model = &op_model_fsl_emb;
break;
#endif
default:
return -ENODEV;
}
model->num_counters = cur_cpu_spec->num_pmcs;
ops->cpu_type = cur_cpu_spec->oprofile_cpu_type;
ops->create_files = op_powerpc_create_files;
ops->setup = op_powerpc_setup;
ops->shutdown = op_powerpc_shutdown;
ops->start = op_powerpc_start;
ops->stop = op_powerpc_stop;
ops->backtrace = op_powerpc_backtrace;
printk(KERN_DEBUG "oprofile: using %s performance monitoring.\n",
ops->cpu_type);
return 0;
}
void oprofile_arch_exit(void)
{
}
| gpl-2.0 |
jeboo/kernel_KK_i9505_NB8 | drivers/nfc/bcm2079x-i2c.c | 1033 | 12812 | /*
* Copyright (C) 2012 Broadcom Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/jiffies.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/miscdevice.h>
#include <linux/spinlock.h>
#include <linux/poll.h>
#include <linux/version.h>
#include <linux/nfc/bcm2079x.h>
/* do not change below */
#define MAX_BUFFER_SIZE 780
/* Read data */
#define PACKET_HEADER_SIZE_NCI (4)
#define PACKET_HEADER_SIZE_HCI (3)
#define PACKET_TYPE_NCI (16)
#define PACKET_TYPE_HCIEV (4)
#define MAX_PACKET_SIZE (PACKET_HEADER_SIZE_NCI + 255)
struct bcm2079x_dev {
wait_queue_head_t read_wq;
struct mutex read_mutex;
struct i2c_client *client;
struct miscdevice bcm2079x_device;
unsigned int wake_gpio;
unsigned int en_gpio;
unsigned int irq_gpio;
bool irq_enabled;
spinlock_t irq_enabled_lock;
unsigned int count_irq;
};
static void bcm2079x_init_stat(struct bcm2079x_dev *bcm2079x_dev)
{
bcm2079x_dev->count_irq = 0;
}
static void bcm2079x_disable_irq(struct bcm2079x_dev *bcm2079x_dev)
{
unsigned long flags;
spin_lock_irqsave(&bcm2079x_dev->irq_enabled_lock, flags);
if (bcm2079x_dev->irq_enabled) {
disable_irq_nosync(bcm2079x_dev->client->irq);
bcm2079x_dev->irq_enabled = false;
}
spin_unlock_irqrestore(&bcm2079x_dev->irq_enabled_lock, flags);
}
static void bcm2079x_enable_irq(struct bcm2079x_dev *bcm2079x_dev)
{
unsigned long flags;
spin_lock_irqsave(&bcm2079x_dev->irq_enabled_lock, flags);
if (!bcm2079x_dev->irq_enabled) {
bcm2079x_dev->irq_enabled = true;
enable_irq(bcm2079x_dev->client->irq);
}
spin_unlock_irqrestore(&bcm2079x_dev->irq_enabled_lock, flags);
}
/*
The alias address 0x79, when sent as a 7-bit address from the host processor
will match the first byte (highest 2 bits) of the default client address
(0x1FA) that is programmed in bcm20791.
When used together with the first byte (0xFA) of the byte sequence below,
it can be used to address the bcm20791 in a system that does not support
10-bit address and change the default address to 0x38.
the new address can be changed by changing the CLIENT_ADDRESS below if 0x38
conflicts with other device on the same i2c bus.
*/
#define ALIAS_ADDRESS 0x79
static int change_client_addr(struct bcm2079x_dev *bcm2079x_dev, int addr)
{
struct i2c_client *client;
int ret;
int i;
char addr_data[] = {
0xFA, 0xF2, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x2A
};
client = bcm2079x_dev->client;
client->addr = ALIAS_ADDRESS;
client->flags &= ~I2C_CLIENT_TEN;
addr_data[5] = addr & 0xFF;
ret = 0;
for (i = 1; i < sizeof(addr_data) - 1; ++i)
ret += addr_data[i];
addr_data[sizeof(addr_data) - 1] = (ret & 0xFF);
dev_info(&client->dev,
"Change client device from (0x%04X) flag = "\
"%04x, addr_data[%d] = %02x\n",
client->addr, client->flags, sizeof(addr_data) - 1,
addr_data[sizeof(addr_data) - 1]);
ret = i2c_master_send(client, addr_data, sizeof(addr_data));
if (ret != sizeof(addr_data)) {
client->addr = ALIAS_ADDRESS;
client->flags &= ~I2C_CLIENT_TEN;
dev_info(&client->dev,
"Change client device from (0x%04X) flag = "\
"%04x, addr_data[%d] = %02x\n",
client->addr, client->flags, sizeof(addr_data) - 1,
addr_data[sizeof(addr_data) - 1]);
ret = i2c_master_send(client, addr_data, sizeof(addr_data));
}
client->addr = addr_data[5];
dev_info(&client->dev,
"Change client device changed to (0x%04X) flag = %04x, ret = %d\n",
client->addr, client->flags, ret);
return (ret == sizeof(addr_data) ? 0 : -EIO);
}
static irqreturn_t bcm2079x_dev_irq_handler(int irq, void *dev_id)
{
struct bcm2079x_dev *bcm2079x_dev = dev_id;
unsigned long flags;
spin_lock_irqsave(&bcm2079x_dev->irq_enabled_lock, flags);
bcm2079x_dev->count_irq++;
spin_unlock_irqrestore(&bcm2079x_dev->irq_enabled_lock, flags);
wake_up(&bcm2079x_dev->read_wq);
return IRQ_HANDLED;
}
static unsigned int bcm2079x_dev_poll(struct file *filp, poll_table *wait)
{
struct bcm2079x_dev *bcm2079x_dev = filp->private_data;
unsigned int mask = 0;
unsigned long flags;
poll_wait(filp, &bcm2079x_dev->read_wq, wait);
spin_lock_irqsave(&bcm2079x_dev->irq_enabled_lock, flags);
if (bcm2079x_dev->count_irq > 0)
{
bcm2079x_dev->count_irq--;
mask |= POLLIN | POLLRDNORM;
}
spin_unlock_irqrestore(&bcm2079x_dev->irq_enabled_lock, flags);
return mask;
}
static ssize_t bcm2079x_dev_read(struct file *filp, char __user *buf,
size_t count, loff_t *offset)
{
struct bcm2079x_dev *bcm2079x_dev = filp->private_data;
unsigned char tmp[MAX_BUFFER_SIZE];
int total, len, ret;
total = 0;
len = 0;
if (count > MAX_BUFFER_SIZE)
count = MAX_BUFFER_SIZE;
mutex_lock(&bcm2079x_dev->read_mutex);
/** Read the first 4 bytes to include the length of the NCI or HCI packet.
**/
ret = i2c_master_recv(bcm2079x_dev->client, tmp, 4);
if (ret == 4) {
total = ret;
/** First byte is the packet type
**/
switch(tmp[0]) {
case PACKET_TYPE_NCI:
len = tmp[PACKET_HEADER_SIZE_NCI-1];
break;
case PACKET_TYPE_HCIEV:
len = tmp[PACKET_HEADER_SIZE_HCI-1];
if (len == 0)
total--;/*Since payload is 0, decrement total size (from 4 to 3) */
else
len--;/*First byte of payload is in tmp[3] already */
break;
default:
len = 0;/*Unknown packet byte */
break;
} /* switch*/
/** make sure full packet fits in the buffer
**/
if (len > 0 && (len + total) <= count) {
/** read the remainder of the packet.
**/
ret = i2c_master_recv(bcm2079x_dev->client, tmp+total, len);
if (ret == len)
total += len;
} /* if */
} /* if */
mutex_unlock(&bcm2079x_dev->read_mutex);
if (total > count || copy_to_user(buf, tmp, total)) {
dev_err(&bcm2079x_dev->client->dev,
"failed to copy to user space, total = %d\n", total);
total = -EFAULT;
}
return total;
}
static ssize_t bcm2079x_dev_write(struct file *filp, const char __user *buf,
size_t count, loff_t *offset)
{
struct bcm2079x_dev *bcm2079x_dev = filp->private_data;
char tmp[MAX_BUFFER_SIZE];
int ret;
if (count > MAX_BUFFER_SIZE) {
dev_err(&bcm2079x_dev->client->dev, "out of memory\n");
return -ENOMEM;
}
if (copy_from_user(tmp, buf, count)) {
dev_err(&bcm2079x_dev->client->dev,
"failed to copy from user space\n");
return -EFAULT;
}
mutex_lock(&bcm2079x_dev->read_mutex);
/* Write data */
ret = i2c_master_send(bcm2079x_dev->client, tmp, count);
if (ret != count) {
dev_err(&bcm2079x_dev->client->dev,
"failed to write %d\n", ret);
ret = -EIO;
}
mutex_unlock(&bcm2079x_dev->read_mutex);
return ret;
}
static int bcm2079x_dev_open(struct inode *inode, struct file *filp)
{
int ret = 0;
struct bcm2079x_dev *bcm2079x_dev = container_of(filp->private_data,
struct bcm2079x_dev,
bcm2079x_device);
filp->private_data = bcm2079x_dev;
bcm2079x_init_stat(bcm2079x_dev);
bcm2079x_enable_irq(bcm2079x_dev);
dev_info(&bcm2079x_dev->client->dev,
"%d,%d\n", imajor(inode), iminor(inode));
return ret;
}
static long bcm2079x_dev_unlocked_ioctl(struct file *filp,
unsigned int cmd, unsigned long arg)
{
struct bcm2079x_dev *bcm2079x_dev = filp->private_data;
switch (cmd) {
case BCMNFC_READ_FULL_PACKET:
break;
case BCMNFC_READ_MULTI_PACKETS:
break;
case BCMNFC_CHANGE_ADDR:
dev_info(&bcm2079x_dev->client->dev,
"%s, BCMNFC_CHANGE_ADDR (%x, %lx):\n", __func__, cmd,
arg);
return change_client_addr(bcm2079x_dev, arg);
case BCMNFC_POWER_CTL:
gpio_set_value(bcm2079x_dev->en_gpio, arg);
break;
case BCMNFC_WAKE_CTL:
gpio_set_value(bcm2079x_dev->wake_gpio, arg);
break;
default:
dev_err(&bcm2079x_dev->client->dev,
"%s, unknown cmd (%x, %lx)\n", __func__, cmd, arg);
return 0;
}
return 0;
}
static const struct file_operations bcm2079x_dev_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.poll = bcm2079x_dev_poll,
.read = bcm2079x_dev_read,
.write = bcm2079x_dev_write,
.open = bcm2079x_dev_open,
.unlocked_ioctl = bcm2079x_dev_unlocked_ioctl
};
static int bcm2079x_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret;
struct bcm2079x_platform_data *platform_data;
struct bcm2079x_dev *bcm2079x_dev;
platform_data = client->dev.platform_data;
dev_info(&client->dev, "%s, probing bcm2079x driver flags = %x\n", __func__, client->flags);
if (platform_data == NULL) {
dev_err(&client->dev, "nfc probe fail\n");
return -ENODEV;
}
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
dev_err(&client->dev, "need I2C_FUNC_I2C\n");
return -ENODEV;
}
ret = gpio_request_one(platform_data->irq_gpio, GPIOF_IN, "nfc_int");
if (ret)
return -ENODEV;
ret = gpio_request_one(platform_data->en_gpio, GPIOF_OUT_INIT_LOW, "nfc_ven");
if (ret)
goto err_en;
ret = gpio_request_one(platform_data->wake_gpio, GPIOF_OUT_INIT_LOW,"nfc_firm");
if (ret)
goto err_firm;
gpio_set_value(platform_data->en_gpio, 0);
gpio_set_value(platform_data->wake_gpio, 0);
bcm2079x_dev = kzalloc(sizeof(*bcm2079x_dev), GFP_KERNEL);
if (bcm2079x_dev == NULL) {
dev_err(&client->dev,
"failed to allocate memory for module data\n");
ret = -ENOMEM;
goto err_exit;
}
bcm2079x_dev->wake_gpio = platform_data->wake_gpio;
bcm2079x_dev->irq_gpio = platform_data->irq_gpio;
bcm2079x_dev->en_gpio = platform_data->en_gpio;
bcm2079x_dev->client = client;
/* init mutex and queues */
init_waitqueue_head(&bcm2079x_dev->read_wq);
mutex_init(&bcm2079x_dev->read_mutex);
spin_lock_init(&bcm2079x_dev->irq_enabled_lock);
bcm2079x_dev->bcm2079x_device.minor = MISC_DYNAMIC_MINOR;
bcm2079x_dev->bcm2079x_device.name = "bcm2079x-i2c";
bcm2079x_dev->bcm2079x_device.fops = &bcm2079x_dev_fops;
ret = misc_register(&bcm2079x_dev->bcm2079x_device);
if (ret) {
dev_err(&client->dev, "misc_register failed\n");
goto err_misc_register;
}
/* request irq. the irq is set whenever the chip has data available
* for reading. it is cleared when all data has been read.
*/
dev_info(&client->dev, "requesting IRQ %d\n", client->irq);
bcm2079x_dev->irq_enabled = true;
ret = request_irq(client->irq, bcm2079x_dev_irq_handler,
IRQF_TRIGGER_RISING, client->name, bcm2079x_dev);
if (ret) {
dev_err(&client->dev, "request_irq failed\n");
goto err_request_irq_failed;
}
bcm2079x_disable_irq(bcm2079x_dev);
i2c_set_clientdata(client, bcm2079x_dev);
dev_info(&client->dev,
"%s, probing bcm2079x driver exited successfully\n",
__func__);
return 0;
err_request_irq_failed:
misc_deregister(&bcm2079x_dev->bcm2079x_device);
err_misc_register:
mutex_destroy(&bcm2079x_dev->read_mutex);
kfree(bcm2079x_dev);
err_exit:
gpio_free(platform_data->wake_gpio);
err_firm:
gpio_free(platform_data->en_gpio);
err_en:
gpio_free(platform_data->irq_gpio);
return ret;
}
static int bcm2079x_remove(struct i2c_client *client)
{
struct bcm2079x_dev *bcm2079x_dev;
bcm2079x_dev = i2c_get_clientdata(client);
free_irq(client->irq, bcm2079x_dev);
misc_deregister(&bcm2079x_dev->bcm2079x_device);
mutex_destroy(&bcm2079x_dev->read_mutex);
gpio_free(bcm2079x_dev->irq_gpio);
gpio_free(bcm2079x_dev->en_gpio);
gpio_free(bcm2079x_dev->wake_gpio);
kfree(bcm2079x_dev);
return 0;
}
static const struct i2c_device_id bcm2079x_id[] = {
{"bcm2079x-i2c", 0},
{}
};
static struct i2c_driver bcm2079x_driver = {
.id_table = bcm2079x_id,
.probe = bcm2079x_probe,
.remove = bcm2079x_remove,
.driver = {
.owner = THIS_MODULE,
.name = "bcm2079x-i2c",
},
};
/*
* module load/unload record keeping
*/
static int __init bcm2079x_dev_init(void)
{
return i2c_add_driver(&bcm2079x_driver);
}
module_init(bcm2079x_dev_init);
static void __exit bcm2079x_dev_exit(void)
{
i2c_del_driver(&bcm2079x_driver);
}
module_exit(bcm2079x_dev_exit);
MODULE_AUTHOR("Broadcom");
MODULE_DESCRIPTION("NFC bcm2079x driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
M1cha/android_kernel_xiaomi_aries | drivers/video/msm/mipi_renesas.c | 1289 | 53994 | /* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "msm_fb.h"
#include "mipi_dsi.h"
#include "mipi_renesas.h"
#include <mach/socinfo.h>
#define RENESAS_CMD_DELAY 0 /* 50 */
#define RENESAS_SLEEP_OFF_DELAY 50
static struct msm_panel_common_pdata *mipi_renesas_pdata;
static struct dsi_buf renesas_tx_buf;
static struct dsi_buf renesas_rx_buf;
static int mipi_renesas_lcd_init(void);
static char config_sleep_out[2] = {0x11, 0x00};
static char config_CMD_MODE[2] = {0x40, 0x01};
static char config_WRTXHT[7] = {0x92, 0x16, 0x08, 0x08, 0x00, 0x01, 0xe0};
static char config_WRTXVT[7] = {0x8b, 0x02, 0x02, 0x02, 0x00, 0x03, 0x60};
static char config_PLL2NR[2] = {0xa0, 0x24};
static char config_PLL2NF1[2] = {0xa2, 0xd0};
static char config_PLL2NF2[2] = {0xa4, 0x00};
static char config_PLL2BWADJ1[2] = {0xa6, 0xd0};
static char config_PLL2BWADJ2[2] = {0xa8, 0x00};
static char config_PLL2CTL[2] = {0xaa, 0x00};
static char config_DBICBR[2] = {0x48, 0x03};
static char config_DBICTYPE[2] = {0x49, 0x00};
static char config_DBICSET1[2] = {0x4a, 0x1c};
static char config_DBICADD[2] = {0x4b, 0x00};
static char config_DBICCTL[2] = {0x4e, 0x01};
/* static char config_COLMOD_565[2] = {0x3a, 0x05}; */
/* static char config_COLMOD_666PACK[2] = {0x3a, 0x06}; */
static char config_COLMOD_888[2] = {0x3a, 0x07};
static char config_MADCTL[2] = {0x36, 0x00};
static char config_DBIOC[2] = {0x82, 0x40};
static char config_CASET[7] = {0x2a, 0x00, 0x00, 0x00, 0x00, 0x01, 0xdf };
static char config_PASET[7] = {0x2b, 0x00, 0x00, 0x00, 0x00, 0x03, 0x5f };
static char config_TXON[2] = {0x81, 0x00};
static char config_BLSET_TM[2] = {0xff, 0x6c};
static char config_DSIRXCTL[2] = {0x41, 0x01};
static char config_TEON[2] = {0x35, 0x00};
static char config_TEOFF[1] = {0x34};
static char config_AGCPSCTL_TM[2] = {0x56, 0x08};
static char config_DBICADD70[2] = {0x4b, 0x70};
static char config_DBICSET_15[2] = {0x4a, 0x15};
static char config_DBICADD72[2] = {0x4b, 0x72};
static char config_Power_Ctrl_2a_cmd[3] = {0x4c, 0x40, 0x10};
static char config_Auto_Sequencer_Setting_a_cmd[3] = {0x4c, 0x00, 0x00};
static char Driver_Output_Ctrl_indx[3] = {0x4c, 0x00, 0x01};
static char Driver_Output_Ctrl_cmd[3] = {0x4c, 0x03, 0x10};
static char config_LCD_drive_AC_Ctrl_indx[3] = {0x4c, 0x00, 0x02};
static char config_LCD_drive_AC_Ctrl_cmd[3] = {0x4c, 0x01, 0x00};
static char config_Entry_Mode_indx[3] = {0x4c, 0x00, 0x03};
static char config_Entry_Mode_cmd[3] = {0x4c, 0x00, 0x00};
static char config_Display_Ctrl_1_indx[3] = {0x4c, 0x00, 0x07};
static char config_Display_Ctrl_1_cmd[3] = {0x4c, 0x00, 0x00};
static char config_Display_Ctrl_2_indx[3] = {0x4c, 0x00, 0x08};
static char config_Display_Ctrl_2_cmd[3] = {0x4c, 0x00, 0x04};
static char config_Display_Ctrl_3_indx[3] = {0x4c, 0x00, 0x09};
static char config_Display_Ctrl_3_cmd[3] = {0x4c, 0x00, 0x0c};
static char config_Display_IF_Ctrl_1_indx[3] = {0x4c, 0x00, 0x0c};
static char config_Display_IF_Ctrl_1_cmd[3] = {0x4c, 0x40, 0x10};
static char config_Display_IF_Ctrl_2_indx[3] = {0x4c, 0x00, 0x0e};
static char config_Display_IF_Ctrl_2_cmd[3] = {0x4c, 0x00, 0x00};
static char config_Panel_IF_Ctrl_1_indx[3] = {0x4c, 0x00, 0x20};
static char config_Panel_IF_Ctrl_1_cmd[3] = {0x4c, 0x01, 0x3f};
static char config_Panel_IF_Ctrl_3_indx[3] = {0x4c, 0x00, 0x22};
static char config_Panel_IF_Ctrl_3_cmd[3] = {0x4c, 0x76, 0x00};
static char config_Panel_IF_Ctrl_4_indx[3] = {0x4c, 0x00, 0x23};
static char config_Panel_IF_Ctrl_4_cmd[3] = {0x4c, 0x1c, 0x0a};
static char config_Panel_IF_Ctrl_5_indx[3] = {0x4c, 0x00, 0x24};
static char config_Panel_IF_Ctrl_5_cmd[3] = {0x4c, 0x1c, 0x2c};
static char config_Panel_IF_Ctrl_6_indx[3] = {0x4c, 0x00, 0x25};
static char config_Panel_IF_Ctrl_6_cmd[3] = {0x4c, 0x1c, 0x4e};
static char config_Panel_IF_Ctrl_8_indx[3] = {0x4c, 0x00, 0x27};
static char config_Panel_IF_Ctrl_8_cmd[3] = {0x4c, 0x00, 0x00};
static char config_Panel_IF_Ctrl_9_indx[3] = {0x4c, 0x00, 0x28};
static char config_Panel_IF_Ctrl_9_cmd[3] = {0x4c, 0x76, 0x0c};
static char config_gam_adjust_00_indx[3] = {0x4c, 0x03, 0x00};
static char config_gam_adjust_00_cmd[3] = {0x4c, 0x00, 0x00};
static char config_gam_adjust_01_indx[3] = {0x4c, 0x03, 0x01};
static char config_gam_adjust_01_cmd[3] = {0x4c, 0x05, 0x02};
static char config_gam_adjust_02_indx[3] = {0x4c, 0x03, 0x02};
static char config_gam_adjust_02_cmd[3] = {0x4c, 0x07, 0x05};
static char config_gam_adjust_03_indx[3] = {0x4c, 0x03, 0x03};
static char config_gam_adjust_03_cmd[3] = {0x4c, 0x00, 0x00};
static char config_gam_adjust_04_indx[3] = {0x4c, 0x03, 0x04};
static char config_gam_adjust_04_cmd[3] = {0x4c, 0x02, 0x00};
static char config_gam_adjust_05_indx[3] = {0x4c, 0x03, 0x05};
static char config_gam_adjust_05_cmd[3] = {0x4c, 0x07, 0x07};
static char config_gam_adjust_06_indx[3] = {0x4c, 0x03, 0x06};
static char config_gam_adjust_06_cmd[3] = {0x4c, 0x10, 0x10};
static char config_gam_adjust_07_indx[3] = {0x4c, 0x03, 0x07};
static char config_gam_adjust_07_cmd[3] = {0x4c, 0x02, 0x02};
static char config_gam_adjust_08_indx[3] = {0x4c, 0x03, 0x08};
static char config_gam_adjust_08_cmd[3] = {0x4c, 0x07, 0x04};
static char config_gam_adjust_09_indx[3] = {0x4c, 0x03, 0x09};
static char config_gam_adjust_09_cmd[3] = {0x4c, 0x07, 0x07};
static char config_gam_adjust_0A_indx[3] = {0x4c, 0x03, 0x0a};
static char config_gam_adjust_0A_cmd[3] = {0x4c, 0x00, 0x00};
static char config_gam_adjust_0B_indx[3] = {0x4c, 0x03, 0x0b};
static char config_gam_adjust_0B_cmd[3] = {0x4c, 0x00, 0x00};
static char config_gam_adjust_0C_indx[3] = {0x4c, 0x03, 0x0c};
static char config_gam_adjust_0C_cmd[3] = {0x4c, 0x07, 0x07};
static char config_gam_adjust_0D_indx[3] = {0x4c, 0x03, 0x0d};
static char config_gam_adjust_0D_cmd[3] = {0x4c, 0x10, 0x10};
static char config_gam_adjust_10_indx[3] = {0x4c, 0x03, 0x10};
static char config_gam_adjust_10_cmd[3] = {0x4c, 0x01, 0x04};
static char config_gam_adjust_11_indx[3] = {0x4c, 0x03, 0x11};
static char config_gam_adjust_11_cmd[3] = {0x4c, 0x05, 0x03};
static char config_gam_adjust_12_indx[3] = {0x4c, 0x03, 0x12};
static char config_gam_adjust_12_cmd[3] = {0x4c, 0x03, 0x04};
static char config_gam_adjust_15_indx[3] = {0x4c, 0x03, 0x15};
static char config_gam_adjust_15_cmd[3] = {0x4c, 0x03, 0x04};
static char config_gam_adjust_16_indx[3] = {0x4c, 0x03, 0x16};
static char config_gam_adjust_16_cmd[3] = {0x4c, 0x03, 0x1c};
static char config_gam_adjust_17_indx[3] = {0x4c, 0x03, 0x17};
static char config_gam_adjust_17_cmd[3] = {0x4c, 0x02, 0x04};
static char config_gam_adjust_18_indx[3] = {0x4c, 0x03, 0x18};
static char config_gam_adjust_18_cmd[3] = {0x4c, 0x04, 0x02};
static char config_gam_adjust_19_indx[3] = {0x4c, 0x03, 0x19};
static char config_gam_adjust_19_cmd[3] = {0x4c, 0x03, 0x05};
static char config_gam_adjust_1C_indx[3] = {0x4c, 0x03, 0x1c};
static char config_gam_adjust_1C_cmd[3] = {0x4c, 0x07, 0x07};
static char config_gam_adjust_1D_indx[3] = {0x4c, 0x03, 0x1D};
static char config_gam_adjust_1D_cmd[3] = {0x4c, 0x02, 0x1f};
static char config_gam_adjust_20_indx[3] = {0x4c, 0x03, 0x20};
static char config_gam_adjust_20_cmd[3] = {0x4c, 0x05, 0x07};
static char config_gam_adjust_21_indx[3] = {0x4c, 0x03, 0x21};
static char config_gam_adjust_21_cmd[3] = {0x4c, 0x06, 0x04};
static char config_gam_adjust_22_indx[3] = {0x4c, 0x03, 0x22};
static char config_gam_adjust_22_cmd[3] = {0x4c, 0x04, 0x05};
static char config_gam_adjust_27_indx[3] = {0x4c, 0x03, 0x27};
static char config_gam_adjust_27_cmd[3] = {0x4c, 0x02, 0x03};
static char config_gam_adjust_28_indx[3] = {0x4c, 0x03, 0x28};
static char config_gam_adjust_28_cmd[3] = {0x4c, 0x03, 0x00};
static char config_gam_adjust_29_indx[3] = {0x4c, 0x03, 0x29};
static char config_gam_adjust_29_cmd[3] = {0x4c, 0x00, 0x02};
static char config_Power_Ctrl_1_indx[3] = {0x4c, 0x01, 0x00};
static char config_Power_Ctrl_1b_cmd[3] = {0x4c, 0x36, 0x3c};
static char config_Power_Ctrl_2_indx[3] = {0x4c, 0x01, 0x01};
static char config_Power_Ctrl_2b_cmd[3] = {0x4c, 0x40, 0x03};
static char config_Power_Ctrl_3_indx[3] = {0x4c, 0x01, 0x02};
static char config_Power_Ctrl_3a_cmd[3] = {0x4c, 0x00, 0x01};
static char config_Power_Ctrl_4_indx[3] = {0x4c, 0x01, 0x03};
static char config_Power_Ctrl_4a_cmd[3] = {0x4c, 0x3c, 0x58};
static char config_Power_Ctrl_6_indx[3] = {0x4c, 0x01, 0x0c};
static char config_Power_Ctrl_6a_cmd[3] = {0x4c, 0x01, 0x35};
static char config_Auto_Sequencer_Setting_b_cmd[3] = {0x4c, 0x00, 0x02};
static char config_Panel_IF_Ctrl_10_indx[3] = {0x4c, 0x00, 0x29};
static char config_Panel_IF_Ctrl_10a_cmd[3] = {0x4c, 0x03, 0xbf};
static char config_Auto_Sequencer_Setting_indx[3] = {0x4c, 0x01, 0x06};
static char config_Auto_Sequencer_Setting_c_cmd[3] = {0x4c, 0x00, 0x03};
static char config_Power_Ctrl_2c_cmd[3] = {0x4c, 0x40, 0x10};
static char config_VIDEO[2] = {0x40, 0x00};
static char config_Panel_IF_Ctrl_10_indx_off[3] = {0x4C, 0x00, 0x29};
static char config_Panel_IF_Ctrl_10b_cmd_off[3] = {0x4C, 0x00, 0x02};
static char config_Power_Ctrl_1a_cmd[3] = {0x4C, 0x30, 0x00};
static struct dsi_cmd_desc renesas_sleep_off_cmds[] = {
{DTYPE_DCS_WRITE, 1, 0, 0, RENESAS_SLEEP_OFF_DELAY,
sizeof(config_sleep_out), config_sleep_out }
};
static struct dsi_cmd_desc renesas_display_off_cmds[] = {
/* Choosing Command Mode */
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_CMD_MODE), config_CMD_MODE },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_indx),
config_Auto_Sequencer_Setting_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_b_cmd),
config_Auto_Sequencer_Setting_b_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY * 2,
sizeof(config_DBICSET_15), config_DBICSET_15},
/* After waiting >= 5 frames, turn OFF RGB signals
This is done by on DSI/MDP (depends on Vid/Cmd Mode. */
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_indx),
config_Auto_Sequencer_Setting_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_a_cmd),
config_Auto_Sequencer_Setting_a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_10_indx_off),
config_Panel_IF_Ctrl_10_indx_off},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_10b_cmd_off),
config_Panel_IF_Ctrl_10b_cmd_off},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_1_indx),
config_Power_Ctrl_1_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_1a_cmd),
config_Power_Ctrl_1a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_TEOFF), config_TEOFF},
};
static struct dsi_cmd_desc renesas_display_on_cmds[] = {
/* Choosing Command Mode */
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_CMD_MODE), config_CMD_MODE },
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_WRTXHT), config_WRTXHT },
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_WRTXVT), config_WRTXVT },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_PLL2NR), config_PLL2NR },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_PLL2NF1), config_PLL2NF1 },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_PLL2NF2), config_PLL2NF2 },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_PLL2BWADJ1), config_PLL2BWADJ1},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_PLL2BWADJ2), config_PLL2BWADJ2},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_PLL2CTL), config_PLL2CTL},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICBR), config_DBICBR},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICTYPE), config_DBICTYPE},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET1), config_DBICSET1},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD), config_DBICADD},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICCTL), config_DBICCTL},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_COLMOD_888), config_COLMOD_888},
/* Choose config_COLMOD_565 or config_COLMOD_666PACK for other modes */
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_MADCTL), config_MADCTL},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBIOC), config_DBIOC},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_CASET), config_CASET},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_PASET), config_PASET},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DSIRXCTL), config_DSIRXCTL},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_TEON), config_TEON},
{DTYPE_DCS_WRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_TXON), config_TXON},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_BLSET_TM), config_BLSET_TM},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_AGCPSCTL_TM), config_AGCPSCTL_TM},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_1_indx), config_Power_Ctrl_1_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_1a_cmd), config_Power_Ctrl_1a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_2_indx), config_Power_Ctrl_2_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_2a_cmd), config_Power_Ctrl_2a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_indx),
config_Auto_Sequencer_Setting_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_a_cmd),
config_Auto_Sequencer_Setting_a_cmd },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(Driver_Output_Ctrl_indx), Driver_Output_Ctrl_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(Driver_Output_Ctrl_cmd),
Driver_Output_Ctrl_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_LCD_drive_AC_Ctrl_indx),
config_LCD_drive_AC_Ctrl_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_LCD_drive_AC_Ctrl_cmd),
config_LCD_drive_AC_Ctrl_cmd },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Entry_Mode_indx),
config_Entry_Mode_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Entry_Mode_cmd),
config_Entry_Mode_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_Ctrl_1_indx),
config_Display_Ctrl_1_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_Ctrl_1_cmd),
config_Display_Ctrl_1_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_Ctrl_2_indx),
config_Display_Ctrl_2_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_Ctrl_2_cmd),
config_Display_Ctrl_2_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_Ctrl_3_indx),
config_Display_Ctrl_3_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_Ctrl_3_cmd),
config_Display_Ctrl_3_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_IF_Ctrl_1_indx),
config_Display_IF_Ctrl_1_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_IF_Ctrl_1_cmd),
config_Display_IF_Ctrl_1_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_IF_Ctrl_2_indx),
config_Display_IF_Ctrl_2_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Display_IF_Ctrl_2_cmd),
config_Display_IF_Ctrl_2_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_1_indx),
config_Panel_IF_Ctrl_1_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_1_cmd),
config_Panel_IF_Ctrl_1_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_3_indx),
config_Panel_IF_Ctrl_3_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_3_cmd),
config_Panel_IF_Ctrl_3_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_4_indx),
config_Panel_IF_Ctrl_4_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_4_cmd),
config_Panel_IF_Ctrl_4_cmd },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_5_indx),
config_Panel_IF_Ctrl_5_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_5_cmd),
config_Panel_IF_Ctrl_5_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_6_indx),
config_Panel_IF_Ctrl_6_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_6_cmd),
config_Panel_IF_Ctrl_6_cmd },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_8_indx),
config_Panel_IF_Ctrl_8_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_8_cmd),
config_Panel_IF_Ctrl_8_cmd },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_9_indx),
config_Panel_IF_Ctrl_9_indx },
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_9_cmd),
config_Panel_IF_Ctrl_9_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_00_indx),
config_gam_adjust_00_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_00_cmd),
config_gam_adjust_00_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_01_indx),
config_gam_adjust_01_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_01_cmd),
config_gam_adjust_01_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_02_indx),
config_gam_adjust_02_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_02_cmd),
config_gam_adjust_02_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_03_indx),
config_gam_adjust_03_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_03_cmd),
config_gam_adjust_03_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_04_indx), config_gam_adjust_04_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_04_cmd), config_gam_adjust_04_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_05_indx), config_gam_adjust_05_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_05_cmd), config_gam_adjust_05_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_06_indx), config_gam_adjust_06_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_06_cmd), config_gam_adjust_06_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_07_indx), config_gam_adjust_07_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_07_cmd), config_gam_adjust_07_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_08_indx), config_gam_adjust_08_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_08_cmd), config_gam_adjust_08_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_09_indx), config_gam_adjust_09_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_09_cmd), config_gam_adjust_09_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0A_indx), config_gam_adjust_0A_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0A_cmd), config_gam_adjust_0A_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0B_indx), config_gam_adjust_0B_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0B_cmd), config_gam_adjust_0B_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0C_indx), config_gam_adjust_0C_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0C_cmd), config_gam_adjust_0C_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0D_indx), config_gam_adjust_0D_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_0D_cmd), config_gam_adjust_0D_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_10_indx), config_gam_adjust_10_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_10_cmd), config_gam_adjust_10_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_11_indx), config_gam_adjust_11_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_11_cmd), config_gam_adjust_11_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_12_indx), config_gam_adjust_12_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_12_cmd), config_gam_adjust_12_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_15_indx), config_gam_adjust_15_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_15_cmd), config_gam_adjust_15_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_16_indx), config_gam_adjust_16_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_16_cmd), config_gam_adjust_16_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_17_indx), config_gam_adjust_17_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_17_cmd), config_gam_adjust_17_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_18_indx), config_gam_adjust_18_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_18_cmd), config_gam_adjust_18_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_19_indx), config_gam_adjust_19_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_19_cmd), config_gam_adjust_19_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_1C_indx), config_gam_adjust_1C_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_1C_cmd), config_gam_adjust_1C_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_1D_indx), config_gam_adjust_1D_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_1D_cmd), config_gam_adjust_1D_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_20_indx), config_gam_adjust_20_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_20_cmd), config_gam_adjust_20_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_21_indx), config_gam_adjust_21_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_21_cmd), config_gam_adjust_21_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_22_indx), config_gam_adjust_22_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_22_cmd), config_gam_adjust_22_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_27_indx), config_gam_adjust_27_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_27_cmd), config_gam_adjust_27_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_28_indx), config_gam_adjust_28_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_28_cmd), config_gam_adjust_28_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_29_indx), config_gam_adjust_29_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_gam_adjust_29_cmd), config_gam_adjust_29_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_1_indx), config_Power_Ctrl_1_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_1b_cmd), config_Power_Ctrl_1b_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_2_indx), config_Power_Ctrl_2_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_2b_cmd), config_Power_Ctrl_2b_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_3_indx), config_Power_Ctrl_3_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_3a_cmd), config_Power_Ctrl_3a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_4_indx), config_Power_Ctrl_4_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_4a_cmd), config_Power_Ctrl_4a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_6_indx), config_Power_Ctrl_6_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_6a_cmd), config_Power_Ctrl_6a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_indx),
config_Auto_Sequencer_Setting_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_b_cmd),
config_Auto_Sequencer_Setting_b_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_10_indx),
config_Panel_IF_Ctrl_10_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Panel_IF_Ctrl_10a_cmd),
config_Panel_IF_Ctrl_10a_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_indx),
config_Auto_Sequencer_Setting_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Auto_Sequencer_Setting_c_cmd),
config_Auto_Sequencer_Setting_c_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD70), config_DBICADD70},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_2_indx),
config_Power_Ctrl_2_indx},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICSET_15), config_DBICSET_15},
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_DBICADD72), config_DBICADD72},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_Power_Ctrl_2c_cmd),
config_Power_Ctrl_2c_cmd},
{DTYPE_DCS_WRITE1, 1, 0, 0, 0/* RENESAS_CMD_DELAY */,
sizeof(config_DBICSET_15), config_DBICSET_15},
};
static char config_WRTXHT2[7] = {0x92, 0x15, 0x05, 0x0F, 0x00, 0x01, 0xe0};
static char config_WRTXVT2[7] = {0x8b, 0x14, 0x01, 0x14, 0x00, 0x03, 0x60};
static struct dsi_cmd_desc renesas_hvga_on_cmds[] = {
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_WRTXHT2), config_WRTXHT2},
{DTYPE_DCS_LWRITE, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_WRTXVT2), config_WRTXVT2},
};
static struct dsi_cmd_desc renesas_video_on_cmds[] = {
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_VIDEO), config_VIDEO}
};
static struct dsi_cmd_desc renesas_cmd_on_cmds[] = {
{DTYPE_DCS_WRITE1, 1, 0, 0, RENESAS_CMD_DELAY,
sizeof(config_CMD_MODE), config_CMD_MODE},
};
static int mipi_renesas_lcd_on(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd;
struct mipi_panel_info *mipi;
mfd = platform_get_drvdata(pdev);
mipi = &mfd->panel_info.mipi;
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
mipi_dsi_cmds_tx(&renesas_tx_buf, renesas_sleep_off_cmds,
ARRAY_SIZE(renesas_sleep_off_cmds));
mipi_set_tx_power_mode(1);
mipi_dsi_cmds_tx(&renesas_tx_buf, renesas_display_on_cmds,
ARRAY_SIZE(renesas_display_on_cmds));
if (cpu_is_msm7x25a() || cpu_is_msm7x25aa() || cpu_is_msm7x25ab()) {
mipi_dsi_cmds_tx(&renesas_tx_buf, renesas_hvga_on_cmds,
ARRAY_SIZE(renesas_hvga_on_cmds));
}
if (mipi->mode == DSI_VIDEO_MODE)
mipi_dsi_cmds_tx(&renesas_tx_buf, renesas_video_on_cmds,
ARRAY_SIZE(renesas_video_on_cmds));
else
mipi_dsi_cmds_tx(&renesas_tx_buf, renesas_cmd_on_cmds,
ARRAY_SIZE(renesas_cmd_on_cmds));
mipi_set_tx_power_mode(0);
return 0;
}
static int mipi_renesas_lcd_off(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd;
mfd = platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
mipi_dsi_cmds_tx(&renesas_tx_buf, renesas_display_off_cmds,
ARRAY_SIZE(renesas_display_off_cmds));
return 0;
}
static int __devinit mipi_renesas_lcd_probe(struct platform_device *pdev)
{
if (pdev->id == 0) {
mipi_renesas_pdata = pdev->dev.platform_data;
return 0;
}
msm_fb_add_device(pdev);
return 0;
}
static void mipi_renesas_set_backlight(struct msm_fb_data_type *mfd)
{
int ret = -EPERM;
int bl_level;
bl_level = mfd->bl_level;
if (mipi_renesas_pdata && mipi_renesas_pdata->pmic_backlight)
ret = mipi_renesas_pdata->pmic_backlight(bl_level);
else
pr_err("%s(): Backlight level set failed", __func__);
}
static struct platform_driver this_driver = {
.probe = mipi_renesas_lcd_probe,
.driver = {
.name = "mipi_renesas",
},
};
static struct msm_fb_panel_data renesas_panel_data = {
.on = mipi_renesas_lcd_on,
.off = mipi_renesas_lcd_off,
.set_backlight = mipi_renesas_set_backlight,
};
static int ch_used[3];
int mipi_renesas_device_register(struct msm_panel_info *pinfo,
u32 channel, u32 panel)
{
struct platform_device *pdev = NULL;
int ret;
if ((channel >= 3) || ch_used[channel])
return -ENODEV;
ch_used[channel] = TRUE;
ret = mipi_renesas_lcd_init();
if (ret) {
pr_err("mipi_renesas_lcd_init() failed with ret %u\n", ret);
return ret;
}
pdev = platform_device_alloc("mipi_renesas", (panel << 8)|channel);
if (!pdev)
return -ENOMEM;
renesas_panel_data.panel_info = *pinfo;
ret = platform_device_add_data(pdev, &renesas_panel_data,
sizeof(renesas_panel_data));
if (ret) {
pr_err("%s: platform_device_add_data failed!\n", __func__);
goto err_device_put;
}
ret = platform_device_add(pdev);
if (ret) {
pr_err("%s: platform_device_register failed!\n", __func__);
goto err_device_put;
}
return 0;
err_device_put:
platform_device_put(pdev);
return ret;
}
static int mipi_renesas_lcd_init(void)
{
mipi_dsi_buf_alloc(&renesas_tx_buf, DSI_BUF_SIZE);
mipi_dsi_buf_alloc(&renesas_rx_buf, DSI_BUF_SIZE);
return platform_driver_register(&this_driver);
}
| gpl-2.0 |
fenggangwu/sffs | drivers/net/ethernet/samsung/sxgbe/sxgbe_xpcs.c | 1545 | 2797 | /* 10G controller driver for Samsung SoCs
*
* Copyright (C) 2013 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Author: Siva Reddy Kallam <siva.kallam@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/bitops.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/phy.h>
#include "sxgbe_common.h"
#include "sxgbe_xpcs.h"
static int sxgbe_xpcs_read(struct net_device *ndev, unsigned int reg)
{
u32 value;
struct sxgbe_priv_data *priv = netdev_priv(ndev);
value = readl(priv->ioaddr + XPCS_OFFSET + reg);
return value;
}
static int sxgbe_xpcs_write(struct net_device *ndev, int reg, int data)
{
struct sxgbe_priv_data *priv = netdev_priv(ndev);
writel(data, priv->ioaddr + XPCS_OFFSET + reg);
return 0;
}
int sxgbe_xpcs_init(struct net_device *ndev)
{
u32 value;
value = sxgbe_xpcs_read(ndev, SR_PCS_MMD_CONTROL1);
/* 10G XAUI mode */
sxgbe_xpcs_write(ndev, SR_PCS_CONTROL2, XPCS_TYPE_SEL_X);
sxgbe_xpcs_write(ndev, VR_PCS_MMD_XAUI_MODE_CONTROL, XPCS_XAUI_MODE);
sxgbe_xpcs_write(ndev, VR_PCS_MMD_XAUI_MODE_CONTROL, value | BIT(13));
sxgbe_xpcs_write(ndev, SR_PCS_MMD_CONTROL1, value | BIT(11));
do {
value = sxgbe_xpcs_read(ndev, VR_PCS_MMD_DIGITAL_STATUS);
} while ((value & XPCS_QSEQ_STATE_MPLLOFF) == XPCS_QSEQ_STATE_STABLE);
value = sxgbe_xpcs_read(ndev, SR_PCS_MMD_CONTROL1);
sxgbe_xpcs_write(ndev, SR_PCS_MMD_CONTROL1, value & ~BIT(11));
do {
value = sxgbe_xpcs_read(ndev, VR_PCS_MMD_DIGITAL_STATUS);
} while ((value & XPCS_QSEQ_STATE_MPLLOFF) != XPCS_QSEQ_STATE_STABLE);
return 0;
}
int sxgbe_xpcs_init_1G(struct net_device *ndev)
{
int value;
/* 10GBASE-X PCS (1G) mode */
sxgbe_xpcs_write(ndev, SR_PCS_CONTROL2, XPCS_TYPE_SEL_X);
sxgbe_xpcs_write(ndev, VR_PCS_MMD_XAUI_MODE_CONTROL, XPCS_XAUI_MODE);
value = sxgbe_xpcs_read(ndev, SR_PCS_MMD_CONTROL1);
sxgbe_xpcs_write(ndev, SR_PCS_MMD_CONTROL1, value & ~BIT(13));
value = sxgbe_xpcs_read(ndev, SR_MII_MMD_CONTROL);
sxgbe_xpcs_write(ndev, SR_MII_MMD_CONTROL, value | BIT(6));
sxgbe_xpcs_write(ndev, SR_MII_MMD_CONTROL, value & ~BIT(13));
value = sxgbe_xpcs_read(ndev, SR_PCS_MMD_CONTROL1);
sxgbe_xpcs_write(ndev, SR_PCS_MMD_CONTROL1, value | BIT(11));
do {
value = sxgbe_xpcs_read(ndev, VR_PCS_MMD_DIGITAL_STATUS);
} while ((value & XPCS_QSEQ_STATE_MPLLOFF) != XPCS_QSEQ_STATE_STABLE);
value = sxgbe_xpcs_read(ndev, SR_PCS_MMD_CONTROL1);
sxgbe_xpcs_write(ndev, SR_PCS_MMD_CONTROL1, value & ~BIT(11));
/* Auto Negotiation cluase 37 enable */
value = sxgbe_xpcs_read(ndev, SR_MII_MMD_CONTROL);
sxgbe_xpcs_write(ndev, SR_MII_MMD_CONTROL, value | BIT(12));
return 0;
}
| gpl-2.0 |
dext3r/lpc3xxx-ea3250v2 | drivers/base/bus.c | 2313 | 25706 | /*
* bus.c - bus driver management
*
* Copyright (c) 2002-3 Patrick Mochel
* Copyright (c) 2002-3 Open Source Development Labs
* Copyright (c) 2007 Greg Kroah-Hartman <gregkh@suse.de>
* Copyright (c) 2007 Novell Inc.
*
* This file is released under the GPLv2
*
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/string.h>
#include "base.h"
#include "power/power.h"
#define to_bus_attr(_attr) container_of(_attr, struct bus_attribute, attr)
/*
* sysfs bindings for drivers
*/
#define to_drv_attr(_attr) container_of(_attr, struct driver_attribute, attr)
static int __must_check bus_rescan_devices_helper(struct device *dev,
void *data);
static struct bus_type *bus_get(struct bus_type *bus)
{
if (bus) {
kset_get(&bus->p->subsys);
return bus;
}
return NULL;
}
static void bus_put(struct bus_type *bus)
{
if (bus)
kset_put(&bus->p->subsys);
}
static ssize_t drv_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct driver_attribute *drv_attr = to_drv_attr(attr);
struct driver_private *drv_priv = to_driver(kobj);
ssize_t ret = -EIO;
if (drv_attr->show)
ret = drv_attr->show(drv_priv->driver, buf);
return ret;
}
static ssize_t drv_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct driver_attribute *drv_attr = to_drv_attr(attr);
struct driver_private *drv_priv = to_driver(kobj);
ssize_t ret = -EIO;
if (drv_attr->store)
ret = drv_attr->store(drv_priv->driver, buf, count);
return ret;
}
static const struct sysfs_ops driver_sysfs_ops = {
.show = drv_attr_show,
.store = drv_attr_store,
};
static void driver_release(struct kobject *kobj)
{
struct driver_private *drv_priv = to_driver(kobj);
pr_debug("driver: '%s': %s\n", kobject_name(kobj), __func__);
kfree(drv_priv);
}
static struct kobj_type driver_ktype = {
.sysfs_ops = &driver_sysfs_ops,
.release = driver_release,
};
/*
* sysfs bindings for buses
*/
static ssize_t bus_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct bus_attribute *bus_attr = to_bus_attr(attr);
struct subsys_private *subsys_priv = to_subsys_private(kobj);
ssize_t ret = 0;
if (bus_attr->show)
ret = bus_attr->show(subsys_priv->bus, buf);
return ret;
}
static ssize_t bus_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct bus_attribute *bus_attr = to_bus_attr(attr);
struct subsys_private *subsys_priv = to_subsys_private(kobj);
ssize_t ret = 0;
if (bus_attr->store)
ret = bus_attr->store(subsys_priv->bus, buf, count);
return ret;
}
static const struct sysfs_ops bus_sysfs_ops = {
.show = bus_attr_show,
.store = bus_attr_store,
};
int bus_create_file(struct bus_type *bus, struct bus_attribute *attr)
{
int error;
if (bus_get(bus)) {
error = sysfs_create_file(&bus->p->subsys.kobj, &attr->attr);
bus_put(bus);
} else
error = -EINVAL;
return error;
}
EXPORT_SYMBOL_GPL(bus_create_file);
void bus_remove_file(struct bus_type *bus, struct bus_attribute *attr)
{
if (bus_get(bus)) {
sysfs_remove_file(&bus->p->subsys.kobj, &attr->attr);
bus_put(bus);
}
}
EXPORT_SYMBOL_GPL(bus_remove_file);
static struct kobj_type bus_ktype = {
.sysfs_ops = &bus_sysfs_ops,
};
static int bus_uevent_filter(struct kset *kset, struct kobject *kobj)
{
struct kobj_type *ktype = get_ktype(kobj);
if (ktype == &bus_ktype)
return 1;
return 0;
}
static const struct kset_uevent_ops bus_uevent_ops = {
.filter = bus_uevent_filter,
};
static struct kset *bus_kset;
#ifdef CONFIG_HOTPLUG
/* Manually detach a device from its associated driver. */
static ssize_t driver_unbind(struct device_driver *drv,
const char *buf, size_t count)
{
struct bus_type *bus = bus_get(drv->bus);
struct device *dev;
int err = -ENODEV;
dev = bus_find_device_by_name(bus, NULL, buf);
if (dev && dev->driver == drv) {
if (dev->parent) /* Needed for USB */
device_lock(dev->parent);
device_release_driver(dev);
if (dev->parent)
device_unlock(dev->parent);
err = count;
}
put_device(dev);
bus_put(bus);
return err;
}
static DRIVER_ATTR(unbind, S_IWUSR, NULL, driver_unbind);
/*
* Manually attach a device to a driver.
* Note: the driver must want to bind to the device,
* it is not possible to override the driver's id table.
*/
static ssize_t driver_bind(struct device_driver *drv,
const char *buf, size_t count)
{
struct bus_type *bus = bus_get(drv->bus);
struct device *dev;
int err = -ENODEV;
dev = bus_find_device_by_name(bus, NULL, buf);
if (dev && dev->driver == NULL && driver_match_device(drv, dev)) {
if (dev->parent) /* Needed for USB */
device_lock(dev->parent);
device_lock(dev);
err = driver_probe_device(drv, dev);
device_unlock(dev);
if (dev->parent)
device_unlock(dev->parent);
if (err > 0) {
/* success */
err = count;
} else if (err == 0) {
/* driver didn't accept device */
err = -ENODEV;
}
}
put_device(dev);
bus_put(bus);
return err;
}
static DRIVER_ATTR(bind, S_IWUSR, NULL, driver_bind);
static ssize_t show_drivers_autoprobe(struct bus_type *bus, char *buf)
{
return sprintf(buf, "%d\n", bus->p->drivers_autoprobe);
}
static ssize_t store_drivers_autoprobe(struct bus_type *bus,
const char *buf, size_t count)
{
if (buf[0] == '0')
bus->p->drivers_autoprobe = 0;
else
bus->p->drivers_autoprobe = 1;
return count;
}
static ssize_t store_drivers_probe(struct bus_type *bus,
const char *buf, size_t count)
{
struct device *dev;
dev = bus_find_device_by_name(bus, NULL, buf);
if (!dev)
return -ENODEV;
if (bus_rescan_devices_helper(dev, NULL) != 0)
return -EINVAL;
return count;
}
#endif
static struct device *next_device(struct klist_iter *i)
{
struct klist_node *n = klist_next(i);
struct device *dev = NULL;
struct device_private *dev_prv;
if (n) {
dev_prv = to_device_private_bus(n);
dev = dev_prv->device;
}
return dev;
}
/**
* bus_for_each_dev - device iterator.
* @bus: bus type.
* @start: device to start iterating from.
* @data: data for the callback.
* @fn: function to be called for each device.
*
* Iterate over @bus's list of devices, and call @fn for each,
* passing it @data. If @start is not NULL, we use that device to
* begin iterating from.
*
* We check the return of @fn each time. If it returns anything
* other than 0, we break out and return that value.
*
* NOTE: The device that returns a non-zero value is not retained
* in any way, nor is its refcount incremented. If the caller needs
* to retain this data, it should do so, and increment the reference
* count in the supplied callback.
*/
int bus_for_each_dev(struct bus_type *bus, struct device *start,
void *data, int (*fn)(struct device *, void *))
{
struct klist_iter i;
struct device *dev;
int error = 0;
if (!bus)
return -EINVAL;
klist_iter_init_node(&bus->p->klist_devices, &i,
(start ? &start->p->knode_bus : NULL));
while ((dev = next_device(&i)) && !error)
error = fn(dev, data);
klist_iter_exit(&i);
return error;
}
EXPORT_SYMBOL_GPL(bus_for_each_dev);
/**
* bus_find_device - device iterator for locating a particular device.
* @bus: bus type
* @start: Device to begin with
* @data: Data to pass to match function
* @match: Callback function to check device
*
* This is similar to the bus_for_each_dev() function above, but it
* returns a reference to a device that is 'found' for later use, as
* determined by the @match callback.
*
* The callback should return 0 if the device doesn't match and non-zero
* if it does. If the callback returns non-zero, this function will
* return to the caller and not iterate over any more devices.
*/
struct device *bus_find_device(struct bus_type *bus,
struct device *start, void *data,
int (*match)(struct device *dev, void *data))
{
struct klist_iter i;
struct device *dev;
if (!bus)
return NULL;
klist_iter_init_node(&bus->p->klist_devices, &i,
(start ? &start->p->knode_bus : NULL));
while ((dev = next_device(&i)))
if (match(dev, data) && get_device(dev))
break;
klist_iter_exit(&i);
return dev;
}
EXPORT_SYMBOL_GPL(bus_find_device);
static int match_name(struct device *dev, void *data)
{
const char *name = data;
return sysfs_streq(name, dev_name(dev));
}
/**
* bus_find_device_by_name - device iterator for locating a particular device of a specific name
* @bus: bus type
* @start: Device to begin with
* @name: name of the device to match
*
* This is similar to the bus_find_device() function above, but it handles
* searching by a name automatically, no need to write another strcmp matching
* function.
*/
struct device *bus_find_device_by_name(struct bus_type *bus,
struct device *start, const char *name)
{
return bus_find_device(bus, start, (void *)name, match_name);
}
EXPORT_SYMBOL_GPL(bus_find_device_by_name);
static struct device_driver *next_driver(struct klist_iter *i)
{
struct klist_node *n = klist_next(i);
struct driver_private *drv_priv;
if (n) {
drv_priv = container_of(n, struct driver_private, knode_bus);
return drv_priv->driver;
}
return NULL;
}
/**
* bus_for_each_drv - driver iterator
* @bus: bus we're dealing with.
* @start: driver to start iterating on.
* @data: data to pass to the callback.
* @fn: function to call for each driver.
*
* This is nearly identical to the device iterator above.
* We iterate over each driver that belongs to @bus, and call
* @fn for each. If @fn returns anything but 0, we break out
* and return it. If @start is not NULL, we use it as the head
* of the list.
*
* NOTE: we don't return the driver that returns a non-zero
* value, nor do we leave the reference count incremented for that
* driver. If the caller needs to know that info, it must set it
* in the callback. It must also be sure to increment the refcount
* so it doesn't disappear before returning to the caller.
*/
int bus_for_each_drv(struct bus_type *bus, struct device_driver *start,
void *data, int (*fn)(struct device_driver *, void *))
{
struct klist_iter i;
struct device_driver *drv;
int error = 0;
if (!bus)
return -EINVAL;
klist_iter_init_node(&bus->p->klist_drivers, &i,
start ? &start->p->knode_bus : NULL);
while ((drv = next_driver(&i)) && !error)
error = fn(drv, data);
klist_iter_exit(&i);
return error;
}
EXPORT_SYMBOL_GPL(bus_for_each_drv);
static int device_add_attrs(struct bus_type *bus, struct device *dev)
{
int error = 0;
int i;
if (!bus->dev_attrs)
return 0;
for (i = 0; attr_name(bus->dev_attrs[i]); i++) {
error = device_create_file(dev, &bus->dev_attrs[i]);
if (error) {
while (--i >= 0)
device_remove_file(dev, &bus->dev_attrs[i]);
break;
}
}
return error;
}
static void device_remove_attrs(struct bus_type *bus, struct device *dev)
{
int i;
if (bus->dev_attrs) {
for (i = 0; attr_name(bus->dev_attrs[i]); i++)
device_remove_file(dev, &bus->dev_attrs[i]);
}
}
/**
* bus_add_device - add device to bus
* @dev: device being added
*
* - Add device's bus attributes.
* - Create links to device's bus.
* - Add the device to its bus's list of devices.
*/
int bus_add_device(struct device *dev)
{
struct bus_type *bus = bus_get(dev->bus);
int error = 0;
if (bus) {
pr_debug("bus: '%s': add device %s\n", bus->name, dev_name(dev));
error = device_add_attrs(bus, dev);
if (error)
goto out_put;
error = sysfs_create_link(&bus->p->devices_kset->kobj,
&dev->kobj, dev_name(dev));
if (error)
goto out_id;
error = sysfs_create_link(&dev->kobj,
&dev->bus->p->subsys.kobj, "subsystem");
if (error)
goto out_subsys;
klist_add_tail(&dev->p->knode_bus, &bus->p->klist_devices);
}
return 0;
out_subsys:
sysfs_remove_link(&bus->p->devices_kset->kobj, dev_name(dev));
out_id:
device_remove_attrs(bus, dev);
out_put:
bus_put(dev->bus);
return error;
}
/**
* bus_probe_device - probe drivers for a new device
* @dev: device to probe
*
* - Automatically probe for a driver if the bus allows it.
*/
void bus_probe_device(struct device *dev)
{
struct bus_type *bus = dev->bus;
int ret;
if (bus && bus->p->drivers_autoprobe) {
ret = device_attach(dev);
WARN_ON(ret < 0);
}
}
/**
* bus_remove_device - remove device from bus
* @dev: device to be removed
*
* - Remove symlink from bus's directory.
* - Delete device from bus's list.
* - Detach from its driver.
* - Drop reference taken in bus_add_device().
*/
void bus_remove_device(struct device *dev)
{
if (dev->bus) {
sysfs_remove_link(&dev->kobj, "subsystem");
sysfs_remove_link(&dev->bus->p->devices_kset->kobj,
dev_name(dev));
device_remove_attrs(dev->bus, dev);
if (klist_node_attached(&dev->p->knode_bus))
klist_del(&dev->p->knode_bus);
pr_debug("bus: '%s': remove device %s\n",
dev->bus->name, dev_name(dev));
device_release_driver(dev);
bus_put(dev->bus);
}
}
static int driver_add_attrs(struct bus_type *bus, struct device_driver *drv)
{
int error = 0;
int i;
if (bus->drv_attrs) {
for (i = 0; attr_name(bus->drv_attrs[i]); i++) {
error = driver_create_file(drv, &bus->drv_attrs[i]);
if (error)
goto err;
}
}
done:
return error;
err:
while (--i >= 0)
driver_remove_file(drv, &bus->drv_attrs[i]);
goto done;
}
static void driver_remove_attrs(struct bus_type *bus,
struct device_driver *drv)
{
int i;
if (bus->drv_attrs) {
for (i = 0; attr_name(bus->drv_attrs[i]); i++)
driver_remove_file(drv, &bus->drv_attrs[i]);
}
}
#ifdef CONFIG_HOTPLUG
/*
* Thanks to drivers making their tables __devinit, we can't allow manual
* bind and unbind from userspace unless CONFIG_HOTPLUG is enabled.
*/
static int __must_check add_bind_files(struct device_driver *drv)
{
int ret;
ret = driver_create_file(drv, &driver_attr_unbind);
if (ret == 0) {
ret = driver_create_file(drv, &driver_attr_bind);
if (ret)
driver_remove_file(drv, &driver_attr_unbind);
}
return ret;
}
static void remove_bind_files(struct device_driver *drv)
{
driver_remove_file(drv, &driver_attr_bind);
driver_remove_file(drv, &driver_attr_unbind);
}
static BUS_ATTR(drivers_probe, S_IWUSR, NULL, store_drivers_probe);
static BUS_ATTR(drivers_autoprobe, S_IWUSR | S_IRUGO,
show_drivers_autoprobe, store_drivers_autoprobe);
static int add_probe_files(struct bus_type *bus)
{
int retval;
retval = bus_create_file(bus, &bus_attr_drivers_probe);
if (retval)
goto out;
retval = bus_create_file(bus, &bus_attr_drivers_autoprobe);
if (retval)
bus_remove_file(bus, &bus_attr_drivers_probe);
out:
return retval;
}
static void remove_probe_files(struct bus_type *bus)
{
bus_remove_file(bus, &bus_attr_drivers_autoprobe);
bus_remove_file(bus, &bus_attr_drivers_probe);
}
#else
static inline int add_bind_files(struct device_driver *drv) { return 0; }
static inline void remove_bind_files(struct device_driver *drv) {}
static inline int add_probe_files(struct bus_type *bus) { return 0; }
static inline void remove_probe_files(struct bus_type *bus) {}
#endif
static ssize_t driver_uevent_store(struct device_driver *drv,
const char *buf, size_t count)
{
enum kobject_action action;
if (kobject_action_type(buf, count, &action) == 0)
kobject_uevent(&drv->p->kobj, action);
return count;
}
static DRIVER_ATTR(uevent, S_IWUSR, NULL, driver_uevent_store);
/**
* bus_add_driver - Add a driver to the bus.
* @drv: driver.
*/
int bus_add_driver(struct device_driver *drv)
{
struct bus_type *bus;
struct driver_private *priv;
int error = 0;
bus = bus_get(drv->bus);
if (!bus)
return -EINVAL;
pr_debug("bus: '%s': add driver %s\n", bus->name, drv->name);
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv) {
error = -ENOMEM;
goto out_put_bus;
}
klist_init(&priv->klist_devices, NULL, NULL);
priv->driver = drv;
drv->p = priv;
priv->kobj.kset = bus->p->drivers_kset;
error = kobject_init_and_add(&priv->kobj, &driver_ktype, NULL,
"%s", drv->name);
if (error)
goto out_unregister;
if (drv->bus->p->drivers_autoprobe) {
error = driver_attach(drv);
if (error)
goto out_unregister;
}
klist_add_tail(&priv->knode_bus, &bus->p->klist_drivers);
module_add_driver(drv->owner, drv);
error = driver_create_file(drv, &driver_attr_uevent);
if (error) {
printk(KERN_ERR "%s: uevent attr (%s) failed\n",
__func__, drv->name);
}
error = driver_add_attrs(bus, drv);
if (error) {
/* How the hell do we get out of this pickle? Give up */
printk(KERN_ERR "%s: driver_add_attrs(%s) failed\n",
__func__, drv->name);
}
if (!drv->suppress_bind_attrs) {
error = add_bind_files(drv);
if (error) {
/* Ditto */
printk(KERN_ERR "%s: add_bind_files(%s) failed\n",
__func__, drv->name);
}
}
kobject_uevent(&priv->kobj, KOBJ_ADD);
return 0;
out_unregister:
kobject_put(&priv->kobj);
kfree(drv->p);
drv->p = NULL;
out_put_bus:
bus_put(bus);
return error;
}
/**
* bus_remove_driver - delete driver from bus's knowledge.
* @drv: driver.
*
* Detach the driver from the devices it controls, and remove
* it from its bus's list of drivers. Finally, we drop the reference
* to the bus we took in bus_add_driver().
*/
void bus_remove_driver(struct device_driver *drv)
{
if (!drv->bus)
return;
if (!drv->suppress_bind_attrs)
remove_bind_files(drv);
driver_remove_attrs(drv->bus, drv);
driver_remove_file(drv, &driver_attr_uevent);
klist_remove(&drv->p->knode_bus);
pr_debug("bus: '%s': remove driver %s\n", drv->bus->name, drv->name);
driver_detach(drv);
module_remove_driver(drv);
kobject_put(&drv->p->kobj);
bus_put(drv->bus);
}
/* Helper for bus_rescan_devices's iter */
static int __must_check bus_rescan_devices_helper(struct device *dev,
void *data)
{
int ret = 0;
if (!dev->driver) {
if (dev->parent) /* Needed for USB */
device_lock(dev->parent);
ret = device_attach(dev);
if (dev->parent)
device_unlock(dev->parent);
}
return ret < 0 ? ret : 0;
}
/**
* bus_rescan_devices - rescan devices on the bus for possible drivers
* @bus: the bus to scan.
*
* This function will look for devices on the bus with no driver
* attached and rescan it against existing drivers to see if it matches
* any by calling device_attach() for the unbound devices.
*/
int bus_rescan_devices(struct bus_type *bus)
{
return bus_for_each_dev(bus, NULL, NULL, bus_rescan_devices_helper);
}
EXPORT_SYMBOL_GPL(bus_rescan_devices);
/**
* device_reprobe - remove driver for a device and probe for a new driver
* @dev: the device to reprobe
*
* This function detaches the attached driver (if any) for the given
* device and restarts the driver probing process. It is intended
* to use if probing criteria changed during a devices lifetime and
* driver attachment should change accordingly.
*/
int device_reprobe(struct device *dev)
{
if (dev->driver) {
if (dev->parent) /* Needed for USB */
device_lock(dev->parent);
device_release_driver(dev);
if (dev->parent)
device_unlock(dev->parent);
}
return bus_rescan_devices_helper(dev, NULL);
}
EXPORT_SYMBOL_GPL(device_reprobe);
/**
* find_bus - locate bus by name.
* @name: name of bus.
*
* Call kset_find_obj() to iterate over list of buses to
* find a bus by name. Return bus if found.
*
* Note that kset_find_obj increments bus' reference count.
*/
#if 0
struct bus_type *find_bus(char *name)
{
struct kobject *k = kset_find_obj(bus_kset, name);
return k ? to_bus(k) : NULL;
}
#endif /* 0 */
/**
* bus_add_attrs - Add default attributes for this bus.
* @bus: Bus that has just been registered.
*/
static int bus_add_attrs(struct bus_type *bus)
{
int error = 0;
int i;
if (bus->bus_attrs) {
for (i = 0; attr_name(bus->bus_attrs[i]); i++) {
error = bus_create_file(bus, &bus->bus_attrs[i]);
if (error)
goto err;
}
}
done:
return error;
err:
while (--i >= 0)
bus_remove_file(bus, &bus->bus_attrs[i]);
goto done;
}
static void bus_remove_attrs(struct bus_type *bus)
{
int i;
if (bus->bus_attrs) {
for (i = 0; attr_name(bus->bus_attrs[i]); i++)
bus_remove_file(bus, &bus->bus_attrs[i]);
}
}
static void klist_devices_get(struct klist_node *n)
{
struct device_private *dev_prv = to_device_private_bus(n);
struct device *dev = dev_prv->device;
get_device(dev);
}
static void klist_devices_put(struct klist_node *n)
{
struct device_private *dev_prv = to_device_private_bus(n);
struct device *dev = dev_prv->device;
put_device(dev);
}
static ssize_t bus_uevent_store(struct bus_type *bus,
const char *buf, size_t count)
{
enum kobject_action action;
if (kobject_action_type(buf, count, &action) == 0)
kobject_uevent(&bus->p->subsys.kobj, action);
return count;
}
static BUS_ATTR(uevent, S_IWUSR, NULL, bus_uevent_store);
/**
* bus_register - register a bus with the system.
* @bus: bus.
*
* Once we have that, we registered the bus with the kobject
* infrastructure, then register the children subsystems it has:
* the devices and drivers that belong to the bus.
*/
int bus_register(struct bus_type *bus)
{
int retval;
struct subsys_private *priv;
priv = kzalloc(sizeof(struct subsys_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->bus = bus;
bus->p = priv;
BLOCKING_INIT_NOTIFIER_HEAD(&priv->bus_notifier);
retval = kobject_set_name(&priv->subsys.kobj, "%s", bus->name);
if (retval)
goto out;
priv->subsys.kobj.kset = bus_kset;
priv->subsys.kobj.ktype = &bus_ktype;
priv->drivers_autoprobe = 1;
retval = kset_register(&priv->subsys);
if (retval)
goto out;
retval = bus_create_file(bus, &bus_attr_uevent);
if (retval)
goto bus_uevent_fail;
priv->devices_kset = kset_create_and_add("devices", NULL,
&priv->subsys.kobj);
if (!priv->devices_kset) {
retval = -ENOMEM;
goto bus_devices_fail;
}
priv->drivers_kset = kset_create_and_add("drivers", NULL,
&priv->subsys.kobj);
if (!priv->drivers_kset) {
retval = -ENOMEM;
goto bus_drivers_fail;
}
klist_init(&priv->klist_devices, klist_devices_get, klist_devices_put);
klist_init(&priv->klist_drivers, NULL, NULL);
retval = add_probe_files(bus);
if (retval)
goto bus_probe_files_fail;
retval = bus_add_attrs(bus);
if (retval)
goto bus_attrs_fail;
pr_debug("bus: '%s': registered\n", bus->name);
return 0;
bus_attrs_fail:
remove_probe_files(bus);
bus_probe_files_fail:
kset_unregister(bus->p->drivers_kset);
bus_drivers_fail:
kset_unregister(bus->p->devices_kset);
bus_devices_fail:
bus_remove_file(bus, &bus_attr_uevent);
bus_uevent_fail:
kset_unregister(&bus->p->subsys);
out:
kfree(bus->p);
bus->p = NULL;
return retval;
}
EXPORT_SYMBOL_GPL(bus_register);
/**
* bus_unregister - remove a bus from the system
* @bus: bus.
*
* Unregister the child subsystems and the bus itself.
* Finally, we call bus_put() to release the refcount
*/
void bus_unregister(struct bus_type *bus)
{
pr_debug("bus: '%s': unregistering\n", bus->name);
bus_remove_attrs(bus);
remove_probe_files(bus);
kset_unregister(bus->p->drivers_kset);
kset_unregister(bus->p->devices_kset);
bus_remove_file(bus, &bus_attr_uevent);
kset_unregister(&bus->p->subsys);
kfree(bus->p);
bus->p = NULL;
}
EXPORT_SYMBOL_GPL(bus_unregister);
int bus_register_notifier(struct bus_type *bus, struct notifier_block *nb)
{
return blocking_notifier_chain_register(&bus->p->bus_notifier, nb);
}
EXPORT_SYMBOL_GPL(bus_register_notifier);
int bus_unregister_notifier(struct bus_type *bus, struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(&bus->p->bus_notifier, nb);
}
EXPORT_SYMBOL_GPL(bus_unregister_notifier);
struct kset *bus_get_kset(struct bus_type *bus)
{
return &bus->p->subsys;
}
EXPORT_SYMBOL_GPL(bus_get_kset);
struct klist *bus_get_device_klist(struct bus_type *bus)
{
return &bus->p->klist_devices;
}
EXPORT_SYMBOL_GPL(bus_get_device_klist);
/*
* Yes, this forcibly breaks the klist abstraction temporarily. It
* just wants to sort the klist, not change reference counts and
* take/drop locks rapidly in the process. It does all this while
* holding the lock for the list, so objects can't otherwise be
* added/removed while we're swizzling.
*/
static void device_insertion_sort_klist(struct device *a, struct list_head *list,
int (*compare)(const struct device *a,
const struct device *b))
{
struct list_head *pos;
struct klist_node *n;
struct device_private *dev_prv;
struct device *b;
list_for_each(pos, list) {
n = container_of(pos, struct klist_node, n_node);
dev_prv = to_device_private_bus(n);
b = dev_prv->device;
if (compare(a, b) <= 0) {
list_move_tail(&a->p->knode_bus.n_node,
&b->p->knode_bus.n_node);
return;
}
}
list_move_tail(&a->p->knode_bus.n_node, list);
}
void bus_sort_breadthfirst(struct bus_type *bus,
int (*compare)(const struct device *a,
const struct device *b))
{
LIST_HEAD(sorted_devices);
struct list_head *pos, *tmp;
struct klist_node *n;
struct device_private *dev_prv;
struct device *dev;
struct klist *device_klist;
device_klist = bus_get_device_klist(bus);
spin_lock(&device_klist->k_lock);
list_for_each_safe(pos, tmp, &device_klist->k_list) {
n = container_of(pos, struct klist_node, n_node);
dev_prv = to_device_private_bus(n);
dev = dev_prv->device;
device_insertion_sort_klist(dev, &sorted_devices, compare);
}
list_splice(&sorted_devices, &device_klist->k_list);
spin_unlock(&device_klist->k_lock);
}
EXPORT_SYMBOL_GPL(bus_sort_breadthfirst);
int __init buses_init(void)
{
bus_kset = kset_create_and_add("bus", &bus_uevent_ops, NULL);
if (!bus_kset)
return -ENOMEM;
return 0;
}
| gpl-2.0 |
TheCollective/android_kernel_samsung_i927 | arch/arm/mach-tcc8k/board-tcc8000-sdk.c | 2825 | 1912 | /*
* Copyright (C) 2009 Hans J. Koch <hjk@linutronix.de>
*
* 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/delay.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/time.h>
#include <mach/clock.h>
#include <mach/tcc-nand.h>
#include <mach/tcc8k-regs.h>
#include "common.h"
#define XI_FREQUENCY 12000000
#define XTI_FREQUENCY 32768
#ifdef CONFIG_MTD_NAND_TCC
/* NAND */
static struct tcc_nand_platform_data tcc8k_sdk_nand_data = {
.width = 1,
.hw_ecc = 0,
};
#endif
static void __init tcc8k_init(void)
{
#ifdef CONFIG_MTD_NAND_TCC
tcc_nand_device.dev.platform_data = &tcc8k_sdk_nand_data;
platform_device_register(&tcc_nand_device);
#endif
}
static void __init tcc8k_init_timer(void)
{
tcc_clocks_init(XI_FREQUENCY, XTI_FREQUENCY);
}
static struct sys_timer tcc8k_timer = {
.init = tcc8k_init_timer,
};
static void __init tcc8k_map_io(void)
{
tcc8k_map_common_io();
/* set PLL0 clock to 96MHz, adapt UART0 divisor */
__raw_writel(0x00026003, CKC_BASE + PLL0CFG_OFFS);
__raw_writel(0x10000001, CKC_BASE + ACLKUART0_OFFS);
/* set PLL1 clock to 192MHz */
__raw_writel(0x00016003, CKC_BASE + PLL1CFG_OFFS);
/* set PLL2 clock to 48MHz */
__raw_writel(0x00036003, CKC_BASE + PLL2CFG_OFFS);
/* with CPU freq higher than 150 MHz, need extra DTCM wait */
__raw_writel(0x00000001, SCFG_BASE + DTCMWAIT_OFFS);
/* PLL locking time as specified */
udelay(300);
}
MACHINE_START(TCC8000_SDK, "Telechips TCC8000-SDK Demo Board")
.boot_params = PLAT_PHYS_OFFSET + 0x00000100,
.map_io = tcc8k_map_io,
.init_irq = tcc8k_init_irq,
.init_machine = tcc8k_init,
.timer = &tcc8k_timer,
MACHINE_END
| gpl-2.0 |
wolverine2k/htc7x30-3.0 | arch/arm/mach-s5pv210/mach-torbreck.c | 2825 | 3393 | /* linux/arch/arm/mach-s5pv210/mach-torbreck.c
*
* Copyright (c) 2010 aESOP Community
* http://www.aesop.or.kr/
*
* 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/i2c.h>
#include <linux/init.h>
#include <linux/serial_core.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <plat/regs-serial.h>
#include <plat/s5pv210.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/iic.h>
#include <plat/s5p-time.h>
/* Following are default values for UCON, ULCON and UFCON UART registers */
#define TORBRECK_UCON_DEFAULT (S3C2410_UCON_TXILEVEL | \
S3C2410_UCON_RXILEVEL | \
S3C2410_UCON_TXIRQMODE | \
S3C2410_UCON_RXIRQMODE | \
S3C2410_UCON_RXFIFO_TOI | \
S3C2443_UCON_RXERR_IRQEN)
#define TORBRECK_ULCON_DEFAULT S3C2410_LCON_CS8
#define TORBRECK_UFCON_DEFAULT (S3C2410_UFCON_FIFOMODE | \
S5PV210_UFCON_TXTRIG4 | \
S5PV210_UFCON_RXTRIG4)
static struct s3c2410_uartcfg torbreck_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = TORBRECK_UCON_DEFAULT,
.ulcon = TORBRECK_ULCON_DEFAULT,
.ufcon = TORBRECK_UFCON_DEFAULT,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = TORBRECK_UCON_DEFAULT,
.ulcon = TORBRECK_ULCON_DEFAULT,
.ufcon = TORBRECK_UFCON_DEFAULT,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = TORBRECK_UCON_DEFAULT,
.ulcon = TORBRECK_ULCON_DEFAULT,
.ufcon = TORBRECK_UFCON_DEFAULT,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = TORBRECK_UCON_DEFAULT,
.ulcon = TORBRECK_ULCON_DEFAULT,
.ufcon = TORBRECK_UFCON_DEFAULT,
},
};
static struct platform_device *torbreck_devices[] __initdata = {
&s5pv210_device_iis0,
&s3c_device_cfcon,
&s3c_device_hsmmc0,
&s3c_device_hsmmc1,
&s3c_device_hsmmc2,
&s3c_device_hsmmc3,
&s3c_device_i2c0,
&s3c_device_i2c1,
&s3c_device_i2c2,
&s3c_device_rtc,
&s3c_device_wdt,
};
static struct i2c_board_info torbreck_i2c_devs0[] __initdata = {
/* To Be Updated */
};
static struct i2c_board_info torbreck_i2c_devs1[] __initdata = {
/* To Be Updated */
};
static struct i2c_board_info torbreck_i2c_devs2[] __initdata = {
/* To Be Updated */
};
static void __init torbreck_map_io(void)
{
s5p_init_io(NULL, 0, S5P_VA_CHIPID);
s3c24xx_init_clocks(24000000);
s3c24xx_init_uarts(torbreck_uartcfgs, ARRAY_SIZE(torbreck_uartcfgs));
s5p_set_timer_source(S5P_PWM3, S5P_PWM4);
}
static void __init torbreck_machine_init(void)
{
s3c_i2c0_set_platdata(NULL);
s3c_i2c1_set_platdata(NULL);
s3c_i2c2_set_platdata(NULL);
i2c_register_board_info(0, torbreck_i2c_devs0,
ARRAY_SIZE(torbreck_i2c_devs0));
i2c_register_board_info(1, torbreck_i2c_devs1,
ARRAY_SIZE(torbreck_i2c_devs1));
i2c_register_board_info(2, torbreck_i2c_devs2,
ARRAY_SIZE(torbreck_i2c_devs2));
platform_add_devices(torbreck_devices, ARRAY_SIZE(torbreck_devices));
}
MACHINE_START(TORBRECK, "TORBRECK")
/* Maintainer: Hyunchul Ko <ghcstop@gmail.com> */
.boot_params = S5P_PA_SDRAM + 0x100,
.init_irq = s5pv210_init_irq,
.map_io = torbreck_map_io,
.init_machine = torbreck_machine_init,
.timer = &s5p_timer,
MACHINE_END
| gpl-2.0 |
Pafcholini/emotion_kernel_tw_p | drivers/input/misc/ad714x-i2c.c | 3081 | 2841 | /*
* AD714X CapTouch Programmable Controller driver (I2C bus)
*
* Copyright 2009-2011 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/input.h> /* BUS_I2C */
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/pm.h>
#include "ad714x.h"
#ifdef CONFIG_PM_SLEEP
static int ad714x_i2c_suspend(struct device *dev)
{
return ad714x_disable(i2c_get_clientdata(to_i2c_client(dev)));
}
static int ad714x_i2c_resume(struct device *dev)
{
return ad714x_enable(i2c_get_clientdata(to_i2c_client(dev)));
}
#endif
static SIMPLE_DEV_PM_OPS(ad714x_i2c_pm, ad714x_i2c_suspend, ad714x_i2c_resume);
static int ad714x_i2c_write(struct ad714x_chip *chip,
unsigned short reg, unsigned short data)
{
struct i2c_client *client = to_i2c_client(chip->dev);
int error;
chip->xfer_buf[0] = cpu_to_be16(reg);
chip->xfer_buf[1] = cpu_to_be16(data);
error = i2c_master_send(client, (u8 *)chip->xfer_buf,
2 * sizeof(*chip->xfer_buf));
if (unlikely(error < 0)) {
dev_err(&client->dev, "I2C write error: %d\n", error);
return error;
}
return 0;
}
static int ad714x_i2c_read(struct ad714x_chip *chip,
unsigned short reg, unsigned short *data, size_t len)
{
struct i2c_client *client = to_i2c_client(chip->dev);
int i;
int error;
chip->xfer_buf[0] = cpu_to_be16(reg);
error = i2c_master_send(client, (u8 *)chip->xfer_buf,
sizeof(*chip->xfer_buf));
if (error >= 0)
error = i2c_master_recv(client, (u8 *)chip->xfer_buf,
len * sizeof(*chip->xfer_buf));
if (unlikely(error < 0)) {
dev_err(&client->dev, "I2C read error: %d\n", error);
return error;
}
for (i = 0; i < len; i++)
data[i] = be16_to_cpu(chip->xfer_buf[i]);
return 0;
}
static int ad714x_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct ad714x_chip *chip;
chip = ad714x_probe(&client->dev, BUS_I2C, client->irq,
ad714x_i2c_read, ad714x_i2c_write);
if (IS_ERR(chip))
return PTR_ERR(chip);
i2c_set_clientdata(client, chip);
return 0;
}
static int ad714x_i2c_remove(struct i2c_client *client)
{
struct ad714x_chip *chip = i2c_get_clientdata(client);
ad714x_remove(chip);
return 0;
}
static const struct i2c_device_id ad714x_id[] = {
{ "ad7142_captouch", 0 },
{ "ad7143_captouch", 0 },
{ "ad7147_captouch", 0 },
{ "ad7147a_captouch", 0 },
{ "ad7148_captouch", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ad714x_id);
static struct i2c_driver ad714x_i2c_driver = {
.driver = {
.name = "ad714x_captouch",
.pm = &ad714x_i2c_pm,
},
.probe = ad714x_i2c_probe,
.remove = ad714x_i2c_remove,
.id_table = ad714x_id,
};
module_i2c_driver(ad714x_i2c_driver);
MODULE_DESCRIPTION("Analog Devices AD714X Capacitance Touch Sensor I2C Bus Driver");
MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
pec0ra/williams | fs/ext4/move_extent.c | 3081 | 41825 | /*
* Copyright (c) 2008,2009 NEC Software Tohoku, Ltd.
* Written by Takashi Sato <t-sato@yk.jp.nec.com>
* Akira Fujita <a-fujita@rs.jp.nec.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2.1 of the GNU Lesser General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/fs.h>
#include <linux/quotaops.h>
#include <linux/slab.h>
#include "ext4_jbd2.h"
#include "ext4.h"
/**
* get_ext_path - Find an extent path for designated logical block number.
*
* @inode: an inode which is searched
* @lblock: logical block number to find an extent path
* @path: pointer to an extent path pointer (for output)
*
* ext4_ext_find_extent wrapper. Return 0 on success, or a negative error value
* on failure.
*/
static inline int
get_ext_path(struct inode *inode, ext4_lblk_t lblock,
struct ext4_ext_path **path)
{
int ret = 0;
*path = ext4_ext_find_extent(inode, lblock, *path);
if (IS_ERR(*path)) {
ret = PTR_ERR(*path);
*path = NULL;
} else if ((*path)[ext_depth(inode)].p_ext == NULL)
ret = -ENODATA;
return ret;
}
/**
* copy_extent_status - Copy the extent's initialization status
*
* @src: an extent for getting initialize status
* @dest: an extent to be set the status
*/
static void
copy_extent_status(struct ext4_extent *src, struct ext4_extent *dest)
{
if (ext4_ext_is_uninitialized(src))
ext4_ext_mark_uninitialized(dest);
else
dest->ee_len = cpu_to_le16(ext4_ext_get_actual_len(dest));
}
/**
* mext_next_extent - Search for the next extent and set it to "extent"
*
* @inode: inode which is searched
* @path: this will obtain data for the next extent
* @extent: pointer to the next extent we have just gotten
*
* Search the next extent in the array of ext4_ext_path structure (@path)
* and set it to ext4_extent structure (@extent). In addition, the member of
* @path (->p_ext) also points the next extent. Return 0 on success, 1 if
* ext4_ext_path structure refers to the last extent, or a negative error
* value on failure.
*/
static int
mext_next_extent(struct inode *inode, struct ext4_ext_path *path,
struct ext4_extent **extent)
{
struct ext4_extent_header *eh;
int ppos, leaf_ppos = path->p_depth;
ppos = leaf_ppos;
if (EXT_LAST_EXTENT(path[ppos].p_hdr) > path[ppos].p_ext) {
/* leaf block */
*extent = ++path[ppos].p_ext;
path[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);
return 0;
}
while (--ppos >= 0) {
if (EXT_LAST_INDEX(path[ppos].p_hdr) >
path[ppos].p_idx) {
int cur_ppos = ppos;
/* index block */
path[ppos].p_idx++;
path[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);
if (path[ppos+1].p_bh)
brelse(path[ppos+1].p_bh);
path[ppos+1].p_bh =
sb_bread(inode->i_sb, path[ppos].p_block);
if (!path[ppos+1].p_bh)
return -EIO;
path[ppos+1].p_hdr =
ext_block_hdr(path[ppos+1].p_bh);
/* Halfway index block */
while (++cur_ppos < leaf_ppos) {
path[cur_ppos].p_idx =
EXT_FIRST_INDEX(path[cur_ppos].p_hdr);
path[cur_ppos].p_block =
ext4_idx_pblock(path[cur_ppos].p_idx);
if (path[cur_ppos+1].p_bh)
brelse(path[cur_ppos+1].p_bh);
path[cur_ppos+1].p_bh = sb_bread(inode->i_sb,
path[cur_ppos].p_block);
if (!path[cur_ppos+1].p_bh)
return -EIO;
path[cur_ppos+1].p_hdr =
ext_block_hdr(path[cur_ppos+1].p_bh);
}
path[leaf_ppos].p_ext = *extent = NULL;
eh = path[leaf_ppos].p_hdr;
if (le16_to_cpu(eh->eh_entries) == 0)
/* empty leaf is found */
return -ENODATA;
/* leaf block */
path[leaf_ppos].p_ext = *extent =
EXT_FIRST_EXTENT(path[leaf_ppos].p_hdr);
path[leaf_ppos].p_block =
ext4_ext_pblock(path[leaf_ppos].p_ext);
return 0;
}
}
/* We found the last extent */
return 1;
}
/**
* mext_check_null_inode - NULL check for two inodes
*
* If inode1 or inode2 is NULL, return -EIO. Otherwise, return 0.
*/
static int
mext_check_null_inode(struct inode *inode1, struct inode *inode2,
const char *function, unsigned int line)
{
int ret = 0;
if (inode1 == NULL) {
__ext4_error(inode2->i_sb, function, line,
"Both inodes should not be NULL: "
"inode1 NULL inode2 %lu", inode2->i_ino);
ret = -EIO;
} else if (inode2 == NULL) {
__ext4_error(inode1->i_sb, function, line,
"Both inodes should not be NULL: "
"inode1 %lu inode2 NULL", inode1->i_ino);
ret = -EIO;
}
return ret;
}
/**
* double_down_write_data_sem - Acquire two inodes' write lock of i_data_sem
*
* @orig_inode: original inode structure
* @donor_inode: donor inode structure
* Acquire write lock of i_data_sem of the two inodes (orig and donor) by
* i_ino order.
*/
static void
double_down_write_data_sem(struct inode *orig_inode, struct inode *donor_inode)
{
struct inode *first = orig_inode, *second = donor_inode;
/*
* Use the inode number to provide the stable locking order instead
* of its address, because the C language doesn't guarantee you can
* compare pointers that don't come from the same array.
*/
if (donor_inode->i_ino < orig_inode->i_ino) {
first = donor_inode;
second = orig_inode;
}
down_write(&EXT4_I(first)->i_data_sem);
down_write_nested(&EXT4_I(second)->i_data_sem, SINGLE_DEPTH_NESTING);
}
/**
* double_up_write_data_sem - Release two inodes' write lock of i_data_sem
*
* @orig_inode: original inode structure to be released its lock first
* @donor_inode: donor inode structure to be released its lock second
* Release write lock of i_data_sem of two inodes (orig and donor).
*/
static void
double_up_write_data_sem(struct inode *orig_inode, struct inode *donor_inode)
{
up_write(&EXT4_I(orig_inode)->i_data_sem);
up_write(&EXT4_I(donor_inode)->i_data_sem);
}
/**
* mext_insert_across_blocks - Insert extents across leaf block
*
* @handle: journal handle
* @orig_inode: original inode
* @o_start: first original extent to be changed
* @o_end: last original extent to be changed
* @start_ext: first new extent to be inserted
* @new_ext: middle of new extent to be inserted
* @end_ext: last new extent to be inserted
*
* Allocate a new leaf block and insert extents into it. Return 0 on success,
* or a negative error value on failure.
*/
static int
mext_insert_across_blocks(handle_t *handle, struct inode *orig_inode,
struct ext4_extent *o_start, struct ext4_extent *o_end,
struct ext4_extent *start_ext, struct ext4_extent *new_ext,
struct ext4_extent *end_ext)
{
struct ext4_ext_path *orig_path = NULL;
ext4_lblk_t eblock = 0;
int new_flag = 0;
int end_flag = 0;
int err = 0;
if (start_ext->ee_len && new_ext->ee_len && end_ext->ee_len) {
if (o_start == o_end) {
/* start_ext new_ext end_ext
* donor |---------|-----------|--------|
* orig |------------------------------|
*/
end_flag = 1;
} else {
/* start_ext new_ext end_ext
* donor |---------|----------|---------|
* orig |---------------|--------------|
*/
o_end->ee_block = end_ext->ee_block;
o_end->ee_len = end_ext->ee_len;
ext4_ext_store_pblock(o_end, ext4_ext_pblock(end_ext));
}
o_start->ee_len = start_ext->ee_len;
eblock = le32_to_cpu(start_ext->ee_block);
new_flag = 1;
} else if (start_ext->ee_len && new_ext->ee_len &&
!end_ext->ee_len && o_start == o_end) {
/* start_ext new_ext
* donor |--------------|---------------|
* orig |------------------------------|
*/
o_start->ee_len = start_ext->ee_len;
eblock = le32_to_cpu(start_ext->ee_block);
new_flag = 1;
} else if (!start_ext->ee_len && new_ext->ee_len &&
end_ext->ee_len && o_start == o_end) {
/* new_ext end_ext
* donor |--------------|---------------|
* orig |------------------------------|
*/
o_end->ee_block = end_ext->ee_block;
o_end->ee_len = end_ext->ee_len;
ext4_ext_store_pblock(o_end, ext4_ext_pblock(end_ext));
/*
* Set 0 to the extent block if new_ext was
* the first block.
*/
if (new_ext->ee_block)
eblock = le32_to_cpu(new_ext->ee_block);
new_flag = 1;
} else {
ext4_debug("ext4 move extent: Unexpected insert case\n");
return -EIO;
}
if (new_flag) {
err = get_ext_path(orig_inode, eblock, &orig_path);
if (err)
goto out;
if (ext4_ext_insert_extent(handle, orig_inode,
orig_path, new_ext, 0))
goto out;
}
if (end_flag) {
err = get_ext_path(orig_inode,
le32_to_cpu(end_ext->ee_block) - 1, &orig_path);
if (err)
goto out;
if (ext4_ext_insert_extent(handle, orig_inode,
orig_path, end_ext, 0))
goto out;
}
out:
if (orig_path) {
ext4_ext_drop_refs(orig_path);
kfree(orig_path);
}
return err;
}
/**
* mext_insert_inside_block - Insert new extent to the extent block
*
* @o_start: first original extent to be moved
* @o_end: last original extent to be moved
* @start_ext: first new extent to be inserted
* @new_ext: middle of new extent to be inserted
* @end_ext: last new extent to be inserted
* @eh: extent header of target leaf block
* @range_to_move: used to decide how to insert extent
*
* Insert extents into the leaf block. The extent (@o_start) is overwritten
* by inserted extents.
*/
static void
mext_insert_inside_block(struct ext4_extent *o_start,
struct ext4_extent *o_end,
struct ext4_extent *start_ext,
struct ext4_extent *new_ext,
struct ext4_extent *end_ext,
struct ext4_extent_header *eh,
int range_to_move)
{
int i = 0;
unsigned long len;
/* Move the existing extents */
if (range_to_move && o_end < EXT_LAST_EXTENT(eh)) {
len = (unsigned long)(EXT_LAST_EXTENT(eh) + 1) -
(unsigned long)(o_end + 1);
memmove(o_end + 1 + range_to_move, o_end + 1, len);
}
/* Insert start entry */
if (start_ext->ee_len)
o_start[i++].ee_len = start_ext->ee_len;
/* Insert new entry */
if (new_ext->ee_len) {
o_start[i] = *new_ext;
ext4_ext_store_pblock(&o_start[i++], ext4_ext_pblock(new_ext));
}
/* Insert end entry */
if (end_ext->ee_len)
o_start[i] = *end_ext;
/* Increment the total entries counter on the extent block */
le16_add_cpu(&eh->eh_entries, range_to_move);
}
/**
* mext_insert_extents - Insert new extent
*
* @handle: journal handle
* @orig_inode: original inode
* @orig_path: path indicates first extent to be changed
* @o_start: first original extent to be changed
* @o_end: last original extent to be changed
* @start_ext: first new extent to be inserted
* @new_ext: middle of new extent to be inserted
* @end_ext: last new extent to be inserted
*
* Call the function to insert extents. If we cannot add more extents into
* the leaf block, we call mext_insert_across_blocks() to create a
* new leaf block. Otherwise call mext_insert_inside_block(). Return 0
* on success, or a negative error value on failure.
*/
static int
mext_insert_extents(handle_t *handle, struct inode *orig_inode,
struct ext4_ext_path *orig_path,
struct ext4_extent *o_start,
struct ext4_extent *o_end,
struct ext4_extent *start_ext,
struct ext4_extent *new_ext,
struct ext4_extent *end_ext)
{
struct ext4_extent_header *eh;
unsigned long need_slots, slots_range;
int range_to_move, depth, ret;
/*
* The extents need to be inserted
* start_extent + new_extent + end_extent.
*/
need_slots = (start_ext->ee_len ? 1 : 0) + (end_ext->ee_len ? 1 : 0) +
(new_ext->ee_len ? 1 : 0);
/* The number of slots between start and end */
slots_range = ((unsigned long)(o_end + 1) - (unsigned long)o_start + 1)
/ sizeof(struct ext4_extent);
/* Range to move the end of extent */
range_to_move = need_slots - slots_range;
depth = orig_path->p_depth;
orig_path += depth;
eh = orig_path->p_hdr;
if (depth) {
/* Register to journal */
ret = ext4_journal_get_write_access(handle, orig_path->p_bh);
if (ret)
return ret;
}
/* Expansion */
if (range_to_move > 0 &&
(range_to_move > le16_to_cpu(eh->eh_max)
- le16_to_cpu(eh->eh_entries))) {
ret = mext_insert_across_blocks(handle, orig_inode, o_start,
o_end, start_ext, new_ext, end_ext);
if (ret < 0)
return ret;
} else
mext_insert_inside_block(o_start, o_end, start_ext, new_ext,
end_ext, eh, range_to_move);
if (depth) {
ret = ext4_handle_dirty_metadata(handle, orig_inode,
orig_path->p_bh);
if (ret)
return ret;
} else {
ret = ext4_mark_inode_dirty(handle, orig_inode);
if (ret < 0)
return ret;
}
return 0;
}
/**
* mext_leaf_block - Move one leaf extent block into the inode.
*
* @handle: journal handle
* @orig_inode: original inode
* @orig_path: path indicates first extent to be changed
* @dext: donor extent
* @from: start offset on the target file
*
* In order to insert extents into the leaf block, we must divide the extent
* in the leaf block into three extents. The one is located to be inserted
* extents, and the others are located around it.
*
* Therefore, this function creates structures to save extents of the leaf
* block, and inserts extents by calling mext_insert_extents() with
* created extents. Return 0 on success, or a negative error value on failure.
*/
static int
mext_leaf_block(handle_t *handle, struct inode *orig_inode,
struct ext4_ext_path *orig_path, struct ext4_extent *dext,
ext4_lblk_t *from)
{
struct ext4_extent *oext, *o_start, *o_end, *prev_ext;
struct ext4_extent new_ext, start_ext, end_ext;
ext4_lblk_t new_ext_end;
int oext_alen, new_ext_alen, end_ext_alen;
int depth = ext_depth(orig_inode);
int ret;
start_ext.ee_block = end_ext.ee_block = 0;
o_start = o_end = oext = orig_path[depth].p_ext;
oext_alen = ext4_ext_get_actual_len(oext);
start_ext.ee_len = end_ext.ee_len = 0;
new_ext.ee_block = cpu_to_le32(*from);
ext4_ext_store_pblock(&new_ext, ext4_ext_pblock(dext));
new_ext.ee_len = dext->ee_len;
new_ext_alen = ext4_ext_get_actual_len(&new_ext);
new_ext_end = le32_to_cpu(new_ext.ee_block) + new_ext_alen - 1;
/*
* Case: original extent is first
* oext |--------|
* new_ext |--|
* start_ext |--|
*/
if (le32_to_cpu(oext->ee_block) < le32_to_cpu(new_ext.ee_block) &&
le32_to_cpu(new_ext.ee_block) <
le32_to_cpu(oext->ee_block) + oext_alen) {
start_ext.ee_len = cpu_to_le16(le32_to_cpu(new_ext.ee_block) -
le32_to_cpu(oext->ee_block));
start_ext.ee_block = oext->ee_block;
copy_extent_status(oext, &start_ext);
} else if (oext > EXT_FIRST_EXTENT(orig_path[depth].p_hdr)) {
prev_ext = oext - 1;
/*
* We can merge new_ext into previous extent,
* if these are contiguous and same extent type.
*/
if (ext4_can_extents_be_merged(orig_inode, prev_ext,
&new_ext)) {
o_start = prev_ext;
start_ext.ee_len = cpu_to_le16(
ext4_ext_get_actual_len(prev_ext) +
new_ext_alen);
start_ext.ee_block = oext->ee_block;
copy_extent_status(prev_ext, &start_ext);
new_ext.ee_len = 0;
}
}
/*
* Case: new_ext_end must be less than oext
* oext |-----------|
* new_ext |-------|
*/
if (le32_to_cpu(oext->ee_block) + oext_alen - 1 < new_ext_end) {
EXT4_ERROR_INODE(orig_inode,
"new_ext_end(%u) should be less than or equal to "
"oext->ee_block(%u) + oext_alen(%d) - 1",
new_ext_end, le32_to_cpu(oext->ee_block),
oext_alen);
ret = -EIO;
goto out;
}
/*
* Case: new_ext is smaller than original extent
* oext |---------------|
* new_ext |-----------|
* end_ext |---|
*/
if (le32_to_cpu(oext->ee_block) <= new_ext_end &&
new_ext_end < le32_to_cpu(oext->ee_block) + oext_alen - 1) {
end_ext.ee_len =
cpu_to_le16(le32_to_cpu(oext->ee_block) +
oext_alen - 1 - new_ext_end);
copy_extent_status(oext, &end_ext);
end_ext_alen = ext4_ext_get_actual_len(&end_ext);
ext4_ext_store_pblock(&end_ext,
(ext4_ext_pblock(o_end) + oext_alen - end_ext_alen));
end_ext.ee_block =
cpu_to_le32(le32_to_cpu(o_end->ee_block) +
oext_alen - end_ext_alen);
}
ret = mext_insert_extents(handle, orig_inode, orig_path, o_start,
o_end, &start_ext, &new_ext, &end_ext);
out:
return ret;
}
/**
* mext_calc_swap_extents - Calculate extents for extent swapping.
*
* @tmp_dext: the extent that will belong to the original inode
* @tmp_oext: the extent that will belong to the donor inode
* @orig_off: block offset of original inode
* @donor_off: block offset of donor inode
* @max_count: the maximum length of extents
*
* Return 0 on success, or a negative error value on failure.
*/
static int
mext_calc_swap_extents(struct ext4_extent *tmp_dext,
struct ext4_extent *tmp_oext,
ext4_lblk_t orig_off, ext4_lblk_t donor_off,
ext4_lblk_t max_count)
{
ext4_lblk_t diff, orig_diff;
struct ext4_extent dext_old, oext_old;
BUG_ON(orig_off != donor_off);
/* original and donor extents have to cover the same block offset */
if (orig_off < le32_to_cpu(tmp_oext->ee_block) ||
le32_to_cpu(tmp_oext->ee_block) +
ext4_ext_get_actual_len(tmp_oext) - 1 < orig_off)
return -ENODATA;
if (orig_off < le32_to_cpu(tmp_dext->ee_block) ||
le32_to_cpu(tmp_dext->ee_block) +
ext4_ext_get_actual_len(tmp_dext) - 1 < orig_off)
return -ENODATA;
dext_old = *tmp_dext;
oext_old = *tmp_oext;
/* When tmp_dext is too large, pick up the target range. */
diff = donor_off - le32_to_cpu(tmp_dext->ee_block);
ext4_ext_store_pblock(tmp_dext, ext4_ext_pblock(tmp_dext) + diff);
tmp_dext->ee_block =
cpu_to_le32(le32_to_cpu(tmp_dext->ee_block) + diff);
tmp_dext->ee_len = cpu_to_le16(le16_to_cpu(tmp_dext->ee_len) - diff);
if (max_count < ext4_ext_get_actual_len(tmp_dext))
tmp_dext->ee_len = cpu_to_le16(max_count);
orig_diff = orig_off - le32_to_cpu(tmp_oext->ee_block);
ext4_ext_store_pblock(tmp_oext, ext4_ext_pblock(tmp_oext) + orig_diff);
/* Adjust extent length if donor extent is larger than orig */
if (ext4_ext_get_actual_len(tmp_dext) >
ext4_ext_get_actual_len(tmp_oext) - orig_diff)
tmp_dext->ee_len = cpu_to_le16(le16_to_cpu(tmp_oext->ee_len) -
orig_diff);
tmp_oext->ee_len = cpu_to_le16(ext4_ext_get_actual_len(tmp_dext));
copy_extent_status(&oext_old, tmp_dext);
copy_extent_status(&dext_old, tmp_oext);
return 0;
}
/**
* mext_replace_branches - Replace original extents with new extents
*
* @handle: journal handle
* @orig_inode: original inode
* @donor_inode: donor inode
* @from: block offset of orig_inode
* @count: block count to be replaced
* @err: pointer to save return value
*
* Replace original inode extents and donor inode extents page by page.
* We implement this replacement in the following three steps:
* 1. Save the block information of original and donor inodes into
* dummy extents.
* 2. Change the block information of original inode to point at the
* donor inode blocks.
* 3. Change the block information of donor inode to point at the saved
* original inode blocks in the dummy extents.
*
* Return replaced block count.
*/
static int
mext_replace_branches(handle_t *handle, struct inode *orig_inode,
struct inode *donor_inode, ext4_lblk_t from,
ext4_lblk_t count, int *err)
{
struct ext4_ext_path *orig_path = NULL;
struct ext4_ext_path *donor_path = NULL;
struct ext4_extent *oext, *dext;
struct ext4_extent tmp_dext, tmp_oext;
ext4_lblk_t orig_off = from, donor_off = from;
int depth;
int replaced_count = 0;
int dext_alen;
/* Protect extent trees against block allocations via delalloc */
double_down_write_data_sem(orig_inode, donor_inode);
/* Get the original extent for the block "orig_off" */
*err = get_ext_path(orig_inode, orig_off, &orig_path);
if (*err)
goto out;
/* Get the donor extent for the head */
*err = get_ext_path(donor_inode, donor_off, &donor_path);
if (*err)
goto out;
depth = ext_depth(orig_inode);
oext = orig_path[depth].p_ext;
tmp_oext = *oext;
depth = ext_depth(donor_inode);
dext = donor_path[depth].p_ext;
tmp_dext = *dext;
*err = mext_calc_swap_extents(&tmp_dext, &tmp_oext, orig_off,
donor_off, count);
if (*err)
goto out;
/* Loop for the donor extents */
while (1) {
/* The extent for donor must be found. */
if (!dext) {
EXT4_ERROR_INODE(donor_inode,
"The extent for donor must be found");
*err = -EIO;
goto out;
} else if (donor_off != le32_to_cpu(tmp_dext.ee_block)) {
EXT4_ERROR_INODE(donor_inode,
"Donor offset(%u) and the first block of donor "
"extent(%u) should be equal",
donor_off,
le32_to_cpu(tmp_dext.ee_block));
*err = -EIO;
goto out;
}
/* Set donor extent to orig extent */
*err = mext_leaf_block(handle, orig_inode,
orig_path, &tmp_dext, &orig_off);
if (*err)
goto out;
/* Set orig extent to donor extent */
*err = mext_leaf_block(handle, donor_inode,
donor_path, &tmp_oext, &donor_off);
if (*err)
goto out;
dext_alen = ext4_ext_get_actual_len(&tmp_dext);
replaced_count += dext_alen;
donor_off += dext_alen;
orig_off += dext_alen;
/* Already moved the expected blocks */
if (replaced_count >= count)
break;
if (orig_path)
ext4_ext_drop_refs(orig_path);
*err = get_ext_path(orig_inode, orig_off, &orig_path);
if (*err)
goto out;
depth = ext_depth(orig_inode);
oext = orig_path[depth].p_ext;
tmp_oext = *oext;
if (donor_path)
ext4_ext_drop_refs(donor_path);
*err = get_ext_path(donor_inode, donor_off, &donor_path);
if (*err)
goto out;
depth = ext_depth(donor_inode);
dext = donor_path[depth].p_ext;
tmp_dext = *dext;
*err = mext_calc_swap_extents(&tmp_dext, &tmp_oext, orig_off,
donor_off, count - replaced_count);
if (*err)
goto out;
}
out:
if (orig_path) {
ext4_ext_drop_refs(orig_path);
kfree(orig_path);
}
if (donor_path) {
ext4_ext_drop_refs(donor_path);
kfree(donor_path);
}
ext4_ext_invalidate_cache(orig_inode);
ext4_ext_invalidate_cache(donor_inode);
double_up_write_data_sem(orig_inode, donor_inode);
return replaced_count;
}
/**
* move_extent_per_page - Move extent data per page
*
* @o_filp: file structure of original file
* @donor_inode: donor inode
* @orig_page_offset: page index on original file
* @data_offset_in_page: block index where data swapping starts
* @block_len_in_page: the number of blocks to be swapped
* @uninit: orig extent is uninitialized or not
* @err: pointer to save return value
*
* Save the data in original inode blocks and replace original inode extents
* with donor inode extents by calling mext_replace_branches().
* Finally, write out the saved data in new original inode blocks. Return
* replaced block count.
*/
static int
move_extent_per_page(struct file *o_filp, struct inode *donor_inode,
pgoff_t orig_page_offset, int data_offset_in_page,
int block_len_in_page, int uninit, int *err)
{
struct inode *orig_inode = o_filp->f_dentry->d_inode;
struct address_space *mapping = orig_inode->i_mapping;
struct buffer_head *bh;
struct page *page = NULL;
const struct address_space_operations *a_ops = mapping->a_ops;
handle_t *handle;
ext4_lblk_t orig_blk_offset;
long long offs = orig_page_offset << PAGE_CACHE_SHIFT;
unsigned long blocksize = orig_inode->i_sb->s_blocksize;
unsigned int w_flags = 0;
unsigned int tmp_data_size, data_size, replaced_size;
void *fsdata;
int i, jblocks;
int err2 = 0;
int replaced_count = 0;
int blocks_per_page = PAGE_CACHE_SIZE >> orig_inode->i_blkbits;
/*
* It needs twice the amount of ordinary journal buffers because
* inode and donor_inode may change each different metadata blocks.
*/
jblocks = ext4_writepage_trans_blocks(orig_inode) * 2;
handle = ext4_journal_start(orig_inode, jblocks);
if (IS_ERR(handle)) {
*err = PTR_ERR(handle);
return 0;
}
if (segment_eq(get_fs(), KERNEL_DS))
w_flags |= AOP_FLAG_UNINTERRUPTIBLE;
orig_blk_offset = orig_page_offset * blocks_per_page +
data_offset_in_page;
/*
* If orig extent is uninitialized one,
* it's not necessary force the page into memory
* and then force it to be written out again.
* Just swap data blocks between orig and donor.
*/
if (uninit) {
replaced_count = mext_replace_branches(handle, orig_inode,
donor_inode, orig_blk_offset,
block_len_in_page, err);
goto out2;
}
offs = (long long)orig_blk_offset << orig_inode->i_blkbits;
/* Calculate data_size */
if ((orig_blk_offset + block_len_in_page - 1) ==
((orig_inode->i_size - 1) >> orig_inode->i_blkbits)) {
/* Replace the last block */
tmp_data_size = orig_inode->i_size & (blocksize - 1);
/*
* If data_size equal zero, it shows data_size is multiples of
* blocksize. So we set appropriate value.
*/
if (tmp_data_size == 0)
tmp_data_size = blocksize;
data_size = tmp_data_size +
((block_len_in_page - 1) << orig_inode->i_blkbits);
} else
data_size = block_len_in_page << orig_inode->i_blkbits;
replaced_size = data_size;
*err = a_ops->write_begin(o_filp, mapping, offs, data_size, w_flags,
&page, &fsdata);
if (unlikely(*err < 0))
goto out;
if (!PageUptodate(page)) {
mapping->a_ops->readpage(o_filp, page);
lock_page(page);
}
/*
* try_to_release_page() doesn't call releasepage in writeback mode.
* We should care about the order of writing to the same file
* by multiple move extent processes.
* It needs to call wait_on_page_writeback() to wait for the
* writeback of the page.
*/
wait_on_page_writeback(page);
/* Release old bh and drop refs */
try_to_release_page(page, 0);
replaced_count = mext_replace_branches(handle, orig_inode, donor_inode,
orig_blk_offset, block_len_in_page,
&err2);
if (err2) {
if (replaced_count) {
block_len_in_page = replaced_count;
replaced_size =
block_len_in_page << orig_inode->i_blkbits;
} else
goto out;
}
if (!page_has_buffers(page))
create_empty_buffers(page, 1 << orig_inode->i_blkbits, 0);
bh = page_buffers(page);
for (i = 0; i < data_offset_in_page; i++)
bh = bh->b_this_page;
for (i = 0; i < block_len_in_page; i++) {
*err = ext4_get_block(orig_inode,
(sector_t)(orig_blk_offset + i), bh, 0);
if (*err < 0)
goto out;
if (bh->b_this_page != NULL)
bh = bh->b_this_page;
}
*err = a_ops->write_end(o_filp, mapping, offs, data_size, replaced_size,
page, fsdata);
page = NULL;
out:
if (unlikely(page)) {
if (PageLocked(page))
unlock_page(page);
page_cache_release(page);
ext4_journal_stop(handle);
}
out2:
ext4_journal_stop(handle);
if (err2)
*err = err2;
return replaced_count;
}
/**
* mext_check_arguments - Check whether move extent can be done
*
* @orig_inode: original inode
* @donor_inode: donor inode
* @orig_start: logical start offset in block for orig
* @donor_start: logical start offset in block for donor
* @len: the number of blocks to be moved
*
* Check the arguments of ext4_move_extents() whether the files can be
* exchanged with each other.
* Return 0 on success, or a negative error value on failure.
*/
static int
mext_check_arguments(struct inode *orig_inode,
struct inode *donor_inode, __u64 orig_start,
__u64 donor_start, __u64 *len)
{
ext4_lblk_t orig_blocks, donor_blocks;
unsigned int blkbits = orig_inode->i_blkbits;
unsigned int blocksize = 1 << blkbits;
if (donor_inode->i_mode & (S_ISUID|S_ISGID)) {
ext4_debug("ext4 move extent: suid or sgid is set"
" to donor file [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
if (IS_IMMUTABLE(donor_inode) || IS_APPEND(donor_inode))
return -EPERM;
/* Ext4 move extent does not support swapfile */
if (IS_SWAPFILE(orig_inode) || IS_SWAPFILE(donor_inode)) {
ext4_debug("ext4 move extent: The argument files should "
"not be swapfile [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* Files should be in the same ext4 FS */
if (orig_inode->i_sb != donor_inode->i_sb) {
ext4_debug("ext4 move extent: The argument files "
"should be in same FS [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* Ext4 move extent supports only extent based file */
if (!(ext4_test_inode_flag(orig_inode, EXT4_INODE_EXTENTS))) {
ext4_debug("ext4 move extent: orig file is not extents "
"based file [ino:orig %lu]\n", orig_inode->i_ino);
return -EOPNOTSUPP;
} else if (!(ext4_test_inode_flag(donor_inode, EXT4_INODE_EXTENTS))) {
ext4_debug("ext4 move extent: donor file is not extents "
"based file [ino:donor %lu]\n", donor_inode->i_ino);
return -EOPNOTSUPP;
}
if ((!orig_inode->i_size) || (!donor_inode->i_size)) {
ext4_debug("ext4 move extent: File size is 0 byte\n");
return -EINVAL;
}
/* Start offset should be same */
if (orig_start != donor_start) {
ext4_debug("ext4 move extent: orig and donor's start "
"offset are not same [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
if ((orig_start >= EXT_MAX_BLOCKS) ||
(donor_start >= EXT_MAX_BLOCKS) ||
(*len > EXT_MAX_BLOCKS) ||
(orig_start + *len >= EXT_MAX_BLOCKS)) {
ext4_debug("ext4 move extent: Can't handle over [%u] blocks "
"[ino:orig %lu, donor %lu]\n", EXT_MAX_BLOCKS,
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
if (orig_inode->i_size > donor_inode->i_size) {
donor_blocks = (donor_inode->i_size + blocksize - 1) >> blkbits;
/* TODO: eliminate this artificial restriction */
if (orig_start >= donor_blocks) {
ext4_debug("ext4 move extent: orig start offset "
"[%llu] should be less than donor file blocks "
"[%u] [ino:orig %lu, donor %lu]\n",
orig_start, donor_blocks,
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* TODO: eliminate this artificial restriction */
if (orig_start + *len > donor_blocks) {
ext4_debug("ext4 move extent: End offset [%llu] should "
"be less than donor file blocks [%u]."
"So adjust length from %llu to %llu "
"[ino:orig %lu, donor %lu]\n",
orig_start + *len, donor_blocks,
*len, donor_blocks - orig_start,
orig_inode->i_ino, donor_inode->i_ino);
*len = donor_blocks - orig_start;
}
} else {
orig_blocks = (orig_inode->i_size + blocksize - 1) >> blkbits;
if (orig_start >= orig_blocks) {
ext4_debug("ext4 move extent: start offset [%llu] "
"should be less than original file blocks "
"[%u] [ino:orig %lu, donor %lu]\n",
orig_start, orig_blocks,
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
if (orig_start + *len > orig_blocks) {
ext4_debug("ext4 move extent: Adjust length "
"from %llu to %llu. Because it should be "
"less than original file blocks "
"[ino:orig %lu, donor %lu]\n",
*len, orig_blocks - orig_start,
orig_inode->i_ino, donor_inode->i_ino);
*len = orig_blocks - orig_start;
}
}
if (!*len) {
ext4_debug("ext4 move extent: len should not be 0 "
"[ino:orig %lu, donor %lu]\n", orig_inode->i_ino,
donor_inode->i_ino);
return -EINVAL;
}
return 0;
}
/**
* mext_inode_double_lock - Lock i_mutex on both @inode1 and @inode2
*
* @inode1: the inode structure
* @inode2: the inode structure
*
* Lock two inodes' i_mutex by i_ino order.
* If inode1 or inode2 is NULL, return -EIO. Otherwise, return 0.
*/
static int
mext_inode_double_lock(struct inode *inode1, struct inode *inode2)
{
int ret = 0;
BUG_ON(inode1 == NULL && inode2 == NULL);
ret = mext_check_null_inode(inode1, inode2, __func__, __LINE__);
if (ret < 0)
goto out;
if (inode1 == inode2) {
mutex_lock(&inode1->i_mutex);
goto out;
}
if (inode1->i_ino < inode2->i_ino) {
mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
} else {
mutex_lock_nested(&inode2->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&inode1->i_mutex, I_MUTEX_CHILD);
}
out:
return ret;
}
/**
* mext_inode_double_unlock - Release i_mutex on both @inode1 and @inode2
*
* @inode1: the inode that is released first
* @inode2: the inode that is released second
*
* If inode1 or inode2 is NULL, return -EIO. Otherwise, return 0.
*/
static int
mext_inode_double_unlock(struct inode *inode1, struct inode *inode2)
{
int ret = 0;
BUG_ON(inode1 == NULL && inode2 == NULL);
ret = mext_check_null_inode(inode1, inode2, __func__, __LINE__);
if (ret < 0)
goto out;
if (inode1)
mutex_unlock(&inode1->i_mutex);
if (inode2 && inode2 != inode1)
mutex_unlock(&inode2->i_mutex);
out:
return ret;
}
/**
* ext4_move_extents - Exchange the specified range of a file
*
* @o_filp: file structure of the original file
* @d_filp: file structure of the donor file
* @orig_start: start offset in block for orig
* @donor_start: start offset in block for donor
* @len: the number of blocks to be moved
* @moved_len: moved block length
*
* This function returns 0 and moved block length is set in moved_len
* if succeed, otherwise returns error value.
*
* Note: ext4_move_extents() proceeds the following order.
* 1:ext4_move_extents() calculates the last block number of moving extent
* function by the start block number (orig_start) and the number of blocks
* to be moved (len) specified as arguments.
* If the {orig, donor}_start points a hole, the extent's start offset
* pointed by ext_cur (current extent), holecheck_path, orig_path are set
* after hole behind.
* 2:Continue step 3 to step 5, until the holecheck_path points to last_extent
* or the ext_cur exceeds the block_end which is last logical block number.
* 3:To get the length of continues area, call mext_next_extent()
* specified with the ext_cur (initial value is holecheck_path) re-cursive,
* until find un-continuous extent, the start logical block number exceeds
* the block_end or the extent points to the last extent.
* 4:Exchange the original inode data with donor inode data
* from orig_page_offset to seq_end_page.
* The start indexes of data are specified as arguments.
* That of the original inode is orig_page_offset,
* and the donor inode is also orig_page_offset
* (To easily handle blocksize != pagesize case, the offset for the
* donor inode is block unit).
* 5:Update holecheck_path and orig_path to points a next proceeding extent,
* then returns to step 2.
* 6:Release holecheck_path, orig_path and set the len to moved_len
* which shows the number of moved blocks.
* The moved_len is useful for the command to calculate the file offset
* for starting next move extent ioctl.
* 7:Return 0 on success, or a negative error value on failure.
*/
int
ext4_move_extents(struct file *o_filp, struct file *d_filp,
__u64 orig_start, __u64 donor_start, __u64 len,
__u64 *moved_len)
{
struct inode *orig_inode = o_filp->f_dentry->d_inode;
struct inode *donor_inode = d_filp->f_dentry->d_inode;
struct ext4_ext_path *orig_path = NULL, *holecheck_path = NULL;
struct ext4_extent *ext_prev, *ext_cur, *ext_dummy;
ext4_lblk_t block_start = orig_start;
ext4_lblk_t block_end, seq_start, add_blocks, file_end, seq_blocks = 0;
ext4_lblk_t rest_blocks;
pgoff_t orig_page_offset = 0, seq_end_page;
int ret1, ret2, depth, last_extent = 0;
int blocks_per_page = PAGE_CACHE_SIZE >> orig_inode->i_blkbits;
int data_offset_in_page;
int block_len_in_page;
int uninit;
/* orig and donor should be different file */
if (orig_inode->i_ino == donor_inode->i_ino) {
ext4_debug("ext4 move extent: The argument files should not "
"be same file [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* Regular file check */
if (!S_ISREG(orig_inode->i_mode) || !S_ISREG(donor_inode->i_mode)) {
ext4_debug("ext4 move extent: The argument files should be "
"regular file [ino:orig %lu, donor %lu]\n",
orig_inode->i_ino, donor_inode->i_ino);
return -EINVAL;
}
/* Protect orig and donor inodes against a truncate */
ret1 = mext_inode_double_lock(orig_inode, donor_inode);
if (ret1 < 0)
return ret1;
/* Protect extent tree against block allocations via delalloc */
double_down_write_data_sem(orig_inode, donor_inode);
/* Check the filesystem environment whether move_extent can be done */
ret1 = mext_check_arguments(orig_inode, donor_inode, orig_start,
donor_start, &len);
if (ret1)
goto out;
file_end = (i_size_read(orig_inode) - 1) >> orig_inode->i_blkbits;
block_end = block_start + len - 1;
if (file_end < block_end)
len -= block_end - file_end;
ret1 = get_ext_path(orig_inode, block_start, &orig_path);
if (ret1)
goto out;
/* Get path structure to check the hole */
ret1 = get_ext_path(orig_inode, block_start, &holecheck_path);
if (ret1)
goto out;
depth = ext_depth(orig_inode);
ext_cur = holecheck_path[depth].p_ext;
/*
* Get proper starting location of block replacement if block_start was
* within the hole.
*/
if (le32_to_cpu(ext_cur->ee_block) +
ext4_ext_get_actual_len(ext_cur) - 1 < block_start) {
/*
* The hole exists between extents or the tail of
* original file.
*/
last_extent = mext_next_extent(orig_inode,
holecheck_path, &ext_cur);
if (last_extent < 0) {
ret1 = last_extent;
goto out;
}
last_extent = mext_next_extent(orig_inode, orig_path,
&ext_dummy);
if (last_extent < 0) {
ret1 = last_extent;
goto out;
}
seq_start = le32_to_cpu(ext_cur->ee_block);
} else if (le32_to_cpu(ext_cur->ee_block) > block_start)
/* The hole exists at the beginning of original file. */
seq_start = le32_to_cpu(ext_cur->ee_block);
else
seq_start = block_start;
/* No blocks within the specified range. */
if (le32_to_cpu(ext_cur->ee_block) > block_end) {
ext4_debug("ext4 move extent: The specified range of file "
"may be the hole\n");
ret1 = -EINVAL;
goto out;
}
/* Adjust start blocks */
add_blocks = min(le32_to_cpu(ext_cur->ee_block) +
ext4_ext_get_actual_len(ext_cur), block_end + 1) -
max(le32_to_cpu(ext_cur->ee_block), block_start);
while (!last_extent && le32_to_cpu(ext_cur->ee_block) <= block_end) {
seq_blocks += add_blocks;
/* Adjust tail blocks */
if (seq_start + seq_blocks - 1 > block_end)
seq_blocks = block_end - seq_start + 1;
ext_prev = ext_cur;
last_extent = mext_next_extent(orig_inode, holecheck_path,
&ext_cur);
if (last_extent < 0) {
ret1 = last_extent;
break;
}
add_blocks = ext4_ext_get_actual_len(ext_cur);
/*
* Extend the length of contiguous block (seq_blocks)
* if extents are contiguous.
*/
if (ext4_can_extents_be_merged(orig_inode,
ext_prev, ext_cur) &&
block_end >= le32_to_cpu(ext_cur->ee_block) &&
!last_extent)
continue;
/* Is original extent is uninitialized */
uninit = ext4_ext_is_uninitialized(ext_prev);
data_offset_in_page = seq_start % blocks_per_page;
/*
* Calculate data blocks count that should be swapped
* at the first page.
*/
if (data_offset_in_page + seq_blocks > blocks_per_page) {
/* Swapped blocks are across pages */
block_len_in_page =
blocks_per_page - data_offset_in_page;
} else {
/* Swapped blocks are in a page */
block_len_in_page = seq_blocks;
}
orig_page_offset = seq_start >>
(PAGE_CACHE_SHIFT - orig_inode->i_blkbits);
seq_end_page = (seq_start + seq_blocks - 1) >>
(PAGE_CACHE_SHIFT - orig_inode->i_blkbits);
seq_start = le32_to_cpu(ext_cur->ee_block);
rest_blocks = seq_blocks;
/*
* Up semaphore to avoid following problems:
* a. transaction deadlock among ext4_journal_start,
* ->write_begin via pagefault, and jbd2_journal_commit
* b. racing with ->readpage, ->write_begin, and ext4_get_block
* in move_extent_per_page
*/
double_up_write_data_sem(orig_inode, donor_inode);
while (orig_page_offset <= seq_end_page) {
/* Swap original branches with new branches */
block_len_in_page = move_extent_per_page(
o_filp, donor_inode,
orig_page_offset,
data_offset_in_page,
block_len_in_page, uninit,
&ret1);
/* Count how many blocks we have exchanged */
*moved_len += block_len_in_page;
if (ret1 < 0)
break;
if (*moved_len > len) {
EXT4_ERROR_INODE(orig_inode,
"We replaced blocks too much! "
"sum of replaced: %llu requested: %llu",
*moved_len, len);
ret1 = -EIO;
break;
}
orig_page_offset++;
data_offset_in_page = 0;
rest_blocks -= block_len_in_page;
if (rest_blocks > blocks_per_page)
block_len_in_page = blocks_per_page;
else
block_len_in_page = rest_blocks;
}
double_down_write_data_sem(orig_inode, donor_inode);
if (ret1 < 0)
break;
/* Decrease buffer counter */
if (holecheck_path)
ext4_ext_drop_refs(holecheck_path);
ret1 = get_ext_path(orig_inode, seq_start, &holecheck_path);
if (ret1)
break;
depth = holecheck_path->p_depth;
/* Decrease buffer counter */
if (orig_path)
ext4_ext_drop_refs(orig_path);
ret1 = get_ext_path(orig_inode, seq_start, &orig_path);
if (ret1)
break;
ext_cur = holecheck_path[depth].p_ext;
add_blocks = ext4_ext_get_actual_len(ext_cur);
seq_blocks = 0;
}
out:
if (*moved_len) {
ext4_discard_preallocations(orig_inode);
ext4_discard_preallocations(donor_inode);
}
if (orig_path) {
ext4_ext_drop_refs(orig_path);
kfree(orig_path);
}
if (holecheck_path) {
ext4_ext_drop_refs(holecheck_path);
kfree(holecheck_path);
}
double_up_write_data_sem(orig_inode, donor_inode);
ret2 = mext_inode_double_unlock(orig_inode, donor_inode);
if (ret1)
return ret1;
else if (ret2)
return ret2;
return 0;
}
| gpl-2.0 |
c0d3x42/android_kernel_vodafone_su6 | arch/arm/mach-davinci/usb.c | 4105 | 3932 | /*
* USB
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/usb/musb.h>
#include <mach/common.h>
#include <mach/irqs.h>
#include <mach/cputype.h>
#include <mach/da8xx.h>
#include <linux/platform_data/usb-davinci.h>
#define DAVINCI_USB_OTG_BASE 0x01c64000
#define DA8XX_USB0_BASE 0x01e00000
#define DA8XX_USB1_BASE 0x01e25000
#if IS_ENABLED(CONFIG_USB_MUSB_HDRC)
static struct musb_hdrc_eps_bits musb_eps[] = {
{ "ep1_tx", 8, },
{ "ep1_rx", 8, },
{ "ep2_tx", 8, },
{ "ep2_rx", 8, },
{ "ep3_tx", 5, },
{ "ep3_rx", 5, },
{ "ep4_tx", 5, },
{ "ep4_rx", 5, },
};
static struct musb_hdrc_config musb_config = {
.multipoint = true,
.dyn_fifo = true,
.soft_con = true,
.dma = true,
.num_eps = 5,
.dma_channels = 8,
.ram_bits = 10,
.eps_bits = musb_eps,
};
static struct musb_hdrc_platform_data usb_data = {
/* OTG requires a Mini-AB connector */
.mode = MUSB_OTG,
.clock = "usb",
.config = &musb_config,
};
static struct resource usb_resources[] = {
{
/* physical address */
.start = DAVINCI_USB_OTG_BASE,
.end = DAVINCI_USB_OTG_BASE + 0x5ff,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_USBINT,
.flags = IORESOURCE_IRQ,
.name = "mc"
},
{
/* placeholder for the dedicated CPPI IRQ */
.flags = IORESOURCE_IRQ,
.name = "dma"
},
};
static u64 usb_dmamask = DMA_BIT_MASK(32);
static struct platform_device usb_dev = {
.name = "musb-davinci",
.id = -1,
.dev = {
.platform_data = &usb_data,
.dma_mask = &usb_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = usb_resources,
.num_resources = ARRAY_SIZE(usb_resources),
};
void __init davinci_setup_usb(unsigned mA, unsigned potpgt_ms)
{
usb_data.power = mA > 510 ? 255 : mA / 2;
usb_data.potpgt = (potpgt_ms + 1) / 2;
if (cpu_is_davinci_dm646x()) {
/* Override the defaults as DM6467 uses different IRQs. */
usb_dev.resource[1].start = IRQ_DM646X_USBINT;
usb_dev.resource[2].start = IRQ_DM646X_USBDMAINT;
} else /* other devices don't have dedicated CPPI IRQ */
usb_dev.num_resources = 2;
platform_device_register(&usb_dev);
}
#ifdef CONFIG_ARCH_DAVINCI_DA8XX
static struct resource da8xx_usb20_resources[] = {
{
.start = DA8XX_USB0_BASE,
.end = DA8XX_USB0_BASE + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_DA8XX_USB_INT,
.flags = IORESOURCE_IRQ,
.name = "mc",
},
};
int __init da8xx_register_usb20(unsigned mA, unsigned potpgt)
{
usb_data.clock = "usb20";
usb_data.power = mA > 510 ? 255 : mA / 2;
usb_data.potpgt = (potpgt + 1) / 2;
usb_dev.resource = da8xx_usb20_resources;
usb_dev.num_resources = ARRAY_SIZE(da8xx_usb20_resources);
usb_dev.name = "musb-da8xx";
return platform_device_register(&usb_dev);
}
#endif /* CONFIG_DAVINCI_DA8XX */
#else
void __init davinci_setup_usb(unsigned mA, unsigned potpgt_ms)
{
}
#ifdef CONFIG_ARCH_DAVINCI_DA8XX
int __init da8xx_register_usb20(unsigned mA, unsigned potpgt)
{
return 0;
}
#endif
#endif /* CONFIG_USB_MUSB_HDRC */
#ifdef CONFIG_ARCH_DAVINCI_DA8XX
static struct resource da8xx_usb11_resources[] = {
[0] = {
.start = DA8XX_USB1_BASE,
.end = DA8XX_USB1_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_DA8XX_IRQN,
.end = IRQ_DA8XX_IRQN,
.flags = IORESOURCE_IRQ,
},
};
static u64 da8xx_usb11_dma_mask = DMA_BIT_MASK(32);
static struct platform_device da8xx_usb11_device = {
.name = "ohci",
.id = 0,
.dev = {
.dma_mask = &da8xx_usb11_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.num_resources = ARRAY_SIZE(da8xx_usb11_resources),
.resource = da8xx_usb11_resources,
};
int __init da8xx_register_usb11(struct da8xx_ohci_root_hub *pdata)
{
da8xx_usb11_device.dev.platform_data = pdata;
return platform_device_register(&da8xx_usb11_device);
}
#endif /* CONFIG_DAVINCI_DA8XX */
| gpl-2.0 |
chevanlol360/Android_Kernel_LGE_Fx1 | drivers/staging/sbe-2t3e3/exar7300.c | 8201 | 4494 | /*
* SBE 2T3E3 synchronous serial card driver for Linux
*
* Copyright (C) 2009-2010 Krzysztof Halasa <khc@pm.waw.pl>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*
* This code is based on a driver written by SBE Inc.
*/
#include "2t3e3.h"
#include "ctrl.h"
void exar7300_init(struct channel *sc)
{
exar7300_write(sc, SBE_2T3E3_LIU_REG_REG1, 0);
/* enable line decodeer and encoder */
exar7300_write(sc, SBE_2T3E3_LIU_REG_REG2, 0);
exar7300_write(sc, SBE_2T3E3_LIU_REG_REG3, 0);
exar7300_write(sc, SBE_2T3E3_LIU_REG_REG4,
SBE_2T3E3_LIU_VAL_T3_MODE_SELECT |
SBE_2T3E3_LIU_VAL_LOOPBACK_OFF);
}
void exar7300_set_loopback(struct channel *sc, u32 mode)
{
u32 val;
switch (mode) {
case SBE_2T3E3_LIU_VAL_LOOPBACK_OFF:
case SBE_2T3E3_LIU_VAL_LOOPBACK_REMOTE:
case SBE_2T3E3_LIU_VAL_LOOPBACK_ANALOG:
case SBE_2T3E3_LIU_VAL_LOOPBACK_DIGITAL:
break;
default:
return;
}
val = exar7300_read(sc, SBE_2T3E3_LIU_REG_REG4);
val &= ~(SBE_2T3E3_LIU_VAL_LOCAL_LOOPBACK | SBE_2T3E3_LIU_VAL_REMOTE_LOOPBACK);
val |= mode;
exar7300_write(sc, SBE_2T3E3_LIU_REG_REG4, val);
#if 0
/* TODO - is it necessary? idea from 2T3E3_HW_Test_code */
switch (mode) {
case SBE_2T3E3_LIU_VAL_LOOPBACK_OFF:
break;
case SBE_2T3E3_LIU_VAL_LOOPBACK_REMOTE:
exar7300_receive_equalization_onoff(sc, SBE_2T3E3_ON);
break;
case SBE_2T3E3_LIU_VAL_LOOPBACK_ANALOG:
exar7300_receive_equalization_onoff(sc, SBE_2T3E3_OFF);
break;
case SBE_2T3E3_LIU_VAL_LOOPBACK_DIGITAL:
exar7300_receive_equalization_onoff(sc, SBE_2T3E3_ON);
break;
}
#endif
}
void exar7300_set_frame_type(struct channel *sc, u32 type)
{
u32 val;
switch (type) {
case SBE_2T3E3_FRAME_TYPE_T3_CBIT:
case SBE_2T3E3_FRAME_TYPE_T3_M13:
case SBE_2T3E3_FRAME_TYPE_E3_G751:
case SBE_2T3E3_FRAME_TYPE_E3_G832:
break;
default:
return;
}
val = exar7300_read(sc, SBE_2T3E3_LIU_REG_REG4);
val &= ~(SBE_2T3E3_LIU_VAL_T3_MODE_SELECT |
SBE_2T3E3_LIU_VAL_E3_MODE_SELECT);
switch (type) {
case SBE_2T3E3_FRAME_TYPE_T3_CBIT:
case SBE_2T3E3_FRAME_TYPE_T3_M13:
val |= SBE_2T3E3_LIU_VAL_T3_MODE_SELECT;
break;
case SBE_2T3E3_FRAME_TYPE_E3_G751:
case SBE_2T3E3_FRAME_TYPE_E3_G832:
val |= SBE_2T3E3_LIU_VAL_E3_MODE_SELECT;
break;
default:
return;
}
exar7300_write(sc, SBE_2T3E3_LIU_REG_REG4, val);
}
void exar7300_transmit_all_ones_onoff(struct channel *sc, u32 mode)
{
if (sc->p.transmit_all_ones == mode)
return;
switch (mode) {
case SBE_2T3E3_ON:
exar7300_set_bit(sc, SBE_2T3E3_LIU_REG_REG1,
SBE_2T3E3_LIU_VAL_TRANSMIT_ALL_ONES);
break;
case SBE_2T3E3_OFF:
exar7300_clear_bit(sc, SBE_2T3E3_LIU_REG_REG1,
SBE_2T3E3_LIU_VAL_TRANSMIT_ALL_ONES);
break;
default:
return;
}
sc->p.transmit_all_ones = mode;
}
void exar7300_receive_equalization_onoff(struct channel *sc, u32 mode)
{
if (sc->p.receive_equalization == mode)
return;
switch (mode) {
case SBE_2T3E3_OFF:
exar7300_set_bit(sc, SBE_2T3E3_LIU_REG_REG2,
SBE_2T3E3_LIU_VAL_RECEIVE_EQUALIZATION_DISABLE);
break;
case SBE_2T3E3_ON:
exar7300_clear_bit(sc, SBE_2T3E3_LIU_REG_REG2,
SBE_2T3E3_LIU_VAL_RECEIVE_EQUALIZATION_DISABLE);
break;
default:
return;
}
sc->p.receive_equalization = mode;
}
void exar7300_line_build_out_onoff(struct channel *sc, u32 mode)
{
if (sc->p.line_build_out == mode)
return;
switch (mode) {
case SBE_2T3E3_OFF:
exar7300_set_bit(sc, SBE_2T3E3_LIU_REG_REG1,
SBE_2T3E3_LIU_VAL_TRANSMIT_LEVEL_SELECT);
exar7300_receive_equalization_onoff(sc, SBE_2T3E3_OFF);
break;
case SBE_2T3E3_ON:
exar7300_clear_bit(sc, SBE_2T3E3_LIU_REG_REG1,
SBE_2T3E3_LIU_VAL_TRANSMIT_LEVEL_SELECT);
exar7300_receive_equalization_onoff(sc, SBE_2T3E3_ON);
break;
default:
return;
}
sc->p.line_build_out = mode;
}
/* TODO - what about encoder in raw mode??? disable it too? */
void exar7300_unipolar_onoff(struct channel *sc, u32 mode)
{
switch (mode) {
case SBE_2T3E3_OFF:
exar7300_clear_bit(sc, SBE_2T3E3_LIU_REG_REG3,
SBE_2T3E3_LIU_VAL_DECODER_DISABLE);
exar7300_clear_bit(sc, SBE_2T3E3_LIU_REG_REG1,
SBE_2T3E3_LIU_VAL_TRANSMIT_BINARY_DATA);
break;
case SBE_2T3E3_ON:
exar7300_set_bit(sc, SBE_2T3E3_LIU_REG_REG3,
SBE_2T3E3_LIU_VAL_DECODER_DISABLE);
exar7300_set_bit(sc, SBE_2T3E3_LIU_REG_REG1,
SBE_2T3E3_LIU_VAL_TRANSMIT_BINARY_DATA);
break;
}
}
| gpl-2.0 |
mifl/android_kernel_qcom_msm8974 | arch/ia64/kvm/vmm.c | 8457 | 2352 | /*
* vmm.c: vmm module interface with kvm module
*
* Copyright (c) 2007, Intel Corporation.
*
* Xiantao Zhang (xiantao.zhang@intel.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*/
#include<linux/kernel.h>
#include<linux/module.h>
#include<asm/fpswa.h>
#include "vcpu.h"
MODULE_AUTHOR("Intel");
MODULE_LICENSE("GPL");
extern char kvm_ia64_ivt;
extern char kvm_asm_mov_from_ar;
extern char kvm_asm_mov_from_ar_sn2;
extern fpswa_interface_t *vmm_fpswa_interface;
long vmm_sanity = 1;
struct kvm_vmm_info vmm_info = {
.module = THIS_MODULE,
.vmm_entry = vmm_entry,
.tramp_entry = vmm_trampoline,
.vmm_ivt = (unsigned long)&kvm_ia64_ivt,
.patch_mov_ar = (unsigned long)&kvm_asm_mov_from_ar,
.patch_mov_ar_sn2 = (unsigned long)&kvm_asm_mov_from_ar_sn2,
};
static int __init kvm_vmm_init(void)
{
vmm_fpswa_interface = fpswa_interface;
/*Register vmm data to kvm side*/
return kvm_init(&vmm_info, 1024, 0, THIS_MODULE);
}
static void __exit kvm_vmm_exit(void)
{
kvm_exit();
return ;
}
void vmm_spin_lock(vmm_spinlock_t *lock)
{
_vmm_raw_spin_lock(lock);
}
void vmm_spin_unlock(vmm_spinlock_t *lock)
{
_vmm_raw_spin_unlock(lock);
}
static void vcpu_debug_exit(struct kvm_vcpu *vcpu)
{
struct exit_ctl_data *p = &vcpu->arch.exit_data;
long psr;
local_irq_save(psr);
p->exit_reason = EXIT_REASON_DEBUG;
vmm_transition(vcpu);
local_irq_restore(psr);
}
asmlinkage int printk(const char *fmt, ...)
{
struct kvm_vcpu *vcpu = current_vcpu;
va_list args;
int r;
memset(vcpu->arch.log_buf, 0, VMM_LOG_LEN);
va_start(args, fmt);
r = vsnprintf(vcpu->arch.log_buf, VMM_LOG_LEN, fmt, args);
va_end(args);
vcpu_debug_exit(vcpu);
return r;
}
module_init(kvm_vmm_init)
module_exit(kvm_vmm_exit)
| gpl-2.0 |
shoey63/kernel-copyleft | drivers/net/ethernet/8390/8390p.c | 9737 | 2249 | /* 8390 core for ISA devices needing bus delays */
static const char version[] =
"8390p.c:v1.10cvs 9/23/94 Donald Becker (becker@cesdis.gsfc.nasa.gov)\n";
#define ei_inb(_p) inb(_p)
#define ei_outb(_v, _p) outb(_v, _p)
#define ei_inb_p(_p) inb_p(_p)
#define ei_outb_p(_v, _p) outb_p(_v, _p)
#include "lib8390.c"
int eip_open(struct net_device *dev)
{
return __ei_open(dev);
}
EXPORT_SYMBOL(eip_open);
int eip_close(struct net_device *dev)
{
return __ei_close(dev);
}
EXPORT_SYMBOL(eip_close);
netdev_tx_t eip_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
return __ei_start_xmit(skb, dev);
}
EXPORT_SYMBOL(eip_start_xmit);
struct net_device_stats *eip_get_stats(struct net_device *dev)
{
return __ei_get_stats(dev);
}
EXPORT_SYMBOL(eip_get_stats);
void eip_set_multicast_list(struct net_device *dev)
{
__ei_set_multicast_list(dev);
}
EXPORT_SYMBOL(eip_set_multicast_list);
void eip_tx_timeout(struct net_device *dev)
{
__ei_tx_timeout(dev);
}
EXPORT_SYMBOL(eip_tx_timeout);
irqreturn_t eip_interrupt(int irq, void *dev_id)
{
return __ei_interrupt(irq, dev_id);
}
EXPORT_SYMBOL(eip_interrupt);
#ifdef CONFIG_NET_POLL_CONTROLLER
void eip_poll(struct net_device *dev)
{
__ei_poll(dev);
}
EXPORT_SYMBOL(eip_poll);
#endif
const struct net_device_ops eip_netdev_ops = {
.ndo_open = eip_open,
.ndo_stop = eip_close,
.ndo_start_xmit = eip_start_xmit,
.ndo_tx_timeout = eip_tx_timeout,
.ndo_get_stats = eip_get_stats,
.ndo_set_rx_mode = eip_set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = eip_poll,
#endif
};
EXPORT_SYMBOL(eip_netdev_ops);
struct net_device *__alloc_eip_netdev(int size)
{
struct net_device *dev = ____alloc_ei_netdev(size);
if (dev)
dev->netdev_ops = &eip_netdev_ops;
return dev;
}
EXPORT_SYMBOL(__alloc_eip_netdev);
void NS8390p_init(struct net_device *dev, int startp)
{
__NS8390_init(dev, startp);
}
EXPORT_SYMBOL(NS8390p_init);
static int __init NS8390p_init_module(void)
{
return 0;
}
static void __exit NS8390p_cleanup_module(void)
{
}
module_init(NS8390p_init_module);
module_exit(NS8390p_cleanup_module);
MODULE_LICENSE("GPL");
| gpl-2.0 |
libcg/android_kernel_samsung_exynos4 | drivers/tty/serial/cpm_uart/cpm_uart_cpm2.c | 10505 | 4712 | /*
* Driver for CPM (SCC/SMC) serial ports; CPM2 definitions
*
* Maintainer: Kumar Gala (galak@kernel.crashing.org) (CPM2)
* Pantelis Antoniou (panto@intracom.gr) (CPM1)
*
* Copyright (C) 2004 Freescale Semiconductor, Inc.
* (C) 2004 Intracom, S.A.
* (C) 2006 MontaVista Software, Inc.
* Vitaly Bordug <vbordug@ru.mvista.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/module.h>
#include <linux/tty.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/device.h>
#include <linux/bootmem.h>
#include <linux/dma-mapping.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/fs_pd.h>
#include <asm/prom.h>
#include <linux/serial_core.h>
#include <linux/kernel.h>
#include "cpm_uart.h"
/**************************************************************/
void cpm_line_cr_cmd(struct uart_cpm_port *port, int cmd)
{
cpm_command(port->command, cmd);
}
void __iomem *cpm_uart_map_pram(struct uart_cpm_port *port,
struct device_node *np)
{
void __iomem *pram;
unsigned long offset;
struct resource res;
resource_size_t len;
/* Don't remap parameter RAM if it has already been initialized
* during console setup.
*/
if (IS_SMC(port) && port->smcup)
return port->smcup;
else if (!IS_SMC(port) && port->sccup)
return port->sccup;
if (of_address_to_resource(np, 1, &res))
return NULL;
len = resource_size(&res);
pram = ioremap(res.start, len);
if (!pram)
return NULL;
if (!IS_SMC(port))
return pram;
if (len != 2) {
printk(KERN_WARNING "cpm_uart[%d]: device tree references "
"SMC pram, using boot loader/wrapper pram mapping. "
"Please fix your device tree to reference the pram "
"base register instead.\n",
port->port.line);
return pram;
}
offset = cpm_dpalloc(PROFF_SMC_SIZE, 64);
out_be16(pram, offset);
iounmap(pram);
return cpm_muram_addr(offset);
}
void cpm_uart_unmap_pram(struct uart_cpm_port *port, void __iomem *pram)
{
if (!IS_SMC(port))
iounmap(pram);
}
/*
* Allocate DP-Ram and memory buffers. We need to allocate a transmit and
* receive buffer descriptors from dual port ram, and a character
* buffer area from host mem. If we are allocating for the console we need
* to do it from bootmem
*/
int cpm_uart_allocbuf(struct uart_cpm_port *pinfo, unsigned int is_con)
{
int dpmemsz, memsz;
u8 __iomem *dp_mem;
unsigned long dp_offset;
u8 *mem_addr;
dma_addr_t dma_addr = 0;
pr_debug("CPM uart[%d]:allocbuf\n", pinfo->port.line);
dpmemsz = sizeof(cbd_t) * (pinfo->rx_nrfifos + pinfo->tx_nrfifos);
dp_offset = cpm_dpalloc(dpmemsz, 8);
if (IS_ERR_VALUE(dp_offset)) {
printk(KERN_ERR
"cpm_uart_cpm.c: could not allocate buffer descriptors\n");
return -ENOMEM;
}
dp_mem = cpm_dpram_addr(dp_offset);
memsz = L1_CACHE_ALIGN(pinfo->rx_nrfifos * pinfo->rx_fifosize) +
L1_CACHE_ALIGN(pinfo->tx_nrfifos * pinfo->tx_fifosize);
if (is_con) {
mem_addr = kzalloc(memsz, GFP_NOWAIT);
dma_addr = virt_to_bus(mem_addr);
}
else
mem_addr = dma_alloc_coherent(pinfo->port.dev, memsz, &dma_addr,
GFP_KERNEL);
if (mem_addr == NULL) {
cpm_dpfree(dp_offset);
printk(KERN_ERR
"cpm_uart_cpm.c: could not allocate coherent memory\n");
return -ENOMEM;
}
pinfo->dp_addr = dp_offset;
pinfo->mem_addr = mem_addr;
pinfo->dma_addr = dma_addr;
pinfo->mem_size = memsz;
pinfo->rx_buf = mem_addr;
pinfo->tx_buf = pinfo->rx_buf + L1_CACHE_ALIGN(pinfo->rx_nrfifos
* pinfo->rx_fifosize);
pinfo->rx_bd_base = (cbd_t __iomem *)dp_mem;
pinfo->tx_bd_base = pinfo->rx_bd_base + pinfo->rx_nrfifos;
return 0;
}
void cpm_uart_freebuf(struct uart_cpm_port *pinfo)
{
dma_free_coherent(pinfo->port.dev, L1_CACHE_ALIGN(pinfo->rx_nrfifos *
pinfo->rx_fifosize) +
L1_CACHE_ALIGN(pinfo->tx_nrfifos *
pinfo->tx_fifosize), (void __force *)pinfo->mem_addr,
pinfo->dma_addr);
cpm_dpfree(pinfo->dp_addr);
}
| gpl-2.0 |
nunogil/lge-kernel-sniper | drivers/uwb/drp-ie.c | 11529 | 9767 | /*
* UWB DRP IE management.
*
* Copyright (C) 2005-2006 Intel Corporation
* Copyright (C) 2008 Cambridge Silicon Radio Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/kernel.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/uwb.h>
#include "uwb-internal.h"
/*
* Return the reason code for a reservations's DRP IE.
*/
int uwb_rsv_reason_code(struct uwb_rsv *rsv)
{
static const int reason_codes[] = {
[UWB_RSV_STATE_O_INITIATED] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_O_PENDING] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_O_MODIFIED] = UWB_DRP_REASON_MODIFIED,
[UWB_RSV_STATE_O_ESTABLISHED] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_O_TO_BE_MOVED] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_O_MOVE_COMBINING] = UWB_DRP_REASON_MODIFIED,
[UWB_RSV_STATE_O_MOVE_REDUCING] = UWB_DRP_REASON_MODIFIED,
[UWB_RSV_STATE_O_MOVE_EXPANDING] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_T_ACCEPTED] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_T_CONFLICT] = UWB_DRP_REASON_CONFLICT,
[UWB_RSV_STATE_T_PENDING] = UWB_DRP_REASON_PENDING,
[UWB_RSV_STATE_T_DENIED] = UWB_DRP_REASON_DENIED,
[UWB_RSV_STATE_T_RESIZED] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_T_EXPANDING_CONFLICT] = UWB_DRP_REASON_CONFLICT,
[UWB_RSV_STATE_T_EXPANDING_PENDING] = UWB_DRP_REASON_PENDING,
[UWB_RSV_STATE_T_EXPANDING_DENIED] = UWB_DRP_REASON_DENIED,
};
return reason_codes[rsv->state];
}
/*
* Return the reason code for a reservations's companion DRP IE .
*/
int uwb_rsv_companion_reason_code(struct uwb_rsv *rsv)
{
static const int companion_reason_codes[] = {
[UWB_RSV_STATE_O_MOVE_EXPANDING] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = UWB_DRP_REASON_ACCEPTED,
[UWB_RSV_STATE_T_EXPANDING_CONFLICT] = UWB_DRP_REASON_CONFLICT,
[UWB_RSV_STATE_T_EXPANDING_PENDING] = UWB_DRP_REASON_PENDING,
[UWB_RSV_STATE_T_EXPANDING_DENIED] = UWB_DRP_REASON_DENIED,
};
return companion_reason_codes[rsv->state];
}
/*
* Return the status bit for a reservations's DRP IE.
*/
int uwb_rsv_status(struct uwb_rsv *rsv)
{
static const int statuses[] = {
[UWB_RSV_STATE_O_INITIATED] = 0,
[UWB_RSV_STATE_O_PENDING] = 0,
[UWB_RSV_STATE_O_MODIFIED] = 1,
[UWB_RSV_STATE_O_ESTABLISHED] = 1,
[UWB_RSV_STATE_O_TO_BE_MOVED] = 0,
[UWB_RSV_STATE_O_MOVE_COMBINING] = 1,
[UWB_RSV_STATE_O_MOVE_REDUCING] = 1,
[UWB_RSV_STATE_O_MOVE_EXPANDING] = 1,
[UWB_RSV_STATE_T_ACCEPTED] = 1,
[UWB_RSV_STATE_T_CONFLICT] = 0,
[UWB_RSV_STATE_T_PENDING] = 0,
[UWB_RSV_STATE_T_DENIED] = 0,
[UWB_RSV_STATE_T_RESIZED] = 1,
[UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = 1,
[UWB_RSV_STATE_T_EXPANDING_CONFLICT] = 1,
[UWB_RSV_STATE_T_EXPANDING_PENDING] = 1,
[UWB_RSV_STATE_T_EXPANDING_DENIED] = 1,
};
return statuses[rsv->state];
}
/*
* Return the status bit for a reservations's companion DRP IE .
*/
int uwb_rsv_companion_status(struct uwb_rsv *rsv)
{
static const int companion_statuses[] = {
[UWB_RSV_STATE_O_MOVE_EXPANDING] = 0,
[UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = 1,
[UWB_RSV_STATE_T_EXPANDING_CONFLICT] = 0,
[UWB_RSV_STATE_T_EXPANDING_PENDING] = 0,
[UWB_RSV_STATE_T_EXPANDING_DENIED] = 0,
};
return companion_statuses[rsv->state];
}
/*
* Allocate a DRP IE.
*
* To save having to free/allocate a DRP IE when its MAS changes,
* enough memory is allocated for the maxiumum number of DRP
* allocation fields. This gives an overhead per reservation of up to
* (UWB_NUM_ZONES - 1) * 4 = 60 octets.
*/
static struct uwb_ie_drp *uwb_drp_ie_alloc(void)
{
struct uwb_ie_drp *drp_ie;
drp_ie = kzalloc(sizeof(struct uwb_ie_drp) +
UWB_NUM_ZONES * sizeof(struct uwb_drp_alloc),
GFP_KERNEL);
if (drp_ie) {
drp_ie->hdr.element_id = UWB_IE_DRP;
}
return drp_ie;
}
/*
* Fill a DRP IE's allocation fields from a MAS bitmap.
*/
static void uwb_drp_ie_from_bm(struct uwb_ie_drp *drp_ie,
struct uwb_mas_bm *mas)
{
int z, i, num_fields = 0, next = 0;
struct uwb_drp_alloc *zones;
__le16 current_bmp;
DECLARE_BITMAP(tmp_bmp, UWB_NUM_MAS);
DECLARE_BITMAP(tmp_mas_bm, UWB_MAS_PER_ZONE);
zones = drp_ie->allocs;
bitmap_copy(tmp_bmp, mas->bm, UWB_NUM_MAS);
/* Determine unique MAS bitmaps in zones from bitmap. */
for (z = 0; z < UWB_NUM_ZONES; z++) {
bitmap_copy(tmp_mas_bm, tmp_bmp, UWB_MAS_PER_ZONE);
if (bitmap_weight(tmp_mas_bm, UWB_MAS_PER_ZONE) > 0) {
bool found = false;
current_bmp = (__le16) *tmp_mas_bm;
for (i = 0; i < next; i++) {
if (current_bmp == zones[i].mas_bm) {
zones[i].zone_bm |= 1 << z;
found = true;
break;
}
}
if (!found) {
num_fields++;
zones[next].zone_bm = 1 << z;
zones[next].mas_bm = current_bmp;
next++;
}
}
bitmap_shift_right(tmp_bmp, tmp_bmp, UWB_MAS_PER_ZONE, UWB_NUM_MAS);
}
/* Store in format ready for transmission (le16). */
for (i = 0; i < num_fields; i++) {
drp_ie->allocs[i].zone_bm = cpu_to_le16(zones[i].zone_bm);
drp_ie->allocs[i].mas_bm = cpu_to_le16(zones[i].mas_bm);
}
drp_ie->hdr.length = sizeof(struct uwb_ie_drp) - sizeof(struct uwb_ie_hdr)
+ num_fields * sizeof(struct uwb_drp_alloc);
}
/**
* uwb_drp_ie_update - update a reservation's DRP IE
* @rsv: the reservation
*/
int uwb_drp_ie_update(struct uwb_rsv *rsv)
{
struct uwb_ie_drp *drp_ie;
struct uwb_rsv_move *mv;
int unsafe;
if (rsv->state == UWB_RSV_STATE_NONE) {
kfree(rsv->drp_ie);
rsv->drp_ie = NULL;
return 0;
}
unsafe = rsv->mas.unsafe ? 1 : 0;
if (rsv->drp_ie == NULL) {
rsv->drp_ie = uwb_drp_ie_alloc();
if (rsv->drp_ie == NULL)
return -ENOMEM;
}
drp_ie = rsv->drp_ie;
uwb_ie_drp_set_unsafe(drp_ie, unsafe);
uwb_ie_drp_set_tiebreaker(drp_ie, rsv->tiebreaker);
uwb_ie_drp_set_owner(drp_ie, uwb_rsv_is_owner(rsv));
uwb_ie_drp_set_status(drp_ie, uwb_rsv_status(rsv));
uwb_ie_drp_set_reason_code(drp_ie, uwb_rsv_reason_code(rsv));
uwb_ie_drp_set_stream_index(drp_ie, rsv->stream);
uwb_ie_drp_set_type(drp_ie, rsv->type);
if (uwb_rsv_is_owner(rsv)) {
switch (rsv->target.type) {
case UWB_RSV_TARGET_DEV:
drp_ie->dev_addr = rsv->target.dev->dev_addr;
break;
case UWB_RSV_TARGET_DEVADDR:
drp_ie->dev_addr = rsv->target.devaddr;
break;
}
} else
drp_ie->dev_addr = rsv->owner->dev_addr;
uwb_drp_ie_from_bm(drp_ie, &rsv->mas);
if (uwb_rsv_has_two_drp_ies(rsv)) {
mv = &rsv->mv;
if (mv->companion_drp_ie == NULL) {
mv->companion_drp_ie = uwb_drp_ie_alloc();
if (mv->companion_drp_ie == NULL)
return -ENOMEM;
}
drp_ie = mv->companion_drp_ie;
/* keep all the same configuration of the main drp_ie */
memcpy(drp_ie, rsv->drp_ie, sizeof(struct uwb_ie_drp));
/* FIXME: handle properly the unsafe bit */
uwb_ie_drp_set_unsafe(drp_ie, 1);
uwb_ie_drp_set_status(drp_ie, uwb_rsv_companion_status(rsv));
uwb_ie_drp_set_reason_code(drp_ie, uwb_rsv_companion_reason_code(rsv));
uwb_drp_ie_from_bm(drp_ie, &mv->companion_mas);
}
rsv->ie_valid = true;
return 0;
}
/*
* Set MAS bits from given MAS bitmap in a single zone of large bitmap.
*
* We are given a zone id and the MAS bitmap of bits that need to be set in
* this zone. Note that this zone may already have bits set and this only
* adds settings - we cannot simply assign the MAS bitmap contents to the
* zone contents. We iterate over the the bits (MAS) in the zone and set the
* bits that are set in the given MAS bitmap.
*/
static
void uwb_drp_ie_single_zone_to_bm(struct uwb_mas_bm *bm, u8 zone, u16 mas_bm)
{
int mas;
u16 mas_mask;
for (mas = 0; mas < UWB_MAS_PER_ZONE; mas++) {
mas_mask = 1 << mas;
if (mas_bm & mas_mask)
set_bit(zone * UWB_NUM_ZONES + mas, bm->bm);
}
}
/**
* uwb_drp_ie_zones_to_bm - convert DRP allocation fields to a bitmap
* @mas: MAS bitmap that will be populated to correspond to the
* allocation fields in the DRP IE
* @drp_ie: the DRP IE that contains the allocation fields.
*
* The input format is an array of MAS allocation fields (16 bit Zone
* bitmap, 16 bit MAS bitmap) as described in [ECMA-368] section
* 16.8.6. The output is a full 256 bit MAS bitmap.
*
* We go over all the allocation fields, for each allocation field we
* know which zones are impacted. We iterate over all the zones
* impacted and call a function that will set the correct MAS bits in
* each zone.
*/
void uwb_drp_ie_to_bm(struct uwb_mas_bm *bm, const struct uwb_ie_drp *drp_ie)
{
int numallocs = (drp_ie->hdr.length - 4) / 4;
const struct uwb_drp_alloc *alloc;
int cnt;
u16 zone_bm, mas_bm;
u8 zone;
u16 zone_mask;
bitmap_zero(bm->bm, UWB_NUM_MAS);
for (cnt = 0; cnt < numallocs; cnt++) {
alloc = &drp_ie->allocs[cnt];
zone_bm = le16_to_cpu(alloc->zone_bm);
mas_bm = le16_to_cpu(alloc->mas_bm);
for (zone = 0; zone < UWB_NUM_ZONES; zone++) {
zone_mask = 1 << zone;
if (zone_bm & zone_mask)
uwb_drp_ie_single_zone_to_bm(bm, zone, mas_bm);
}
}
}
| gpl-2.0 |
jiwanlimbu/ceph-client | drivers/tty/hvc/hvc_bfin_jtag.c | 12809 | 2284 | /*
* Console via Blackfin JTAG Communication
*
* Copyright 2008-2011 Analog Devices Inc.
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
#include <linux/console.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include "hvc_console.h"
/* See the Debug/Emulation chapter in the HRM */
#define EMUDOF 0x00000001 /* EMUDAT_OUT full & valid */
#define EMUDIF 0x00000002 /* EMUDAT_IN full & valid */
#define EMUDOOVF 0x00000004 /* EMUDAT_OUT overflow */
#define EMUDIOVF 0x00000008 /* EMUDAT_IN overflow */
/* Helper functions to glue the register API to simple C operations */
static inline uint32_t bfin_write_emudat(uint32_t emudat)
{
__asm__ __volatile__("emudat = %0;" : : "d"(emudat));
return emudat;
}
static inline uint32_t bfin_read_emudat(void)
{
uint32_t emudat;
__asm__ __volatile__("%0 = emudat;" : "=d"(emudat));
return emudat;
}
/* Send data to the host */
static int hvc_bfin_put_chars(uint32_t vt, const char *buf, int count)
{
static uint32_t outbound_len;
uint32_t emudat;
int ret;
if (bfin_read_DBGSTAT() & EMUDOF)
return 0;
if (!outbound_len) {
outbound_len = count;
bfin_write_emudat(outbound_len);
return 0;
}
ret = min(outbound_len, (uint32_t)4);
memcpy(&emudat, buf, ret);
bfin_write_emudat(emudat);
outbound_len -= ret;
return ret;
}
/* Receive data from the host */
static int hvc_bfin_get_chars(uint32_t vt, char *buf, int count)
{
static uint32_t inbound_len;
uint32_t emudat;
int ret;
if (!(bfin_read_DBGSTAT() & EMUDIF))
return 0;
emudat = bfin_read_emudat();
if (!inbound_len) {
inbound_len = emudat;
return 0;
}
ret = min(inbound_len, (uint32_t)4);
memcpy(buf, &emudat, ret);
inbound_len -= ret;
return ret;
}
/* Glue the HVC layers to the Blackfin layers */
static const struct hv_ops hvc_bfin_get_put_ops = {
.get_chars = hvc_bfin_get_chars,
.put_chars = hvc_bfin_put_chars,
};
static int __init hvc_bfin_console_init(void)
{
hvc_instantiate(0, 0, &hvc_bfin_get_put_ops);
return 0;
}
console_initcall(hvc_bfin_console_init);
static int __init hvc_bfin_init(void)
{
hvc_alloc(0, 0, &hvc_bfin_get_put_ops, 128);
return 0;
}
device_initcall(hvc_bfin_init);
| gpl-2.0 |
weizhenwei/mi1_kernel | net/bridge/netfilter/ebt_ip.c | 13577 | 3302 | /*
* ebt_ip
*
* Authors:
* Bart De Schuymer <bdschuym@pandora.be>
*
* April, 2002
*
* Changes:
* added ip-sport and ip-dport
* Innominate Security Technologies AG <mhopf@innominate.com>
* September, 2002
*/
#include <linux/ip.h>
#include <net/ip.h>
#include <linux/in.h>
#include <linux/module.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_bridge/ebtables.h>
#include <linux/netfilter_bridge/ebt_ip.h>
struct tcpudphdr {
__be16 src;
__be16 dst;
};
static bool
ebt_ip_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct ebt_ip_info *info = par->matchinfo;
const struct iphdr *ih;
struct iphdr _iph;
const struct tcpudphdr *pptr;
struct tcpudphdr _ports;
ih = skb_header_pointer(skb, 0, sizeof(_iph), &_iph);
if (ih == NULL)
return false;
if (info->bitmask & EBT_IP_TOS &&
FWINV(info->tos != ih->tos, EBT_IP_TOS))
return false;
if (info->bitmask & EBT_IP_SOURCE &&
FWINV((ih->saddr & info->smsk) !=
info->saddr, EBT_IP_SOURCE))
return false;
if ((info->bitmask & EBT_IP_DEST) &&
FWINV((ih->daddr & info->dmsk) !=
info->daddr, EBT_IP_DEST))
return false;
if (info->bitmask & EBT_IP_PROTO) {
if (FWINV(info->protocol != ih->protocol, EBT_IP_PROTO))
return false;
if (!(info->bitmask & EBT_IP_DPORT) &&
!(info->bitmask & EBT_IP_SPORT))
return true;
if (ntohs(ih->frag_off) & IP_OFFSET)
return false;
pptr = skb_header_pointer(skb, ih->ihl*4,
sizeof(_ports), &_ports);
if (pptr == NULL)
return false;
if (info->bitmask & EBT_IP_DPORT) {
u32 dst = ntohs(pptr->dst);
if (FWINV(dst < info->dport[0] ||
dst > info->dport[1],
EBT_IP_DPORT))
return false;
}
if (info->bitmask & EBT_IP_SPORT) {
u32 src = ntohs(pptr->src);
if (FWINV(src < info->sport[0] ||
src > info->sport[1],
EBT_IP_SPORT))
return false;
}
}
return true;
}
static int ebt_ip_mt_check(const struct xt_mtchk_param *par)
{
const struct ebt_ip_info *info = par->matchinfo;
const struct ebt_entry *e = par->entryinfo;
if (e->ethproto != htons(ETH_P_IP) ||
e->invflags & EBT_IPROTO)
return -EINVAL;
if (info->bitmask & ~EBT_IP_MASK || info->invflags & ~EBT_IP_MASK)
return -EINVAL;
if (info->bitmask & (EBT_IP_DPORT | EBT_IP_SPORT)) {
if (info->invflags & EBT_IP_PROTO)
return -EINVAL;
if (info->protocol != IPPROTO_TCP &&
info->protocol != IPPROTO_UDP &&
info->protocol != IPPROTO_UDPLITE &&
info->protocol != IPPROTO_SCTP &&
info->protocol != IPPROTO_DCCP)
return -EINVAL;
}
if (info->bitmask & EBT_IP_DPORT && info->dport[0] > info->dport[1])
return -EINVAL;
if (info->bitmask & EBT_IP_SPORT && info->sport[0] > info->sport[1])
return -EINVAL;
return 0;
}
static struct xt_match ebt_ip_mt_reg __read_mostly = {
.name = "ip",
.revision = 0,
.family = NFPROTO_BRIDGE,
.match = ebt_ip_mt,
.checkentry = ebt_ip_mt_check,
.matchsize = sizeof(struct ebt_ip_info),
.me = THIS_MODULE,
};
static int __init ebt_ip_init(void)
{
return xt_register_match(&ebt_ip_mt_reg);
}
static void __exit ebt_ip_fini(void)
{
xt_unregister_match(&ebt_ip_mt_reg);
}
module_init(ebt_ip_init);
module_exit(ebt_ip_fini);
MODULE_DESCRIPTION("Ebtables: IPv4 protocol packet match");
MODULE_LICENSE("GPL");
| gpl-2.0 |
StreamUtils/gst-plugins-bad | tests/check/elements/avwait.c | 10 | 14094 | /* GStreamer unit test for avwait
*
* Copyright (C) 2018 Vivia Nikolaidou <vivia@toolsonair.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/check/gstcheck.h>
#include <gst/audio/audio.h>
#include <gst/video/video.h>
typedef enum _SwitchType
{
DO_NOT_SWITCH = -1,
SWITCH_FALSE = 0,
SWITCH_TRUE = 1
} SwitchType;
static guint audio_buffer_count, video_buffer_count;
static SwitchType switch_after_2s;
static GstVideoTimeCode *target_tc;
static GstVideoTimeCode *end_tc;
static GstClockTime target_running_time;
static gboolean recording;
static gint mode;
static gboolean audio_late;
static GstAudioInfo ainfo;
static guint n_abuffers, n_vbuffers;
static GstClockTime first_audio_timestamp, last_audio_timestamp;
static GstClockTime first_video_timestamp, last_video_timestamp;
typedef struct _ElementPadAndSwitchType
{
GstElement *element;
GstPad *pad;
SwitchType switch_after_2s;
} ElementPadAndSwitchType;
typedef struct _PadAndBoolean
{
GstPad *pad;
gboolean b;
} PadAndBoolean;
static void
set_default_params (void)
{
n_abuffers = 16;
n_vbuffers = 160;
switch_after_2s = DO_NOT_SWITCH;
target_tc = NULL;
end_tc = NULL;
target_running_time = GST_CLOCK_TIME_NONE;
recording = TRUE;
mode = 2;
audio_late = FALSE;
first_audio_timestamp = GST_CLOCK_TIME_NONE;
last_audio_timestamp = GST_CLOCK_TIME_NONE;
first_video_timestamp = GST_CLOCK_TIME_NONE;
last_video_timestamp = GST_CLOCK_TIME_NONE;
};
static GstFlowReturn
output_achain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
{
GstClockTime timestamp, duration;
timestamp = GST_BUFFER_TIMESTAMP (buffer);
duration =
gst_util_uint64_scale (gst_buffer_get_size (buffer) / ainfo.bpf,
GST_SECOND, ainfo.rate);
if (first_audio_timestamp == GST_CLOCK_TIME_NONE)
first_audio_timestamp = timestamp;
last_audio_timestamp = timestamp + duration;
audio_buffer_count++;
gst_buffer_unref (buffer);
return GST_FLOW_OK;
}
static GstFlowReturn
output_vchain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
{
GstClockTime timestamp;
timestamp = GST_BUFFER_TIMESTAMP (buffer);
if (first_video_timestamp == GST_CLOCK_TIME_NONE)
first_video_timestamp = timestamp;
last_video_timestamp = timestamp + GST_BUFFER_DURATION (buffer);
video_buffer_count++;
gst_buffer_unref (buffer);
return GST_FLOW_OK;
}
static gpointer
push_abuffers (gpointer data)
{
GstSegment segment;
gint i;
GstCaps *caps;
guint buf_size = 1000;
guint channels = 2;
PadAndBoolean *e = data;
GstPad *pad = e->pad;
gboolean audio_late = e->b;
GstClockTime timestamp;
if (audio_late) {
timestamp = 50 * GST_MSECOND;
} else {
timestamp = 0;
}
gst_pad_send_event (pad, gst_event_new_stream_start ("test"));
gst_audio_info_set_format (&ainfo, GST_AUDIO_FORMAT_S8, buf_size, channels,
NULL);
caps = gst_audio_info_to_caps (&ainfo);
gst_pad_send_event (pad, gst_event_new_caps (caps));
gst_caps_unref (caps);
gst_segment_init (&segment, GST_FORMAT_TIME);
gst_pad_send_event (pad, gst_event_new_segment (&segment));
for (i = 0; i < n_abuffers; i++) {
GstBuffer *buf = gst_buffer_new_and_alloc (channels * buf_size);
gst_buffer_memset (buf, 0, 0, channels * buf_size);
GST_BUFFER_TIMESTAMP (buf) = timestamp;
timestamp += 1 * GST_SECOND;
GST_BUFFER_DURATION (buf) = timestamp - GST_BUFFER_TIMESTAMP (buf);
fail_unless (gst_pad_chain (pad, buf) == GST_FLOW_OK);
}
gst_pad_send_event (pad, gst_event_new_eos ());
return NULL;
}
static gpointer
push_vbuffers (gpointer data)
{
GstSegment segment;
ElementPadAndSwitchType *e = data;
GstPad *pad = e->pad;
gint i;
GstClockTime timestamp = 0;
GstVideoTimeCode *tc;
gst_pad_send_event (pad, gst_event_new_stream_start ("test"));
gst_segment_init (&segment, GST_FORMAT_TIME);
gst_pad_send_event (pad, gst_event_new_segment (&segment));
tc = gst_video_time_code_new (40, 1, NULL, GST_VIDEO_TIME_CODE_FLAGS_NONE, 0,
0, 0, 0, 0);
for (i = 0; i < n_vbuffers; i++) {
GstBuffer *buf = gst_buffer_new_and_alloc (1000);
gst_buffer_memset (buf, 0, i, 1);
GST_BUFFER_TIMESTAMP (buf) = timestamp;
timestamp += 25 * GST_MSECOND;
GST_BUFFER_DURATION (buf) = timestamp - GST_BUFFER_TIMESTAMP (buf);
gst_buffer_add_video_time_code_meta (buf, tc);
gst_video_time_code_increment_frame (tc);
fail_unless (gst_pad_chain (pad, buf) == GST_FLOW_OK);
if (timestamp == 2 * GST_SECOND && e->switch_after_2s != DO_NOT_SWITCH) {
g_object_set (e->element, "recording", ! !e->switch_after_2s, NULL);
}
}
gst_pad_send_event (pad, gst_event_new_eos ());
gst_video_time_code_free (tc);
return NULL;
}
static void
test_avwait_generic (void)
{
GstElement *avwait;
GstPad *asink, *vsink, *asrc, *vsrc, *aoutput_sink, *voutput_sink;
GThread *athread, *vthread;
GstBus *bus;
ElementPadAndSwitchType *e;
PadAndBoolean *pb;
audio_buffer_count = 0;
video_buffer_count = 0;
avwait = gst_element_factory_make ("avwait", NULL);
fail_unless (avwait != NULL);
g_object_set (avwait, "mode", mode,
"target-running-time", target_running_time, "recording", recording, NULL);
if (target_tc != NULL)
g_object_set (avwait, "target-timecode", target_tc, NULL);
if (end_tc != NULL)
g_object_set (avwait, "end-timecode", end_tc, NULL);
bus = gst_bus_new ();
gst_element_set_bus (avwait, bus);
asink = gst_element_get_static_pad (avwait, "asink");
fail_unless (asink != NULL);
vsink = gst_element_get_static_pad (avwait, "vsink");
fail_unless (vsink != NULL);
asrc = gst_element_get_static_pad (avwait, "asrc");
aoutput_sink = gst_pad_new ("sink", GST_PAD_SINK);
fail_unless (aoutput_sink != NULL);
fail_unless (gst_pad_link (asrc, aoutput_sink) == GST_PAD_LINK_OK);
vsrc = gst_element_get_static_pad (avwait, "vsrc");
voutput_sink = gst_pad_new ("sink", GST_PAD_SINK);
fail_unless (voutput_sink != NULL);
fail_unless (gst_pad_link (vsrc, voutput_sink) == GST_PAD_LINK_OK);
gst_pad_set_chain_function (aoutput_sink, output_achain);
gst_pad_set_chain_function (voutput_sink, output_vchain);
gst_pad_set_active (aoutput_sink, TRUE);
gst_pad_set_active (voutput_sink, TRUE);
fail_unless (gst_element_set_state (avwait,
GST_STATE_PLAYING) == GST_STATE_CHANGE_SUCCESS);
e = g_new0 (ElementPadAndSwitchType, 1);
e->element = avwait;
e->pad = vsink;
e->switch_after_2s = switch_after_2s;
pb = g_new0 (PadAndBoolean, 1);
pb->pad = asink;
pb->b = audio_late;
athread = g_thread_new ("athread", (GThreadFunc) push_abuffers, pb);
vthread = g_thread_new ("vthread", (GThreadFunc) push_vbuffers, e);
g_thread_join (vthread);
g_thread_join (athread);
/* teardown */
gst_element_set_state (avwait, GST_STATE_NULL);
gst_bus_set_flushing (bus, TRUE);
gst_object_unref (bus);
g_free (e);
g_free (pb);
gst_pad_unlink (asrc, aoutput_sink);
gst_object_unref (asrc);
gst_pad_unlink (vsrc, voutput_sink);
gst_object_unref (vsrc);
gst_object_unref (asink);
gst_object_unref (vsink);
gst_pad_set_active (aoutput_sink, FALSE);
gst_object_unref (aoutput_sink);
gst_pad_set_active (voutput_sink, FALSE);
gst_object_unref (voutput_sink);
gst_object_unref (avwait);
}
GST_START_TEST (test_avwait_switch_to_true)
{
set_default_params ();
recording = FALSE;
switch_after_2s = SWITCH_TRUE;
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 2 * GST_SECOND);
fail_unless_equals_uint64 (first_video_timestamp, 2 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_switch_to_false)
{
set_default_params ();
recording = TRUE;
switch_after_2s = SWITCH_FALSE;
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, first_video_timestamp);
fail_unless_equals_uint64 (first_video_timestamp, 0);
fail_unless_equals_uint64 (last_video_timestamp, 2 * GST_SECOND);
fail_unless_equals_uint64 (last_audio_timestamp, 2 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_1s_switch_to_true)
{
set_default_params ();
recording = FALSE;
switch_after_2s = SWITCH_TRUE;
mode = 1;
target_running_time = 1 * GST_SECOND;
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 2 * GST_SECOND);
fail_unless_equals_uint64 (first_video_timestamp, 2 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_1s_switch_to_false)
{
set_default_params ();
recording = TRUE;
switch_after_2s = SWITCH_FALSE;
mode = 1;
target_running_time = 1 * GST_SECOND;
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 1 * GST_SECOND);
fail_unless_equals_uint64 (first_video_timestamp, 1 * GST_SECOND);
fail_unless_equals_uint64 (last_video_timestamp, 2 * GST_SECOND);
fail_unless_equals_uint64 (last_audio_timestamp, 2 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_3s_switch_to_true)
{
set_default_params ();
recording = FALSE;
switch_after_2s = SWITCH_TRUE;
mode = 1;
target_running_time = 3 * GST_SECOND;
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 3 * GST_SECOND);
fail_unless_equals_uint64 (first_video_timestamp, 3 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_3s_switch_to_false)
{
set_default_params ();
recording = TRUE;
switch_after_2s = SWITCH_FALSE;
mode = 1;
target_running_time = 3 * GST_SECOND;
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, GST_CLOCK_TIME_NONE);
fail_unless_equals_uint64 (first_video_timestamp, GST_CLOCK_TIME_NONE);
fail_unless_equals_uint64 (last_audio_timestamp, GST_CLOCK_TIME_NONE);
fail_unless_equals_uint64 (last_video_timestamp, GST_CLOCK_TIME_NONE);
}
GST_END_TEST;
GST_START_TEST (test_avwait_1stc_switch_to_true)
{
set_default_params ();
recording = FALSE;
switch_after_2s = SWITCH_TRUE;
mode = 0;
target_tc =
gst_video_time_code_new (40, 1, NULL, GST_VIDEO_TIME_CODE_FLAGS_NONE, 0,
0, 1, 0, 0);
end_tc =
gst_video_time_code_new (40, 1, NULL, GST_VIDEO_TIME_CODE_FLAGS_NONE, 0,
0, 3, 0, 0);
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 2 * GST_SECOND);
fail_unless_equals_uint64 (first_video_timestamp, 2 * GST_SECOND);
fail_unless_equals_uint64 (last_video_timestamp, 3 * GST_SECOND);
fail_unless_equals_uint64 (last_audio_timestamp, 3 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_1stc_switch_to_false)
{
set_default_params ();
recording = TRUE;
switch_after_2s = SWITCH_FALSE;
mode = 0;
target_tc =
gst_video_time_code_new (40, 1, NULL, GST_VIDEO_TIME_CODE_FLAGS_NONE, 0,
0, 1, 0, 0);
end_tc =
gst_video_time_code_new (40, 1, NULL, GST_VIDEO_TIME_CODE_FLAGS_NONE, 0,
0, 3, 0, 0);
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 1 * GST_SECOND);
fail_unless_equals_uint64 (first_video_timestamp, 1 * GST_SECOND);
fail_unless_equals_uint64 (last_video_timestamp, 2 * GST_SECOND);
fail_unless_equals_uint64 (last_audio_timestamp, 2 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_3stc_switch_to_true)
{
set_default_params ();
recording = FALSE;
switch_after_2s = SWITCH_TRUE;
mode = 0;
target_tc =
gst_video_time_code_new (40, 1, NULL, GST_VIDEO_TIME_CODE_FLAGS_NONE, 0,
0, 3, 0, 0);
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 3 * GST_SECOND);
fail_unless_equals_uint64 (first_video_timestamp, 3 * GST_SECOND);
}
GST_END_TEST;
GST_START_TEST (test_avwait_3stc_switch_to_false)
{
set_default_params ();
recording = TRUE;
switch_after_2s = SWITCH_FALSE;
mode = 0;
target_tc =
gst_video_time_code_new (40, 1, NULL, GST_VIDEO_TIME_CODE_FLAGS_NONE, 0,
0, 3, 0, 0);
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, GST_CLOCK_TIME_NONE);
fail_unless_equals_uint64 (first_video_timestamp, GST_CLOCK_TIME_NONE);
fail_unless_equals_uint64 (last_audio_timestamp, GST_CLOCK_TIME_NONE);
fail_unless_equals_uint64 (last_video_timestamp, GST_CLOCK_TIME_NONE);
}
GST_END_TEST;
GST_START_TEST (test_avwait_audio_late)
{
set_default_params ();
recording = TRUE;
audio_late = TRUE;
test_avwait_generic ();
fail_unless_equals_uint64 (first_audio_timestamp, 50 * GST_MSECOND);
fail_unless_equals_uint64 (first_video_timestamp, 50 * GST_MSECOND);
}
GST_END_TEST;
static Suite *
avwait_suite (void)
{
Suite *s = suite_create ("avwait");
TCase *tc_chain;
tc_chain = tcase_create ("avwait");
tcase_add_test (tc_chain, test_avwait_switch_to_true);
tcase_add_test (tc_chain, test_avwait_switch_to_false);
tcase_add_test (tc_chain, test_avwait_1s_switch_to_true);
tcase_add_test (tc_chain, test_avwait_1s_switch_to_false);
tcase_add_test (tc_chain, test_avwait_3s_switch_to_true);
tcase_add_test (tc_chain, test_avwait_3s_switch_to_false);
tcase_add_test (tc_chain, test_avwait_1stc_switch_to_true);
tcase_add_test (tc_chain, test_avwait_1stc_switch_to_false);
tcase_add_test (tc_chain, test_avwait_3stc_switch_to_true);
tcase_add_test (tc_chain, test_avwait_3stc_switch_to_false);
tcase_add_test (tc_chain, test_avwait_audio_late);
suite_add_tcase (s, tc_chain);
return s;
}
GST_CHECK_MAIN (avwait);
| gpl-2.0 |
PaulMilbank/g300_kernel | drivers/video/msm/mdp4_overlay_mddi.c | 10 | 17611 | /* 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.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/hrtimer.h>
#include <linux/delay.h>
#include <mach/hardware.h>
#include <linux/io.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <linux/semaphore.h>
#include <linux/spinlock.h>
#include <linux/fb.h>
#include "mdp.h"
#include "msm_fb.h"
#include "mdp4.h"
#ifdef CONFIG_HUAWEI_KERNEL
#include <linux/hardware_self_adapt.h>
#endif
static struct mdp4_overlay_pipe *mddi_pipe;
static struct msm_fb_data_type *mddi_mfd;
static int busy_wait_cnt;
static int vsync_start_y_adjust = 4;
static int dmap_vsync_enable;
void mdp_dmap_vsync_set(int enable)
{
dmap_vsync_enable = enable;
}
int mdp_dmap_vsync_get(void)
{
return dmap_vsync_enable;
}
void mdp4_mddi_vsync_enable(struct msm_fb_data_type *mfd,
struct mdp4_overlay_pipe *pipe, int which)
{
uint32 start_y, data, tear_en;
tear_en = (1 << which);
if ((mfd->use_mdp_vsync) && (mfd->ibuf.vsync_enable) &&
(mfd->panel_info.lcd.vsync_enable)) {
if (mdp_hw_revision < MDP4_REVISION_V2_1) {
/* need dmas dmap switch */
if (which == 0 && dmap_vsync_enable == 0 &&
mfd->panel_info.lcd.rev < 2) /* dma_p */
return;
}
if (vsync_start_y_adjust <= pipe->dst_y)
start_y = pipe->dst_y - vsync_start_y_adjust;
else
start_y = (mfd->total_lcd_lines - 1) -
(vsync_start_y_adjust - pipe->dst_y);
if (which == 0)
MDP_OUTP(MDP_BASE + 0x210, start_y); /* primary */
else
MDP_OUTP(MDP_BASE + 0x214, start_y); /* secondary */
data = inpdw(MDP_BASE + 0x20c);
data |= tear_en;
MDP_OUTP(MDP_BASE + 0x20c, data);
} else {
data = inpdw(MDP_BASE + 0x20c);
data &= ~tear_en;
MDP_OUTP(MDP_BASE + 0x20c, data);
}
}
/* Config MDP reg according bpp ,the interface for
* dma_s pipe or dma_p(overlay) pipe.
*/
#ifdef CONFIG_FB_MSM_BPP_SWITCH
void mdp4_dma_s_update_lcd(struct msm_fb_data_type *mfd,
struct mdp4_overlay_pipe *pipe);
void mdp4_switch_bpp_config(struct msm_fb_data_type *mfd,uint32 bpp)
{
uint32 mddi_ld_param;
uint16 mddi_vdo_packet_reg;
mfd->panel_info.bpp = bpp;
printk(KERN_ERR "%s: switch bpp into %d\n", __func__,bpp);
if(24 == bpp)
{
mdp4_dma_s_update_lcd(mfd,mddi_pipe);
}
else if (16 == bpp)
{
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mddi_ld_param = 0;
mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt;
if (mfd->panel_info.type == MDDI_PANEL) {
if (mfd->panel_info.pdest == DISPLAY_1)
mddi_ld_param = 0;
else
mddi_ld_param = 1;
} else {
mddi_ld_param = 2;
}
MDP_OUTP(MDP_BASE + 0x00090, mddi_ld_param);
/* config registers base on bpp(16 ,24 or other) */
if (mfd->panel_info.bpp == 24)
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC_24 << 16) | mddi_vdo_packet_reg);
else if (mfd->panel_info.bpp == 16)
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC_16 << 16) | mddi_vdo_packet_reg);
else
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg);
MDP_OUTP(MDP_BASE + 0x00098, 0x01);
mdp4_overlay_dmap_cfg(mfd, 0);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
else
return;
}
#endif
#define WHOLESCREEN
void mdp4_overlay_update_lcd(struct msm_fb_data_type *mfd)
{
MDPIBUF *iBuf = &mfd->ibuf;
uint8 *src;
int ptype;
uint32 mddi_ld_param;
uint16 mddi_vdo_packet_reg;
struct mdp4_overlay_pipe *pipe;
int ret;
if (mfd->key != MFD_KEY)
return;
mddi_mfd = mfd; /* keep it */
/* MDP cmd block enable */
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
if (mddi_pipe == NULL) {
ptype = mdp4_overlay_format2type(mfd->fb_imgType);
if (ptype < 0)
printk(KERN_INFO "%s: format2type failed\n", __func__);
pipe = mdp4_overlay_pipe_alloc(ptype, MDP4_MIXER0);
if (pipe == NULL)
printk(KERN_INFO "%s: pipe_alloc failed\n", __func__);
pipe->pipe_used++;
pipe->mixer_num = MDP4_MIXER0;
pipe->src_format = mfd->fb_imgType;
mdp4_overlay_panel_mode(pipe->mixer_num, MDP4_PANEL_MDDI);
ret = mdp4_overlay_format2pipe(pipe);
if (ret < 0)
printk(KERN_INFO "%s: format2type failed\n", __func__);
mddi_pipe = pipe; /* keep it */
mddi_pipe->blt_end = 1; /* mark as end */
mddi_ld_param = 0;
mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt;
if (mdp_hw_revision == MDP4_REVISION_V2_1) {
uint32 data;
data = inpdw(MDP_BASE + 0x0028);
data &= ~0x0300; /* bit 8, 9, MASTER4 */
if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */
data |= 0x0200;
else
data |= 0x0100;
MDP_OUTP(MDP_BASE + 0x00028, data);
}
if (mfd->panel_info.type == MDDI_PANEL) {
if (mfd->panel_info.pdest == DISPLAY_1)
mddi_ld_param = 0;
else
mddi_ld_param = 1;
} else {
mddi_ld_param = 2;
}
MDP_OUTP(MDP_BASE + 0x00090, mddi_ld_param);
if (mfd->panel_info.bpp == 24)
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC_24 << 16) | mddi_vdo_packet_reg);
else if (mfd->panel_info.bpp == 16)
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC_16 << 16) | mddi_vdo_packet_reg);
else
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg);
MDP_OUTP(MDP_BASE + 0x00098, 0x01);
} else {
pipe = mddi_pipe;
}
/* 0 for dma_p, client_id = 0 */
MDP_OUTP(MDP_BASE + 0x00090, 0);
src = (uint8 *) iBuf->buf;
#ifdef WHOLESCREEN
{
struct fb_info *fbi;
fbi = mfd->fbi;
pipe->src_height = fbi->var.yres;
pipe->src_width = fbi->var.xres;
pipe->src_h = fbi->var.yres;
pipe->src_w = fbi->var.xres;
pipe->src_y = 0;
pipe->src_x = 0;
pipe->dst_h = fbi->var.yres;
pipe->dst_w = fbi->var.xres;
/*return to the qualcomm original code */
pipe->dst_y = 0;
pipe->dst_x = 0;
pipe->srcp0_addr = (uint32)src;
pipe->srcp0_ystride = fbi->fix.line_length;
}
#else
if (mdp4_overlay_active(MDP4_MIXER0)) {
struct fb_info *fbi;
fbi = mfd->fbi;
pipe->src_height = fbi->var.yres;
pipe->src_width = fbi->var.xres;
pipe->src_h = fbi->var.yres;
pipe->src_w = fbi->var.xres;
pipe->src_y = 0;
pipe->src_x = 0;
pipe->dst_h = fbi->var.yres;
pipe->dst_w = fbi->var.xres;
pipe->dst_y = 0;
pipe->dst_x = 0;
pipe->srcp0_addr = (uint32) src;
pipe->srcp0_ystride = fbi->fix.line_length;
} else {
/* starting input address */
src += (iBuf->dma_x + iBuf->dma_y * iBuf->ibuf_width)
* iBuf->bpp;
pipe->src_height = iBuf->dma_h;
pipe->src_width = iBuf->dma_w;
pipe->src_h = iBuf->dma_h;
pipe->src_w = iBuf->dma_w;
pipe->src_y = 0;
pipe->src_x = 0;
pipe->dst_h = iBuf->dma_h;
pipe->dst_w = iBuf->dma_w;
pipe->dst_y = iBuf->dma_y;
pipe->dst_x = iBuf->dma_x;
pipe->srcp0_addr = (uint32) src;
pipe->srcp0_ystride = iBuf->ibuf_width * iBuf->bpp;
}
#endif
pipe->mixer_stage = MDP4_MIXER_STAGE_BASE;
mdp4_overlay_rgb_setup(pipe);
mdp4_mixer_stage_up(pipe);
mdp4_overlayproc_cfg(pipe);
mdp4_overlay_dmap_xy(pipe);
mdp4_overlay_dmap_cfg(mfd, 0);
mdp4_mddi_vsync_enable(mfd, pipe, 0);
/* MDP cmd block disable */
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
int mdp4_mddi_overlay_blt_offset(int *off)
{
if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* need dmas dmap switch */
if (mddi_pipe->blt_end ||
(mdp4_overlay_mixer_play(mddi_pipe->mixer_num) == 0)) {
*off = -1;
return -EINVAL;
}
} else {
/* no dmas dmap switch */
if (mddi_pipe->blt_end) {
*off = -1;
return -EINVAL;
}
}
if (mddi_pipe->blt_cnt & 0x01)
*off = mddi_pipe->src_height * mddi_pipe->src_width * 3;
else
*off = 0;
return 0;
}
void mdp4_mddi_overlay_blt(ulong addr)
{
unsigned long flag;
spin_lock_irqsave(&mdp_spin_lock, flag);
if (addr) {
mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
mdp_intr_mask |= INTR_DMA_P_DONE;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
mddi_pipe->blt_cnt = 0;
mddi_pipe->blt_end = 0;
mddi_pipe->blt_addr = addr;
} else {
mddi_pipe->blt_end = 1; /* mark as end */
}
spin_unlock_irqrestore(&mdp_spin_lock, flag);
}
void mdp4_blt_xy_update(struct mdp4_overlay_pipe *pipe)
{
uint32 off, addr;
int bpp;
char *overlay_base;
if (pipe->blt_addr == 0)
return;
#ifdef BLT_RGB565
bpp = 2; /* overlay ouput is RGB565 */
#else
bpp = 3; /* overlay ouput is RGB888 */
#endif
off = 0;
if (pipe->dmap_cnt & 0x01)
off = pipe->src_height * pipe->src_width * bpp;
addr = pipe->blt_addr + off;
/* dmap */
MDP_OUTP(MDP_BASE + 0x90008, addr);
/* overlay 0 */
overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE;/* 0x10000 */
outpdw(overlay_base + 0x000c, addr);
outpdw(overlay_base + 0x001c, addr);
}
/*
* mdp4_dmap_done_mddi: called from isr
*/
void mdp4_dma_p_done_mddi(void)
{
if (mddi_pipe->blt_end) {
mddi_pipe->blt_addr = 0;
mdp_intr_mask &= ~INTR_DMA_P_DONE;
outp32(MDP_INTR_ENABLE, mdp_intr_mask);
mdp4_overlayproc_cfg(mddi_pipe);
mdp4_overlay_dmap_xy(mddi_pipe);
}
/*
* single buffer, no need to increase
* mdd_pipe->dmap_cnt here
*/
}
/*
* mdp4_overlay0_done_mddi: called from isr
*/
void mdp4_overlay0_done_mddi(struct mdp_dma_data *dma)
{
mdp_disable_irq_nosync(MDP_OVERLAY0_TERM);
dma->busy = FALSE;
complete(&dma->comp);
mdp_pipe_ctrl(MDP_OVERLAY0_BLOCK,
MDP_BLOCK_POWER_OFF, TRUE);
if (busy_wait_cnt)
busy_wait_cnt--;
pr_debug("%s: ISR-done\n", __func__);
if (mddi_pipe->blt_addr) {
if (mddi_pipe->blt_cnt == 0) {
mdp4_overlayproc_cfg(mddi_pipe);
mdp4_overlay_dmap_xy(mddi_pipe);
mddi_pipe->ov_cnt = 0;
mddi_pipe->dmap_cnt = 0;
/* BLT start from next frame */
} else {
mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON,
FALSE);
mdp4_blt_xy_update(mddi_pipe);
outpdw(MDP_BASE + 0x000c, 0x0); /* start DMAP */
}
mddi_pipe->blt_cnt++;
mddi_pipe->ov_cnt++;
}
}
void mdp4_mddi_overlay_restore(void)
{
if (mddi_mfd == NULL)
return;
pr_debug("%s: resotre, pid=%d\n", __func__, current->pid);
if (mddi_mfd->panel_power_on == 0)
return;
if (mddi_mfd && mddi_pipe) {
mdp4_mddi_dma_busy_wait(mddi_mfd);
mdp4_overlay_update_lcd(mddi_mfd);
mdp4_mddi_overlay_kickoff(mddi_mfd, mddi_pipe);
mddi_mfd->dma_update_flag = 1;
}
if (mdp_hw_revision < MDP4_REVISION_V2_1) /* need dmas dmap switch */
mdp4_mddi_overlay_dmas_restore();
}
/*
* mdp4_mddi_cmd_dma_busy_wait: check mddi link activity
* dsi link is a shared resource and it can only be used
* while it is in idle state.
* ov_mutex need to be acquired before call this function.
*/
void mdp4_mddi_dma_busy_wait(struct msm_fb_data_type *mfd)
{
unsigned long flag;
int need_wait = 0;
pr_debug("%s: START, pid=%d\n", __func__, current->pid);
spin_lock_irqsave(&mdp_spin_lock, flag);
if (mfd->dma->busy == TRUE) {
if (busy_wait_cnt == 0)
INIT_COMPLETION(mfd->dma->comp);
busy_wait_cnt++;
need_wait++;
}
spin_unlock_irqrestore(&mdp_spin_lock, flag);
if (need_wait) {
/* wait until DMA finishes the current job */
pr_debug("%s: PENDING, pid=%d\n", __func__, current->pid);
#ifdef CONFIG_HUAWEI_KERNEL
wait_for_completion_interruptible_timeout(&mfd->dma->comp, 1 * HZ);
#else
wait_for_completion(&mfd->dma->comp);
#endif
}
pr_debug("%s: DONE, pid=%d\n", __func__, current->pid);
}
void mdp4_mddi_kickoff_video(struct msm_fb_data_type *mfd,
struct mdp4_overlay_pipe *pipe)
{
/*delete some lines*/
mdp4_mddi_overlay_kickoff(mfd, pipe);
}
void mdp4_mddi_kickoff_ui(struct msm_fb_data_type *mfd,
struct mdp4_overlay_pipe *pipe)
{
/*delete some lines*/
mdp4_mddi_overlay_kickoff(mfd, pipe);
}
void mdp4_mddi_overlay_kickoff(struct msm_fb_data_type *mfd,
struct mdp4_overlay_pipe *pipe)
{
/* use dma_p(overlay) pipe ,change bpp into 16 */
#ifdef CONFIG_FB_MSM_BPP_SWITCH
if(16 != mfd->panel_info.bpp)
{
mdp4_switch_bpp_config(mfd,16);
}
#endif
/* change mdp clk while mdp is idle` */
mdp4_set_perf_level();
if (mdp_hw_revision == MDP4_REVISION_V2_1) {
if (mdp4_overlay_status_read(MDP4_OVERLAY_TYPE_UNSET)) {
uint32 data;
data = inpdw(MDP_BASE + 0x0028);
data &= ~0x0300; /* bit 8, 9, MASTER4 */
if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */
data |= 0x0200;
else
data |= 0x0100;
MDP_OUTP(MDP_BASE + 0x00028, data);
mdp4_overlay_status_write(MDP4_OVERLAY_TYPE_UNSET,
false);
}
if (mdp4_overlay_status_read(MDP4_OVERLAY_TYPE_SET)) {
uint32 data;
data = inpdw(MDP_BASE + 0x0028);
data &= ~0x0300; /* bit 8, 9, MASTER4 */
MDP_OUTP(MDP_BASE + 0x00028, data);
mdp4_overlay_status_write(MDP4_OVERLAY_TYPE_SET, false);
}
}
mdp_enable_irq(MDP_OVERLAY0_TERM);
mfd->dma->busy = TRUE;
/* start OVERLAY pipe */
mdp_pipe_kickoff(MDP_OVERLAY0_TERM, mfd);
mdp4_stat.kickoff_ov0++;
}
void mdp4_dma_s_update_lcd(struct msm_fb_data_type *mfd,
struct mdp4_overlay_pipe *pipe)
{
MDPIBUF *iBuf = &mfd->ibuf;
uint32 outBpp = iBuf->bpp;
uint16 mddi_vdo_packet_reg;
uint32 dma_s_cfg_reg;
dma_s_cfg_reg = 0;
if (mfd->fb_imgType == MDP_RGBA_8888)
dma_s_cfg_reg |= DMA_PACK_PATTERN_BGR; /* on purpose */
else if (mfd->fb_imgType == MDP_BGR_565)
dma_s_cfg_reg |= DMA_PACK_PATTERN_BGR;
else
dma_s_cfg_reg |= DMA_PACK_PATTERN_RGB;
if (outBpp == 4)
dma_s_cfg_reg |= (1 << 26); /* xRGB8888 */
else if (outBpp == 2)
dma_s_cfg_reg |= DMA_IBUF_FORMAT_RGB565;
dma_s_cfg_reg |= DMA_DITHER_EN;
/* MDP cmd block enable */
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
/* PIXELSIZE */
MDP_OUTP(MDP_BASE + 0xa0004, (pipe->dst_h << 16 | pipe->dst_w));
MDP_OUTP(MDP_BASE + 0xa0008, pipe->srcp0_addr); /* ibuf address */
MDP_OUTP(MDP_BASE + 0xa000c, pipe->srcp0_ystride);/* ystride */
if (mfd->panel_info.bpp == 24) {
dma_s_cfg_reg |= DMA_DSTC0G_8BITS | /* 666 18BPP */
DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS;
} else if (mfd->panel_info.bpp == 18) {
dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */
DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS;
} else {
dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */
DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS;
}
MDP_OUTP(MDP_BASE + 0xa0010, (pipe->dst_y << 16) | pipe->dst_x);
/* 1 for dma_s, client_id = 0 */
MDP_OUTP(MDP_BASE + 0x00090, 1);
mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt;
if (mfd->panel_info.bpp == 24)
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC_24 << 16) | mddi_vdo_packet_reg);
else if (mfd->panel_info.bpp == 16)
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC_16 << 16) | mddi_vdo_packet_reg);
else
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg);
MDP_OUTP(MDP_BASE + 0x00098, 0x01);
MDP_OUTP(MDP_BASE + 0xa0000, dma_s_cfg_reg);
mdp4_mddi_vsync_enable(mfd, pipe, 1);
/* MDP cmd block disable */
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
}
void mdp4_mddi_dma_s_kickoff(struct msm_fb_data_type *mfd,
struct mdp4_overlay_pipe *pipe)
{
/* use dma_s pipe ,change bpp into 24 */
#ifdef CONFIG_FB_MSM_BPP_SWITCH
if(24 != mfd->panel_info.bpp)
{
mdp4_switch_bpp_config(mfd,24);
}
#endif
/* change mdp clk while mdp is idle` */
mdp4_set_perf_level();
mdp_enable_irq(MDP_DMA_S_TERM);
mfd->dma->busy = TRUE;
mfd->ibuf_flushed = TRUE;
/* start dma_s pipe */
mdp_pipe_kickoff(MDP_DMA_S_TERM, mfd);
mdp4_stat.kickoff_dmas++;
/* wait until DMA finishes the current job */
#ifdef CONFIG_HUAWEI_KERNEL
/* huawei modify */
wait_for_completion_interruptible_timeout(&mfd->dma->comp, 2 * HZ);
#else
wait_for_completion(&mfd->dma->comp);
#endif
mdp_disable_irq(MDP_DMA_S_TERM);
}
void mdp4_mddi_overlay_dmas_restore(void)
{
/* mutex held by caller */
if (mddi_mfd && mddi_pipe) {
mdp4_mddi_dma_busy_wait(mddi_mfd);
mdp4_dma_s_update_lcd(mddi_mfd, mddi_pipe);
mdp4_mddi_dma_s_kickoff(mddi_mfd, mddi_pipe);
mddi_mfd->dma_update_flag = 1;
}
}
void mdp4_mddi_overlay(struct msm_fb_data_type *mfd)
{
mutex_lock(&mfd->dma->ov_mutex);
if (mfd && mfd->panel_power_on) {
mdp4_mddi_dma_busy_wait(mfd);
mdp4_overlay_update_lcd(mfd);
if (mdp_hw_revision < MDP4_REVISION_V2_1) {
/* dmas dmap switch */
if (mdp4_overlay_mixer_play(mddi_pipe->mixer_num)
== 0) {
mdp4_dma_s_update_lcd(mfd, mddi_pipe);
mdp4_mddi_dma_s_kickoff(mfd, mddi_pipe);
} else
mdp4_mddi_kickoff_ui(mfd, mddi_pipe);
} else /* no dams dmap switch */
mdp4_mddi_kickoff_ui(mfd, mddi_pipe);
/* signal if pan function is waiting for the update completion */
if (mfd->pan_waiting) {
mfd->pan_waiting = FALSE;
complete(&mfd->pan_comp);
}
}
mutex_unlock(&mfd->dma->ov_mutex);
}
int mdp4_mddi_overlay_cursor(struct fb_info *info, struct fb_cursor *cursor)
{
struct msm_fb_data_type *mfd = info->par;
mutex_lock(&mfd->dma->ov_mutex);
if (mfd && mfd->panel_power_on) {
mdp4_mddi_dma_busy_wait(mfd);
mdp_hw_cursor_update(info, cursor);
}
mutex_unlock(&mfd->dma->ov_mutex);
return 0;
}
| gpl-2.0 |
raptorjr/xbmc | xbmc/windowing/X11/WinSystemX11.cpp | 10 | 30080 | /*
* Copyright (C) 2005-2015 Team Kodi
* http://kodi.tv
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kodi; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#if defined(HAVE_X11)
#include "WinSystemX11.h"
#include "ServiceBroker.h"
#include "settings/DisplaySettings.h"
#include "settings/Settings.h"
#include "settings/lib/Setting.h"
#include "guilib/GraphicContext.h"
#include "guilib/Texture.h"
#include "guilib/DispResource.h"
#include "utils/log.h"
#include "XRandR.h"
#include <vector>
#include <string>
#include "threads/SingleLock.h"
#include "utils/TimeUtils.h"
#include "utils/StringUtils.h"
#include "settings/Settings.h"
#include "windowing/WindowingFactory.h"
#include "CompileInfo.h"
#include "messaging/ApplicationMessenger.h"
#include <X11/Xatom.h>
#include <X11/extensions/Xrandr.h>
#include "../WinEventsX11.h"
#include "input/InputManager.h"
using namespace KODI::MESSAGING;
#define EGL_NO_CONFIG (EGLConfig)0
CWinSystemX11::CWinSystemX11() : CWinSystemBase()
{
m_eWindowSystem = WINDOW_SYSTEM_X11;
m_dpy = NULL;
m_glWindow = 0;
m_mainWindow = 0;
m_bWasFullScreenBeforeMinimize = false;
m_minimized = false;
m_bIgnoreNextFocusMessage = false;
m_invisibleCursor = 0;
m_bIsInternalXrr = false;
m_delayDispReset = false;
XSetErrorHandler(XErrorHandler);
}
CWinSystemX11::~CWinSystemX11()
{
}
bool CWinSystemX11::InitWindowSystem()
{
if ((m_dpy = XOpenDisplay(NULL)))
{
bool ret = CWinSystemBase::InitWindowSystem();
return ret;
}
else
CLog::Log(LOGERROR, "X11 Error: No Display found");
return false;
}
bool CWinSystemX11::DestroyWindowSystem()
{
//restore desktop resolution on exit
if (m_bFullScreen)
{
XOutput out;
XMode mode;
out.name = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strOutput;
mode.w = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).iWidth;
mode.h = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).iHeight;
mode.hz = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).fRefreshRate;
mode.id = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strId;
g_xrandr.SetMode(out, mode);
}
return true;
}
bool CWinSystemX11::CreateNewWindow(const std::string& name, bool fullScreen, RESOLUTION_INFO& res, PHANDLE_EVENT_FUNC userFunction)
{
if(!SetFullScreen(fullScreen, res, false))
return false;
m_bWindowCreated = true;
return true;
}
bool CWinSystemX11::DestroyWindow()
{
if (!m_mainWindow)
return true;
if (m_invisibleCursor)
{
XUndefineCursor(m_dpy, m_mainWindow);
XFreeCursor(m_dpy, m_invisibleCursor);
m_invisibleCursor = 0;
}
CWinEventsX11Imp::Quit();
XUnmapWindow(m_dpy, m_mainWindow);
XDestroyWindow(m_dpy, m_glWindow);
XDestroyWindow(m_dpy, m_mainWindow);
m_glWindow = 0;
m_mainWindow = 0;
if (m_icon)
XFreePixmap(m_dpy, m_icon);
return true;
}
bool CWinSystemX11::ResizeWindow(int newWidth, int newHeight, int newLeft, int newTop)
{
m_userOutput = CServiceBroker::GetSettings().GetString(CSettings::SETTING_VIDEOSCREEN_MONITOR);
XOutput *out = NULL;
if (m_userOutput.compare("Default") != 0)
{
out = g_xrandr.GetOutput(m_userOutput);
if (out)
{
XMode mode = g_xrandr.GetCurrentMode(m_userOutput);
if (!mode.isCurrent)
{
out = NULL;
}
}
}
if (!out)
{
std::vector<XOutput> outputs = g_xrandr.GetModes();
if (!outputs.empty())
{
m_userOutput = outputs[0].name;
}
}
if(m_nWidth == newWidth &&
m_nHeight == newHeight &&
m_userOutput.compare(m_currentOutput) == 0)
{
UpdateCrtc();
return true;
}
if (!SetWindow(newWidth, newHeight, false, m_userOutput))
{
return false;
}
m_nWidth = newWidth;
m_nHeight = newHeight;
m_bFullScreen = false;
m_currentOutput = m_userOutput;
return false;
}
bool CWinSystemX11::SetFullScreen(bool fullScreen, RESOLUTION_INFO& res, bool blankOtherDisplays)
{
XOutput out;
XMode mode;
if (fullScreen)
{
out.name = res.strOutput;
mode.w = res.iWidth;
mode.h = res.iHeight;
mode.hz = res.fRefreshRate;
mode.id = res.strId;
}
else
{
out.name = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strOutput;
mode.w = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).iWidth;
mode.h = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).iHeight;
mode.hz = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).fRefreshRate;
mode.id = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strId;
}
XMode currmode = g_xrandr.GetCurrentMode(out.name);
if (!currmode.name.empty())
{
// flip h/w when rotated
if (m_bIsRotated)
{
int w = mode.w;
mode.w = mode.h;
mode.h = w;
}
// only call xrandr if mode changes
if (m_mainWindow)
{
if (currmode.w != mode.w || currmode.h != mode.h ||
currmode.hz != mode.hz || currmode.id != mode.id)
{
CLog::Log(LOGNOTICE, "CWinSystemX11::SetFullScreen - calling xrandr");
// remember last position of mouse
Window root_return, child_return;
int root_x_return, root_y_return;
int win_x_return, win_y_return;
unsigned int mask_return;
bool isInWin = XQueryPointer(m_dpy, m_mainWindow, &root_return, &child_return,
&root_x_return, &root_y_return,
&win_x_return, &win_y_return,
&mask_return);
if (isInWin)
{
m_MouseX = win_x_return;
m_MouseY = win_y_return;
}
else
{
m_MouseX = -1;
m_MouseY = -1;
}
OnLostDevice();
m_bIsInternalXrr = true;
g_xrandr.SetMode(out, mode);
int delay = CServiceBroker::GetSettings().GetInt("videoscreen.delayrefreshchange");
if (delay > 0)
{
m_delayDispReset = true;
m_dispResetTimer.Set(delay * 100);
}
return true;
}
}
}
if (!SetWindow(res.iWidth, res.iHeight, fullScreen, m_userOutput))
return false;
m_nWidth = res.iWidth;
m_nHeight = res.iHeight;
m_bFullScreen = fullScreen;
m_currentOutput = m_userOutput;
return true;
}
void CWinSystemX11::UpdateResolutions()
{
CWinSystemBase::UpdateResolutions();
int numScreens = XScreenCount(m_dpy);
g_xrandr.SetNumScreens(numScreens);
bool switchOnOff = CServiceBroker::GetSettings().GetBool(CSettings::SETTING_VIDEOSCREEN_BLANKDISPLAYS);
m_userOutput = CServiceBroker::GetSettings().GetString(CSettings::SETTING_VIDEOSCREEN_MONITOR);
if (m_userOutput.compare("Default") == 0)
switchOnOff = false;
if(g_xrandr.Query(true, !switchOnOff))
{
XOutput *out = NULL;
if (m_userOutput.compare("Default") != 0)
{
out = g_xrandr.GetOutput(m_userOutput);
if (out)
{
XMode mode = g_xrandr.GetCurrentMode(m_userOutput);
if (!mode.isCurrent && !switchOnOff)
{
out = NULL;
}
}
}
if (!out)
{
m_userOutput = g_xrandr.GetModes()[0].name;
out = g_xrandr.GetOutput(m_userOutput);
}
if (switchOnOff)
{
// switch on output
g_xrandr.TurnOnOutput(m_userOutput);
// switch off other outputs
std::vector<XOutput> outputs = g_xrandr.GetModes();
for (size_t i=0; i<outputs.size(); i++)
{
if (StringUtils::EqualsNoCase(outputs[i].name, m_userOutput))
continue;
g_xrandr.TurnOffOutput(outputs[i].name);
}
}
XMode mode = g_xrandr.GetCurrentMode(m_userOutput);
if (mode.id.empty())
mode = g_xrandr.GetPreferredMode(m_userOutput);
m_bIsRotated = out->isRotated;
if (!m_bIsRotated)
UpdateDesktopResolution(CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP), 0, mode.w, mode.h, mode.hz);
else
UpdateDesktopResolution(CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP), 0, mode.h, mode.w, mode.hz);
CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strId = mode.id;
CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP).strOutput = m_userOutput;
}
else
{
m_userOutput = "No Output";
m_nScreen = DefaultScreen(m_dpy);
int w = DisplayWidth(m_dpy, m_nScreen);
int h = DisplayHeight(m_dpy, m_nScreen);
UpdateDesktopResolution(CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP), 0, w, h, 0.0);
}
// erase previous stored modes
CDisplaySettings::GetInstance().ClearCustomResolutions();
CLog::Log(LOGINFO, "Available videomodes (xrandr):");
XOutput *out = g_xrandr.GetOutput(m_userOutput);
if (out != NULL)
{
std::vector<XMode>::iterator modeiter;
CLog::Log(LOGINFO, "Output '%s' has %" PRIdS" modes", out->name.c_str(), out->modes.size());
for (modeiter = out->modes.begin() ; modeiter!=out->modes.end() ; modeiter++)
{
XMode mode = *modeiter;
CLog::Log(LOGINFO, "ID:%s Name:%s Refresh:%f Width:%d Height:%d",
mode.id.c_str(), mode.name.c_str(), mode.hz, mode.w, mode.h);
RESOLUTION_INFO res;
res.iScreen = 0; // not used by X11
res.dwFlags = 0;
res.iWidth = mode.w;
res.iHeight = mode.h;
res.iScreenWidth = mode.w;
res.iScreenHeight = mode.h;
if (mode.IsInterlaced())
res.dwFlags |= D3DPRESENTFLAG_INTERLACED;
if (!m_bIsRotated)
{
res.iWidth = mode.w;
res.iHeight = mode.h;
}
else
{
res.iWidth = mode.h;
res.iHeight = mode.w;
}
if (mode.h>0 && mode.w>0 && out->hmm>0 && out->wmm>0)
res.fPixelRatio = ((float)out->wmm/(float)mode.w) / (((float)out->hmm/(float)mode.h));
else
res.fPixelRatio = 1.0f;
CLog::Log(LOGINFO, "Pixel Ratio: %f", res.fPixelRatio);
res.strMode = StringUtils::Format("%s: %s @ %.2fHz", out->name.c_str(), mode.name.c_str(), mode.hz);
res.strOutput = out->name;
res.strId = mode.id;
res.iSubtitles = (int)(0.965*mode.h);
res.fRefreshRate = mode.hz;
res.bFullScreen = true;
g_graphicsContext.ResetOverscan(res);
CDisplaySettings::GetInstance().AddResolutionInfo(res);
}
}
CDisplaySettings::GetInstance().ApplyCalibrations();
}
bool CWinSystemX11::HasCalibration(const RESOLUTION_INFO &resInfo)
{
XOutput *out = g_xrandr.GetOutput(m_currentOutput);
// keep calibrations done on a not connected output
if (!StringUtils::EqualsNoCase(out->name, resInfo.strOutput))
return true;
// keep calibrations not updated with resolution data
if (resInfo.iWidth == 0)
return true;
float fPixRatio;
if (resInfo.iHeight>0 && resInfo.iWidth>0 && out->hmm>0 && out->wmm>0)
fPixRatio = ((float)out->wmm/(float)resInfo.iWidth) / (((float)out->hmm/(float)resInfo.iHeight));
else
fPixRatio = 1.0f;
if (resInfo.Overscan.left != 0)
return true;
if (resInfo.Overscan.top != 0)
return true;
if (resInfo.Overscan.right != resInfo.iWidth)
return true;
if (resInfo.Overscan.bottom != resInfo.iHeight)
return true;
if (resInfo.fPixelRatio != fPixRatio)
return true;
if (resInfo.iSubtitles != (int)(0.965*resInfo.iHeight))
return true;
return false;
}
void CWinSystemX11::GetConnectedOutputs(std::vector<std::string> *outputs)
{
std::vector<XOutput> outs;
g_xrandr.Query(true);
outs = g_xrandr.GetModes();
outputs->push_back("Default");
for(unsigned int i=0; i<outs.size(); ++i)
{
outputs->push_back(outs[i].name);
}
}
bool CWinSystemX11::IsCurrentOutput(std::string output)
{
return (StringUtils::EqualsNoCase(output, "Default")) || (m_currentOutput.compare(output.c_str()) == 0);
}
void CWinSystemX11::ShowOSMouse(bool show)
{
if (show)
XUndefineCursor(m_dpy,m_mainWindow);
else if (m_invisibleCursor)
XDefineCursor(m_dpy,m_mainWindow, m_invisibleCursor);
}
void CWinSystemX11::ResetOSScreensaver()
{
if (m_bFullScreen)
{
//disallow the screensaver when we're fullscreen by periodically calling XResetScreenSaver(),
//normally SDL does this but we disable that in CApplication::Create()
//for some reason setting a 0 timeout with XSetScreenSaver doesn't work with gnome
if (!m_screensaverReset.IsRunning() || m_screensaverReset.GetElapsedSeconds() > 5.0f)
{
m_screensaverReset.StartZero();
XResetScreenSaver(m_dpy);
}
}
else
{
m_screensaverReset.Stop();
}
}
void CWinSystemX11::EnableSystemScreenSaver(bool bEnable)
{
if (!m_dpy)
return;
if (bEnable)
XForceScreenSaver(m_dpy, ScreenSaverActive);
else
{
Window root_return, child_return;
int root_x_return, root_y_return;
int win_x_return, win_y_return;
unsigned int mask_return;
XQueryPointer(m_dpy, RootWindow(m_dpy, m_nScreen), &root_return, &child_return,
&root_x_return, &root_y_return,
&win_x_return, &win_y_return,
&mask_return);
XWarpPointer(m_dpy, None, RootWindow(m_dpy, m_nScreen), 0, 0, 0, 0, root_x_return+300, root_y_return+300);
XSync(m_dpy, FALSE);
XWarpPointer(m_dpy, None, RootWindow(m_dpy, m_nScreen), 0, 0, 0, 0, 0, 0);
XSync(m_dpy, FALSE);
XWarpPointer(m_dpy, None, RootWindow(m_dpy, m_nScreen), 0, 0, 0, 0, root_x_return, root_y_return);
XSync(m_dpy, FALSE);
}
}
void CWinSystemX11::NotifyAppActiveChange(bool bActivated)
{
if (bActivated && m_bWasFullScreenBeforeMinimize && !m_bFullScreen)
{
CApplicationMessenger::GetInstance().PostMsg(TMSG_TOGGLEFULLSCREEN);
m_bWasFullScreenBeforeMinimize = false;
}
m_minimized = !bActivated;
}
void CWinSystemX11::NotifyAppFocusChange(bool bGaining)
{
if (bGaining && m_bWasFullScreenBeforeMinimize && !m_bIgnoreNextFocusMessage &&
!m_bFullScreen)
{
m_bWasFullScreenBeforeMinimize = false;
CApplicationMessenger::GetInstance().PostMsg(TMSG_TOGGLEFULLSCREEN);
m_minimized = false;
}
if (!bGaining)
m_bIgnoreNextFocusMessage = false;
}
bool CWinSystemX11::Minimize()
{
m_bWasFullScreenBeforeMinimize = m_bFullScreen;
if (m_bWasFullScreenBeforeMinimize)
{
m_bIgnoreNextFocusMessage = true;
CApplicationMessenger::GetInstance().PostMsg(TMSG_TOGGLEFULLSCREEN);
}
XIconifyWindow(m_dpy, m_mainWindow, m_nScreen);
m_minimized = true;
return true;
}
bool CWinSystemX11::Restore()
{
return false;
}
bool CWinSystemX11::Hide()
{
XUnmapWindow(m_dpy, m_mainWindow);
XFlush(m_dpy);
return true;
}
bool CWinSystemX11::Show(bool raise)
{
XMapWindow(m_dpy, m_mainWindow);
XFlush(m_dpy);
m_minimized = false;
return true;
}
void CWinSystemX11::NotifyXRREvent()
{
CLog::Log(LOGDEBUG, "%s - notify display reset event", __FUNCTION__);
CSingleLock lock(g_graphicsContext);
if (!g_xrandr.Query(true))
{
CLog::Log(LOGERROR, "WinSystemX11::RefreshWindow - failed to query xrandr");
return;
}
// if external event update resolutions
if (!m_bIsInternalXrr)
{
UpdateResolutions();
}
RecreateWindow();
}
void CWinSystemX11::RecreateWindow()
{
m_windowDirty = true;
CSingleLock lock(g_graphicsContext);
XOutput *out = g_xrandr.GetOutput(m_userOutput);
XMode mode = g_xrandr.GetCurrentMode(m_userOutput);
if (out)
CLog::Log(LOGDEBUG, "%s - current output: %s, mode: %s, refresh: %.3f", __FUNCTION__
, out->name.c_str(), mode.id.c_str(), mode.hz);
else
CLog::Log(LOGWARNING, "%s - output name not set", __FUNCTION__);
RESOLUTION_INFO res;
unsigned int i;
bool found(false);
for (i = RES_DESKTOP; i < CDisplaySettings::GetInstance().ResolutionInfoSize(); ++i)
{
res = CDisplaySettings::GetInstance().GetResolutionInfo(i);
if (StringUtils::EqualsNoCase(CDisplaySettings::GetInstance().GetResolutionInfo(i).strId, mode.id))
{
found = true;
break;
}
}
if (!found)
{
CLog::Log(LOGERROR, "CWinSystemX11::RecreateWindow - could not find resolution");
i = RES_DESKTOP;
}
if (g_graphicsContext.IsFullScreenRoot())
g_graphicsContext.SetVideoResolution((RESOLUTION)i, true);
else
g_graphicsContext.SetVideoResolution(RES_WINDOW, true);
}
void CWinSystemX11::OnLostDevice()
{
CLog::Log(LOGDEBUG, "%s - notify display change event", __FUNCTION__);
// make sure renderer has no invalid references
KODI::MESSAGING::CApplicationMessenger::GetInstance().SendMsg(TMSG_RENDERER_FLUSH);
{ CSingleLock lock(m_resourceSection);
for (std::vector<IDispResource *>::iterator i = m_resources.begin(); i != m_resources.end(); ++i)
(*i)->OnLostDisplay();
}
CWinEventsX11Imp::SetXRRFailSafeTimer(3000);
}
void CWinSystemX11::Register(IDispResource *resource)
{
CSingleLock lock(m_resourceSection);
m_resources.push_back(resource);
}
void CWinSystemX11::Unregister(IDispResource* resource)
{
CSingleLock lock(m_resourceSection);
std::vector<IDispResource*>::iterator i = find(m_resources.begin(), m_resources.end(), resource);
if (i != m_resources.end())
m_resources.erase(i);
}
int CWinSystemX11::XErrorHandler(Display* dpy, XErrorEvent* error)
{
char buf[1024];
XGetErrorText(error->display, error->error_code, buf, sizeof(buf));
CLog::Log(LOGERROR, "CWinSystemX11::XErrorHandler: %s, type:%i, serial:%lu, error_code:%i, request_code:%i minor_code:%i",
buf, error->type, error->serial, (int)error->error_code, (int)error->request_code, (int)error->minor_code);
return 0;
}
bool CWinSystemX11::SetWindow(int width, int height, bool fullscreen, const std::string &output, int *winstate)
{
bool changeWindow = false;
bool changeSize = false;
float mouseX = 0.5;
float mouseY = 0.5;
if (!m_mainWindow)
{
CInputManager::GetInstance().SetMouseActive(false);
}
if (m_mainWindow && ((m_bFullScreen != fullscreen) || m_currentOutput.compare(output) != 0 || m_windowDirty))
{
// set mouse to last known position
// we can't trust values after an xrr event
if (m_bIsInternalXrr && m_MouseX >= 0 && m_MouseY >= 0)
{
mouseX = (float)m_MouseX/m_nWidth;
mouseY = (float)m_MouseY/m_nHeight;
}
else if (!m_windowDirty)
{
Window root_return, child_return;
int root_x_return, root_y_return;
int win_x_return, win_y_return;
unsigned int mask_return;
bool isInWin = XQueryPointer(m_dpy, m_mainWindow, &root_return, &child_return,
&root_x_return, &root_y_return,
&win_x_return, &win_y_return,
&mask_return);
if (isInWin)
{
mouseX = (float)win_x_return/m_nWidth;
mouseY = (float)win_y_return/m_nHeight;
}
}
CInputManager::GetInstance().SetMouseActive(false);
OnLostDevice();
DestroyWindow();
m_windowDirty = true;
}
// create main window
if (!m_mainWindow)
{
EnableSystemScreenSaver(false);
Colormap cmap;
XSetWindowAttributes swa;
XVisualInfo *vi;
int x0 = 0;
int y0 = 0;
XOutput *out = g_xrandr.GetOutput(output);
if (!out)
out = g_xrandr.GetOutput(m_currentOutput);
if (out)
{
m_nScreen = out->screen;
x0 = out->x;
y0 = out->y;
}
vi = GetVisual();
if (!vi)
{
CLog::Log(LOGERROR, "Failed to find matching visual");
return false;
}
cmap = XCreateColormap(m_dpy, RootWindow(m_dpy, vi->screen), vi->visual, AllocNone);
bool hasWM = HasWindowManager();
int def_vis = (vi->visual == DefaultVisual(m_dpy, vi->screen));
swa.override_redirect = hasWM ? False : True;
swa.border_pixel = fullscreen ? 0 : 5;
swa.background_pixel = def_vis ? BlackPixel(m_dpy, vi->screen) : 0;
swa.colormap = cmap;
swa.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
PropertyChangeMask | StructureNotifyMask | KeymapStateMask |
EnterWindowMask | LeaveWindowMask | ExposureMask;
unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWOverrideRedirect | CWEventMask;
m_mainWindow = XCreateWindow(m_dpy, RootWindow(m_dpy, vi->screen),
x0, y0, width, height, 0, vi->depth,
InputOutput, vi->visual,
mask, &swa);
swa.override_redirect = False;
swa.border_pixel = 0;
swa.event_mask = ExposureMask;
mask = CWBackPixel | CWBorderPixel | CWColormap | CWOverrideRedirect | CWColormap | CWEventMask;
m_glWindow = XCreateWindow(m_dpy, m_mainWindow,
0, 0, width, height, 0, vi->depth,
InputOutput, vi->visual,
mask, &swa);
if (fullscreen && hasWM)
{
Atom fs = XInternAtom(m_dpy, "_NET_WM_STATE_FULLSCREEN", True);
XChangeProperty(m_dpy, m_mainWindow, XInternAtom(m_dpy, "_NET_WM_STATE", True), XA_ATOM, 32, PropModeReplace, (unsigned char *) &fs, 1);
// disable desktop compositing for KDE, when Kodi is in full-screen mode
int one = 1;
Atom composite = XInternAtom(m_dpy, "_KDE_NET_WM_BLOCK_COMPOSITING", True);
if (composite != None)
{
XChangeProperty(m_dpy, m_mainWindow, XInternAtom(m_dpy, "_KDE_NET_WM_BLOCK_COMPOSITING", True), XA_CARDINAL, 32,
PropModeReplace, (unsigned char*) &one, 1);
}
composite = XInternAtom(m_dpy, "_NET_WM_BYPASS_COMPOSITOR", True);
if (composite != None)
{
// standard way for Gnome 3
XChangeProperty(m_dpy, m_mainWindow, XInternAtom(m_dpy, "_NET_WM_BYPASS_COMPOSITOR", True), XA_CARDINAL, 32,
PropModeReplace, (unsigned char*) &one, 1);
}
}
// define invisible cursor
Pixmap bitmapNoData;
XColor black;
static char noData[] = { 0,0,0,0,0,0,0,0 };
black.red = black.green = black.blue = 0;
bitmapNoData = XCreateBitmapFromData(m_dpy, m_mainWindow, noData, 8, 8);
m_invisibleCursor = XCreatePixmapCursor(m_dpy, bitmapNoData, bitmapNoData,
&black, &black, 0, 0);
XFreePixmap(m_dpy, bitmapNoData);
XDefineCursor(m_dpy,m_mainWindow, m_invisibleCursor);
XFree(vi);
//init X11 events
CWinEventsX11Imp::Init(m_dpy, m_mainWindow);
changeWindow = true;
changeSize = true;
}
if (!CWinEventsX11Imp::HasStructureChanged() && ((width != m_nWidth) || (height != m_nHeight)))
{
changeSize = true;
}
if (changeSize || changeWindow)
{
XResizeWindow(m_dpy, m_mainWindow, width, height);
}
if ((width != m_nWidth) || (height != m_nHeight) || changeWindow)
{
XResizeWindow(m_dpy, m_glWindow, width, height);
}
if (changeWindow)
{
m_icon = None;
{
CreateIconPixmap();
XWMHints *wm_hints;
XClassHint *class_hints;
XTextProperty windowName, iconName;
std::string titleString = CCompileInfo::GetAppName();
std::string classString = titleString;
char *title = (char*)titleString.c_str();
XStringListToTextProperty(&title, 1, &windowName);
XStringListToTextProperty(&title, 1, &iconName);
wm_hints = XAllocWMHints();
wm_hints->initial_state = NormalState;
wm_hints->icon_pixmap = m_icon;
wm_hints->flags = StateHint | IconPixmapHint;
class_hints = XAllocClassHint();
class_hints->res_class = (char*)classString.c_str();
class_hints->res_name = (char*)classString.c_str();
XSetWMProperties(m_dpy, m_mainWindow, &windowName, &iconName,
NULL, 0, NULL, wm_hints,
class_hints);
XFree(class_hints);
XFree(wm_hints);
// register interest in the delete window message
Atom wmDeleteMessage = XInternAtom(m_dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(m_dpy, m_mainWindow, &wmDeleteMessage, 1);
}
// placement of window may follow mouse
XWarpPointer(m_dpy, None, m_mainWindow, 0, 0, 0, 0, mouseX*width, mouseY*height);
XMapRaised(m_dpy, m_glWindow);
XMapRaised(m_dpy, m_mainWindow);
// discard events generated by creating the window, i.e. xrr events
XSync(m_dpy, TRUE);
if (winstate)
*winstate = 1;
}
UpdateCrtc();
return true;
}
bool CWinSystemX11::CreateIconPixmap()
{
int depth;
XImage *img = NULL;
Visual *vis;
XWindowAttributes wndattribs;
XVisualInfo visInfo;
double rRatio;
double gRatio;
double bRatio;
int outIndex = 0;
unsigned int i,j;
unsigned char *buf;
uint32_t *newBuf = 0;
size_t numNewBufBytes;
// Get visual Info
XGetWindowAttributes(m_dpy, m_glWindow, &wndattribs);
visInfo.visualid = wndattribs.visual->visualid;
int nvisuals = 0;
XVisualInfo* visuals = XGetVisualInfo(m_dpy, VisualIDMask, &visInfo, &nvisuals);
if (nvisuals != 1)
{
CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - could not find visual");
return false;
}
visInfo = visuals[0];
XFree(visuals);
depth = visInfo.depth;
vis = visInfo.visual;
if (depth < 15)
{
CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - no suitable depth");
return false;
}
rRatio = vis->red_mask / 255.0;
gRatio = vis->green_mask / 255.0;
bRatio = vis->blue_mask / 255.0;
CBaseTexture *iconTexture = CBaseTexture::LoadFromFile("special://xbmc/media/icon256x256.png");
if (!iconTexture)
return false;
buf = iconTexture->GetPixels();
if (depth>=24)
numNewBufBytes = (4 * (iconTexture->GetWidth() * iconTexture->GetHeight()));
else
numNewBufBytes = (2 * (iconTexture->GetWidth() * iconTexture->GetHeight()));
newBuf = (uint32_t*)malloc(numNewBufBytes);
if (!newBuf)
{
CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - malloc failed");
return false;
}
for (i=0; i<iconTexture->GetHeight();++i)
{
for (j=0; j<iconTexture->GetWidth();++j)
{
unsigned int pos = i*iconTexture->GetPitch()+j*4;
unsigned int r, g, b;
r = (buf[pos+2] * rRatio);
g = (buf[pos+1] * gRatio);
b = (buf[pos+0] * bRatio);
r &= vis->red_mask;
g &= vis->green_mask;
b &= vis->blue_mask;
newBuf[outIndex] = r | g | b;
++outIndex;
}
}
img = XCreateImage(m_dpy, vis, depth,ZPixmap, 0, (char *)newBuf,
iconTexture->GetWidth(), iconTexture->GetHeight(),
(depth>=24)?32:16, 0);
if (!img)
{
CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - could not create image");
free(newBuf);
return false;
}
if (!XInitImage(img))
{
CLog::Log(LOGERROR, "CWinSystemX11::CreateIconPixmap - init image failed");
XDestroyImage(img);
return false;
}
// set byte order
union
{
char c[sizeof(short)];
short s;
} order;
order.s = 1;
if ((1 == order.c[0]))
{
img->byte_order = LSBFirst;
}
else
{
img->byte_order = MSBFirst;
}
// create icon pixmap from image
m_icon = XCreatePixmap(m_dpy, m_glWindow, img->width, img->height, depth);
GC gc = XCreateGC(m_dpy, m_glWindow, 0, NULL);
XPutImage(m_dpy, m_icon, gc, img, 0, 0, 0, 0, img->width, img->height);
XFreeGC(m_dpy, gc);
XDestroyImage(img); // this also frees newBuf
delete iconTexture;
return true;
}
bool CWinSystemX11::HasWindowManager()
{
Window wm_check;
unsigned char *data;
int status, real_format;
Atom real_type, prop;
unsigned long items_read, items_left;
prop = XInternAtom(m_dpy, "_NET_SUPPORTING_WM_CHECK", True);
if (prop == None)
return false;
status = XGetWindowProperty(m_dpy, DefaultRootWindow(m_dpy), prop,
0L, 1L, False, XA_WINDOW, &real_type, &real_format,
&items_read, &items_left, &data);
if(status != Success || ! items_read)
{
if(status == Success)
XFree(data);
return false;
}
wm_check = ((Window*)data)[0];
XFree(data);
status = XGetWindowProperty(m_dpy, wm_check, prop,
0L, 1L, False, XA_WINDOW, &real_type, &real_format,
&items_read, &items_left, &data);
if(status != Success || !items_read)
{
if(status == Success)
XFree(data);
return false;
}
if(wm_check != ((Window*)data)[0])
{
XFree(data);
return false;
}
XFree(data);
prop = XInternAtom(m_dpy, "_NET_WM_NAME", True);
if (prop == None)
{
CLog::Log(LOGDEBUG,"Window Manager Name: ");
return true;
}
status = XGetWindowProperty(m_dpy, wm_check, prop,
0L, (~0L), False, AnyPropertyType, &real_type, &real_format,
&items_read, &items_left, &data);
if(status == Success && items_read)
{
CLog::Log(LOGDEBUG,"Window Manager Name: %s", data);
}
else
CLog::Log(LOGDEBUG,"Window Manager Name: ");
if(status == Success)
XFree(data);
return true;
}
void CWinSystemX11::UpdateCrtc()
{
XWindowAttributes winattr;
int posx, posy;
float fps = 0.0f;
Window child;
XGetWindowAttributes(m_dpy, m_mainWindow, &winattr);
XTranslateCoordinates(m_dpy, m_mainWindow, RootWindow(m_dpy, m_nScreen), winattr.x, winattr.y,
&posx, &posy, &child);
m_crtc = g_xrandr.GetCrtc(posx+winattr.width/2, posy+winattr.height/2, fps);
g_graphicsContext.SetFPS(fps);
}
#endif
| gpl-2.0 |
NamanG/coreboot2.0 | src/superio/nsc/pc87309/superio.c | 10 | 2004 | /*
* This file is part of the coreboot project.
*
* Copyright (C) 2007 Uwe Hermann <uwe@hermann-uwe.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.
*/
#include <arch/io.h>
#include <device/device.h>
#include <device/pnp.h>
#include <pc80/keyboard.h>
#include <stdlib.h>
#include "pc87309.h"
static void init(struct device *dev)
{
if (!dev->enabled)
return;
switch (dev->path.pnp.device) {
case PC87309_KBCK:
pc_keyboard_init();
break;
}
}
static struct device_operations ops = {
.read_resources = pnp_read_resources,
.set_resources = pnp_set_resources,
.enable_resources = pnp_enable_resources,
.enable = pnp_enable,
.init = init,
};
static struct pnp_info pnp_dev_info[] = {
{ &ops, PC87309_FDC, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0, {0x07fa, 0}, },
{ &ops, PC87309_PP, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0, {0x04f8, 0}, },
{ &ops, PC87309_SP2, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0 | PNP_DRQ1, {0x07f8, 0}, },
{ &ops, PC87309_SP1, PNP_IO0 | PNP_IRQ0, {0x07f8, 0}, },
/* TODO: PM. */
{ &ops, PC87309_KBCM, PNP_IRQ0, },
{ &ops, PC87309_KBCK, PNP_IO0 | PNP_IO1 | PNP_IRQ0, {0x07f8, 0}, {0x7f8, 4}, },
};
static void enable_dev(struct device *dev)
{
pnp_enable_devices(dev, &pnp_ops,
ARRAY_SIZE(pnp_dev_info), pnp_dev_info);
}
struct chip_operations superio_nsc_pc87309_ops = {
CHIP_NAME("NSC PC87309 Super I/O")
.enable_dev = enable_dev,
};
| gpl-2.0 |
openjdk/jdk17u | src/hotspot/share/jfr/support/jfrStackTraceMark.cpp | 10 | 3260 | /*
* Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "jfr/recorder/jfrEventSetting.inline.hpp"
#include "jfr/recorder/stacktrace/jfrStackTraceRepository.hpp"
#include "jfr/support/jfrStackTraceMark.hpp"
#include "jfr/support/jfrThreadLocal.hpp"
#include "runtime/thread.inline.hpp"
JfrStackTraceMark::JfrStackTraceMark() : _t(Thread::current()), _previous_id(0), _previous_hash(0) {
JfrThreadLocal* const tl = _t->jfr_thread_local();
if (tl->has_cached_stack_trace()) {
_previous_id = tl->cached_stack_trace_id();
_previous_hash = tl->cached_stack_trace_hash();
}
tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(Thread::current()));
}
JfrStackTraceMark::JfrStackTraceMark(Thread* t) : _t(t), _previous_id(0), _previous_hash(0) {
JfrThreadLocal* const tl = _t->jfr_thread_local();
if (tl->has_cached_stack_trace()) {
_previous_id = tl->cached_stack_trace_id();
_previous_hash = tl->cached_stack_trace_hash();
}
tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(t));
}
JfrStackTraceMark::JfrStackTraceMark(JfrEventId eventId) : _t(NULL), _previous_id(0), _previous_hash(0) {
if (JfrEventSetting::has_stacktrace(eventId)) {
_t = Thread::current();
JfrThreadLocal* const tl = _t->jfr_thread_local();
if (tl->has_cached_stack_trace()) {
_previous_id = tl->cached_stack_trace_id();
_previous_hash = tl->cached_stack_trace_hash();
}
tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(_t));
}
}
JfrStackTraceMark::JfrStackTraceMark(JfrEventId eventId, Thread* t) : _t(NULL), _previous_id(0), _previous_hash(0) {
if (JfrEventSetting::has_stacktrace(eventId)) {
_t = t;
JfrThreadLocal* const tl = _t->jfr_thread_local();
if (tl->has_cached_stack_trace()) {
_previous_id = tl->cached_stack_trace_id();
_previous_hash = tl->cached_stack_trace_hash();
}
tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(_t));
}
}
JfrStackTraceMark::~JfrStackTraceMark() {
if (_previous_id != 0) {
_t->jfr_thread_local()->set_cached_stack_trace_id(_previous_id, _previous_hash);
} else {
if (_t != NULL) {
_t->jfr_thread_local()->clear_cached_stack_trace();
}
}
}
| gpl-2.0 |
reille/proj_ecos | src/ecos/packages/hal/arm/xscale/iq80310/current/src/iq80310_misc.c | 10 | 3736 | //==========================================================================
//
// cyclone_misc.c
//
// HAL misc board support code for CYCLONE evaluation board
//
//==========================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####
// -------------------------------------------
// This file is part of eCos, the Embedded Configurable Operating System.
// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
//
// eCos 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.
//
// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// As a special exception, if other files instantiate templates or use
// macros or inline functions from this file, or you compile this file
// and link it with other works to produce a work based on this file,
// this file does not by itself cause the resulting work to be covered by
// the GNU General Public License. However the source code for this file
// must still be made available in accordance with section (3) of the GNU
// General Public License v2.
//
// This exception does not invalidate any other reasons why a work based
// on this file might be covered by the GNU General Public License.
// -------------------------------------------
// ####ECOSGPLCOPYRIGHTEND####
//==========================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s): gthomas
// Contributors: gthomas
// Date: 2002-10-01
// Purpose: HAL board support
// Description: Implementations of HAL board interfaces
//
//####DESCRIPTIONEND####
//
//========================================================================*/
#include <pkgconf/hal.h>
#include <pkgconf/system.h>
#include CYGBLD_HAL_PLATFORM_H
#include CYGHWR_MEMORY_LAYOUT_H
#include <cyg/infra/cyg_type.h> // base types
#include <cyg/infra/cyg_trac.h> // tracing macros
#include <cyg/infra/cyg_ass.h> // assertion macros
#include <cyg/hal/hal_io.h> // IO macros
#include <cyg/hal/hal_stub.h> // Stub macros
#include <cyg/hal/hal_if.h> // calling interface API
#include <cyg/hal/hal_arch.h> // Register state info
#include <cyg/hal/hal_diag.h>
#include <cyg/hal/hal_intr.h> // Interrupt names
#include <cyg/hal/hal_cache.h>
#include <cyg/hal/hal_iop310.h> // Hardware definitions
#include <cyg/infra/diag.h> // diag_printf
#include <cyg/hal/drv_api.h> // CYG_ISR_HANDLED
// Some initialization has already been done before we get here.
void hal_plf_hardware_init(void)
{
// Put any platform specific initialization here
}
/*------------------------------------------------------------------------*/
// EOF cyclone_misc.c
| gpl-2.0 |
ibazzi/rk3288-kernel | drivers/net/usb/asix_common.c | 10 | 15264 | /*
* ASIX AX8817X based USB 2.0 Ethernet Devices
* Copyright (C) 2003-2006 David Hollis <dhollis@davehollis.com>
* Copyright (C) 2005 Phil Chang <pchang23@sbcglobal.net>
* Copyright (C) 2006 James Painter <jamie.painter@iname.com>
* Copyright (c) 2002-2003 TiVo Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "asix.h"
int asix_read_cmd(struct usbnet *dev, u8 cmd, u16 value, u16 index,
u16 size, void *data)
{
int ret;
ret = usbnet_read_cmd(dev, cmd,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index, data, size);
if (ret != size && ret >= 0)
return -EINVAL;
return ret;
}
int asix_write_cmd(struct usbnet *dev, u8 cmd, u16 value, u16 index,
u16 size, void *data)
{
return usbnet_write_cmd(dev, cmd,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index, data, size);
}
void asix_write_cmd_async(struct usbnet *dev, u8 cmd, u16 value, u16 index,
u16 size, void *data)
{
usbnet_write_cmd_async(dev, cmd,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index, data, size);
}
int asix_rx_fixup_internal(struct usbnet *dev, struct sk_buff *skb,
struct asix_rx_fixup_info *rx)
{
int offset = 0;
while (offset + sizeof(u16) <= skb->len) {
u16 remaining = 0;
unsigned char *data;
if (!rx->size) {
if ((skb->len - offset == sizeof(u16)) ||
rx->split_head) {
if(!rx->split_head) {
rx->header = get_unaligned_le16(
skb->data + offset);
rx->split_head = true;
offset += sizeof(u16);
break;
} else {
rx->header |= (get_unaligned_le16(
skb->data + offset)
<< 16);
rx->split_head = false;
offset += sizeof(u16);
}
} else {
rx->header = get_unaligned_le32(skb->data +
offset);
offset += sizeof(u32);
}
/* get the packet length */
rx->size = (u16) (rx->header & 0x7ff);
if (rx->size != ((~rx->header >> 16) & 0x7ff)) {
netdev_err(dev->net, "asix_rx_fixup() Bad Header Length 0x%x, offset %d\n",
rx->header, offset);
rx->size = 0;
return 0;
}
rx->ax_skb = netdev_alloc_skb_ip_align(dev->net,
rx->size);
if (!rx->ax_skb)
return 0;
}
if (rx->size > dev->net->mtu + ETH_HLEN + VLAN_HLEN) {
netdev_err(dev->net, "asix_rx_fixup() Bad RX Length %d\n",
rx->size);
kfree_skb(rx->ax_skb);
rx->ax_skb = NULL;
rx->size = 0U;
return 0;
}
if (rx->size > skb->len - offset) {
remaining = rx->size - (skb->len - offset);
rx->size = skb->len - offset;
}
if (!rx->ax_skb) {
rx->size = 0;
netdev_err(dev->net, "asix_rx_fixup_internal Bad ax_skb buf.\n");
return 0;
}
data = skb_put(rx->ax_skb, rx->size);
memcpy(data, skb->data + offset, rx->size);
if (!remaining)
usbnet_skb_return(dev, rx->ax_skb);
offset += (rx->size + 1) & 0xfffe;
rx->size = remaining;
}
if (skb->len != offset) {
netdev_err(dev->net, "asix_rx_fixup() Bad SKB Length %d, %d\n",
skb->len, offset);
return 0;
}
return 1;
}
int asix_rx_fixup_common(struct usbnet *dev, struct sk_buff *skb)
{
struct asix_common_private *dp = dev->driver_priv;
struct asix_rx_fixup_info *rx = &dp->rx_fixup_info;
return asix_rx_fixup_internal(dev, skb, rx);
}
struct sk_buff *asix_tx_fixup(struct usbnet *dev, struct sk_buff *skb,
gfp_t flags)
{
int padlen;
int headroom = skb_headroom(skb);
int tailroom = skb_tailroom(skb);
u32 packet_len;
u32 padbytes = 0xffff0000;
padlen = ((skb->len + 4) & (dev->maxpacket - 1)) ? 0 : 4;
/* We need to push 4 bytes in front of frame (packet_len)
* and maybe add 4 bytes after the end (if padlen is 4)
*
* Avoid skb_copy_expand() expensive call, using following rules :
* - We are allowed to push 4 bytes in headroom if skb_header_cloned()
* is false (and if we have 4 bytes of headroom)
* - We are allowed to put 4 bytes at tail if skb_cloned()
* is false (and if we have 4 bytes of tailroom)
*
* TCP packets for example are cloned, but skb_header_release()
* was called in tcp stack, allowing us to use headroom for our needs.
*/
if (!skb_header_cloned(skb) &&
!(padlen && skb_cloned(skb)) &&
headroom + tailroom >= 4 + padlen) {
/* following should not happen, but better be safe */
if (headroom < 4 ||
tailroom < padlen) {
skb->data = memmove(skb->head + 4, skb->data, skb->len);
skb_set_tail_pointer(skb, skb->len);
}
} else {
struct sk_buff *skb2;
skb2 = skb_copy_expand(skb, 4, padlen, flags);
dev_kfree_skb_any(skb);
skb = skb2;
if (!skb)
return NULL;
}
packet_len = ((skb->len ^ 0x0000ffff) << 16) + skb->len;
skb_push(skb, 4);
cpu_to_le32s(&packet_len);
skb_copy_to_linear_data(skb, &packet_len, sizeof(packet_len));
if (padlen) {
cpu_to_le32s(&padbytes);
memcpy(skb_tail_pointer(skb), &padbytes, sizeof(padbytes));
skb_put(skb, sizeof(padbytes));
}
return skb;
}
int asix_set_sw_mii(struct usbnet *dev)
{
int ret;
ret = asix_write_cmd(dev, AX_CMD_SET_SW_MII, 0x0000, 0, 0, NULL);
if (ret < 0)
netdev_err(dev->net, "Failed to enable software MII access\n");
return ret;
}
int asix_set_hw_mii(struct usbnet *dev)
{
int ret;
ret = asix_write_cmd(dev, AX_CMD_SET_HW_MII, 0x0000, 0, 0, NULL);
if (ret < 0)
netdev_err(dev->net, "Failed to enable hardware MII access\n");
return ret;
}
int asix_read_phy_addr(struct usbnet *dev, int internal)
{
int offset = (internal ? 1 : 0);
u8 buf[2];
int ret = asix_read_cmd(dev, AX_CMD_READ_PHY_ID, 0, 0, 2, buf);
netdev_dbg(dev->net, "asix_get_phy_addr()\n");
if (ret < 0) {
netdev_err(dev->net, "Error reading PHYID register: %02x\n", ret);
goto out;
}
netdev_dbg(dev->net, "asix_get_phy_addr() returning 0x%04x\n",
*((__le16 *)buf));
ret = buf[offset];
out:
return ret;
}
int asix_get_phy_addr(struct usbnet *dev)
{
/* return the address of the internal phy */
return asix_read_phy_addr(dev, 1);
}
int asix_sw_reset(struct usbnet *dev, u8 flags)
{
int ret;
ret = asix_write_cmd(dev, AX_CMD_SW_RESET, flags, 0, 0, NULL);
if (ret < 0)
netdev_err(dev->net, "Failed to send software reset: %02x\n", ret);
return ret;
}
u16 asix_read_rx_ctl(struct usbnet *dev)
{
__le16 v;
int ret = asix_read_cmd(dev, AX_CMD_READ_RX_CTL, 0, 0, 2, &v);
if (ret < 0) {
netdev_err(dev->net, "Error reading RX_CTL register: %02x\n", ret);
goto out;
}
ret = le16_to_cpu(v);
out:
return ret;
}
int asix_write_rx_ctl(struct usbnet *dev, u16 mode)
{
int ret;
netdev_dbg(dev->net, "asix_write_rx_ctl() - mode = 0x%04x\n", mode);
ret = asix_write_cmd(dev, AX_CMD_WRITE_RX_CTL, mode, 0, 0, NULL);
if (ret < 0)
netdev_err(dev->net, "Failed to write RX_CTL mode to 0x%04x: %02x\n",
mode, ret);
return ret;
}
u16 asix_read_medium_status(struct usbnet *dev)
{
__le16 v;
int ret = asix_read_cmd(dev, AX_CMD_READ_MEDIUM_STATUS, 0, 0, 2, &v);
if (ret < 0) {
netdev_err(dev->net, "Error reading Medium Status register: %02x\n",
ret);
return ret; /* TODO: callers not checking for error ret */
}
return le16_to_cpu(v);
}
int asix_write_medium_mode(struct usbnet *dev, u16 mode)
{
int ret;
netdev_dbg(dev->net, "asix_write_medium_mode() - mode = 0x%04x\n", mode);
ret = asix_write_cmd(dev, AX_CMD_WRITE_MEDIUM_MODE, mode, 0, 0, NULL);
if (ret < 0)
netdev_err(dev->net, "Failed to write Medium Mode mode to 0x%04x: %02x\n",
mode, ret);
return ret;
}
int asix_write_gpio(struct usbnet *dev, u16 value, int sleep)
{
int ret;
netdev_dbg(dev->net, "asix_write_gpio() - value = 0x%04x\n", value);
ret = asix_write_cmd(dev, AX_CMD_WRITE_GPIOS, value, 0, 0, NULL);
if (ret < 0)
netdev_err(dev->net, "Failed to write GPIO value 0x%04x: %02x\n",
value, ret);
if (sleep)
msleep(sleep);
return ret;
}
/*
* AX88772 & AX88178 have a 16-bit RX_CTL value
*/
void asix_set_multicast(struct net_device *net)
{
struct usbnet *dev = netdev_priv(net);
struct asix_data *data = (struct asix_data *)&dev->data;
u16 rx_ctl = AX_DEFAULT_RX_CTL;
if (net->flags & IFF_PROMISC) {
rx_ctl |= AX_RX_CTL_PRO;
} else if (net->flags & IFF_ALLMULTI ||
netdev_mc_count(net) > AX_MAX_MCAST) {
rx_ctl |= AX_RX_CTL_AMALL;
} else if (netdev_mc_empty(net)) {
/* just broadcast and directed */
} else {
/* We use the 20 byte dev->data
* for our 8 byte filter buffer
* to avoid allocating memory that
* is tricky to free later */
struct netdev_hw_addr *ha;
u32 crc_bits;
memset(data->multi_filter, 0, AX_MCAST_FILTER_SIZE);
/* Build the multicast hash filter. */
netdev_for_each_mc_addr(ha, net) {
crc_bits = ether_crc(ETH_ALEN, ha->addr) >> 26;
data->multi_filter[crc_bits >> 3] |=
1 << (crc_bits & 7);
}
asix_write_cmd_async(dev, AX_CMD_WRITE_MULTI_FILTER, 0, 0,
AX_MCAST_FILTER_SIZE, data->multi_filter);
rx_ctl |= AX_RX_CTL_AM;
}
asix_write_cmd_async(dev, AX_CMD_WRITE_RX_CTL, rx_ctl, 0, 0, NULL);
}
int asix_mdio_read(struct net_device *netdev, int phy_id, int loc)
{
struct usbnet *dev = netdev_priv(netdev);
__le16 res;
mutex_lock(&dev->phy_mutex);
asix_set_sw_mii(dev);
asix_read_cmd(dev, AX_CMD_READ_MII_REG, phy_id,
(__u16)loc, 2, &res);
asix_set_hw_mii(dev);
mutex_unlock(&dev->phy_mutex);
netdev_dbg(dev->net, "asix_mdio_read() phy_id=0x%02x, loc=0x%02x, returns=0x%04x\n",
phy_id, loc, le16_to_cpu(res));
return le16_to_cpu(res);
}
void asix_mdio_write(struct net_device *netdev, int phy_id, int loc, int val)
{
struct usbnet *dev = netdev_priv(netdev);
__le16 res = cpu_to_le16(val);
netdev_dbg(dev->net, "asix_mdio_write() phy_id=0x%02x, loc=0x%02x, val=0x%04x\n",
phy_id, loc, val);
mutex_lock(&dev->phy_mutex);
asix_set_sw_mii(dev);
asix_write_cmd(dev, AX_CMD_WRITE_MII_REG, phy_id, (__u16)loc, 2, &res);
asix_set_hw_mii(dev);
mutex_unlock(&dev->phy_mutex);
}
void asix_get_wol(struct net_device *net, struct ethtool_wolinfo *wolinfo)
{
struct usbnet *dev = netdev_priv(net);
u8 opt;
if (asix_read_cmd(dev, AX_CMD_READ_MONITOR_MODE, 0, 0, 1, &opt) < 0) {
wolinfo->supported = 0;
wolinfo->wolopts = 0;
return;
}
wolinfo->supported = WAKE_PHY | WAKE_MAGIC;
wolinfo->wolopts = 0;
if (opt & AX_MONITOR_LINK)
wolinfo->wolopts |= WAKE_PHY;
if (opt & AX_MONITOR_MAGIC)
wolinfo->wolopts |= WAKE_MAGIC;
}
int asix_set_wol(struct net_device *net, struct ethtool_wolinfo *wolinfo)
{
struct usbnet *dev = netdev_priv(net);
u8 opt = 0;
if (wolinfo->wolopts & WAKE_PHY)
opt |= AX_MONITOR_LINK;
if (wolinfo->wolopts & WAKE_MAGIC)
opt |= AX_MONITOR_MAGIC;
if (asix_write_cmd(dev, AX_CMD_WRITE_MONITOR_MODE,
opt, 0, 0, NULL) < 0)
return -EINVAL;
return 0;
}
int asix_get_eeprom_len(struct net_device *net)
{
return AX_EEPROM_LEN;
}
int asix_get_eeprom(struct net_device *net, struct ethtool_eeprom *eeprom,
u8 *data)
{
struct usbnet *dev = netdev_priv(net);
u16 *eeprom_buff;
int first_word, last_word;
int i;
if (eeprom->len == 0)
return -EINVAL;
eeprom->magic = AX_EEPROM_MAGIC;
first_word = eeprom->offset >> 1;
last_word = (eeprom->offset + eeprom->len - 1) >> 1;
eeprom_buff = kmalloc(sizeof(u16) * (last_word - first_word + 1),
GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
/* ax8817x returns 2 bytes from eeprom on read */
for (i = first_word; i <= last_word; i++) {
if (asix_read_cmd(dev, AX_CMD_READ_EEPROM, i, 0, 2,
&(eeprom_buff[i - first_word])) < 0) {
kfree(eeprom_buff);
return -EIO;
}
}
memcpy(data, (u8 *)eeprom_buff + (eeprom->offset & 1), eeprom->len);
kfree(eeprom_buff);
return 0;
}
int asix_set_eeprom(struct net_device *net, struct ethtool_eeprom *eeprom,
u8 *data)
{
struct usbnet *dev = netdev_priv(net);
u16 *eeprom_buff;
int first_word, last_word;
int i;
int ret;
netdev_dbg(net, "write EEPROM len %d, offset %d, magic 0x%x\n",
eeprom->len, eeprom->offset, eeprom->magic);
if (eeprom->len == 0)
return -EINVAL;
if (eeprom->magic != AX_EEPROM_MAGIC)
return -EINVAL;
first_word = eeprom->offset >> 1;
last_word = (eeprom->offset + eeprom->len - 1) >> 1;
eeprom_buff = kmalloc(sizeof(u16) * (last_word - first_word + 1),
GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
/* align data to 16 bit boundaries, read the missing data from
the EEPROM */
if (eeprom->offset & 1) {
ret = asix_read_cmd(dev, AX_CMD_READ_EEPROM, first_word, 0, 2,
&(eeprom_buff[0]));
if (ret < 0) {
netdev_err(net, "Failed to read EEPROM at offset 0x%02x.\n", first_word);
goto free;
}
}
if ((eeprom->offset + eeprom->len) & 1) {
ret = asix_read_cmd(dev, AX_CMD_READ_EEPROM, last_word, 0, 2,
&(eeprom_buff[last_word - first_word]));
if (ret < 0) {
netdev_err(net, "Failed to read EEPROM at offset 0x%02x.\n", last_word);
goto free;
}
}
memcpy((u8 *)eeprom_buff + (eeprom->offset & 1), data, eeprom->len);
/* write data to EEPROM */
ret = asix_write_cmd(dev, AX_CMD_WRITE_ENABLE, 0x0000, 0, 0, NULL);
if (ret < 0) {
netdev_err(net, "Failed to enable EEPROM write\n");
goto free;
}
msleep(20);
for (i = first_word; i <= last_word; i++) {
netdev_dbg(net, "write to EEPROM at offset 0x%02x, data 0x%04x\n",
i, eeprom_buff[i - first_word]);
ret = asix_write_cmd(dev, AX_CMD_WRITE_EEPROM, i,
eeprom_buff[i - first_word], 0, NULL);
if (ret < 0) {
netdev_err(net, "Failed to write EEPROM at offset 0x%02x.\n",
i);
goto free;
}
msleep(20);
}
ret = asix_write_cmd(dev, AX_CMD_WRITE_DISABLE, 0x0000, 0, 0, NULL);
if (ret < 0) {
netdev_err(net, "Failed to disable EEPROM write\n");
goto free;
}
ret = 0;
free:
kfree(eeprom_buff);
return ret;
}
void asix_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *info)
{
/* Inherit standard device info */
usbnet_get_drvinfo(net, info);
strlcpy(info->driver, DRIVER_NAME, sizeof(info->driver));
strlcpy(info->version, DRIVER_VERSION, sizeof(info->version));
info->eedump_len = AX_EEPROM_LEN;
}
int asix_set_mac_address(struct net_device *net, void *p)
{
struct usbnet *dev = netdev_priv(net);
struct asix_data *data = (struct asix_data *)&dev->data;
struct sockaddr *addr = p;
if (netif_running(net))
return -EBUSY;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(net->dev_addr, addr->sa_data, ETH_ALEN);
/* We use the 20 byte dev->data
* for our 6 byte mac buffer
* to avoid allocating memory that
* is tricky to free later */
memcpy(data->mac_addr, addr->sa_data, ETH_ALEN);
asix_write_cmd_async(dev, AX_CMD_WRITE_NODE_ID, 0, 0, ETH_ALEN,
data->mac_addr);
return 0;
}
| gpl-2.0 |
vovan888/p750-kernel | kernel/sysctl.c | 10 | 72746 | /*
* sysctl.c: General linux system control interface
*
* Begun 24 March 1995, Stephen Tweedie
* Added /proc support, Dec 1995
* Added bdflush entry and intvec min/max checking, 2/23/96, Tom Dyas.
* Added hooks for /proc/sys/net (minor, minor patch), 96/4/1, Mike Shaver.
* Added kernel/java-{interpreter,appletviewer}, 96/5/10, Mike Shaver.
* Dynamic registration fixes, Stephen Tweedie.
* Added kswapd-interval, ctrl-alt-del, printk stuff, 1/8/97, Chris Horn.
* Made sysctl support optional via CONFIG_SYSCTL, 1/10/97, Chris
* Horn.
* Added proc_doulongvec_ms_jiffies_minmax, 09/08/99, Carlos H. Bauer.
* Added proc_doulongvec_minmax, 09/08/99, Carlos H. Bauer.
* Changed linked lists to use list.h instead of lists.h, 02/24/00, Bill
* Wendling.
* The list_for_each() macro wasn't appropriate for the sysctl loop.
* Removed it and replaced it with older style, 03/23/00, Bill Wendling
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/security.h>
#include <linux/ctype.h>
#include <linux/utsname.h>
#include <linux/smp_lock.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/net.h>
#include <linux/sysrq.h>
#include <linux/highuid.h>
#include <linux/writeback.h>
#include <linux/hugetlb.h>
#include <linux/initrd.h>
#include <linux/key.h>
#include <linux/times.h>
#include <linux/limits.h>
#include <linux/dcache.h>
#include <linux/syscalls.h>
#include <linux/vmstat.h>
#include <linux/nfs_fs.h>
#include <linux/acpi.h>
#include <linux/reboot.h>
#include <linux/ftrace.h>
#include <asm/uaccess.h>
#include <asm/processor.h>
#ifdef CONFIG_X86
#include <asm/nmi.h>
#include <asm/stacktrace.h>
#include <asm/io.h>
#endif
static int deprecated_sysctl_warning(struct __sysctl_args *args);
#if defined(CONFIG_SYSCTL)
/* External variables not in a header file. */
extern int C_A_D;
extern int print_fatal_signals;
extern int sysctl_overcommit_memory;
extern int sysctl_overcommit_ratio;
extern int sysctl_panic_on_oom;
extern int sysctl_oom_kill_allocating_task;
extern int sysctl_oom_dump_tasks;
extern int max_threads;
extern int core_uses_pid;
extern int suid_dumpable;
extern char core_pattern[];
extern int pid_max;
extern int min_free_kbytes;
extern int pid_max_min, pid_max_max;
extern int sysctl_drop_caches;
extern int percpu_pagelist_fraction;
extern int compat_log;
extern int latencytop_enabled;
extern int sysctl_nr_open_min, sysctl_nr_open_max;
#ifdef CONFIG_RCU_TORTURE_TEST
extern int rcutorture_runnable;
#endif /* #ifdef CONFIG_RCU_TORTURE_TEST */
/* Constants used for minimum and maximum */
#if defined(CONFIG_HIGHMEM) || defined(CONFIG_DETECT_SOFTLOCKUP)
static int one = 1;
#endif
#ifdef CONFIG_DETECT_SOFTLOCKUP
static int sixty = 60;
static int neg_one = -1;
#endif
#if defined(CONFIG_MMU) && defined(CONFIG_FILE_LOCKING)
static int two = 2;
#endif
static int zero;
static int one_hundred = 100;
/* this is needed for the proc_dointvec_minmax for [fs_]overflow UID and GID */
static int maxolduid = 65535;
static int minolduid;
static int min_percpu_pagelist_fract = 8;
static int ngroups_max = NGROUPS_MAX;
#ifdef CONFIG_MODULES
extern char modprobe_path[];
#endif
#ifdef CONFIG_CHR_DEV_SG
extern int sg_big_buff;
#endif
#ifdef CONFIG_SPARC
#include <asm/system.h>
#endif
#ifdef __hppa__
extern int pwrsw_enabled;
extern int unaligned_enabled;
#endif
#ifdef CONFIG_S390
#ifdef CONFIG_MATHEMU
extern int sysctl_ieee_emulation_warnings;
#endif
extern int sysctl_userprocess_debug;
extern int spin_retry;
#endif
#ifdef CONFIG_BSD_PROCESS_ACCT
extern int acct_parm[];
#endif
#ifdef CONFIG_IA64
extern int no_unaligned_warning;
#endif
#ifdef CONFIG_RT_MUTEXES
extern int max_lock_depth;
#endif
#ifdef CONFIG_PROC_SYSCTL
static int proc_do_cad_pid(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos);
static int proc_taint(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos);
#endif
static struct ctl_table root_table[];
static struct ctl_table_root sysctl_table_root;
static struct ctl_table_header root_table_header = {
.count = 1,
.ctl_table = root_table,
.ctl_entry = LIST_HEAD_INIT(sysctl_table_root.default_set.list),
.root = &sysctl_table_root,
.set = &sysctl_table_root.default_set,
};
static struct ctl_table_root sysctl_table_root = {
.root_list = LIST_HEAD_INIT(sysctl_table_root.root_list),
.default_set.list = LIST_HEAD_INIT(root_table_header.ctl_entry),
};
static struct ctl_table kern_table[];
static struct ctl_table vm_table[];
static struct ctl_table fs_table[];
static struct ctl_table debug_table[];
static struct ctl_table dev_table[];
extern struct ctl_table random_table[];
#ifdef CONFIG_INOTIFY_USER
extern struct ctl_table inotify_table[];
#endif
#ifdef CONFIG_EPOLL
extern struct ctl_table epoll_table[];
#endif
#ifdef HAVE_ARCH_PICK_MMAP_LAYOUT
int sysctl_legacy_va_layout;
#endif
extern int prove_locking;
extern int lock_stat;
/* The default sysctl tables: */
static struct ctl_table root_table[] = {
{
.ctl_name = CTL_KERN,
.procname = "kernel",
.mode = 0555,
.child = kern_table,
},
{
.ctl_name = CTL_VM,
.procname = "vm",
.mode = 0555,
.child = vm_table,
},
{
.ctl_name = CTL_FS,
.procname = "fs",
.mode = 0555,
.child = fs_table,
},
{
.ctl_name = CTL_DEBUG,
.procname = "debug",
.mode = 0555,
.child = debug_table,
},
{
.ctl_name = CTL_DEV,
.procname = "dev",
.mode = 0555,
.child = dev_table,
},
/*
* NOTE: do not add new entries to this table unless you have read
* Documentation/sysctl/ctl_unnumbered.txt
*/
{ .ctl_name = 0 }
};
#ifdef CONFIG_SCHED_DEBUG
static int min_sched_granularity_ns = 100000; /* 100 usecs */
static int max_sched_granularity_ns = NSEC_PER_SEC; /* 1 second */
static int min_wakeup_granularity_ns; /* 0 usecs */
static int max_wakeup_granularity_ns = NSEC_PER_SEC; /* 1 second */
#endif
static struct ctl_table kern_table[] = {
#ifdef CONFIG_SCHED_DEBUG
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_min_granularity_ns",
.data = &sysctl_sched_min_granularity,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &sched_nr_latency_handler,
.strategy = &sysctl_intvec,
.extra1 = &min_sched_granularity_ns,
.extra2 = &max_sched_granularity_ns,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_latency_ns",
.data = &sysctl_sched_latency,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &sched_nr_latency_handler,
.strategy = &sysctl_intvec,
.extra1 = &min_sched_granularity_ns,
.extra2 = &max_sched_granularity_ns,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_wakeup_granularity_ns",
.data = &sysctl_sched_wakeup_granularity,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &min_wakeup_granularity_ns,
.extra2 = &max_wakeup_granularity_ns,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_shares_ratelimit",
.data = &sysctl_sched_shares_ratelimit,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_shares_thresh",
.data = &sysctl_sched_shares_thresh,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &zero,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_child_runs_first",
.data = &sysctl_sched_child_runs_first,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_features",
.data = &sysctl_sched_features,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_migration_cost",
.data = &sysctl_sched_migration_cost,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_nr_migrate",
.data = &sysctl_sched_nr_migrate,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_rt_period_us",
.data = &sysctl_sched_rt_period,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &sched_rt_handler,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_rt_runtime_us",
.data = &sysctl_sched_rt_runtime,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &sched_rt_handler,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "sched_compat_yield",
.data = &sysctl_sched_compat_yield,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#ifdef CONFIG_PROVE_LOCKING
{
.ctl_name = CTL_UNNUMBERED,
.procname = "prove_locking",
.data = &prove_locking,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_LOCK_STAT
{
.ctl_name = CTL_UNNUMBERED,
.procname = "lock_stat",
.data = &lock_stat,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = KERN_PANIC,
.procname = "panic",
.data = &panic_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = KERN_CORE_USES_PID,
.procname = "core_uses_pid",
.data = &core_uses_pid,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = KERN_CORE_PATTERN,
.procname = "core_pattern",
.data = core_pattern,
.maxlen = CORENAME_MAX_SIZE,
.mode = 0644,
.proc_handler = &proc_dostring,
.strategy = &sysctl_string,
},
#ifdef CONFIG_PROC_SYSCTL
{
.procname = "tainted",
.maxlen = sizeof(long),
.mode = 0644,
.proc_handler = &proc_taint,
},
#endif
#ifdef CONFIG_LATENCYTOP
{
.procname = "latencytop",
.data = &latencytop_enabled,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_BLK_DEV_INITRD
{
.ctl_name = KERN_REALROOTDEV,
.procname = "real-root-dev",
.data = &real_root_dev,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = CTL_UNNUMBERED,
.procname = "print-fatal-signals",
.data = &print_fatal_signals,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#ifdef CONFIG_SPARC
{
.ctl_name = KERN_SPARC_REBOOT,
.procname = "reboot-cmd",
.data = reboot_command,
.maxlen = 256,
.mode = 0644,
.proc_handler = &proc_dostring,
.strategy = &sysctl_string,
},
{
.ctl_name = KERN_SPARC_STOP_A,
.procname = "stop-a",
.data = &stop_a_enabled,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = KERN_SPARC_SCONS_PWROFF,
.procname = "scons-poweroff",
.data = &scons_pwroff,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef __hppa__
{
.ctl_name = KERN_HPPA_PWRSW,
.procname = "soft-power",
.data = &pwrsw_enabled,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = KERN_HPPA_UNALIGNED,
.procname = "unaligned-trap",
.data = &unaligned_enabled,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = KERN_CTLALTDEL,
.procname = "ctrl-alt-del",
.data = &C_A_D,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#ifdef CONFIG_FUNCTION_TRACER
{
.ctl_name = CTL_UNNUMBERED,
.procname = "ftrace_enabled",
.data = &ftrace_enabled,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &ftrace_enable_sysctl,
},
#endif
#ifdef CONFIG_MODULES
{
.ctl_name = KERN_MODPROBE,
.procname = "modprobe",
.data = &modprobe_path,
.maxlen = KMOD_PATH_LEN,
.mode = 0644,
.proc_handler = &proc_dostring,
.strategy = &sysctl_string,
},
#endif
#if defined(CONFIG_HOTPLUG) && defined(CONFIG_NET)
{
.ctl_name = KERN_HOTPLUG,
.procname = "hotplug",
.data = &uevent_helper,
.maxlen = UEVENT_HELPER_PATH_LEN,
.mode = 0644,
.proc_handler = &proc_dostring,
.strategy = &sysctl_string,
},
#endif
#ifdef CONFIG_CHR_DEV_SG
{
.ctl_name = KERN_SG_BIG_BUFF,
.procname = "sg-big-buff",
.data = &sg_big_buff,
.maxlen = sizeof (int),
.mode = 0444,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_BSD_PROCESS_ACCT
{
.ctl_name = KERN_ACCT,
.procname = "acct",
.data = &acct_parm,
.maxlen = 3*sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_MAGIC_SYSRQ
{
.ctl_name = KERN_SYSRQ,
.procname = "sysrq",
.data = &__sysrq_enabled,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_PROC_SYSCTL
{
.procname = "cad_pid",
.data = NULL,
.maxlen = sizeof (int),
.mode = 0600,
.proc_handler = &proc_do_cad_pid,
},
#endif
{
.ctl_name = KERN_MAX_THREADS,
.procname = "threads-max",
.data = &max_threads,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = KERN_RANDOM,
.procname = "random",
.mode = 0555,
.child = random_table,
},
{
.ctl_name = KERN_OVERFLOWUID,
.procname = "overflowuid",
.data = &overflowuid,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &minolduid,
.extra2 = &maxolduid,
},
{
.ctl_name = KERN_OVERFLOWGID,
.procname = "overflowgid",
.data = &overflowgid,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &minolduid,
.extra2 = &maxolduid,
},
#ifdef CONFIG_S390
#ifdef CONFIG_MATHEMU
{
.ctl_name = KERN_IEEE_EMULATION_WARNINGS,
.procname = "ieee_emulation_warnings",
.data = &sysctl_ieee_emulation_warnings,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = KERN_S390_USER_DEBUG_LOGGING,
.procname = "userprocess_debug",
.data = &sysctl_userprocess_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = KERN_PIDMAX,
.procname = "pid_max",
.data = &pid_max,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = sysctl_intvec,
.extra1 = &pid_max_min,
.extra2 = &pid_max_max,
},
{
.ctl_name = KERN_PANIC_ON_OOPS,
.procname = "panic_on_oops",
.data = &panic_on_oops,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#if defined CONFIG_PRINTK
{
.ctl_name = KERN_PRINTK,
.procname = "printk",
.data = &console_loglevel,
.maxlen = 4*sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = KERN_PRINTK_RATELIMIT,
.procname = "printk_ratelimit",
.data = &printk_ratelimit_state.interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_jiffies,
.strategy = &sysctl_jiffies,
},
{
.ctl_name = KERN_PRINTK_RATELIMIT_BURST,
.procname = "printk_ratelimit_burst",
.data = &printk_ratelimit_state.burst,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = KERN_NGROUPS_MAX,
.procname = "ngroups_max",
.data = &ngroups_max,
.maxlen = sizeof (int),
.mode = 0444,
.proc_handler = &proc_dointvec,
},
#if defined(CONFIG_X86_LOCAL_APIC) && defined(CONFIG_X86)
{
.ctl_name = KERN_UNKNOWN_NMI_PANIC,
.procname = "unknown_nmi_panic",
.data = &unknown_nmi_panic,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.procname = "nmi_watchdog",
.data = &nmi_watchdog_enabled,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_nmi_enabled,
},
#endif
#if defined(CONFIG_X86)
{
.ctl_name = KERN_PANIC_ON_NMI,
.procname = "panic_on_unrecovered_nmi",
.data = &panic_on_unrecovered_nmi,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = KERN_BOOTLOADER_TYPE,
.procname = "bootloader_type",
.data = &bootloader_type,
.maxlen = sizeof (int),
.mode = 0444,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "kstack_depth_to_print",
.data = &kstack_depth_to_print,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "io_delay_type",
.data = &io_delay_type,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#if defined(CONFIG_MMU)
{
.ctl_name = KERN_RANDOMIZE,
.procname = "randomize_va_space",
.data = &randomize_va_space,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#if defined(CONFIG_S390) && defined(CONFIG_SMP)
{
.ctl_name = KERN_SPIN_RETRY,
.procname = "spin_retry",
.data = &spin_retry,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#if defined(CONFIG_ACPI_SLEEP) && defined(CONFIG_X86)
{
.procname = "acpi_video_flags",
.data = &acpi_realmode_flags,
.maxlen = sizeof (unsigned long),
.mode = 0644,
.proc_handler = &proc_doulongvec_minmax,
},
#endif
#ifdef CONFIG_IA64
{
.ctl_name = KERN_IA64_UNALIGNED,
.procname = "ignore-unaligned-usertrap",
.data = &no_unaligned_warning,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_DETECT_SOFTLOCKUP
{
.ctl_name = CTL_UNNUMBERED,
.procname = "softlockup_panic",
.data = &softlockup_panic,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &one,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "softlockup_thresh",
.data = &softlockup_thresh,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &neg_one,
.extra2 = &sixty,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "hung_task_check_count",
.data = &sysctl_hung_task_check_count,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = &proc_doulongvec_minmax,
.strategy = &sysctl_intvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "hung_task_timeout_secs",
.data = &sysctl_hung_task_timeout_secs,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = &proc_doulongvec_minmax,
.strategy = &sysctl_intvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "hung_task_warnings",
.data = &sysctl_hung_task_warnings,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = &proc_doulongvec_minmax,
.strategy = &sysctl_intvec,
},
#endif
#ifdef CONFIG_COMPAT
{
.ctl_name = KERN_COMPAT_LOG,
.procname = "compat-log",
.data = &compat_log,
.maxlen = sizeof (int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_RT_MUTEXES
{
.ctl_name = KERN_MAX_LOCK_DEPTH,
.procname = "max_lock_depth",
.data = &max_lock_depth,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
{
.ctl_name = CTL_UNNUMBERED,
.procname = "poweroff_cmd",
.data = &poweroff_cmd,
.maxlen = POWEROFF_CMD_PATH_LEN,
.mode = 0644,
.proc_handler = &proc_dostring,
.strategy = &sysctl_string,
},
#ifdef CONFIG_KEYS
{
.ctl_name = CTL_UNNUMBERED,
.procname = "keys",
.mode = 0555,
.child = key_sysctls,
},
#endif
#ifdef CONFIG_RCU_TORTURE_TEST
{
.ctl_name = CTL_UNNUMBERED,
.procname = "rcutorture_runnable",
.data = &rcutorture_runnable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_UNEVICTABLE_LRU
{
.ctl_name = CTL_UNNUMBERED,
.procname = "scan_unevictable_pages",
.data = &scan_unevictable_pages,
.maxlen = sizeof(scan_unevictable_pages),
.mode = 0644,
.proc_handler = &scan_unevictable_handler,
},
#endif
/*
* NOTE: do not add new entries to this table unless you have read
* Documentation/sysctl/ctl_unnumbered.txt
*/
{ .ctl_name = 0 }
};
static struct ctl_table vm_table[] = {
{
.ctl_name = VM_OVERCOMMIT_MEMORY,
.procname = "overcommit_memory",
.data = &sysctl_overcommit_memory,
.maxlen = sizeof(sysctl_overcommit_memory),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = VM_PANIC_ON_OOM,
.procname = "panic_on_oom",
.data = &sysctl_panic_on_oom,
.maxlen = sizeof(sysctl_panic_on_oom),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "oom_kill_allocating_task",
.data = &sysctl_oom_kill_allocating_task,
.maxlen = sizeof(sysctl_oom_kill_allocating_task),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "oom_dump_tasks",
.data = &sysctl_oom_dump_tasks,
.maxlen = sizeof(sysctl_oom_dump_tasks),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = VM_OVERCOMMIT_RATIO,
.procname = "overcommit_ratio",
.data = &sysctl_overcommit_ratio,
.maxlen = sizeof(sysctl_overcommit_ratio),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = VM_PAGE_CLUSTER,
.procname = "page-cluster",
.data = &page_cluster,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = VM_DIRTY_BACKGROUND,
.procname = "dirty_background_ratio",
.data = &dirty_background_ratio,
.maxlen = sizeof(dirty_background_ratio),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &one_hundred,
},
{
.ctl_name = VM_DIRTY_RATIO,
.procname = "dirty_ratio",
.data = &vm_dirty_ratio,
.maxlen = sizeof(vm_dirty_ratio),
.mode = 0644,
.proc_handler = &dirty_ratio_handler,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &one_hundred,
},
{
.procname = "dirty_writeback_centisecs",
.data = &dirty_writeback_interval,
.maxlen = sizeof(dirty_writeback_interval),
.mode = 0644,
.proc_handler = &dirty_writeback_centisecs_handler,
},
{
.procname = "dirty_expire_centisecs",
.data = &dirty_expire_interval,
.maxlen = sizeof(dirty_expire_interval),
.mode = 0644,
.proc_handler = &proc_dointvec_userhz_jiffies,
},
{
.ctl_name = VM_NR_PDFLUSH_THREADS,
.procname = "nr_pdflush_threads",
.data = &nr_pdflush_threads,
.maxlen = sizeof nr_pdflush_threads,
.mode = 0444 /* read-only*/,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = VM_SWAPPINESS,
.procname = "swappiness",
.data = &vm_swappiness,
.maxlen = sizeof(vm_swappiness),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &one_hundred,
},
#ifdef CONFIG_HUGETLB_PAGE
{
.procname = "nr_hugepages",
.data = NULL,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = &hugetlb_sysctl_handler,
.extra1 = (void *)&hugetlb_zero,
.extra2 = (void *)&hugetlb_infinity,
},
{
.ctl_name = VM_HUGETLB_GROUP,
.procname = "hugetlb_shm_group",
.data = &sysctl_hugetlb_shm_group,
.maxlen = sizeof(gid_t),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "hugepages_treat_as_movable",
.data = &hugepages_treat_as_movable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &hugetlb_treat_movable_handler,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "nr_overcommit_hugepages",
.data = NULL,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = &hugetlb_overcommit_handler,
.extra1 = (void *)&hugetlb_zero,
.extra2 = (void *)&hugetlb_infinity,
},
#endif
{
.ctl_name = VM_LOWMEM_RESERVE_RATIO,
.procname = "lowmem_reserve_ratio",
.data = &sysctl_lowmem_reserve_ratio,
.maxlen = sizeof(sysctl_lowmem_reserve_ratio),
.mode = 0644,
.proc_handler = &lowmem_reserve_ratio_sysctl_handler,
.strategy = &sysctl_intvec,
},
{
.ctl_name = VM_DROP_PAGECACHE,
.procname = "drop_caches",
.data = &sysctl_drop_caches,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = drop_caches_sysctl_handler,
.strategy = &sysctl_intvec,
},
{
.ctl_name = VM_MIN_FREE_KBYTES,
.procname = "min_free_kbytes",
.data = &min_free_kbytes,
.maxlen = sizeof(min_free_kbytes),
.mode = 0644,
.proc_handler = &min_free_kbytes_sysctl_handler,
.strategy = &sysctl_intvec,
.extra1 = &zero,
},
{
.ctl_name = VM_PERCPU_PAGELIST_FRACTION,
.procname = "percpu_pagelist_fraction",
.data = &percpu_pagelist_fraction,
.maxlen = sizeof(percpu_pagelist_fraction),
.mode = 0644,
.proc_handler = &percpu_pagelist_fraction_sysctl_handler,
.strategy = &sysctl_intvec,
.extra1 = &min_percpu_pagelist_fract,
},
#ifdef CONFIG_MMU
{
.ctl_name = VM_MAX_MAP_COUNT,
.procname = "max_map_count",
.data = &sysctl_max_map_count,
.maxlen = sizeof(sysctl_max_map_count),
.mode = 0644,
.proc_handler = &proc_dointvec
},
#endif
{
.ctl_name = VM_LAPTOP_MODE,
.procname = "laptop_mode",
.data = &laptop_mode,
.maxlen = sizeof(laptop_mode),
.mode = 0644,
.proc_handler = &proc_dointvec_jiffies,
.strategy = &sysctl_jiffies,
},
{
.ctl_name = VM_BLOCK_DUMP,
.procname = "block_dump",
.data = &block_dump,
.maxlen = sizeof(block_dump),
.mode = 0644,
.proc_handler = &proc_dointvec,
.strategy = &sysctl_intvec,
.extra1 = &zero,
},
{
.ctl_name = VM_VFS_CACHE_PRESSURE,
.procname = "vfs_cache_pressure",
.data = &sysctl_vfs_cache_pressure,
.maxlen = sizeof(sysctl_vfs_cache_pressure),
.mode = 0644,
.proc_handler = &proc_dointvec,
.strategy = &sysctl_intvec,
.extra1 = &zero,
},
#ifdef HAVE_ARCH_PICK_MMAP_LAYOUT
{
.ctl_name = VM_LEGACY_VA_LAYOUT,
.procname = "legacy_va_layout",
.data = &sysctl_legacy_va_layout,
.maxlen = sizeof(sysctl_legacy_va_layout),
.mode = 0644,
.proc_handler = &proc_dointvec,
.strategy = &sysctl_intvec,
.extra1 = &zero,
},
#endif
#ifdef CONFIG_NUMA
{
.ctl_name = VM_ZONE_RECLAIM_MODE,
.procname = "zone_reclaim_mode",
.data = &zone_reclaim_mode,
.maxlen = sizeof(zone_reclaim_mode),
.mode = 0644,
.proc_handler = &proc_dointvec,
.strategy = &sysctl_intvec,
.extra1 = &zero,
},
{
.ctl_name = VM_MIN_UNMAPPED,
.procname = "min_unmapped_ratio",
.data = &sysctl_min_unmapped_ratio,
.maxlen = sizeof(sysctl_min_unmapped_ratio),
.mode = 0644,
.proc_handler = &sysctl_min_unmapped_ratio_sysctl_handler,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &one_hundred,
},
{
.ctl_name = VM_MIN_SLAB,
.procname = "min_slab_ratio",
.data = &sysctl_min_slab_ratio,
.maxlen = sizeof(sysctl_min_slab_ratio),
.mode = 0644,
.proc_handler = &sysctl_min_slab_ratio_sysctl_handler,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &one_hundred,
},
#endif
#ifdef CONFIG_SMP
{
.ctl_name = CTL_UNNUMBERED,
.procname = "stat_interval",
.data = &sysctl_stat_interval,
.maxlen = sizeof(sysctl_stat_interval),
.mode = 0644,
.proc_handler = &proc_dointvec_jiffies,
.strategy = &sysctl_jiffies,
},
#endif
#ifdef CONFIG_SECURITY
{
.ctl_name = CTL_UNNUMBERED,
.procname = "mmap_min_addr",
.data = &mmap_min_addr,
.maxlen = sizeof(unsigned long),
.mode = 0644,
.proc_handler = &proc_doulongvec_minmax,
},
#endif
#ifdef CONFIG_NUMA
{
.ctl_name = CTL_UNNUMBERED,
.procname = "numa_zonelist_order",
.data = &numa_zonelist_order,
.maxlen = NUMA_ZONELIST_ORDER_LEN,
.mode = 0644,
.proc_handler = &numa_zonelist_order_handler,
.strategy = &sysctl_string,
},
#endif
#if (defined(CONFIG_X86_32) && !defined(CONFIG_UML))|| \
(defined(CONFIG_SUPERH) && defined(CONFIG_VSYSCALL))
{
.ctl_name = VM_VDSO_ENABLED,
.procname = "vdso_enabled",
.data = &vdso_enabled,
.maxlen = sizeof(vdso_enabled),
.mode = 0644,
.proc_handler = &proc_dointvec,
.strategy = &sysctl_intvec,
.extra1 = &zero,
},
#endif
#ifdef CONFIG_HIGHMEM
{
.ctl_name = CTL_UNNUMBERED,
.procname = "highmem_is_dirtyable",
.data = &vm_highmem_is_dirtyable,
.maxlen = sizeof(vm_highmem_is_dirtyable),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &one,
},
#endif
/*
* NOTE: do not add new entries to this table unless you have read
* Documentation/sysctl/ctl_unnumbered.txt
*/
{ .ctl_name = 0 }
};
#if defined(CONFIG_BINFMT_MISC) || defined(CONFIG_BINFMT_MISC_MODULE)
static struct ctl_table binfmt_misc_table[] = {
{ .ctl_name = 0 }
};
#endif
static struct ctl_table fs_table[] = {
{
.ctl_name = FS_NRINODE,
.procname = "inode-nr",
.data = &inodes_stat,
.maxlen = 2*sizeof(int),
.mode = 0444,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = FS_STATINODE,
.procname = "inode-state",
.data = &inodes_stat,
.maxlen = 7*sizeof(int),
.mode = 0444,
.proc_handler = &proc_dointvec,
},
{
.procname = "file-nr",
.data = &files_stat,
.maxlen = 3*sizeof(int),
.mode = 0444,
.proc_handler = &proc_nr_files,
},
{
.ctl_name = FS_MAXFILE,
.procname = "file-max",
.data = &files_stat.max_files,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = CTL_UNNUMBERED,
.procname = "nr_open",
.data = &sysctl_nr_open,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.extra1 = &sysctl_nr_open_min,
.extra2 = &sysctl_nr_open_max,
},
{
.ctl_name = FS_DENTRY,
.procname = "dentry-state",
.data = &dentry_stat,
.maxlen = 6*sizeof(int),
.mode = 0444,
.proc_handler = &proc_dointvec,
},
{
.ctl_name = FS_OVERFLOWUID,
.procname = "overflowuid",
.data = &fs_overflowuid,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &minolduid,
.extra2 = &maxolduid,
},
{
.ctl_name = FS_OVERFLOWGID,
.procname = "overflowgid",
.data = &fs_overflowgid,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &minolduid,
.extra2 = &maxolduid,
},
#ifdef CONFIG_FILE_LOCKING
{
.ctl_name = FS_LEASES,
.procname = "leases-enable",
.data = &leases_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_DNOTIFY
{
.ctl_name = FS_DIR_NOTIFY,
.procname = "dir-notify-enable",
.data = &dir_notify_enable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#endif
#ifdef CONFIG_MMU
#ifdef CONFIG_FILE_LOCKING
{
.ctl_name = FS_LEASE_TIME,
.procname = "lease-break-time",
.data = &lease_break_time,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec_minmax,
.strategy = &sysctl_intvec,
.extra1 = &zero,
.extra2 = &two,
},
#endif
#ifdef CONFIG_AIO
{
.procname = "aio-nr",
.data = &aio_nr,
.maxlen = sizeof(aio_nr),
.mode = 0444,
.proc_handler = &proc_doulongvec_minmax,
},
{
.procname = "aio-max-nr",
.data = &aio_max_nr,
.maxlen = sizeof(aio_max_nr),
.mode = 0644,
.proc_handler = &proc_doulongvec_minmax,
},
#endif /* CONFIG_AIO */
#ifdef CONFIG_INOTIFY_USER
{
.ctl_name = FS_INOTIFY,
.procname = "inotify",
.mode = 0555,
.child = inotify_table,
},
#endif
#ifdef CONFIG_EPOLL
{
.procname = "epoll",
.mode = 0555,
.child = epoll_table,
},
#endif
#endif
{
.ctl_name = KERN_SETUID_DUMPABLE,
.procname = "suid_dumpable",
.data = &suid_dumpable,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = &proc_dointvec,
},
#if defined(CONFIG_BINFMT_MISC) || defined(CONFIG_BINFMT_MISC_MODULE)
{
.ctl_name = CTL_UNNUMBERED,
.procname = "binfmt_misc",
.mode = 0555,
.child = binfmt_misc_table,
},
#endif
/*
* NOTE: do not add new entries to this table unless you have read
* Documentation/sysctl/ctl_unnumbered.txt
*/
{ .ctl_name = 0 }
};
static struct ctl_table debug_table[] = {
#if defined(CONFIG_X86) || defined(CONFIG_PPC)
{
.ctl_name = CTL_UNNUMBERED,
.procname = "exception-trace",
.data = &show_unhandled_signals,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
#endif
{ .ctl_name = 0 }
};
static struct ctl_table dev_table[] = {
{ .ctl_name = 0 }
};
static DEFINE_SPINLOCK(sysctl_lock);
/* called under sysctl_lock */
static int use_table(struct ctl_table_header *p)
{
if (unlikely(p->unregistering))
return 0;
p->used++;
return 1;
}
/* called under sysctl_lock */
static void unuse_table(struct ctl_table_header *p)
{
if (!--p->used)
if (unlikely(p->unregistering))
complete(p->unregistering);
}
/* called under sysctl_lock, will reacquire if has to wait */
static void start_unregistering(struct ctl_table_header *p)
{
/*
* if p->used is 0, nobody will ever touch that entry again;
* we'll eliminate all paths to it before dropping sysctl_lock
*/
if (unlikely(p->used)) {
struct completion wait;
init_completion(&wait);
p->unregistering = &wait;
spin_unlock(&sysctl_lock);
wait_for_completion(&wait);
spin_lock(&sysctl_lock);
} else {
/* anything non-NULL; we'll never dereference it */
p->unregistering = ERR_PTR(-EINVAL);
}
/*
* do not remove from the list until nobody holds it; walking the
* list in do_sysctl() relies on that.
*/
list_del_init(&p->ctl_entry);
}
void sysctl_head_get(struct ctl_table_header *head)
{
spin_lock(&sysctl_lock);
head->count++;
spin_unlock(&sysctl_lock);
}
void sysctl_head_put(struct ctl_table_header *head)
{
spin_lock(&sysctl_lock);
if (!--head->count)
kfree(head);
spin_unlock(&sysctl_lock);
}
struct ctl_table_header *sysctl_head_grab(struct ctl_table_header *head)
{
if (!head)
BUG();
spin_lock(&sysctl_lock);
if (!use_table(head))
head = ERR_PTR(-ENOENT);
spin_unlock(&sysctl_lock);
return head;
}
void sysctl_head_finish(struct ctl_table_header *head)
{
if (!head)
return;
spin_lock(&sysctl_lock);
unuse_table(head);
spin_unlock(&sysctl_lock);
}
static struct ctl_table_set *
lookup_header_set(struct ctl_table_root *root, struct nsproxy *namespaces)
{
struct ctl_table_set *set = &root->default_set;
if (root->lookup)
set = root->lookup(root, namespaces);
return set;
}
static struct list_head *
lookup_header_list(struct ctl_table_root *root, struct nsproxy *namespaces)
{
struct ctl_table_set *set = lookup_header_set(root, namespaces);
return &set->list;
}
struct ctl_table_header *__sysctl_head_next(struct nsproxy *namespaces,
struct ctl_table_header *prev)
{
struct ctl_table_root *root;
struct list_head *header_list;
struct ctl_table_header *head;
struct list_head *tmp;
spin_lock(&sysctl_lock);
if (prev) {
head = prev;
tmp = &prev->ctl_entry;
unuse_table(prev);
goto next;
}
tmp = &root_table_header.ctl_entry;
for (;;) {
head = list_entry(tmp, struct ctl_table_header, ctl_entry);
if (!use_table(head))
goto next;
spin_unlock(&sysctl_lock);
return head;
next:
root = head->root;
tmp = tmp->next;
header_list = lookup_header_list(root, namespaces);
if (tmp != header_list)
continue;
do {
root = list_entry(root->root_list.next,
struct ctl_table_root, root_list);
if (root == &sysctl_table_root)
goto out;
header_list = lookup_header_list(root, namespaces);
} while (list_empty(header_list));
tmp = header_list->next;
}
out:
spin_unlock(&sysctl_lock);
return NULL;
}
struct ctl_table_header *sysctl_head_next(struct ctl_table_header *prev)
{
return __sysctl_head_next(current->nsproxy, prev);
}
void register_sysctl_root(struct ctl_table_root *root)
{
spin_lock(&sysctl_lock);
list_add_tail(&root->root_list, &sysctl_table_root.root_list);
spin_unlock(&sysctl_lock);
}
#ifdef CONFIG_SYSCTL_SYSCALL
/* Perform the actual read/write of a sysctl table entry. */
static int do_sysctl_strategy(struct ctl_table_root *root,
struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
int op = 0, rc;
if (oldval)
op |= MAY_READ;
if (newval)
op |= MAY_WRITE;
if (sysctl_perm(root, table, op))
return -EPERM;
if (table->strategy) {
rc = table->strategy(table, oldval, oldlenp, newval, newlen);
if (rc < 0)
return rc;
if (rc > 0)
return 0;
}
/* If there is no strategy routine, or if the strategy returns
* zero, proceed with automatic r/w */
if (table->data && table->maxlen) {
rc = sysctl_data(table, oldval, oldlenp, newval, newlen);
if (rc < 0)
return rc;
}
return 0;
}
static int parse_table(int __user *name, int nlen,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen,
struct ctl_table_root *root,
struct ctl_table *table)
{
int n;
repeat:
if (!nlen)
return -ENOTDIR;
if (get_user(n, name))
return -EFAULT;
for ( ; table->ctl_name || table->procname; table++) {
if (!table->ctl_name)
continue;
if (n == table->ctl_name) {
int error;
if (table->child) {
if (sysctl_perm(root, table, MAY_EXEC))
return -EPERM;
name++;
nlen--;
table = table->child;
goto repeat;
}
error = do_sysctl_strategy(root, table,
oldval, oldlenp,
newval, newlen);
return error;
}
}
return -ENOTDIR;
}
int do_sysctl(int __user *name, int nlen, void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
struct ctl_table_header *head;
int error = -ENOTDIR;
if (nlen <= 0 || nlen >= CTL_MAXNAME)
return -ENOTDIR;
if (oldval) {
int old_len;
if (!oldlenp || get_user(old_len, oldlenp))
return -EFAULT;
}
for (head = sysctl_head_next(NULL); head;
head = sysctl_head_next(head)) {
error = parse_table(name, nlen, oldval, oldlenp,
newval, newlen,
head->root, head->ctl_table);
if (error != -ENOTDIR) {
sysctl_head_finish(head);
break;
}
}
return error;
}
SYSCALL_DEFINE1(sysctl, struct __sysctl_args __user *, args)
{
struct __sysctl_args tmp;
int error;
if (copy_from_user(&tmp, args, sizeof(tmp)))
return -EFAULT;
error = deprecated_sysctl_warning(&tmp);
if (error)
goto out;
lock_kernel();
error = do_sysctl(tmp.name, tmp.nlen, tmp.oldval, tmp.oldlenp,
tmp.newval, tmp.newlen);
unlock_kernel();
out:
return error;
}
#endif /* CONFIG_SYSCTL_SYSCALL */
/*
* sysctl_perm does NOT grant the superuser all rights automatically, because
* some sysctl variables are readonly even to root.
*/
static int test_perm(int mode, int op)
{
if (!current->euid)
mode >>= 6;
else if (in_egroup_p(0))
mode >>= 3;
if ((op & ~mode & (MAY_READ|MAY_WRITE|MAY_EXEC)) == 0)
return 0;
return -EACCES;
}
int sysctl_perm(struct ctl_table_root *root, struct ctl_table *table, int op)
{
int error;
int mode;
error = security_sysctl(table, op & (MAY_READ | MAY_WRITE | MAY_EXEC));
if (error)
return error;
if (root->permissions)
mode = root->permissions(root, current->nsproxy, table);
else
mode = table->mode;
return test_perm(mode, op);
}
static void sysctl_set_parent(struct ctl_table *parent, struct ctl_table *table)
{
for (; table->ctl_name || table->procname; table++) {
table->parent = parent;
if (table->child)
sysctl_set_parent(table, table->child);
}
}
static __init int sysctl_init(void)
{
sysctl_set_parent(NULL, root_table);
#ifdef CONFIG_SYSCTL_SYSCALL_CHECK
{
int err;
err = sysctl_check_table(current->nsproxy, root_table);
}
#endif
return 0;
}
core_initcall(sysctl_init);
static struct ctl_table *is_branch_in(struct ctl_table *branch,
struct ctl_table *table)
{
struct ctl_table *p;
const char *s = branch->procname;
/* branch should have named subdirectory as its first element */
if (!s || !branch->child)
return NULL;
/* ... and nothing else */
if (branch[1].procname || branch[1].ctl_name)
return NULL;
/* table should contain subdirectory with the same name */
for (p = table; p->procname || p->ctl_name; p++) {
if (!p->child)
continue;
if (p->procname && strcmp(p->procname, s) == 0)
return p;
}
return NULL;
}
/* see if attaching q to p would be an improvement */
static void try_attach(struct ctl_table_header *p, struct ctl_table_header *q)
{
struct ctl_table *to = p->ctl_table, *by = q->ctl_table;
struct ctl_table *next;
int is_better = 0;
int not_in_parent = !p->attached_by;
while ((next = is_branch_in(by, to)) != NULL) {
if (by == q->attached_by)
is_better = 1;
if (to == p->attached_by)
not_in_parent = 1;
by = by->child;
to = next->child;
}
if (is_better && not_in_parent) {
q->attached_by = by;
q->attached_to = to;
q->parent = p;
}
}
/**
* __register_sysctl_paths - register a sysctl hierarchy
* @root: List of sysctl headers to register on
* @namespaces: Data to compute which lists of sysctl entries are visible
* @path: The path to the directory the sysctl table is in.
* @table: the top-level table structure
*
* Register a sysctl table hierarchy. @table should be a filled in ctl_table
* array. A completely 0 filled entry terminates the table.
*
* The members of the &struct ctl_table structure are used as follows:
*
* ctl_name - This is the numeric sysctl value used by sysctl(2). The number
* must be unique within that level of sysctl
*
* procname - the name of the sysctl file under /proc/sys. Set to %NULL to not
* enter a sysctl file
*
* data - a pointer to data for use by proc_handler
*
* maxlen - the maximum size in bytes of the data
*
* mode - the file permissions for the /proc/sys file, and for sysctl(2)
*
* child - a pointer to the child sysctl table if this entry is a directory, or
* %NULL.
*
* proc_handler - the text handler routine (described below)
*
* strategy - the strategy routine (described below)
*
* de - for internal use by the sysctl routines
*
* extra1, extra2 - extra pointers usable by the proc handler routines
*
* Leaf nodes in the sysctl tree will be represented by a single file
* under /proc; non-leaf nodes will be represented by directories.
*
* sysctl(2) can automatically manage read and write requests through
* the sysctl table. The data and maxlen fields of the ctl_table
* struct enable minimal validation of the values being written to be
* performed, and the mode field allows minimal authentication.
*
* More sophisticated management can be enabled by the provision of a
* strategy routine with the table entry. This will be called before
* any automatic read or write of the data is performed.
*
* The strategy routine may return
*
* < 0 - Error occurred (error is passed to user process)
*
* 0 - OK - proceed with automatic read or write.
*
* > 0 - OK - read or write has been done by the strategy routine, so
* return immediately.
*
* There must be a proc_handler routine for any terminal nodes
* mirrored under /proc/sys (non-terminals are handled by a built-in
* directory handler). Several default handlers are available to
* cover common cases -
*
* proc_dostring(), proc_dointvec(), proc_dointvec_jiffies(),
* proc_dointvec_userhz_jiffies(), proc_dointvec_minmax(),
* proc_doulongvec_ms_jiffies_minmax(), proc_doulongvec_minmax()
*
* It is the handler's job to read the input buffer from user memory
* and process it. The handler should return 0 on success.
*
* This routine returns %NULL on a failure to register, and a pointer
* to the table header on success.
*/
struct ctl_table_header *__register_sysctl_paths(
struct ctl_table_root *root,
struct nsproxy *namespaces,
const struct ctl_path *path, struct ctl_table *table)
{
struct ctl_table_header *header;
struct ctl_table *new, **prevp;
unsigned int n, npath;
struct ctl_table_set *set;
/* Count the path components */
for (npath = 0; path[npath].ctl_name || path[npath].procname; ++npath)
;
/*
* For each path component, allocate a 2-element ctl_table array.
* The first array element will be filled with the sysctl entry
* for this, the second will be the sentinel (ctl_name == 0).
*
* We allocate everything in one go so that we don't have to
* worry about freeing additional memory in unregister_sysctl_table.
*/
header = kzalloc(sizeof(struct ctl_table_header) +
(2 * npath * sizeof(struct ctl_table)), GFP_KERNEL);
if (!header)
return NULL;
new = (struct ctl_table *) (header + 1);
/* Now connect the dots */
prevp = &header->ctl_table;
for (n = 0; n < npath; ++n, ++path) {
/* Copy the procname */
new->procname = path->procname;
new->ctl_name = path->ctl_name;
new->mode = 0555;
*prevp = new;
prevp = &new->child;
new += 2;
}
*prevp = table;
header->ctl_table_arg = table;
INIT_LIST_HEAD(&header->ctl_entry);
header->used = 0;
header->unregistering = NULL;
header->root = root;
sysctl_set_parent(NULL, header->ctl_table);
header->count = 1;
#ifdef CONFIG_SYSCTL_SYSCALL_CHECK
if (sysctl_check_table(namespaces, header->ctl_table)) {
kfree(header);
return NULL;
}
#endif
spin_lock(&sysctl_lock);
header->set = lookup_header_set(root, namespaces);
header->attached_by = header->ctl_table;
header->attached_to = root_table;
header->parent = &root_table_header;
for (set = header->set; set; set = set->parent) {
struct ctl_table_header *p;
list_for_each_entry(p, &set->list, ctl_entry) {
if (p->unregistering)
continue;
try_attach(p, header);
}
}
header->parent->count++;
list_add_tail(&header->ctl_entry, &header->set->list);
spin_unlock(&sysctl_lock);
return header;
}
/**
* register_sysctl_table_path - register a sysctl table hierarchy
* @path: The path to the directory the sysctl table is in.
* @table: the top-level table structure
*
* Register a sysctl table hierarchy. @table should be a filled in ctl_table
* array. A completely 0 filled entry terminates the table.
*
* See __register_sysctl_paths for more details.
*/
struct ctl_table_header *register_sysctl_paths(const struct ctl_path *path,
struct ctl_table *table)
{
return __register_sysctl_paths(&sysctl_table_root, current->nsproxy,
path, table);
}
/**
* register_sysctl_table - register a sysctl table hierarchy
* @table: the top-level table structure
*
* Register a sysctl table hierarchy. @table should be a filled in ctl_table
* array. A completely 0 filled entry terminates the table.
*
* See register_sysctl_paths for more details.
*/
struct ctl_table_header *register_sysctl_table(struct ctl_table *table)
{
static const struct ctl_path null_path[] = { {} };
return register_sysctl_paths(null_path, table);
}
/**
* unregister_sysctl_table - unregister a sysctl table hierarchy
* @header: the header returned from register_sysctl_table
*
* Unregisters the sysctl table and all children. proc entries may not
* actually be removed until they are no longer used by anyone.
*/
void unregister_sysctl_table(struct ctl_table_header * header)
{
might_sleep();
if (header == NULL)
return;
spin_lock(&sysctl_lock);
start_unregistering(header);
if (!--header->parent->count) {
WARN_ON(1);
kfree(header->parent);
}
if (!--header->count)
kfree(header);
spin_unlock(&sysctl_lock);
}
int sysctl_is_seen(struct ctl_table_header *p)
{
struct ctl_table_set *set = p->set;
int res;
spin_lock(&sysctl_lock);
if (p->unregistering)
res = 0;
else if (!set->is_seen)
res = 1;
else
res = set->is_seen(set);
spin_unlock(&sysctl_lock);
return res;
}
void setup_sysctl_set(struct ctl_table_set *p,
struct ctl_table_set *parent,
int (*is_seen)(struct ctl_table_set *))
{
INIT_LIST_HEAD(&p->list);
p->parent = parent ? parent : &sysctl_table_root.default_set;
p->is_seen = is_seen;
}
#else /* !CONFIG_SYSCTL */
struct ctl_table_header *register_sysctl_table(struct ctl_table * table)
{
return NULL;
}
struct ctl_table_header *register_sysctl_paths(const struct ctl_path *path,
struct ctl_table *table)
{
return NULL;
}
void unregister_sysctl_table(struct ctl_table_header * table)
{
}
void setup_sysctl_set(struct ctl_table_set *p,
struct ctl_table_set *parent,
int (*is_seen)(struct ctl_table_set *))
{
}
void sysctl_head_put(struct ctl_table_header *head)
{
}
#endif /* CONFIG_SYSCTL */
/*
* /proc/sys support
*/
#ifdef CONFIG_PROC_SYSCTL
static int _proc_do_string(void* data, int maxlen, int write,
struct file *filp, void __user *buffer,
size_t *lenp, loff_t *ppos)
{
size_t len;
char __user *p;
char c;
if (!data || !maxlen || !*lenp) {
*lenp = 0;
return 0;
}
if (write) {
len = 0;
p = buffer;
while (len < *lenp) {
if (get_user(c, p++))
return -EFAULT;
if (c == 0 || c == '\n')
break;
len++;
}
if (len >= maxlen)
len = maxlen-1;
if(copy_from_user(data, buffer, len))
return -EFAULT;
((char *) data)[len] = 0;
*ppos += *lenp;
} else {
len = strlen(data);
if (len > maxlen)
len = maxlen;
if (*ppos > len) {
*lenp = 0;
return 0;
}
data += *ppos;
len -= *ppos;
if (len > *lenp)
len = *lenp;
if (len)
if(copy_to_user(buffer, data, len))
return -EFAULT;
if (len < *lenp) {
if(put_user('\n', ((char __user *) buffer) + len))
return -EFAULT;
len++;
}
*lenp = len;
*ppos += len;
}
return 0;
}
/**
* proc_dostring - read a string sysctl
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: file position
*
* Reads/writes a string from/to the user buffer. If the kernel
* buffer provided is not large enough to hold the string, the
* string is truncated. The copied string is %NULL-terminated.
* If the string is being read by the user process, it is copied
* and a newline '\n' is added. It is truncated if the buffer is
* not large enough.
*
* Returns 0 on success.
*/
int proc_dostring(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return _proc_do_string(table->data, table->maxlen, write, filp,
buffer, lenp, ppos);
}
static int do_proc_dointvec_conv(int *negp, unsigned long *lvalp,
int *valp,
int write, void *data)
{
if (write) {
*valp = *negp ? -*lvalp : *lvalp;
} else {
int val = *valp;
if (val < 0) {
*negp = -1;
*lvalp = (unsigned long)-val;
} else {
*negp = 0;
*lvalp = (unsigned long)val;
}
}
return 0;
}
static int __do_proc_dointvec(void *tbl_data, struct ctl_table *table,
int write, struct file *filp, void __user *buffer,
size_t *lenp, loff_t *ppos,
int (*conv)(int *negp, unsigned long *lvalp, int *valp,
int write, void *data),
void *data)
{
#define TMPBUFLEN 21
int *i, vleft, first=1, neg, val;
unsigned long lval;
size_t left, len;
char buf[TMPBUFLEN], *p;
char __user *s = buffer;
if (!tbl_data || !table->maxlen || !*lenp ||
(*ppos && !write)) {
*lenp = 0;
return 0;
}
i = (int *) tbl_data;
vleft = table->maxlen / sizeof(*i);
left = *lenp;
if (!conv)
conv = do_proc_dointvec_conv;
for (; left && vleft--; i++, first=0) {
if (write) {
while (left) {
char c;
if (get_user(c, s))
return -EFAULT;
if (!isspace(c))
break;
left--;
s++;
}
if (!left)
break;
neg = 0;
len = left;
if (len > sizeof(buf) - 1)
len = sizeof(buf) - 1;
if (copy_from_user(buf, s, len))
return -EFAULT;
buf[len] = 0;
p = buf;
if (*p == '-' && left > 1) {
neg = 1;
p++;
}
if (*p < '0' || *p > '9')
break;
lval = simple_strtoul(p, &p, 0);
len = p-buf;
if ((len < left) && *p && !isspace(*p))
break;
if (neg)
val = -val;
s += len;
left -= len;
if (conv(&neg, &lval, i, 1, data))
break;
} else {
p = buf;
if (!first)
*p++ = '\t';
if (conv(&neg, &lval, i, 0, data))
break;
sprintf(p, "%s%lu", neg ? "-" : "", lval);
len = strlen(buf);
if (len > left)
len = left;
if(copy_to_user(s, buf, len))
return -EFAULT;
left -= len;
s += len;
}
}
if (!write && !first && left) {
if(put_user('\n', s))
return -EFAULT;
left--, s++;
}
if (write) {
while (left) {
char c;
if (get_user(c, s++))
return -EFAULT;
if (!isspace(c))
break;
left--;
}
}
if (write && first)
return -EINVAL;
*lenp -= left;
*ppos += *lenp;
return 0;
#undef TMPBUFLEN
}
static int do_proc_dointvec(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos,
int (*conv)(int *negp, unsigned long *lvalp, int *valp,
int write, void *data),
void *data)
{
return __do_proc_dointvec(table->data, table, write, filp,
buffer, lenp, ppos, conv, data);
}
/**
* proc_dointvec - read a vector of integers
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: file position
*
* Reads/writes up to table->maxlen/sizeof(unsigned int) integer
* values from/to the user buffer, treated as an ASCII string.
*
* Returns 0 on success.
*/
int proc_dointvec(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return do_proc_dointvec(table,write,filp,buffer,lenp,ppos,
NULL,NULL);
}
/*
* Taint values can only be increased
* This means we can safely use a temporary.
*/
static int proc_taint(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table t;
unsigned long tmptaint = get_taint();
int err;
if (write && !capable(CAP_SYS_ADMIN))
return -EPERM;
t = *table;
t.data = &tmptaint;
err = proc_doulongvec_minmax(&t, write, filp, buffer, lenp, ppos);
if (err < 0)
return err;
if (write) {
/*
* Poor man's atomic or. Not worth adding a primitive
* to everyone's atomic.h for this
*/
int i;
for (i = 0; i < BITS_PER_LONG && tmptaint >> i; i++) {
if ((tmptaint >> i) & 1)
add_taint(i);
}
}
return err;
}
struct do_proc_dointvec_minmax_conv_param {
int *min;
int *max;
};
static int do_proc_dointvec_minmax_conv(int *negp, unsigned long *lvalp,
int *valp,
int write, void *data)
{
struct do_proc_dointvec_minmax_conv_param *param = data;
if (write) {
int val = *negp ? -*lvalp : *lvalp;
if ((param->min && *param->min > val) ||
(param->max && *param->max < val))
return -EINVAL;
*valp = val;
} else {
int val = *valp;
if (val < 0) {
*negp = -1;
*lvalp = (unsigned long)-val;
} else {
*negp = 0;
*lvalp = (unsigned long)val;
}
}
return 0;
}
/**
* proc_dointvec_minmax - read a vector of integers with min/max values
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: file position
*
* Reads/writes up to table->maxlen/sizeof(unsigned int) integer
* values from/to the user buffer, treated as an ASCII string.
*
* This routine will ensure the values are within the range specified by
* table->extra1 (min) and table->extra2 (max).
*
* Returns 0 on success.
*/
int proc_dointvec_minmax(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct do_proc_dointvec_minmax_conv_param param = {
.min = (int *) table->extra1,
.max = (int *) table->extra2,
};
return do_proc_dointvec(table, write, filp, buffer, lenp, ppos,
do_proc_dointvec_minmax_conv, ¶m);
}
static int __do_proc_doulongvec_minmax(void *data, struct ctl_table *table, int write,
struct file *filp,
void __user *buffer,
size_t *lenp, loff_t *ppos,
unsigned long convmul,
unsigned long convdiv)
{
#define TMPBUFLEN 21
unsigned long *i, *min, *max, val;
int vleft, first=1, neg;
size_t len, left;
char buf[TMPBUFLEN], *p;
char __user *s = buffer;
if (!data || !table->maxlen || !*lenp ||
(*ppos && !write)) {
*lenp = 0;
return 0;
}
i = (unsigned long *) data;
min = (unsigned long *) table->extra1;
max = (unsigned long *) table->extra2;
vleft = table->maxlen / sizeof(unsigned long);
left = *lenp;
for (; left && vleft--; i++, min++, max++, first=0) {
if (write) {
while (left) {
char c;
if (get_user(c, s))
return -EFAULT;
if (!isspace(c))
break;
left--;
s++;
}
if (!left)
break;
neg = 0;
len = left;
if (len > TMPBUFLEN-1)
len = TMPBUFLEN-1;
if (copy_from_user(buf, s, len))
return -EFAULT;
buf[len] = 0;
p = buf;
if (*p == '-' && left > 1) {
neg = 1;
p++;
}
if (*p < '0' || *p > '9')
break;
val = simple_strtoul(p, &p, 0) * convmul / convdiv ;
len = p-buf;
if ((len < left) && *p && !isspace(*p))
break;
if (neg)
val = -val;
s += len;
left -= len;
if(neg)
continue;
if ((min && val < *min) || (max && val > *max))
continue;
*i = val;
} else {
p = buf;
if (!first)
*p++ = '\t';
sprintf(p, "%lu", convdiv * (*i) / convmul);
len = strlen(buf);
if (len > left)
len = left;
if(copy_to_user(s, buf, len))
return -EFAULT;
left -= len;
s += len;
}
}
if (!write && !first && left) {
if(put_user('\n', s))
return -EFAULT;
left--, s++;
}
if (write) {
while (left) {
char c;
if (get_user(c, s++))
return -EFAULT;
if (!isspace(c))
break;
left--;
}
}
if (write && first)
return -EINVAL;
*lenp -= left;
*ppos += *lenp;
return 0;
#undef TMPBUFLEN
}
static int do_proc_doulongvec_minmax(struct ctl_table *table, int write,
struct file *filp,
void __user *buffer,
size_t *lenp, loff_t *ppos,
unsigned long convmul,
unsigned long convdiv)
{
return __do_proc_doulongvec_minmax(table->data, table, write,
filp, buffer, lenp, ppos, convmul, convdiv);
}
/**
* proc_doulongvec_minmax - read a vector of long integers with min/max values
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: file position
*
* Reads/writes up to table->maxlen/sizeof(unsigned long) unsigned long
* values from/to the user buffer, treated as an ASCII string.
*
* This routine will ensure the values are within the range specified by
* table->extra1 (min) and table->extra2 (max).
*
* Returns 0 on success.
*/
int proc_doulongvec_minmax(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return do_proc_doulongvec_minmax(table, write, filp, buffer, lenp, ppos, 1l, 1l);
}
/**
* proc_doulongvec_ms_jiffies_minmax - read a vector of millisecond values with min/max values
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: file position
*
* Reads/writes up to table->maxlen/sizeof(unsigned long) unsigned long
* values from/to the user buffer, treated as an ASCII string. The values
* are treated as milliseconds, and converted to jiffies when they are stored.
*
* This routine will ensure the values are within the range specified by
* table->extra1 (min) and table->extra2 (max).
*
* Returns 0 on success.
*/
int proc_doulongvec_ms_jiffies_minmax(struct ctl_table *table, int write,
struct file *filp,
void __user *buffer,
size_t *lenp, loff_t *ppos)
{
return do_proc_doulongvec_minmax(table, write, filp, buffer,
lenp, ppos, HZ, 1000l);
}
static int do_proc_dointvec_jiffies_conv(int *negp, unsigned long *lvalp,
int *valp,
int write, void *data)
{
if (write) {
if (*lvalp > LONG_MAX / HZ)
return 1;
*valp = *negp ? -(*lvalp*HZ) : (*lvalp*HZ);
} else {
int val = *valp;
unsigned long lval;
if (val < 0) {
*negp = -1;
lval = (unsigned long)-val;
} else {
*negp = 0;
lval = (unsigned long)val;
}
*lvalp = lval / HZ;
}
return 0;
}
static int do_proc_dointvec_userhz_jiffies_conv(int *negp, unsigned long *lvalp,
int *valp,
int write, void *data)
{
if (write) {
if (USER_HZ < HZ && *lvalp > (LONG_MAX / HZ) * USER_HZ)
return 1;
*valp = clock_t_to_jiffies(*negp ? -*lvalp : *lvalp);
} else {
int val = *valp;
unsigned long lval;
if (val < 0) {
*negp = -1;
lval = (unsigned long)-val;
} else {
*negp = 0;
lval = (unsigned long)val;
}
*lvalp = jiffies_to_clock_t(lval);
}
return 0;
}
static int do_proc_dointvec_ms_jiffies_conv(int *negp, unsigned long *lvalp,
int *valp,
int write, void *data)
{
if (write) {
*valp = msecs_to_jiffies(*negp ? -*lvalp : *lvalp);
} else {
int val = *valp;
unsigned long lval;
if (val < 0) {
*negp = -1;
lval = (unsigned long)-val;
} else {
*negp = 0;
lval = (unsigned long)val;
}
*lvalp = jiffies_to_msecs(lval);
}
return 0;
}
/**
* proc_dointvec_jiffies - read a vector of integers as seconds
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: file position
*
* Reads/writes up to table->maxlen/sizeof(unsigned int) integer
* values from/to the user buffer, treated as an ASCII string.
* The values read are assumed to be in seconds, and are converted into
* jiffies.
*
* Returns 0 on success.
*/
int proc_dointvec_jiffies(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return do_proc_dointvec(table,write,filp,buffer,lenp,ppos,
do_proc_dointvec_jiffies_conv,NULL);
}
/**
* proc_dointvec_userhz_jiffies - read a vector of integers as 1/USER_HZ seconds
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: pointer to the file position
*
* Reads/writes up to table->maxlen/sizeof(unsigned int) integer
* values from/to the user buffer, treated as an ASCII string.
* The values read are assumed to be in 1/USER_HZ seconds, and
* are converted into jiffies.
*
* Returns 0 on success.
*/
int proc_dointvec_userhz_jiffies(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return do_proc_dointvec(table,write,filp,buffer,lenp,ppos,
do_proc_dointvec_userhz_jiffies_conv,NULL);
}
/**
* proc_dointvec_ms_jiffies - read a vector of integers as 1 milliseconds
* @table: the sysctl table
* @write: %TRUE if this is a write to the sysctl file
* @filp: the file structure
* @buffer: the user buffer
* @lenp: the size of the user buffer
* @ppos: file position
* @ppos: the current position in the file
*
* Reads/writes up to table->maxlen/sizeof(unsigned int) integer
* values from/to the user buffer, treated as an ASCII string.
* The values read are assumed to be in 1/1000 seconds, and
* are converted into jiffies.
*
* Returns 0 on success.
*/
int proc_dointvec_ms_jiffies(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return do_proc_dointvec(table, write, filp, buffer, lenp, ppos,
do_proc_dointvec_ms_jiffies_conv, NULL);
}
static int proc_do_cad_pid(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct pid *new_pid;
pid_t tmp;
int r;
tmp = pid_vnr(cad_pid);
r = __do_proc_dointvec(&tmp, table, write, filp, buffer,
lenp, ppos, NULL, NULL);
if (r || !write)
return r;
new_pid = find_get_pid(tmp);
if (!new_pid)
return -ESRCH;
put_pid(xchg(&cad_pid, new_pid));
return 0;
}
#else /* CONFIG_PROC_FS */
int proc_dostring(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
int proc_dointvec(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
int proc_dointvec_minmax(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
int proc_dointvec_jiffies(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
int proc_dointvec_userhz_jiffies(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
int proc_dointvec_ms_jiffies(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
int proc_doulongvec_minmax(struct ctl_table *table, int write, struct file *filp,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
int proc_doulongvec_ms_jiffies_minmax(struct ctl_table *table, int write,
struct file *filp,
void __user *buffer,
size_t *lenp, loff_t *ppos)
{
return -ENOSYS;
}
#endif /* CONFIG_PROC_FS */
#ifdef CONFIG_SYSCTL_SYSCALL
/*
* General sysctl support routines
*/
/* The generic sysctl data routine (used if no strategy routine supplied) */
int sysctl_data(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
size_t len;
/* Get out of I don't have a variable */
if (!table->data || !table->maxlen)
return -ENOTDIR;
if (oldval && oldlenp) {
if (get_user(len, oldlenp))
return -EFAULT;
if (len) {
if (len > table->maxlen)
len = table->maxlen;
if (copy_to_user(oldval, table->data, len))
return -EFAULT;
if (put_user(len, oldlenp))
return -EFAULT;
}
}
if (newval && newlen) {
if (newlen > table->maxlen)
newlen = table->maxlen;
if (copy_from_user(table->data, newval, newlen))
return -EFAULT;
}
return 1;
}
/* The generic string strategy routine: */
int sysctl_string(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
if (!table->data || !table->maxlen)
return -ENOTDIR;
if (oldval && oldlenp) {
size_t bufsize;
if (get_user(bufsize, oldlenp))
return -EFAULT;
if (bufsize) {
size_t len = strlen(table->data), copied;
/* This shouldn't trigger for a well-formed sysctl */
if (len > table->maxlen)
len = table->maxlen;
/* Copy up to a max of bufsize-1 bytes of the string */
copied = (len >= bufsize) ? bufsize - 1 : len;
if (copy_to_user(oldval, table->data, copied) ||
put_user(0, (char __user *)(oldval + copied)))
return -EFAULT;
if (put_user(len, oldlenp))
return -EFAULT;
}
}
if (newval && newlen) {
size_t len = newlen;
if (len > table->maxlen)
len = table->maxlen;
if(copy_from_user(table->data, newval, len))
return -EFAULT;
if (len == table->maxlen)
len--;
((char *) table->data)[len] = 0;
}
return 1;
}
/*
* This function makes sure that all of the integers in the vector
* are between the minimum and maximum values given in the arrays
* table->extra1 and table->extra2, respectively.
*/
int sysctl_intvec(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
if (newval && newlen) {
int __user *vec = (int __user *) newval;
int *min = (int *) table->extra1;
int *max = (int *) table->extra2;
size_t length;
int i;
if (newlen % sizeof(int) != 0)
return -EINVAL;
if (!table->extra1 && !table->extra2)
return 0;
if (newlen > table->maxlen)
newlen = table->maxlen;
length = newlen / sizeof(int);
for (i = 0; i < length; i++) {
int value;
if (get_user(value, vec + i))
return -EFAULT;
if (min && value < min[i])
return -EINVAL;
if (max && value > max[i])
return -EINVAL;
}
}
return 0;
}
/* Strategy function to convert jiffies to seconds */
int sysctl_jiffies(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
if (oldval && oldlenp) {
size_t olen;
if (get_user(olen, oldlenp))
return -EFAULT;
if (olen) {
int val;
if (olen < sizeof(int))
return -EINVAL;
val = *(int *)(table->data) / HZ;
if (put_user(val, (int __user *)oldval))
return -EFAULT;
if (put_user(sizeof(int), oldlenp))
return -EFAULT;
}
}
if (newval && newlen) {
int new;
if (newlen != sizeof(int))
return -EINVAL;
if (get_user(new, (int __user *)newval))
return -EFAULT;
*(int *)(table->data) = new*HZ;
}
return 1;
}
/* Strategy function to convert jiffies to seconds */
int sysctl_ms_jiffies(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
if (oldval && oldlenp) {
size_t olen;
if (get_user(olen, oldlenp))
return -EFAULT;
if (olen) {
int val;
if (olen < sizeof(int))
return -EINVAL;
val = jiffies_to_msecs(*(int *)(table->data));
if (put_user(val, (int __user *)oldval))
return -EFAULT;
if (put_user(sizeof(int), oldlenp))
return -EFAULT;
}
}
if (newval && newlen) {
int new;
if (newlen != sizeof(int))
return -EINVAL;
if (get_user(new, (int __user *)newval))
return -EFAULT;
*(int *)(table->data) = msecs_to_jiffies(new);
}
return 1;
}
#else /* CONFIG_SYSCTL_SYSCALL */
SYSCALL_DEFINE1(sysctl, struct __sysctl_args __user *, args)
{
struct __sysctl_args tmp;
int error;
if (copy_from_user(&tmp, args, sizeof(tmp)))
return -EFAULT;
error = deprecated_sysctl_warning(&tmp);
/* If no error reading the parameters then just -ENOSYS ... */
if (!error)
error = -ENOSYS;
return error;
}
int sysctl_data(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
return -ENOSYS;
}
int sysctl_string(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
return -ENOSYS;
}
int sysctl_intvec(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
return -ENOSYS;
}
int sysctl_jiffies(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
return -ENOSYS;
}
int sysctl_ms_jiffies(struct ctl_table *table,
void __user *oldval, size_t __user *oldlenp,
void __user *newval, size_t newlen)
{
return -ENOSYS;
}
#endif /* CONFIG_SYSCTL_SYSCALL */
static int deprecated_sysctl_warning(struct __sysctl_args *args)
{
static int msg_count;
int name[CTL_MAXNAME];
int i;
/* Check args->nlen. */
if (args->nlen < 0 || args->nlen > CTL_MAXNAME)
return -ENOTDIR;
/* Read in the sysctl name for better debug message logging */
for (i = 0; i < args->nlen; i++)
if (get_user(name[i], args->name + i))
return -EFAULT;
/* Ignore accesses to kernel.version */
if ((args->nlen == 2) && (name[0] == CTL_KERN) && (name[1] == KERN_VERSION))
return 0;
if (msg_count < 5) {
msg_count++;
printk(KERN_INFO
"warning: process `%s' used the deprecated sysctl "
"system call with ", current->comm);
for (i = 0; i < args->nlen; i++)
printk("%d.", name[i]);
printk("\n");
}
return 0;
}
/*
* No sense putting this after each symbol definition, twice,
* exception granted :-)
*/
EXPORT_SYMBOL(proc_dointvec);
EXPORT_SYMBOL(proc_dointvec_jiffies);
EXPORT_SYMBOL(proc_dointvec_minmax);
EXPORT_SYMBOL(proc_dointvec_userhz_jiffies);
EXPORT_SYMBOL(proc_dointvec_ms_jiffies);
EXPORT_SYMBOL(proc_dostring);
EXPORT_SYMBOL(proc_doulongvec_minmax);
EXPORT_SYMBOL(proc_doulongvec_ms_jiffies_minmax);
EXPORT_SYMBOL(register_sysctl_table);
EXPORT_SYMBOL(register_sysctl_paths);
EXPORT_SYMBOL(sysctl_intvec);
EXPORT_SYMBOL(sysctl_jiffies);
EXPORT_SYMBOL(sysctl_ms_jiffies);
EXPORT_SYMBOL(sysctl_string);
EXPORT_SYMBOL(sysctl_data);
EXPORT_SYMBOL(unregister_sysctl_table);
| gpl-2.0 |
dremaker/imx6ul_linux | drivers/scsi/lpfc/lpfc_ct.c | 522 | 54174 | /*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2004-2013 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.emulex.com *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of version 2 of the GNU General *
* Public License as published by the Free Software Foundation. *
* This program is distributed in the hope that it will be useful. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
/*
* Fibre Channel SCSI LAN Device Driver CT support: FC Generic Services FC-GS
*/
#include <linux/blkdev.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/utsname.h>
#include <scsi/scsi.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_fc.h>
#include <scsi/fc/fc_fs.h>
#include "lpfc_hw4.h"
#include "lpfc_hw.h"
#include "lpfc_sli.h"
#include "lpfc_sli4.h"
#include "lpfc_nl.h"
#include "lpfc_disc.h"
#include "lpfc_scsi.h"
#include "lpfc.h"
#include "lpfc_logmsg.h"
#include "lpfc_crtn.h"
#include "lpfc_version.h"
#include "lpfc_vport.h"
#include "lpfc_debugfs.h"
/* FDMI Port Speed definitions */
#define HBA_PORTSPEED_1GBIT 0x0001 /* 1 GBit/sec */
#define HBA_PORTSPEED_2GBIT 0x0002 /* 2 GBit/sec */
#define HBA_PORTSPEED_4GBIT 0x0008 /* 4 GBit/sec */
#define HBA_PORTSPEED_10GBIT 0x0004 /* 10 GBit/sec */
#define HBA_PORTSPEED_8GBIT 0x0010 /* 8 GBit/sec */
#define HBA_PORTSPEED_16GBIT 0x0020 /* 16 GBit/sec */
#define HBA_PORTSPEED_UNKNOWN 0x0800 /* Unknown */
#define FOURBYTES 4
static char *lpfc_release_version = LPFC_DRIVER_VERSION;
static void
lpfc_ct_ignore_hbq_buffer(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
struct lpfc_dmabuf *mp, uint32_t size)
{
if (!mp) {
lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
"0146 Ignoring unsolicited CT No HBQ "
"status = x%x\n",
piocbq->iocb.ulpStatus);
}
lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
"0145 Ignoring unsolicted CT HBQ Size:%d "
"status = x%x\n",
size, piocbq->iocb.ulpStatus);
}
static void
lpfc_ct_unsol_buffer(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
struct lpfc_dmabuf *mp, uint32_t size)
{
lpfc_ct_ignore_hbq_buffer(phba, piocbq, mp, size);
}
void
lpfc_ct_unsol_event(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
struct lpfc_iocbq *piocbq)
{
struct lpfc_dmabuf *mp = NULL;
IOCB_t *icmd = &piocbq->iocb;
int i;
struct lpfc_iocbq *iocbq;
dma_addr_t paddr;
uint32_t size;
struct list_head head;
struct lpfc_dmabuf *bdeBuf;
if (lpfc_bsg_ct_unsol_event(phba, pring, piocbq) == 0)
return;
if (unlikely(icmd->ulpStatus == IOSTAT_NEED_BUFFER)) {
lpfc_sli_hbqbuf_add_hbqs(phba, LPFC_ELS_HBQ);
} else if ((icmd->ulpStatus == IOSTAT_LOCAL_REJECT) &&
((icmd->un.ulpWord[4] & IOERR_PARAM_MASK) ==
IOERR_RCV_BUFFER_WAITING)) {
/* Not enough posted buffers; Try posting more buffers */
phba->fc_stat.NoRcvBuf++;
if (!(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED))
lpfc_post_buffer(phba, pring, 2);
return;
}
/* If there are no BDEs associated with this IOCB,
* there is nothing to do.
*/
if (icmd->ulpBdeCount == 0)
return;
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
INIT_LIST_HEAD(&head);
list_add_tail(&head, &piocbq->list);
list_for_each_entry(iocbq, &head, list) {
icmd = &iocbq->iocb;
if (icmd->ulpBdeCount == 0)
continue;
bdeBuf = iocbq->context2;
iocbq->context2 = NULL;
size = icmd->un.cont64[0].tus.f.bdeSize;
lpfc_ct_unsol_buffer(phba, piocbq, bdeBuf, size);
lpfc_in_buf_free(phba, bdeBuf);
if (icmd->ulpBdeCount == 2) {
bdeBuf = iocbq->context3;
iocbq->context3 = NULL;
size = icmd->unsli3.rcvsli3.bde2.tus.f.bdeSize;
lpfc_ct_unsol_buffer(phba, piocbq, bdeBuf,
size);
lpfc_in_buf_free(phba, bdeBuf);
}
}
list_del(&head);
} else {
INIT_LIST_HEAD(&head);
list_add_tail(&head, &piocbq->list);
list_for_each_entry(iocbq, &head, list) {
icmd = &iocbq->iocb;
if (icmd->ulpBdeCount == 0)
lpfc_ct_unsol_buffer(phba, iocbq, NULL, 0);
for (i = 0; i < icmd->ulpBdeCount; i++) {
paddr = getPaddr(icmd->un.cont64[i].addrHigh,
icmd->un.cont64[i].addrLow);
mp = lpfc_sli_ringpostbuf_get(phba, pring,
paddr);
size = icmd->un.cont64[i].tus.f.bdeSize;
lpfc_ct_unsol_buffer(phba, iocbq, mp, size);
lpfc_in_buf_free(phba, mp);
}
lpfc_post_buffer(phba, pring, i);
}
list_del(&head);
}
}
/**
* lpfc_ct_handle_unsol_abort - ct upper level protocol abort handler
* @phba: Pointer to HBA context object.
* @dmabuf: pointer to a dmabuf that describes the FC sequence
*
* This function serves as the upper level protocol abort handler for CT
* protocol.
*
* Return 1 if abort has been handled, 0 otherwise.
**/
int
lpfc_ct_handle_unsol_abort(struct lpfc_hba *phba, struct hbq_dmabuf *dmabuf)
{
int handled;
/* CT upper level goes through BSG */
handled = lpfc_bsg_ct_unsol_abort(phba, dmabuf);
return handled;
}
static void
lpfc_free_ct_rsp(struct lpfc_hba *phba, struct lpfc_dmabuf *mlist)
{
struct lpfc_dmabuf *mlast, *next_mlast;
list_for_each_entry_safe(mlast, next_mlast, &mlist->list, list) {
lpfc_mbuf_free(phba, mlast->virt, mlast->phys);
list_del(&mlast->list);
kfree(mlast);
}
lpfc_mbuf_free(phba, mlist->virt, mlist->phys);
kfree(mlist);
return;
}
static struct lpfc_dmabuf *
lpfc_alloc_ct_rsp(struct lpfc_hba *phba, int cmdcode, struct ulp_bde64 *bpl,
uint32_t size, int *entries)
{
struct lpfc_dmabuf *mlist = NULL;
struct lpfc_dmabuf *mp;
int cnt, i = 0;
/* We get chunks of FCELSSIZE */
cnt = size > FCELSSIZE ? FCELSSIZE: size;
while (size) {
/* Allocate buffer for rsp payload */
mp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!mp) {
if (mlist)
lpfc_free_ct_rsp(phba, mlist);
return NULL;
}
INIT_LIST_HEAD(&mp->list);
if (cmdcode == be16_to_cpu(SLI_CTNS_GID_FT) ||
cmdcode == be16_to_cpu(SLI_CTNS_GFF_ID))
mp->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &(mp->phys));
else
mp->virt = lpfc_mbuf_alloc(phba, 0, &(mp->phys));
if (!mp->virt) {
kfree(mp);
if (mlist)
lpfc_free_ct_rsp(phba, mlist);
return NULL;
}
/* Queue it to a linked list */
if (!mlist)
mlist = mp;
else
list_add_tail(&mp->list, &mlist->list);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
/* build buffer ptr list for IOCB */
bpl->addrLow = le32_to_cpu(putPaddrLow(mp->phys) );
bpl->addrHigh = le32_to_cpu(putPaddrHigh(mp->phys) );
bpl->tus.f.bdeSize = (uint16_t) cnt;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
bpl++;
i++;
size -= cnt;
}
*entries = i;
return mlist;
}
int
lpfc_ct_free_iocb(struct lpfc_hba *phba, struct lpfc_iocbq *ctiocb)
{
struct lpfc_dmabuf *buf_ptr;
if (ctiocb->context_un.ndlp) {
lpfc_nlp_put(ctiocb->context_un.ndlp);
ctiocb->context_un.ndlp = NULL;
}
if (ctiocb->context1) {
buf_ptr = (struct lpfc_dmabuf *) ctiocb->context1;
lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
kfree(buf_ptr);
ctiocb->context1 = NULL;
}
if (ctiocb->context2) {
lpfc_free_ct_rsp(phba, (struct lpfc_dmabuf *) ctiocb->context2);
ctiocb->context2 = NULL;
}
if (ctiocb->context3) {
buf_ptr = (struct lpfc_dmabuf *) ctiocb->context3;
lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
kfree(buf_ptr);
ctiocb->context3 = NULL;
}
lpfc_sli_release_iocbq(phba, ctiocb);
return 0;
}
static int
lpfc_gen_req(struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
struct lpfc_dmabuf *inp, struct lpfc_dmabuf *outp,
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *),
struct lpfc_nodelist *ndlp, uint32_t usr_flg, uint32_t num_entry,
uint32_t tmo, uint8_t retry)
{
struct lpfc_hba *phba = vport->phba;
IOCB_t *icmd;
struct lpfc_iocbq *geniocb;
int rc;
/* Allocate buffer for command iocb */
geniocb = lpfc_sli_get_iocbq(phba);
if (geniocb == NULL)
return 1;
icmd = &geniocb->iocb;
icmd->un.genreq64.bdl.ulpIoTag32 = 0;
icmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
icmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
icmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
icmd->un.genreq64.bdl.bdeSize = (num_entry * sizeof (struct ulp_bde64));
if (usr_flg)
geniocb->context3 = NULL;
else
geniocb->context3 = (uint8_t *) bmp;
/* Save for completion so we can release these resources */
geniocb->context1 = (uint8_t *) inp;
geniocb->context2 = (uint8_t *) outp;
geniocb->context_un.ndlp = lpfc_nlp_get(ndlp);
/* Fill in payload, bp points to frame payload */
icmd->ulpCommand = CMD_GEN_REQUEST64_CR;
/* Fill in rest of iocb */
icmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
icmd->un.genreq64.w5.hcsw.Dfctl = 0;
icmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
icmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
if (!tmo) {
/* FC spec states we need 3 * ratov for CT requests */
tmo = (3 * phba->fc_ratov);
}
icmd->ulpTimeout = tmo;
icmd->ulpBdeCount = 1;
icmd->ulpLe = 1;
icmd->ulpClass = CLASS3;
icmd->ulpContext = ndlp->nlp_rpi;
if (phba->sli_rev == LPFC_SLI_REV4)
icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
/* For GEN_REQUEST64_CR, use the RPI */
icmd->ulpCt_h = 0;
icmd->ulpCt_l = 0;
}
/* Issue GEN REQ IOCB for NPORT <did> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
"0119 Issue GEN REQ IOCB to NPORT x%x "
"Data: x%x x%x\n",
ndlp->nlp_DID, icmd->ulpIoTag,
vport->port_state);
geniocb->iocb_cmpl = cmpl;
geniocb->drvrTimeout = icmd->ulpTimeout + LPFC_DRVR_TIMEOUT;
geniocb->vport = vport;
geniocb->retry = retry;
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, geniocb, 0);
if (rc == IOCB_ERROR) {
lpfc_sli_release_iocbq(phba, geniocb);
return 1;
}
return 0;
}
static int
lpfc_ct_cmd(struct lpfc_vport *vport, struct lpfc_dmabuf *inmp,
struct lpfc_dmabuf *bmp, struct lpfc_nodelist *ndlp,
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *),
uint32_t rsp_size, uint8_t retry)
{
struct lpfc_hba *phba = vport->phba;
struct ulp_bde64 *bpl = (struct ulp_bde64 *) bmp->virt;
struct lpfc_dmabuf *outmp;
int cnt = 0, status;
int cmdcode = ((struct lpfc_sli_ct_request *) inmp->virt)->
CommandResponse.bits.CmdRsp;
bpl++; /* Skip past ct request */
/* Put buffer(s) for ct rsp in bpl */
outmp = lpfc_alloc_ct_rsp(phba, cmdcode, bpl, rsp_size, &cnt);
if (!outmp)
return -ENOMEM;
/*
* Form the CT IOCB. The total number of BDEs in this IOCB
* is the single command plus response count from
* lpfc_alloc_ct_rsp.
*/
cnt += 1;
status = lpfc_gen_req(vport, bmp, inmp, outmp, cmpl, ndlp, 0,
cnt, 0, retry);
if (status) {
lpfc_free_ct_rsp(phba, outmp);
return -ENOMEM;
}
return 0;
}
struct lpfc_vport *
lpfc_find_vport_by_did(struct lpfc_hba *phba, uint32_t did) {
struct lpfc_vport *vport_curr;
unsigned long flags;
spin_lock_irqsave(&phba->hbalock, flags);
list_for_each_entry(vport_curr, &phba->port_list, listentry) {
if ((vport_curr->fc_myDID) && (vport_curr->fc_myDID == did)) {
spin_unlock_irqrestore(&phba->hbalock, flags);
return vport_curr;
}
}
spin_unlock_irqrestore(&phba->hbalock, flags);
return NULL;
}
static int
lpfc_ns_rsp(struct lpfc_vport *vport, struct lpfc_dmabuf *mp, uint32_t Size)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_sli_ct_request *Response =
(struct lpfc_sli_ct_request *) mp->virt;
struct lpfc_nodelist *ndlp = NULL;
struct lpfc_dmabuf *mlast, *next_mp;
uint32_t *ctptr = (uint32_t *) & Response->un.gid.PortType;
uint32_t Did, CTentry;
int Cnt;
struct list_head head;
lpfc_set_disctmo(vport);
vport->num_disc_nodes = 0;
vport->fc_ns_retry = 0;
list_add_tail(&head, &mp->list);
list_for_each_entry_safe(mp, next_mp, &head, list) {
mlast = mp;
Cnt = Size > FCELSSIZE ? FCELSSIZE : Size;
Size -= Cnt;
if (!ctptr) {
ctptr = (uint32_t *) mlast->virt;
} else
Cnt -= 16; /* subtract length of CT header */
/* Loop through entire NameServer list of DIDs */
while (Cnt >= sizeof (uint32_t)) {
/* Get next DID from NameServer List */
CTentry = *ctptr++;
Did = ((be32_to_cpu(CTentry)) & Mask_DID);
ndlp = NULL;
/*
* Check for rscn processing or not
* To conserve rpi's, filter out addresses for other
* vports on the same physical HBAs.
*/
if ((Did != vport->fc_myDID) &&
((lpfc_find_vport_by_did(phba, Did) == NULL) ||
vport->cfg_peer_port_login)) {
if ((vport->port_type != LPFC_NPIV_PORT) ||
(!(vport->ct_flags & FC_CT_RFF_ID)) ||
(!vport->cfg_restrict_login)) {
ndlp = lpfc_setup_disc_node(vport, Did);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)) {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Parse GID_FTrsp: "
"did:x%x flg:x%x x%x",
Did, ndlp->nlp_flag,
vport->fc_flag);
lpfc_printf_vlog(vport,
KERN_INFO,
LOG_DISCOVERY,
"0238 Process "
"x%x NameServer Rsp"
"Data: x%x x%x x%x\n",
Did, ndlp->nlp_flag,
vport->fc_flag,
vport->fc_rscn_id_cnt);
} else {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Skip1 GID_FTrsp: "
"did:x%x flg:x%x cnt:%d",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
lpfc_printf_vlog(vport,
KERN_INFO,
LOG_DISCOVERY,
"0239 Skip x%x "
"NameServer Rsp Data: "
"x%x x%x\n",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
}
} else {
if (!(vport->fc_flag & FC_RSCN_MODE) ||
(lpfc_rscn_payload_check(vport, Did))) {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Query GID_FTrsp: "
"did:x%x flg:x%x cnt:%d",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
/* This NPortID was previously
* a FCP target, * Don't even
* bother to send GFF_ID.
*/
ndlp = lpfc_findnode_did(vport,
Did);
if (ndlp &&
NLP_CHK_NODE_ACT(ndlp)
&& (ndlp->nlp_type &
NLP_FCP_TARGET))
lpfc_setup_disc_node
(vport, Did);
else if (lpfc_ns_cmd(vport,
SLI_CTNS_GFF_ID,
0, Did) == 0)
vport->num_disc_nodes++;
else
lpfc_setup_disc_node
(vport, Did);
}
else {
lpfc_debugfs_disc_trc(vport,
LPFC_DISC_TRC_CT,
"Skip2 GID_FTrsp: "
"did:x%x flg:x%x cnt:%d",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
lpfc_printf_vlog(vport,
KERN_INFO,
LOG_DISCOVERY,
"0245 Skip x%x "
"NameServer Rsp Data: "
"x%x x%x\n",
Did, vport->fc_flag,
vport->fc_rscn_id_cnt);
}
}
}
if (CTentry & (be32_to_cpu(SLI_CT_LAST_ENTRY)))
goto nsout1;
Cnt -= sizeof (uint32_t);
}
ctptr = NULL;
}
nsout1:
list_del(&head);
return 0;
}
static void
lpfc_cmpl_ct_cmd_gid_ft(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
IOCB_t *irsp;
struct lpfc_dmabuf *bmp;
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
struct lpfc_nodelist *ndlp;
int rc;
/* First save ndlp, before we overwrite it */
ndlp = cmdiocb->context_un.ndlp;
/* we pass cmdiocb to state machine which needs rspiocb as well */
cmdiocb->context_un.rsp_iocb = rspiocb;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
bmp = (struct lpfc_dmabuf *) cmdiocb->context3;
irsp = &rspiocb->iocb;
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT cmpl: status:x%x/x%x rtry:%d",
irsp->ulpStatus, irsp->un.ulpWord[4], vport->fc_ns_retry);
/* Don't bother processing response if vport is being torn down. */
if (vport->load_flag & FC_UNLOADING) {
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
goto out;
}
if (lpfc_els_chk_latt(vport)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0216 Link event during NS query\n");
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
goto out;
}
if (lpfc_error_lost_link(irsp)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0226 NS query failed due to link event\n");
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
goto out;
}
if (irsp->ulpStatus) {
/* Check for retry */
if (vport->fc_ns_retry < LPFC_MAX_NS_RETRY) {
if (irsp->ulpStatus != IOSTAT_LOCAL_REJECT ||
(irsp->un.ulpWord[4] & IOERR_PARAM_MASK) !=
IOERR_NO_RESOURCES)
vport->fc_ns_retry++;
/* CT command is being retried */
rc = lpfc_ns_cmd(vport, SLI_CTNS_GID_FT,
vport->fc_ns_retry, 0);
if (rc == 0)
goto out;
}
if (vport->fc_flag & FC_RSCN_MODE)
lpfc_els_flush_rscn(vport);
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0257 GID_FT Query error: 0x%x 0x%x\n",
irsp->ulpStatus, vport->fc_ns_retry);
} else {
/* Good status, continue checking */
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0208 NameServer Rsp Data: x%x\n",
vport->fc_flag);
lpfc_ns_rsp(vport, outp,
(uint32_t) (irsp->un.genreq64.bdl.bdeSize));
} else if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_RJT)) {
/* NameServer Rsp Error */
if ((CTrsp->ReasonCode == SLI_CT_UNABLE_TO_PERFORM_REQ)
&& (CTrsp->Explanation == SLI_CT_NO_FC4_TYPES)) {
lpfc_printf_vlog(vport, KERN_INFO,
LOG_DISCOVERY,
"0269 No NameServer Entries "
"Data: x%x x%x x%x x%x\n",
CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation,
vport->fc_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT no entry cmd:x%x rsn:x%x exp:x%x",
(uint32_t)CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation);
} else {
lpfc_printf_vlog(vport, KERN_INFO,
LOG_DISCOVERY,
"0240 NameServer Rsp Error "
"Data: x%x x%x x%x x%x\n",
CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation,
vport->fc_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT rsp err1 cmd:x%x rsn:x%x exp:x%x",
(uint32_t)CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation);
}
} else {
/* NameServer Rsp Error */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0241 NameServer Rsp Error "
"Data: x%x x%x x%x x%x\n",
CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation,
vport->fc_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GID_FT rsp err2 cmd:x%x rsn:x%x exp:x%x",
(uint32_t)CTrsp->CommandResponse.bits.CmdRsp,
(uint32_t) CTrsp->ReasonCode,
(uint32_t) CTrsp->Explanation);
}
}
/* Link up / RSCN discovery */
if (vport->num_disc_nodes == 0) {
/*
* The driver has cycled through all Nports in the RSCN payload.
* Complete the handling by cleaning up and marking the
* current driver state.
*/
if (vport->port_state >= LPFC_DISC_AUTH) {
if (vport->fc_flag & FC_RSCN_MODE) {
lpfc_els_flush_rscn(vport);
spin_lock_irq(shost->host_lock);
vport->fc_flag |= FC_RSCN_MODE; /* RSCN still */
spin_unlock_irq(shost->host_lock);
}
else
lpfc_els_flush_rscn(vport);
}
lpfc_disc_start(vport);
}
out:
cmdiocb->context_un.ndlp = ndlp; /* Now restore ndlp for free */
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_gff_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_dmabuf *inp = (struct lpfc_dmabuf *) cmdiocb->context1;
struct lpfc_dmabuf *outp = (struct lpfc_dmabuf *) cmdiocb->context2;
struct lpfc_sli_ct_request *CTrsp;
int did, rc, retry;
uint8_t fbits;
struct lpfc_nodelist *ndlp;
did = ((struct lpfc_sli_ct_request *) inp->virt)->un.gff.PortId;
did = be32_to_cpu(did);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"GFF_ID cmpl: status:x%x/x%x did:x%x",
irsp->ulpStatus, irsp->un.ulpWord[4], did);
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
/* Good status, continue checking */
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
fbits = CTrsp->un.gff_acc.fbits[FCP_TYPE_FEATURE_OFFSET];
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC)) {
if ((fbits & FC4_FEATURE_INIT) &&
!(fbits & FC4_FEATURE_TARGET)) {
lpfc_printf_vlog(vport, KERN_INFO,
LOG_DISCOVERY,
"0270 Skip x%x GFF "
"NameServer Rsp Data: (init) "
"x%x x%x\n", did, fbits,
vport->fc_rscn_id_cnt);
goto out;
}
}
}
else {
/* Check for retry */
if (cmdiocb->retry < LPFC_MAX_NS_RETRY) {
retry = 1;
if (irsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch ((irsp->un.ulpWord[4] &
IOERR_PARAM_MASK)) {
case IOERR_NO_RESOURCES:
/* We don't increment the retry
* count for this case.
*/
break;
case IOERR_LINK_DOWN:
case IOERR_SLI_ABORTED:
case IOERR_SLI_DOWN:
retry = 0;
break;
default:
cmdiocb->retry++;
}
}
else
cmdiocb->retry++;
if (retry) {
/* CT command is being retried */
rc = lpfc_ns_cmd(vport, SLI_CTNS_GFF_ID,
cmdiocb->retry, did);
if (rc == 0) {
/* success */
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
}
}
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0267 NameServer GFF Rsp "
"x%x Error (%d %d) Data: x%x x%x\n",
did, irsp->ulpStatus, irsp->un.ulpWord[4],
vport->fc_flag, vport->fc_rscn_id_cnt);
}
/* This is a target port, unregistered port, or the GFF_ID failed */
ndlp = lpfc_setup_disc_node(vport, did);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0242 Process x%x GFF "
"NameServer Rsp Data: x%x x%x x%x\n",
did, ndlp->nlp_flag, vport->fc_flag,
vport->fc_rscn_id_cnt);
} else {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0243 Skip x%x GFF "
"NameServer Rsp Data: x%x x%x\n", did,
vport->fc_flag, vport->fc_rscn_id_cnt);
}
out:
/* Link up / RSCN discovery */
if (vport->num_disc_nodes)
vport->num_disc_nodes--;
if (vport->num_disc_nodes == 0) {
/*
* The driver has cycled through all Nports in the RSCN payload.
* Complete the handling by cleaning up and marking the
* current driver state.
*/
if (vport->port_state >= LPFC_DISC_AUTH) {
if (vport->fc_flag & FC_RSCN_MODE) {
lpfc_els_flush_rscn(vport);
spin_lock_irq(shost->host_lock);
vport->fc_flag |= FC_RSCN_MODE; /* RSCN still */
spin_unlock_irq(shost->host_lock);
}
else
lpfc_els_flush_rscn(vport);
}
lpfc_disc_start(vport);
}
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
static void
lpfc_cmpl_ct(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
struct lpfc_dmabuf *inp;
struct lpfc_dmabuf *outp;
IOCB_t *irsp;
struct lpfc_sli_ct_request *CTrsp;
struct lpfc_nodelist *ndlp;
int cmdcode, rc;
uint8_t retry;
uint32_t latt;
/* First save ndlp, before we overwrite it */
ndlp = cmdiocb->context_un.ndlp;
/* we pass cmdiocb to state machine which needs rspiocb as well */
cmdiocb->context_un.rsp_iocb = rspiocb;
inp = (struct lpfc_dmabuf *) cmdiocb->context1;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
irsp = &rspiocb->iocb;
cmdcode = be16_to_cpu(((struct lpfc_sli_ct_request *) inp->virt)->
CommandResponse.bits.CmdRsp);
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
latt = lpfc_els_chk_latt(vport);
/* RFT request completes status <ulpStatus> CmdRsp <CmdRsp> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0209 CT Request completes, latt %d, "
"ulpStatus x%x CmdRsp x%x, Context x%x, Tag x%x\n",
latt, irsp->ulpStatus,
CTrsp->CommandResponse.bits.CmdRsp,
cmdiocb->iocb.ulpContext, cmdiocb->iocb.ulpIoTag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"CT cmd cmpl: status:x%x/x%x cmd:x%x",
irsp->ulpStatus, irsp->un.ulpWord[4], cmdcode);
if (irsp->ulpStatus) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0268 NS cmd x%x Error (x%x x%x)\n",
cmdcode, irsp->ulpStatus, irsp->un.ulpWord[4]);
if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
(((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
IOERR_SLI_DOWN) ||
((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
IOERR_SLI_ABORTED)))
goto out;
retry = cmdiocb->retry;
if (retry >= LPFC_MAX_NS_RETRY)
goto out;
retry++;
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0250 Retrying NS cmd %x\n", cmdcode);
rc = lpfc_ns_cmd(vport, cmdcode, retry, 0);
if (rc == 0)
goto out;
}
out:
cmdiocb->context_un.ndlp = ndlp; /* Now restore ndlp for free */
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rft_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RFT_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rnn_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RNN_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rspn_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RSPN_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rsnn_nn(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RSNN_NN;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_da_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_vport *vport = cmdiocb->vport;
/* even if it fails we will act as though it succeeded. */
vport->ct_flags = 0;
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
static void
lpfc_cmpl_ct_cmd_rff_id(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
IOCB_t *irsp = &rspiocb->iocb;
struct lpfc_vport *vport = cmdiocb->vport;
if (irsp->ulpStatus == IOSTAT_SUCCESS) {
struct lpfc_dmabuf *outp;
struct lpfc_sli_ct_request *CTrsp;
outp = (struct lpfc_dmabuf *) cmdiocb->context2;
CTrsp = (struct lpfc_sli_ct_request *) outp->virt;
if (CTrsp->CommandResponse.bits.CmdRsp ==
be16_to_cpu(SLI_CT_RESPONSE_FS_ACC))
vport->ct_flags |= FC_CT_RFF_ID;
}
lpfc_cmpl_ct(phba, cmdiocb, rspiocb);
return;
}
int
lpfc_vport_symbolic_port_name(struct lpfc_vport *vport, char *symbol,
size_t size)
{
int n;
uint8_t *wwn = vport->phba->wwpn;
n = snprintf(symbol, size,
"Emulex PPN-%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
wwn[0], wwn[1], wwn[2], wwn[3],
wwn[4], wwn[5], wwn[6], wwn[7]);
if (vport->port_type == LPFC_PHYSICAL_PORT)
return n;
if (n < size)
n += snprintf(symbol + n, size - n, " VPort-%d", vport->vpi);
if (n < size &&
strlen(vport->fc_vport->symbolic_name))
n += snprintf(symbol + n, size - n, " VName-%s",
vport->fc_vport->symbolic_name);
return n;
}
int
lpfc_vport_symbolic_node_name(struct lpfc_vport *vport, char *symbol,
size_t size)
{
char fwrev[FW_REV_STR_SIZE];
int n;
lpfc_decode_firmware_rev(vport->phba, fwrev, 0);
n = snprintf(symbol, size, "Emulex %s FV%s DV%s",
vport->phba->ModelName, fwrev, lpfc_release_version);
return n;
}
/*
* lpfc_ns_cmd
* Description:
* Issue Cmd to NameServer
* SLI_CTNS_GID_FT
* LI_CTNS_RFT_ID
*/
int
lpfc_ns_cmd(struct lpfc_vport *vport, int cmdcode,
uint8_t retry, uint32_t context)
{
struct lpfc_nodelist * ndlp;
struct lpfc_hba *phba = vport->phba;
struct lpfc_dmabuf *mp, *bmp;
struct lpfc_sli_ct_request *CtReq;
struct ulp_bde64 *bpl;
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *) = NULL;
uint32_t rsp_size = 1024;
size_t size;
int rc = 0;
ndlp = lpfc_findnode_did(vport, NameServer_DID);
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)
|| ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) {
rc=1;
goto ns_cmd_exit;
}
/* fill in BDEs for command */
/* Allocate buffer for command payload */
mp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!mp) {
rc=2;
goto ns_cmd_exit;
}
INIT_LIST_HEAD(&mp->list);
mp->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &(mp->phys));
if (!mp->virt) {
rc=3;
goto ns_cmd_free_mp;
}
/* Allocate buffer for Buffer ptr list */
bmp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc=4;
goto ns_cmd_free_mpvirt;
}
INIT_LIST_HEAD(&bmp->list);
bmp->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &(bmp->phys));
if (!bmp->virt) {
rc=5;
goto ns_cmd_free_bmp;
}
/* NameServer Req */
lpfc_printf_vlog(vport, KERN_INFO ,LOG_DISCOVERY,
"0236 NameServer Req Data: x%x x%x x%x\n",
cmdcode, vport->fc_flag, vport->fc_rscn_id_cnt);
bpl = (struct ulp_bde64 *) bmp->virt;
memset(bpl, 0, sizeof(struct ulp_bde64));
bpl->addrHigh = le32_to_cpu(putPaddrHigh(mp->phys) );
bpl->addrLow = le32_to_cpu(putPaddrLow(mp->phys) );
bpl->tus.f.bdeFlags = 0;
if (cmdcode == SLI_CTNS_GID_FT)
bpl->tus.f.bdeSize = GID_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_GFF_ID)
bpl->tus.f.bdeSize = GFF_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RFT_ID)
bpl->tus.f.bdeSize = RFT_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RNN_ID)
bpl->tus.f.bdeSize = RNN_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RSPN_ID)
bpl->tus.f.bdeSize = RSPN_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RSNN_NN)
bpl->tus.f.bdeSize = RSNN_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_DA_ID)
bpl->tus.f.bdeSize = DA_ID_REQUEST_SZ;
else if (cmdcode == SLI_CTNS_RFF_ID)
bpl->tus.f.bdeSize = RFF_REQUEST_SZ;
else
bpl->tus.f.bdeSize = 0;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
CtReq = (struct lpfc_sli_ct_request *) mp->virt;
memset(CtReq, 0, sizeof (struct lpfc_sli_ct_request));
CtReq->RevisionId.bits.Revision = SLI_CT_REVISION;
CtReq->RevisionId.bits.InId = 0;
CtReq->FsType = SLI_CT_DIRECTORY_SERVICE;
CtReq->FsSubType = SLI_CT_DIRECTORY_NAME_SERVER;
CtReq->CommandResponse.bits.Size = 0;
switch (cmdcode) {
case SLI_CTNS_GID_FT:
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_GID_FT);
CtReq->un.gid.Fc4Type = SLI_CTPT_FCP;
if (vport->port_state < LPFC_NS_QRY)
vport->port_state = LPFC_NS_QRY;
lpfc_set_disctmo(vport);
cmpl = lpfc_cmpl_ct_cmd_gid_ft;
rsp_size = FC_MAX_NS_RSP;
break;
case SLI_CTNS_GFF_ID:
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_GFF_ID);
CtReq->un.gff.PortId = cpu_to_be32(context);
cmpl = lpfc_cmpl_ct_cmd_gff_id;
break;
case SLI_CTNS_RFT_ID:
vport->ct_flags &= ~FC_CT_RFT_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RFT_ID);
CtReq->un.rft.PortId = cpu_to_be32(vport->fc_myDID);
CtReq->un.rft.fcpReg = 1;
cmpl = lpfc_cmpl_ct_cmd_rft_id;
break;
case SLI_CTNS_RNN_ID:
vport->ct_flags &= ~FC_CT_RNN_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RNN_ID);
CtReq->un.rnn.PortId = cpu_to_be32(vport->fc_myDID);
memcpy(CtReq->un.rnn.wwnn, &vport->fc_nodename,
sizeof (struct lpfc_name));
cmpl = lpfc_cmpl_ct_cmd_rnn_id;
break;
case SLI_CTNS_RSPN_ID:
vport->ct_flags &= ~FC_CT_RSPN_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RSPN_ID);
CtReq->un.rspn.PortId = cpu_to_be32(vport->fc_myDID);
size = sizeof(CtReq->un.rspn.symbname);
CtReq->un.rspn.len =
lpfc_vport_symbolic_port_name(vport,
CtReq->un.rspn.symbname, size);
cmpl = lpfc_cmpl_ct_cmd_rspn_id;
break;
case SLI_CTNS_RSNN_NN:
vport->ct_flags &= ~FC_CT_RSNN_NN;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RSNN_NN);
memcpy(CtReq->un.rsnn.wwnn, &vport->fc_nodename,
sizeof (struct lpfc_name));
size = sizeof(CtReq->un.rsnn.symbname);
CtReq->un.rsnn.len =
lpfc_vport_symbolic_node_name(vport,
CtReq->un.rsnn.symbname, size);
cmpl = lpfc_cmpl_ct_cmd_rsnn_nn;
break;
case SLI_CTNS_DA_ID:
/* Implement DA_ID Nameserver request */
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_DA_ID);
CtReq->un.da_id.port_id = cpu_to_be32(vport->fc_myDID);
cmpl = lpfc_cmpl_ct_cmd_da_id;
break;
case SLI_CTNS_RFF_ID:
vport->ct_flags &= ~FC_CT_RFF_ID;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_CTNS_RFF_ID);
CtReq->un.rff.PortId = cpu_to_be32(vport->fc_myDID);
CtReq->un.rff.fbits = FC4_FEATURE_INIT;
CtReq->un.rff.type_code = FC_TYPE_FCP;
cmpl = lpfc_cmpl_ct_cmd_rff_id;
break;
}
/* The lpfc_ct_cmd/lpfc_get_req shall increment ndlp reference count
* to hold ndlp reference for the corresponding callback function.
*/
if (!lpfc_ct_cmd(vport, mp, bmp, ndlp, cmpl, rsp_size, retry)) {
/* On success, The cmpl function will free the buffers */
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"Issue CT cmd: cmd:x%x did:x%x",
cmdcode, ndlp->nlp_DID, 0);
return 0;
}
rc=6;
/* Decrement ndlp reference count to release ndlp reference held
* for the failed command's callback function.
*/
lpfc_nlp_put(ndlp);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
ns_cmd_free_bmp:
kfree(bmp);
ns_cmd_free_mpvirt:
lpfc_mbuf_free(phba, mp->virt, mp->phys);
ns_cmd_free_mp:
kfree(mp);
ns_cmd_exit:
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0266 Issue NameServer Req x%x err %d Data: x%x x%x\n",
cmdcode, rc, vport->fc_flag, vport->fc_rscn_id_cnt);
return 1;
}
static void
lpfc_cmpl_ct_cmd_fdmi(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq * rspiocb)
{
struct lpfc_dmabuf *inp = cmdiocb->context1;
struct lpfc_dmabuf *outp = cmdiocb->context2;
struct lpfc_sli_ct_request *CTrsp = outp->virt;
struct lpfc_sli_ct_request *CTcmd = inp->virt;
struct lpfc_nodelist *ndlp;
uint16_t fdmi_cmd = CTcmd->CommandResponse.bits.CmdRsp;
uint16_t fdmi_rsp = CTrsp->CommandResponse.bits.CmdRsp;
struct lpfc_vport *vport = cmdiocb->vport;
IOCB_t *irsp = &rspiocb->iocb;
uint32_t latt;
latt = lpfc_els_chk_latt(vport);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_CT,
"FDMI cmpl: status:x%x/x%x latt:%d",
irsp->ulpStatus, irsp->un.ulpWord[4], latt);
if (latt || irsp->ulpStatus) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0229 FDMI cmd %04x failed, latt = %d "
"ulpStatus: x%x, rid x%x\n",
be16_to_cpu(fdmi_cmd), latt, irsp->ulpStatus,
irsp->un.ulpWord[4]);
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
ndlp = lpfc_findnode_did(vport, FDMI_DID);
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
goto fail_out;
if (fdmi_rsp == be16_to_cpu(SLI_CT_RESPONSE_FS_RJT)) {
/* FDMI rsp failed */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0220 FDMI rsp failed Data: x%x\n",
be16_to_cpu(fdmi_cmd));
}
switch (be16_to_cpu(fdmi_cmd)) {
case SLI_MGMT_RHBA:
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_RPA);
break;
case SLI_MGMT_RPA:
break;
case SLI_MGMT_DHBA:
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_DPRT);
break;
case SLI_MGMT_DPRT:
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_RHBA);
break;
}
fail_out:
lpfc_ct_free_iocb(phba, cmdiocb);
return;
}
int
lpfc_fdmi_cmd(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp, int cmdcode)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_dmabuf *mp, *bmp;
struct lpfc_sli_ct_request *CtReq;
struct ulp_bde64 *bpl;
uint32_t size;
REG_HBA *rh;
PORT_ENTRY *pe;
REG_PORT_ATTRIBUTE *pab;
ATTRIBUTE_BLOCK *ab;
ATTRIBUTE_ENTRY *ae;
void (*cmpl) (struct lpfc_hba *, struct lpfc_iocbq *,
struct lpfc_iocbq *);
/* fill in BDEs for command */
/* Allocate buffer for command payload */
mp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!mp)
goto fdmi_cmd_exit;
mp->virt = lpfc_mbuf_alloc(phba, 0, &(mp->phys));
if (!mp->virt)
goto fdmi_cmd_free_mp;
/* Allocate buffer for Buffer ptr list */
bmp = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp)
goto fdmi_cmd_free_mpvirt;
bmp->virt = lpfc_mbuf_alloc(phba, 0, &(bmp->phys));
if (!bmp->virt)
goto fdmi_cmd_free_bmp;
INIT_LIST_HEAD(&mp->list);
INIT_LIST_HEAD(&bmp->list);
/* FDMI request */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0218 FDMI Request Data: x%x x%x x%x\n",
vport->fc_flag, vport->port_state, cmdcode);
CtReq = (struct lpfc_sli_ct_request *) mp->virt;
memset(CtReq, 0, sizeof(struct lpfc_sli_ct_request));
CtReq->RevisionId.bits.Revision = SLI_CT_REVISION;
CtReq->RevisionId.bits.InId = 0;
CtReq->FsType = SLI_CT_MANAGEMENT_SERVICE;
CtReq->FsSubType = SLI_CT_FDMI_Subtypes;
size = 0;
switch (cmdcode) {
case SLI_MGMT_RHBA:
{
lpfc_vpd_t *vp = &phba->vpd;
uint32_t i, j, incr;
int len;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_MGMT_RHBA);
CtReq->CommandResponse.bits.Size = 0;
rh = (REG_HBA *) & CtReq->un.PortID;
memcpy(&rh->hi.PortName, &vport->fc_sparam.portName,
sizeof (struct lpfc_name));
/* One entry (port) per adapter */
rh->rpl.EntryCnt = be32_to_cpu(1);
memcpy(&rh->rpl.pe, &vport->fc_sparam.portName,
sizeof (struct lpfc_name));
/* point to the HBA attribute block */
size = 2 * sizeof (struct lpfc_name) + FOURBYTES;
ab = (ATTRIBUTE_BLOCK *) ((uint8_t *) rh + size);
ab->EntryCnt = 0;
/* Point to the beginning of the first HBA attribute
entry */
/* #1 HBA attribute entry */
size += FOURBYTES;
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(NODE_NAME);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES
+ sizeof (struct lpfc_name));
memcpy(&ae->un.NodeName, &vport->fc_sparam.nodeName,
sizeof (struct lpfc_name));
ab->EntryCnt++;
size += FOURBYTES + sizeof (struct lpfc_name);
/* #2 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MANUFACTURER);
strcpy(ae->un.Manufacturer, "Emulex Corporation");
len = strlen(ae->un.Manufacturer);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #3 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(SERIAL_NUMBER);
strcpy(ae->un.SerialNumber, phba->SerialNumber);
len = strlen(ae->un.SerialNumber);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #4 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MODEL);
strcpy(ae->un.Model, phba->ModelName);
len = strlen(ae->un.Model);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #5 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MODEL_DESCRIPTION);
strcpy(ae->un.ModelDescription, phba->ModelDesc);
len = strlen(ae->un.ModelDescription);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #6 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(HARDWARE_VERSION);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 8);
/* Convert JEDEC ID to ascii for hardware version */
incr = vp->rev.biuRev;
for (i = 0; i < 8; i++) {
j = (incr & 0xf);
if (j <= 9)
ae->un.HardwareVersion[7 - i] =
(char)((uint8_t) 0x30 +
(uint8_t) j);
else
ae->un.HardwareVersion[7 - i] =
(char)((uint8_t) 0x61 +
(uint8_t) (j - 10));
incr = (incr >> 4);
}
ab->EntryCnt++;
size += FOURBYTES + 8;
/* #7 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(DRIVER_VERSION);
strcpy(ae->un.DriverVersion, lpfc_release_version);
len = strlen(ae->un.DriverVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #8 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(OPTION_ROM_VERSION);
strcpy(ae->un.OptionROMVersion, phba->OptionROMVersion);
len = strlen(ae->un.OptionROMVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #9 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(FIRMWARE_VERSION);
lpfc_decode_firmware_rev(phba, ae->un.FirmwareVersion,
1);
len = strlen(ae->un.FirmwareVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #10 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(OS_NAME_VERSION);
sprintf(ae->un.OsNameVersion, "%s %s %s",
init_utsname()->sysname,
init_utsname()->release,
init_utsname()->version);
len = strlen(ae->un.OsNameVersion);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
ab->EntryCnt++;
size += FOURBYTES + len;
/* #11 HBA attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) rh + size);
ae->ad.bits.AttrType = be16_to_cpu(MAX_CT_PAYLOAD_LEN);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
ae->un.MaxCTPayloadLen = (65 * 4096);
ab->EntryCnt++;
size += FOURBYTES + 4;
ab->EntryCnt = be32_to_cpu(ab->EntryCnt);
/* Total size */
size = GID_REQUEST_SZ - 4 + size;
}
break;
case SLI_MGMT_RPA:
{
lpfc_vpd_t *vp;
struct serv_parm *hsp;
int len;
vp = &phba->vpd;
CtReq->CommandResponse.bits.CmdRsp =
be16_to_cpu(SLI_MGMT_RPA);
CtReq->CommandResponse.bits.Size = 0;
pab = (REG_PORT_ATTRIBUTE *) & CtReq->un.PortID;
size = sizeof (struct lpfc_name) + FOURBYTES;
memcpy((uint8_t *) & pab->PortName,
(uint8_t *) & vport->fc_sparam.portName,
sizeof (struct lpfc_name));
pab->ab.EntryCnt = 0;
/* #1 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(SUPPORTED_FC4_TYPES);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 32);
ae->un.SupportFC4Types[2] = 1;
ae->un.SupportFC4Types[7] = 1;
pab->ab.EntryCnt++;
size += FOURBYTES + 32;
/* #2 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(SUPPORTED_SPEED);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
ae->un.SupportSpeed = 0;
if (phba->lmt & LMT_16Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_16GBIT;
if (phba->lmt & LMT_10Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_10GBIT;
if (phba->lmt & LMT_8Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_8GBIT;
if (phba->lmt & LMT_4Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_4GBIT;
if (phba->lmt & LMT_2Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_2GBIT;
if (phba->lmt & LMT_1Gb)
ae->un.SupportSpeed |= HBA_PORTSPEED_1GBIT;
pab->ab.EntryCnt++;
size += FOURBYTES + 4;
/* #3 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(PORT_SPEED);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
switch(phba->fc_linkspeed) {
case LPFC_LINK_SPEED_1GHZ:
ae->un.PortSpeed = HBA_PORTSPEED_1GBIT;
break;
case LPFC_LINK_SPEED_2GHZ:
ae->un.PortSpeed = HBA_PORTSPEED_2GBIT;
break;
case LPFC_LINK_SPEED_4GHZ:
ae->un.PortSpeed = HBA_PORTSPEED_4GBIT;
break;
case LPFC_LINK_SPEED_8GHZ:
ae->un.PortSpeed = HBA_PORTSPEED_8GBIT;
break;
case LPFC_LINK_SPEED_10GHZ:
ae->un.PortSpeed = HBA_PORTSPEED_10GBIT;
break;
case LPFC_LINK_SPEED_16GHZ:
ae->un.PortSpeed = HBA_PORTSPEED_16GBIT;
break;
default:
ae->un.PortSpeed = HBA_PORTSPEED_UNKNOWN;
break;
}
pab->ab.EntryCnt++;
size += FOURBYTES + 4;
/* #4 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(MAX_FRAME_SIZE);
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + 4);
hsp = (struct serv_parm *) & vport->fc_sparam;
ae->un.MaxFrameSize =
(((uint32_t) hsp->cmn.
bbRcvSizeMsb) << 8) | (uint32_t) hsp->cmn.
bbRcvSizeLsb;
pab->ab.EntryCnt++;
size += FOURBYTES + 4;
/* #5 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab + size);
ae->ad.bits.AttrType = be16_to_cpu(OS_DEVICE_NAME);
strcpy((char *)ae->un.OsDeviceName, LPFC_DRIVER_NAME);
len = strlen((char *)ae->un.OsDeviceName);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen = be16_to_cpu(FOURBYTES + len);
pab->ab.EntryCnt++;
size += FOURBYTES + len;
if (vport->cfg_fdmi_on == 2) {
/* #6 Port attribute entry */
ae = (ATTRIBUTE_ENTRY *) ((uint8_t *) pab +
size);
ae->ad.bits.AttrType = be16_to_cpu(HOST_NAME);
sprintf(ae->un.HostName, "%s",
init_utsname()->nodename);
len = strlen(ae->un.HostName);
len += (len & 3) ? (4 - (len & 3)) : 4;
ae->ad.bits.AttrLen =
be16_to_cpu(FOURBYTES + len);
pab->ab.EntryCnt++;
size += FOURBYTES + len;
}
pab->ab.EntryCnt = be32_to_cpu(pab->ab.EntryCnt);
/* Total size */
size = GID_REQUEST_SZ - 4 + size;
}
break;
case SLI_MGMT_DHBA:
CtReq->CommandResponse.bits.CmdRsp = be16_to_cpu(SLI_MGMT_DHBA);
CtReq->CommandResponse.bits.Size = 0;
pe = (PORT_ENTRY *) & CtReq->un.PortID;
memcpy((uint8_t *) & pe->PortName,
(uint8_t *) & vport->fc_sparam.portName,
sizeof (struct lpfc_name));
size = GID_REQUEST_SZ - 4 + sizeof (struct lpfc_name);
break;
case SLI_MGMT_DPRT:
CtReq->CommandResponse.bits.CmdRsp = be16_to_cpu(SLI_MGMT_DPRT);
CtReq->CommandResponse.bits.Size = 0;
pe = (PORT_ENTRY *) & CtReq->un.PortID;
memcpy((uint8_t *) & pe->PortName,
(uint8_t *) & vport->fc_sparam.portName,
sizeof (struct lpfc_name));
size = GID_REQUEST_SZ - 4 + sizeof (struct lpfc_name);
break;
}
bpl = (struct ulp_bde64 *) bmp->virt;
bpl->addrHigh = le32_to_cpu(putPaddrHigh(mp->phys) );
bpl->addrLow = le32_to_cpu(putPaddrLow(mp->phys) );
bpl->tus.f.bdeFlags = 0;
bpl->tus.f.bdeSize = size;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
cmpl = lpfc_cmpl_ct_cmd_fdmi;
/* The lpfc_ct_cmd/lpfc_get_req shall increment ndlp reference count
* to hold ndlp reference for the corresponding callback function.
*/
if (!lpfc_ct_cmd(vport, mp, bmp, ndlp, cmpl, FC_MAX_NS_RSP, 0))
return 0;
/* Decrement ndlp reference count to release ndlp reference held
* for the failed command's callback function.
*/
lpfc_nlp_put(ndlp);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
fdmi_cmd_free_bmp:
kfree(bmp);
fdmi_cmd_free_mpvirt:
lpfc_mbuf_free(phba, mp->virt, mp->phys);
fdmi_cmd_free_mp:
kfree(mp);
fdmi_cmd_exit:
/* Issue FDMI request failed */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0244 Issue FDMI request failed Data: x%x\n",
cmdcode);
return 1;
}
/**
* lpfc_delayed_disc_tmo - Timeout handler for delayed discovery timer.
* @ptr - Context object of the timer.
*
* This function set the WORKER_DELAYED_DISC_TMO flag and wake up
* the worker thread.
**/
void
lpfc_delayed_disc_tmo(unsigned long ptr)
{
struct lpfc_vport *vport = (struct lpfc_vport *)ptr;
struct lpfc_hba *phba = vport->phba;
uint32_t tmo_posted;
unsigned long iflag;
spin_lock_irqsave(&vport->work_port_lock, iflag);
tmo_posted = vport->work_port_events & WORKER_DELAYED_DISC_TMO;
if (!tmo_posted)
vport->work_port_events |= WORKER_DELAYED_DISC_TMO;
spin_unlock_irqrestore(&vport->work_port_lock, iflag);
if (!tmo_posted)
lpfc_worker_wake_up(phba);
return;
}
/**
* lpfc_delayed_disc_timeout_handler - Function called by worker thread to
* handle delayed discovery.
* @vport: pointer to a host virtual N_Port data structure.
*
* This function start nport discovery of the vport.
**/
void
lpfc_delayed_disc_timeout_handler(struct lpfc_vport *vport)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
spin_lock_irq(shost->host_lock);
if (!(vport->fc_flag & FC_DISC_DELAYED)) {
spin_unlock_irq(shost->host_lock);
return;
}
vport->fc_flag &= ~FC_DISC_DELAYED;
spin_unlock_irq(shost->host_lock);
lpfc_do_scr_ns_plogi(vport->phba, vport);
}
void
lpfc_fdmi_tmo(unsigned long ptr)
{
struct lpfc_vport *vport = (struct lpfc_vport *)ptr;
struct lpfc_hba *phba = vport->phba;
uint32_t tmo_posted;
unsigned long iflag;
spin_lock_irqsave(&vport->work_port_lock, iflag);
tmo_posted = vport->work_port_events & WORKER_FDMI_TMO;
if (!tmo_posted)
vport->work_port_events |= WORKER_FDMI_TMO;
spin_unlock_irqrestore(&vport->work_port_lock, iflag);
if (!tmo_posted)
lpfc_worker_wake_up(phba);
return;
}
void
lpfc_fdmi_timeout_handler(struct lpfc_vport *vport)
{
struct lpfc_nodelist *ndlp;
ndlp = lpfc_findnode_did(vport, FDMI_DID);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)) {
if (init_utsname()->nodename[0] != '\0')
lpfc_fdmi_cmd(vport, ndlp, SLI_MGMT_DHBA);
else
mod_timer(&vport->fc_fdmitmo, jiffies +
msecs_to_jiffies(1000 * 60));
}
return;
}
void
lpfc_decode_firmware_rev(struct lpfc_hba *phba, char *fwrevision, int flag)
{
struct lpfc_sli *psli = &phba->sli;
lpfc_vpd_t *vp = &phba->vpd;
uint32_t b1, b2, b3, b4, i, rev;
char c;
uint32_t *ptr, str[4];
uint8_t *fwname;
if (phba->sli_rev == LPFC_SLI_REV4)
snprintf(fwrevision, FW_REV_STR_SIZE, "%s", vp->rev.opFwName);
else if (vp->rev.rBit) {
if (psli->sli_flag & LPFC_SLI_ACTIVE)
rev = vp->rev.sli2FwRev;
else
rev = vp->rev.sli1FwRev;
b1 = (rev & 0x0000f000) >> 12;
b2 = (rev & 0x00000f00) >> 8;
b3 = (rev & 0x000000c0) >> 6;
b4 = (rev & 0x00000030) >> 4;
switch (b4) {
case 0:
c = 'N';
break;
case 1:
c = 'A';
break;
case 2:
c = 'B';
break;
case 3:
c = 'X';
break;
default:
c = 0;
break;
}
b4 = (rev & 0x0000000f);
if (psli->sli_flag & LPFC_SLI_ACTIVE)
fwname = vp->rev.sli2FwName;
else
fwname = vp->rev.sli1FwName;
for (i = 0; i < 16; i++)
if (fwname[i] == 0x20)
fwname[i] = 0;
ptr = (uint32_t*)fwname;
for (i = 0; i < 3; i++)
str[i] = be32_to_cpu(*ptr++);
if (c == 0) {
if (flag)
sprintf(fwrevision, "%d.%d%d (%s)",
b1, b2, b3, (char *)str);
else
sprintf(fwrevision, "%d.%d%d", b1,
b2, b3);
} else {
if (flag)
sprintf(fwrevision, "%d.%d%d%c%d (%s)",
b1, b2, b3, c,
b4, (char *)str);
else
sprintf(fwrevision, "%d.%d%d%c%d",
b1, b2, b3, c, b4);
}
} else {
rev = vp->rev.smFwRev;
b1 = (rev & 0xff000000) >> 24;
b2 = (rev & 0x00f00000) >> 20;
b3 = (rev & 0x000f0000) >> 16;
c = (rev & 0x0000ff00) >> 8;
b4 = (rev & 0x000000ff);
sprintf(fwrevision, "%d.%d%d%c%d", b1, b2, b3, c, b4);
}
return;
}
| gpl-2.0 |
b8e5n/KTG-kernel_es209ra | fs/nfs/nfs4namespace.c | 522 | 6622 | /*
* linux/fs/nfs/nfs4namespace.c
*
* Copyright (C) 2005 Trond Myklebust <Trond.Myklebust@netapp.com>
* - Modified by David Howells <dhowells@redhat.com>
*
* NFSv4 namespace
*/
#include <linux/dcache.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/nfs_fs.h>
#include <linux/string.h>
#include <linux/sunrpc/clnt.h>
#include <linux/vfs.h>
#include <linux/inet.h>
#include "internal.h"
#include "nfs4_fs.h"
#include "dns_resolve.h"
#define NFSDBG_FACILITY NFSDBG_VFS
/*
* Convert the NFSv4 pathname components into a standard posix path.
*
* Note that the resulting string will be placed at the end of the buffer
*/
static inline char *nfs4_pathname_string(const struct nfs4_pathname *pathname,
char *buffer, ssize_t buflen)
{
char *end = buffer + buflen;
int n;
*--end = '\0';
buflen--;
n = pathname->ncomponents;
while (--n >= 0) {
const struct nfs4_string *component = &pathname->components[n];
buflen -= component->len + 1;
if (buflen < 0)
goto Elong;
end -= component->len;
memcpy(end, component->data, component->len);
*--end = '/';
}
return end;
Elong:
return ERR_PTR(-ENAMETOOLONG);
}
/*
* Determine the mount path as a string
*/
static char *nfs4_path(const struct vfsmount *mnt_parent,
const struct dentry *dentry,
char *buffer, ssize_t buflen)
{
const char *srvpath;
srvpath = strchr(mnt_parent->mnt_devname, ':');
if (srvpath)
srvpath++;
else
srvpath = mnt_parent->mnt_devname;
return nfs_path(srvpath, mnt_parent->mnt_root, dentry, buffer, buflen);
}
/*
* Check that fs_locations::fs_root [RFC3530 6.3] is a prefix for what we
* believe to be the server path to this dentry
*/
static int nfs4_validate_fspath(const struct vfsmount *mnt_parent,
const struct dentry *dentry,
const struct nfs4_fs_locations *locations,
char *page, char *page2)
{
const char *path, *fs_path;
path = nfs4_path(mnt_parent, dentry, page, PAGE_SIZE);
if (IS_ERR(path))
return PTR_ERR(path);
fs_path = nfs4_pathname_string(&locations->fs_path, page2, PAGE_SIZE);
if (IS_ERR(fs_path))
return PTR_ERR(fs_path);
if (strncmp(path, fs_path, strlen(fs_path)) != 0) {
dprintk("%s: path %s does not begin with fsroot %s\n",
__func__, path, fs_path);
return -ENOENT;
}
return 0;
}
static size_t nfs_parse_server_name(char *string, size_t len,
struct sockaddr *sa, size_t salen)
{
ssize_t ret;
ret = rpc_pton(string, len, sa, salen);
if (ret == 0) {
ret = nfs_dns_resolve_name(string, len, sa, salen);
if (ret < 0)
ret = 0;
}
return ret;
}
static struct vfsmount *try_location(struct nfs_clone_mount *mountdata,
char *page, char *page2,
const struct nfs4_fs_location *location)
{
struct vfsmount *mnt = ERR_PTR(-ENOENT);
char *mnt_path;
unsigned int maxbuflen;
unsigned int s;
mnt_path = nfs4_pathname_string(&location->rootpath, page2, PAGE_SIZE);
if (IS_ERR(mnt_path))
return ERR_CAST(mnt_path);
mountdata->mnt_path = mnt_path;
maxbuflen = mnt_path - 1 - page2;
for (s = 0; s < location->nservers; s++) {
const struct nfs4_string *buf = &location->servers[s];
struct sockaddr_storage addr;
if (buf->len <= 0 || buf->len >= maxbuflen)
continue;
if (memchr(buf->data, IPV6_SCOPE_DELIMITER, buf->len))
continue;
mountdata->addrlen = nfs_parse_server_name(buf->data, buf->len,
(struct sockaddr *)&addr, sizeof(addr));
if (mountdata->addrlen == 0)
continue;
mountdata->addr = (struct sockaddr *)&addr;
rpc_set_port(mountdata->addr, NFS_PORT);
memcpy(page2, buf->data, buf->len);
page2[buf->len] = '\0';
mountdata->hostname = page2;
snprintf(page, PAGE_SIZE, "%s:%s",
mountdata->hostname,
mountdata->mnt_path);
mnt = vfs_kern_mount(&nfs4_referral_fs_type, 0, page, mountdata);
if (!IS_ERR(mnt))
break;
}
return mnt;
}
/**
* nfs_follow_referral - set up mountpoint when hitting a referral on moved error
* @mnt_parent - mountpoint of parent directory
* @dentry - parent directory
* @locations - array of NFSv4 server location information
*
*/
static struct vfsmount *nfs_follow_referral(const struct vfsmount *mnt_parent,
const struct dentry *dentry,
const struct nfs4_fs_locations *locations)
{
struct vfsmount *mnt = ERR_PTR(-ENOENT);
struct nfs_clone_mount mountdata = {
.sb = mnt_parent->mnt_sb,
.dentry = dentry,
.authflavor = NFS_SB(mnt_parent->mnt_sb)->client->cl_auth->au_flavor,
};
char *page = NULL, *page2 = NULL;
int loc, error;
if (locations == NULL || locations->nlocations <= 0)
goto out;
dprintk("%s: referral at %s/%s\n", __func__,
dentry->d_parent->d_name.name, dentry->d_name.name);
page = (char *) __get_free_page(GFP_USER);
if (!page)
goto out;
page2 = (char *) __get_free_page(GFP_USER);
if (!page2)
goto out;
/* Ensure fs path is a prefix of current dentry path */
error = nfs4_validate_fspath(mnt_parent, dentry, locations, page, page2);
if (error < 0) {
mnt = ERR_PTR(error);
goto out;
}
for (loc = 0; loc < locations->nlocations; loc++) {
const struct nfs4_fs_location *location = &locations->locations[loc];
if (location == NULL || location->nservers <= 0 ||
location->rootpath.ncomponents == 0)
continue;
mnt = try_location(&mountdata, page, page2, location);
if (!IS_ERR(mnt))
break;
}
out:
free_page((unsigned long) page);
free_page((unsigned long) page2);
dprintk("%s: done\n", __func__);
return mnt;
}
/*
* nfs_do_refmount - handle crossing a referral on server
* @dentry - dentry of referral
* @nd - nameidata info
*
*/
struct vfsmount *nfs_do_refmount(const struct vfsmount *mnt_parent, struct dentry *dentry)
{
struct vfsmount *mnt = ERR_PTR(-ENOMEM);
struct dentry *parent;
struct nfs4_fs_locations *fs_locations = NULL;
struct page *page;
int err;
/* BUG_ON(IS_ROOT(dentry)); */
dprintk("%s: enter\n", __func__);
page = alloc_page(GFP_KERNEL);
if (page == NULL)
goto out;
fs_locations = kmalloc(sizeof(struct nfs4_fs_locations), GFP_KERNEL);
if (fs_locations == NULL)
goto out_free;
/* Get locations */
mnt = ERR_PTR(-ENOENT);
parent = dget_parent(dentry);
dprintk("%s: getting locations for %s/%s\n",
__func__, parent->d_name.name, dentry->d_name.name);
err = nfs4_proc_fs_locations(parent->d_inode, &dentry->d_name, fs_locations, page);
dput(parent);
if (err != 0 ||
fs_locations->nlocations <= 0 ||
fs_locations->fs_path.ncomponents <= 0)
goto out_free;
mnt = nfs_follow_referral(mnt_parent, dentry, fs_locations);
out_free:
__free_page(page);
kfree(fs_locations);
out:
dprintk("%s: done\n", __func__);
return mnt;
}
| gpl-2.0 |
vk2rq/linux-stable | drivers/media/video/cx25840/cx25840-audio.c | 522 | 11073 | /* cx25840 audio functions
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <media/v4l2-common.h>
#include <media/cx25840.h>
#include "cx25840-core.h"
static int set_audclk_freq(struct i2c_client *client, u32 freq)
{
struct cx25840_state *state = to_state(i2c_get_clientdata(client));
if (freq != 32000 && freq != 44100 && freq != 48000)
return -EINVAL;
/* common for all inputs and rates */
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x10 */
if (!state->is_cx23885 && !state->is_cx231xx)
cx25840_write(client, 0x127, 0x50);
if (state->aud_input != CX25840_AUDIO_SERIAL) {
switch (freq) {
case 32000:
if (state->is_cx23885) {
/* We don't have register values
* so avoid destroying registers. */
break;
}
if (!state->is_cx231xx) {
/* VID_PLL and AUX_PLL */
cx25840_write4(client, 0x108, 0x1006040f);
/* AUX_PLL_FRAC */
cx25840_write4(client, 0x110, 0x01bb39ee);
}
if (state->is_cx25836)
break;
/* src3/4/6_ctl = 0x0801f77f */
cx25840_write4(client, 0x900, 0x0801f77f);
cx25840_write4(client, 0x904, 0x0801f77f);
cx25840_write4(client, 0x90c, 0x0801f77f);
break;
case 44100:
if (state->is_cx23885) {
/* We don't have register values
* so avoid destroying registers. */
break;
}
if (!state->is_cx231xx) {
/* VID_PLL and AUX_PLL */
cx25840_write4(client, 0x108, 0x1009040f);
/* AUX_PLL_FRAC */
cx25840_write4(client, 0x110, 0x00ec6bd6);
}
if (state->is_cx25836)
break;
/* src3/4/6_ctl = 0x08016d59 */
cx25840_write4(client, 0x900, 0x08016d59);
cx25840_write4(client, 0x904, 0x08016d59);
cx25840_write4(client, 0x90c, 0x08016d59);
break;
case 48000:
if (state->is_cx23885) {
/* We don't have register values
* so avoid destroying registers. */
break;
}
if (!state->is_cx231xx) {
/* VID_PLL and AUX_PLL */
cx25840_write4(client, 0x108, 0x100a040f);
/* AUX_PLL_FRAC */
cx25840_write4(client, 0x110, 0x0098d6e5);
}
if (state->is_cx25836)
break;
/* src3/4/6_ctl = 0x08014faa */
cx25840_write4(client, 0x900, 0x08014faa);
cx25840_write4(client, 0x904, 0x08014faa);
cx25840_write4(client, 0x90c, 0x08014faa);
break;
}
} else {
switch (freq) {
case 32000:
if (state->is_cx23885) {
/* We don't have register values
* so avoid destroying registers. */
break;
}
if (!state->is_cx231xx) {
/* VID_PLL and AUX_PLL */
cx25840_write4(client, 0x108, 0x1e08040f);
/* AUX_PLL_FRAC */
cx25840_write4(client, 0x110, 0x012a0869);
}
if (state->is_cx25836)
break;
/* src1_ctl = 0x08010000 */
cx25840_write4(client, 0x8f8, 0x08010000);
/* src3/4/6_ctl = 0x08020000 */
cx25840_write4(client, 0x900, 0x08020000);
cx25840_write4(client, 0x904, 0x08020000);
cx25840_write4(client, 0x90c, 0x08020000);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x14 */
cx25840_write(client, 0x127, 0x54);
break;
case 44100:
if (state->is_cx23885) {
/* We don't have register values
* so avoid destroying registers. */
break;
}
if (!state->is_cx231xx) {
/* VID_PLL and AUX_PLL */
cx25840_write4(client, 0x108, 0x1809040f);
/* AUX_PLL_FRAC */
cx25840_write4(client, 0x110, 0x00ec6bd6);
}
if (state->is_cx25836)
break;
/* src1_ctl = 0x08010000 */
cx25840_write4(client, 0x8f8, 0x080160cd);
/* src3/4/6_ctl = 0x08020000 */
cx25840_write4(client, 0x900, 0x08017385);
cx25840_write4(client, 0x904, 0x08017385);
cx25840_write4(client, 0x90c, 0x08017385);
break;
case 48000:
if (!state->is_cx23885 && !state->is_cx231xx) {
/* VID_PLL and AUX_PLL */
cx25840_write4(client, 0x108, 0x180a040f);
/* AUX_PLL_FRAC */
cx25840_write4(client, 0x110, 0x0098d6e5);
}
if (state->is_cx25836)
break;
if (!state->is_cx23885 && !state->is_cx231xx) {
/* src1_ctl */
cx25840_write4(client, 0x8f8, 0x08018000);
/* src3/4/6_ctl */
cx25840_write4(client, 0x900, 0x08015555);
cx25840_write4(client, 0x904, 0x08015555);
cx25840_write4(client, 0x90c, 0x08015555);
} else {
cx25840_write4(client, 0x8f8, 0x0801867c);
cx25840_write4(client, 0x900, 0x08014faa);
cx25840_write4(client, 0x904, 0x08014faa);
cx25840_write4(client, 0x90c, 0x08014faa);
}
break;
}
}
state->audclk_freq = freq;
return 0;
}
void cx25840_audio_set_path(struct i2c_client *client)
{
struct cx25840_state *state = to_state(i2c_get_clientdata(client));
/* assert soft reset */
cx25840_and_or(client, 0x810, ~0x1, 0x01);
/* stop microcontroller */
cx25840_and_or(client, 0x803, ~0x10, 0);
/* Mute everything to prevent the PFFT! */
cx25840_write(client, 0x8d3, 0x1f);
if (state->aud_input == CX25840_AUDIO_SERIAL) {
/* Set Path1 to Serial Audio Input */
cx25840_write4(client, 0x8d0, 0x01011012);
/* The microcontroller should not be started for the
* non-tuner inputs: autodetection is specific for
* TV audio. */
} else {
/* Set Path1 to Analog Demod Main Channel */
cx25840_write4(client, 0x8d0, 0x1f063870);
}
set_audclk_freq(client, state->audclk_freq);
if (state->aud_input != CX25840_AUDIO_SERIAL) {
/* When the microcontroller detects the
* audio format, it will unmute the lines */
cx25840_and_or(client, 0x803, ~0x10, 0x10);
}
/* deassert soft reset */
cx25840_and_or(client, 0x810, ~0x1, 0x00);
/* Ensure the controller is running when we exit */
if (state->is_cx23885 || state->is_cx231xx)
cx25840_and_or(client, 0x803, ~0x10, 0x10);
}
static int get_volume(struct i2c_client *client)
{
struct cx25840_state *state = to_state(i2c_get_clientdata(client));
int vol;
if (state->unmute_volume >= 0)
return state->unmute_volume;
/* Volume runs +18dB to -96dB in 1/2dB steps
* change to fit the msp3400 -114dB to +12dB range */
/* check PATH1_VOLUME */
vol = 228 - cx25840_read(client, 0x8d4);
vol = (vol / 2) + 23;
return vol << 9;
}
static void set_volume(struct i2c_client *client, int volume)
{
struct cx25840_state *state = to_state(i2c_get_clientdata(client));
int vol;
if (state->unmute_volume >= 0) {
state->unmute_volume = volume;
return;
}
/* Convert the volume to msp3400 values (0-127) */
vol = volume >> 9;
/* now scale it up to cx25840 values
* -114dB to -96dB maps to 0
* this should be 19, but in my testing that was 4dB too loud */
if (vol <= 23) {
vol = 0;
} else {
vol -= 23;
}
/* PATH1_VOLUME */
cx25840_write(client, 0x8d4, 228 - (vol * 2));
}
static int get_bass(struct i2c_client *client)
{
/* bass is 49 steps +12dB to -12dB */
/* check PATH1_EQ_BASS_VOL */
int bass = cx25840_read(client, 0x8d9) & 0x3f;
bass = (((48 - bass) * 0xffff) + 47) / 48;
return bass;
}
static void set_bass(struct i2c_client *client, int bass)
{
/* PATH1_EQ_BASS_VOL */
cx25840_and_or(client, 0x8d9, ~0x3f, 48 - (bass * 48 / 0xffff));
}
static int get_treble(struct i2c_client *client)
{
/* treble is 49 steps +12dB to -12dB */
/* check PATH1_EQ_TREBLE_VOL */
int treble = cx25840_read(client, 0x8db) & 0x3f;
treble = (((48 - treble) * 0xffff) + 47) / 48;
return treble;
}
static void set_treble(struct i2c_client *client, int treble)
{
/* PATH1_EQ_TREBLE_VOL */
cx25840_and_or(client, 0x8db, ~0x3f, 48 - (treble * 48 / 0xffff));
}
static int get_balance(struct i2c_client *client)
{
/* balance is 7 bit, 0 to -96dB */
/* check PATH1_BAL_LEVEL */
int balance = cx25840_read(client, 0x8d5) & 0x7f;
/* check PATH1_BAL_LEFT */
if ((cx25840_read(client, 0x8d5) & 0x80) == 0)
balance = 0x80 - balance;
else
balance = 0x80 + balance;
return balance << 8;
}
static void set_balance(struct i2c_client *client, int balance)
{
int bal = balance >> 8;
if (bal > 0x80) {
/* PATH1_BAL_LEFT */
cx25840_and_or(client, 0x8d5, 0x7f, 0x80);
/* PATH1_BAL_LEVEL */
cx25840_and_or(client, 0x8d5, ~0x7f, bal & 0x7f);
} else {
/* PATH1_BAL_LEFT */
cx25840_and_or(client, 0x8d5, 0x7f, 0x00);
/* PATH1_BAL_LEVEL */
cx25840_and_or(client, 0x8d5, ~0x7f, 0x80 - bal);
}
}
static int get_mute(struct i2c_client *client)
{
struct cx25840_state *state = to_state(i2c_get_clientdata(client));
return state->unmute_volume >= 0;
}
static void set_mute(struct i2c_client *client, int mute)
{
struct cx25840_state *state = to_state(i2c_get_clientdata(client));
if (mute && state->unmute_volume == -1) {
int vol = get_volume(client);
set_volume(client, 0);
state->unmute_volume = vol;
}
else if (!mute && state->unmute_volume != -1) {
int vol = state->unmute_volume;
state->unmute_volume = -1;
set_volume(client, vol);
}
}
int cx25840_s_clock_freq(struct v4l2_subdev *sd, u32 freq)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct cx25840_state *state = to_state(sd);
int retval;
if (!state->is_cx25836)
cx25840_and_or(client, 0x810, ~0x1, 1);
if (state->aud_input != CX25840_AUDIO_SERIAL) {
cx25840_and_or(client, 0x803, ~0x10, 0);
cx25840_write(client, 0x8d3, 0x1f);
}
retval = set_audclk_freq(client, freq);
if (state->aud_input != CX25840_AUDIO_SERIAL)
cx25840_and_or(client, 0x803, ~0x10, 0x10);
if (!state->is_cx25836)
cx25840_and_or(client, 0x810, ~0x1, 0);
return retval;
}
int cx25840_audio_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME:
ctrl->value = get_volume(client);
break;
case V4L2_CID_AUDIO_BASS:
ctrl->value = get_bass(client);
break;
case V4L2_CID_AUDIO_TREBLE:
ctrl->value = get_treble(client);
break;
case V4L2_CID_AUDIO_BALANCE:
ctrl->value = get_balance(client);
break;
case V4L2_CID_AUDIO_MUTE:
ctrl->value = get_mute(client);
break;
default:
return -EINVAL;
}
return 0;
}
int cx25840_audio_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME:
set_volume(client, ctrl->value);
break;
case V4L2_CID_AUDIO_BASS:
set_bass(client, ctrl->value);
break;
case V4L2_CID_AUDIO_TREBLE:
set_treble(client, ctrl->value);
break;
case V4L2_CID_AUDIO_BALANCE:
set_balance(client, ctrl->value);
break;
case V4L2_CID_AUDIO_MUTE:
set_mute(client, ctrl->value);
break;
default:
return -EINVAL;
}
return 0;
}
| gpl-2.0 |
Bogdacutu/STLinux-Kernel | arch/s390/kernel/ipl.c | 2058 | 52053 | /*
* ipl/reipl/dump support for Linux on s390.
*
* Copyright IBM Corp. 2005, 2012
* Author(s): Michael Holzheu <holzheu@de.ibm.com>
* Heiko Carstens <heiko.carstens@de.ibm.com>
* Volker Sameske <sameske@de.ibm.com>
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/reboot.h>
#include <linux/ctype.h>
#include <linux/fs.h>
#include <linux/gfp.h>
#include <linux/crash_dump.h>
#include <linux/debug_locks.h>
#include <asm/ipl.h>
#include <asm/smp.h>
#include <asm/setup.h>
#include <asm/cpcmd.h>
#include <asm/cio.h>
#include <asm/ebcdic.h>
#include <asm/reset.h>
#include <asm/sclp.h>
#include <asm/checksum.h>
#include <asm/debug.h>
#include <asm/os_info.h>
#include "entry.h"
#define IPL_PARM_BLOCK_VERSION 0
#define IPL_UNKNOWN_STR "unknown"
#define IPL_CCW_STR "ccw"
#define IPL_FCP_STR "fcp"
#define IPL_FCP_DUMP_STR "fcp_dump"
#define IPL_NSS_STR "nss"
#define DUMP_CCW_STR "ccw"
#define DUMP_FCP_STR "fcp"
#define DUMP_NONE_STR "none"
/*
* Four shutdown trigger types are supported:
* - panic
* - halt
* - power off
* - reipl
* - restart
*/
#define ON_PANIC_STR "on_panic"
#define ON_HALT_STR "on_halt"
#define ON_POFF_STR "on_poff"
#define ON_REIPL_STR "on_reboot"
#define ON_RESTART_STR "on_restart"
struct shutdown_action;
struct shutdown_trigger {
char *name;
struct shutdown_action *action;
};
/*
* The following shutdown action types are supported:
*/
#define SHUTDOWN_ACTION_IPL_STR "ipl"
#define SHUTDOWN_ACTION_REIPL_STR "reipl"
#define SHUTDOWN_ACTION_DUMP_STR "dump"
#define SHUTDOWN_ACTION_VMCMD_STR "vmcmd"
#define SHUTDOWN_ACTION_STOP_STR "stop"
#define SHUTDOWN_ACTION_DUMP_REIPL_STR "dump_reipl"
struct shutdown_action {
char *name;
void (*fn) (struct shutdown_trigger *trigger);
int (*init) (void);
int init_rc;
};
static char *ipl_type_str(enum ipl_type type)
{
switch (type) {
case IPL_TYPE_CCW:
return IPL_CCW_STR;
case IPL_TYPE_FCP:
return IPL_FCP_STR;
case IPL_TYPE_FCP_DUMP:
return IPL_FCP_DUMP_STR;
case IPL_TYPE_NSS:
return IPL_NSS_STR;
case IPL_TYPE_UNKNOWN:
default:
return IPL_UNKNOWN_STR;
}
}
enum dump_type {
DUMP_TYPE_NONE = 1,
DUMP_TYPE_CCW = 2,
DUMP_TYPE_FCP = 4,
};
static char *dump_type_str(enum dump_type type)
{
switch (type) {
case DUMP_TYPE_NONE:
return DUMP_NONE_STR;
case DUMP_TYPE_CCW:
return DUMP_CCW_STR;
case DUMP_TYPE_FCP:
return DUMP_FCP_STR;
default:
return NULL;
}
}
/*
* Must be in data section since the bss section
* is not cleared when these are accessed.
*/
static u16 ipl_devno __attribute__((__section__(".data"))) = 0;
u32 ipl_flags __attribute__((__section__(".data"))) = 0;
enum ipl_method {
REIPL_METHOD_CCW_CIO,
REIPL_METHOD_CCW_DIAG,
REIPL_METHOD_CCW_VM,
REIPL_METHOD_FCP_RO_DIAG,
REIPL_METHOD_FCP_RW_DIAG,
REIPL_METHOD_FCP_RO_VM,
REIPL_METHOD_FCP_DUMP,
REIPL_METHOD_NSS,
REIPL_METHOD_NSS_DIAG,
REIPL_METHOD_DEFAULT,
};
enum dump_method {
DUMP_METHOD_NONE,
DUMP_METHOD_CCW_CIO,
DUMP_METHOD_CCW_DIAG,
DUMP_METHOD_CCW_VM,
DUMP_METHOD_FCP_DIAG,
};
static int diag308_set_works = 0;
static struct ipl_parameter_block ipl_block;
static int reipl_capabilities = IPL_TYPE_UNKNOWN;
static enum ipl_type reipl_type = IPL_TYPE_UNKNOWN;
static enum ipl_method reipl_method = REIPL_METHOD_DEFAULT;
static struct ipl_parameter_block *reipl_block_fcp;
static struct ipl_parameter_block *reipl_block_ccw;
static struct ipl_parameter_block *reipl_block_nss;
static struct ipl_parameter_block *reipl_block_actual;
static int dump_capabilities = DUMP_TYPE_NONE;
static enum dump_type dump_type = DUMP_TYPE_NONE;
static enum dump_method dump_method = DUMP_METHOD_NONE;
static struct ipl_parameter_block *dump_block_fcp;
static struct ipl_parameter_block *dump_block_ccw;
static struct sclp_ipl_info sclp_ipl_info;
int diag308(unsigned long subcode, void *addr)
{
register unsigned long _addr asm("0") = (unsigned long) addr;
register unsigned long _rc asm("1") = 0;
asm volatile(
" diag %0,%2,0x308\n"
"0:\n"
EX_TABLE(0b,0b)
: "+d" (_addr), "+d" (_rc)
: "d" (subcode) : "cc", "memory");
return _rc;
}
EXPORT_SYMBOL_GPL(diag308);
/* SYSFS */
#define DEFINE_IPL_ATTR_RO(_prefix, _name, _format, _value) \
static ssize_t sys_##_prefix##_##_name##_show(struct kobject *kobj, \
struct kobj_attribute *attr, \
char *page) \
{ \
return sprintf(page, _format, _value); \
} \
static struct kobj_attribute sys_##_prefix##_##_name##_attr = \
__ATTR(_name, S_IRUGO, sys_##_prefix##_##_name##_show, NULL);
#define DEFINE_IPL_ATTR_RW(_prefix, _name, _fmt_out, _fmt_in, _value) \
static ssize_t sys_##_prefix##_##_name##_show(struct kobject *kobj, \
struct kobj_attribute *attr, \
char *page) \
{ \
return sprintf(page, _fmt_out, \
(unsigned long long) _value); \
} \
static ssize_t sys_##_prefix##_##_name##_store(struct kobject *kobj, \
struct kobj_attribute *attr, \
const char *buf, size_t len) \
{ \
unsigned long long value; \
if (sscanf(buf, _fmt_in, &value) != 1) \
return -EINVAL; \
_value = value; \
return len; \
} \
static struct kobj_attribute sys_##_prefix##_##_name##_attr = \
__ATTR(_name,(S_IRUGO | S_IWUSR), \
sys_##_prefix##_##_name##_show, \
sys_##_prefix##_##_name##_store);
#define DEFINE_IPL_ATTR_STR_RW(_prefix, _name, _fmt_out, _fmt_in, _value)\
static ssize_t sys_##_prefix##_##_name##_show(struct kobject *kobj, \
struct kobj_attribute *attr, \
char *page) \
{ \
return sprintf(page, _fmt_out, _value); \
} \
static ssize_t sys_##_prefix##_##_name##_store(struct kobject *kobj, \
struct kobj_attribute *attr, \
const char *buf, size_t len) \
{ \
strncpy(_value, buf, sizeof(_value) - 1); \
strim(_value); \
return len; \
} \
static struct kobj_attribute sys_##_prefix##_##_name##_attr = \
__ATTR(_name,(S_IRUGO | S_IWUSR), \
sys_##_prefix##_##_name##_show, \
sys_##_prefix##_##_name##_store);
static void make_attrs_ro(struct attribute **attrs)
{
while (*attrs) {
(*attrs)->mode = S_IRUGO;
attrs++;
}
}
/*
* ipl section
*/
static __init enum ipl_type get_ipl_type(void)
{
struct ipl_parameter_block *ipl = IPL_PARMBLOCK_START;
if (ipl_flags & IPL_NSS_VALID)
return IPL_TYPE_NSS;
if (!(ipl_flags & IPL_DEVNO_VALID))
return IPL_TYPE_UNKNOWN;
if (!(ipl_flags & IPL_PARMBLOCK_VALID))
return IPL_TYPE_CCW;
if (ipl->hdr.version > IPL_MAX_SUPPORTED_VERSION)
return IPL_TYPE_UNKNOWN;
if (ipl->hdr.pbt != DIAG308_IPL_TYPE_FCP)
return IPL_TYPE_UNKNOWN;
if (ipl->ipl_info.fcp.opt == DIAG308_IPL_OPT_DUMP)
return IPL_TYPE_FCP_DUMP;
return IPL_TYPE_FCP;
}
struct ipl_info ipl_info;
EXPORT_SYMBOL_GPL(ipl_info);
static ssize_t ipl_type_show(struct kobject *kobj, struct kobj_attribute *attr,
char *page)
{
return sprintf(page, "%s\n", ipl_type_str(ipl_info.type));
}
static struct kobj_attribute sys_ipl_type_attr = __ATTR_RO(ipl_type);
/* VM IPL PARM routines */
static size_t reipl_get_ascii_vmparm(char *dest, size_t size,
const struct ipl_parameter_block *ipb)
{
int i;
size_t len;
char has_lowercase = 0;
len = 0;
if ((ipb->ipl_info.ccw.vm_flags & DIAG308_VM_FLAGS_VP_VALID) &&
(ipb->ipl_info.ccw.vm_parm_len > 0)) {
len = min_t(size_t, size - 1, ipb->ipl_info.ccw.vm_parm_len);
memcpy(dest, ipb->ipl_info.ccw.vm_parm, len);
/* If at least one character is lowercase, we assume mixed
* case; otherwise we convert everything to lowercase.
*/
for (i = 0; i < len; i++)
if ((dest[i] > 0x80 && dest[i] < 0x8a) || /* a-i */
(dest[i] > 0x90 && dest[i] < 0x9a) || /* j-r */
(dest[i] > 0xa1 && dest[i] < 0xaa)) { /* s-z */
has_lowercase = 1;
break;
}
if (!has_lowercase)
EBC_TOLOWER(dest, len);
EBCASC(dest, len);
}
dest[len] = 0;
return len;
}
size_t append_ipl_vmparm(char *dest, size_t size)
{
size_t rc;
rc = 0;
if (diag308_set_works && (ipl_block.hdr.pbt == DIAG308_IPL_TYPE_CCW))
rc = reipl_get_ascii_vmparm(dest, size, &ipl_block);
else
dest[0] = 0;
return rc;
}
static ssize_t ipl_vm_parm_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
char parm[DIAG308_VMPARM_SIZE + 1] = {};
append_ipl_vmparm(parm, sizeof(parm));
return sprintf(page, "%s\n", parm);
}
static size_t scpdata_length(const char* buf, size_t count)
{
while (count) {
if (buf[count - 1] != '\0' && buf[count - 1] != ' ')
break;
count--;
}
return count;
}
static size_t reipl_append_ascii_scpdata(char *dest, size_t size,
const struct ipl_parameter_block *ipb)
{
size_t count;
size_t i;
int has_lowercase;
count = min(size - 1, scpdata_length(ipb->ipl_info.fcp.scp_data,
ipb->ipl_info.fcp.scp_data_len));
if (!count)
goto out;
has_lowercase = 0;
for (i = 0; i < count; i++) {
if (!isascii(ipb->ipl_info.fcp.scp_data[i])) {
count = 0;
goto out;
}
if (!has_lowercase && islower(ipb->ipl_info.fcp.scp_data[i]))
has_lowercase = 1;
}
if (has_lowercase)
memcpy(dest, ipb->ipl_info.fcp.scp_data, count);
else
for (i = 0; i < count; i++)
dest[i] = tolower(ipb->ipl_info.fcp.scp_data[i]);
out:
dest[count] = '\0';
return count;
}
size_t append_ipl_scpdata(char *dest, size_t len)
{
size_t rc;
rc = 0;
if (ipl_block.hdr.pbt == DIAG308_IPL_TYPE_FCP)
rc = reipl_append_ascii_scpdata(dest, len, &ipl_block);
else
dest[0] = 0;
return rc;
}
static struct kobj_attribute sys_ipl_vm_parm_attr =
__ATTR(parm, S_IRUGO, ipl_vm_parm_show, NULL);
static ssize_t sys_ipl_device_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
struct ipl_parameter_block *ipl = IPL_PARMBLOCK_START;
switch (ipl_info.type) {
case IPL_TYPE_CCW:
return sprintf(page, "0.0.%04x\n", ipl_devno);
case IPL_TYPE_FCP:
case IPL_TYPE_FCP_DUMP:
return sprintf(page, "0.0.%04x\n", ipl->ipl_info.fcp.devno);
default:
return 0;
}
}
static struct kobj_attribute sys_ipl_device_attr =
__ATTR(device, S_IRUGO, sys_ipl_device_show, NULL);
static ssize_t ipl_parameter_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t off, size_t count)
{
return memory_read_from_buffer(buf, count, &off, IPL_PARMBLOCK_START,
IPL_PARMBLOCK_SIZE);
}
static struct bin_attribute ipl_parameter_attr = {
.attr = {
.name = "binary_parameter",
.mode = S_IRUGO,
},
.size = PAGE_SIZE,
.read = &ipl_parameter_read,
};
static ssize_t ipl_scp_data_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t off, size_t count)
{
unsigned int size = IPL_PARMBLOCK_START->ipl_info.fcp.scp_data_len;
void *scp_data = &IPL_PARMBLOCK_START->ipl_info.fcp.scp_data;
return memory_read_from_buffer(buf, count, &off, scp_data, size);
}
static struct bin_attribute ipl_scp_data_attr = {
.attr = {
.name = "scp_data",
.mode = S_IRUGO,
},
.size = PAGE_SIZE,
.read = ipl_scp_data_read,
};
/* FCP ipl device attributes */
DEFINE_IPL_ATTR_RO(ipl_fcp, wwpn, "0x%016llx\n", (unsigned long long)
IPL_PARMBLOCK_START->ipl_info.fcp.wwpn);
DEFINE_IPL_ATTR_RO(ipl_fcp, lun, "0x%016llx\n", (unsigned long long)
IPL_PARMBLOCK_START->ipl_info.fcp.lun);
DEFINE_IPL_ATTR_RO(ipl_fcp, bootprog, "%lld\n", (unsigned long long)
IPL_PARMBLOCK_START->ipl_info.fcp.bootprog);
DEFINE_IPL_ATTR_RO(ipl_fcp, br_lba, "%lld\n", (unsigned long long)
IPL_PARMBLOCK_START->ipl_info.fcp.br_lba);
static struct attribute *ipl_fcp_attrs[] = {
&sys_ipl_type_attr.attr,
&sys_ipl_device_attr.attr,
&sys_ipl_fcp_wwpn_attr.attr,
&sys_ipl_fcp_lun_attr.attr,
&sys_ipl_fcp_bootprog_attr.attr,
&sys_ipl_fcp_br_lba_attr.attr,
NULL,
};
static struct attribute_group ipl_fcp_attr_group = {
.attrs = ipl_fcp_attrs,
};
/* CCW ipl device attributes */
static ssize_t ipl_ccw_loadparm_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
char loadparm[LOADPARM_LEN + 1] = {};
if (!sclp_ipl_info.is_valid)
return sprintf(page, "#unknown#\n");
memcpy(loadparm, &sclp_ipl_info.loadparm, LOADPARM_LEN);
EBCASC(loadparm, LOADPARM_LEN);
strim(loadparm);
return sprintf(page, "%s\n", loadparm);
}
static struct kobj_attribute sys_ipl_ccw_loadparm_attr =
__ATTR(loadparm, 0444, ipl_ccw_loadparm_show, NULL);
static struct attribute *ipl_ccw_attrs_vm[] = {
&sys_ipl_type_attr.attr,
&sys_ipl_device_attr.attr,
&sys_ipl_ccw_loadparm_attr.attr,
&sys_ipl_vm_parm_attr.attr,
NULL,
};
static struct attribute *ipl_ccw_attrs_lpar[] = {
&sys_ipl_type_attr.attr,
&sys_ipl_device_attr.attr,
&sys_ipl_ccw_loadparm_attr.attr,
NULL,
};
static struct attribute_group ipl_ccw_attr_group_vm = {
.attrs = ipl_ccw_attrs_vm,
};
static struct attribute_group ipl_ccw_attr_group_lpar = {
.attrs = ipl_ccw_attrs_lpar
};
/* NSS ipl device attributes */
DEFINE_IPL_ATTR_RO(ipl_nss, name, "%s\n", kernel_nss_name);
static struct attribute *ipl_nss_attrs[] = {
&sys_ipl_type_attr.attr,
&sys_ipl_nss_name_attr.attr,
&sys_ipl_ccw_loadparm_attr.attr,
&sys_ipl_vm_parm_attr.attr,
NULL,
};
static struct attribute_group ipl_nss_attr_group = {
.attrs = ipl_nss_attrs,
};
/* UNKNOWN ipl device attributes */
static struct attribute *ipl_unknown_attrs[] = {
&sys_ipl_type_attr.attr,
NULL,
};
static struct attribute_group ipl_unknown_attr_group = {
.attrs = ipl_unknown_attrs,
};
static struct kset *ipl_kset;
static int __init ipl_register_fcp_files(void)
{
int rc;
rc = sysfs_create_group(&ipl_kset->kobj, &ipl_fcp_attr_group);
if (rc)
goto out;
rc = sysfs_create_bin_file(&ipl_kset->kobj, &ipl_parameter_attr);
if (rc)
goto out_ipl_parm;
rc = sysfs_create_bin_file(&ipl_kset->kobj, &ipl_scp_data_attr);
if (!rc)
goto out;
sysfs_remove_bin_file(&ipl_kset->kobj, &ipl_parameter_attr);
out_ipl_parm:
sysfs_remove_group(&ipl_kset->kobj, &ipl_fcp_attr_group);
out:
return rc;
}
static void __ipl_run(void *unused)
{
diag308(DIAG308_IPL, NULL);
if (MACHINE_IS_VM)
__cpcmd("IPL", NULL, 0, NULL);
else if (ipl_info.type == IPL_TYPE_CCW)
reipl_ccw_dev(&ipl_info.data.ccw.dev_id);
}
static void ipl_run(struct shutdown_trigger *trigger)
{
smp_call_ipl_cpu(__ipl_run, NULL);
}
static int __init ipl_init(void)
{
int rc;
ipl_kset = kset_create_and_add("ipl", NULL, firmware_kobj);
if (!ipl_kset) {
rc = -ENOMEM;
goto out;
}
switch (ipl_info.type) {
case IPL_TYPE_CCW:
if (MACHINE_IS_VM)
rc = sysfs_create_group(&ipl_kset->kobj,
&ipl_ccw_attr_group_vm);
else
rc = sysfs_create_group(&ipl_kset->kobj,
&ipl_ccw_attr_group_lpar);
break;
case IPL_TYPE_FCP:
case IPL_TYPE_FCP_DUMP:
rc = ipl_register_fcp_files();
break;
case IPL_TYPE_NSS:
rc = sysfs_create_group(&ipl_kset->kobj, &ipl_nss_attr_group);
break;
default:
rc = sysfs_create_group(&ipl_kset->kobj,
&ipl_unknown_attr_group);
break;
}
out:
if (rc)
panic("ipl_init failed: rc = %i\n", rc);
return 0;
}
static struct shutdown_action __refdata ipl_action = {
.name = SHUTDOWN_ACTION_IPL_STR,
.fn = ipl_run,
.init = ipl_init,
};
/*
* reipl shutdown action: Reboot Linux on shutdown.
*/
/* VM IPL PARM attributes */
static ssize_t reipl_generic_vmparm_show(struct ipl_parameter_block *ipb,
char *page)
{
char vmparm[DIAG308_VMPARM_SIZE + 1] = {};
reipl_get_ascii_vmparm(vmparm, sizeof(vmparm), ipb);
return sprintf(page, "%s\n", vmparm);
}
static ssize_t reipl_generic_vmparm_store(struct ipl_parameter_block *ipb,
size_t vmparm_max,
const char *buf, size_t len)
{
int i, ip_len;
/* ignore trailing newline */
ip_len = len;
if ((len > 0) && (buf[len - 1] == '\n'))
ip_len--;
if (ip_len > vmparm_max)
return -EINVAL;
/* parm is used to store kernel options, check for common chars */
for (i = 0; i < ip_len; i++)
if (!(isalnum(buf[i]) || isascii(buf[i]) || isprint(buf[i])))
return -EINVAL;
memset(ipb->ipl_info.ccw.vm_parm, 0, DIAG308_VMPARM_SIZE);
ipb->ipl_info.ccw.vm_parm_len = ip_len;
if (ip_len > 0) {
ipb->ipl_info.ccw.vm_flags |= DIAG308_VM_FLAGS_VP_VALID;
memcpy(ipb->ipl_info.ccw.vm_parm, buf, ip_len);
ASCEBC(ipb->ipl_info.ccw.vm_parm, ip_len);
} else {
ipb->ipl_info.ccw.vm_flags &= ~DIAG308_VM_FLAGS_VP_VALID;
}
return len;
}
/* NSS wrapper */
static ssize_t reipl_nss_vmparm_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return reipl_generic_vmparm_show(reipl_block_nss, page);
}
static ssize_t reipl_nss_vmparm_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return reipl_generic_vmparm_store(reipl_block_nss, 56, buf, len);
}
/* CCW wrapper */
static ssize_t reipl_ccw_vmparm_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return reipl_generic_vmparm_show(reipl_block_ccw, page);
}
static ssize_t reipl_ccw_vmparm_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return reipl_generic_vmparm_store(reipl_block_ccw, 64, buf, len);
}
static struct kobj_attribute sys_reipl_nss_vmparm_attr =
__ATTR(parm, S_IRUGO | S_IWUSR, reipl_nss_vmparm_show,
reipl_nss_vmparm_store);
static struct kobj_attribute sys_reipl_ccw_vmparm_attr =
__ATTR(parm, S_IRUGO | S_IWUSR, reipl_ccw_vmparm_show,
reipl_ccw_vmparm_store);
/* FCP reipl device attributes */
static ssize_t reipl_fcp_scpdata_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
size_t size = reipl_block_fcp->ipl_info.fcp.scp_data_len;
void *scp_data = reipl_block_fcp->ipl_info.fcp.scp_data;
return memory_read_from_buffer(buf, count, &off, scp_data, size);
}
static ssize_t reipl_fcp_scpdata_write(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
size_t padding;
size_t scpdata_len;
if (off < 0)
return -EINVAL;
if (off >= DIAG308_SCPDATA_SIZE)
return -ENOSPC;
if (count > DIAG308_SCPDATA_SIZE - off)
count = DIAG308_SCPDATA_SIZE - off;
memcpy(reipl_block_fcp->ipl_info.fcp.scp_data, buf + off, count);
scpdata_len = off + count;
if (scpdata_len % 8) {
padding = 8 - (scpdata_len % 8);
memset(reipl_block_fcp->ipl_info.fcp.scp_data + scpdata_len,
0, padding);
scpdata_len += padding;
}
reipl_block_fcp->ipl_info.fcp.scp_data_len = scpdata_len;
reipl_block_fcp->hdr.len = IPL_PARM_BLK_FCP_LEN + scpdata_len;
reipl_block_fcp->hdr.blk0_len = IPL_PARM_BLK0_FCP_LEN + scpdata_len;
return count;
}
static struct bin_attribute sys_reipl_fcp_scp_data_attr = {
.attr = {
.name = "scp_data",
.mode = S_IRUGO | S_IWUSR,
},
.size = PAGE_SIZE,
.read = reipl_fcp_scpdata_read,
.write = reipl_fcp_scpdata_write,
};
DEFINE_IPL_ATTR_RW(reipl_fcp, wwpn, "0x%016llx\n", "%llx\n",
reipl_block_fcp->ipl_info.fcp.wwpn);
DEFINE_IPL_ATTR_RW(reipl_fcp, lun, "0x%016llx\n", "%llx\n",
reipl_block_fcp->ipl_info.fcp.lun);
DEFINE_IPL_ATTR_RW(reipl_fcp, bootprog, "%lld\n", "%lld\n",
reipl_block_fcp->ipl_info.fcp.bootprog);
DEFINE_IPL_ATTR_RW(reipl_fcp, br_lba, "%lld\n", "%lld\n",
reipl_block_fcp->ipl_info.fcp.br_lba);
DEFINE_IPL_ATTR_RW(reipl_fcp, device, "0.0.%04llx\n", "0.0.%llx\n",
reipl_block_fcp->ipl_info.fcp.devno);
static struct attribute *reipl_fcp_attrs[] = {
&sys_reipl_fcp_device_attr.attr,
&sys_reipl_fcp_wwpn_attr.attr,
&sys_reipl_fcp_lun_attr.attr,
&sys_reipl_fcp_bootprog_attr.attr,
&sys_reipl_fcp_br_lba_attr.attr,
NULL,
};
static struct attribute_group reipl_fcp_attr_group = {
.attrs = reipl_fcp_attrs,
};
/* CCW reipl device attributes */
DEFINE_IPL_ATTR_RW(reipl_ccw, device, "0.0.%04llx\n", "0.0.%llx\n",
reipl_block_ccw->ipl_info.ccw.devno);
static void reipl_get_ascii_loadparm(char *loadparm,
struct ipl_parameter_block *ibp)
{
memcpy(loadparm, ibp->ipl_info.ccw.load_parm, LOADPARM_LEN);
EBCASC(loadparm, LOADPARM_LEN);
loadparm[LOADPARM_LEN] = 0;
strim(loadparm);
}
static ssize_t reipl_generic_loadparm_show(struct ipl_parameter_block *ipb,
char *page)
{
char buf[LOADPARM_LEN + 1];
reipl_get_ascii_loadparm(buf, ipb);
return sprintf(page, "%s\n", buf);
}
static ssize_t reipl_generic_loadparm_store(struct ipl_parameter_block *ipb,
const char *buf, size_t len)
{
int i, lp_len;
/* ignore trailing newline */
lp_len = len;
if ((len > 0) && (buf[len - 1] == '\n'))
lp_len--;
/* loadparm can have max 8 characters and must not start with a blank */
if ((lp_len > LOADPARM_LEN) || ((lp_len > 0) && (buf[0] == ' ')))
return -EINVAL;
/* loadparm can only contain "a-z,A-Z,0-9,SP,." */
for (i = 0; i < lp_len; i++) {
if (isalpha(buf[i]) || isdigit(buf[i]) || (buf[i] == ' ') ||
(buf[i] == '.'))
continue;
return -EINVAL;
}
/* initialize loadparm with blanks */
memset(ipb->ipl_info.ccw.load_parm, ' ', LOADPARM_LEN);
/* copy and convert to ebcdic */
memcpy(ipb->ipl_info.ccw.load_parm, buf, lp_len);
ASCEBC(ipb->ipl_info.ccw.load_parm, LOADPARM_LEN);
return len;
}
/* NSS wrapper */
static ssize_t reipl_nss_loadparm_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return reipl_generic_loadparm_show(reipl_block_nss, page);
}
static ssize_t reipl_nss_loadparm_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return reipl_generic_loadparm_store(reipl_block_nss, buf, len);
}
/* CCW wrapper */
static ssize_t reipl_ccw_loadparm_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return reipl_generic_loadparm_show(reipl_block_ccw, page);
}
static ssize_t reipl_ccw_loadparm_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return reipl_generic_loadparm_store(reipl_block_ccw, buf, len);
}
static struct kobj_attribute sys_reipl_ccw_loadparm_attr =
__ATTR(loadparm, S_IRUGO | S_IWUSR, reipl_ccw_loadparm_show,
reipl_ccw_loadparm_store);
static struct attribute *reipl_ccw_attrs_vm[] = {
&sys_reipl_ccw_device_attr.attr,
&sys_reipl_ccw_loadparm_attr.attr,
&sys_reipl_ccw_vmparm_attr.attr,
NULL,
};
static struct attribute *reipl_ccw_attrs_lpar[] = {
&sys_reipl_ccw_device_attr.attr,
&sys_reipl_ccw_loadparm_attr.attr,
NULL,
};
static struct attribute_group reipl_ccw_attr_group_vm = {
.name = IPL_CCW_STR,
.attrs = reipl_ccw_attrs_vm,
};
static struct attribute_group reipl_ccw_attr_group_lpar = {
.name = IPL_CCW_STR,
.attrs = reipl_ccw_attrs_lpar,
};
/* NSS reipl device attributes */
static void reipl_get_ascii_nss_name(char *dst,
struct ipl_parameter_block *ipb)
{
memcpy(dst, ipb->ipl_info.ccw.nss_name, NSS_NAME_SIZE);
EBCASC(dst, NSS_NAME_SIZE);
dst[NSS_NAME_SIZE] = 0;
}
static ssize_t reipl_nss_name_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
char nss_name[NSS_NAME_SIZE + 1] = {};
reipl_get_ascii_nss_name(nss_name, reipl_block_nss);
return sprintf(page, "%s\n", nss_name);
}
static ssize_t reipl_nss_name_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
int nss_len;
/* ignore trailing newline */
nss_len = len;
if ((len > 0) && (buf[len - 1] == '\n'))
nss_len--;
if (nss_len > NSS_NAME_SIZE)
return -EINVAL;
memset(reipl_block_nss->ipl_info.ccw.nss_name, 0x40, NSS_NAME_SIZE);
if (nss_len > 0) {
reipl_block_nss->ipl_info.ccw.vm_flags |=
DIAG308_VM_FLAGS_NSS_VALID;
memcpy(reipl_block_nss->ipl_info.ccw.nss_name, buf, nss_len);
ASCEBC(reipl_block_nss->ipl_info.ccw.nss_name, nss_len);
EBC_TOUPPER(reipl_block_nss->ipl_info.ccw.nss_name, nss_len);
} else {
reipl_block_nss->ipl_info.ccw.vm_flags &=
~DIAG308_VM_FLAGS_NSS_VALID;
}
return len;
}
static struct kobj_attribute sys_reipl_nss_name_attr =
__ATTR(name, S_IRUGO | S_IWUSR, reipl_nss_name_show,
reipl_nss_name_store);
static struct kobj_attribute sys_reipl_nss_loadparm_attr =
__ATTR(loadparm, S_IRUGO | S_IWUSR, reipl_nss_loadparm_show,
reipl_nss_loadparm_store);
static struct attribute *reipl_nss_attrs[] = {
&sys_reipl_nss_name_attr.attr,
&sys_reipl_nss_loadparm_attr.attr,
&sys_reipl_nss_vmparm_attr.attr,
NULL,
};
static struct attribute_group reipl_nss_attr_group = {
.name = IPL_NSS_STR,
.attrs = reipl_nss_attrs,
};
static void set_reipl_block_actual(struct ipl_parameter_block *reipl_block)
{
reipl_block_actual = reipl_block;
os_info_entry_add(OS_INFO_REIPL_BLOCK, reipl_block_actual,
reipl_block->hdr.len);
}
/* reipl type */
static int reipl_set_type(enum ipl_type type)
{
if (!(reipl_capabilities & type))
return -EINVAL;
switch(type) {
case IPL_TYPE_CCW:
if (diag308_set_works)
reipl_method = REIPL_METHOD_CCW_DIAG;
else if (MACHINE_IS_VM)
reipl_method = REIPL_METHOD_CCW_VM;
else
reipl_method = REIPL_METHOD_CCW_CIO;
set_reipl_block_actual(reipl_block_ccw);
break;
case IPL_TYPE_FCP:
if (diag308_set_works)
reipl_method = REIPL_METHOD_FCP_RW_DIAG;
else if (MACHINE_IS_VM)
reipl_method = REIPL_METHOD_FCP_RO_VM;
else
reipl_method = REIPL_METHOD_FCP_RO_DIAG;
set_reipl_block_actual(reipl_block_fcp);
break;
case IPL_TYPE_FCP_DUMP:
reipl_method = REIPL_METHOD_FCP_DUMP;
break;
case IPL_TYPE_NSS:
if (diag308_set_works)
reipl_method = REIPL_METHOD_NSS_DIAG;
else
reipl_method = REIPL_METHOD_NSS;
set_reipl_block_actual(reipl_block_nss);
break;
case IPL_TYPE_UNKNOWN:
reipl_method = REIPL_METHOD_DEFAULT;
break;
default:
BUG();
}
reipl_type = type;
return 0;
}
static ssize_t reipl_type_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return sprintf(page, "%s\n", ipl_type_str(reipl_type));
}
static ssize_t reipl_type_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
int rc = -EINVAL;
if (strncmp(buf, IPL_CCW_STR, strlen(IPL_CCW_STR)) == 0)
rc = reipl_set_type(IPL_TYPE_CCW);
else if (strncmp(buf, IPL_FCP_STR, strlen(IPL_FCP_STR)) == 0)
rc = reipl_set_type(IPL_TYPE_FCP);
else if (strncmp(buf, IPL_NSS_STR, strlen(IPL_NSS_STR)) == 0)
rc = reipl_set_type(IPL_TYPE_NSS);
return (rc != 0) ? rc : len;
}
static struct kobj_attribute reipl_type_attr =
__ATTR(reipl_type, 0644, reipl_type_show, reipl_type_store);
static struct kset *reipl_kset;
static struct kset *reipl_fcp_kset;
static void get_ipl_string(char *dst, struct ipl_parameter_block *ipb,
const enum ipl_method m)
{
char loadparm[LOADPARM_LEN + 1] = {};
char vmparm[DIAG308_VMPARM_SIZE + 1] = {};
char nss_name[NSS_NAME_SIZE + 1] = {};
size_t pos = 0;
reipl_get_ascii_loadparm(loadparm, ipb);
reipl_get_ascii_nss_name(nss_name, ipb);
reipl_get_ascii_vmparm(vmparm, sizeof(vmparm), ipb);
switch (m) {
case REIPL_METHOD_CCW_VM:
pos = sprintf(dst, "IPL %X CLEAR", ipb->ipl_info.ccw.devno);
break;
case REIPL_METHOD_NSS:
pos = sprintf(dst, "IPL %s", nss_name);
break;
default:
break;
}
if (strlen(loadparm) > 0)
pos += sprintf(dst + pos, " LOADPARM '%s'", loadparm);
if (strlen(vmparm) > 0)
sprintf(dst + pos, " PARM %s", vmparm);
}
static void __reipl_run(void *unused)
{
struct ccw_dev_id devid;
static char buf[128];
switch (reipl_method) {
case REIPL_METHOD_CCW_CIO:
devid.devno = reipl_block_ccw->ipl_info.ccw.devno;
devid.ssid = 0;
reipl_ccw_dev(&devid);
break;
case REIPL_METHOD_CCW_VM:
get_ipl_string(buf, reipl_block_ccw, REIPL_METHOD_CCW_VM);
__cpcmd(buf, NULL, 0, NULL);
break;
case REIPL_METHOD_CCW_DIAG:
diag308(DIAG308_SET, reipl_block_ccw);
diag308(DIAG308_IPL, NULL);
break;
case REIPL_METHOD_FCP_RW_DIAG:
diag308(DIAG308_SET, reipl_block_fcp);
diag308(DIAG308_IPL, NULL);
break;
case REIPL_METHOD_FCP_RO_DIAG:
diag308(DIAG308_IPL, NULL);
break;
case REIPL_METHOD_FCP_RO_VM:
__cpcmd("IPL", NULL, 0, NULL);
break;
case REIPL_METHOD_NSS_DIAG:
diag308(DIAG308_SET, reipl_block_nss);
diag308(DIAG308_IPL, NULL);
break;
case REIPL_METHOD_NSS:
get_ipl_string(buf, reipl_block_nss, REIPL_METHOD_NSS);
__cpcmd(buf, NULL, 0, NULL);
break;
case REIPL_METHOD_DEFAULT:
if (MACHINE_IS_VM)
__cpcmd("IPL", NULL, 0, NULL);
diag308(DIAG308_IPL, NULL);
break;
case REIPL_METHOD_FCP_DUMP:
break;
}
disabled_wait((unsigned long) __builtin_return_address(0));
}
static void reipl_run(struct shutdown_trigger *trigger)
{
smp_call_ipl_cpu(__reipl_run, NULL);
}
static void reipl_block_ccw_init(struct ipl_parameter_block *ipb)
{
ipb->hdr.len = IPL_PARM_BLK_CCW_LEN;
ipb->hdr.version = IPL_PARM_BLOCK_VERSION;
ipb->hdr.blk0_len = IPL_PARM_BLK0_CCW_LEN;
ipb->hdr.pbt = DIAG308_IPL_TYPE_CCW;
}
static void reipl_block_ccw_fill_parms(struct ipl_parameter_block *ipb)
{
/* LOADPARM */
/* check if read scp info worked and set loadparm */
if (sclp_ipl_info.is_valid)
memcpy(ipb->ipl_info.ccw.load_parm,
&sclp_ipl_info.loadparm, LOADPARM_LEN);
else
/* read scp info failed: set empty loadparm (EBCDIC blanks) */
memset(ipb->ipl_info.ccw.load_parm, 0x40, LOADPARM_LEN);
ipb->hdr.flags = DIAG308_FLAGS_LP_VALID;
/* VM PARM */
if (MACHINE_IS_VM && diag308_set_works &&
(ipl_block.ipl_info.ccw.vm_flags & DIAG308_VM_FLAGS_VP_VALID)) {
ipb->ipl_info.ccw.vm_flags |= DIAG308_VM_FLAGS_VP_VALID;
ipb->ipl_info.ccw.vm_parm_len =
ipl_block.ipl_info.ccw.vm_parm_len;
memcpy(ipb->ipl_info.ccw.vm_parm,
ipl_block.ipl_info.ccw.vm_parm, DIAG308_VMPARM_SIZE);
}
}
static int __init reipl_nss_init(void)
{
int rc;
if (!MACHINE_IS_VM)
return 0;
reipl_block_nss = (void *) get_zeroed_page(GFP_KERNEL);
if (!reipl_block_nss)
return -ENOMEM;
if (!diag308_set_works)
sys_reipl_nss_vmparm_attr.attr.mode = S_IRUGO;
rc = sysfs_create_group(&reipl_kset->kobj, &reipl_nss_attr_group);
if (rc)
return rc;
reipl_block_ccw_init(reipl_block_nss);
if (ipl_info.type == IPL_TYPE_NSS) {
memset(reipl_block_nss->ipl_info.ccw.nss_name,
' ', NSS_NAME_SIZE);
memcpy(reipl_block_nss->ipl_info.ccw.nss_name,
kernel_nss_name, strlen(kernel_nss_name));
ASCEBC(reipl_block_nss->ipl_info.ccw.nss_name, NSS_NAME_SIZE);
reipl_block_nss->ipl_info.ccw.vm_flags |=
DIAG308_VM_FLAGS_NSS_VALID;
reipl_block_ccw_fill_parms(reipl_block_nss);
}
reipl_capabilities |= IPL_TYPE_NSS;
return 0;
}
static int __init reipl_ccw_init(void)
{
int rc;
reipl_block_ccw = (void *) get_zeroed_page(GFP_KERNEL);
if (!reipl_block_ccw)
return -ENOMEM;
if (MACHINE_IS_VM) {
if (!diag308_set_works)
sys_reipl_ccw_vmparm_attr.attr.mode = S_IRUGO;
rc = sysfs_create_group(&reipl_kset->kobj,
&reipl_ccw_attr_group_vm);
} else {
if(!diag308_set_works)
sys_reipl_ccw_loadparm_attr.attr.mode = S_IRUGO;
rc = sysfs_create_group(&reipl_kset->kobj,
&reipl_ccw_attr_group_lpar);
}
if (rc)
return rc;
reipl_block_ccw_init(reipl_block_ccw);
if (ipl_info.type == IPL_TYPE_CCW) {
reipl_block_ccw->ipl_info.ccw.devno = ipl_devno;
reipl_block_ccw_fill_parms(reipl_block_ccw);
}
reipl_capabilities |= IPL_TYPE_CCW;
return 0;
}
static int __init reipl_fcp_init(void)
{
int rc;
if (!diag308_set_works) {
if (ipl_info.type == IPL_TYPE_FCP) {
make_attrs_ro(reipl_fcp_attrs);
sys_reipl_fcp_scp_data_attr.attr.mode = S_IRUGO;
} else
return 0;
}
reipl_block_fcp = (void *) get_zeroed_page(GFP_KERNEL);
if (!reipl_block_fcp)
return -ENOMEM;
/* sysfs: create fcp kset for mixing attr group and bin attrs */
reipl_fcp_kset = kset_create_and_add(IPL_FCP_STR, NULL,
&reipl_kset->kobj);
if (!reipl_fcp_kset) {
free_page((unsigned long) reipl_block_fcp);
return -ENOMEM;
}
rc = sysfs_create_group(&reipl_fcp_kset->kobj, &reipl_fcp_attr_group);
if (rc) {
kset_unregister(reipl_fcp_kset);
free_page((unsigned long) reipl_block_fcp);
return rc;
}
rc = sysfs_create_bin_file(&reipl_fcp_kset->kobj,
&sys_reipl_fcp_scp_data_attr);
if (rc) {
sysfs_remove_group(&reipl_fcp_kset->kobj, &reipl_fcp_attr_group);
kset_unregister(reipl_fcp_kset);
free_page((unsigned long) reipl_block_fcp);
return rc;
}
if (ipl_info.type == IPL_TYPE_FCP)
memcpy(reipl_block_fcp, IPL_PARMBLOCK_START, PAGE_SIZE);
else {
reipl_block_fcp->hdr.len = IPL_PARM_BLK_FCP_LEN;
reipl_block_fcp->hdr.version = IPL_PARM_BLOCK_VERSION;
reipl_block_fcp->hdr.blk0_len = IPL_PARM_BLK0_FCP_LEN;
reipl_block_fcp->hdr.pbt = DIAG308_IPL_TYPE_FCP;
reipl_block_fcp->ipl_info.fcp.opt = DIAG308_IPL_OPT_IPL;
}
reipl_capabilities |= IPL_TYPE_FCP;
return 0;
}
static int __init reipl_type_init(void)
{
enum ipl_type reipl_type = ipl_info.type;
struct ipl_parameter_block *reipl_block;
unsigned long size;
reipl_block = os_info_old_entry(OS_INFO_REIPL_BLOCK, &size);
if (!reipl_block)
goto out;
/*
* If we have an OS info reipl block, this will be used
*/
if (reipl_block->hdr.pbt == DIAG308_IPL_TYPE_FCP) {
memcpy(reipl_block_fcp, reipl_block, size);
reipl_type = IPL_TYPE_FCP;
} else if (reipl_block->hdr.pbt == DIAG308_IPL_TYPE_CCW) {
memcpy(reipl_block_ccw, reipl_block, size);
reipl_type = IPL_TYPE_CCW;
}
out:
return reipl_set_type(reipl_type);
}
static int __init reipl_init(void)
{
int rc;
reipl_kset = kset_create_and_add("reipl", NULL, firmware_kobj);
if (!reipl_kset)
return -ENOMEM;
rc = sysfs_create_file(&reipl_kset->kobj, &reipl_type_attr.attr);
if (rc) {
kset_unregister(reipl_kset);
return rc;
}
rc = reipl_ccw_init();
if (rc)
return rc;
rc = reipl_fcp_init();
if (rc)
return rc;
rc = reipl_nss_init();
if (rc)
return rc;
return reipl_type_init();
}
static struct shutdown_action __refdata reipl_action = {
.name = SHUTDOWN_ACTION_REIPL_STR,
.fn = reipl_run,
.init = reipl_init,
};
/*
* dump shutdown action: Dump Linux on shutdown.
*/
/* FCP dump device attributes */
DEFINE_IPL_ATTR_RW(dump_fcp, wwpn, "0x%016llx\n", "%llx\n",
dump_block_fcp->ipl_info.fcp.wwpn);
DEFINE_IPL_ATTR_RW(dump_fcp, lun, "0x%016llx\n", "%llx\n",
dump_block_fcp->ipl_info.fcp.lun);
DEFINE_IPL_ATTR_RW(dump_fcp, bootprog, "%lld\n", "%lld\n",
dump_block_fcp->ipl_info.fcp.bootprog);
DEFINE_IPL_ATTR_RW(dump_fcp, br_lba, "%lld\n", "%lld\n",
dump_block_fcp->ipl_info.fcp.br_lba);
DEFINE_IPL_ATTR_RW(dump_fcp, device, "0.0.%04llx\n", "0.0.%llx\n",
dump_block_fcp->ipl_info.fcp.devno);
static struct attribute *dump_fcp_attrs[] = {
&sys_dump_fcp_device_attr.attr,
&sys_dump_fcp_wwpn_attr.attr,
&sys_dump_fcp_lun_attr.attr,
&sys_dump_fcp_bootprog_attr.attr,
&sys_dump_fcp_br_lba_attr.attr,
NULL,
};
static struct attribute_group dump_fcp_attr_group = {
.name = IPL_FCP_STR,
.attrs = dump_fcp_attrs,
};
/* CCW dump device attributes */
DEFINE_IPL_ATTR_RW(dump_ccw, device, "0.0.%04llx\n", "0.0.%llx\n",
dump_block_ccw->ipl_info.ccw.devno);
static struct attribute *dump_ccw_attrs[] = {
&sys_dump_ccw_device_attr.attr,
NULL,
};
static struct attribute_group dump_ccw_attr_group = {
.name = IPL_CCW_STR,
.attrs = dump_ccw_attrs,
};
/* dump type */
static int dump_set_type(enum dump_type type)
{
if (!(dump_capabilities & type))
return -EINVAL;
switch (type) {
case DUMP_TYPE_CCW:
if (diag308_set_works)
dump_method = DUMP_METHOD_CCW_DIAG;
else if (MACHINE_IS_VM)
dump_method = DUMP_METHOD_CCW_VM;
else
dump_method = DUMP_METHOD_CCW_CIO;
break;
case DUMP_TYPE_FCP:
dump_method = DUMP_METHOD_FCP_DIAG;
break;
default:
dump_method = DUMP_METHOD_NONE;
}
dump_type = type;
return 0;
}
static ssize_t dump_type_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return sprintf(page, "%s\n", dump_type_str(dump_type));
}
static ssize_t dump_type_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
int rc = -EINVAL;
if (strncmp(buf, DUMP_NONE_STR, strlen(DUMP_NONE_STR)) == 0)
rc = dump_set_type(DUMP_TYPE_NONE);
else if (strncmp(buf, DUMP_CCW_STR, strlen(DUMP_CCW_STR)) == 0)
rc = dump_set_type(DUMP_TYPE_CCW);
else if (strncmp(buf, DUMP_FCP_STR, strlen(DUMP_FCP_STR)) == 0)
rc = dump_set_type(DUMP_TYPE_FCP);
return (rc != 0) ? rc : len;
}
static struct kobj_attribute dump_type_attr =
__ATTR(dump_type, 0644, dump_type_show, dump_type_store);
static struct kset *dump_kset;
static void diag308_dump(void *dump_block)
{
diag308(DIAG308_SET, dump_block);
while (1) {
if (diag308(DIAG308_DUMP, NULL) != 0x302)
break;
udelay_simple(USEC_PER_SEC);
}
}
static void __dump_run(void *unused)
{
struct ccw_dev_id devid;
static char buf[100];
switch (dump_method) {
case DUMP_METHOD_CCW_CIO:
devid.devno = dump_block_ccw->ipl_info.ccw.devno;
devid.ssid = 0;
reipl_ccw_dev(&devid);
break;
case DUMP_METHOD_CCW_VM:
sprintf(buf, "STORE STATUS");
__cpcmd(buf, NULL, 0, NULL);
sprintf(buf, "IPL %X", dump_block_ccw->ipl_info.ccw.devno);
__cpcmd(buf, NULL, 0, NULL);
break;
case DUMP_METHOD_CCW_DIAG:
diag308_dump(dump_block_ccw);
break;
case DUMP_METHOD_FCP_DIAG:
diag308_dump(dump_block_fcp);
break;
default:
break;
}
}
static void dump_run(struct shutdown_trigger *trigger)
{
if (dump_method == DUMP_METHOD_NONE)
return;
smp_send_stop();
smp_call_ipl_cpu(__dump_run, NULL);
}
static int __init dump_ccw_init(void)
{
int rc;
dump_block_ccw = (void *) get_zeroed_page(GFP_KERNEL);
if (!dump_block_ccw)
return -ENOMEM;
rc = sysfs_create_group(&dump_kset->kobj, &dump_ccw_attr_group);
if (rc) {
free_page((unsigned long)dump_block_ccw);
return rc;
}
dump_block_ccw->hdr.len = IPL_PARM_BLK_CCW_LEN;
dump_block_ccw->hdr.version = IPL_PARM_BLOCK_VERSION;
dump_block_ccw->hdr.blk0_len = IPL_PARM_BLK0_CCW_LEN;
dump_block_ccw->hdr.pbt = DIAG308_IPL_TYPE_CCW;
dump_capabilities |= DUMP_TYPE_CCW;
return 0;
}
static int __init dump_fcp_init(void)
{
int rc;
if (!sclp_ipl_info.has_dump)
return 0; /* LDIPL DUMP is not installed */
if (!diag308_set_works)
return 0;
dump_block_fcp = (void *) get_zeroed_page(GFP_KERNEL);
if (!dump_block_fcp)
return -ENOMEM;
rc = sysfs_create_group(&dump_kset->kobj, &dump_fcp_attr_group);
if (rc) {
free_page((unsigned long)dump_block_fcp);
return rc;
}
dump_block_fcp->hdr.len = IPL_PARM_BLK_FCP_LEN;
dump_block_fcp->hdr.version = IPL_PARM_BLOCK_VERSION;
dump_block_fcp->hdr.blk0_len = IPL_PARM_BLK0_FCP_LEN;
dump_block_fcp->hdr.pbt = DIAG308_IPL_TYPE_FCP;
dump_block_fcp->ipl_info.fcp.opt = DIAG308_IPL_OPT_DUMP;
dump_capabilities |= DUMP_TYPE_FCP;
return 0;
}
static int __init dump_init(void)
{
int rc;
dump_kset = kset_create_and_add("dump", NULL, firmware_kobj);
if (!dump_kset)
return -ENOMEM;
rc = sysfs_create_file(&dump_kset->kobj, &dump_type_attr.attr);
if (rc) {
kset_unregister(dump_kset);
return rc;
}
rc = dump_ccw_init();
if (rc)
return rc;
rc = dump_fcp_init();
if (rc)
return rc;
dump_set_type(DUMP_TYPE_NONE);
return 0;
}
static struct shutdown_action __refdata dump_action = {
.name = SHUTDOWN_ACTION_DUMP_STR,
.fn = dump_run,
.init = dump_init,
};
static void dump_reipl_run(struct shutdown_trigger *trigger)
{
unsigned long ipib = (unsigned long) reipl_block_actual;
unsigned int csum;
csum = csum_partial(reipl_block_actual, reipl_block_actual->hdr.len, 0);
mem_assign_absolute(S390_lowcore.ipib, ipib);
mem_assign_absolute(S390_lowcore.ipib_checksum, csum);
dump_run(trigger);
}
static int __init dump_reipl_init(void)
{
if (!diag308_set_works)
return -EOPNOTSUPP;
else
return 0;
}
static struct shutdown_action __refdata dump_reipl_action = {
.name = SHUTDOWN_ACTION_DUMP_REIPL_STR,
.fn = dump_reipl_run,
.init = dump_reipl_init,
};
/*
* vmcmd shutdown action: Trigger vm command on shutdown.
*/
static char vmcmd_on_reboot[128];
static char vmcmd_on_panic[128];
static char vmcmd_on_halt[128];
static char vmcmd_on_poff[128];
static char vmcmd_on_restart[128];
DEFINE_IPL_ATTR_STR_RW(vmcmd, on_reboot, "%s\n", "%s\n", vmcmd_on_reboot);
DEFINE_IPL_ATTR_STR_RW(vmcmd, on_panic, "%s\n", "%s\n", vmcmd_on_panic);
DEFINE_IPL_ATTR_STR_RW(vmcmd, on_halt, "%s\n", "%s\n", vmcmd_on_halt);
DEFINE_IPL_ATTR_STR_RW(vmcmd, on_poff, "%s\n", "%s\n", vmcmd_on_poff);
DEFINE_IPL_ATTR_STR_RW(vmcmd, on_restart, "%s\n", "%s\n", vmcmd_on_restart);
static struct attribute *vmcmd_attrs[] = {
&sys_vmcmd_on_reboot_attr.attr,
&sys_vmcmd_on_panic_attr.attr,
&sys_vmcmd_on_halt_attr.attr,
&sys_vmcmd_on_poff_attr.attr,
&sys_vmcmd_on_restart_attr.attr,
NULL,
};
static struct attribute_group vmcmd_attr_group = {
.attrs = vmcmd_attrs,
};
static struct kset *vmcmd_kset;
static void vmcmd_run(struct shutdown_trigger *trigger)
{
char *cmd;
if (strcmp(trigger->name, ON_REIPL_STR) == 0)
cmd = vmcmd_on_reboot;
else if (strcmp(trigger->name, ON_PANIC_STR) == 0)
cmd = vmcmd_on_panic;
else if (strcmp(trigger->name, ON_HALT_STR) == 0)
cmd = vmcmd_on_halt;
else if (strcmp(trigger->name, ON_POFF_STR) == 0)
cmd = vmcmd_on_poff;
else if (strcmp(trigger->name, ON_RESTART_STR) == 0)
cmd = vmcmd_on_restart;
else
return;
if (strlen(cmd) == 0)
return;
__cpcmd(cmd, NULL, 0, NULL);
}
static int vmcmd_init(void)
{
if (!MACHINE_IS_VM)
return -EOPNOTSUPP;
vmcmd_kset = kset_create_and_add("vmcmd", NULL, firmware_kobj);
if (!vmcmd_kset)
return -ENOMEM;
return sysfs_create_group(&vmcmd_kset->kobj, &vmcmd_attr_group);
}
static struct shutdown_action vmcmd_action = {SHUTDOWN_ACTION_VMCMD_STR,
vmcmd_run, vmcmd_init};
/*
* stop shutdown action: Stop Linux on shutdown.
*/
static void stop_run(struct shutdown_trigger *trigger)
{
if (strcmp(trigger->name, ON_PANIC_STR) == 0 ||
strcmp(trigger->name, ON_RESTART_STR) == 0)
disabled_wait((unsigned long) __builtin_return_address(0));
smp_stop_cpu();
}
static struct shutdown_action stop_action = {SHUTDOWN_ACTION_STOP_STR,
stop_run, NULL};
/* action list */
static struct shutdown_action *shutdown_actions_list[] = {
&ipl_action, &reipl_action, &dump_reipl_action, &dump_action,
&vmcmd_action, &stop_action};
#define SHUTDOWN_ACTIONS_COUNT (sizeof(shutdown_actions_list) / sizeof(void *))
/*
* Trigger section
*/
static struct kset *shutdown_actions_kset;
static int set_trigger(const char *buf, struct shutdown_trigger *trigger,
size_t len)
{
int i;
for (i = 0; i < SHUTDOWN_ACTIONS_COUNT; i++) {
if (sysfs_streq(buf, shutdown_actions_list[i]->name)) {
if (shutdown_actions_list[i]->init_rc) {
return shutdown_actions_list[i]->init_rc;
} else {
trigger->action = shutdown_actions_list[i];
return len;
}
}
}
return -EINVAL;
}
/* on reipl */
static struct shutdown_trigger on_reboot_trigger = {ON_REIPL_STR,
&reipl_action};
static ssize_t on_reboot_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return sprintf(page, "%s\n", on_reboot_trigger.action->name);
}
static ssize_t on_reboot_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return set_trigger(buf, &on_reboot_trigger, len);
}
static struct kobj_attribute on_reboot_attr =
__ATTR(on_reboot, 0644, on_reboot_show, on_reboot_store);
static void do_machine_restart(char *__unused)
{
smp_send_stop();
on_reboot_trigger.action->fn(&on_reboot_trigger);
reipl_run(NULL);
}
void (*_machine_restart)(char *command) = do_machine_restart;
/* on panic */
static struct shutdown_trigger on_panic_trigger = {ON_PANIC_STR, &stop_action};
static ssize_t on_panic_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return sprintf(page, "%s\n", on_panic_trigger.action->name);
}
static ssize_t on_panic_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return set_trigger(buf, &on_panic_trigger, len);
}
static struct kobj_attribute on_panic_attr =
__ATTR(on_panic, 0644, on_panic_show, on_panic_store);
static void do_panic(void)
{
lgr_info_log();
on_panic_trigger.action->fn(&on_panic_trigger);
stop_run(&on_panic_trigger);
}
/* on restart */
static struct shutdown_trigger on_restart_trigger = {ON_RESTART_STR,
&stop_action};
static ssize_t on_restart_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return sprintf(page, "%s\n", on_restart_trigger.action->name);
}
static ssize_t on_restart_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return set_trigger(buf, &on_restart_trigger, len);
}
static struct kobj_attribute on_restart_attr =
__ATTR(on_restart, 0644, on_restart_show, on_restart_store);
static void __do_restart(void *ignore)
{
__arch_local_irq_stosm(0x04); /* enable DAT */
smp_send_stop();
#ifdef CONFIG_CRASH_DUMP
crash_kexec(NULL);
#endif
on_restart_trigger.action->fn(&on_restart_trigger);
stop_run(&on_restart_trigger);
}
void do_restart(void)
{
tracing_off();
debug_locks_off();
lgr_info_log();
smp_call_online_cpu(__do_restart, NULL);
}
/* on halt */
static struct shutdown_trigger on_halt_trigger = {ON_HALT_STR, &stop_action};
static ssize_t on_halt_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return sprintf(page, "%s\n", on_halt_trigger.action->name);
}
static ssize_t on_halt_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return set_trigger(buf, &on_halt_trigger, len);
}
static struct kobj_attribute on_halt_attr =
__ATTR(on_halt, 0644, on_halt_show, on_halt_store);
static void do_machine_halt(void)
{
smp_send_stop();
on_halt_trigger.action->fn(&on_halt_trigger);
stop_run(&on_halt_trigger);
}
void (*_machine_halt)(void) = do_machine_halt;
/* on power off */
static struct shutdown_trigger on_poff_trigger = {ON_POFF_STR, &stop_action};
static ssize_t on_poff_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
return sprintf(page, "%s\n", on_poff_trigger.action->name);
}
static ssize_t on_poff_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
return set_trigger(buf, &on_poff_trigger, len);
}
static struct kobj_attribute on_poff_attr =
__ATTR(on_poff, 0644, on_poff_show, on_poff_store);
static void do_machine_power_off(void)
{
smp_send_stop();
on_poff_trigger.action->fn(&on_poff_trigger);
stop_run(&on_poff_trigger);
}
void (*_machine_power_off)(void) = do_machine_power_off;
static void __init shutdown_triggers_init(void)
{
shutdown_actions_kset = kset_create_and_add("shutdown_actions", NULL,
firmware_kobj);
if (!shutdown_actions_kset)
goto fail;
if (sysfs_create_file(&shutdown_actions_kset->kobj,
&on_reboot_attr.attr))
goto fail;
if (sysfs_create_file(&shutdown_actions_kset->kobj,
&on_panic_attr.attr))
goto fail;
if (sysfs_create_file(&shutdown_actions_kset->kobj,
&on_halt_attr.attr))
goto fail;
if (sysfs_create_file(&shutdown_actions_kset->kobj,
&on_poff_attr.attr))
goto fail;
if (sysfs_create_file(&shutdown_actions_kset->kobj,
&on_restart_attr.attr))
goto fail;
return;
fail:
panic("shutdown_triggers_init failed\n");
}
static void __init shutdown_actions_init(void)
{
int i;
for (i = 0; i < SHUTDOWN_ACTIONS_COUNT; i++) {
if (!shutdown_actions_list[i]->init)
continue;
shutdown_actions_list[i]->init_rc =
shutdown_actions_list[i]->init();
}
}
static int __init s390_ipl_init(void)
{
sclp_get_ipl_info(&sclp_ipl_info);
shutdown_actions_init();
shutdown_triggers_init();
return 0;
}
__initcall(s390_ipl_init);
static void __init strncpy_skip_quote(char *dst, char *src, int n)
{
int sx, dx;
dx = 0;
for (sx = 0; src[sx] != 0; sx++) {
if (src[sx] == '"')
continue;
dst[dx++] = src[sx];
if (dx >= n)
break;
}
}
static int __init vmcmd_on_reboot_setup(char *str)
{
if (!MACHINE_IS_VM)
return 1;
strncpy_skip_quote(vmcmd_on_reboot, str, 127);
vmcmd_on_reboot[127] = 0;
on_reboot_trigger.action = &vmcmd_action;
return 1;
}
__setup("vmreboot=", vmcmd_on_reboot_setup);
static int __init vmcmd_on_panic_setup(char *str)
{
if (!MACHINE_IS_VM)
return 1;
strncpy_skip_quote(vmcmd_on_panic, str, 127);
vmcmd_on_panic[127] = 0;
on_panic_trigger.action = &vmcmd_action;
return 1;
}
__setup("vmpanic=", vmcmd_on_panic_setup);
static int __init vmcmd_on_halt_setup(char *str)
{
if (!MACHINE_IS_VM)
return 1;
strncpy_skip_quote(vmcmd_on_halt, str, 127);
vmcmd_on_halt[127] = 0;
on_halt_trigger.action = &vmcmd_action;
return 1;
}
__setup("vmhalt=", vmcmd_on_halt_setup);
static int __init vmcmd_on_poff_setup(char *str)
{
if (!MACHINE_IS_VM)
return 1;
strncpy_skip_quote(vmcmd_on_poff, str, 127);
vmcmd_on_poff[127] = 0;
on_poff_trigger.action = &vmcmd_action;
return 1;
}
__setup("vmpoff=", vmcmd_on_poff_setup);
static int on_panic_notify(struct notifier_block *self,
unsigned long event, void *data)
{
do_panic();
return NOTIFY_OK;
}
static struct notifier_block on_panic_nb = {
.notifier_call = on_panic_notify,
.priority = INT_MIN,
};
void __init setup_ipl(void)
{
ipl_info.type = get_ipl_type();
switch (ipl_info.type) {
case IPL_TYPE_CCW:
ipl_info.data.ccw.dev_id.devno = ipl_devno;
ipl_info.data.ccw.dev_id.ssid = 0;
break;
case IPL_TYPE_FCP:
case IPL_TYPE_FCP_DUMP:
ipl_info.data.fcp.dev_id.devno =
IPL_PARMBLOCK_START->ipl_info.fcp.devno;
ipl_info.data.fcp.dev_id.ssid = 0;
ipl_info.data.fcp.wwpn = IPL_PARMBLOCK_START->ipl_info.fcp.wwpn;
ipl_info.data.fcp.lun = IPL_PARMBLOCK_START->ipl_info.fcp.lun;
break;
case IPL_TYPE_NSS:
strncpy(ipl_info.data.nss.name, kernel_nss_name,
sizeof(ipl_info.data.nss.name));
break;
case IPL_TYPE_UNKNOWN:
/* We have no info to copy */
break;
}
atomic_notifier_chain_register(&panic_notifier_list, &on_panic_nb);
}
void __init ipl_update_parameters(void)
{
int rc;
rc = diag308(DIAG308_STORE, &ipl_block);
if ((rc == DIAG308_RC_OK) || (rc == DIAG308_RC_NOCONFIG))
diag308_set_works = 1;
}
void __init ipl_save_parameters(void)
{
struct cio_iplinfo iplinfo;
void *src, *dst;
if (cio_get_iplinfo(&iplinfo))
return;
ipl_devno = iplinfo.devno;
ipl_flags |= IPL_DEVNO_VALID;
if (!iplinfo.is_qdio)
return;
ipl_flags |= IPL_PARMBLOCK_VALID;
src = (void *)(unsigned long)S390_lowcore.ipl_parmblock_ptr;
dst = (void *)IPL_PARMBLOCK_ORIGIN;
memmove(dst, src, PAGE_SIZE);
S390_lowcore.ipl_parmblock_ptr = IPL_PARMBLOCK_ORIGIN;
}
static LIST_HEAD(rcall);
static DEFINE_MUTEX(rcall_mutex);
void register_reset_call(struct reset_call *reset)
{
mutex_lock(&rcall_mutex);
list_add(&reset->list, &rcall);
mutex_unlock(&rcall_mutex);
}
EXPORT_SYMBOL_GPL(register_reset_call);
void unregister_reset_call(struct reset_call *reset)
{
mutex_lock(&rcall_mutex);
list_del(&reset->list);
mutex_unlock(&rcall_mutex);
}
EXPORT_SYMBOL_GPL(unregister_reset_call);
static void do_reset_calls(void)
{
struct reset_call *reset;
#ifdef CONFIG_64BIT
if (diag308_set_works) {
diag308_reset();
return;
}
#endif
list_for_each_entry(reset, &rcall, list)
reset->fn();
}
u32 dump_prefix_page;
void s390_reset_system(void (*func)(void *), void *data)
{
struct _lowcore *lc;
lc = (struct _lowcore *)(unsigned long) store_prefix();
/* Stack for interrupt/machine check handler */
lc->panic_stack = S390_lowcore.panic_stack;
/* Save prefix page address for dump case */
dump_prefix_page = (u32)(unsigned long) lc;
/* Disable prefixing */
set_prefix(0);
/* Disable lowcore protection */
__ctl_clear_bit(0,28);
/* Set new machine check handler */
S390_lowcore.mcck_new_psw.mask = psw_kernel_bits | PSW_MASK_DAT;
S390_lowcore.mcck_new_psw.addr =
PSW_ADDR_AMODE | (unsigned long) s390_base_mcck_handler;
/* Set new program check handler */
S390_lowcore.program_new_psw.mask = psw_kernel_bits | PSW_MASK_DAT;
S390_lowcore.program_new_psw.addr =
PSW_ADDR_AMODE | (unsigned long) s390_base_pgm_handler;
/* Store status at absolute zero */
store_status();
do_reset_calls();
if (func)
func(data);
}
| gpl-2.0 |
baran0119/android_kernel_samsung_gprimeltexx | drivers/isdn/hisax/avm_pci.c | 2314 | 23142 | /* $Id: avm_pci.c,v 1.29.2.4 2004/02/11 13:21:32 keil Exp $
*
* low level stuff for AVM Fritz!PCI and ISA PnP isdn cards
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* Thanks to AVM, Berlin for information
*
*/
#include <linux/init.h>
#include "hisax.h"
#include "isac.h"
#include "isdnl1.h"
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/isapnp.h>
#include <linux/interrupt.h>
static const char *avm_pci_rev = "$Revision: 1.29.2.4 $";
#define AVM_FRITZ_PCI 1
#define AVM_FRITZ_PNP 2
#define HDLC_FIFO 0x0
#define HDLC_STATUS 0x4
#define AVM_HDLC_1 0x00
#define AVM_HDLC_2 0x01
#define AVM_ISAC_FIFO 0x02
#define AVM_ISAC_REG_LOW 0x04
#define AVM_ISAC_REG_HIGH 0x06
#define AVM_STATUS0_IRQ_ISAC 0x01
#define AVM_STATUS0_IRQ_HDLC 0x02
#define AVM_STATUS0_IRQ_TIMER 0x04
#define AVM_STATUS0_IRQ_MASK 0x07
#define AVM_STATUS0_RESET 0x01
#define AVM_STATUS0_DIS_TIMER 0x02
#define AVM_STATUS0_RES_TIMER 0x04
#define AVM_STATUS0_ENA_IRQ 0x08
#define AVM_STATUS0_TESTBIT 0x10
#define AVM_STATUS1_INT_SEL 0x0f
#define AVM_STATUS1_ENA_IOM 0x80
#define HDLC_MODE_ITF_FLG 0x01
#define HDLC_MODE_TRANS 0x02
#define HDLC_MODE_CCR_7 0x04
#define HDLC_MODE_CCR_16 0x08
#define HDLC_MODE_TESTLOOP 0x80
#define HDLC_INT_XPR 0x80
#define HDLC_INT_XDU 0x40
#define HDLC_INT_RPR 0x20
#define HDLC_INT_MASK 0xE0
#define HDLC_STAT_RME 0x01
#define HDLC_STAT_RDO 0x10
#define HDLC_STAT_CRCVFRRAB 0x0E
#define HDLC_STAT_CRCVFR 0x06
#define HDLC_STAT_RML_MASK 0x3f00
#define HDLC_CMD_XRS 0x80
#define HDLC_CMD_XME 0x01
#define HDLC_CMD_RRS 0x20
#define HDLC_CMD_XML_MASK 0x3f00
/* Interface functions */
static u_char
ReadISAC(struct IsdnCardState *cs, u_char offset)
{
register u_char idx = (offset > 0x2f) ? AVM_ISAC_REG_HIGH : AVM_ISAC_REG_LOW;
register u_char val;
outb(idx, cs->hw.avm.cfg_reg + 4);
val = inb(cs->hw.avm.isac + (offset & 0xf));
return (val);
}
static void
WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
register u_char idx = (offset > 0x2f) ? AVM_ISAC_REG_HIGH : AVM_ISAC_REG_LOW;
outb(idx, cs->hw.avm.cfg_reg + 4);
outb(value, cs->hw.avm.isac + (offset & 0xf));
}
static void
ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size)
{
outb(AVM_ISAC_FIFO, cs->hw.avm.cfg_reg + 4);
insb(cs->hw.avm.isac, data, size);
}
static void
WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size)
{
outb(AVM_ISAC_FIFO, cs->hw.avm.cfg_reg + 4);
outsb(cs->hw.avm.isac, data, size);
}
static inline u_int
ReadHDLCPCI(struct IsdnCardState *cs, int chan, u_char offset)
{
register u_int idx = chan ? AVM_HDLC_2 : AVM_HDLC_1;
register u_int val;
outl(idx, cs->hw.avm.cfg_reg + 4);
val = inl(cs->hw.avm.isac + offset);
return (val);
}
static inline void
WriteHDLCPCI(struct IsdnCardState *cs, int chan, u_char offset, u_int value)
{
register u_int idx = chan ? AVM_HDLC_2 : AVM_HDLC_1;
outl(idx, cs->hw.avm.cfg_reg + 4);
outl(value, cs->hw.avm.isac + offset);
}
static inline u_char
ReadHDLCPnP(struct IsdnCardState *cs, int chan, u_char offset)
{
register u_char idx = chan ? AVM_HDLC_2 : AVM_HDLC_1;
register u_char val;
outb(idx, cs->hw.avm.cfg_reg + 4);
val = inb(cs->hw.avm.isac + offset);
return (val);
}
static inline void
WriteHDLCPnP(struct IsdnCardState *cs, int chan, u_char offset, u_char value)
{
register u_char idx = chan ? AVM_HDLC_2 : AVM_HDLC_1;
outb(idx, cs->hw.avm.cfg_reg + 4);
outb(value, cs->hw.avm.isac + offset);
}
static u_char
ReadHDLC_s(struct IsdnCardState *cs, int chan, u_char offset)
{
return (0xff & ReadHDLCPCI(cs, chan, offset));
}
static void
WriteHDLC_s(struct IsdnCardState *cs, int chan, u_char offset, u_char value)
{
WriteHDLCPCI(cs, chan, offset, value);
}
static inline
struct BCState *Sel_BCS(struct IsdnCardState *cs, int channel)
{
if (cs->bcs[0].mode && (cs->bcs[0].channel == channel))
return (&cs->bcs[0]);
else if (cs->bcs[1].mode && (cs->bcs[1].channel == channel))
return (&cs->bcs[1]);
else
return (NULL);
}
static void
write_ctrl(struct BCState *bcs, int which) {
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "hdlc %c wr%x ctrl %x",
'A' + bcs->channel, which, bcs->hw.hdlc.ctrl.ctrl);
if (bcs->cs->subtyp == AVM_FRITZ_PCI) {
WriteHDLCPCI(bcs->cs, bcs->channel, HDLC_STATUS, bcs->hw.hdlc.ctrl.ctrl);
} else {
if (which & 4)
WriteHDLCPnP(bcs->cs, bcs->channel, HDLC_STATUS + 2,
bcs->hw.hdlc.ctrl.sr.mode);
if (which & 2)
WriteHDLCPnP(bcs->cs, bcs->channel, HDLC_STATUS + 1,
bcs->hw.hdlc.ctrl.sr.xml);
if (which & 1)
WriteHDLCPnP(bcs->cs, bcs->channel, HDLC_STATUS,
bcs->hw.hdlc.ctrl.sr.cmd);
}
}
static void
modehdlc(struct BCState *bcs, int mode, int bc)
{
struct IsdnCardState *cs = bcs->cs;
int hdlc = bcs->channel;
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "hdlc %c mode %d --> %d ichan %d --> %d",
'A' + hdlc, bcs->mode, mode, hdlc, bc);
bcs->hw.hdlc.ctrl.ctrl = 0;
switch (mode) {
case (-1): /* used for init */
bcs->mode = 1;
bcs->channel = bc;
bc = 0;
case (L1_MODE_NULL):
if (bcs->mode == L1_MODE_NULL)
return;
bcs->hw.hdlc.ctrl.sr.cmd = HDLC_CMD_XRS | HDLC_CMD_RRS;
bcs->hw.hdlc.ctrl.sr.mode = HDLC_MODE_TRANS;
write_ctrl(bcs, 5);
bcs->mode = L1_MODE_NULL;
bcs->channel = bc;
break;
case (L1_MODE_TRANS):
bcs->mode = mode;
bcs->channel = bc;
bcs->hw.hdlc.ctrl.sr.cmd = HDLC_CMD_XRS | HDLC_CMD_RRS;
bcs->hw.hdlc.ctrl.sr.mode = HDLC_MODE_TRANS;
write_ctrl(bcs, 5);
bcs->hw.hdlc.ctrl.sr.cmd = HDLC_CMD_XRS;
write_ctrl(bcs, 1);
bcs->hw.hdlc.ctrl.sr.cmd = 0;
schedule_event(bcs, B_XMTBUFREADY);
break;
case (L1_MODE_HDLC):
bcs->mode = mode;
bcs->channel = bc;
bcs->hw.hdlc.ctrl.sr.cmd = HDLC_CMD_XRS | HDLC_CMD_RRS;
bcs->hw.hdlc.ctrl.sr.mode = HDLC_MODE_ITF_FLG;
write_ctrl(bcs, 5);
bcs->hw.hdlc.ctrl.sr.cmd = HDLC_CMD_XRS;
write_ctrl(bcs, 1);
bcs->hw.hdlc.ctrl.sr.cmd = 0;
schedule_event(bcs, B_XMTBUFREADY);
break;
}
}
static inline void
hdlc_empty_fifo(struct BCState *bcs, int count)
{
register u_int *ptr;
u_char *p;
u_char idx = bcs->channel ? AVM_HDLC_2 : AVM_HDLC_1;
int cnt = 0;
struct IsdnCardState *cs = bcs->cs;
if ((cs->debug & L1_DEB_HSCX) && !(cs->debug & L1_DEB_HSCX_FIFO))
debugl1(cs, "hdlc_empty_fifo %d", count);
if (bcs->hw.hdlc.rcvidx + count > HSCX_BUFMAX) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "hdlc_empty_fifo: incoming packet too large");
return;
}
p = bcs->hw.hdlc.rcvbuf + bcs->hw.hdlc.rcvidx;
ptr = (u_int *)p;
bcs->hw.hdlc.rcvidx += count;
if (cs->subtyp == AVM_FRITZ_PCI) {
outl(idx, cs->hw.avm.cfg_reg + 4);
while (cnt < count) {
#ifdef __powerpc__
*ptr++ = in_be32((unsigned *)(cs->hw.avm.isac + _IO_BASE));
#else
*ptr++ = inl(cs->hw.avm.isac);
#endif /* __powerpc__ */
cnt += 4;
}
} else {
outb(idx, cs->hw.avm.cfg_reg + 4);
while (cnt < count) {
*p++ = inb(cs->hw.avm.isac);
cnt++;
}
}
if (cs->debug & L1_DEB_HSCX_FIFO) {
char *t = bcs->blog;
if (cs->subtyp == AVM_FRITZ_PNP)
p = (u_char *) ptr;
t += sprintf(t, "hdlc_empty_fifo %c cnt %d",
bcs->channel ? 'B' : 'A', count);
QuickHex(t, p, count);
debugl1(cs, bcs->blog);
}
}
static inline void
hdlc_fill_fifo(struct BCState *bcs)
{
struct IsdnCardState *cs = bcs->cs;
int count, cnt = 0;
int fifo_size = 32;
u_char *p;
u_int *ptr;
if ((cs->debug & L1_DEB_HSCX) && !(cs->debug & L1_DEB_HSCX_FIFO))
debugl1(cs, "hdlc_fill_fifo");
if (!bcs->tx_skb)
return;
if (bcs->tx_skb->len <= 0)
return;
bcs->hw.hdlc.ctrl.sr.cmd &= ~HDLC_CMD_XME;
if (bcs->tx_skb->len > fifo_size) {
count = fifo_size;
} else {
count = bcs->tx_skb->len;
if (bcs->mode != L1_MODE_TRANS)
bcs->hw.hdlc.ctrl.sr.cmd |= HDLC_CMD_XME;
}
if ((cs->debug & L1_DEB_HSCX) && !(cs->debug & L1_DEB_HSCX_FIFO))
debugl1(cs, "hdlc_fill_fifo %d/%u", count, bcs->tx_skb->len);
p = bcs->tx_skb->data;
ptr = (u_int *)p;
skb_pull(bcs->tx_skb, count);
bcs->tx_cnt -= count;
bcs->hw.hdlc.count += count;
bcs->hw.hdlc.ctrl.sr.xml = ((count == fifo_size) ? 0 : count);
write_ctrl(bcs, 3); /* sets the correct index too */
if (cs->subtyp == AVM_FRITZ_PCI) {
while (cnt < count) {
#ifdef __powerpc__
out_be32((unsigned *)(cs->hw.avm.isac + _IO_BASE), *ptr++);
#else
outl(*ptr++, cs->hw.avm.isac);
#endif /* __powerpc__ */
cnt += 4;
}
} else {
while (cnt < count) {
outb(*p++, cs->hw.avm.isac);
cnt++;
}
}
if (cs->debug & L1_DEB_HSCX_FIFO) {
char *t = bcs->blog;
if (cs->subtyp == AVM_FRITZ_PNP)
p = (u_char *) ptr;
t += sprintf(t, "hdlc_fill_fifo %c cnt %d",
bcs->channel ? 'B' : 'A', count);
QuickHex(t, p, count);
debugl1(cs, bcs->blog);
}
}
static void
HDLC_irq(struct BCState *bcs, u_int stat) {
int len;
struct sk_buff *skb;
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "ch%d stat %#x", bcs->channel, stat);
if (stat & HDLC_INT_RPR) {
if (stat & HDLC_STAT_RDO) {
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "RDO");
else
debugl1(bcs->cs, "ch%d stat %#x", bcs->channel, stat);
bcs->hw.hdlc.ctrl.sr.xml = 0;
bcs->hw.hdlc.ctrl.sr.cmd |= HDLC_CMD_RRS;
write_ctrl(bcs, 1);
bcs->hw.hdlc.ctrl.sr.cmd &= ~HDLC_CMD_RRS;
write_ctrl(bcs, 1);
bcs->hw.hdlc.rcvidx = 0;
} else {
if (!(len = (stat & HDLC_STAT_RML_MASK) >> 8))
len = 32;
hdlc_empty_fifo(bcs, len);
if ((stat & HDLC_STAT_RME) || (bcs->mode == L1_MODE_TRANS)) {
if (((stat & HDLC_STAT_CRCVFRRAB) == HDLC_STAT_CRCVFR) ||
(bcs->mode == L1_MODE_TRANS)) {
if (!(skb = dev_alloc_skb(bcs->hw.hdlc.rcvidx)))
printk(KERN_WARNING "HDLC: receive out of memory\n");
else {
memcpy(skb_put(skb, bcs->hw.hdlc.rcvidx),
bcs->hw.hdlc.rcvbuf, bcs->hw.hdlc.rcvidx);
skb_queue_tail(&bcs->rqueue, skb);
}
bcs->hw.hdlc.rcvidx = 0;
schedule_event(bcs, B_RCVBUFREADY);
} else {
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "invalid frame");
else
debugl1(bcs->cs, "ch%d invalid frame %#x", bcs->channel, stat);
bcs->hw.hdlc.rcvidx = 0;
}
}
}
}
if (stat & HDLC_INT_XDU) {
/* Here we lost an TX interrupt, so
* restart transmitting the whole frame.
*/
if (bcs->tx_skb) {
skb_push(bcs->tx_skb, bcs->hw.hdlc.count);
bcs->tx_cnt += bcs->hw.hdlc.count;
bcs->hw.hdlc.count = 0;
if (bcs->cs->debug & L1_DEB_WARN)
debugl1(bcs->cs, "ch%d XDU", bcs->channel);
} else if (bcs->cs->debug & L1_DEB_WARN)
debugl1(bcs->cs, "ch%d XDU without skb", bcs->channel);
bcs->hw.hdlc.ctrl.sr.xml = 0;
bcs->hw.hdlc.ctrl.sr.cmd |= HDLC_CMD_XRS;
write_ctrl(bcs, 1);
bcs->hw.hdlc.ctrl.sr.cmd &= ~HDLC_CMD_XRS;
write_ctrl(bcs, 1);
hdlc_fill_fifo(bcs);
} else if (stat & HDLC_INT_XPR) {
if (bcs->tx_skb) {
if (bcs->tx_skb->len) {
hdlc_fill_fifo(bcs);
return;
} else {
if (test_bit(FLG_LLI_L1WAKEUP, &bcs->st->lli.flag) &&
(PACKET_NOACK != bcs->tx_skb->pkt_type)) {
u_long flags;
spin_lock_irqsave(&bcs->aclock, flags);
bcs->ackcnt += bcs->hw.hdlc.count;
spin_unlock_irqrestore(&bcs->aclock, flags);
schedule_event(bcs, B_ACKPENDING);
}
dev_kfree_skb_irq(bcs->tx_skb);
bcs->hw.hdlc.count = 0;
bcs->tx_skb = NULL;
}
}
if ((bcs->tx_skb = skb_dequeue(&bcs->squeue))) {
bcs->hw.hdlc.count = 0;
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
hdlc_fill_fifo(bcs);
} else {
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
schedule_event(bcs, B_XMTBUFREADY);
}
}
}
static inline void
HDLC_irq_main(struct IsdnCardState *cs)
{
u_int stat;
struct BCState *bcs;
if (cs->subtyp == AVM_FRITZ_PCI) {
stat = ReadHDLCPCI(cs, 0, HDLC_STATUS);
} else {
stat = ReadHDLCPnP(cs, 0, HDLC_STATUS);
if (stat & HDLC_INT_RPR)
stat |= (ReadHDLCPnP(cs, 0, HDLC_STATUS + 1)) << 8;
}
if (stat & HDLC_INT_MASK) {
if (!(bcs = Sel_BCS(cs, 0))) {
if (cs->debug)
debugl1(cs, "hdlc spurious channel 0 IRQ");
} else
HDLC_irq(bcs, stat);
}
if (cs->subtyp == AVM_FRITZ_PCI) {
stat = ReadHDLCPCI(cs, 1, HDLC_STATUS);
} else {
stat = ReadHDLCPnP(cs, 1, HDLC_STATUS);
if (stat & HDLC_INT_RPR)
stat |= (ReadHDLCPnP(cs, 1, HDLC_STATUS + 1)) << 8;
}
if (stat & HDLC_INT_MASK) {
if (!(bcs = Sel_BCS(cs, 1))) {
if (cs->debug)
debugl1(cs, "hdlc spurious channel 1 IRQ");
} else
HDLC_irq(bcs, stat);
}
}
static void
hdlc_l2l1(struct PStack *st, int pr, void *arg)
{
struct BCState *bcs = st->l1.bcs;
struct sk_buff *skb = arg;
u_long flags;
switch (pr) {
case (PH_DATA | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
skb_queue_tail(&bcs->squeue, skb);
} else {
bcs->tx_skb = skb;
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->hw.hdlc.count = 0;
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | INDICATION):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
printk(KERN_WARNING "hdlc_l2l1: this shouldn't happen\n");
} else {
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->tx_skb = skb;
bcs->hw.hdlc.count = 0;
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | REQUEST):
if (!bcs->tx_skb) {
test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
} else
test_and_set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
case (PH_ACTIVATE | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_set_bit(BC_FLG_ACTIV, &bcs->Flag);
modehdlc(bcs, st->l1.mode, st->l1.bc);
spin_unlock_irqrestore(&bcs->cs->lock, flags);
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | REQUEST):
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | CONFIRM):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_clear_bit(BC_FLG_ACTIV, &bcs->Flag);
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
modehdlc(bcs, 0, st->l1.bc);
spin_unlock_irqrestore(&bcs->cs->lock, flags);
st->l1.l1l2(st, PH_DEACTIVATE | CONFIRM, NULL);
break;
}
}
static void
close_hdlcstate(struct BCState *bcs)
{
modehdlc(bcs, 0, 0);
if (test_and_clear_bit(BC_FLG_INIT, &bcs->Flag)) {
kfree(bcs->hw.hdlc.rcvbuf);
bcs->hw.hdlc.rcvbuf = NULL;
kfree(bcs->blog);
bcs->blog = NULL;
skb_queue_purge(&bcs->rqueue);
skb_queue_purge(&bcs->squeue);
if (bcs->tx_skb) {
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
}
}
}
static int
open_hdlcstate(struct IsdnCardState *cs, struct BCState *bcs)
{
if (!test_and_set_bit(BC_FLG_INIT, &bcs->Flag)) {
if (!(bcs->hw.hdlc.rcvbuf = kmalloc(HSCX_BUFMAX, GFP_ATOMIC))) {
printk(KERN_WARNING
"HiSax: No memory for hdlc.rcvbuf\n");
return (1);
}
if (!(bcs->blog = kmalloc(MAX_BLOG_SPACE, GFP_ATOMIC))) {
printk(KERN_WARNING
"HiSax: No memory for bcs->blog\n");
test_and_clear_bit(BC_FLG_INIT, &bcs->Flag);
kfree(bcs->hw.hdlc.rcvbuf);
bcs->hw.hdlc.rcvbuf = NULL;
return (2);
}
skb_queue_head_init(&bcs->rqueue);
skb_queue_head_init(&bcs->squeue);
}
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->event = 0;
bcs->hw.hdlc.rcvidx = 0;
bcs->tx_cnt = 0;
return (0);
}
static int
setstack_hdlc(struct PStack *st, struct BCState *bcs)
{
bcs->channel = st->l1.bc;
if (open_hdlcstate(st->l1.hardware, bcs))
return (-1);
st->l1.bcs = bcs;
st->l2.l2l1 = hdlc_l2l1;
setstack_manager(st);
bcs->st = st;
setstack_l1_B(st);
return (0);
}
#if 0
void __init
clear_pending_hdlc_ints(struct IsdnCardState *cs)
{
u_int val;
if (cs->subtyp == AVM_FRITZ_PCI) {
val = ReadHDLCPCI(cs, 0, HDLC_STATUS);
debugl1(cs, "HDLC 1 STA %x", val);
val = ReadHDLCPCI(cs, 1, HDLC_STATUS);
debugl1(cs, "HDLC 2 STA %x", val);
} else {
val = ReadHDLCPnP(cs, 0, HDLC_STATUS);
debugl1(cs, "HDLC 1 STA %x", val);
val = ReadHDLCPnP(cs, 0, HDLC_STATUS + 1);
debugl1(cs, "HDLC 1 RML %x", val);
val = ReadHDLCPnP(cs, 0, HDLC_STATUS + 2);
debugl1(cs, "HDLC 1 MODE %x", val);
val = ReadHDLCPnP(cs, 0, HDLC_STATUS + 3);
debugl1(cs, "HDLC 1 VIN %x", val);
val = ReadHDLCPnP(cs, 1, HDLC_STATUS);
debugl1(cs, "HDLC 2 STA %x", val);
val = ReadHDLCPnP(cs, 1, HDLC_STATUS + 1);
debugl1(cs, "HDLC 2 RML %x", val);
val = ReadHDLCPnP(cs, 1, HDLC_STATUS + 2);
debugl1(cs, "HDLC 2 MODE %x", val);
val = ReadHDLCPnP(cs, 1, HDLC_STATUS + 3);
debugl1(cs, "HDLC 2 VIN %x", val);
}
}
#endif /* 0 */
static void
inithdlc(struct IsdnCardState *cs)
{
cs->bcs[0].BC_SetStack = setstack_hdlc;
cs->bcs[1].BC_SetStack = setstack_hdlc;
cs->bcs[0].BC_Close = close_hdlcstate;
cs->bcs[1].BC_Close = close_hdlcstate;
modehdlc(cs->bcs, -1, 0);
modehdlc(cs->bcs + 1, -1, 1);
}
static irqreturn_t
avm_pcipnp_interrupt(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_long flags;
u_char val;
u_char sval;
spin_lock_irqsave(&cs->lock, flags);
sval = inb(cs->hw.avm.cfg_reg + 2);
if ((sval & AVM_STATUS0_IRQ_MASK) == AVM_STATUS0_IRQ_MASK) {
/* possible a shared IRQ reqest */
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_NONE;
}
if (!(sval & AVM_STATUS0_IRQ_ISAC)) {
val = ReadISAC(cs, ISAC_ISTA);
isac_interrupt(cs, val);
}
if (!(sval & AVM_STATUS0_IRQ_HDLC)) {
HDLC_irq_main(cs);
}
WriteISAC(cs, ISAC_MASK, 0xFF);
WriteISAC(cs, ISAC_MASK, 0x0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static void
reset_avmpcipnp(struct IsdnCardState *cs)
{
printk(KERN_INFO "AVM PCI/PnP: reset\n");
outb(AVM_STATUS0_RESET | AVM_STATUS0_DIS_TIMER, cs->hw.avm.cfg_reg + 2);
mdelay(10);
outb(AVM_STATUS0_DIS_TIMER | AVM_STATUS0_RES_TIMER | AVM_STATUS0_ENA_IRQ, cs->hw.avm.cfg_reg + 2);
outb(AVM_STATUS1_ENA_IOM | cs->irq, cs->hw.avm.cfg_reg + 3);
mdelay(10);
printk(KERN_INFO "AVM PCI/PnP: S1 %x\n", inb(cs->hw.avm.cfg_reg + 3));
}
static int
AVM_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
u_long flags;
switch (mt) {
case CARD_RESET:
spin_lock_irqsave(&cs->lock, flags);
reset_avmpcipnp(cs);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_RELEASE:
outb(0, cs->hw.avm.cfg_reg + 2);
release_region(cs->hw.avm.cfg_reg, 32);
return (0);
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
reset_avmpcipnp(cs);
clear_pending_isac_ints(cs);
initisac(cs);
inithdlc(cs);
outb(AVM_STATUS0_DIS_TIMER | AVM_STATUS0_RES_TIMER,
cs->hw.avm.cfg_reg + 2);
WriteISAC(cs, ISAC_MASK, 0);
outb(AVM_STATUS0_DIS_TIMER | AVM_STATUS0_RES_TIMER |
AVM_STATUS0_ENA_IRQ, cs->hw.avm.cfg_reg + 2);
/* RESET Receiver and Transmitter */
WriteISAC(cs, ISAC_CMDR, 0x41);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_TEST:
return (0);
}
return (0);
}
static int avm_setup_rest(struct IsdnCardState *cs)
{
u_int val, ver;
cs->hw.avm.isac = cs->hw.avm.cfg_reg + 0x10;
if (!request_region(cs->hw.avm.cfg_reg, 32,
(cs->subtyp == AVM_FRITZ_PCI) ? "avm PCI" : "avm PnP")) {
printk(KERN_WARNING
"HiSax: Fritz!PCI/PNP config port %x-%x already in use\n",
cs->hw.avm.cfg_reg,
cs->hw.avm.cfg_reg + 31);
return (0);
}
switch (cs->subtyp) {
case AVM_FRITZ_PCI:
val = inl(cs->hw.avm.cfg_reg);
printk(KERN_INFO "AVM PCI: stat %#x\n", val);
printk(KERN_INFO "AVM PCI: Class %X Rev %d\n",
val & 0xff, (val >> 8) & 0xff);
cs->BC_Read_Reg = &ReadHDLC_s;
cs->BC_Write_Reg = &WriteHDLC_s;
break;
case AVM_FRITZ_PNP:
val = inb(cs->hw.avm.cfg_reg);
ver = inb(cs->hw.avm.cfg_reg + 1);
printk(KERN_INFO "AVM PnP: Class %X Rev %d\n", val, ver);
cs->BC_Read_Reg = &ReadHDLCPnP;
cs->BC_Write_Reg = &WriteHDLCPnP;
break;
default:
printk(KERN_WARNING "AVM unknown subtype %d\n", cs->subtyp);
return (0);
}
printk(KERN_INFO "HiSax: %s config irq:%d base:0x%X\n",
(cs->subtyp == AVM_FRITZ_PCI) ? "AVM Fritz!PCI" : "AVM Fritz!PnP",
cs->irq, cs->hw.avm.cfg_reg);
setup_isac(cs);
cs->readisac = &ReadISAC;
cs->writeisac = &WriteISAC;
cs->readisacfifo = &ReadISACfifo;
cs->writeisacfifo = &WriteISACfifo;
cs->BC_Send_Data = &hdlc_fill_fifo;
cs->cardmsg = &AVM_card_msg;
cs->irq_func = &avm_pcipnp_interrupt;
cs->writeisac(cs, ISAC_MASK, 0xFF);
ISACVersion(cs, (cs->subtyp == AVM_FRITZ_PCI) ? "AVM PCI:" : "AVM PnP:");
return (1);
}
#ifndef __ISAPNP__
static int avm_pnp_setup(struct IsdnCardState *cs)
{
return (1); /* no-op: success */
}
#else
static struct pnp_card *pnp_avm_c = NULL;
static int avm_pnp_setup(struct IsdnCardState *cs)
{
struct pnp_dev *pnp_avm_d = NULL;
if (!isapnp_present())
return (1); /* no-op: success */
if ((pnp_avm_c = pnp_find_card(
ISAPNP_VENDOR('A', 'V', 'M'),
ISAPNP_FUNCTION(0x0900), pnp_avm_c))) {
if ((pnp_avm_d = pnp_find_dev(pnp_avm_c,
ISAPNP_VENDOR('A', 'V', 'M'),
ISAPNP_FUNCTION(0x0900), pnp_avm_d))) {
int err;
pnp_disable_dev(pnp_avm_d);
err = pnp_activate_dev(pnp_avm_d);
if (err < 0) {
printk(KERN_WARNING "%s: pnp_activate_dev ret(%d)\n",
__func__, err);
return (0);
}
cs->hw.avm.cfg_reg =
pnp_port_start(pnp_avm_d, 0);
cs->irq = pnp_irq(pnp_avm_d, 0);
if (!cs->irq) {
printk(KERN_ERR "FritzPnP:No IRQ\n");
return (0);
}
if (!cs->hw.avm.cfg_reg) {
printk(KERN_ERR "FritzPnP:No IO address\n");
return (0);
}
cs->subtyp = AVM_FRITZ_PNP;
return (2); /* goto 'ready' label */
}
}
return (1);
}
#endif /* __ISAPNP__ */
#ifndef CONFIG_PCI
static int avm_pci_setup(struct IsdnCardState *cs)
{
return (1); /* no-op: success */
}
#else
static struct pci_dev *dev_avm = NULL;
static int avm_pci_setup(struct IsdnCardState *cs)
{
if ((dev_avm = hisax_find_pci_device(PCI_VENDOR_ID_AVM,
PCI_DEVICE_ID_AVM_A1, dev_avm))) {
if (pci_enable_device(dev_avm))
return (0);
cs->irq = dev_avm->irq;
if (!cs->irq) {
printk(KERN_ERR "FritzPCI: No IRQ for PCI card found\n");
return (0);
}
cs->hw.avm.cfg_reg = pci_resource_start(dev_avm, 1);
if (!cs->hw.avm.cfg_reg) {
printk(KERN_ERR "FritzPCI: No IO-Adr for PCI card found\n");
return (0);
}
cs->subtyp = AVM_FRITZ_PCI;
} else {
printk(KERN_WARNING "FritzPCI: No PCI card found\n");
return (0);
}
cs->irq_flags |= IRQF_SHARED;
return (1);
}
#endif /* CONFIG_PCI */
int setup_avm_pcipnp(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
char tmp[64];
int rc;
strcpy(tmp, avm_pci_rev);
printk(KERN_INFO "HiSax: AVM PCI driver Rev. %s\n", HiSax_getrev(tmp));
if (cs->typ != ISDN_CTYPE_FRITZPCI)
return (0);
if (card->para[1]) {
/* old manual method */
cs->hw.avm.cfg_reg = card->para[1];
cs->irq = card->para[0];
cs->subtyp = AVM_FRITZ_PNP;
goto ready;
}
rc = avm_pnp_setup(cs);
if (rc < 1)
return (0);
if (rc == 2)
goto ready;
rc = avm_pci_setup(cs);
if (rc < 1)
return (0);
ready:
return avm_setup_rest(cs);
}
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE500CL | linux/kernel/drivers/net/wireless/p54/main.c | 2314 | 21614 | /*
* mac80211 glue code for mac80211 Prism54 drivers
*
* Copyright (c) 2006, Michael Wu <flamingice@sourmilk.net>
* Copyright (c) 2007-2009, Christian Lamparter <chunkeey@web.de>
* Copyright 2008, Johannes Berg <johannes@sipsolutions.net>
*
* Based on:
* - the islsm (softmac prism54) driver, which is:
* Copyright 2004-2006 Jean-Baptiste Note <jbnote@gmail.com>, et al.
* - stlc45xx driver
* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
*
* 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/slab.h>
#include <linux/firmware.h>
#include <linux/etherdevice.h>
#include <linux/module.h>
#include <net/mac80211.h>
#include "p54.h"
#include "lmac.h"
static bool modparam_nohwcrypt;
module_param_named(nohwcrypt, modparam_nohwcrypt, bool, S_IRUGO);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
MODULE_AUTHOR("Michael Wu <flamingice@sourmilk.net>");
MODULE_DESCRIPTION("Softmac Prism54 common code");
MODULE_LICENSE("GPL");
MODULE_ALIAS("prism54common");
static int p54_sta_add_remove(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct p54_common *priv = hw->priv;
/*
* Notify the firmware that we don't want or we don't
* need to buffer frames for this station anymore.
*/
p54_sta_unlock(priv, sta->addr);
return 0;
}
static void p54_sta_notify(struct ieee80211_hw *dev, struct ieee80211_vif *vif,
enum sta_notify_cmd notify_cmd,
struct ieee80211_sta *sta)
{
struct p54_common *priv = dev->priv;
switch (notify_cmd) {
case STA_NOTIFY_AWAKE:
/* update the firmware's filter table */
p54_sta_unlock(priv, sta->addr);
break;
default:
break;
}
}
static int p54_set_tim(struct ieee80211_hw *dev, struct ieee80211_sta *sta,
bool set)
{
struct p54_common *priv = dev->priv;
return p54_update_beacon_tim(priv, sta->aid, set);
}
u8 *p54_find_ie(struct sk_buff *skb, u8 ie)
{
struct ieee80211_mgmt *mgmt = (void *)skb->data;
u8 *pos, *end;
if (skb->len <= sizeof(mgmt))
return NULL;
pos = (u8 *)mgmt->u.beacon.variable;
end = skb->data + skb->len;
while (pos < end) {
if (pos + 2 + pos[1] > end)
return NULL;
if (pos[0] == ie)
return pos;
pos += 2 + pos[1];
}
return NULL;
}
static int p54_beacon_format_ie_tim(struct sk_buff *skb)
{
/*
* the good excuse for this mess is ... the firmware.
* The dummy TIM MUST be at the end of the beacon frame,
* because it'll be overwritten!
*/
u8 *tim;
u8 dtim_len;
u8 dtim_period;
u8 *next;
tim = p54_find_ie(skb, WLAN_EID_TIM);
if (!tim)
return 0;
dtim_len = tim[1];
dtim_period = tim[3];
next = tim + 2 + dtim_len;
if (dtim_len < 3)
return -EINVAL;
memmove(tim, next, skb_tail_pointer(skb) - next);
tim = skb_tail_pointer(skb) - (dtim_len + 2);
/* add the dummy at the end */
tim[0] = WLAN_EID_TIM;
tim[1] = 3;
tim[2] = 0;
tim[3] = dtim_period;
tim[4] = 0;
if (dtim_len > 3)
skb_trim(skb, skb->len - (dtim_len - 3));
return 0;
}
static int p54_beacon_update(struct p54_common *priv,
struct ieee80211_vif *vif)
{
struct ieee80211_tx_control control = { };
struct sk_buff *beacon;
int ret;
beacon = ieee80211_beacon_get(priv->hw, vif);
if (!beacon)
return -ENOMEM;
ret = p54_beacon_format_ie_tim(beacon);
if (ret)
return ret;
/*
* During operation, the firmware takes care of beaconing.
* The driver only needs to upload a new beacon template, once
* the template was changed by the stack or userspace.
*
* LMAC API 3.2.2 also specifies that the driver does not need
* to cancel the old beacon template by hand, instead the firmware
* will release the previous one through the feedback mechanism.
*/
p54_tx_80211(priv->hw, &control, beacon);
priv->tsf_high32 = 0;
priv->tsf_low32 = 0;
return 0;
}
static int p54_start(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
int err;
mutex_lock(&priv->conf_mutex);
err = priv->open(dev);
if (err)
goto out;
P54_SET_QUEUE(priv->qos_params[0], 0x0002, 0x0003, 0x0007, 47);
P54_SET_QUEUE(priv->qos_params[1], 0x0002, 0x0007, 0x000f, 94);
P54_SET_QUEUE(priv->qos_params[2], 0x0003, 0x000f, 0x03ff, 0);
P54_SET_QUEUE(priv->qos_params[3], 0x0007, 0x000f, 0x03ff, 0);
err = p54_set_edcf(priv);
if (err)
goto out;
memset(priv->bssid, ~0, ETH_ALEN);
priv->mode = NL80211_IFTYPE_MONITOR;
err = p54_setup_mac(priv);
if (err) {
priv->mode = NL80211_IFTYPE_UNSPECIFIED;
goto out;
}
ieee80211_queue_delayed_work(dev, &priv->work, 0);
priv->softled_state = 0;
err = p54_set_leds(priv);
out:
mutex_unlock(&priv->conf_mutex);
return err;
}
static void p54_stop(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
int i;
priv->mode = NL80211_IFTYPE_UNSPECIFIED;
priv->softled_state = 0;
cancel_delayed_work_sync(&priv->work);
mutex_lock(&priv->conf_mutex);
p54_set_leds(priv);
priv->stop(dev);
skb_queue_purge(&priv->tx_pending);
skb_queue_purge(&priv->tx_queue);
for (i = 0; i < P54_QUEUE_NUM; i++) {
priv->tx_stats[i].count = 0;
priv->tx_stats[i].len = 0;
}
priv->beacon_req_id = cpu_to_le32(0);
priv->tsf_high32 = priv->tsf_low32 = 0;
mutex_unlock(&priv->conf_mutex);
}
static int p54_add_interface(struct ieee80211_hw *dev,
struct ieee80211_vif *vif)
{
struct p54_common *priv = dev->priv;
int err;
vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER;
mutex_lock(&priv->conf_mutex);
if (priv->mode != NL80211_IFTYPE_MONITOR) {
mutex_unlock(&priv->conf_mutex);
return -EOPNOTSUPP;
}
priv->vif = vif;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_MESH_POINT:
priv->mode = vif->type;
break;
default:
mutex_unlock(&priv->conf_mutex);
return -EOPNOTSUPP;
}
memcpy(priv->mac_addr, vif->addr, ETH_ALEN);
err = p54_setup_mac(priv);
mutex_unlock(&priv->conf_mutex);
return err;
}
static void p54_remove_interface(struct ieee80211_hw *dev,
struct ieee80211_vif *vif)
{
struct p54_common *priv = dev->priv;
mutex_lock(&priv->conf_mutex);
priv->vif = NULL;
/*
* LMAC API 3.2.2 states that any active beacon template must be
* canceled by the driver before attempting a mode transition.
*/
if (le32_to_cpu(priv->beacon_req_id) != 0) {
p54_tx_cancel(priv, priv->beacon_req_id);
wait_for_completion_interruptible_timeout(&priv->beacon_comp, HZ);
}
priv->mode = NL80211_IFTYPE_MONITOR;
memset(priv->mac_addr, 0, ETH_ALEN);
memset(priv->bssid, 0, ETH_ALEN);
p54_setup_mac(priv);
mutex_unlock(&priv->conf_mutex);
}
static int p54_wait_for_stats(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
int ret;
priv->update_stats = true;
ret = p54_fetch_statistics(priv);
if (ret)
return ret;
ret = wait_for_completion_interruptible_timeout(&priv->stat_comp, HZ);
if (ret == 0)
return -ETIMEDOUT;
return 0;
}
static void p54_reset_stats(struct p54_common *priv)
{
struct ieee80211_channel *chan = priv->curchan;
if (chan) {
struct survey_info *info = &priv->survey[chan->hw_value];
/* only reset channel statistics, don't touch .filled, etc. */
info->channel_time = 0;
info->channel_time_busy = 0;
info->channel_time_tx = 0;
}
priv->update_stats = true;
priv->survey_raw.active = 0;
priv->survey_raw.cca = 0;
priv->survey_raw.tx = 0;
}
static int p54_config(struct ieee80211_hw *dev, u32 changed)
{
int ret = 0;
struct p54_common *priv = dev->priv;
struct ieee80211_conf *conf = &dev->conf;
mutex_lock(&priv->conf_mutex);
if (changed & IEEE80211_CONF_CHANGE_POWER)
priv->output_power = conf->power_level << 2;
if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
struct ieee80211_channel *oldchan;
WARN_ON(p54_wait_for_stats(dev));
oldchan = priv->curchan;
priv->curchan = NULL;
ret = p54_scan(priv, P54_SCAN_EXIT, 0);
if (ret) {
priv->curchan = oldchan;
goto out;
}
/*
* TODO: Use the LM_SCAN_TRAP to determine the current
* operating channel.
*/
priv->curchan = priv->hw->conf.chandef.chan;
p54_reset_stats(priv);
WARN_ON(p54_fetch_statistics(priv));
}
if (changed & IEEE80211_CONF_CHANGE_PS) {
WARN_ON(p54_wait_for_stats(dev));
ret = p54_set_ps(priv);
if (ret)
goto out;
WARN_ON(p54_wait_for_stats(dev));
}
if (changed & IEEE80211_CONF_CHANGE_IDLE) {
WARN_ON(p54_wait_for_stats(dev));
ret = p54_setup_mac(priv);
if (ret)
goto out;
WARN_ON(p54_wait_for_stats(dev));
}
out:
mutex_unlock(&priv->conf_mutex);
return ret;
}
static u64 p54_prepare_multicast(struct ieee80211_hw *dev,
struct netdev_hw_addr_list *mc_list)
{
struct p54_common *priv = dev->priv;
struct netdev_hw_addr *ha;
int i;
BUILD_BUG_ON(ARRAY_SIZE(priv->mc_maclist) !=
ARRAY_SIZE(((struct p54_group_address_table *)NULL)->mac_list));
/*
* The first entry is reserved for the global broadcast MAC.
* Otherwise the firmware will drop it and ARP will no longer work.
*/
i = 1;
priv->mc_maclist_num = netdev_hw_addr_list_count(mc_list) + i;
netdev_hw_addr_list_for_each(ha, mc_list) {
memcpy(&priv->mc_maclist[i], ha->addr, ETH_ALEN);
i++;
if (i >= ARRAY_SIZE(priv->mc_maclist))
break;
}
return 1; /* update */
}
static void p54_configure_filter(struct ieee80211_hw *dev,
unsigned int changed_flags,
unsigned int *total_flags,
u64 multicast)
{
struct p54_common *priv = dev->priv;
*total_flags &= FIF_PROMISC_IN_BSS |
FIF_ALLMULTI |
FIF_OTHER_BSS;
priv->filter_flags = *total_flags;
if (changed_flags & (FIF_PROMISC_IN_BSS | FIF_OTHER_BSS))
p54_setup_mac(priv);
if (changed_flags & FIF_ALLMULTI || multicast)
p54_set_groupfilter(priv);
}
static int p54_conf_tx(struct ieee80211_hw *dev,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *params)
{
struct p54_common *priv = dev->priv;
int ret;
mutex_lock(&priv->conf_mutex);
if (queue < dev->queues) {
P54_SET_QUEUE(priv->qos_params[queue], params->aifs,
params->cw_min, params->cw_max, params->txop);
ret = p54_set_edcf(priv);
} else
ret = -EINVAL;
mutex_unlock(&priv->conf_mutex);
return ret;
}
static void p54_work(struct work_struct *work)
{
struct p54_common *priv = container_of(work, struct p54_common,
work.work);
if (unlikely(priv->mode == NL80211_IFTYPE_UNSPECIFIED))
return ;
/*
* TODO: walk through tx_queue and do the following tasks
* 1. initiate bursts.
* 2. cancel stuck frames / reset the device if necessary.
*/
mutex_lock(&priv->conf_mutex);
WARN_ON_ONCE(p54_fetch_statistics(priv));
mutex_unlock(&priv->conf_mutex);
}
static int p54_get_stats(struct ieee80211_hw *dev,
struct ieee80211_low_level_stats *stats)
{
struct p54_common *priv = dev->priv;
memcpy(stats, &priv->stats, sizeof(*stats));
return 0;
}
static void p54_bss_info_changed(struct ieee80211_hw *dev,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *info,
u32 changed)
{
struct p54_common *priv = dev->priv;
mutex_lock(&priv->conf_mutex);
if (changed & BSS_CHANGED_BSSID) {
memcpy(priv->bssid, info->bssid, ETH_ALEN);
p54_setup_mac(priv);
}
if (changed & BSS_CHANGED_BEACON) {
p54_scan(priv, P54_SCAN_EXIT, 0);
p54_setup_mac(priv);
p54_beacon_update(priv, vif);
p54_set_edcf(priv);
}
if (changed & (BSS_CHANGED_ERP_SLOT | BSS_CHANGED_BEACON)) {
priv->use_short_slot = info->use_short_slot;
p54_set_edcf(priv);
}
if (changed & BSS_CHANGED_BASIC_RATES) {
if (dev->conf.chandef.chan->band == IEEE80211_BAND_5GHZ)
priv->basic_rate_mask = (info->basic_rates << 4);
else
priv->basic_rate_mask = info->basic_rates;
p54_setup_mac(priv);
if (priv->fw_var >= 0x500)
p54_scan(priv, P54_SCAN_EXIT, 0);
}
if (changed & BSS_CHANGED_ASSOC) {
if (info->assoc) {
priv->aid = info->aid;
priv->wakeup_timer = info->beacon_int *
info->dtim_period * 5;
p54_setup_mac(priv);
} else {
priv->wakeup_timer = 500;
priv->aid = 0;
}
}
mutex_unlock(&priv->conf_mutex);
}
static int p54_set_key(struct ieee80211_hw *dev, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct p54_common *priv = dev->priv;
int slot, ret = 0;
u8 algo = 0;
u8 *addr = NULL;
if (modparam_nohwcrypt)
return -EOPNOTSUPP;
if (key->flags & IEEE80211_KEY_FLAG_RX_MGMT) {
/*
* Unfortunately most/all firmwares are trying to decrypt
* incoming management frames if a suitable key can be found.
* However, in doing so the data in these frames gets
* corrupted. So, we can't have firmware supported crypto
* offload in this case.
*/
return -EOPNOTSUPP;
}
mutex_lock(&priv->conf_mutex);
if (cmd == SET_KEY) {
switch (key->cipher) {
case WLAN_CIPHER_SUITE_TKIP:
if (!(priv->privacy_caps & (BR_DESC_PRIV_CAP_MICHAEL |
BR_DESC_PRIV_CAP_TKIP))) {
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
algo = P54_CRYPTO_TKIPMICHAEL;
break;
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
if (!(priv->privacy_caps & BR_DESC_PRIV_CAP_WEP)) {
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
algo = P54_CRYPTO_WEP;
break;
case WLAN_CIPHER_SUITE_CCMP:
if (!(priv->privacy_caps & BR_DESC_PRIV_CAP_AESCCMP)) {
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
algo = P54_CRYPTO_AESCCMP;
break;
default:
ret = -EOPNOTSUPP;
goto out_unlock;
}
slot = bitmap_find_free_region(priv->used_rxkeys,
priv->rx_keycache_size, 0);
if (slot < 0) {
/*
* The device supports the chosen algorithm, but the
* firmware does not provide enough key slots to store
* all of them.
* But encryption offload for outgoing frames is always
* possible, so we just pretend that the upload was
* successful and do the decryption in software.
*/
/* mark the key as invalid. */
key->hw_key_idx = 0xff;
goto out_unlock;
}
} else {
slot = key->hw_key_idx;
if (slot == 0xff) {
/* This key was not uploaded into the rx key cache. */
goto out_unlock;
}
bitmap_release_region(priv->used_rxkeys, slot, 0);
algo = 0;
}
if (sta)
addr = sta->addr;
ret = p54_upload_key(priv, algo, slot, key->keyidx,
key->keylen, addr, key->key);
if (ret) {
bitmap_release_region(priv->used_rxkeys, slot, 0);
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->hw_key_idx = slot;
out_unlock:
mutex_unlock(&priv->conf_mutex);
return ret;
}
static int p54_get_survey(struct ieee80211_hw *dev, int idx,
struct survey_info *survey)
{
struct p54_common *priv = dev->priv;
struct ieee80211_channel *chan;
int err, tries;
bool in_use = false;
if (idx >= priv->chan_num)
return -ENOENT;
#define MAX_TRIES 1
for (tries = 0; tries < MAX_TRIES; tries++) {
chan = priv->curchan;
if (chan && chan->hw_value == idx) {
mutex_lock(&priv->conf_mutex);
err = p54_wait_for_stats(dev);
mutex_unlock(&priv->conf_mutex);
if (err)
return err;
in_use = true;
}
memcpy(survey, &priv->survey[idx], sizeof(*survey));
if (in_use) {
/* test if the reported statistics are valid. */
if (survey->channel_time != 0) {
survey->filled |= SURVEY_INFO_IN_USE;
} else {
/*
* hw/fw has not accumulated enough sample sets.
* Wait for 100ms, this ought to be enough to
* to get at least one non-null set of channel
* usage statistics.
*/
msleep(100);
continue;
}
}
return 0;
}
return -ETIMEDOUT;
#undef MAX_TRIES
}
static unsigned int p54_flush_count(struct p54_common *priv)
{
unsigned int total = 0, i;
BUILD_BUG_ON(P54_QUEUE_NUM > ARRAY_SIZE(priv->tx_stats));
/*
* Because the firmware has the sole control over any frames
* in the P54_QUEUE_BEACON or P54_QUEUE_SCAN queues, they
* don't really count as pending or active.
*/
for (i = P54_QUEUE_MGMT; i < P54_QUEUE_NUM; i++)
total += priv->tx_stats[i].len;
return total;
}
static void p54_flush(struct ieee80211_hw *dev, u32 queues, bool drop)
{
struct p54_common *priv = dev->priv;
unsigned int total, i;
/*
* Currently, it wouldn't really matter if we wait for one second
* or 15 minutes. But once someone gets around and completes the
* TODOs [ancel stuck frames / reset device] in p54_work, it will
* suddenly make sense to wait that long.
*/
i = P54_STATISTICS_UPDATE * 2 / 20;
/*
* In this case no locking is required because as we speak the
* queues have already been stopped and no new frames can sneak
* up from behind.
*/
while ((total = p54_flush_count(priv) && i--)) {
/* waste time */
msleep(20);
}
WARN(total, "tx flush timeout, unresponsive firmware");
}
static void p54_set_coverage_class(struct ieee80211_hw *dev, u8 coverage_class)
{
struct p54_common *priv = dev->priv;
mutex_lock(&priv->conf_mutex);
/* support all coverage class values as in 802.11-2007 Table 7-27 */
priv->coverage_class = clamp_t(u8, coverage_class, 0, 31);
p54_set_edcf(priv);
mutex_unlock(&priv->conf_mutex);
}
static const struct ieee80211_ops p54_ops = {
.tx = p54_tx_80211,
.start = p54_start,
.stop = p54_stop,
.add_interface = p54_add_interface,
.remove_interface = p54_remove_interface,
.set_tim = p54_set_tim,
.sta_notify = p54_sta_notify,
.sta_add = p54_sta_add_remove,
.sta_remove = p54_sta_add_remove,
.set_key = p54_set_key,
.config = p54_config,
.flush = p54_flush,
.bss_info_changed = p54_bss_info_changed,
.prepare_multicast = p54_prepare_multicast,
.configure_filter = p54_configure_filter,
.conf_tx = p54_conf_tx,
.get_stats = p54_get_stats,
.get_survey = p54_get_survey,
.set_coverage_class = p54_set_coverage_class,
};
struct ieee80211_hw *p54_init_common(size_t priv_data_len)
{
struct ieee80211_hw *dev;
struct p54_common *priv;
dev = ieee80211_alloc_hw(priv_data_len, &p54_ops);
if (!dev)
return NULL;
priv = dev->priv;
priv->hw = dev;
priv->mode = NL80211_IFTYPE_UNSPECIFIED;
priv->basic_rate_mask = 0x15f;
spin_lock_init(&priv->tx_stats_lock);
skb_queue_head_init(&priv->tx_queue);
skb_queue_head_init(&priv->tx_pending);
dev->flags = IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_PS_NULLFUNC_STACK |
IEEE80211_HW_MFP_CAPABLE |
IEEE80211_HW_REPORTS_TX_ACK_STATUS;
dev->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_MESH_POINT);
dev->channel_change_time = 1000; /* TODO: find actual value */
priv->beacon_req_id = cpu_to_le32(0);
priv->tx_stats[P54_QUEUE_BEACON].limit = 1;
priv->tx_stats[P54_QUEUE_FWSCAN].limit = 1;
priv->tx_stats[P54_QUEUE_MGMT].limit = 3;
priv->tx_stats[P54_QUEUE_CAB].limit = 3;
priv->tx_stats[P54_QUEUE_DATA].limit = 5;
dev->queues = 1;
priv->noise = -94;
/*
* We support at most 8 tries no matter which rate they're at,
* we cannot support max_rates * max_rate_tries as we set it
* here, but setting it correctly to 4/2 or so would limit us
* artificially if the RC algorithm wants just two rates, so
* let's say 4/7, we'll redistribute it at TX time, see the
* comments there.
*/
dev->max_rates = 4;
dev->max_rate_tries = 7;
dev->extra_tx_headroom = sizeof(struct p54_hdr) + 4 +
sizeof(struct p54_tx_data);
/*
* For now, disable PS by default because it affects
* link stability significantly.
*/
dev->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
mutex_init(&priv->conf_mutex);
mutex_init(&priv->eeprom_mutex);
init_completion(&priv->stat_comp);
init_completion(&priv->eeprom_comp);
init_completion(&priv->beacon_comp);
INIT_DELAYED_WORK(&priv->work, p54_work);
memset(&priv->mc_maclist[0], ~0, ETH_ALEN);
priv->curchan = NULL;
p54_reset_stats(priv);
return dev;
}
EXPORT_SYMBOL_GPL(p54_init_common);
int p54_register_common(struct ieee80211_hw *dev, struct device *pdev)
{
struct p54_common __maybe_unused *priv = dev->priv;
int err;
err = ieee80211_register_hw(dev);
if (err) {
dev_err(pdev, "Cannot register device (%d).\n", err);
return err;
}
priv->registered = true;
#ifdef CONFIG_P54_LEDS
err = p54_init_leds(priv);
if (err) {
p54_unregister_common(dev);
return err;
}
#endif /* CONFIG_P54_LEDS */
dev_info(pdev, "is registered as '%s'\n", wiphy_name(dev->wiphy));
return 0;
}
EXPORT_SYMBOL_GPL(p54_register_common);
void p54_free_common(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
unsigned int i;
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
kfree(priv->band_table[i]);
kfree(priv->iq_autocal);
kfree(priv->output_limit);
kfree(priv->curve_data);
kfree(priv->rssi_db);
kfree(priv->used_rxkeys);
kfree(priv->survey);
priv->iq_autocal = NULL;
priv->output_limit = NULL;
priv->curve_data = NULL;
priv->rssi_db = NULL;
priv->used_rxkeys = NULL;
priv->survey = NULL;
ieee80211_free_hw(dev);
}
EXPORT_SYMBOL_GPL(p54_free_common);
void p54_unregister_common(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
#ifdef CONFIG_P54_LEDS
p54_unregister_leds(priv);
#endif /* CONFIG_P54_LEDS */
if (priv->registered) {
priv->registered = false;
ieee80211_unregister_hw(dev);
}
mutex_destroy(&priv->conf_mutex);
mutex_destroy(&priv->eeprom_mutex);
}
EXPORT_SYMBOL_GPL(p54_unregister_common);
| gpl-2.0 |
elp/iwlwifi | sound/usb/caiaq/midi.c | 4362 | 4529 | /*
* Copyright (c) 2006,2007 Daniel Mack
*
* 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/device.h>
#include <linux/usb.h>
#include <linux/gfp.h>
#include <sound/rawmidi.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include "device.h"
#include "midi.h"
static int snd_usb_caiaq_midi_input_open(struct snd_rawmidi_substream *substream)
{
return 0;
}
static int snd_usb_caiaq_midi_input_close(struct snd_rawmidi_substream *substream)
{
return 0;
}
static void snd_usb_caiaq_midi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
struct snd_usb_caiaqdev *cdev = substream->rmidi->private_data;
if (!cdev)
return;
cdev->midi_receive_substream = up ? substream : NULL;
}
static int snd_usb_caiaq_midi_output_open(struct snd_rawmidi_substream *substream)
{
return 0;
}
static int snd_usb_caiaq_midi_output_close(struct snd_rawmidi_substream *substream)
{
struct snd_usb_caiaqdev *cdev = substream->rmidi->private_data;
if (cdev->midi_out_active) {
usb_kill_urb(&cdev->midi_out_urb);
cdev->midi_out_active = 0;
}
return 0;
}
static void snd_usb_caiaq_midi_send(struct snd_usb_caiaqdev *cdev,
struct snd_rawmidi_substream *substream)
{
int len, ret;
struct device *dev = caiaqdev_to_dev(cdev);
cdev->midi_out_buf[0] = EP1_CMD_MIDI_WRITE;
cdev->midi_out_buf[1] = 0; /* port */
len = snd_rawmidi_transmit(substream, cdev->midi_out_buf + 3,
EP1_BUFSIZE - 3);
if (len <= 0)
return;
cdev->midi_out_buf[2] = len;
cdev->midi_out_urb.transfer_buffer_length = len+3;
ret = usb_submit_urb(&cdev->midi_out_urb, GFP_ATOMIC);
if (ret < 0)
dev_err(dev,
"snd_usb_caiaq_midi_send(%p): usb_submit_urb() failed,"
"ret=%d, len=%d\n", substream, ret, len);
else
cdev->midi_out_active = 1;
}
static void snd_usb_caiaq_midi_output_trigger(struct snd_rawmidi_substream *substream, int up)
{
struct snd_usb_caiaqdev *cdev = substream->rmidi->private_data;
if (up) {
cdev->midi_out_substream = substream;
if (!cdev->midi_out_active)
snd_usb_caiaq_midi_send(cdev, substream);
} else {
cdev->midi_out_substream = NULL;
}
}
static struct snd_rawmidi_ops snd_usb_caiaq_midi_output =
{
.open = snd_usb_caiaq_midi_output_open,
.close = snd_usb_caiaq_midi_output_close,
.trigger = snd_usb_caiaq_midi_output_trigger,
};
static struct snd_rawmidi_ops snd_usb_caiaq_midi_input =
{
.open = snd_usb_caiaq_midi_input_open,
.close = snd_usb_caiaq_midi_input_close,
.trigger = snd_usb_caiaq_midi_input_trigger,
};
void snd_usb_caiaq_midi_handle_input(struct snd_usb_caiaqdev *cdev,
int port, const char *buf, int len)
{
if (!cdev->midi_receive_substream)
return;
snd_rawmidi_receive(cdev->midi_receive_substream, buf, len);
}
int snd_usb_caiaq_midi_init(struct snd_usb_caiaqdev *device)
{
int ret;
struct snd_rawmidi *rmidi;
ret = snd_rawmidi_new(device->chip.card, device->product_name, 0,
device->spec.num_midi_out,
device->spec.num_midi_in,
&rmidi);
if (ret < 0)
return ret;
strlcpy(rmidi->name, device->product_name, sizeof(rmidi->name));
rmidi->info_flags = SNDRV_RAWMIDI_INFO_DUPLEX;
rmidi->private_data = device;
if (device->spec.num_midi_out > 0) {
rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT;
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT,
&snd_usb_caiaq_midi_output);
}
if (device->spec.num_midi_in > 0) {
rmidi->info_flags |= SNDRV_RAWMIDI_INFO_INPUT;
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT,
&snd_usb_caiaq_midi_input);
}
device->rmidi = rmidi;
return 0;
}
void snd_usb_caiaq_midi_output_done(struct urb* urb)
{
struct snd_usb_caiaqdev *cdev = urb->context;
cdev->midi_out_active = 0;
if (urb->status != 0)
return;
if (!cdev->midi_out_substream)
return;
snd_usb_caiaq_midi_send(cdev, cdev->midi_out_substream);
}
| gpl-2.0 |
kbc-developers/sc04d_kernel | arch/powerpc/lib/sstep.c | 6666 | 38272 | /*
* Single-step support.
*
* Copyright (C) 2004 Paul Mackerras <paulus@au.ibm.com>, IBM
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/ptrace.h>
#include <linux/prefetch.h>
#include <asm/sstep.h>
#include <asm/processor.h>
#include <asm/uaccess.h>
#include <asm/cputable.h>
extern char system_call_common[];
#ifdef CONFIG_PPC64
/* Bits in SRR1 that are copied from MSR */
#define MSR_MASK 0xffffffff87c0ffffUL
#else
#define MSR_MASK 0x87c0ffff
#endif
/* Bits in XER */
#define XER_SO 0x80000000U
#define XER_OV 0x40000000U
#define XER_CA 0x20000000U
#ifdef CONFIG_PPC_FPU
/*
* Functions in ldstfp.S
*/
extern int do_lfs(int rn, unsigned long ea);
extern int do_lfd(int rn, unsigned long ea);
extern int do_stfs(int rn, unsigned long ea);
extern int do_stfd(int rn, unsigned long ea);
extern int do_lvx(int rn, unsigned long ea);
extern int do_stvx(int rn, unsigned long ea);
extern int do_lxvd2x(int rn, unsigned long ea);
extern int do_stxvd2x(int rn, unsigned long ea);
#endif
/*
* Emulate the truncation of 64 bit values in 32-bit mode.
*/
static unsigned long truncate_if_32bit(unsigned long msr, unsigned long val)
{
#ifdef __powerpc64__
if ((msr & MSR_64BIT) == 0)
val &= 0xffffffffUL;
#endif
return val;
}
/*
* Determine whether a conditional branch instruction would branch.
*/
static int __kprobes branch_taken(unsigned int instr, struct pt_regs *regs)
{
unsigned int bo = (instr >> 21) & 0x1f;
unsigned int bi;
if ((bo & 4) == 0) {
/* decrement counter */
--regs->ctr;
if (((bo >> 1) & 1) ^ (regs->ctr == 0))
return 0;
}
if ((bo & 0x10) == 0) {
/* check bit from CR */
bi = (instr >> 16) & 0x1f;
if (((regs->ccr >> (31 - bi)) & 1) != ((bo >> 3) & 1))
return 0;
}
return 1;
}
static long __kprobes address_ok(struct pt_regs *regs, unsigned long ea, int nb)
{
if (!user_mode(regs))
return 1;
return __access_ok(ea, nb, USER_DS);
}
/*
* Calculate effective address for a D-form instruction
*/
static unsigned long __kprobes dform_ea(unsigned int instr, struct pt_regs *regs)
{
int ra;
unsigned long ea;
ra = (instr >> 16) & 0x1f;
ea = (signed short) instr; /* sign-extend */
if (ra) {
ea += regs->gpr[ra];
if (instr & 0x04000000) /* update forms */
regs->gpr[ra] = ea;
}
return truncate_if_32bit(regs->msr, ea);
}
#ifdef __powerpc64__
/*
* Calculate effective address for a DS-form instruction
*/
static unsigned long __kprobes dsform_ea(unsigned int instr, struct pt_regs *regs)
{
int ra;
unsigned long ea;
ra = (instr >> 16) & 0x1f;
ea = (signed short) (instr & ~3); /* sign-extend */
if (ra) {
ea += regs->gpr[ra];
if ((instr & 3) == 1) /* update forms */
regs->gpr[ra] = ea;
}
return truncate_if_32bit(regs->msr, ea);
}
#endif /* __powerpc64 */
/*
* Calculate effective address for an X-form instruction
*/
static unsigned long __kprobes xform_ea(unsigned int instr, struct pt_regs *regs,
int do_update)
{
int ra, rb;
unsigned long ea;
ra = (instr >> 16) & 0x1f;
rb = (instr >> 11) & 0x1f;
ea = regs->gpr[rb];
if (ra) {
ea += regs->gpr[ra];
if (do_update) /* update forms */
regs->gpr[ra] = ea;
}
return truncate_if_32bit(regs->msr, ea);
}
/*
* Return the largest power of 2, not greater than sizeof(unsigned long),
* such that x is a multiple of it.
*/
static inline unsigned long max_align(unsigned long x)
{
x |= sizeof(unsigned long);
return x & -x; /* isolates rightmost bit */
}
static inline unsigned long byterev_2(unsigned long x)
{
return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
}
static inline unsigned long byterev_4(unsigned long x)
{
return ((x >> 24) & 0xff) | ((x >> 8) & 0xff00) |
((x & 0xff00) << 8) | ((x & 0xff) << 24);
}
#ifdef __powerpc64__
static inline unsigned long byterev_8(unsigned long x)
{
return (byterev_4(x) << 32) | byterev_4(x >> 32);
}
#endif
static int __kprobes read_mem_aligned(unsigned long *dest, unsigned long ea,
int nb)
{
int err = 0;
unsigned long x = 0;
switch (nb) {
case 1:
err = __get_user(x, (unsigned char __user *) ea);
break;
case 2:
err = __get_user(x, (unsigned short __user *) ea);
break;
case 4:
err = __get_user(x, (unsigned int __user *) ea);
break;
#ifdef __powerpc64__
case 8:
err = __get_user(x, (unsigned long __user *) ea);
break;
#endif
}
if (!err)
*dest = x;
return err;
}
static int __kprobes read_mem_unaligned(unsigned long *dest, unsigned long ea,
int nb, struct pt_regs *regs)
{
int err;
unsigned long x, b, c;
/* unaligned, do this in pieces */
x = 0;
for (; nb > 0; nb -= c) {
c = max_align(ea);
if (c > nb)
c = max_align(nb);
err = read_mem_aligned(&b, ea, c);
if (err)
return err;
x = (x << (8 * c)) + b;
ea += c;
}
*dest = x;
return 0;
}
/*
* Read memory at address ea for nb bytes, return 0 for success
* or -EFAULT if an error occurred.
*/
static int __kprobes read_mem(unsigned long *dest, unsigned long ea, int nb,
struct pt_regs *regs)
{
if (!address_ok(regs, ea, nb))
return -EFAULT;
if ((ea & (nb - 1)) == 0)
return read_mem_aligned(dest, ea, nb);
return read_mem_unaligned(dest, ea, nb, regs);
}
static int __kprobes write_mem_aligned(unsigned long val, unsigned long ea,
int nb)
{
int err = 0;
switch (nb) {
case 1:
err = __put_user(val, (unsigned char __user *) ea);
break;
case 2:
err = __put_user(val, (unsigned short __user *) ea);
break;
case 4:
err = __put_user(val, (unsigned int __user *) ea);
break;
#ifdef __powerpc64__
case 8:
err = __put_user(val, (unsigned long __user *) ea);
break;
#endif
}
return err;
}
static int __kprobes write_mem_unaligned(unsigned long val, unsigned long ea,
int nb, struct pt_regs *regs)
{
int err;
unsigned long c;
/* unaligned or little-endian, do this in pieces */
for (; nb > 0; nb -= c) {
c = max_align(ea);
if (c > nb)
c = max_align(nb);
err = write_mem_aligned(val >> (nb - c) * 8, ea, c);
if (err)
return err;
++ea;
}
return 0;
}
/*
* Write memory at address ea for nb bytes, return 0 for success
* or -EFAULT if an error occurred.
*/
static int __kprobes write_mem(unsigned long val, unsigned long ea, int nb,
struct pt_regs *regs)
{
if (!address_ok(regs, ea, nb))
return -EFAULT;
if ((ea & (nb - 1)) == 0)
return write_mem_aligned(val, ea, nb);
return write_mem_unaligned(val, ea, nb, regs);
}
#ifdef CONFIG_PPC_FPU
/*
* Check the address and alignment, and call func to do the actual
* load or store.
*/
static int __kprobes do_fp_load(int rn, int (*func)(int, unsigned long),
unsigned long ea, int nb,
struct pt_regs *regs)
{
int err;
unsigned long val[sizeof(double) / sizeof(long)];
unsigned long ptr;
if (!address_ok(regs, ea, nb))
return -EFAULT;
if ((ea & 3) == 0)
return (*func)(rn, ea);
ptr = (unsigned long) &val[0];
if (sizeof(unsigned long) == 8 || nb == 4) {
err = read_mem_unaligned(&val[0], ea, nb, regs);
ptr += sizeof(unsigned long) - nb;
} else {
/* reading a double on 32-bit */
err = read_mem_unaligned(&val[0], ea, 4, regs);
if (!err)
err = read_mem_unaligned(&val[1], ea + 4, 4, regs);
}
if (err)
return err;
return (*func)(rn, ptr);
}
static int __kprobes do_fp_store(int rn, int (*func)(int, unsigned long),
unsigned long ea, int nb,
struct pt_regs *regs)
{
int err;
unsigned long val[sizeof(double) / sizeof(long)];
unsigned long ptr;
if (!address_ok(regs, ea, nb))
return -EFAULT;
if ((ea & 3) == 0)
return (*func)(rn, ea);
ptr = (unsigned long) &val[0];
if (sizeof(unsigned long) == 8 || nb == 4) {
ptr += sizeof(unsigned long) - nb;
err = (*func)(rn, ptr);
if (err)
return err;
err = write_mem_unaligned(val[0], ea, nb, regs);
} else {
/* writing a double on 32-bit */
err = (*func)(rn, ptr);
if (err)
return err;
err = write_mem_unaligned(val[0], ea, 4, regs);
if (!err)
err = write_mem_unaligned(val[1], ea + 4, 4, regs);
}
return err;
}
#endif
#ifdef CONFIG_ALTIVEC
/* For Altivec/VMX, no need to worry about alignment */
static int __kprobes do_vec_load(int rn, int (*func)(int, unsigned long),
unsigned long ea, struct pt_regs *regs)
{
if (!address_ok(regs, ea & ~0xfUL, 16))
return -EFAULT;
return (*func)(rn, ea);
}
static int __kprobes do_vec_store(int rn, int (*func)(int, unsigned long),
unsigned long ea, struct pt_regs *regs)
{
if (!address_ok(regs, ea & ~0xfUL, 16))
return -EFAULT;
return (*func)(rn, ea);
}
#endif /* CONFIG_ALTIVEC */
#ifdef CONFIG_VSX
static int __kprobes do_vsx_load(int rn, int (*func)(int, unsigned long),
unsigned long ea, struct pt_regs *regs)
{
int err;
unsigned long val[2];
if (!address_ok(regs, ea, 16))
return -EFAULT;
if ((ea & 3) == 0)
return (*func)(rn, ea);
err = read_mem_unaligned(&val[0], ea, 8, regs);
if (!err)
err = read_mem_unaligned(&val[1], ea + 8, 8, regs);
if (!err)
err = (*func)(rn, (unsigned long) &val[0]);
return err;
}
static int __kprobes do_vsx_store(int rn, int (*func)(int, unsigned long),
unsigned long ea, struct pt_regs *regs)
{
int err;
unsigned long val[2];
if (!address_ok(regs, ea, 16))
return -EFAULT;
if ((ea & 3) == 0)
return (*func)(rn, ea);
err = (*func)(rn, (unsigned long) &val[0]);
if (err)
return err;
err = write_mem_unaligned(val[0], ea, 8, regs);
if (!err)
err = write_mem_unaligned(val[1], ea + 8, 8, regs);
return err;
}
#endif /* CONFIG_VSX */
#define __put_user_asmx(x, addr, err, op, cr) \
__asm__ __volatile__( \
"1: " op " %2,0,%3\n" \
" mfcr %1\n" \
"2:\n" \
".section .fixup,\"ax\"\n" \
"3: li %0,%4\n" \
" b 2b\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
PPC_LONG_ALIGN "\n" \
PPC_LONG "1b,3b\n" \
".previous" \
: "=r" (err), "=r" (cr) \
: "r" (x), "r" (addr), "i" (-EFAULT), "0" (err))
#define __get_user_asmx(x, addr, err, op) \
__asm__ __volatile__( \
"1: "op" %1,0,%2\n" \
"2:\n" \
".section .fixup,\"ax\"\n" \
"3: li %0,%3\n" \
" b 2b\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
PPC_LONG_ALIGN "\n" \
PPC_LONG "1b,3b\n" \
".previous" \
: "=r" (err), "=r" (x) \
: "r" (addr), "i" (-EFAULT), "0" (err))
#define __cacheop_user_asmx(addr, err, op) \
__asm__ __volatile__( \
"1: "op" 0,%1\n" \
"2:\n" \
".section .fixup,\"ax\"\n" \
"3: li %0,%3\n" \
" b 2b\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
PPC_LONG_ALIGN "\n" \
PPC_LONG "1b,3b\n" \
".previous" \
: "=r" (err) \
: "r" (addr), "i" (-EFAULT), "0" (err))
static void __kprobes set_cr0(struct pt_regs *regs, int rd)
{
long val = regs->gpr[rd];
regs->ccr = (regs->ccr & 0x0fffffff) | ((regs->xer >> 3) & 0x10000000);
#ifdef __powerpc64__
if (!(regs->msr & MSR_64BIT))
val = (int) val;
#endif
if (val < 0)
regs->ccr |= 0x80000000;
else if (val > 0)
regs->ccr |= 0x40000000;
else
regs->ccr |= 0x20000000;
}
static void __kprobes add_with_carry(struct pt_regs *regs, int rd,
unsigned long val1, unsigned long val2,
unsigned long carry_in)
{
unsigned long val = val1 + val2;
if (carry_in)
++val;
regs->gpr[rd] = val;
#ifdef __powerpc64__
if (!(regs->msr & MSR_64BIT)) {
val = (unsigned int) val;
val1 = (unsigned int) val1;
}
#endif
if (val < val1 || (carry_in && val == val1))
regs->xer |= XER_CA;
else
regs->xer &= ~XER_CA;
}
static void __kprobes do_cmp_signed(struct pt_regs *regs, long v1, long v2,
int crfld)
{
unsigned int crval, shift;
crval = (regs->xer >> 31) & 1; /* get SO bit */
if (v1 < v2)
crval |= 8;
else if (v1 > v2)
crval |= 4;
else
crval |= 2;
shift = (7 - crfld) * 4;
regs->ccr = (regs->ccr & ~(0xf << shift)) | (crval << shift);
}
static void __kprobes do_cmp_unsigned(struct pt_regs *regs, unsigned long v1,
unsigned long v2, int crfld)
{
unsigned int crval, shift;
crval = (regs->xer >> 31) & 1; /* get SO bit */
if (v1 < v2)
crval |= 8;
else if (v1 > v2)
crval |= 4;
else
crval |= 2;
shift = (7 - crfld) * 4;
regs->ccr = (regs->ccr & ~(0xf << shift)) | (crval << shift);
}
/*
* Elements of 32-bit rotate and mask instructions.
*/
#define MASK32(mb, me) ((0xffffffffUL >> (mb)) + \
((signed long)-0x80000000L >> (me)) + ((me) >= (mb)))
#ifdef __powerpc64__
#define MASK64_L(mb) (~0UL >> (mb))
#define MASK64_R(me) ((signed long)-0x8000000000000000L >> (me))
#define MASK64(mb, me) (MASK64_L(mb) + MASK64_R(me) + ((me) >= (mb)))
#define DATA32(x) (((x) & 0xffffffffUL) | (((x) & 0xffffffffUL) << 32))
#else
#define DATA32(x) (x)
#endif
#define ROTATE(x, n) ((n) ? (((x) << (n)) | ((x) >> (8 * sizeof(long) - (n)))) : (x))
/*
* Emulate instructions that cause a transfer of control,
* loads and stores, and a few other instructions.
* Returns 1 if the step was emulated, 0 if not,
* or -1 if the instruction is one that should not be stepped,
* such as an rfid, or a mtmsrd that would clear MSR_RI.
*/
int __kprobes emulate_step(struct pt_regs *regs, unsigned int instr)
{
unsigned int opcode, ra, rb, rd, spr, u;
unsigned long int imm;
unsigned long int val, val2;
unsigned long int ea;
unsigned int cr, mb, me, sh;
int err;
unsigned long old_ra;
long ival;
opcode = instr >> 26;
switch (opcode) {
case 16: /* bc */
imm = (signed short)(instr & 0xfffc);
if ((instr & 2) == 0)
imm += regs->nip;
regs->nip += 4;
regs->nip = truncate_if_32bit(regs->msr, regs->nip);
if (instr & 1)
regs->link = regs->nip;
if (branch_taken(instr, regs))
regs->nip = imm;
return 1;
#ifdef CONFIG_PPC64
case 17: /* sc */
/*
* N.B. this uses knowledge about how the syscall
* entry code works. If that is changed, this will
* need to be changed also.
*/
if (regs->gpr[0] == 0x1ebe &&
cpu_has_feature(CPU_FTR_REAL_LE)) {
regs->msr ^= MSR_LE;
goto instr_done;
}
regs->gpr[9] = regs->gpr[13];
regs->gpr[10] = MSR_KERNEL;
regs->gpr[11] = regs->nip + 4;
regs->gpr[12] = regs->msr & MSR_MASK;
regs->gpr[13] = (unsigned long) get_paca();
regs->nip = (unsigned long) &system_call_common;
regs->msr = MSR_KERNEL;
return 1;
#endif
case 18: /* b */
imm = instr & 0x03fffffc;
if (imm & 0x02000000)
imm -= 0x04000000;
if ((instr & 2) == 0)
imm += regs->nip;
if (instr & 1)
regs->link = truncate_if_32bit(regs->msr, regs->nip + 4);
imm = truncate_if_32bit(regs->msr, imm);
regs->nip = imm;
return 1;
case 19:
switch ((instr >> 1) & 0x3ff) {
case 16: /* bclr */
case 528: /* bcctr */
imm = (instr & 0x400)? regs->ctr: regs->link;
regs->nip = truncate_if_32bit(regs->msr, regs->nip + 4);
imm = truncate_if_32bit(regs->msr, imm);
if (instr & 1)
regs->link = regs->nip;
if (branch_taken(instr, regs))
regs->nip = imm;
return 1;
case 18: /* rfid, scary */
return -1;
case 150: /* isync */
isync();
goto instr_done;
case 33: /* crnor */
case 129: /* crandc */
case 193: /* crxor */
case 225: /* crnand */
case 257: /* crand */
case 289: /* creqv */
case 417: /* crorc */
case 449: /* cror */
ra = (instr >> 16) & 0x1f;
rb = (instr >> 11) & 0x1f;
rd = (instr >> 21) & 0x1f;
ra = (regs->ccr >> (31 - ra)) & 1;
rb = (regs->ccr >> (31 - rb)) & 1;
val = (instr >> (6 + ra * 2 + rb)) & 1;
regs->ccr = (regs->ccr & ~(1UL << (31 - rd))) |
(val << (31 - rd));
goto instr_done;
}
break;
case 31:
switch ((instr >> 1) & 0x3ff) {
case 598: /* sync */
#ifdef __powerpc64__
switch ((instr >> 21) & 3) {
case 1: /* lwsync */
asm volatile("lwsync" : : : "memory");
goto instr_done;
case 2: /* ptesync */
asm volatile("ptesync" : : : "memory");
goto instr_done;
}
#endif
mb();
goto instr_done;
case 854: /* eieio */
eieio();
goto instr_done;
}
break;
}
/* Following cases refer to regs->gpr[], so we need all regs */
if (!FULL_REGS(regs))
return 0;
rd = (instr >> 21) & 0x1f;
ra = (instr >> 16) & 0x1f;
rb = (instr >> 11) & 0x1f;
switch (opcode) {
case 7: /* mulli */
regs->gpr[rd] = regs->gpr[ra] * (short) instr;
goto instr_done;
case 8: /* subfic */
imm = (short) instr;
add_with_carry(regs, rd, ~regs->gpr[ra], imm, 1);
goto instr_done;
case 10: /* cmpli */
imm = (unsigned short) instr;
val = regs->gpr[ra];
#ifdef __powerpc64__
if ((rd & 1) == 0)
val = (unsigned int) val;
#endif
do_cmp_unsigned(regs, val, imm, rd >> 2);
goto instr_done;
case 11: /* cmpi */
imm = (short) instr;
val = regs->gpr[ra];
#ifdef __powerpc64__
if ((rd & 1) == 0)
val = (int) val;
#endif
do_cmp_signed(regs, val, imm, rd >> 2);
goto instr_done;
case 12: /* addic */
imm = (short) instr;
add_with_carry(regs, rd, regs->gpr[ra], imm, 0);
goto instr_done;
case 13: /* addic. */
imm = (short) instr;
add_with_carry(regs, rd, regs->gpr[ra], imm, 0);
set_cr0(regs, rd);
goto instr_done;
case 14: /* addi */
imm = (short) instr;
if (ra)
imm += regs->gpr[ra];
regs->gpr[rd] = imm;
goto instr_done;
case 15: /* addis */
imm = ((short) instr) << 16;
if (ra)
imm += regs->gpr[ra];
regs->gpr[rd] = imm;
goto instr_done;
case 20: /* rlwimi */
mb = (instr >> 6) & 0x1f;
me = (instr >> 1) & 0x1f;
val = DATA32(regs->gpr[rd]);
imm = MASK32(mb, me);
regs->gpr[ra] = (regs->gpr[ra] & ~imm) | (ROTATE(val, rb) & imm);
goto logical_done;
case 21: /* rlwinm */
mb = (instr >> 6) & 0x1f;
me = (instr >> 1) & 0x1f;
val = DATA32(regs->gpr[rd]);
regs->gpr[ra] = ROTATE(val, rb) & MASK32(mb, me);
goto logical_done;
case 23: /* rlwnm */
mb = (instr >> 6) & 0x1f;
me = (instr >> 1) & 0x1f;
rb = regs->gpr[rb] & 0x1f;
val = DATA32(regs->gpr[rd]);
regs->gpr[ra] = ROTATE(val, rb) & MASK32(mb, me);
goto logical_done;
case 24: /* ori */
imm = (unsigned short) instr;
regs->gpr[ra] = regs->gpr[rd] | imm;
goto instr_done;
case 25: /* oris */
imm = (unsigned short) instr;
regs->gpr[ra] = regs->gpr[rd] | (imm << 16);
goto instr_done;
case 26: /* xori */
imm = (unsigned short) instr;
regs->gpr[ra] = regs->gpr[rd] ^ imm;
goto instr_done;
case 27: /* xoris */
imm = (unsigned short) instr;
regs->gpr[ra] = regs->gpr[rd] ^ (imm << 16);
goto instr_done;
case 28: /* andi. */
imm = (unsigned short) instr;
regs->gpr[ra] = regs->gpr[rd] & imm;
set_cr0(regs, ra);
goto instr_done;
case 29: /* andis. */
imm = (unsigned short) instr;
regs->gpr[ra] = regs->gpr[rd] & (imm << 16);
set_cr0(regs, ra);
goto instr_done;
#ifdef __powerpc64__
case 30: /* rld* */
mb = ((instr >> 6) & 0x1f) | (instr & 0x20);
val = regs->gpr[rd];
if ((instr & 0x10) == 0) {
sh = rb | ((instr & 2) << 4);
val = ROTATE(val, sh);
switch ((instr >> 2) & 3) {
case 0: /* rldicl */
regs->gpr[ra] = val & MASK64_L(mb);
goto logical_done;
case 1: /* rldicr */
regs->gpr[ra] = val & MASK64_R(mb);
goto logical_done;
case 2: /* rldic */
regs->gpr[ra] = val & MASK64(mb, 63 - sh);
goto logical_done;
case 3: /* rldimi */
imm = MASK64(mb, 63 - sh);
regs->gpr[ra] = (regs->gpr[ra] & ~imm) |
(val & imm);
goto logical_done;
}
} else {
sh = regs->gpr[rb] & 0x3f;
val = ROTATE(val, sh);
switch ((instr >> 1) & 7) {
case 0: /* rldcl */
regs->gpr[ra] = val & MASK64_L(mb);
goto logical_done;
case 1: /* rldcr */
regs->gpr[ra] = val & MASK64_R(mb);
goto logical_done;
}
}
#endif
case 31:
switch ((instr >> 1) & 0x3ff) {
case 83: /* mfmsr */
if (regs->msr & MSR_PR)
break;
regs->gpr[rd] = regs->msr & MSR_MASK;
goto instr_done;
case 146: /* mtmsr */
if (regs->msr & MSR_PR)
break;
imm = regs->gpr[rd];
if ((imm & MSR_RI) == 0)
/* can't step mtmsr that would clear MSR_RI */
return -1;
regs->msr = imm;
goto instr_done;
#ifdef CONFIG_PPC64
case 178: /* mtmsrd */
/* only MSR_EE and MSR_RI get changed if bit 15 set */
/* mtmsrd doesn't change MSR_HV and MSR_ME */
if (regs->msr & MSR_PR)
break;
imm = (instr & 0x10000)? 0x8002: 0xefffffffffffefffUL;
imm = (regs->msr & MSR_MASK & ~imm)
| (regs->gpr[rd] & imm);
if ((imm & MSR_RI) == 0)
/* can't step mtmsrd that would clear MSR_RI */
return -1;
regs->msr = imm;
goto instr_done;
#endif
case 19: /* mfcr */
regs->gpr[rd] = regs->ccr;
regs->gpr[rd] &= 0xffffffffUL;
goto instr_done;
case 144: /* mtcrf */
imm = 0xf0000000UL;
val = regs->gpr[rd];
for (sh = 0; sh < 8; ++sh) {
if (instr & (0x80000 >> sh))
regs->ccr = (regs->ccr & ~imm) |
(val & imm);
imm >>= 4;
}
goto instr_done;
case 339: /* mfspr */
spr = (instr >> 11) & 0x3ff;
switch (spr) {
case 0x20: /* mfxer */
regs->gpr[rd] = regs->xer;
regs->gpr[rd] &= 0xffffffffUL;
goto instr_done;
case 0x100: /* mflr */
regs->gpr[rd] = regs->link;
goto instr_done;
case 0x120: /* mfctr */
regs->gpr[rd] = regs->ctr;
goto instr_done;
}
break;
case 467: /* mtspr */
spr = (instr >> 11) & 0x3ff;
switch (spr) {
case 0x20: /* mtxer */
regs->xer = (regs->gpr[rd] & 0xffffffffUL);
goto instr_done;
case 0x100: /* mtlr */
regs->link = regs->gpr[rd];
goto instr_done;
case 0x120: /* mtctr */
regs->ctr = regs->gpr[rd];
goto instr_done;
}
break;
/*
* Compare instructions
*/
case 0: /* cmp */
val = regs->gpr[ra];
val2 = regs->gpr[rb];
#ifdef __powerpc64__
if ((rd & 1) == 0) {
/* word (32-bit) compare */
val = (int) val;
val2 = (int) val2;
}
#endif
do_cmp_signed(regs, val, val2, rd >> 2);
goto instr_done;
case 32: /* cmpl */
val = regs->gpr[ra];
val2 = regs->gpr[rb];
#ifdef __powerpc64__
if ((rd & 1) == 0) {
/* word (32-bit) compare */
val = (unsigned int) val;
val2 = (unsigned int) val2;
}
#endif
do_cmp_unsigned(regs, val, val2, rd >> 2);
goto instr_done;
/*
* Arithmetic instructions
*/
case 8: /* subfc */
add_with_carry(regs, rd, ~regs->gpr[ra],
regs->gpr[rb], 1);
goto arith_done;
#ifdef __powerpc64__
case 9: /* mulhdu */
asm("mulhdu %0,%1,%2" : "=r" (regs->gpr[rd]) :
"r" (regs->gpr[ra]), "r" (regs->gpr[rb]));
goto arith_done;
#endif
case 10: /* addc */
add_with_carry(regs, rd, regs->gpr[ra],
regs->gpr[rb], 0);
goto arith_done;
case 11: /* mulhwu */
asm("mulhwu %0,%1,%2" : "=r" (regs->gpr[rd]) :
"r" (regs->gpr[ra]), "r" (regs->gpr[rb]));
goto arith_done;
case 40: /* subf */
regs->gpr[rd] = regs->gpr[rb] - regs->gpr[ra];
goto arith_done;
#ifdef __powerpc64__
case 73: /* mulhd */
asm("mulhd %0,%1,%2" : "=r" (regs->gpr[rd]) :
"r" (regs->gpr[ra]), "r" (regs->gpr[rb]));
goto arith_done;
#endif
case 75: /* mulhw */
asm("mulhw %0,%1,%2" : "=r" (regs->gpr[rd]) :
"r" (regs->gpr[ra]), "r" (regs->gpr[rb]));
goto arith_done;
case 104: /* neg */
regs->gpr[rd] = -regs->gpr[ra];
goto arith_done;
case 136: /* subfe */
add_with_carry(regs, rd, ~regs->gpr[ra], regs->gpr[rb],
regs->xer & XER_CA);
goto arith_done;
case 138: /* adde */
add_with_carry(regs, rd, regs->gpr[ra], regs->gpr[rb],
regs->xer & XER_CA);
goto arith_done;
case 200: /* subfze */
add_with_carry(regs, rd, ~regs->gpr[ra], 0L,
regs->xer & XER_CA);
goto arith_done;
case 202: /* addze */
add_with_carry(regs, rd, regs->gpr[ra], 0L,
regs->xer & XER_CA);
goto arith_done;
case 232: /* subfme */
add_with_carry(regs, rd, ~regs->gpr[ra], -1L,
regs->xer & XER_CA);
goto arith_done;
#ifdef __powerpc64__
case 233: /* mulld */
regs->gpr[rd] = regs->gpr[ra] * regs->gpr[rb];
goto arith_done;
#endif
case 234: /* addme */
add_with_carry(regs, rd, regs->gpr[ra], -1L,
regs->xer & XER_CA);
goto arith_done;
case 235: /* mullw */
regs->gpr[rd] = (unsigned int) regs->gpr[ra] *
(unsigned int) regs->gpr[rb];
goto arith_done;
case 266: /* add */
regs->gpr[rd] = regs->gpr[ra] + regs->gpr[rb];
goto arith_done;
#ifdef __powerpc64__
case 457: /* divdu */
regs->gpr[rd] = regs->gpr[ra] / regs->gpr[rb];
goto arith_done;
#endif
case 459: /* divwu */
regs->gpr[rd] = (unsigned int) regs->gpr[ra] /
(unsigned int) regs->gpr[rb];
goto arith_done;
#ifdef __powerpc64__
case 489: /* divd */
regs->gpr[rd] = (long int) regs->gpr[ra] /
(long int) regs->gpr[rb];
goto arith_done;
#endif
case 491: /* divw */
regs->gpr[rd] = (int) regs->gpr[ra] /
(int) regs->gpr[rb];
goto arith_done;
/*
* Logical instructions
*/
case 26: /* cntlzw */
asm("cntlzw %0,%1" : "=r" (regs->gpr[ra]) :
"r" (regs->gpr[rd]));
goto logical_done;
#ifdef __powerpc64__
case 58: /* cntlzd */
asm("cntlzd %0,%1" : "=r" (regs->gpr[ra]) :
"r" (regs->gpr[rd]));
goto logical_done;
#endif
case 28: /* and */
regs->gpr[ra] = regs->gpr[rd] & regs->gpr[rb];
goto logical_done;
case 60: /* andc */
regs->gpr[ra] = regs->gpr[rd] & ~regs->gpr[rb];
goto logical_done;
case 124: /* nor */
regs->gpr[ra] = ~(regs->gpr[rd] | regs->gpr[rb]);
goto logical_done;
case 284: /* xor */
regs->gpr[ra] = ~(regs->gpr[rd] ^ regs->gpr[rb]);
goto logical_done;
case 316: /* xor */
regs->gpr[ra] = regs->gpr[rd] ^ regs->gpr[rb];
goto logical_done;
case 412: /* orc */
regs->gpr[ra] = regs->gpr[rd] | ~regs->gpr[rb];
goto logical_done;
case 444: /* or */
regs->gpr[ra] = regs->gpr[rd] | regs->gpr[rb];
goto logical_done;
case 476: /* nand */
regs->gpr[ra] = ~(regs->gpr[rd] & regs->gpr[rb]);
goto logical_done;
case 922: /* extsh */
regs->gpr[ra] = (signed short) regs->gpr[rd];
goto logical_done;
case 954: /* extsb */
regs->gpr[ra] = (signed char) regs->gpr[rd];
goto logical_done;
#ifdef __powerpc64__
case 986: /* extsw */
regs->gpr[ra] = (signed int) regs->gpr[rd];
goto logical_done;
#endif
/*
* Shift instructions
*/
case 24: /* slw */
sh = regs->gpr[rb] & 0x3f;
if (sh < 32)
regs->gpr[ra] = (regs->gpr[rd] << sh) & 0xffffffffUL;
else
regs->gpr[ra] = 0;
goto logical_done;
case 536: /* srw */
sh = regs->gpr[rb] & 0x3f;
if (sh < 32)
regs->gpr[ra] = (regs->gpr[rd] & 0xffffffffUL) >> sh;
else
regs->gpr[ra] = 0;
goto logical_done;
case 792: /* sraw */
sh = regs->gpr[rb] & 0x3f;
ival = (signed int) regs->gpr[rd];
regs->gpr[ra] = ival >> (sh < 32 ? sh : 31);
if (ival < 0 && (sh >= 32 || (ival & ((1 << sh) - 1)) != 0))
regs->xer |= XER_CA;
else
regs->xer &= ~XER_CA;
goto logical_done;
case 824: /* srawi */
sh = rb;
ival = (signed int) regs->gpr[rd];
regs->gpr[ra] = ival >> sh;
if (ival < 0 && (ival & ((1 << sh) - 1)) != 0)
regs->xer |= XER_CA;
else
regs->xer &= ~XER_CA;
goto logical_done;
#ifdef __powerpc64__
case 27: /* sld */
sh = regs->gpr[rd] & 0x7f;
if (sh < 64)
regs->gpr[ra] = regs->gpr[rd] << sh;
else
regs->gpr[ra] = 0;
goto logical_done;
case 539: /* srd */
sh = regs->gpr[rb] & 0x7f;
if (sh < 64)
regs->gpr[ra] = regs->gpr[rd] >> sh;
else
regs->gpr[ra] = 0;
goto logical_done;
case 794: /* srad */
sh = regs->gpr[rb] & 0x7f;
ival = (signed long int) regs->gpr[rd];
regs->gpr[ra] = ival >> (sh < 64 ? sh : 63);
if (ival < 0 && (sh >= 64 || (ival & ((1 << sh) - 1)) != 0))
regs->xer |= XER_CA;
else
regs->xer &= ~XER_CA;
goto logical_done;
case 826: /* sradi with sh_5 = 0 */
case 827: /* sradi with sh_5 = 1 */
sh = rb | ((instr & 2) << 4);
ival = (signed long int) regs->gpr[rd];
regs->gpr[ra] = ival >> sh;
if (ival < 0 && (ival & ((1 << sh) - 1)) != 0)
regs->xer |= XER_CA;
else
regs->xer &= ~XER_CA;
goto logical_done;
#endif /* __powerpc64__ */
/*
* Cache instructions
*/
case 54: /* dcbst */
ea = xform_ea(instr, regs, 0);
if (!address_ok(regs, ea, 8))
return 0;
err = 0;
__cacheop_user_asmx(ea, err, "dcbst");
if (err)
return 0;
goto instr_done;
case 86: /* dcbf */
ea = xform_ea(instr, regs, 0);
if (!address_ok(regs, ea, 8))
return 0;
err = 0;
__cacheop_user_asmx(ea, err, "dcbf");
if (err)
return 0;
goto instr_done;
case 246: /* dcbtst */
if (rd == 0) {
ea = xform_ea(instr, regs, 0);
prefetchw((void *) ea);
}
goto instr_done;
case 278: /* dcbt */
if (rd == 0) {
ea = xform_ea(instr, regs, 0);
prefetch((void *) ea);
}
goto instr_done;
}
break;
}
/*
* Following cases are for loads and stores, so bail out
* if we're in little-endian mode.
*/
if (regs->msr & MSR_LE)
return 0;
/*
* Save register RA in case it's an update form load or store
* and the access faults.
*/
old_ra = regs->gpr[ra];
switch (opcode) {
case 31:
u = instr & 0x40;
switch ((instr >> 1) & 0x3ff) {
case 20: /* lwarx */
ea = xform_ea(instr, regs, 0);
if (ea & 3)
break; /* can't handle misaligned */
err = -EFAULT;
if (!address_ok(regs, ea, 4))
goto ldst_done;
err = 0;
__get_user_asmx(val, ea, err, "lwarx");
if (!err)
regs->gpr[rd] = val;
goto ldst_done;
case 150: /* stwcx. */
ea = xform_ea(instr, regs, 0);
if (ea & 3)
break; /* can't handle misaligned */
err = -EFAULT;
if (!address_ok(regs, ea, 4))
goto ldst_done;
err = 0;
__put_user_asmx(regs->gpr[rd], ea, err, "stwcx.", cr);
if (!err)
regs->ccr = (regs->ccr & 0x0fffffff) |
(cr & 0xe0000000) |
((regs->xer >> 3) & 0x10000000);
goto ldst_done;
#ifdef __powerpc64__
case 84: /* ldarx */
ea = xform_ea(instr, regs, 0);
if (ea & 7)
break; /* can't handle misaligned */
err = -EFAULT;
if (!address_ok(regs, ea, 8))
goto ldst_done;
err = 0;
__get_user_asmx(val, ea, err, "ldarx");
if (!err)
regs->gpr[rd] = val;
goto ldst_done;
case 214: /* stdcx. */
ea = xform_ea(instr, regs, 0);
if (ea & 7)
break; /* can't handle misaligned */
err = -EFAULT;
if (!address_ok(regs, ea, 8))
goto ldst_done;
err = 0;
__put_user_asmx(regs->gpr[rd], ea, err, "stdcx.", cr);
if (!err)
regs->ccr = (regs->ccr & 0x0fffffff) |
(cr & 0xe0000000) |
((regs->xer >> 3) & 0x10000000);
goto ldst_done;
case 21: /* ldx */
case 53: /* ldux */
err = read_mem(®s->gpr[rd], xform_ea(instr, regs, u),
8, regs);
goto ldst_done;
#endif
case 23: /* lwzx */
case 55: /* lwzux */
err = read_mem(®s->gpr[rd], xform_ea(instr, regs, u),
4, regs);
goto ldst_done;
case 87: /* lbzx */
case 119: /* lbzux */
err = read_mem(®s->gpr[rd], xform_ea(instr, regs, u),
1, regs);
goto ldst_done;
#ifdef CONFIG_ALTIVEC
case 103: /* lvx */
case 359: /* lvxl */
if (!(regs->msr & MSR_VEC))
break;
ea = xform_ea(instr, regs, 0);
err = do_vec_load(rd, do_lvx, ea, regs);
goto ldst_done;
case 231: /* stvx */
case 487: /* stvxl */
if (!(regs->msr & MSR_VEC))
break;
ea = xform_ea(instr, regs, 0);
err = do_vec_store(rd, do_stvx, ea, regs);
goto ldst_done;
#endif /* CONFIG_ALTIVEC */
#ifdef __powerpc64__
case 149: /* stdx */
case 181: /* stdux */
val = regs->gpr[rd];
err = write_mem(val, xform_ea(instr, regs, u), 8, regs);
goto ldst_done;
#endif
case 151: /* stwx */
case 183: /* stwux */
val = regs->gpr[rd];
err = write_mem(val, xform_ea(instr, regs, u), 4, regs);
goto ldst_done;
case 215: /* stbx */
case 247: /* stbux */
val = regs->gpr[rd];
err = write_mem(val, xform_ea(instr, regs, u), 1, regs);
goto ldst_done;
case 279: /* lhzx */
case 311: /* lhzux */
err = read_mem(®s->gpr[rd], xform_ea(instr, regs, u),
2, regs);
goto ldst_done;
#ifdef __powerpc64__
case 341: /* lwax */
case 373: /* lwaux */
err = read_mem(®s->gpr[rd], xform_ea(instr, regs, u),
4, regs);
if (!err)
regs->gpr[rd] = (signed int) regs->gpr[rd];
goto ldst_done;
#endif
case 343: /* lhax */
case 375: /* lhaux */
err = read_mem(®s->gpr[rd], xform_ea(instr, regs, u),
2, regs);
if (!err)
regs->gpr[rd] = (signed short) regs->gpr[rd];
goto ldst_done;
case 407: /* sthx */
case 439: /* sthux */
val = regs->gpr[rd];
err = write_mem(val, xform_ea(instr, regs, u), 2, regs);
goto ldst_done;
#ifdef __powerpc64__
case 532: /* ldbrx */
err = read_mem(&val, xform_ea(instr, regs, 0), 8, regs);
if (!err)
regs->gpr[rd] = byterev_8(val);
goto ldst_done;
#endif
case 534: /* lwbrx */
err = read_mem(&val, xform_ea(instr, regs, 0), 4, regs);
if (!err)
regs->gpr[rd] = byterev_4(val);
goto ldst_done;
#ifdef CONFIG_PPC_CPU
case 535: /* lfsx */
case 567: /* lfsux */
if (!(regs->msr & MSR_FP))
break;
ea = xform_ea(instr, regs, u);
err = do_fp_load(rd, do_lfs, ea, 4, regs);
goto ldst_done;
case 599: /* lfdx */
case 631: /* lfdux */
if (!(regs->msr & MSR_FP))
break;
ea = xform_ea(instr, regs, u);
err = do_fp_load(rd, do_lfd, ea, 8, regs);
goto ldst_done;
case 663: /* stfsx */
case 695: /* stfsux */
if (!(regs->msr & MSR_FP))
break;
ea = xform_ea(instr, regs, u);
err = do_fp_store(rd, do_stfs, ea, 4, regs);
goto ldst_done;
case 727: /* stfdx */
case 759: /* stfdux */
if (!(regs->msr & MSR_FP))
break;
ea = xform_ea(instr, regs, u);
err = do_fp_store(rd, do_stfd, ea, 8, regs);
goto ldst_done;
#endif
#ifdef __powerpc64__
case 660: /* stdbrx */
val = byterev_8(regs->gpr[rd]);
err = write_mem(val, xform_ea(instr, regs, 0), 8, regs);
goto ldst_done;
#endif
case 662: /* stwbrx */
val = byterev_4(regs->gpr[rd]);
err = write_mem(val, xform_ea(instr, regs, 0), 4, regs);
goto ldst_done;
case 790: /* lhbrx */
err = read_mem(&val, xform_ea(instr, regs, 0), 2, regs);
if (!err)
regs->gpr[rd] = byterev_2(val);
goto ldst_done;
case 918: /* sthbrx */
val = byterev_2(regs->gpr[rd]);
err = write_mem(val, xform_ea(instr, regs, 0), 2, regs);
goto ldst_done;
#ifdef CONFIG_VSX
case 844: /* lxvd2x */
case 876: /* lxvd2ux */
if (!(regs->msr & MSR_VSX))
break;
rd |= (instr & 1) << 5;
ea = xform_ea(instr, regs, u);
err = do_vsx_load(rd, do_lxvd2x, ea, regs);
goto ldst_done;
case 972: /* stxvd2x */
case 1004: /* stxvd2ux */
if (!(regs->msr & MSR_VSX))
break;
rd |= (instr & 1) << 5;
ea = xform_ea(instr, regs, u);
err = do_vsx_store(rd, do_stxvd2x, ea, regs);
goto ldst_done;
#endif /* CONFIG_VSX */
}
break;
case 32: /* lwz */
case 33: /* lwzu */
err = read_mem(®s->gpr[rd], dform_ea(instr, regs), 4, regs);
goto ldst_done;
case 34: /* lbz */
case 35: /* lbzu */
err = read_mem(®s->gpr[rd], dform_ea(instr, regs), 1, regs);
goto ldst_done;
case 36: /* stw */
case 37: /* stwu */
val = regs->gpr[rd];
err = write_mem(val, dform_ea(instr, regs), 4, regs);
goto ldst_done;
case 38: /* stb */
case 39: /* stbu */
val = regs->gpr[rd];
err = write_mem(val, dform_ea(instr, regs), 1, regs);
goto ldst_done;
case 40: /* lhz */
case 41: /* lhzu */
err = read_mem(®s->gpr[rd], dform_ea(instr, regs), 2, regs);
goto ldst_done;
case 42: /* lha */
case 43: /* lhau */
err = read_mem(®s->gpr[rd], dform_ea(instr, regs), 2, regs);
if (!err)
regs->gpr[rd] = (signed short) regs->gpr[rd];
goto ldst_done;
case 44: /* sth */
case 45: /* sthu */
val = regs->gpr[rd];
err = write_mem(val, dform_ea(instr, regs), 2, regs);
goto ldst_done;
case 46: /* lmw */
ra = (instr >> 16) & 0x1f;
if (ra >= rd)
break; /* invalid form, ra in range to load */
ea = dform_ea(instr, regs);
do {
err = read_mem(®s->gpr[rd], ea, 4, regs);
if (err)
return 0;
ea += 4;
} while (++rd < 32);
goto instr_done;
case 47: /* stmw */
ea = dform_ea(instr, regs);
do {
err = write_mem(regs->gpr[rd], ea, 4, regs);
if (err)
return 0;
ea += 4;
} while (++rd < 32);
goto instr_done;
#ifdef CONFIG_PPC_FPU
case 48: /* lfs */
case 49: /* lfsu */
if (!(regs->msr & MSR_FP))
break;
ea = dform_ea(instr, regs);
err = do_fp_load(rd, do_lfs, ea, 4, regs);
goto ldst_done;
case 50: /* lfd */
case 51: /* lfdu */
if (!(regs->msr & MSR_FP))
break;
ea = dform_ea(instr, regs);
err = do_fp_load(rd, do_lfd, ea, 8, regs);
goto ldst_done;
case 52: /* stfs */
case 53: /* stfsu */
if (!(regs->msr & MSR_FP))
break;
ea = dform_ea(instr, regs);
err = do_fp_store(rd, do_stfs, ea, 4, regs);
goto ldst_done;
case 54: /* stfd */
case 55: /* stfdu */
if (!(regs->msr & MSR_FP))
break;
ea = dform_ea(instr, regs);
err = do_fp_store(rd, do_stfd, ea, 8, regs);
goto ldst_done;
#endif
#ifdef __powerpc64__
case 58: /* ld[u], lwa */
switch (instr & 3) {
case 0: /* ld */
err = read_mem(®s->gpr[rd], dsform_ea(instr, regs),
8, regs);
goto ldst_done;
case 1: /* ldu */
err = read_mem(®s->gpr[rd], dsform_ea(instr, regs),
8, regs);
goto ldst_done;
case 2: /* lwa */
err = read_mem(®s->gpr[rd], dsform_ea(instr, regs),
4, regs);
if (!err)
regs->gpr[rd] = (signed int) regs->gpr[rd];
goto ldst_done;
}
break;
case 62: /* std[u] */
val = regs->gpr[rd];
switch (instr & 3) {
case 0: /* std */
err = write_mem(val, dsform_ea(instr, regs), 8, regs);
goto ldst_done;
case 1: /* stdu */
err = write_mem(val, dsform_ea(instr, regs), 8, regs);
goto ldst_done;
}
break;
#endif /* __powerpc64__ */
}
err = -EINVAL;
ldst_done:
if (err) {
regs->gpr[ra] = old_ra;
return 0; /* invoke DSI if -EFAULT? */
}
instr_done:
regs->nip = truncate_if_32bit(regs->msr, regs->nip + 4);
return 1;
logical_done:
if (instr & 1)
set_cr0(regs, ra);
goto instr_done;
arith_done:
if (instr & 1)
set_cr0(regs, rd);
goto instr_done;
}
| gpl-2.0 |
macressler/parallella-linux | arch/powerpc/sysdev/uic.c | 7690 | 8394 | /*
* arch/powerpc/sysdev/uic.c
*
* IBM PowerPC 4xx Universal Interrupt Controller
*
* Copyright 2007 David Gibson <dwg@au1.ibm.com>, IBM Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/reboot.h>
#include <linux/slab.h>
#include <linux/stddef.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/device.h>
#include <linux/bootmem.h>
#include <linux/spinlock.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/dcr.h>
#define NR_UIC_INTS 32
#define UIC_SR 0x0
#define UIC_ER 0x2
#define UIC_CR 0x3
#define UIC_PR 0x4
#define UIC_TR 0x5
#define UIC_MSR 0x6
#define UIC_VR 0x7
#define UIC_VCR 0x8
struct uic *primary_uic;
struct uic {
int index;
int dcrbase;
raw_spinlock_t lock;
/* The remapper for this UIC */
struct irq_domain *irqhost;
};
static void uic_unmask_irq(struct irq_data *d)
{
struct uic *uic = irq_data_get_irq_chip_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned long flags;
u32 er, sr;
sr = 1 << (31-src);
raw_spin_lock_irqsave(&uic->lock, flags);
/* ack level-triggered interrupts here */
if (irqd_is_level_type(d))
mtdcr(uic->dcrbase + UIC_SR, sr);
er = mfdcr(uic->dcrbase + UIC_ER);
er |= sr;
mtdcr(uic->dcrbase + UIC_ER, er);
raw_spin_unlock_irqrestore(&uic->lock, flags);
}
static void uic_mask_irq(struct irq_data *d)
{
struct uic *uic = irq_data_get_irq_chip_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned long flags;
u32 er;
raw_spin_lock_irqsave(&uic->lock, flags);
er = mfdcr(uic->dcrbase + UIC_ER);
er &= ~(1 << (31 - src));
mtdcr(uic->dcrbase + UIC_ER, er);
raw_spin_unlock_irqrestore(&uic->lock, flags);
}
static void uic_ack_irq(struct irq_data *d)
{
struct uic *uic = irq_data_get_irq_chip_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned long flags;
raw_spin_lock_irqsave(&uic->lock, flags);
mtdcr(uic->dcrbase + UIC_SR, 1 << (31-src));
raw_spin_unlock_irqrestore(&uic->lock, flags);
}
static void uic_mask_ack_irq(struct irq_data *d)
{
struct uic *uic = irq_data_get_irq_chip_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned long flags;
u32 er, sr;
sr = 1 << (31-src);
raw_spin_lock_irqsave(&uic->lock, flags);
er = mfdcr(uic->dcrbase + UIC_ER);
er &= ~sr;
mtdcr(uic->dcrbase + UIC_ER, er);
/* On the UIC, acking (i.e. clearing the SR bit)
* a level irq will have no effect if the interrupt
* is still asserted by the device, even if
* the interrupt is already masked. Therefore
* we only ack the egde interrupts here, while
* level interrupts are ack'ed after the actual
* isr call in the uic_unmask_irq()
*/
if (!irqd_is_level_type(d))
mtdcr(uic->dcrbase + UIC_SR, sr);
raw_spin_unlock_irqrestore(&uic->lock, flags);
}
static int uic_set_irq_type(struct irq_data *d, unsigned int flow_type)
{
struct uic *uic = irq_data_get_irq_chip_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned long flags;
int trigger, polarity;
u32 tr, pr, mask;
switch (flow_type & IRQ_TYPE_SENSE_MASK) {
case IRQ_TYPE_NONE:
uic_mask_irq(d);
return 0;
case IRQ_TYPE_EDGE_RISING:
trigger = 1; polarity = 1;
break;
case IRQ_TYPE_EDGE_FALLING:
trigger = 1; polarity = 0;
break;
case IRQ_TYPE_LEVEL_HIGH:
trigger = 0; polarity = 1;
break;
case IRQ_TYPE_LEVEL_LOW:
trigger = 0; polarity = 0;
break;
default:
return -EINVAL;
}
mask = ~(1 << (31 - src));
raw_spin_lock_irqsave(&uic->lock, flags);
tr = mfdcr(uic->dcrbase + UIC_TR);
pr = mfdcr(uic->dcrbase + UIC_PR);
tr = (tr & mask) | (trigger << (31-src));
pr = (pr & mask) | (polarity << (31-src));
mtdcr(uic->dcrbase + UIC_PR, pr);
mtdcr(uic->dcrbase + UIC_TR, tr);
raw_spin_unlock_irqrestore(&uic->lock, flags);
return 0;
}
static struct irq_chip uic_irq_chip = {
.name = "UIC",
.irq_unmask = uic_unmask_irq,
.irq_mask = uic_mask_irq,
.irq_mask_ack = uic_mask_ack_irq,
.irq_ack = uic_ack_irq,
.irq_set_type = uic_set_irq_type,
};
static int uic_host_map(struct irq_domain *h, unsigned int virq,
irq_hw_number_t hw)
{
struct uic *uic = h->host_data;
irq_set_chip_data(virq, uic);
/* Despite the name, handle_level_irq() works for both level
* and edge irqs on UIC. FIXME: check this is correct */
irq_set_chip_and_handler(virq, &uic_irq_chip, handle_level_irq);
/* Set default irq type */
irq_set_irq_type(virq, IRQ_TYPE_NONE);
return 0;
}
static struct irq_domain_ops uic_host_ops = {
.map = uic_host_map,
.xlate = irq_domain_xlate_twocell,
};
void uic_irq_cascade(unsigned int virq, struct irq_desc *desc)
{
struct irq_chip *chip = irq_desc_get_chip(desc);
struct irq_data *idata = irq_desc_get_irq_data(desc);
struct uic *uic = irq_get_handler_data(virq);
u32 msr;
int src;
int subvirq;
raw_spin_lock(&desc->lock);
if (irqd_is_level_type(idata))
chip->irq_mask(idata);
else
chip->irq_mask_ack(idata);
raw_spin_unlock(&desc->lock);
msr = mfdcr(uic->dcrbase + UIC_MSR);
if (!msr) /* spurious interrupt */
goto uic_irq_ret;
src = 32 - ffs(msr);
subvirq = irq_linear_revmap(uic->irqhost, src);
generic_handle_irq(subvirq);
uic_irq_ret:
raw_spin_lock(&desc->lock);
if (irqd_is_level_type(idata))
chip->irq_ack(idata);
if (!irqd_irq_disabled(idata) && chip->irq_unmask)
chip->irq_unmask(idata);
raw_spin_unlock(&desc->lock);
}
static struct uic * __init uic_init_one(struct device_node *node)
{
struct uic *uic;
const u32 *indexp, *dcrreg;
int len;
BUG_ON(! of_device_is_compatible(node, "ibm,uic"));
uic = kzalloc(sizeof(*uic), GFP_KERNEL);
if (! uic)
return NULL; /* FIXME: panic? */
raw_spin_lock_init(&uic->lock);
indexp = of_get_property(node, "cell-index", &len);
if (!indexp || (len != sizeof(u32))) {
printk(KERN_ERR "uic: Device node %s has missing or invalid "
"cell-index property\n", node->full_name);
return NULL;
}
uic->index = *indexp;
dcrreg = of_get_property(node, "dcr-reg", &len);
if (!dcrreg || (len != 2*sizeof(u32))) {
printk(KERN_ERR "uic: Device node %s has missing or invalid "
"dcr-reg property\n", node->full_name);
return NULL;
}
uic->dcrbase = *dcrreg;
uic->irqhost = irq_domain_add_linear(node, NR_UIC_INTS, &uic_host_ops,
uic);
if (! uic->irqhost)
return NULL; /* FIXME: panic? */
/* Start with all interrupts disabled, level and non-critical */
mtdcr(uic->dcrbase + UIC_ER, 0);
mtdcr(uic->dcrbase + UIC_CR, 0);
mtdcr(uic->dcrbase + UIC_TR, 0);
/* Clear any pending interrupts, in case the firmware left some */
mtdcr(uic->dcrbase + UIC_SR, 0xffffffff);
printk ("UIC%d (%d IRQ sources) at DCR 0x%x\n", uic->index,
NR_UIC_INTS, uic->dcrbase);
return uic;
}
void __init uic_init_tree(void)
{
struct device_node *np;
struct uic *uic;
const u32 *interrupts;
/* First locate and initialize the top-level UIC */
for_each_compatible_node(np, NULL, "ibm,uic") {
interrupts = of_get_property(np, "interrupts", NULL);
if (!interrupts)
break;
}
BUG_ON(!np); /* uic_init_tree() assumes there's a UIC as the
* top-level interrupt controller */
primary_uic = uic_init_one(np);
if (!primary_uic)
panic("Unable to initialize primary UIC %s\n", np->full_name);
irq_set_default_host(primary_uic->irqhost);
of_node_put(np);
/* The scan again for cascaded UICs */
for_each_compatible_node(np, NULL, "ibm,uic") {
interrupts = of_get_property(np, "interrupts", NULL);
if (interrupts) {
/* Secondary UIC */
int cascade_virq;
uic = uic_init_one(np);
if (! uic)
panic("Unable to initialize a secondary UIC %s\n",
np->full_name);
cascade_virq = irq_of_parse_and_map(np, 0);
irq_set_handler_data(cascade_virq, uic);
irq_set_chained_handler(cascade_virq, uic_irq_cascade);
/* FIXME: setup critical cascade?? */
}
}
}
/* Return an interrupt vector or NO_IRQ if no interrupt is pending. */
unsigned int uic_get_irq(void)
{
u32 msr;
int src;
BUG_ON(! primary_uic);
msr = mfdcr(primary_uic->dcrbase + UIC_MSR);
src = 32 - ffs(msr);
return irq_linear_revmap(primary_uic->irqhost, src);
}
| gpl-2.0 |
jejecule/android_kernel_oppo_msm8974 | drivers/video/cfbfillrect.c | 14858 | 8940 | /*
* Generic fillrect for frame buffers with packed pixels of any depth.
*
* Copyright (C) 2000 James Simmons (jsimmons@linux-fbdev.org)
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*
* NOTES:
*
* Also need to add code to deal with cards endians that are different than
* the native cpu endians. I also need to deal with MSB position in the word.
*
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fb.h>
#include <asm/types.h>
#include "fb_draw.h"
#if BITS_PER_LONG == 32
# define FB_WRITEL fb_writel
# define FB_READL fb_readl
#else
# define FB_WRITEL fb_writeq
# define FB_READL fb_readq
#endif
/*
* Aligned pattern fill using 32/64-bit memory accesses
*/
static void
bitfill_aligned(struct fb_info *p, unsigned long __iomem *dst, int dst_idx,
unsigned long pat, unsigned n, int bits, u32 bswapmask)
{
unsigned long first, last;
if (!n)
return;
first = fb_shifted_pixels_mask_long(p, dst_idx, bswapmask);
last = ~fb_shifted_pixels_mask_long(p, (dst_idx+n) % bits, bswapmask);
if (dst_idx+n <= bits) {
// Single word
if (last)
first &= last;
FB_WRITEL(comp(pat, FB_READL(dst), first), dst);
} else {
// Multiple destination words
// Leading bits
if (first!= ~0UL) {
FB_WRITEL(comp(pat, FB_READL(dst), first), dst);
dst++;
n -= bits - dst_idx;
}
// Main chunk
n /= bits;
while (n >= 8) {
FB_WRITEL(pat, dst++);
FB_WRITEL(pat, dst++);
FB_WRITEL(pat, dst++);
FB_WRITEL(pat, dst++);
FB_WRITEL(pat, dst++);
FB_WRITEL(pat, dst++);
FB_WRITEL(pat, dst++);
FB_WRITEL(pat, dst++);
n -= 8;
}
while (n--)
FB_WRITEL(pat, dst++);
// Trailing bits
if (last)
FB_WRITEL(comp(pat, FB_READL(dst), last), dst);
}
}
/*
* Unaligned generic pattern fill using 32/64-bit memory accesses
* The pattern must have been expanded to a full 32/64-bit value
* Left/right are the appropriate shifts to convert to the pattern to be
* used for the next 32/64-bit word
*/
static void
bitfill_unaligned(struct fb_info *p, unsigned long __iomem *dst, int dst_idx,
unsigned long pat, int left, int right, unsigned n, int bits)
{
unsigned long first, last;
if (!n)
return;
first = FB_SHIFT_HIGH(p, ~0UL, dst_idx);
last = ~(FB_SHIFT_HIGH(p, ~0UL, (dst_idx+n) % bits));
if (dst_idx+n <= bits) {
// Single word
if (last)
first &= last;
FB_WRITEL(comp(pat, FB_READL(dst), first), dst);
} else {
// Multiple destination words
// Leading bits
if (first) {
FB_WRITEL(comp(pat, FB_READL(dst), first), dst);
dst++;
pat = pat << left | pat >> right;
n -= bits - dst_idx;
}
// Main chunk
n /= bits;
while (n >= 4) {
FB_WRITEL(pat, dst++);
pat = pat << left | pat >> right;
FB_WRITEL(pat, dst++);
pat = pat << left | pat >> right;
FB_WRITEL(pat, dst++);
pat = pat << left | pat >> right;
FB_WRITEL(pat, dst++);
pat = pat << left | pat >> right;
n -= 4;
}
while (n--) {
FB_WRITEL(pat, dst++);
pat = pat << left | pat >> right;
}
// Trailing bits
if (last)
FB_WRITEL(comp(pat, FB_READL(dst), last), dst);
}
}
/*
* Aligned pattern invert using 32/64-bit memory accesses
*/
static void
bitfill_aligned_rev(struct fb_info *p, unsigned long __iomem *dst,
int dst_idx, unsigned long pat, unsigned n, int bits,
u32 bswapmask)
{
unsigned long val = pat, dat;
unsigned long first, last;
if (!n)
return;
first = fb_shifted_pixels_mask_long(p, dst_idx, bswapmask);
last = ~fb_shifted_pixels_mask_long(p, (dst_idx+n) % bits, bswapmask);
if (dst_idx+n <= bits) {
// Single word
if (last)
first &= last;
dat = FB_READL(dst);
FB_WRITEL(comp(dat ^ val, dat, first), dst);
} else {
// Multiple destination words
// Leading bits
if (first!=0UL) {
dat = FB_READL(dst);
FB_WRITEL(comp(dat ^ val, dat, first), dst);
dst++;
n -= bits - dst_idx;
}
// Main chunk
n /= bits;
while (n >= 8) {
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
n -= 8;
}
while (n--) {
FB_WRITEL(FB_READL(dst) ^ val, dst);
dst++;
}
// Trailing bits
if (last) {
dat = FB_READL(dst);
FB_WRITEL(comp(dat ^ val, dat, last), dst);
}
}
}
/*
* Unaligned generic pattern invert using 32/64-bit memory accesses
* The pattern must have been expanded to a full 32/64-bit value
* Left/right are the appropriate shifts to convert to the pattern to be
* used for the next 32/64-bit word
*/
static void
bitfill_unaligned_rev(struct fb_info *p, unsigned long __iomem *dst,
int dst_idx, unsigned long pat, int left, int right,
unsigned n, int bits)
{
unsigned long first, last, dat;
if (!n)
return;
first = FB_SHIFT_HIGH(p, ~0UL, dst_idx);
last = ~(FB_SHIFT_HIGH(p, ~0UL, (dst_idx+n) % bits));
if (dst_idx+n <= bits) {
// Single word
if (last)
first &= last;
dat = FB_READL(dst);
FB_WRITEL(comp(dat ^ pat, dat, first), dst);
} else {
// Multiple destination words
// Leading bits
if (first != 0UL) {
dat = FB_READL(dst);
FB_WRITEL(comp(dat ^ pat, dat, first), dst);
dst++;
pat = pat << left | pat >> right;
n -= bits - dst_idx;
}
// Main chunk
n /= bits;
while (n >= 4) {
FB_WRITEL(FB_READL(dst) ^ pat, dst);
dst++;
pat = pat << left | pat >> right;
FB_WRITEL(FB_READL(dst) ^ pat, dst);
dst++;
pat = pat << left | pat >> right;
FB_WRITEL(FB_READL(dst) ^ pat, dst);
dst++;
pat = pat << left | pat >> right;
FB_WRITEL(FB_READL(dst) ^ pat, dst);
dst++;
pat = pat << left | pat >> right;
n -= 4;
}
while (n--) {
FB_WRITEL(FB_READL(dst) ^ pat, dst);
dst++;
pat = pat << left | pat >> right;
}
// Trailing bits
if (last) {
dat = FB_READL(dst);
FB_WRITEL(comp(dat ^ pat, dat, last), dst);
}
}
}
void cfb_fillrect(struct fb_info *p, const struct fb_fillrect *rect)
{
unsigned long pat, pat2, fg;
unsigned long width = rect->width, height = rect->height;
int bits = BITS_PER_LONG, bytes = bits >> 3;
u32 bpp = p->var.bits_per_pixel;
unsigned long __iomem *dst;
int dst_idx, left;
if (p->state != FBINFO_STATE_RUNNING)
return;
if (p->fix.visual == FB_VISUAL_TRUECOLOR ||
p->fix.visual == FB_VISUAL_DIRECTCOLOR )
fg = ((u32 *) (p->pseudo_palette))[rect->color];
else
fg = rect->color;
pat = pixel_to_pat(bpp, fg);
dst = (unsigned long __iomem *)((unsigned long)p->screen_base & ~(bytes-1));
dst_idx = ((unsigned long)p->screen_base & (bytes - 1))*8;
dst_idx += rect->dy*p->fix.line_length*8+rect->dx*bpp;
/* FIXME For now we support 1-32 bpp only */
left = bits % bpp;
if (p->fbops->fb_sync)
p->fbops->fb_sync(p);
if (!left) {
u32 bswapmask = fb_compute_bswapmask(p);
void (*fill_op32)(struct fb_info *p,
unsigned long __iomem *dst, int dst_idx,
unsigned long pat, unsigned n, int bits,
u32 bswapmask) = NULL;
switch (rect->rop) {
case ROP_XOR:
fill_op32 = bitfill_aligned_rev;
break;
case ROP_COPY:
fill_op32 = bitfill_aligned;
break;
default:
printk( KERN_ERR "cfb_fillrect(): unknown rop, defaulting to ROP_COPY\n");
fill_op32 = bitfill_aligned;
break;
}
while (height--) {
dst += dst_idx >> (ffs(bits) - 1);
dst_idx &= (bits - 1);
fill_op32(p, dst, dst_idx, pat, width*bpp, bits,
bswapmask);
dst_idx += p->fix.line_length*8;
}
} else {
int right, r;
void (*fill_op)(struct fb_info *p, unsigned long __iomem *dst,
int dst_idx, unsigned long pat, int left,
int right, unsigned n, int bits) = NULL;
#ifdef __LITTLE_ENDIAN
right = left;
left = bpp - right;
#else
right = bpp - left;
#endif
switch (rect->rop) {
case ROP_XOR:
fill_op = bitfill_unaligned_rev;
break;
case ROP_COPY:
fill_op = bitfill_unaligned;
break;
default:
printk(KERN_ERR "cfb_fillrect(): unknown rop, defaulting to ROP_COPY\n");
fill_op = bitfill_unaligned;
break;
}
while (height--) {
dst += dst_idx / bits;
dst_idx &= (bits - 1);
r = dst_idx % bpp;
/* rotate pattern to the correct start position */
pat2 = le_long_to_cpu(rolx(cpu_to_le_long(pat), r, bpp));
fill_op(p, dst, dst_idx, pat2, left, right,
width*bpp, bits);
dst_idx += p->fix.line_length*8;
}
}
}
EXPORT_SYMBOL(cfb_fillrect);
MODULE_AUTHOR("James Simmons <jsimmons@users.sf.net>");
MODULE_DESCRIPTION("Generic software accelerated fill rectangle");
MODULE_LICENSE("GPL");
| gpl-2.0 |
sooorajjj/tomato_tree | camera/QCamera/HAL/core/src/QCameraHWI_Preview.cpp | 11 | 42357 | /*
** Copyright (c) 2012 The Linux Foundation. All rights reserved.
**
** Not a Contribution, Apache license notifications and license are retained
** for attribution purposes only.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*#error uncomment this for compiler test!*/
#define LOG_TAG "QCameraHWI_Preview"
#include <utils/Log.h>
#include <utils/threads.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "QCameraHAL.h"
#include "QCameraHWI.h"
#include <genlock.h>
#include <gralloc_priv.h>
#define UNLIKELY(exp) __builtin_expect(!!(exp), 0)
/* QCameraHWI_Preview class implementation goes here*/
/* following code implement the preview mode's image capture & display logic of this class*/
namespace android {
status_t QCameraStream_preview::getBufferFromSurface() {
int err = 0;
status_t ret = NO_ERROR;
int gralloc_usage;
struct ion_fd_data ion_info_fd;
preview_stream_ops_t *previewWindow = mHalCamCtrl->mPreviewWindow;
ALOGI(" %s : E ", __FUNCTION__);
if( previewWindow == NULL) {
ALOGE("%s: PreviewWindow = NULL", __func__);
return INVALID_OPERATION;
}
mHalCamCtrl->mPreviewMemoryLock.lock();
mHalCamCtrl->mPreviewMemory.buffer_count = mNumBuffers;
err = previewWindow->set_buffer_count(previewWindow, mHalCamCtrl->mPreviewMemory.buffer_count );
if (err != 0) {
ALOGE("set_buffer_count failed: %s (%d)",
strerror(-err), -err);
ret = UNKNOWN_ERROR;
goto end;
}
err = previewWindow->set_buffers_geometry(previewWindow, mWidth, mHeight,
mHalCamCtrl->getPreviewFormatInfo().Hal_format);
if (err != 0) {
ALOGE("set_buffers_geometry failed: %s (%d)",
strerror(-err), -err);
ret = UNKNOWN_ERROR;
goto end;
}
ret = p_mm_ops->ops->get_parm(mCameraHandle, MM_CAMERA_PARM_VFE_OUTPUT_ENABLE, &mVFEOutputs);
if(ret != MM_CAMERA_OK) {
ALOGE("get parm MM_CAMERA_PARM_VFE_OUTPUT_ENABLE failed");
ret = BAD_VALUE;
goto end;
}
//as software encoder is used to encode 720p, to enhance the performance
//cashed pmem is used here
if(mVFEOutputs == 1)
gralloc_usage = CAMERA_GRALLOC_HEAP_ID | CAMERA_GRALLOC_FALLBACK_HEAP_ID;
else
gralloc_usage = CAMERA_GRALLOC_HEAP_ID | CAMERA_GRALLOC_FALLBACK_HEAP_ID |
CAMERA_GRALLOC_CACHING_ID;
err = previewWindow->set_usage(previewWindow, gralloc_usage);
if(err != 0) {
/* set_usage error out */
ALOGE("%s: set_usage rc = %d", __func__, err);
ret = UNKNOWN_ERROR;
goto end;
}
ret = p_mm_ops->ops->get_parm(mCameraHandle, MM_CAMERA_PARM_HFR_FRAME_SKIP, &mHFRFrameSkip);
if(ret != MM_CAMERA_OK) {
ALOGE("get parm MM_CAMERA_PARM_HFR_FRAME_SKIP failed");
ret = BAD_VALUE;
goto end;
}
for (int cnt = 0; cnt < mHalCamCtrl->mPreviewMemory.buffer_count; cnt++) {
int stride;
err = previewWindow->dequeue_buffer(previewWindow,
&mHalCamCtrl->mPreviewMemory.buffer_handle[cnt],
&mHalCamCtrl->mPreviewMemory.stride[cnt]);
if(!err) {
ALOGV("%s: dequeue buf hdl =%p", __func__, *mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]);
err = previewWindow->lock_buffer(previewWindow,
mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]);
// lock the buffer using genlock
ALOGV("%s: camera call genlock_lock, hdl=%p",
__FUNCTION__, (*mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]));
if (GENLOCK_NO_ERROR != genlock_lock_buffer((native_handle_t *)(*mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]),
GENLOCK_WRITE_LOCK, GENLOCK_MAX_TIMEOUT)) {
ALOGE("%s: genlock_lock_buffer(WRITE) failed", __func__);
mHalCamCtrl->mPreviewMemory.local_flag[cnt] = BUFFER_UNLOCKED;
} else {
ALOGV("%s: genlock_lock_buffer hdl =%p", __func__, *mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]);
mHalCamCtrl->mPreviewMemory.local_flag[cnt] = BUFFER_LOCKED;
}
} else {
mHalCamCtrl->mPreviewMemory.local_flag[cnt] = BUFFER_NOT_OWNED;
ALOGE("%s: dequeue_buffer idx = %d err = %d", __func__, cnt, err);
}
ALOGV("%s: dequeue buf: %p\n", __func__, mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]);
if(err != 0) {
ALOGE("%s: dequeue_buffer failed: %s (%d)", __func__,
strerror(-err), -err);
ret = UNKNOWN_ERROR;
for(int i = 0; i < cnt; i++) {
if (BUFFER_LOCKED == mHalCamCtrl->mPreviewMemory.local_flag[i]) {
ALOGD("%s: camera call genlock_unlock", __func__);
if (GENLOCK_FAILURE == genlock_unlock_buffer((native_handle_t *)
(*(mHalCamCtrl->mPreviewMemory.buffer_handle[i])))) {
ALOGE("%s: genlock_unlock_buffer failed: hdl =%p", __func__, (*(mHalCamCtrl->mPreviewMemory.buffer_handle[i])) );
} else {
mHalCamCtrl->mPreviewMemory.local_flag[i] = BUFFER_UNLOCKED;
}
}
if( mHalCamCtrl->mPreviewMemory.local_flag[i] != BUFFER_NOT_OWNED) {
err = previewWindow->cancel_buffer(previewWindow,
mHalCamCtrl->mPreviewMemory.buffer_handle[i]);
}
mHalCamCtrl->mPreviewMemory.local_flag[i] = BUFFER_NOT_OWNED;
ALOGD("%s: cancel_buffer: hdl =%p", __func__, (*mHalCamCtrl->mPreviewMemory.buffer_handle[i]));
mHalCamCtrl->mPreviewMemory.buffer_handle[i] = NULL;
}
memset(&mHalCamCtrl->mPreviewMemory, 0, sizeof(mHalCamCtrl->mPreviewMemory));
goto end;
}
mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt] =
(struct private_handle_t *)(*mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]);
#ifdef USE_ION
mHalCamCtrl->mPreviewMemory.mem_info[cnt].main_ion_fd = open("/dev/ion", O_RDONLY);
if (mHalCamCtrl->mPreviewMemory.mem_info[cnt].main_ion_fd < 0) {
ALOGE("%s: failed: could not open ion device\n", __func__);
} else {
memset(&ion_info_fd, 0, sizeof(ion_info_fd));
ion_info_fd.fd = mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->fd;
if (ioctl(mHalCamCtrl->mPreviewMemory.mem_info[cnt].main_ion_fd,
ION_IOC_IMPORT, &ion_info_fd) < 0) {
ALOGE("ION import failed\n");
}
}
#endif
mHalCamCtrl->mPreviewMemory.camera_memory[cnt] =
mHalCamCtrl->mGetMemory(mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->fd,
mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->size,
1,
(void *)this);
ALOGD("%s: idx = %d, fd = %d, size = %d, offset = %d", __func__,
cnt, mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->fd,
mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->size,
mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->offset);
mHalCamCtrl->mPreviewMemory.mem_info[cnt].fd =
mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->fd;
mHalCamCtrl->mPreviewMemory.mem_info[cnt].size =
mHalCamCtrl->mPreviewMemory.private_buffer_handle[cnt]->size;
mHalCamCtrl->mPreviewMemory.mem_info[cnt].handle = ion_info_fd.handle;
}
memset(&mHalCamCtrl->mMetadata, 0, sizeof(mHalCamCtrl->mMetadata));
memset(mHalCamCtrl->mFace, 0, sizeof(mHalCamCtrl->mFace));
end:
mHalCamCtrl->mPreviewMemoryLock.unlock();
ALOGI(" %s : X ",__func__);
return ret;
}
status_t QCameraStream_preview::putBufferToSurface() {
int err = 0;
status_t ret = NO_ERROR;
ALOGI(" %s : E ", __FUNCTION__);
mHalCamCtrl->mPreviewMemoryLock.lock();
for (int cnt = 0; cnt < mHalCamCtrl->mPreviewMemory.buffer_count; cnt++) {
mHalCamCtrl->mPreviewMemory.camera_memory[cnt]->release(mHalCamCtrl->mPreviewMemory.camera_memory[cnt]);
#ifdef USE_ION
struct ion_handle_data ion_handle;
memset(&ion_handle, 0, sizeof(ion_handle));
ion_handle.handle = mHalCamCtrl->mPreviewMemory.mem_info[cnt].handle;
if (ioctl(mHalCamCtrl->mPreviewMemory.mem_info[cnt].main_ion_fd, ION_IOC_FREE, &ion_handle) < 0) {
ALOGE("%s: ion free failed\n", __func__);
}
close(mHalCamCtrl->mPreviewMemory.mem_info[cnt].main_ion_fd);
#endif
if (BUFFER_LOCKED == mHalCamCtrl->mPreviewMemory.local_flag[cnt]) {
ALOGD("%s: camera call genlock_unlock", __FUNCTION__);
if (GENLOCK_FAILURE == genlock_unlock_buffer((native_handle_t *)
(*(mHalCamCtrl->mPreviewMemory.buffer_handle[cnt])))) {
ALOGE("%s: genlock_unlock_buffer failed, handle =%p", __FUNCTION__, (*(mHalCamCtrl->mPreviewMemory.buffer_handle[cnt])));
continue;
} else {
ALOGD("%s: genlock_unlock_buffer, handle =%p", __FUNCTION__, (*(mHalCamCtrl->mPreviewMemory.buffer_handle[cnt])));
mHalCamCtrl->mPreviewMemory.local_flag[cnt] = BUFFER_UNLOCKED;
}
}
if( mHalCamCtrl->mPreviewMemory.local_flag[cnt] != BUFFER_NOT_OWNED) {
if (mHalCamCtrl->mPreviewWindow) {
err = mHalCamCtrl->mPreviewWindow->cancel_buffer(mHalCamCtrl->mPreviewWindow,
mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]);
ALOGD("%s: cancel_buffer: hdl =%p", __func__, (*mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]));
} else {
ALOGE("%s: Preview window is NULL, cannot cancel_buffer: hdl =%p",
__func__, (*mHalCamCtrl->mPreviewMemory.buffer_handle[cnt]));
}
}
mHalCamCtrl->mPreviewMemory.local_flag[cnt] = BUFFER_NOT_OWNED;
ALOGD(" put buffer %d successfully", cnt);
}
mHalCamCtrl->mPreviewMemoryLock.unlock();
memset(&mHalCamCtrl->mPreviewMemory, 0, sizeof(mHalCamCtrl->mPreviewMemory));
ALOGI(" %s : X ",__FUNCTION__);
return NO_ERROR;
}
status_t QCameraStream_preview::initStream(uint8_t no_cb_needed, uint8_t stream_on)
{
int format = 0;
status_t ret = NO_ERROR;
int numMinUndequeuedBufs;
int err = 0;
ALOGI(" %s : E ", __FUNCTION__);
if (mHalCamCtrl->isNoDisplayMode()) {
mNumBuffers = PREVIEW_BUFFER_COUNT;
if(mHalCamCtrl->isZSLMode()) {
if(mNumBuffers < mHalCamCtrl->getZSLQueueDepth() + 3) {
mNumBuffers = mHalCamCtrl->getZSLQueueDepth() + 3;
}
}
} else {
if( mHalCamCtrl->mPreviewWindow == NULL) {
ALOGE("%s: PreviewWindow = NULL", __func__);
return INVALID_OPERATION;
}
numMinUndequeuedBufs = 0;
if(mHalCamCtrl->mPreviewWindow->get_min_undequeued_buffer_count) {
err = mHalCamCtrl->mPreviewWindow->get_min_undequeued_buffer_count(
mHalCamCtrl->mPreviewWindow, &numMinUndequeuedBufs);
if (err != 0) {
ALOGE("get_min_undequeued_buffer_count failed: %s (%d)",
strerror(-err), -err);
ret = UNKNOWN_ERROR;
goto end;
}
}
mNumBuffers = PREVIEW_BUFFER_COUNT + numMinUndequeuedBufs;
if(mHalCamCtrl->isZSLMode()) {
if(mHalCamCtrl->getZSLQueueDepth() > numMinUndequeuedBufs)
mNumBuffers += mHalCamCtrl->getZSLQueueDepth() - numMinUndequeuedBufs;
}
}
ret = QCameraStream::initStream(no_cb_needed, stream_on);
end:
ALOGI(" %s : X ", __FUNCTION__);
return ret;
}
status_t QCameraStream_preview::getBufferNoDisplay( )
{
status_t ret = NO_ERROR;
uint32_t planes[VIDEO_MAX_PLANES];
ALOGI("%s : E ", __FUNCTION__);
mHalCamCtrl->mPreviewMemoryLock.lock();
memset(mDisplayBuf, 0, sizeof(mDisplayBuf));
if (mHalCamCtrl->initHeapMem(&mHalCamCtrl->mNoDispPreviewMemory,
mNumBuffers,
mFrameOffsetInfo.frame_len,
MSM_PMEM_MAINIMG,
&mFrameOffsetInfo,
mDisplayBuf) < 0) {
ret = NO_MEMORY;
goto end;
}
memset(&mHalCamCtrl->mMetadata, 0, sizeof(mHalCamCtrl->mMetadata));
memset(mHalCamCtrl->mFace, 0, sizeof(mHalCamCtrl->mFace));
ALOGI(" %s : X ",__FUNCTION__);
end:
mHalCamCtrl->mPreviewMemoryLock.unlock();
return ret;
}
status_t QCameraStream_preview::freeBufferNoDisplay()
{
ALOGI(" %s : E ", __FUNCTION__);
mHalCamCtrl->mPreviewMemoryLock.lock();
mHalCamCtrl->releaseHeapMem(&mHalCamCtrl->mNoDispPreviewMemory);
memset(&mHalCamCtrl->mNoDispPreviewMemory, 0, sizeof(mHalCamCtrl->mNoDispPreviewMemory));
mHalCamCtrl->mPreviewMemoryLock.unlock();
ALOGI(" %s : X ",__FUNCTION__);
return NO_ERROR;
}
void QCameraStream_preview::notifyROIEvent(fd_roi_t roi)
{
switch (roi.type) {
case FD_ROI_TYPE_HEADER:
{
mDisplayLock.lock();
mNumFDRcvd = 0;
memset(mHalCamCtrl->mFace, 0, sizeof(mHalCamCtrl->mFace));
mHalCamCtrl->mMetadata.faces = mHalCamCtrl->mFace;
mHalCamCtrl->mMetadata.number_of_faces = roi.d.hdr.num_face_detected;
if(mHalCamCtrl->mMetadata.number_of_faces > MAX_ROI)
mHalCamCtrl->mMetadata.number_of_faces = MAX_ROI;
mDisplayLock.unlock();
if (mHalCamCtrl->mMetadata.number_of_faces == 0) {
// Clear previous faces
if (mHalCamCtrl->mDataCb && (mHalCamCtrl->mMsgEnabled & CAMERA_MSG_PREVIEW_METADATA)){
ALOGE("%s: Face detection RIO callback", __func__);
mHalCamCtrl->mDataCb(CAMERA_MSG_PREVIEW_METADATA, NULL, 0,
&mHalCamCtrl->mMetadata, mHalCamCtrl->mCallbackCookie);
}
}
}
break;
case FD_ROI_TYPE_DATA:
{
mDisplayLock.lock();
int idx = roi.d.data.idx;
if (idx >= mHalCamCtrl->mMetadata.number_of_faces) {
mDisplayLock.unlock();
ALOGE("%s: idx %d out of boundary %d",
__func__, idx, mHalCamCtrl->mMetadata.number_of_faces);
break;
}
mHalCamCtrl->mFace[idx].id = roi.d.data.face.id;
mHalCamCtrl->mFace[idx].score = roi.d.data.face.score;
// top
mHalCamCtrl->mFace[idx].rect[0] =
roi.d.data.face.face_boundary.x*2000/mHalCamCtrl->mDimension.display_width - 1000;
//right
mHalCamCtrl->mFace[idx].rect[1] =
roi.d.data.face.face_boundary.y*2000/mHalCamCtrl->mDimension.display_height - 1000;
//bottom
mHalCamCtrl->mFace[idx].rect[2] = mHalCamCtrl->mFace[idx].rect[0] +
roi.d.data.face.face_boundary.dx*2000/mHalCamCtrl->mDimension.display_width;
//left
mHalCamCtrl->mFace[idx].rect[3] = mHalCamCtrl->mFace[idx].rect[1] +
roi.d.data.face.face_boundary.dy*2000/mHalCamCtrl->mDimension.display_height;
// Center of left eye
mHalCamCtrl->mFace[idx].left_eye[0] =
roi.d.data.face.left_eye_center[0]*2000/mHalCamCtrl->mDimension.display_width - 1000;
mHalCamCtrl->mFace[idx].left_eye[1] =
roi.d.data.face.left_eye_center[1]*2000/mHalCamCtrl->mDimension.display_height - 1000;
// Center of right eye
mHalCamCtrl->mFace[idx].right_eye[0] =
roi.d.data.face.right_eye_center[0]*2000/mHalCamCtrl->mDimension.display_width - 1000;
mHalCamCtrl->mFace[idx].right_eye[1] =
roi.d.data.face.right_eye_center[1]*2000/mHalCamCtrl->mDimension.display_height - 1000;
// Center of mouth
mHalCamCtrl->mFace[idx].mouth[0] =
roi.d.data.face.mouth_center[0]*2000/mHalCamCtrl->mDimension.display_width - 1000;
mHalCamCtrl->mFace[idx].mouth[1] =
roi.d.data.face.mouth_center[1]*2000/mHalCamCtrl->mDimension.display_height - 1000;
mHalCamCtrl->mFace[idx].smile_degree = roi.d.data.face.smile_degree;
mHalCamCtrl->mFace[idx].smile_score = roi.d.data.face.smile_confidence;
mHalCamCtrl->mFace[idx].blink_detected = roi.d.data.face.blink_detected;
mHalCamCtrl->mFace[idx].face_recognised = roi.d.data.face.is_face_recognised;
mHalCamCtrl->mFace[idx].gaze_angle = roi.d.data.face.gaze_angle;
/* newly added */
// upscale by 2 to recover from demaen downscaling
mHalCamCtrl->mFace[idx].updown_dir = roi.d.data.face.updown_dir * 2;
mHalCamCtrl->mFace[idx].leftright_dir = roi.d.data.face.leftright_dir * 2;
mHalCamCtrl->mFace[idx].roll_dir = roi.d.data.face.roll_dir * 2;
mHalCamCtrl->mFace[idx].leye_blink = roi.d.data.face.left_blink;
mHalCamCtrl->mFace[idx].reye_blink = roi.d.data.face.right_blink;
mHalCamCtrl->mFace[idx].left_right_gaze = roi.d.data.face.left_right_gaze;
mHalCamCtrl->mFace[idx].top_bottom_gaze = roi.d.data.face.top_bottom_gaze;
ALOGE("%s: Face(%d, %d, %d, %d), leftEye(%d, %d), rightEye(%d, %d), mouth(%d, %d), smile(%d, %d), face_recg(%d)", __func__,
mHalCamCtrl->mFace[idx].rect[0], mHalCamCtrl->mFace[idx].rect[1],
mHalCamCtrl->mFace[idx].rect[2], mHalCamCtrl->mFace[idx].rect[3],
mHalCamCtrl->mFace[idx].left_eye[0], mHalCamCtrl->mFace[idx].left_eye[1],
mHalCamCtrl->mFace[idx].right_eye[0], mHalCamCtrl->mFace[idx].right_eye[1],
mHalCamCtrl->mFace[idx].mouth[0], mHalCamCtrl->mFace[idx].mouth[1],
mHalCamCtrl->mFace[idx].smile_degree, mHalCamCtrl->mFace[idx].smile_score,
mHalCamCtrl->mFace[idx].face_recognised);
ALOGE("%s: gaze(%d, %d, %d), updown(%d), leftright(%d), roll(%d), blink(%d, %d, %d)", __func__,
mHalCamCtrl->mFace[idx].gaze_angle, mHalCamCtrl->mFace[idx].left_right_gaze,
mHalCamCtrl->mFace[idx].top_bottom_gaze, mHalCamCtrl->mFace[idx].updown_dir,
mHalCamCtrl->mFace[idx].leftright_dir, mHalCamCtrl->mFace[idx].roll_dir,
mHalCamCtrl->mFace[idx].blink_detected,
mHalCamCtrl->mFace[idx].leye_blink, mHalCamCtrl->mFace[idx].reye_blink);
mNumFDRcvd++;
mDisplayLock.unlock();
if (mNumFDRcvd == mHalCamCtrl->mMetadata.number_of_faces) {
if (mHalCamCtrl->mDataCb && (mHalCamCtrl->mMsgEnabled & CAMERA_MSG_PREVIEW_METADATA)){
ALOGE("%s: Face detection RIO callback with %d faces detected (score=%d)", __func__, mNumFDRcvd, mHalCamCtrl->mFace[idx].score);
mHalCamCtrl->mDataCb(CAMERA_MSG_PREVIEW_METADATA, NULL,
0, &mHalCamCtrl->mMetadata, mHalCamCtrl->mCallbackCookie);
}
}
}
break;
}
}
status_t QCameraStream_preview::initDisplayBuffers()
{
status_t ret = NO_ERROR;
uint8_t num_planes = mFrameOffsetInfo.num_planes;
uint32_t planes[VIDEO_MAX_PLANES];
ALOGI("%s:BEGIN",__func__);
memset(&mHalCamCtrl->mMetadata, 0, sizeof(camera_frame_metadata_t));
mHalCamCtrl->mPreviewMemoryLock.lock();
memset(&mHalCamCtrl->mPreviewMemory, 0, sizeof(mHalCamCtrl->mPreviewMemory));
mHalCamCtrl->mPreviewMemoryLock.unlock();
memset(mNotifyBuffer, 0, sizeof(mNotifyBuffer));
ret = getBufferFromSurface();
if(ret != NO_ERROR) {
ALOGE("%s: cannot get memory from surface texture client, ret = %d", __func__, ret);
return ret;
}
/* set 4 buffers for display */
mHalCamCtrl->mPreviewMemoryLock.lock();
for(int i=0; i < num_planes; i++)
planes[i] = mFrameOffsetInfo.mp[i].len;
memset(mDisplayBuf, 0, sizeof(mm_camera_buf_def_t) * 2 * PREVIEW_BUFFER_COUNT);
/*allocate memory for the buffers*/
for(int i = 0; i < mNumBuffers; i++){
if (mHalCamCtrl->mPreviewMemory.private_buffer_handle[i] == NULL)
continue;
mHalCamCtrl->mPreviewMemory.addr_offset[i] =
mHalCamCtrl->mPreviewMemory.private_buffer_handle[i]->offset;
ALOGD("%s: idx = %d, fd = %d, size = %d, cbcr_offset = %d, y_offset = %d, "
"offset = %d, vaddr = 0x%lx", __func__, i, mHalCamCtrl->mPreviewMemory.private_buffer_handle[i]->fd,
mHalCamCtrl->mPreviewMemory.private_buffer_handle[i]->size,
planes[0], 0,
mHalCamCtrl->mPreviewMemory.addr_offset[i],
(long unsigned int)mHalCamCtrl->mPreviewMemory.camera_memory[i]->data);
mDisplayBuf[i].num_planes = num_planes;
/* Plane 0 needs to be set seperately. Set other planes
* in a loop. */
mDisplayBuf[i].planes[0].length = planes[0];
mDisplayBuf[i].planes[0].m.userptr = mHalCamCtrl->mPreviewMemory.private_buffer_handle[i]->fd;
mDisplayBuf[i].planes[0].data_offset = mFrameOffsetInfo.mp[0].offset;
mDisplayBuf[i].planes[0].reserved[0] =0;// mHalCamCtrl->mPreviewMemory.addr_offset[i]; // mDisplayBuf.preview.buf.mp[i].frame_offset;
for (int j = 1; j < num_planes; j++) {
mDisplayBuf[i].planes[j].length = planes[j];
mDisplayBuf[i].planes[j].m.userptr = mHalCamCtrl->mPreviewMemory.private_buffer_handle[i]->fd;
mDisplayBuf[i].planes[j].data_offset = mFrameOffsetInfo.mp[j].offset;
mDisplayBuf[i].planes[j].reserved[0] =
mDisplayBuf[i].planes[j-1].reserved[0] +
mDisplayBuf[i].planes[j-1].length;
}
for (int j = 0; j < num_planes; j++)
ALOGD("Planes: %d length: %d userptr: %lu offset: %d\n", j,
mDisplayBuf[i].planes[j].length,
mDisplayBuf[i].planes[j].m.userptr,
mDisplayBuf[i].planes[j].reserved[0]);
mDisplayBuf[i].fd = mHalCamCtrl->mPreviewMemory.private_buffer_handle[i]->fd;
ALOGD("DEBUG2:Display buf[%d] fd:%d",i,mDisplayBuf[i].fd);
mDisplayBuf[i].frame_len = mFrameOffsetInfo.frame_len;
mDisplayBuf[i].buffer = (void *)mHalCamCtrl->mPreviewMemory.camera_memory[i]->data;
mDisplayBuf[i].mem_info = (void *)&mHalCamCtrl->mPreviewMemory.mem_info[i];
}/*end of for loop*/
/* register the streaming buffers for the channel*/
mHalCamCtrl->mPreviewMemoryLock.unlock();
ALOGI("%s:END",__func__);
return NO_ERROR;
error:
mHalCamCtrl->mPreviewMemoryLock.unlock();
putBufferToSurface();
ALOGV("%s: X", __func__);
return ret;
}
status_t QCameraStream_preview::initPreviewOnlyBuffers()
{
status_t ret = NO_ERROR;
uint8_t num_planes = mFrameOffsetInfo.num_planes;
uint32_t planes[VIDEO_MAX_PLANES];
ALOGI("%s:BEGIN",__func__);
memset(&mHalCamCtrl->mMetadata, 0, sizeof(camera_frame_metadata_t));
mHalCamCtrl->mPreviewMemoryLock.lock();
memset(&mHalCamCtrl->mNoDispPreviewMemory, 0, sizeof(mHalCamCtrl->mNoDispPreviewMemory));
mHalCamCtrl->mPreviewMemoryLock.unlock();
memset(mNotifyBuffer, 0, sizeof(mNotifyBuffer));
memset(mDisplayBuf, 0, sizeof(mDisplayBuf));
ret = getBufferNoDisplay( );
if(ret != NO_ERROR) {
ALOGE("%s: cannot get memory from surface texture client, ret = %d", __func__, ret);
return ret;
}
ALOGI("%s:END",__func__);
return NO_ERROR;
}
void QCameraStream_preview::dumpFrameToFile(mm_camera_buf_def_t *newFrame)
{
int32_t enabled = 0;
int frm_num;
uint32_t skip_mode;
char value[PROPERTY_VALUE_MAX];
char buf[32];
int w, h;
static int count = 0;
cam_ctrl_dimension_t dim;
int file_fd;
int rc = 0;
int len;
unsigned long addr;
unsigned long * tmp = (unsigned long *)newFrame->buffer;
addr = *tmp;
status_t ret = p_mm_ops->ops->get_parm(mCameraHandle,
MM_CAMERA_PARM_DIMENSION, &dim);
w = dim.display_width;
h = dim.display_height;
len = (w * h)*3/2;
count++;
if(count < 100) {
snprintf(buf, sizeof(buf), "/data/mzhu%d.yuv", count);
file_fd = open(buf, O_RDWR | O_CREAT, 0777);
rc = write(file_fd, (const void *)addr, len);
ALOGE("%s: file='%s', vaddr_old=0x%x, addr_map = 0x%p, len = %d, rc = %d",
__func__, buf, (uint32_t)newFrame->buffer, (void *)addr, len, rc);
close(file_fd);
ALOGE("%s: dump %s, rc = %d, len = %d", __func__, buf, rc, len);
}
}
status_t QCameraStream_preview::processPreviewFrameWithDisplay(mm_camera_super_buf_t *frame)
{
ALOGV("%s",__func__);
int err = 0;
int msgType = 0;
int i;
camera_memory_t *data = NULL;
camera_frame_metadata_t *metadata = NULL;
int preview_buf_idx = frame->bufs[0]->buf_idx;
if(!mActive) {
ALOGE("Preview Stopped. Returning callback");
return NO_ERROR;
}
if(mHalCamCtrl==NULL) {
ALOGE("%s: X: HAL control object not set",__func__);
/*Call buf done*/
return BAD_VALUE;
}
if(mFirstFrameRcvd == false) {
mFirstFrameRcvd = true;
}
if (UNLIKELY(mHalCamCtrl->mDebugFps)) {
mHalCamCtrl->debugShowPreviewFPS();
}
mHalCamCtrl->dumpFrameToFile(frame->bufs[0], HAL_DUMP_FRM_PREVIEW);
mHalCamCtrl->mPreviewMemoryLock.lock();
mNotifyBuffer[preview_buf_idx] = *frame;
ALOGD("<DEBUG2>: Received Frame fd:%d placed in index:%d db[index].fd:%d",
frame->bufs[0]->fd, preview_buf_idx,
mHalCamCtrl->mPreviewMemory.private_buffer_handle[preview_buf_idx]->fd);
ALOGI("Enqueue buf handle %p\n",
mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]);
ALOGD("%s: camera call genlock_unlock", __FUNCTION__);
if (BUFFER_LOCKED == mHalCamCtrl->mPreviewMemory.local_flag[preview_buf_idx]) {
ALOGD("%s: genlock_unlock_buffer hdl =%p", __FUNCTION__, (*mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]));
if (GENLOCK_FAILURE == genlock_unlock_buffer((native_handle_t*)
(*mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]))) {
ALOGE("%s: genlock_unlock_buffer failed", __FUNCTION__);
} else {
mHalCamCtrl->mPreviewMemory.local_flag[preview_buf_idx] = BUFFER_UNLOCKED;
}
} else {
ALOGE("%s: buffer to be enqueued is not locked", __FUNCTION__);
}
mHalCamCtrl->cache_ops(&mHalCamCtrl->mPreviewMemory.mem_info[preview_buf_idx],
(void *)mHalCamCtrl->mPreviewMemory.camera_memory[preview_buf_idx]->data,
ION_IOC_CLEAN_CACHES);
mHalCamCtrl->cache_ops(&mHalCamCtrl->mPreviewMemory.mem_info[preview_buf_idx],
(void *)mHalCamCtrl->mPreviewMemory.camera_memory[preview_buf_idx]->data,
ION_IOC_CLEAN_INV_CACHES);
if(mHFRFrameSkip == 1)
{
ALOGE("In HFR Frame skip");
const char *str = mHalCamCtrl->mParameters.get(
QCameraParameters::KEY_QC_VIDEO_HIGH_FRAME_RATE);
if(str != NULL){
int is_hfr_off = 0;
mHFRFrameCnt++;
if(!strcmp(str, QCameraParameters::VIDEO_HFR_OFF)) {
is_hfr_off = 1;
err = mHalCamCtrl->mPreviewWindow->enqueue_buffer(mHalCamCtrl->mPreviewWindow,
(buffer_handle_t *)mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]);
} else if (!strcmp(str, QCameraParameters::VIDEO_HFR_2X)) {
mHFRFrameCnt %= 2;
} else if (!strcmp(str, QCameraParameters::VIDEO_HFR_3X)) {
mHFRFrameCnt %= 3;
} else if (!strcmp(str, QCameraParameters::VIDEO_HFR_4X)) {
mHFRFrameCnt %= 4;
}
if(mHFRFrameCnt == 0)
err = mHalCamCtrl->mPreviewWindow->enqueue_buffer(mHalCamCtrl->mPreviewWindow,
(buffer_handle_t *)mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]);
else if(!is_hfr_off)
err = mHalCamCtrl->mPreviewWindow->cancel_buffer(mHalCamCtrl->mPreviewWindow,
(buffer_handle_t *)mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]);
} else
err = mHalCamCtrl->mPreviewWindow->enqueue_buffer(mHalCamCtrl->mPreviewWindow,
(buffer_handle_t *)mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]);
} else {
err = mHalCamCtrl->mPreviewWindow->enqueue_buffer(mHalCamCtrl->mPreviewWindow,
(buffer_handle_t *)mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]);
}
if(err != 0) {
ALOGE("%s: enqueue_buffer failed, err = %d", __func__, err);
} else {
ALOGD("%s: enqueue_buffer hdl=%p", __func__, *mHalCamCtrl->mPreviewMemory.buffer_handle[preview_buf_idx]);
mHalCamCtrl->mPreviewMemory.local_flag[preview_buf_idx] = BUFFER_NOT_OWNED;
}
buffer_handle_t *buffer_handle = NULL;
int tmp_stride = 0;
err = mHalCamCtrl->mPreviewWindow->dequeue_buffer(mHalCamCtrl->mPreviewWindow,
&buffer_handle, &tmp_stride);
if (err == NO_ERROR && buffer_handle != NULL) {
ALOGD("%s: dequed buf hdl =%p", __func__, *buffer_handle);
for(i = 0; i < mHalCamCtrl->mPreviewMemory.buffer_count; i++) {
if(mHalCamCtrl->mPreviewMemory.buffer_handle[i] == buffer_handle) {
ALOGE("<DEBUG2>:Found buffer in idx:%d",i);
mHalCamCtrl->mPreviewMemory.local_flag[i] = BUFFER_UNLOCKED;
break;
}
}
if (i < mHalCamCtrl->mPreviewMemory.buffer_count ) {
err = mHalCamCtrl->mPreviewWindow->lock_buffer(mHalCamCtrl->mPreviewWindow, buffer_handle);
ALOGD("%s: camera call genlock_lock: hdl =%p", __func__, *buffer_handle);
if (GENLOCK_FAILURE == genlock_lock_buffer((native_handle_t*)(*buffer_handle), GENLOCK_WRITE_LOCK,
GENLOCK_MAX_TIMEOUT)) {
ALOGE("%s: genlock_lock_buffer(WRITE) failed", __func__);
} else {
mHalCamCtrl->mPreviewMemory.local_flag[i] = BUFFER_LOCKED;
if(MM_CAMERA_OK != p_mm_ops->ops->qbuf(mCameraHandle, mChannelId, mNotifyBuffer[i].bufs[0])) {
ALOGE("BUF DONE FAILED");
}
mHalCamCtrl->cache_ops((QCameraHalMemInfo_t *)(mNotifyBuffer[i].bufs[0]->mem_info),
mNotifyBuffer[i].bufs[0]->buffer,
ION_IOC_INV_CACHES);
}
}
} else
ALOGE("%s: enqueue_buffer idx = %d, no free buffer from display now", __func__, frame->bufs[0]->buf_idx);
/* Save the last displayed frame. We'll be using it to fill the gap between
when preview stops and postview start during snapshot.*/
mLastQueuedFrame = &(mDisplayBuf[preview_buf_idx]);
mHalCamCtrl->mPreviewMemoryLock.unlock();
nsecs_t timeStamp = seconds_to_nanoseconds(frame->bufs[0]->ts.tv_sec) ;
timeStamp += frame->bufs[0]->ts.tv_nsec;
ALOGD("Message enabled = 0x%x", mHalCamCtrl->mMsgEnabled);
camera_memory_t *previewMem = NULL;
if (mHalCamCtrl->mDataCb != NULL) {
ALOGD("%s: mMsgEnabled =0x%x, preview format =%d", __func__,
mHalCamCtrl->mMsgEnabled, mHalCamCtrl->mPreviewFormat);
//Sending preview callback if corresponding Msgs are enabled
if(mHalCamCtrl->mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME) {
ALOGE("Q%s: PCB callback enabled", __func__);
msgType |= CAMERA_MSG_PREVIEW_FRAME;
int previewBufSize;
/* The preview buffer size sent back in the callback should be (width*height*bytes_per_pixel)
* As all preview formats we support, use 12 bits per pixel, buffer size = previewWidth * previewHeight * 3/2.
* We need to put a check if some other formats are supported in future. (punits) */
if ((mHalCamCtrl->mPreviewFormat == CAMERA_YUV_420_NV21) ||
(mHalCamCtrl->mPreviewFormat == CAMERA_YUV_420_NV12) ||
(mHalCamCtrl->mPreviewFormat == CAMERA_YUV_420_YV12))
{
if(mHalCamCtrl->mPreviewFormat == CAMERA_YUV_420_YV12) {
previewBufSize = ((mHalCamCtrl->mPreviewWidth+15)/16) * 16 * mHalCamCtrl->mPreviewHeight +
((mHalCamCtrl->mPreviewWidth/2+15)/16) * 16* mHalCamCtrl->mPreviewHeight;
} else {
previewBufSize = mHalCamCtrl->mPreviewWidth * mHalCamCtrl->mPreviewHeight * 3/2;
}
if(previewBufSize != mHalCamCtrl->mPreviewMemory.private_buffer_handle[preview_buf_idx]->size) {
previewMem = mHalCamCtrl->mGetMemory(mHalCamCtrl->mPreviewMemory.private_buffer_handle[preview_buf_idx]->fd,
previewBufSize, 1, mHalCamCtrl->mCallbackCookie);
if (!previewMem || !previewMem->data) {
ALOGE("%s: mGetMemory failed.\n", __func__);
} else {
data = previewMem;
}
} else
data = mHalCamCtrl->mPreviewMemory.camera_memory[preview_buf_idx];
} else {
data = mHalCamCtrl->mPreviewMemory.camera_memory[preview_buf_idx];
ALOGE("Invalid preview format, buffer size in preview callback may be wrong.");
}
} else {
data = NULL;
}
if(msgType && mActive) {
mHalCamCtrl->mDataCb(msgType, data, 0, metadata, mHalCamCtrl->mCallbackCookie);
}
if (previewMem) {
previewMem->release(previewMem);
}
ALOGD("end of cb");
} else {
ALOGD("%s PCB is not enabled", __func__);
}
if(mHalCamCtrl->mDataCbTimestamp != NULL && mVFEOutputs == 1)
{
int flagwait = 1;
if(mHalCamCtrl->mStartRecording == true &&
( mHalCamCtrl->mMsgEnabled & CAMERA_MSG_VIDEO_FRAME))
{
if (mHalCamCtrl->mStoreMetaDataInFrame)
{
if(mHalCamCtrl->mRecordingMemory.metadata_memory[preview_buf_idx])
{
flagwait = 1;
mHalCamCtrl->mDataCbTimestamp(timeStamp, CAMERA_MSG_VIDEO_FRAME,
mHalCamCtrl->mRecordingMemory.metadata_memory[preview_buf_idx],
0, mHalCamCtrl->mCallbackCookie);
}else
flagwait = 0;
}
else
{
mHalCamCtrl->mDataCbTimestamp(timeStamp, CAMERA_MSG_VIDEO_FRAME,
mHalCamCtrl->mPreviewMemory.camera_memory[preview_buf_idx],
0, mHalCamCtrl->mCallbackCookie);
}
if(flagwait){
Mutex::Autolock rLock(&mHalCamCtrl->mRecordFrameLock);
if (mHalCamCtrl->mReleasedRecordingFrame != true) {
mHalCamCtrl->mRecordWait.wait(mHalCamCtrl->mRecordFrameLock);
}
mHalCamCtrl->mReleasedRecordingFrame = false;
}
}
}
return NO_ERROR;
}
status_t QCameraStream_preview::processPreviewFrameWithOutDisplay(
mm_camera_super_buf_t *frame)
{
ALOGV("%s",__func__);
int err = 0;
int msgType = 0;
int i;
camera_memory_t *data = NULL;
camera_frame_metadata_t *metadata = NULL;
int preview_buf_idx = frame->bufs[0]->buf_idx;
if(mHalCamCtrl==NULL) {
ALOGE("%s: X: HAL control object not set",__func__);
/*Call buf done*/
return BAD_VALUE;
}
if (UNLIKELY(mHalCamCtrl->mDebugFps)) {
mHalCamCtrl->debugShowPreviewFPS();
}
mHalCamCtrl->dumpFrameToFile(frame->bufs[0], HAL_DUMP_FRM_PREVIEW);
mHalCamCtrl->mPreviewMemoryLock.lock();
mNotifyBuffer[preview_buf_idx] = *frame;
/* Save the last displayed frame. We'll be using it to fill the gap between
when preview stops and postview start during snapshot.*/
mLastQueuedFrame = &(mDisplayBuf[frame->bufs[0]->buf_idx]);
mHalCamCtrl->mPreviewMemoryLock.unlock();
ALOGD("Message enabled = 0x%x", mHalCamCtrl->mMsgEnabled);
mHalCamCtrl->cache_ops(&mHalCamCtrl->mNoDispPreviewMemory.mem_info[preview_buf_idx],
(void *)mHalCamCtrl->mNoDispPreviewMemory.camera_memory[preview_buf_idx]->data,
ION_IOC_CLEAN_CACHES);
if (mHalCamCtrl->mDataCb != NULL) {
//Sending preview callback if corresponding Msgs are enabled
if(mHalCamCtrl->mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME) {
msgType |= CAMERA_MSG_PREVIEW_FRAME;
int previewBufSize;
/* For CTS : Forcing preview memory buffer lenth to be
'previewWidth * previewHeight * 3/2'.
Needed when gralloc allocated extra memory.*/
//Can add this check for other formats as well.
data = mHalCamCtrl->mNoDispPreviewMemory.camera_memory[preview_buf_idx];//mPreviewHeap->mBuffers[frame->bufs[0]->buf_idx];
} else {
data = NULL;
}
if(mHalCamCtrl->mMsgEnabled & CAMERA_MSG_PREVIEW_METADATA){
msgType |= CAMERA_MSG_PREVIEW_METADATA;
metadata = &mHalCamCtrl->mMetadata;
} else {
metadata = NULL;
}
if(mActive && msgType) {
mHalCamCtrl->mDataCb(msgType, data, 0, metadata, mHalCamCtrl->mCallbackCookie);
}
if(MM_CAMERA_OK !=p_mm_ops->ops->qbuf(mCameraHandle, mChannelId, mNotifyBuffer[preview_buf_idx].bufs[0])) {
ALOGE("BUF DONE FAILED");
}
mHalCamCtrl->cache_ops((QCameraHalMemInfo_t *)(mNotifyBuffer[preview_buf_idx].bufs[0]->mem_info),
mNotifyBuffer[preview_buf_idx].bufs[0]->buffer,
ION_IOC_INV_CACHES);
ALOGD("end of cb");
}
return NO_ERROR;
}
status_t QCameraStream_preview::processPreviewFrame (
mm_camera_super_buf_t *frame)
{
if (mHalCamCtrl->isNoDisplayMode()) {
return processPreviewFrameWithOutDisplay(frame);
} else {
return processPreviewFrameWithDisplay(frame);
}
}
// ---------------------------------------------------------------------------
// QCameraStream_preview
// ---------------------------------------------------------------------------
QCameraStream_preview::QCameraStream_preview(uint32_t CameraHandle,
uint32_t ChannelId,
uint32_t Width,
uint32_t Height,
uint32_t Format,
uint8_t NumBuffers,
mm_camera_vtbl_t *mm_ops,
mm_camera_img_mode imgmode,
camera_mode_t mode,
QCameraHardwareInterface* camCtrl)
:QCameraStream(CameraHandle,
ChannelId,
Width,
Height,
Format,
NumBuffers,
mm_ops,
imgmode,
mode,
camCtrl),
mLastQueuedFrame(NULL),
mNumFDRcvd(0)
{
}
// ---------------------------------------------------------------------------
// QCameraStream_preview
// ---------------------------------------------------------------------------
QCameraStream_preview::~QCameraStream_preview() {
ALOGV("%s: E", __func__);
release();
ALOGV("%s: X", __func__);
}
// ---------------------------------------------------------------------------
// QCameraStream_preview
// ---------------------------------------------------------------------------
void QCameraStream_preview::release() {
streamOff(0);
deinitStream();
}
void *QCameraStream_preview::getLastQueuedFrame(void)
{
return mLastQueuedFrame;
}
int32_t QCameraStream_preview::setCrop()
{
int32_t rc = QCameraStream::setCrop();
if (0 == rc) {
if (!mHalCamCtrl->mSmoothZoomRunning && mHalCamCtrl->mPreviewWindow) {
rc = mHalCamCtrl->mPreviewWindow->set_crop(
mHalCamCtrl->mPreviewWindow,
mCrop.offset_x,
mCrop.offset_y,
mCrop.offset_x + mCrop.width,
mCrop.offset_y + mCrop.height);
}
}
return rc;
}
int QCameraStream_preview::getBuf(mm_camera_frame_len_offset *frame_offset_info,
uint8_t num_bufs,
uint8_t *initial_reg_flag,
mm_camera_buf_def_t *bufs)
{
int ret = 0;
ALOGE("%s:BEGIN",__func__);
if (num_bufs > mNumBuffers) {
mNumBuffers = num_bufs;
}
if ((mNumBuffers == 0) || (mNumBuffers > MM_CAMERA_MAX_NUM_FRAMES)) {
ALOGE("%s: Invalid number of buffers (=%d) requested!",
__func__, mNumBuffers);
return BAD_VALUE;
}
memcpy(&mFrameOffsetInfo, frame_offset_info, sizeof(mFrameOffsetInfo));
if (mHalCamCtrl->isNoDisplayMode()) {
ret = initPreviewOnlyBuffers();
} else {
ret = initDisplayBuffers();
}
ALOGD("Debug : %s : initDisplayBuffers",__func__);
for(int i = 0; i < num_bufs; i++) {
bufs[i] = mDisplayBuf[i];
initial_reg_flag[i] = true;
}
ALOGV("%s: X - ret = %d ", __func__, ret);
return ret;
}
int QCameraStream_preview::putBuf(uint8_t num_bufs, mm_camera_buf_def_t *bufs)
{
int ret = 0;
ALOGE(" %s : E ", __func__);
if (mHalCamCtrl->isNoDisplayMode()) {
ret = freeBufferNoDisplay();
} else {
ret = putBufferToSurface();
}
ALOGI(" %s : X ",__func__);
return ret;
}
// ---------------------------------------------------------------------------
// No code beyone this line
// ---------------------------------------------------------------------------
}; // namespace android
| gpl-2.0 |
alexanderguy/dpdk | lib/librte_eal/bsdapp/eal/eal_timer.c | 11 | 8638 | /*-
* BSD LICENSE
*
* Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <sys/queue.h>
#include <pthread.h>
#include <errno.h>
#include <rte_common.h>
#include <rte_log.h>
#include <rte_cycles.h>
#include <rte_tailq.h>
#include <rte_memory.h>
#include <rte_memzone.h>
#include <rte_eal.h>
#include <rte_debug.h>
#include "eal_private.h"
#include "eal_internal_cfg.h"
enum timer_source eal_timer_source = EAL_TIMER_HPET;
/* The frequency of the RDTSC timer resolution */
static uint64_t eal_tsc_resolution_hz = 0;
#ifdef RTE_LIBEAL_USE_HPET
#define DEV_HPET "/dev/hpet"
/* Maximum number of counters. */
#define HPET_TIMER_NUM 3
/* General capabilities register */
#define CLK_PERIOD_SHIFT 32 /* Clock period shift. */
#define CLK_PERIOD_MASK 0xffffffff00000000ULL /* Clock period mask. */
/**
* HPET timer registers. From the Intel IA-PC HPET (High Precision Event
* Timers) Specification.
*/
struct eal_hpet_regs {
/* Memory-mapped, software visible registers */
uint64_t capabilities; /**< RO General Capabilities Register. */
uint64_t reserved0; /**< Reserved for future use. */
uint64_t config; /**< RW General Configuration Register. */
uint64_t reserved1; /**< Reserved for future use. */
uint64_t isr; /**< RW Clear General Interrupt Status. */
uint64_t reserved2[25]; /**< Reserved for future use. */
union {
uint64_t counter; /**< RW Main Counter Value Register. */
struct {
uint32_t counter_l; /**< RW Main Counter Low. */
uint32_t counter_h; /**< RW Main Counter High. */
};
};
uint64_t reserved3; /**< Reserved for future use. */
struct {
uint64_t config; /**< RW Timer Config and Capability Reg. */
uint64_t comp; /**< RW Timer Comparator Value Register. */
uint64_t fsb; /**< RW FSB Interrupt Route Register. */
uint64_t reserved4; /**< Reserved for future use. */
} timers[HPET_TIMER_NUM]; /**< Set of HPET timers. */
};
/* Mmap'd hpet registers */
static volatile struct eal_hpet_regs *eal_hpet = NULL;
/* Period at which the HPET counter increments in
* femtoseconds (10^-15 seconds). */
static uint32_t eal_hpet_resolution_fs = 0;
/* Frequency of the HPET counter in Hz */
static uint64_t eal_hpet_resolution_hz = 0;
/* Incremented 4 times during one 32bits hpet full count */
static uint32_t eal_hpet_msb;
static pthread_t msb_inc_thread_id;
/*
* This function runs on a specific thread to update a global variable
* containing used to process MSB of the HPET (unfortunatelly, we need
* this because hpet is 32 bits by default under linux).
*/
static void
hpet_msb_inc(__attribute__((unused)) void *arg)
{
uint32_t t;
while (1) {
t = (eal_hpet->counter_l >> 30);
if (t != (eal_hpet_msb & 3))
eal_hpet_msb ++;
sleep(10);
}
}
uint64_t
rte_get_hpet_hz(void)
{
if(internal_config.no_hpet)
rte_panic("Error, HPET called, but no HPET present\n");
return eal_hpet_resolution_hz;
}
uint64_t
rte_get_hpet_cycles(void)
{
uint32_t t, msb;
uint64_t ret;
if(internal_config.no_hpet)
rte_panic("Error, HPET called, but no HPET present\n");
t = eal_hpet->counter_l;
msb = eal_hpet_msb;
ret = (msb + 2 - (t >> 30)) / 4;
ret <<= 32;
ret += t;
return ret;
}
#endif
void
rte_delay_us(unsigned us)
{
const uint64_t start = rte_get_timer_cycles();
const uint64_t ticks = (uint64_t)us * rte_get_timer_hz() / 1E6;
while ((rte_get_timer_cycles() - start) < ticks)
rte_pause();
}
uint64_t
rte_get_tsc_hz(void)
{
return eal_tsc_resolution_hz;
}
#ifdef RTE_LIBEAL_USE_HPET
/*
* Open and mmap /dev/hpet (high precision event timer) that will
* provide our time reference.
*/
int
rte_eal_hpet_init(int make_default)
{
int fd, ret;
if (internal_config.no_hpet) {
RTE_LOG(INFO, EAL, "HPET is disabled\n");
return -1;
}
fd = open(DEV_HPET, O_RDONLY);
if (fd < 0) {
RTE_LOG(ERR, EAL, "ERROR: Cannot open "DEV_HPET": %s!\n",
strerror(errno));
internal_config.no_hpet = 1;
return -1;
}
eal_hpet = mmap(NULL, 1024, PROT_READ, MAP_SHARED, fd, 0);
if (eal_hpet == MAP_FAILED) {
RTE_LOG(ERR, EAL, "ERROR: Cannot mmap "DEV_HPET"!\n"
"Please enable CONFIG_HPET_MMAP in your kernel configuration "
"to allow HPET support.\n"
"To run without using HPET, set CONFIG_RTE_LIBEAL_USE_HPET=n "
"in your build configuration or use '--no-hpet' EAL flag.\n");
close(fd);
internal_config.no_hpet = 1;
return -1;
}
close(fd);
eal_hpet_resolution_fs = (uint32_t)((eal_hpet->capabilities &
CLK_PERIOD_MASK) >>
CLK_PERIOD_SHIFT);
eal_hpet_resolution_hz = (1000ULL*1000ULL*1000ULL*1000ULL*1000ULL) /
(uint64_t)eal_hpet_resolution_fs;
RTE_LOG(INFO, EAL, "HPET frequency is ~%"PRIu64" kHz\n",
eal_hpet_resolution_hz/1000);
eal_hpet_msb = (eal_hpet->counter_l >> 30);
/* create a thread that will increment a global variable for
* msb (hpet is 32 bits by default under linux) */
ret = pthread_create(&msb_inc_thread_id, NULL,
(void *(*)(void *))hpet_msb_inc, NULL);
if (ret < 0) {
RTE_LOG(ERR, EAL, "ERROR: Cannot create HPET timer thread!\n");
internal_config.no_hpet = 1;
return -1;
}
if (make_default)
eal_timer_source = EAL_TIMER_HPET;
return 0;
}
#endif
static int
set_tsc_freq_from_clock(void)
{
#ifdef CLOCK_MONOTONIC_RAW
#define NS_PER_SEC 1E9
struct timespec sleeptime = {.tv_nsec = 5E8 }; /* 1/2 second */
struct timespec t_start, t_end;
if (clock_gettime(CLOCK_MONOTONIC_RAW, &t_start) == 0) {
uint64_t ns, end, start = rte_rdtsc();
nanosleep(&sleeptime,NULL);
clock_gettime(CLOCK_MONOTONIC_RAW, &t_end);
end = rte_rdtsc();
ns = ((t_end.tv_sec - t_start.tv_sec) * NS_PER_SEC);
ns += (t_end.tv_nsec - t_start.tv_nsec);
double secs = (double)ns/NS_PER_SEC;
eal_tsc_resolution_hz = (uint64_t)((end - start)/secs);
return 0;
}
#endif
return -1;
}
static void
set_tsc_freq_fallback(void)
{
RTE_LOG(WARNING, EAL, "WARNING: clock_gettime cannot use "
"CLOCK_MONOTONIC_RAW and HPET is not available"
" - clock timings may be less accurate.\n");
/* assume that the sleep(1) will sleep for 1 second */
uint64_t start = rte_rdtsc();
sleep(1);
eal_tsc_resolution_hz = rte_rdtsc() - start;
}
/*
* This function measures the TSC frequency. It uses a variety of approaches.
*
* 1. If kernel provides CLOCK_MONOTONIC_RAW we use that to tune the TSC value
* 2. If kernel does not provide that, and we have HPET support, tune using HPET
* 3. Lastly, if neither of the above can be used, just sleep for 1 second and
* tune off that, printing a warning about inaccuracy of timing
*/
static void
set_tsc_freq(void)
{
if (set_tsc_freq_from_clock() < 0)
set_tsc_freq_fallback();
RTE_LOG(INFO, EAL, "TSC frequency is ~%"PRIu64" KHz\n",
eal_tsc_resolution_hz/1000);
}
int
rte_eal_timer_init(void)
{
eal_timer_source = EAL_TIMER_TSC;
set_tsc_freq();
return 0;
}
| gpl-2.0 |
ahsparrow/xcsoar_orig | src/Language/MOFile.cpp | 11 | 2685 | /*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2015 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 "MOFile.hpp"
#include <assert.h>
#include <string.h>
MOFile::MOFile(const void *_data, size_t _size)
:data((const uint8_t *)_data), size(_size), count(0) {
const struct mo_header *header = (const struct mo_header *)_data;
if (size < sizeof(*header))
return;
if (header->magic == 0x950412de)
native_byte_order = true;
else if (header->magic == 0xde120495)
native_byte_order = false;
else
/* invalid magic */
return;
unsigned n = import_uint32(header->num_strings);
if (n >= 0x100000)
return;
strings.ResizeDiscard(n);
const struct mo_table_entry *entry = (const struct mo_table_entry *)
(const void *)(data + import_uint32(header->original_table_offset));
for (unsigned i = 0; i < n; ++i) {
strings[i].original = get_string(entry++);
if (strings[i].original == NULL)
return;
}
entry = (const struct mo_table_entry *)(const void *)
(data + import_uint32(header->translation_table_offset));
for (unsigned i = 0; i < n; ++i) {
strings[i].translation = get_string(entry++);
if (strings[i].translation == NULL)
return;
}
count = n;
}
const char *
MOFile::lookup(const char *p) const
{
assert(p != NULL);
for (unsigned i = 0; i < count; ++i)
if (strcmp(strings[i].original, p) == 0)
return strings[i].translation;
return NULL;
}
const char *
MOFile::get_string(const struct mo_table_entry *entry) const
{
unsigned length = import_uint32(entry->length);
unsigned offset = import_uint32(entry->offset);
if (offset >= size || length >= size || (offset + length) >= size)
/* overflow */
return NULL;
const char *p = (const char *)(data + offset);
if (p[length] != 0 || strlen(p) != length)
/* invalid string */
return NULL;
return p;
}
| gpl-2.0 |
TobiasLohner/XCSoar | src/Device/Driver/Volkslogger/Declare.cpp | 11 | 5562 | /*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2015 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 "Internal.hpp"
#include "Protocol.hpp"
#include "Device/Port/Port.hpp"
#include "Device/Declaration.hpp"
#include "Operation/Operation.hpp"
#include "vlapi2.h"
#include "dbbconv.h"
#include "Engine/Waypoint/Waypoint.hpp"
#ifdef _UNICODE
#include <windows.h>
#endif
#include <algorithm>
static void
CopyToNarrowBuffer(char *dest, size_t max_size, const TCHAR *src)
{
#ifdef _UNICODE
size_t src_length = _tcslen(src);
if (src_length >= max_size)
src_length = max_size - 1;
int dest_length = WideCharToMultiByte(CP_ACP, 0, src, src_length,
dest, max_size - 1,
nullptr, nullptr);
if (dest_length < 0)
dest_length = 0;
dest[dest_length] = 0;
#else
strncpy(dest, src, max_size - 1);
dest[max_size - 1] = 0;
#endif
}
static void
CopyWaypoint(VLAPI_DATA::WPT &dest, const Waypoint &src)
{
CopyToNarrowBuffer(dest.name, sizeof(dest.name), src.name.c_str());
dest.location = src.location;
}
static void
CopyTurnPoint(VLAPI_DATA::DCLWPT &dest, const Declaration::TurnPoint &src)
{
CopyWaypoint(dest, src.waypoint);
switch (src.shape) {
case Declaration::TurnPoint::CYLINDER:
dest.oztyp = VLAPI_DATA::DCLWPT::OZTYP_CYLSKT;
dest.rz = src.radius;
dest.rs = 0;
break;
case Declaration::TurnPoint::DAEC_KEYHOLE:
dest.oztyp = VLAPI_DATA::DCLWPT::OZTYP_CYLSKT;
dest.lw = dest.rs = 10000;
dest.rz = 500;
break;
case Declaration::TurnPoint::SECTOR:
dest.oztyp = VLAPI_DATA::DCLWPT::OZTYP_CYLSKT;
dest.rs = src.radius;
dest.rz = 0;
break;
case Declaration::TurnPoint::LINE:
dest.oztyp = VLAPI_DATA::DCLWPT::OZTYP_LINE;
dest.lw = (src.radius*2)/1000; //Linewidth is radius*2 unit for lw is km
dest.rs = dest.rz = 0;
break;
}
/* auto direction */
dest.ws = 360;
}
static bool
DeclareInner(Port &port, const unsigned bulkrate,
const Declaration &declaration, const Waypoint *home,
OperationEnvironment &env)
{
assert(declaration.Size() >= 2);
if (!Volkslogger::ConnectAndFlush(port, env, 20000))
return false;
//Clear DECLARATION struct and populate with xcs declaration
VLAPI_DATA::DECLARATION vl_declaration;
memset(&vl_declaration, 0, sizeof(vl_declaration));
CopyToNarrowBuffer(vl_declaration.flightinfo.pilot,
sizeof(vl_declaration.flightinfo.pilot),
declaration.pilot_name);
CopyToNarrowBuffer(vl_declaration.flightinfo.gliderid,
sizeof(vl_declaration.flightinfo.gliderid),
declaration.aircraft_registration);
CopyToNarrowBuffer(vl_declaration.flightinfo.glidertype,
sizeof(vl_declaration.flightinfo.glidertype),
declaration.aircraft_type);
if (home != nullptr)
CopyWaypoint(vl_declaration.flightinfo.homepoint, *home);
// start..
CopyTurnPoint(vl_declaration.task.startpoint,
declaration.turnpoints.front());
// rest of task...
const unsigned n = std::min(declaration.Size() - 2, 12u);
for (unsigned i = 0; i < n; ++i)
CopyTurnPoint(vl_declaration.task.turnpoints[i],
declaration.turnpoints[i + 1]);
// Finish
CopyTurnPoint(vl_declaration.task.finishpoint,
declaration.turnpoints.back());
vl_declaration.task.nturnpoints = n;
//populate DBB structure with database(=block) read from logger
DBB dbb1;
if (Volkslogger::ReadDatabase(port, bulkrate, env,
dbb1.buffer, sizeof(dbb1.buffer)) <= 0)
return false;
//do NOT use the declaration(=fdf) from logger
memset(dbb1.GetFDF(), 0xff, dbb1.FRM_SIZE);
dbb1.open_dbb();
//update declaration section
vl_declaration.put(&dbb1);
// and write buffer back into VOLKSLOGGER
if (!Volkslogger::ConnectAndFlush(port, env, 10000))
return false;
const bool success =
Volkslogger::WriteDatabase(port, env, dbb1.buffer, sizeof(dbb1.buffer));
Volkslogger::Reset(port, env);
return success;
}
bool
VolksloggerDevice::Declare(const Declaration &declaration,
const Waypoint *home,
OperationEnvironment &env)
{
if (declaration.Size() < 2)
return false;
port.StopRxThread();
// change to IO mode baud rate
unsigned old_baud_rate = port.GetBaudrate();
if (old_baud_rate == 9600)
old_baud_rate = 0;
else if (old_baud_rate != 0 && !port.SetBaudrate(9600))
return false;
bool success = DeclareInner(port, bulkrate, declaration, home, env);
// restore baudrate
if (old_baud_rate != 0)
port.SetBaudrate(old_baud_rate);
return success;
}
| gpl-2.0 |
andyjhf/mini2440-linux-2.6.32.2 | arch/powerpc/platforms/cell/cbe_cpufreq.c | 779 | 4980 | /*
* cpufreq driver for the cell processor
*
* (C) Copyright IBM Deutschland Entwicklung GmbH 2005-2007
*
* Author: Christian Krafft <krafft@de.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/cpufreq.h>
#include <linux/of_platform.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/cell-regs.h>
#include "cbe_cpufreq.h"
static DEFINE_MUTEX(cbe_switch_mutex);
/* the CBE supports an 8 step frequency scaling */
static struct cpufreq_frequency_table cbe_freqs[] = {
{1, 0},
{2, 0},
{3, 0},
{4, 0},
{5, 0},
{6, 0},
{8, 0},
{10, 0},
{0, CPUFREQ_TABLE_END},
};
/*
* hardware specific functions
*/
static int set_pmode(unsigned int cpu, unsigned int slow_mode)
{
int rc;
if (cbe_cpufreq_has_pmi)
rc = cbe_cpufreq_set_pmode_pmi(cpu, slow_mode);
else
rc = cbe_cpufreq_set_pmode(cpu, slow_mode);
pr_debug("register contains slow mode %d\n", cbe_cpufreq_get_pmode(cpu));
return rc;
}
/*
* cpufreq functions
*/
static int cbe_cpufreq_cpu_init(struct cpufreq_policy *policy)
{
const u32 *max_freqp;
u32 max_freq;
int i, cur_pmode;
struct device_node *cpu;
cpu = of_get_cpu_node(policy->cpu, NULL);
if (!cpu)
return -ENODEV;
pr_debug("init cpufreq on CPU %d\n", policy->cpu);
/*
* Let's check we can actually get to the CELL regs
*/
if (!cbe_get_cpu_pmd_regs(policy->cpu) ||
!cbe_get_cpu_mic_tm_regs(policy->cpu)) {
pr_info("invalid CBE regs pointers for cpufreq\n");
return -EINVAL;
}
max_freqp = of_get_property(cpu, "clock-frequency", NULL);
of_node_put(cpu);
if (!max_freqp)
return -EINVAL;
/* we need the freq in kHz */
max_freq = *max_freqp / 1000;
pr_debug("max clock-frequency is at %u kHz\n", max_freq);
pr_debug("initializing frequency table\n");
/* initialize frequency table */
for (i=0; cbe_freqs[i].frequency!=CPUFREQ_TABLE_END; i++) {
cbe_freqs[i].frequency = max_freq / cbe_freqs[i].index;
pr_debug("%d: %d\n", i, cbe_freqs[i].frequency);
}
/* if DEBUG is enabled set_pmode() measures the latency
* of a transition */
policy->cpuinfo.transition_latency = 25000;
cur_pmode = cbe_cpufreq_get_pmode(policy->cpu);
pr_debug("current pmode is at %d\n",cur_pmode);
policy->cur = cbe_freqs[cur_pmode].frequency;
#ifdef CONFIG_SMP
cpumask_copy(policy->cpus, &per_cpu(cpu_sibling_map, policy->cpu));
#endif
cpufreq_frequency_table_get_attr(cbe_freqs, policy->cpu);
/* this ensures that policy->cpuinfo_min
* and policy->cpuinfo_max are set correctly */
return cpufreq_frequency_table_cpuinfo(policy, cbe_freqs);
}
static int cbe_cpufreq_cpu_exit(struct cpufreq_policy *policy)
{
cpufreq_frequency_table_put_attr(policy->cpu);
return 0;
}
static int cbe_cpufreq_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy, cbe_freqs);
}
static int cbe_cpufreq_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
int rc;
struct cpufreq_freqs freqs;
unsigned int cbe_pmode_new;
cpufreq_frequency_table_target(policy,
cbe_freqs,
target_freq,
relation,
&cbe_pmode_new);
freqs.old = policy->cur;
freqs.new = cbe_freqs[cbe_pmode_new].frequency;
freqs.cpu = policy->cpu;
mutex_lock(&cbe_switch_mutex);
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
pr_debug("setting frequency for cpu %d to %d kHz, " \
"1/%d of max frequency\n",
policy->cpu,
cbe_freqs[cbe_pmode_new].frequency,
cbe_freqs[cbe_pmode_new].index);
rc = set_pmode(policy->cpu, cbe_pmode_new);
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
mutex_unlock(&cbe_switch_mutex);
return rc;
}
static struct cpufreq_driver cbe_cpufreq_driver = {
.verify = cbe_cpufreq_verify,
.target = cbe_cpufreq_target,
.init = cbe_cpufreq_cpu_init,
.exit = cbe_cpufreq_cpu_exit,
.name = "cbe-cpufreq",
.owner = THIS_MODULE,
.flags = CPUFREQ_CONST_LOOPS,
};
/*
* module init and destoy
*/
static int __init cbe_cpufreq_init(void)
{
if (!machine_is(cell))
return -ENODEV;
return cpufreq_register_driver(&cbe_cpufreq_driver);
}
static void __exit cbe_cpufreq_exit(void)
{
cpufreq_unregister_driver(&cbe_cpufreq_driver);
}
module_init(cbe_cpufreq_init);
module_exit(cbe_cpufreq_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Christian Krafft <krafft@de.ibm.com>");
| gpl-2.0 |
drikinukoda/android_kernel_lge_e8lte | net/ipv6/icmp.c | 1035 | 23097 | /*
* Internet Control Message Protocol (ICMPv6)
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Based on net/ipv4/icmp.c
*
* RFC 1885
*
* 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:
*
* Andi Kleen : exception handling
* Andi Kleen add rate limits. never reply to a icmp.
* add more length checks and other fixes.
* yoshfuji : ensure to sent parameter problem for
* fragments.
* YOSHIFUJI Hideaki @USAGI: added sysctl for icmp rate limit.
* Randy Dunlap and
* YOSHIFUJI Hideaki @USAGI: Per-interface statistics support
* Kazunori MIYAZAWA @USAGI: change output process to use ip6_append_data
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/netfilter.h>
#include <linux/slab.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/icmpv6.h>
#include <net/ip.h>
#include <net/sock.h>
#include <net/ipv6.h>
#include <net/ip6_checksum.h>
#include <net/ping.h>
#include <net/protocol.h>
#include <net/raw.h>
#include <net/rawv6.h>
#include <net/transp_v6.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/inet_common.h>
#include <asm/uaccess.h>
/*
* The ICMP socket(s). This is the most convenient way to flow control
* our ICMP output as well as maintain a clean interface throughout
* all layers. All Socketless IP sends will soon be gone.
*
* On SMP we have one ICMP socket per-cpu.
*/
static inline struct sock *icmpv6_sk(struct net *net)
{
return net->ipv6.icmp_sk[smp_processor_id()];
}
static void icmpv6_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
/* icmpv6_notify checks 8 bytes can be pulled, icmp6hdr is 8 bytes */
struct icmp6hdr *icmp6 = (struct icmp6hdr *) (skb->data + offset);
if (!(type & ICMPV6_INFOMSG_MASK))
if (icmp6->icmp6_type == ICMPV6_ECHO_REQUEST)
ping_err(skb, offset, info);
}
static int icmpv6_rcv(struct sk_buff *skb);
static const struct inet6_protocol icmpv6_protocol = {
.handler = icmpv6_rcv,
.err_handler = icmpv6_err,
.flags = INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL,
};
static __inline__ struct sock *icmpv6_xmit_lock(struct net *net)
{
struct sock *sk;
local_bh_disable();
sk = icmpv6_sk(net);
if (unlikely(!spin_trylock(&sk->sk_lock.slock))) {
/* This can happen if the output path (f.e. SIT or
* ip6ip6 tunnel) signals dst_link_failure() for an
* outgoing ICMP6 packet.
*/
local_bh_enable();
return NULL;
}
return sk;
}
static __inline__ void icmpv6_xmit_unlock(struct sock *sk)
{
spin_unlock_bh(&sk->sk_lock.slock);
}
/*
* Slightly more convenient version of icmpv6_send.
*/
void icmpv6_param_prob(struct sk_buff *skb, u8 code, int pos)
{
icmpv6_send(skb, ICMPV6_PARAMPROB, code, pos);
kfree_skb(skb);
}
/*
* Figure out, may we reply to this packet with icmp error.
*
* We do not reply, if:
* - it was icmp error message.
* - it is truncated, so that it is known, that protocol is ICMPV6
* (i.e. in the middle of some exthdr)
*
* --ANK (980726)
*/
static int is_ineligible(struct sk_buff *skb)
{
int ptr = (u8 *)(ipv6_hdr(skb) + 1) - skb->data;
int len = skb->len - ptr;
__u8 nexthdr = ipv6_hdr(skb)->nexthdr;
__be16 frag_off;
if (len < 0)
return 1;
ptr = ipv6_skip_exthdr(skb, ptr, &nexthdr, &frag_off);
if (ptr < 0)
return 0;
if (nexthdr == IPPROTO_ICMPV6) {
u8 _type, *tp;
tp = skb_header_pointer(skb,
ptr+offsetof(struct icmp6hdr, icmp6_type),
sizeof(_type), &_type);
if (tp == NULL ||
!(*tp & ICMPV6_INFOMSG_MASK))
return 1;
}
return 0;
}
/*
* Check the ICMP output rate limit
*/
static inline bool icmpv6_xrlim_allow(struct sock *sk, u8 type,
struct flowi6 *fl6)
{
struct dst_entry *dst;
struct net *net = sock_net(sk);
bool res = false;
/* Informational messages are not limited. */
if (type & ICMPV6_INFOMSG_MASK)
return true;
/* Do not limit pmtu discovery, it would break it. */
if (type == ICMPV6_PKT_TOOBIG)
return true;
/*
* Look up the output route.
* XXX: perhaps the expire for routing entries cloned by
* this lookup should be more aggressive (not longer than timeout).
*/
dst = ip6_route_output(net, sk, fl6);
if (dst->error) {
IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_OUTNOROUTES);
} else if (dst->dev && (dst->dev->flags&IFF_LOOPBACK)) {
res = true;
} else {
struct rt6_info *rt = (struct rt6_info *)dst;
int tmo = net->ipv6.sysctl.icmpv6_time;
/* Give more bandwidth to wider prefixes. */
if (rt->rt6i_dst.plen < 128)
tmo >>= ((128 - rt->rt6i_dst.plen)>>5);
if (!rt->rt6i_peer)
rt6_bind_peer(rt, 1);
res = inet_peer_xrlim_allow(rt->rt6i_peer, tmo);
}
dst_release(dst);
return res;
}
/*
* an inline helper for the "simple" if statement below
* checks if parameter problem report is caused by an
* unrecognized IPv6 option that has the Option Type
* highest-order two bits set to 10
*/
static __inline__ int opt_unrec(struct sk_buff *skb, __u32 offset)
{
u8 _optval, *op;
offset += skb_network_offset(skb);
op = skb_header_pointer(skb, offset, sizeof(_optval), &_optval);
if (op == NULL)
return 1;
return (*op & 0xC0) == 0x80;
}
int icmpv6_push_pending_frames(struct sock *sk, struct flowi6 *fl6,
struct icmp6hdr *thdr, int len)
{
struct sk_buff *skb;
struct icmp6hdr *icmp6h;
int err = 0;
if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
goto out;
icmp6h = icmp6_hdr(skb);
memcpy(icmp6h, thdr, sizeof(struct icmp6hdr));
icmp6h->icmp6_cksum = 0;
if (skb_queue_len(&sk->sk_write_queue) == 1) {
skb->csum = csum_partial(icmp6h,
sizeof(struct icmp6hdr), skb->csum);
icmp6h->icmp6_cksum = csum_ipv6_magic(&fl6->saddr,
&fl6->daddr,
len, fl6->flowi6_proto,
skb->csum);
} else {
__wsum tmp_csum = 0;
skb_queue_walk(&sk->sk_write_queue, skb) {
tmp_csum = csum_add(tmp_csum, skb->csum);
}
tmp_csum = csum_partial(icmp6h,
sizeof(struct icmp6hdr), tmp_csum);
icmp6h->icmp6_cksum = csum_ipv6_magic(&fl6->saddr,
&fl6->daddr,
len, fl6->flowi6_proto,
tmp_csum);
}
ip6_push_pending_frames(sk);
out:
return err;
}
struct icmpv6_msg {
struct sk_buff *skb;
int offset;
uint8_t type;
};
static int icmpv6_getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb)
{
struct icmpv6_msg *msg = (struct icmpv6_msg *) from;
struct sk_buff *org_skb = msg->skb;
__wsum csum = 0;
csum = skb_copy_and_csum_bits(org_skb, msg->offset + offset,
to, len, csum);
skb->csum = csum_block_add(skb->csum, csum, odd);
if (!(msg->type & ICMPV6_INFOMSG_MASK))
nf_ct_attach(skb, org_skb);
return 0;
}
#if defined(CONFIG_IPV6_MIP6) || defined(CONFIG_IPV6_MIP6_MODULE)
static void mip6_addr_swap(struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
struct inet6_skb_parm *opt = IP6CB(skb);
struct ipv6_destopt_hao *hao;
struct in6_addr tmp;
int off;
if (opt->dsthao) {
off = ipv6_find_tlv(skb, opt->dsthao, IPV6_TLV_HAO);
if (likely(off >= 0)) {
hao = (struct ipv6_destopt_hao *)
(skb_network_header(skb) + off);
tmp = iph->saddr;
iph->saddr = hao->addr;
hao->addr = tmp;
}
}
}
#else
static inline void mip6_addr_swap(struct sk_buff *skb) {}
#endif
struct dst_entry *icmpv6_route_lookup(struct net *net, struct sk_buff *skb,
struct sock *sk, struct flowi6 *fl6)
{
struct dst_entry *dst, *dst2;
struct flowi6 fl2;
int err;
err = ip6_dst_lookup(sk, &dst, fl6);
if (err)
return ERR_PTR(err);
/*
* We won't send icmp if the destination is known
* anycast.
*/
if (((struct rt6_info *)dst)->rt6i_flags & RTF_ANYCAST) {
LIMIT_NETDEBUG(KERN_DEBUG "icmpv6_send: acast source\n");
dst_release(dst);
return ERR_PTR(-EINVAL);
}
/* No need to clone since we're just using its address. */
dst2 = dst;
dst = xfrm_lookup(net, dst, flowi6_to_flowi(fl6), sk, 0);
if (!IS_ERR(dst)) {
if (dst != dst2)
return dst;
} else {
if (PTR_ERR(dst) == -EPERM)
dst = NULL;
else
return dst;
}
err = xfrm_decode_session_reverse(skb, flowi6_to_flowi(&fl2), AF_INET6);
if (err)
goto relookup_failed;
err = ip6_dst_lookup(sk, &dst2, &fl2);
if (err)
goto relookup_failed;
dst2 = xfrm_lookup(net, dst2, flowi6_to_flowi(&fl2), sk, XFRM_LOOKUP_ICMP);
if (!IS_ERR(dst2)) {
dst_release(dst);
dst = dst2;
} else {
err = PTR_ERR(dst2);
if (err == -EPERM) {
dst_release(dst);
return dst2;
} else
goto relookup_failed;
}
relookup_failed:
if (dst)
return dst;
return ERR_PTR(err);
}
/*
* Send an ICMP message in response to a packet in error
*/
void icmpv6_send(struct sk_buff *skb, u8 type, u8 code, __u32 info)
{
struct net *net = dev_net(skb->dev);
struct inet6_dev *idev = NULL;
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct sock *sk;
struct ipv6_pinfo *np;
const struct in6_addr *saddr = NULL;
struct dst_entry *dst;
struct icmp6hdr tmp_hdr;
struct flowi6 fl6;
struct icmpv6_msg msg;
int iif = 0;
int addr_type = 0;
int len;
int hlimit;
int err = 0;
u32 mark = IP6_REPLY_MARK(net, skb->mark);
if ((u8 *)hdr < skb->head ||
(skb->network_header + sizeof(*hdr)) > skb->tail)
return;
/*
* Make sure we respect the rules
* i.e. RFC 1885 2.4(e)
* Rule (e.1) is enforced by not using icmpv6_send
* in any code that processes icmp errors.
*/
addr_type = ipv6_addr_type(&hdr->daddr);
if (ipv6_chk_addr(net, &hdr->daddr, skb->dev, 0))
saddr = &hdr->daddr;
/*
* Dest addr check
*/
if ((addr_type & IPV6_ADDR_MULTICAST || skb->pkt_type != PACKET_HOST)) {
if (type != ICMPV6_PKT_TOOBIG &&
!(type == ICMPV6_PARAMPROB &&
code == ICMPV6_UNK_OPTION &&
(opt_unrec(skb, info))))
return;
saddr = NULL;
}
addr_type = ipv6_addr_type(&hdr->saddr);
/*
* Source addr check
*/
if (addr_type & IPV6_ADDR_LINKLOCAL)
iif = skb->dev->ifindex;
/*
* Must not send error if the source does not uniquely
* identify a single node (RFC2463 Section 2.4).
* We check unspecified / multicast addresses here,
* and anycast addresses will be checked later.
*/
if ((addr_type == IPV6_ADDR_ANY) || (addr_type & IPV6_ADDR_MULTICAST)) {
LIMIT_NETDEBUG(KERN_DEBUG "icmpv6_send: addr_any/mcast source\n");
return;
}
/*
* Never answer to a ICMP packet.
*/
if (is_ineligible(skb)) {
LIMIT_NETDEBUG(KERN_DEBUG "icmpv6_send: no reply to icmp error\n");
return;
}
mip6_addr_swap(skb);
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_ICMPV6;
fl6.daddr = hdr->saddr;
if (saddr)
fl6.saddr = *saddr;
fl6.flowi6_mark = mark;
fl6.flowi6_oif = iif;
fl6.fl6_icmp_type = type;
fl6.fl6_icmp_code = code;
security_skb_classify_flow(skb, flowi6_to_flowi(&fl6));
sk = icmpv6_xmit_lock(net);
if (sk == NULL)
return;
sk->sk_mark = mark;
np = inet6_sk(sk);
if (!icmpv6_xrlim_allow(sk, type, &fl6))
goto out;
tmp_hdr.icmp6_type = type;
tmp_hdr.icmp6_code = code;
tmp_hdr.icmp6_cksum = 0;
tmp_hdr.icmp6_pointer = htonl(info);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
dst = icmpv6_route_lookup(net, skb, sk, &fl6);
if (IS_ERR(dst))
goto out;
if (ipv6_addr_is_multicast(&fl6.daddr))
hlimit = np->mcast_hops;
else
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
msg.skb = skb;
msg.offset = skb_network_offset(skb);
msg.type = type;
len = skb->len - msg.offset;
len = min_t(unsigned int, len, IPV6_MIN_MTU - sizeof(struct ipv6hdr) -sizeof(struct icmp6hdr));
if (len < 0) {
LIMIT_NETDEBUG(KERN_DEBUG "icmp: len problem\n");
goto out_dst_release;
}
rcu_read_lock();
idev = __in6_dev_get(skb->dev);
err = ip6_append_data(sk, icmpv6_getfrag, &msg,
len + sizeof(struct icmp6hdr),
sizeof(struct icmp6hdr), hlimit,
np->tclass, NULL, &fl6, (struct rt6_info*)dst,
MSG_DONTWAIT, np->dontfrag);
if (err) {
ICMP6_INC_STATS_BH(net, idev, ICMP6_MIB_OUTERRORS);
ip6_flush_pending_frames(sk);
} else {
err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr,
len + sizeof(struct icmp6hdr));
}
rcu_read_unlock();
out_dst_release:
dst_release(dst);
out:
icmpv6_xmit_unlock(sk);
}
EXPORT_SYMBOL(icmpv6_send);
static void icmpv6_echo_reply(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct sock *sk;
struct inet6_dev *idev;
struct ipv6_pinfo *np;
const struct in6_addr *saddr = NULL;
struct icmp6hdr *icmph = icmp6_hdr(skb);
struct icmp6hdr tmp_hdr;
struct flowi6 fl6;
struct icmpv6_msg msg;
struct dst_entry *dst;
int err = 0;
int hlimit;
u32 mark = IP6_REPLY_MARK(net, skb->mark);
saddr = &ipv6_hdr(skb)->daddr;
if (!ipv6_unicast_destination(skb))
saddr = NULL;
memcpy(&tmp_hdr, icmph, sizeof(tmp_hdr));
tmp_hdr.icmp6_type = ICMPV6_ECHO_REPLY;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_ICMPV6;
fl6.daddr = ipv6_hdr(skb)->saddr;
if (saddr)
fl6.saddr = *saddr;
fl6.flowi6_oif = skb->dev->ifindex;
fl6.fl6_icmp_type = ICMPV6_ECHO_REPLY;
fl6.flowi6_mark = mark;
security_skb_classify_flow(skb, flowi6_to_flowi(&fl6));
sk = icmpv6_xmit_lock(net);
if (sk == NULL)
return;
sk->sk_mark = mark;
np = inet6_sk(sk);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
err = ip6_dst_lookup(sk, &dst, &fl6);
if (err)
goto out;
dst = xfrm_lookup(net, dst, flowi6_to_flowi(&fl6), sk, 0);
if (IS_ERR(dst))
goto out;
if (ipv6_addr_is_multicast(&fl6.daddr))
hlimit = np->mcast_hops;
else
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
idev = __in6_dev_get(skb->dev);
msg.skb = skb;
msg.offset = 0;
msg.type = ICMPV6_ECHO_REPLY;
err = ip6_append_data(sk, icmpv6_getfrag, &msg, skb->len + sizeof(struct icmp6hdr),
sizeof(struct icmp6hdr), hlimit, np->tclass, NULL, &fl6,
(struct rt6_info*)dst, MSG_DONTWAIT,
np->dontfrag);
if (err) {
ICMP6_INC_STATS_BH(net, idev, ICMP6_MIB_OUTERRORS);
ip6_flush_pending_frames(sk);
} else {
err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr,
skb->len + sizeof(struct icmp6hdr));
}
dst_release(dst);
out:
icmpv6_xmit_unlock(sk);
}
void icmpv6_notify(struct sk_buff *skb, u8 type, u8 code, __be32 info)
{
const struct inet6_protocol *ipprot;
int inner_offset;
int hash;
u8 nexthdr;
__be16 frag_off;
if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
return;
nexthdr = ((struct ipv6hdr *)skb->data)->nexthdr;
if (ipv6_ext_hdr(nexthdr)) {
/* now skip over extension headers */
inner_offset = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr),
&nexthdr, &frag_off);
if (inner_offset<0)
return;
} else {
inner_offset = sizeof(struct ipv6hdr);
}
/* Checkin header including 8 bytes of inner protocol header. */
if (!pskb_may_pull(skb, inner_offset+8))
return;
/* BUGGG_FUTURE: we should try to parse exthdrs in this packet.
Without this we will not able f.e. to make source routed
pmtu discovery.
Corresponding argument (opt) to notifiers is already added.
--ANK (980726)
*/
hash = nexthdr & (MAX_INET_PROTOS - 1);
rcu_read_lock();
ipprot = rcu_dereference(inet6_protos[hash]);
if (ipprot && ipprot->err_handler)
ipprot->err_handler(skb, NULL, type, code, inner_offset, info);
rcu_read_unlock();
raw6_icmp_error(skb, nexthdr, type, code, inner_offset, info);
}
/*
* Handle icmp messages
*/
static int icmpv6_rcv(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct inet6_dev *idev = __in6_dev_get(dev);
const struct in6_addr *saddr, *daddr;
const struct ipv6hdr *orig_hdr;
struct icmp6hdr *hdr;
u8 type;
if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) {
struct sec_path *sp = skb_sec_path(skb);
int nh;
if (!(sp && sp->xvec[sp->len - 1]->props.flags &
XFRM_STATE_ICMP))
goto drop_no_count;
if (!pskb_may_pull(skb, sizeof(*hdr) + sizeof(*orig_hdr)))
goto drop_no_count;
nh = skb_network_offset(skb);
skb_set_network_header(skb, sizeof(*hdr));
if (!xfrm6_policy_check_reverse(NULL, XFRM_POLICY_IN, skb))
goto drop_no_count;
skb_set_network_header(skb, nh);
}
ICMP6_INC_STATS_BH(dev_net(dev), idev, ICMP6_MIB_INMSGS);
saddr = &ipv6_hdr(skb)->saddr;
daddr = &ipv6_hdr(skb)->daddr;
/* Perform checksum. */
switch (skb->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_ipv6_magic(saddr, daddr, skb->len, IPPROTO_ICMPV6,
skb->csum))
break;
/* fall through */
case CHECKSUM_NONE:
skb->csum = ~csum_unfold(csum_ipv6_magic(saddr, daddr, skb->len,
IPPROTO_ICMPV6, 0));
if (__skb_checksum_complete(skb)) {
LIMIT_NETDEBUG(KERN_DEBUG
"ICMPv6 checksum failed [%pI6c > %pI6c]\n",
saddr, daddr);
goto discard_it;
}
}
if (!pskb_pull(skb, sizeof(*hdr)))
goto discard_it;
hdr = icmp6_hdr(skb);
type = hdr->icmp6_type;
ICMP6MSGIN_INC_STATS_BH(dev_net(dev), idev, type);
switch (type) {
case ICMPV6_ECHO_REQUEST:
icmpv6_echo_reply(skb);
break;
case ICMPV6_ECHO_REPLY:
ping_rcv(skb);
break;
case ICMPV6_PKT_TOOBIG:
/* BUGGG_FUTURE: if packet contains rthdr, we cannot update
standard destination cache. Seems, only "advanced"
destination cache will allow to solve this problem
--ANK (980726)
*/
if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
goto discard_it;
hdr = icmp6_hdr(skb);
orig_hdr = (struct ipv6hdr *) (hdr + 1);
rt6_pmtu_discovery(&orig_hdr->daddr, &orig_hdr->saddr, dev,
ntohl(hdr->icmp6_mtu));
/*
* Drop through to notify
*/
case ICMPV6_DEST_UNREACH:
case ICMPV6_TIME_EXCEED:
case ICMPV6_PARAMPROB:
icmpv6_notify(skb, type, hdr->icmp6_code, hdr->icmp6_mtu);
break;
case NDISC_ROUTER_SOLICITATION:
case NDISC_ROUTER_ADVERTISEMENT:
case NDISC_NEIGHBOUR_SOLICITATION:
case NDISC_NEIGHBOUR_ADVERTISEMENT:
case NDISC_REDIRECT:
ndisc_rcv(skb);
break;
case ICMPV6_MGM_QUERY:
igmp6_event_query(skb);
break;
case ICMPV6_MGM_REPORT:
igmp6_event_report(skb);
break;
case ICMPV6_MGM_REDUCTION:
case ICMPV6_NI_QUERY:
case ICMPV6_NI_REPLY:
case ICMPV6_MLD2_REPORT:
case ICMPV6_DHAAD_REQUEST:
case ICMPV6_DHAAD_REPLY:
case ICMPV6_MOBILE_PREFIX_SOL:
case ICMPV6_MOBILE_PREFIX_ADV:
break;
default:
LIMIT_NETDEBUG(KERN_DEBUG "icmpv6: msg of unknown type\n");
/* informational */
if (type & ICMPV6_INFOMSG_MASK)
break;
/*
* error of unknown type.
* must pass to upper level
*/
icmpv6_notify(skb, type, hdr->icmp6_code, hdr->icmp6_mtu);
}
kfree_skb(skb);
return 0;
discard_it:
ICMP6_INC_STATS_BH(dev_net(dev), idev, ICMP6_MIB_INERRORS);
drop_no_count:
kfree_skb(skb);
return 0;
}
void icmpv6_flow_init(struct sock *sk, struct flowi6 *fl6,
u8 type,
const struct in6_addr *saddr,
const struct in6_addr *daddr,
int oif)
{
memset(fl6, 0, sizeof(*fl6));
fl6->saddr = *saddr;
fl6->daddr = *daddr;
fl6->flowi6_proto = IPPROTO_ICMPV6;
fl6->fl6_icmp_type = type;
fl6->fl6_icmp_code = 0;
fl6->flowi6_oif = oif;
security_sk_classify_flow(sk, flowi6_to_flowi(fl6));
}
/*
* Special lock-class for __icmpv6_sk:
*/
static struct lock_class_key icmpv6_socket_sk_dst_lock_key;
static int __net_init icmpv6_sk_init(struct net *net)
{
struct sock *sk;
int err, i, j;
net->ipv6.icmp_sk =
kzalloc(nr_cpu_ids * sizeof(struct sock *), GFP_KERNEL);
if (net->ipv6.icmp_sk == NULL)
return -ENOMEM;
for_each_possible_cpu(i) {
err = inet_ctl_sock_create(&sk, PF_INET6,
SOCK_RAW, IPPROTO_ICMPV6, net);
if (err < 0) {
printk(KERN_ERR
"Failed to initialize the ICMP6 control socket "
"(err %d).\n",
err);
goto fail;
}
net->ipv6.icmp_sk[i] = sk;
/*
* Split off their lock-class, because sk->sk_dst_lock
* gets used from softirqs, which is safe for
* __icmpv6_sk (because those never get directly used
* via userspace syscalls), but unsafe for normal sockets.
*/
lockdep_set_class(&sk->sk_dst_lock,
&icmpv6_socket_sk_dst_lock_key);
/* Enough space for 2 64K ICMP packets, including
* sk_buff struct overhead.
*/
sk->sk_sndbuf = 2 * SKB_TRUESIZE(64 * 1024);
}
return 0;
fail:
for (j = 0; j < i; j++)
inet_ctl_sock_destroy(net->ipv6.icmp_sk[j]);
kfree(net->ipv6.icmp_sk);
return err;
}
static void __net_exit icmpv6_sk_exit(struct net *net)
{
int i;
for_each_possible_cpu(i) {
inet_ctl_sock_destroy(net->ipv6.icmp_sk[i]);
}
kfree(net->ipv6.icmp_sk);
}
static struct pernet_operations icmpv6_sk_ops = {
.init = icmpv6_sk_init,
.exit = icmpv6_sk_exit,
};
int __init icmpv6_init(void)
{
int err;
err = register_pernet_subsys(&icmpv6_sk_ops);
if (err < 0)
return err;
err = -EAGAIN;
if (inet6_add_protocol(&icmpv6_protocol, IPPROTO_ICMPV6) < 0)
goto fail;
return 0;
fail:
printk(KERN_ERR "Failed to register ICMP6 protocol\n");
unregister_pernet_subsys(&icmpv6_sk_ops);
return err;
}
void icmpv6_cleanup(void)
{
unregister_pernet_subsys(&icmpv6_sk_ops);
inet6_del_protocol(&icmpv6_protocol, IPPROTO_ICMPV6);
}
static const struct icmp6_err {
int err;
int fatal;
} tab_unreach[] = {
{ /* NOROUTE */
.err = ENETUNREACH,
.fatal = 0,
},
{ /* ADM_PROHIBITED */
.err = EACCES,
.fatal = 1,
},
{ /* Was NOT_NEIGHBOUR, now reserved */
.err = EHOSTUNREACH,
.fatal = 0,
},
{ /* ADDR_UNREACH */
.err = EHOSTUNREACH,
.fatal = 0,
},
{ /* PORT_UNREACH */
.err = ECONNREFUSED,
.fatal = 1,
},
};
int icmpv6_err_convert(u8 type, u8 code, int *err)
{
int fatal = 0;
*err = EPROTO;
switch (type) {
case ICMPV6_DEST_UNREACH:
fatal = 1;
if (code <= ICMPV6_PORT_UNREACH) {
*err = tab_unreach[code].err;
fatal = tab_unreach[code].fatal;
}
break;
case ICMPV6_PKT_TOOBIG:
*err = EMSGSIZE;
break;
case ICMPV6_PARAMPROB:
*err = EPROTO;
fatal = 1;
break;
case ICMPV6_TIME_EXCEED:
*err = EHOSTUNREACH;
break;
}
return fatal;
}
EXPORT_SYMBOL(icmpv6_err_convert);
#ifdef CONFIG_SYSCTL
ctl_table ipv6_icmp_table_template[] = {
{
.procname = "ratelimit",
.data = &init_net.ipv6.sysctl.icmpv6_time,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{ },
};
struct ctl_table * __net_init ipv6_icmp_sysctl_init(struct net *net)
{
struct ctl_table *table;
table = kmemdup(ipv6_icmp_table_template,
sizeof(ipv6_icmp_table_template),
GFP_KERNEL);
if (table)
table[0].data = &net->ipv6.sysctl.icmpv6_time;
return table;
}
#endif
| gpl-2.0 |
corcor67/SMPL_M8_GPE | drivers/platform/msm/ipa/ipa_dp.c | 1803 | 38583 | /* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dmapool.h>
#include <linux/list.h>
#include <linux/netdevice.h>
#include "ipa_i.h"
#define list_next_entry(pos, member) \
list_entry(pos->member.next, typeof(*pos), member)
#define IPA_LAST_DESC_CNT 0xFFFF
#define POLLING_INACTIVITY_RX 40
#define POLLING_MIN_SLEEP_RX 950
#define POLLING_MAX_SLEEP_RX 1050
#define POLLING_INACTIVITY_TX 40
#define POLLING_MIN_SLEEP_TX 400
#define POLLING_MAX_SLEEP_TX 500
static void replenish_rx_work_func(struct work_struct *work);
static struct delayed_work replenish_rx_work;
static void ipa_wq_handle_rx(struct work_struct *work);
static DECLARE_WORK(rx_work, ipa_wq_handle_rx);
static void ipa_wq_handle_tx(struct work_struct *work);
static DECLARE_WORK(tx_work, ipa_wq_handle_tx);
/**
* ipa_write_done() - this function will be (eventually) called when a Tx
* operation is complete
* * @work: work_struct used by the work queue
*
* Will be called in deferred context.
* - invoke the callback supplied by the client who sent this command
* - iterate over all packets and validate that
* the order for sent packet is the same as expected
* - delete all the tx packet descriptors from the system
* pipe context (not needed anymore)
* - return the tx buffer back to dma_pool
*/
void ipa_wq_write_done(struct work_struct *work)
{
struct ipa_tx_pkt_wrapper *tx_pkt;
struct ipa_tx_pkt_wrapper *tx_pkt_expected;
unsigned long irq_flags;
tx_pkt = container_of(work, struct ipa_tx_pkt_wrapper, work);
if (unlikely(tx_pkt == NULL))
WARN_ON(1);
WARN_ON(tx_pkt->cnt != 1);
spin_lock_irqsave(&tx_pkt->sys->spinlock, irq_flags);
tx_pkt_expected = list_first_entry(&tx_pkt->sys->head_desc_list,
struct ipa_tx_pkt_wrapper,
link);
if (unlikely(tx_pkt != tx_pkt_expected)) {
spin_unlock_irqrestore(&tx_pkt->sys->spinlock,
irq_flags);
WARN_ON(1);
}
list_del(&tx_pkt->link);
spin_unlock_irqrestore(&tx_pkt->sys->spinlock, irq_flags);
if (unlikely(ipa_ctx->ipa_hw_type == IPA_HW_v1_0)) {
dma_pool_free(ipa_ctx->dma_pool,
tx_pkt->bounce,
tx_pkt->mem.phys_base);
} else {
dma_unmap_single(NULL, tx_pkt->mem.phys_base,
tx_pkt->mem.size,
DMA_TO_DEVICE);
}
if (tx_pkt->callback)
tx_pkt->callback(tx_pkt->user1, tx_pkt->user2);
kmem_cache_free(ipa_ctx->tx_pkt_wrapper_cache, tx_pkt);
}
int ipa_handle_tx_core(struct ipa_sys_context *sys, bool process_all,
bool in_poll_state)
{
struct ipa_tx_pkt_wrapper *tx_pkt;
struct sps_iovec iov;
int ret;
int cnt = 0;
unsigned long irq_flags;
while ((in_poll_state ? atomic_read(&sys->curr_polling_state) :
!atomic_read(&sys->curr_polling_state))) {
if (cnt && !process_all)
break;
ret = sps_get_iovec(sys->ep->ep_hdl, &iov);
if (ret) {
IPAERR("sps_get_iovec failed %d\n", ret);
break;
}
if (iov.addr == 0)
break;
if (unlikely(list_empty(&sys->head_desc_list)))
continue;
spin_lock_irqsave(&sys->spinlock, irq_flags);
tx_pkt = list_first_entry(&sys->head_desc_list,
struct ipa_tx_pkt_wrapper, link);
sys->len--;
list_del(&tx_pkt->link);
spin_unlock_irqrestore(&sys->spinlock, irq_flags);
IPADBG("--curr_cnt=%d\n", sys->len);
if (unlikely(ipa_ctx->ipa_hw_type == IPA_HW_v1_0))
dma_pool_free(ipa_ctx->dma_pool,
tx_pkt->bounce,
tx_pkt->mem.phys_base);
else
dma_unmap_single(NULL, tx_pkt->mem.phys_base,
tx_pkt->mem.size,
DMA_TO_DEVICE);
if (tx_pkt->callback)
tx_pkt->callback(tx_pkt->user1, tx_pkt->user2);
if (tx_pkt->cnt > 1 && tx_pkt->cnt != IPA_LAST_DESC_CNT)
dma_pool_free(ipa_ctx->dma_pool, tx_pkt->mult.base,
tx_pkt->mult.phys_base);
kmem_cache_free(ipa_ctx->tx_pkt_wrapper_cache, tx_pkt);
cnt++;
};
return cnt;
}
/**
* ipa_tx_switch_to_intr_mode() - Operate the Tx data path in interrupt mode
*/
static void ipa_tx_switch_to_intr_mode(struct ipa_sys_context *sys)
{
int ret;
if (!atomic_read(&sys->curr_polling_state)) {
IPAERR("already in intr mode\n");
goto fail;
}
ret = sps_get_config(sys->ep->ep_hdl, &sys->ep->connect);
if (ret) {
IPAERR("sps_get_config() failed %d\n", ret);
goto fail;
}
sys->event.options = SPS_O_EOT;
ret = sps_register_event(sys->ep->ep_hdl, &sys->event);
if (ret) {
IPAERR("sps_register_event() failed %d\n", ret);
goto fail;
}
sys->ep->connect.options =
SPS_O_AUTO_ENABLE | SPS_O_ACK_TRANSFERS | SPS_O_EOT;
ret = sps_set_config(sys->ep->ep_hdl, &sys->ep->connect);
if (ret) {
IPAERR("sps_set_config() failed %d\n", ret);
goto fail;
}
atomic_set(&sys->curr_polling_state, 0);
ipa_handle_tx_core(sys, true, false);
return;
fail:
IPA_STATS_INC_CNT(ipa_ctx->stats.x_intr_repost_tx);
schedule_delayed_work(&sys->switch_to_intr_work, msecs_to_jiffies(1));
return;
}
static void ipa_handle_tx(struct ipa_sys_context *sys)
{
int inactive_cycles = 0;
int cnt;
ipa_inc_client_enable_clks();
do {
cnt = ipa_handle_tx_core(sys, true, true);
if (cnt == 0) {
inactive_cycles++;
usleep_range(POLLING_MIN_SLEEP_TX,
POLLING_MAX_SLEEP_TX);
} else {
inactive_cycles = 0;
}
} while (inactive_cycles <= POLLING_INACTIVITY_TX);
ipa_tx_switch_to_intr_mode(sys);
ipa_dec_client_disable_clks();
}
static void ipa_wq_handle_tx(struct work_struct *work)
{
ipa_handle_tx(&ipa_ctx->sys[IPA_A5_LAN_WAN_OUT]);
}
/**
* ipa_send_one() - Send a single descriptor
* @sys: system pipe context
* @desc: descriptor to send
* @in_atomic: whether caller is in atomic context
*
* - Allocate tx_packet wrapper
* - Allocate a bounce buffer due to HW constrains
* (This buffer will be used for the DMA command)
* - Copy the data (desc->pyld) to the bounce buffer
* - transfer data to the IPA
* - after the transfer was done the SPS will
* notify the sending user via ipa_sps_irq_comp_tx()
*
* Return codes: 0: success, -EFAULT: failure
*/
int ipa_send_one(struct ipa_sys_context *sys, struct ipa_desc *desc,
bool in_atomic)
{
struct ipa_tx_pkt_wrapper *tx_pkt;
unsigned long irq_flags;
int result;
u16 sps_flags = SPS_IOVEC_FLAG_EOT;
dma_addr_t dma_address;
u16 len;
u32 mem_flag = GFP_ATOMIC;
if (unlikely(!in_atomic))
mem_flag = GFP_KERNEL;
tx_pkt = kmem_cache_zalloc(ipa_ctx->tx_pkt_wrapper_cache, mem_flag);
if (!tx_pkt) {
IPAERR("failed to alloc tx wrapper\n");
goto fail_mem_alloc;
}
if (unlikely(ipa_ctx->ipa_hw_type == IPA_HW_v1_0)) {
WARN_ON(desc->len > 512);
/*
* Due to a HW limitation, we need to make sure that the packet
* does not cross a 1KB boundary
*/
tx_pkt->bounce = dma_pool_alloc(
ipa_ctx->dma_pool,
mem_flag, &dma_address);
if (!tx_pkt->bounce) {
dma_address = 0;
} else {
WARN_ON(!ipa_straddle_boundary
((u32)dma_address,
(u32)dma_address + desc->len - 1,
1024));
memcpy(tx_pkt->bounce, desc->pyld, desc->len);
}
} else {
dma_address = dma_map_single(NULL, desc->pyld, desc->len,
DMA_TO_DEVICE);
}
if (!dma_address) {
IPAERR("failed to DMA wrap\n");
goto fail_dma_map;
}
INIT_LIST_HEAD(&tx_pkt->link);
tx_pkt->type = desc->type;
tx_pkt->cnt = 1; /* only 1 desc in this "set" */
tx_pkt->mem.phys_base = dma_address;
tx_pkt->mem.base = desc->pyld;
tx_pkt->mem.size = desc->len;
tx_pkt->sys = sys;
tx_pkt->callback = desc->callback;
tx_pkt->user1 = desc->user1;
tx_pkt->user2 = desc->user2;
/*
* Special treatment for immediate commands, where the structure of the
* descriptor is different
*/
if (desc->type == IPA_IMM_CMD_DESC) {
sps_flags |= SPS_IOVEC_FLAG_IMME;
len = desc->opcode;
IPADBG("sending cmd=%d pyld_len=%d sps_flags=%x\n",
desc->opcode, desc->len, sps_flags);
IPA_DUMP_BUFF(desc->pyld, dma_address, desc->len);
} else {
len = desc->len;
}
INIT_WORK(&tx_pkt->work, ipa_wq_write_done);
spin_lock_irqsave(&sys->spinlock, irq_flags);
list_add_tail(&tx_pkt->link, &sys->head_desc_list);
result = sps_transfer_one(sys->ep->ep_hdl, dma_address, len, tx_pkt,
sps_flags);
if (result) {
IPAERR("sps_transfer_one failed rc=%d\n", result);
goto fail_sps_send;
}
spin_unlock_irqrestore(&sys->spinlock, irq_flags);
return 0;
fail_sps_send:
list_del(&tx_pkt->link);
spin_unlock_irqrestore(&sys->spinlock, irq_flags);
if (unlikely(ipa_ctx->ipa_hw_type == IPA_HW_v1_0))
dma_pool_free(ipa_ctx->dma_pool, tx_pkt->bounce,
dma_address);
else
dma_unmap_single(NULL, dma_address, desc->len, DMA_TO_DEVICE);
fail_dma_map:
kmem_cache_free(ipa_ctx->tx_pkt_wrapper_cache, tx_pkt);
fail_mem_alloc:
return -EFAULT;
}
/**
* ipa_send() - Send multiple descriptors in one HW transaction
* @sys: system pipe context
* @num_desc: number of packets
* @desc: packets to send (may be immediate command or data)
* @in_atomic: whether caller is in atomic context
*
* This function is used for system-to-bam connection.
* - SPS driver expect struct sps_transfer which will contain all the data
* for a transaction
* - The sps_transfer struct will be pointing to bounce buffers for
* its DMA command (immediate command and data)
* - ipa_tx_pkt_wrapper will be used for each ipa
* descriptor (allocated from wrappers cache)
* - The wrapper struct will be configured for each ipa-desc payload and will
* contain information which will be later used by the user callbacks
* - each transfer will be made by calling to sps_transfer()
* - Each packet (command or data) that will be sent will also be saved in
* ipa_sys_context for later check that all data was sent
*
* Return codes: 0: success, -EFAULT: failure
*/
int ipa_send(struct ipa_sys_context *sys, u32 num_desc, struct ipa_desc *desc,
bool in_atomic)
{
struct ipa_tx_pkt_wrapper *tx_pkt;
struct ipa_tx_pkt_wrapper *next_pkt;
struct sps_transfer transfer = { 0 };
struct sps_iovec *iovec;
unsigned long irq_flags;
dma_addr_t dma_addr;
int i = 0;
int j;
int result;
int fail_dma_wrap = 0;
uint size = num_desc * sizeof(struct sps_iovec);
u32 mem_flag = GFP_ATOMIC;
if (unlikely(!in_atomic))
mem_flag = GFP_KERNEL;
transfer.iovec = dma_pool_alloc(ipa_ctx->dma_pool, mem_flag, &dma_addr);
transfer.iovec_phys = dma_addr;
transfer.iovec_count = num_desc;
spin_lock_irqsave(&sys->spinlock, irq_flags);
if (!transfer.iovec) {
IPAERR("fail to alloc DMA mem for sps xfr buff\n");
goto failure_coherent;
}
for (i = 0; i < num_desc; i++) {
fail_dma_wrap = 0;
tx_pkt = kmem_cache_zalloc(ipa_ctx->tx_pkt_wrapper_cache,
mem_flag);
if (!tx_pkt) {
IPAERR("failed to alloc tx wrapper\n");
goto failure;
}
/*
* first desc of set is "special" as it holds the count and
* other info
*/
if (i == 0) {
transfer.user = tx_pkt;
tx_pkt->mult.phys_base = dma_addr;
tx_pkt->mult.base = transfer.iovec;
tx_pkt->mult.size = size;
tx_pkt->cnt = num_desc;
}
iovec = &transfer.iovec[i];
iovec->flags = 0;
INIT_LIST_HEAD(&tx_pkt->link);
tx_pkt->type = desc[i].type;
tx_pkt->mem.base = desc[i].pyld;
tx_pkt->mem.size = desc[i].len;
if (unlikely(ipa_ctx->ipa_hw_type == IPA_HW_v1_0)) {
WARN_ON(tx_pkt->mem.size > 512);
/*
* Due to a HW limitation, we need to make sure that the
* packet does not cross a 1KB boundary
*/
tx_pkt->bounce =
dma_pool_alloc(ipa_ctx->dma_pool,
mem_flag,
&tx_pkt->mem.phys_base);
if (!tx_pkt->bounce) {
tx_pkt->mem.phys_base = 0;
} else {
WARN_ON(!ipa_straddle_boundary(
(u32)tx_pkt->mem.phys_base,
(u32)tx_pkt->mem.phys_base +
tx_pkt->mem.size - 1, 1024));
memcpy(tx_pkt->bounce, tx_pkt->mem.base,
tx_pkt->mem.size);
}
} else {
tx_pkt->mem.phys_base =
dma_map_single(NULL, tx_pkt->mem.base,
tx_pkt->mem.size,
DMA_TO_DEVICE);
}
if (!tx_pkt->mem.phys_base) {
IPAERR("failed to alloc tx wrapper\n");
fail_dma_wrap = 1;
goto failure;
}
tx_pkt->sys = sys;
tx_pkt->callback = desc[i].callback;
tx_pkt->user1 = desc[i].user1;
tx_pkt->user2 = desc[i].user2;
/*
* Point the iovec to the bounce buffer and
* add this packet to system pipe context.
*/
iovec->addr = tx_pkt->mem.phys_base;
list_add_tail(&tx_pkt->link, &sys->head_desc_list);
/*
* Special treatment for immediate commands, where the structure
* of the descriptor is different
*/
if (desc[i].type == IPA_IMM_CMD_DESC) {
iovec->size = desc[i].opcode;
iovec->flags |= SPS_IOVEC_FLAG_IMME;
} else {
iovec->size = desc[i].len;
}
if (i == (num_desc - 1)) {
iovec->flags |= SPS_IOVEC_FLAG_EOT;
/* "mark" the last desc */
tx_pkt->cnt = IPA_LAST_DESC_CNT;
}
}
result = sps_transfer(sys->ep->ep_hdl, &transfer);
if (result) {
IPAERR("sps_transfer failed rc=%d\n", result);
goto failure;
}
spin_unlock_irqrestore(&sys->spinlock, irq_flags);
return 0;
failure:
tx_pkt = transfer.user;
for (j = 0; j < i; j++) {
next_pkt = list_next_entry(tx_pkt, link);
list_del(&tx_pkt->link);
if (unlikely(ipa_ctx->ipa_hw_type == IPA_HW_v1_0))
dma_pool_free(ipa_ctx->dma_pool,
tx_pkt->bounce,
tx_pkt->mem.phys_base);
else
dma_unmap_single(NULL, tx_pkt->mem.phys_base,
tx_pkt->mem.size,
DMA_TO_DEVICE);
kmem_cache_free(ipa_ctx->tx_pkt_wrapper_cache, tx_pkt);
tx_pkt = next_pkt;
}
if (i < num_desc)
/* last desc failed */
if (fail_dma_wrap)
kmem_cache_free(ipa_ctx->tx_pkt_wrapper_cache, tx_pkt);
if (transfer.iovec_phys)
dma_pool_free(ipa_ctx->dma_pool, transfer.iovec,
transfer.iovec_phys);
failure_coherent:
spin_unlock_irqrestore(&sys->spinlock, irq_flags);
return -EFAULT;
}
/**
* ipa_sps_irq_cmd_ack - callback function which will be called by SPS driver after an
* immediate command is complete.
* @user1: pointer to the descriptor of the transfer
* @user2:
*
* Complete the immediate commands completion object, this will release the
* thread which waits on this completion object (ipa_send_cmd())
*/
static void ipa_sps_irq_cmd_ack(void *user1, void *user2)
{
struct ipa_desc *desc = (struct ipa_desc *)user1;
if (!desc)
WARN_ON(1);
IPADBG("got ack for cmd=%d\n", desc->opcode);
complete(&desc->xfer_done);
}
/**
* ipa_send_cmd - send immediate commands
* @num_desc: number of descriptors within the desc struct
* @descr: descriptor structure
*
* Function will block till command gets ACK from IPA HW, caller needs
* to free any resources it allocated after function returns
* The callback in ipa_desc should not be set by the caller
* for this function.
*/
int ipa_send_cmd(u16 num_desc, struct ipa_desc *descr)
{
struct ipa_desc *desc;
int result = 0;
ipa_inc_client_enable_clks();
if (num_desc == 1) {
init_completion(&descr->xfer_done);
if (descr->callback || descr->user1)
WARN_ON(1);
descr->callback = ipa_sps_irq_cmd_ack;
descr->user1 = descr;
if (ipa_send_one(&ipa_ctx->sys[IPA_A5_CMD], descr, false)) {
IPAERR("fail to send immediate command\n");
result = -EFAULT;
goto bail;
}
wait_for_completion(&descr->xfer_done);
} else {
desc = &descr[num_desc - 1];
init_completion(&desc->xfer_done);
if (desc->callback || desc->user1)
WARN_ON(1);
desc->callback = ipa_sps_irq_cmd_ack;
desc->user1 = desc;
if (ipa_send(&ipa_ctx->sys[IPA_A5_CMD], num_desc,
descr, false)) {
IPAERR("fail to send multiple immediate command set\n");
result = -EFAULT;
goto bail;
}
wait_for_completion(&desc->xfer_done);
}
IPA_STATS_INC_IC_CNT(num_desc, descr, ipa_ctx->stats.imm_cmds);
bail:
ipa_dec_client_disable_clks();
return result;
}
/**
* ipa_sps_irq_tx_notify() - Callback function which will be called by
* the SPS driver to start a Tx poll operation.
* Called in an interrupt context.
* @notify: SPS driver supplied notification struct
*
* This function defer the work for this event to the tx workqueue.
*/
static void ipa_sps_irq_tx_notify(struct sps_event_notify *notify)
{
struct ipa_sys_context *sys = &ipa_ctx->sys[IPA_A5_LAN_WAN_OUT];
int ret;
IPADBG("event %d notified\n", notify->event_id);
switch (notify->event_id) {
case SPS_EVENT_EOT:
if (!atomic_read(&sys->curr_polling_state)) {
ret = sps_get_config(sys->ep->ep_hdl,
&sys->ep->connect);
if (ret) {
IPAERR("sps_get_config() failed %d\n", ret);
break;
}
sys->ep->connect.options = SPS_O_AUTO_ENABLE |
SPS_O_ACK_TRANSFERS | SPS_O_POLL;
ret = sps_set_config(sys->ep->ep_hdl,
&sys->ep->connect);
if (ret) {
IPAERR("sps_set_config() failed %d\n", ret);
break;
}
atomic_set(&sys->curr_polling_state, 1);
queue_work(ipa_ctx->tx_wq, &tx_work);
}
break;
default:
IPAERR("recieved unexpected event id %d\n", notify->event_id);
}
}
/**
* ipa_sps_irq_tx_no_aggr_notify() - Callback function which will be called by
* the SPS driver after a Tx operation is complete.
* Called in an interrupt context.
* @notify: SPS driver supplied notification struct
*
* This function defer the work for this event to the tx workqueue.
* This event will be later handled by ipa_write_done.
*/
static void ipa_sps_irq_tx_no_aggr_notify(struct sps_event_notify *notify)
{
struct ipa_tx_pkt_wrapper *tx_pkt;
IPADBG("event %d notified\n", notify->event_id);
switch (notify->event_id) {
case SPS_EVENT_EOT:
tx_pkt = notify->data.transfer.user;
schedule_work(&tx_pkt->work);
break;
default:
IPAERR("recieved unexpected event id %d\n", notify->event_id);
}
}
/**
* ipa_handle_rx_core() - The core functionality of packet reception. This
* function is read from multiple code paths.
*
* All the packets on the Rx data path are received on the IPA_A5_LAN_WAN_IN
* endpoint. The function runs as long as there are packets in the pipe.
* For each packet:
* - Disconnect the packet from the system pipe linked list
* - Unmap the packets skb, make it non DMAable
* - Free the packet from the cache
* - Prepare a proper skb
* - Call the endpoints notify function, passing the skb in the parameters
* - Replenish the rx cache
*/
int ipa_handle_rx_core(struct ipa_sys_context *sys, bool process_all,
bool in_poll_state)
{
struct ipa_a5_mux_hdr *mux_hdr;
struct ipa_rx_pkt_wrapper *rx_pkt;
struct sk_buff *rx_skb;
struct sps_iovec iov;
unsigned int pull_len;
unsigned int padding;
int ret;
struct ipa_ep_context *ep;
int cnt = 0;
unsigned int src_pipe;
while ((in_poll_state ? atomic_read(&sys->curr_polling_state) :
!atomic_read(&sys->curr_polling_state))) {
if (cnt && !process_all)
break;
ret = sps_get_iovec(sys->ep->ep_hdl, &iov);
if (ret) {
IPAERR("sps_get_iovec failed %d\n", ret);
break;
}
if (iov.addr == 0)
break;
if (unlikely(list_empty(&sys->head_desc_list)))
continue;
rx_pkt = list_first_entry(&sys->head_desc_list,
struct ipa_rx_pkt_wrapper, link);
rx_pkt->len = iov.size;
sys->len--;
list_del(&rx_pkt->link);
IPADBG("--curr_cnt=%d\n", sys->len);
rx_skb = rx_pkt->skb;
dma_unmap_single(NULL, rx_pkt->dma_address, IPA_RX_SKB_SIZE,
DMA_FROM_DEVICE);
/*
* make it look like a real skb, "data" was already set at
* alloc time
*/
rx_skb->tail = rx_skb->data + rx_pkt->len;
rx_skb->len = rx_pkt->len;
rx_skb->truesize = rx_pkt->len + sizeof(struct sk_buff);
kmem_cache_free(ipa_ctx->rx_pkt_wrapper_cache, rx_pkt);
mux_hdr = (struct ipa_a5_mux_hdr *)rx_skb->data;
src_pipe = mux_hdr->src_pipe_index;
IPADBG("RX pkt len=%d IID=0x%x src=%d, flags=0x%x, meta=0x%x\n",
rx_skb->len, ntohs(mux_hdr->interface_id),
src_pipe, mux_hdr->flags, ntohl(mux_hdr->metadata));
IPA_DUMP_BUFF(rx_skb->data, 0, rx_skb->len);
IPA_STATS_INC_CNT(ipa_ctx->stats.rx_pkts);
IPA_STATS_EXCP_CNT(mux_hdr->flags, ipa_ctx->stats.rx_excp_pkts);
/*
* Any packets arriving over AMPDU_TX should be dispatched
* to the regular WLAN RX data-path.
*/
if (unlikely(src_pipe == WLAN_AMPDU_TX_EP))
src_pipe = WLAN_PROD_TX_EP;
if (unlikely(src_pipe >= IPA_NUM_PIPES ||
!ipa_ctx->ep[src_pipe].valid ||
!ipa_ctx->ep[src_pipe].client_notify)) {
IPAERR("drop pipe=%d ep_valid=%d client_notify=%p\n",
src_pipe, ipa_ctx->ep[src_pipe].valid,
ipa_ctx->ep[src_pipe].client_notify);
dev_kfree_skb(rx_skb);
ipa_replenish_rx_cache();
++cnt;
continue;
}
ep = &ipa_ctx->ep[src_pipe];
pull_len = sizeof(struct ipa_a5_mux_hdr);
/*
* IP packet starts on word boundary
* remove the MUX header and any padding and pass the frame to
* the client which registered a rx callback on the "src pipe"
*/
padding = ep->cfg.hdr.hdr_len & 0x3;
if (padding)
pull_len += 4 - padding;
IPADBG("pulling %d bytes from skb\n", pull_len);
skb_pull(rx_skb, pull_len);
ipa_replenish_rx_cache();
ep->client_notify(ep->priv, IPA_RECEIVE,
(unsigned long)(rx_skb));
cnt++;
};
return cnt;
}
/**
* ipa_rx_switch_to_intr_mode() - Operate the Rx data path in interrupt mode
*/
static void ipa_rx_switch_to_intr_mode(struct ipa_sys_context *sys)
{
int ret;
if (!atomic_read(&sys->curr_polling_state)) {
IPAERR("already in intr mode\n");
goto fail;
}
ret = sps_get_config(sys->ep->ep_hdl, &sys->ep->connect);
if (ret) {
IPAERR("sps_get_config() failed %d\n", ret);
goto fail;
}
sys->event.options = SPS_O_EOT;
ret = sps_register_event(sys->ep->ep_hdl, &sys->event);
if (ret) {
IPAERR("sps_register_event() failed %d\n", ret);
goto fail;
}
sys->ep->connect.options =
SPS_O_AUTO_ENABLE | SPS_O_ACK_TRANSFERS | SPS_O_EOT;
ret = sps_set_config(sys->ep->ep_hdl, &sys->ep->connect);
if (ret) {
IPAERR("sps_set_config() failed %d\n", ret);
goto fail;
}
atomic_set(&sys->curr_polling_state, 0);
ipa_handle_rx_core(sys, true, false);
return;
fail:
IPA_STATS_INC_CNT(ipa_ctx->stats.x_intr_repost);
schedule_delayed_work(&sys->switch_to_intr_work, msecs_to_jiffies(1));
}
/**
* ipa_rx_notify() - Callback function which is called by the SPS driver when a
* a packet is received
* @notify: SPS driver supplied notification information
*
* Called in an interrupt context, therefore the majority of the work is
* deffered using a work queue.
*
* After receiving a packet, the driver goes to polling mode and keeps pulling
* packets until the rx buffer is empty, then it goes back to interrupt mode.
* This comes to prevent the CPU from handling too many interrupts when the
* throughput is high.
*/
static void ipa_sps_irq_rx_notify(struct sps_event_notify *notify)
{
struct ipa_sys_context *sys = &ipa_ctx->sys[IPA_A5_LAN_WAN_IN];
int ret;
IPADBG("event %d notified\n", notify->event_id);
switch (notify->event_id) {
case SPS_EVENT_EOT:
if (!atomic_read(&sys->curr_polling_state)) {
ret = sps_get_config(sys->ep->ep_hdl,
&sys->ep->connect);
if (ret) {
IPAERR("sps_get_config() failed %d\n", ret);
break;
}
sys->ep->connect.options = SPS_O_AUTO_ENABLE |
SPS_O_ACK_TRANSFERS | SPS_O_POLL;
ret = sps_set_config(sys->ep->ep_hdl,
&sys->ep->connect);
if (ret) {
IPAERR("sps_set_config() failed %d\n", ret);
break;
}
atomic_set(&sys->curr_polling_state, 1);
queue_work(ipa_ctx->rx_wq, &rx_work);
}
break;
default:
IPAERR("recieved unexpected event id %d\n", notify->event_id);
}
}
static void switch_to_intr_tx_work_func(struct work_struct *work)
{
struct delayed_work *dwork;
struct ipa_sys_context *sys;
dwork = container_of(work, struct delayed_work, work);
sys = container_of(dwork, struct ipa_sys_context, switch_to_intr_work);
ipa_handle_tx(sys);
}
/**
* ipa_handle_rx() - handle packet reception. This function is executed in the
* context of a work queue.
* @work: work struct needed by the work queue
*
* ipa_handle_rx_core() is run in polling mode. After all packets has been
* received, the driver switches back to interrupt mode.
*/
static void ipa_handle_rx(struct ipa_sys_context *sys)
{
int inactive_cycles = 0;
int cnt;
ipa_inc_client_enable_clks();
do {
cnt = ipa_handle_rx_core(sys, true, true);
if (cnt == 0) {
inactive_cycles++;
usleep_range(POLLING_MIN_SLEEP_RX,
POLLING_MAX_SLEEP_RX);
} else {
inactive_cycles = 0;
}
} while (inactive_cycles <= POLLING_INACTIVITY_RX);
ipa_rx_switch_to_intr_mode(sys);
ipa_dec_client_disable_clks();
}
static void switch_to_intr_rx_work_func(struct work_struct *work)
{
struct delayed_work *dwork;
struct ipa_sys_context *sys;
dwork = container_of(work, struct delayed_work, work);
sys = container_of(dwork, struct ipa_sys_context, switch_to_intr_work);
ipa_handle_rx(sys);
}
/**
* ipa_setup_sys_pipe() - Setup an IPA end-point in system-BAM mode and perform
* IPA EP configuration
* @sys_in: [in] input needed to setup BAM pipe and configure EP
* @clnt_hdl: [out] client handle
*
* - configure the end-point registers with the supplied
* parameters from the user.
* - call SPS APIs to create a system-to-bam connection with IPA.
* - allocate descriptor FIFO
* - register callback function(ipa_sps_irq_rx_notify or
* ipa_sps_irq_tx_notify - depends on client type) in case the driver is
* not configured to pulling mode
*
* Returns: 0 on success, negative on failure
*/
int ipa_setup_sys_pipe(struct ipa_sys_connect_params *sys_in, u32 *clnt_hdl)
{
int ipa_ep_idx;
int sys_idx = -1;
int result = -EFAULT;
dma_addr_t dma_addr;
if (sys_in == NULL || clnt_hdl == NULL ||
sys_in->client >= IPA_CLIENT_MAX || sys_in->desc_fifo_sz == 0) {
IPAERR("bad parm.\n");
result = -EINVAL;
goto fail_bad_param;
}
ipa_ep_idx = ipa_get_ep_mapping(ipa_ctx->mode, sys_in->client);
if (ipa_ep_idx == -1) {
IPAERR("Invalid client.\n");
goto fail_bad_param;
}
if (ipa_ctx->ep[ipa_ep_idx].valid == 1) {
IPAERR("EP already allocated.\n");
goto fail_bad_param;
}
memset(&ipa_ctx->ep[ipa_ep_idx], 0, sizeof(struct ipa_ep_context));
ipa_ctx->ep[ipa_ep_idx].valid = 1;
ipa_ctx->ep[ipa_ep_idx].client = sys_in->client;
ipa_ctx->ep[ipa_ep_idx].client_notify = sys_in->notify;
ipa_ctx->ep[ipa_ep_idx].priv = sys_in->priv;
if (ipa_cfg_ep(ipa_ep_idx, &sys_in->ipa_ep_cfg)) {
IPAERR("fail to configure EP.\n");
goto fail_sps_api;
}
/* Default Config */
ipa_ctx->ep[ipa_ep_idx].ep_hdl = sps_alloc_endpoint();
if (ipa_ctx->ep[ipa_ep_idx].ep_hdl == NULL) {
IPAERR("SPS EP allocation failed.\n");
goto fail_sps_api;
}
result = sps_get_config(ipa_ctx->ep[ipa_ep_idx].ep_hdl,
&ipa_ctx->ep[ipa_ep_idx].connect);
if (result) {
IPAERR("fail to get config.\n");
goto fail_mem_alloc;
}
/* Specific Config */
if (IPA_CLIENT_IS_CONS(sys_in->client)) {
ipa_ctx->ep[ipa_ep_idx].connect.mode = SPS_MODE_SRC;
ipa_ctx->ep[ipa_ep_idx].connect.destination =
SPS_DEV_HANDLE_MEM;
ipa_ctx->ep[ipa_ep_idx].connect.source = ipa_ctx->bam_handle;
ipa_ctx->ep[ipa_ep_idx].connect.dest_pipe_index =
ipa_ctx->a5_pipe_index++;
ipa_ctx->ep[ipa_ep_idx].connect.src_pipe_index = ipa_ep_idx;
ipa_ctx->ep[ipa_ep_idx].connect.options = SPS_O_ACK_TRANSFERS |
SPS_O_NO_DISABLE;
} else {
ipa_ctx->ep[ipa_ep_idx].connect.mode = SPS_MODE_DEST;
ipa_ctx->ep[ipa_ep_idx].connect.source = SPS_DEV_HANDLE_MEM;
ipa_ctx->ep[ipa_ep_idx].connect.destination =
ipa_ctx->bam_handle;
ipa_ctx->ep[ipa_ep_idx].connect.src_pipe_index =
ipa_ctx->a5_pipe_index++;
ipa_ctx->ep[ipa_ep_idx].connect.dest_pipe_index = ipa_ep_idx;
if (sys_in->client == IPA_CLIENT_A5_LAN_WAN_PROD)
ipa_ctx->ep[ipa_ep_idx].connect.options |=
SPS_O_ACK_TRANSFERS;
}
ipa_ctx->ep[ipa_ep_idx].connect.options |= (SPS_O_AUTO_ENABLE |
SPS_O_EOT);
if (ipa_ctx->polling_mode)
ipa_ctx->ep[ipa_ep_idx].connect.options |= SPS_O_POLL;
ipa_ctx->ep[ipa_ep_idx].connect.desc.size = sys_in->desc_fifo_sz;
ipa_ctx->ep[ipa_ep_idx].connect.desc.base =
dma_alloc_coherent(NULL, ipa_ctx->ep[ipa_ep_idx].connect.desc.size,
&dma_addr, 0);
ipa_ctx->ep[ipa_ep_idx].connect.desc.phys_base = dma_addr;
if (ipa_ctx->ep[ipa_ep_idx].connect.desc.base == NULL) {
IPAERR("fail to get DMA desc memory.\n");
goto fail_mem_alloc;
}
ipa_ctx->ep[ipa_ep_idx].connect.event_thresh = IPA_EVENT_THRESHOLD;
result = sps_connect(ipa_ctx->ep[ipa_ep_idx].ep_hdl,
&ipa_ctx->ep[ipa_ep_idx].connect);
if (result) {
IPAERR("sps_connect fails.\n");
goto fail_sps_connect;
}
switch (ipa_ep_idx) {
case 1:
sys_idx = ipa_ep_idx;
break;
case 2:
sys_idx = ipa_ep_idx;
INIT_DELAYED_WORK(&ipa_ctx->sys[sys_idx].switch_to_intr_work,
switch_to_intr_tx_work_func);
break;
case 3:
sys_idx = ipa_ep_idx;
INIT_DELAYED_WORK(&replenish_rx_work, replenish_rx_work_func);
INIT_DELAYED_WORK(&ipa_ctx->sys[sys_idx].switch_to_intr_work,
switch_to_intr_rx_work_func);
break;
case WLAN_AMPDU_TX_EP:
sys_idx = IPA_A5_WLAN_AMPDU_OUT;
break;
default:
IPAERR("Invalid EP index.\n");
result = -EFAULT;
goto fail_register_event;
}
if (!ipa_ctx->polling_mode) {
ipa_ctx->sys[sys_idx].event.options = SPS_O_EOT;
ipa_ctx->sys[sys_idx].event.mode = SPS_TRIGGER_CALLBACK;
ipa_ctx->sys[sys_idx].event.xfer_done = NULL;
ipa_ctx->sys[sys_idx].event.user =
&ipa_ctx->sys[sys_idx];
ipa_ctx->sys[sys_idx].event.callback =
IPA_CLIENT_IS_CONS(sys_in->client) ?
ipa_sps_irq_rx_notify :
(sys_in->client ==
IPA_CLIENT_A5_LAN_WAN_PROD ?
ipa_sps_irq_tx_notify :
ipa_sps_irq_tx_no_aggr_notify);
result = sps_register_event(ipa_ctx->ep[ipa_ep_idx].ep_hdl,
&ipa_ctx->sys[sys_idx].event);
if (result < 0) {
IPAERR("register event error %d\n", result);
goto fail_register_event;
}
}
*clnt_hdl = ipa_ep_idx;
IPADBG("client %d (ep: %d) connected\n", sys_in->client, ipa_ep_idx);
return 0;
fail_register_event:
sps_disconnect(ipa_ctx->ep[ipa_ep_idx].ep_hdl);
fail_sps_connect:
dma_free_coherent(NULL, ipa_ctx->ep[ipa_ep_idx].connect.desc.size,
ipa_ctx->ep[ipa_ep_idx].connect.desc.base,
ipa_ctx->ep[ipa_ep_idx].connect.desc.phys_base);
fail_mem_alloc:
sps_free_endpoint(ipa_ctx->ep[ipa_ep_idx].ep_hdl);
fail_sps_api:
memset(&ipa_ctx->ep[ipa_ep_idx], 0, sizeof(struct ipa_ep_context));
fail_bad_param:
return result;
}
EXPORT_SYMBOL(ipa_setup_sys_pipe);
/**
* ipa_teardown_sys_pipe() - Teardown the system-BAM pipe and cleanup IPA EP
* @clnt_hdl: [in] the handle obtained from ipa_setup_sys_pipe
*
* Returns: 0 on success, negative on failure
*/
int ipa_teardown_sys_pipe(u32 clnt_hdl)
{
if (clnt_hdl >= IPA_NUM_PIPES || ipa_ctx->ep[clnt_hdl].valid == 0) {
IPAERR("bad parm.\n");
return -EINVAL;
}
sps_disconnect(ipa_ctx->ep[clnt_hdl].ep_hdl);
dma_free_coherent(NULL, ipa_ctx->ep[clnt_hdl].connect.desc.size,
ipa_ctx->ep[clnt_hdl].connect.desc.base,
ipa_ctx->ep[clnt_hdl].connect.desc.phys_base);
sps_free_endpoint(ipa_ctx->ep[clnt_hdl].ep_hdl);
memset(&ipa_ctx->ep[clnt_hdl], 0, sizeof(struct ipa_ep_context));
IPADBG("client (ep: %d) disconnected\n", clnt_hdl);
return 0;
}
EXPORT_SYMBOL(ipa_teardown_sys_pipe);
/**
* ipa_tx_comp_usr_notify_release() - Callback function which will call the
* user supplied callback function to release the skb, or release it on
* its own if no callback function was supplied.
* @user1
* @user2
*
* This notified callback is for the destination client.
* This function is supplied in ipa_connect.
*/
static void ipa_tx_comp_usr_notify_release(void *user1, void *user2)
{
struct sk_buff *skb = (struct sk_buff *)user1;
u32 ep_idx = (u32)user2;
IPADBG("skb=%p ep=%d\n", skb, ep_idx);
IPA_STATS_INC_TX_CNT(ep_idx, ipa_ctx->stats.tx_sw_pkts,
ipa_ctx->stats.tx_hw_pkts);
if (ipa_ctx->ep[ep_idx].client_notify)
ipa_ctx->ep[ep_idx].client_notify(ipa_ctx->ep[ep_idx].priv,
IPA_WRITE_DONE, (unsigned long)skb);
else
dev_kfree_skb(skb);
}
static void ipa_tx_cmd_comp(void *user1, void *user2)
{
kfree(user1);
}
/**
* ipa_tx_dp() - Data-path tx handler
* @dst: [in] which IPA destination to route tx packets to
* @skb: [in] the packet to send
* @metadata: [in] TX packet meta-data
*
* Data-path tx handler, this is used for both SW data-path which by-passes most
* IPA HW blocks AND the regular HW data-path for WLAN AMPDU traffic only. If
* dst is a "valid" CONS type, then SW data-path is used. If dst is the
* WLAN_AMPDU PROD type, then HW data-path for WLAN AMPDU is used. Anything else
* is an error. For errors, client needs to free the skb as needed. For success,
* IPA driver will later invoke client callback if one was supplied. That
* callback should free the skb. If no callback supplied, IPA driver will free
* the skb internally
*
* The function will use two descriptors for this send command
* (for A5_WLAN_AMPDU_PROD only one desciprtor will be sent),
* the first descriptor will be used to inform the IPA hardware that
* apps need to push data into the IPA (IP_PACKET_INIT immediate command).
* Once this send was done from SPS point-of-view the IPA driver will
* get notified by the supplied callback - ipa_sps_irq_tx_comp()
*
* ipa_sps_irq_tx_comp will call to the user supplied
* callback (from ipa_connect)
*
* Returns: 0 on success, negative on failure
*/
int ipa_tx_dp(enum ipa_client_type dst, struct sk_buff *skb,
struct ipa_tx_meta *meta)
{
struct ipa_desc desc[2];
int ipa_ep_idx;
struct ipa_ip_packet_init *cmd;
memset(&desc, 0, 2 * sizeof(struct ipa_desc));
ipa_ep_idx = ipa_get_ep_mapping(ipa_ctx->mode, dst);
if (unlikely(ipa_ep_idx == -1)) {
IPAERR("dest EP does not exist.\n");
goto fail_gen;
}
if (unlikely(ipa_ctx->ep[ipa_ep_idx].valid == 0)) {
IPAERR("dest EP not valid.\n");
goto fail_gen;
}
if (IPA_CLIENT_IS_CONS(dst)) {
cmd = kzalloc(sizeof(struct ipa_ip_packet_init), GFP_ATOMIC);
if (!cmd) {
IPAERR("failed to alloc immediate command object\n");
goto fail_mem_alloc;
}
cmd->destination_pipe_index = ipa_ep_idx;
if (meta && meta->mbim_stream_id_valid)
cmd->metadata = meta->mbim_stream_id;
desc[0].opcode = IPA_IP_PACKET_INIT;
desc[0].pyld = cmd;
desc[0].len = sizeof(struct ipa_ip_packet_init);
desc[0].type = IPA_IMM_CMD_DESC;
desc[0].callback = ipa_tx_cmd_comp;
desc[0].user1 = cmd;
desc[1].pyld = skb->data;
desc[1].len = skb->len;
desc[1].type = IPA_DATA_DESC_SKB;
desc[1].callback = ipa_tx_comp_usr_notify_release;
desc[1].user1 = skb;
desc[1].user2 = (void *)ipa_ep_idx;
if (ipa_send(&ipa_ctx->sys[IPA_A5_LAN_WAN_OUT], 2, desc,
true)) {
IPAERR("fail to send immediate command\n");
goto fail_send;
}
IPA_STATS_INC_CNT(ipa_ctx->stats.imm_cmds[IPA_IP_PACKET_INIT]);
} else if (dst == IPA_CLIENT_A5_WLAN_AMPDU_PROD) {
desc[0].pyld = skb->data;
desc[0].len = skb->len;
desc[0].type = IPA_DATA_DESC_SKB;
desc[0].callback = ipa_tx_comp_usr_notify_release;
desc[0].user1 = skb;
desc[0].user2 = (void *)ipa_ep_idx;
if (ipa_send_one(&ipa_ctx->sys[IPA_A5_WLAN_AMPDU_OUT],
&desc[0], true)) {
IPAERR("fail to send skb\n");
goto fail_gen;
}
} else {
IPAERR("%d PROD is not supported.\n", dst);
goto fail_gen;
}
return 0;
fail_send:
kfree(cmd);
fail_mem_alloc:
fail_gen:
return -EFAULT;
}
EXPORT_SYMBOL(ipa_tx_dp);
static void ipa_wq_handle_rx(struct work_struct *work)
{
ipa_handle_rx(&ipa_ctx->sys[IPA_A5_LAN_WAN_IN]);
}
/**
* ipa_replenish_rx_cache() - Replenish the Rx packets cache.
*
* The function allocates buffers in the rx_pkt_wrapper_cache cache until there
* are IPA_RX_POOL_CEIL buffers in the cache.
* - Allocate a buffer in the cache
* - Initialized the packets link
* - Initialize the packets work struct
* - Allocate the packets socket buffer (skb)
* - Fill the packets skb with data
* - Make the packet DMAable
* - Add the packet to the system pipe linked list
* - Initiate a SPS transfer so that SPS driver will use this packet later.
*/
void ipa_replenish_rx_cache(void)
{
void *ptr;
struct ipa_rx_pkt_wrapper *rx_pkt;
int ret;
int rx_len_cached = 0;
struct ipa_sys_context *sys = &ipa_ctx->sys[IPA_A5_LAN_WAN_IN];
gfp_t flag = GFP_NOWAIT | __GFP_NOWARN;
rx_len_cached = sys->len;
while (rx_len_cached < IPA_RX_POOL_CEIL) {
rx_pkt = kmem_cache_zalloc(ipa_ctx->rx_pkt_wrapper_cache,
flag);
if (!rx_pkt) {
IPAERR("failed to alloc rx wrapper\n");
goto fail_kmem_cache_alloc;
}
INIT_LIST_HEAD(&rx_pkt->link);
rx_pkt->skb = __dev_alloc_skb(IPA_RX_SKB_SIZE, flag);
if (rx_pkt->skb == NULL) {
IPAERR("failed to alloc skb\n");
goto fail_skb_alloc;
}
ptr = skb_put(rx_pkt->skb, IPA_RX_SKB_SIZE);
rx_pkt->dma_address = dma_map_single(NULL, ptr,
IPA_RX_SKB_SIZE,
DMA_FROM_DEVICE);
if (rx_pkt->dma_address == 0 || rx_pkt->dma_address == ~0) {
IPAERR("dma_map_single failure %p for %p\n",
(void *)rx_pkt->dma_address, ptr);
goto fail_dma_mapping;
}
list_add_tail(&rx_pkt->link, &sys->head_desc_list);
rx_len_cached = ++sys->len;
ret = sps_transfer_one(sys->ep->ep_hdl, rx_pkt->dma_address,
IPA_RX_SKB_SIZE, rx_pkt,
0);
if (ret) {
IPAERR("sps_transfer_one failed %d\n", ret);
goto fail_sps_transfer;
}
}
ipa_ctx->stats.rx_q_len = sys->len;
return;
fail_sps_transfer:
list_del(&rx_pkt->link);
rx_len_cached = --sys->len;
dma_unmap_single(NULL, rx_pkt->dma_address, IPA_RX_SKB_SIZE,
DMA_FROM_DEVICE);
fail_dma_mapping:
dev_kfree_skb(rx_pkt->skb);
fail_skb_alloc:
kmem_cache_free(ipa_ctx->rx_pkt_wrapper_cache, rx_pkt);
fail_kmem_cache_alloc:
if (rx_len_cached == 0) {
IPA_STATS_INC_CNT(ipa_ctx->stats.rx_repl_repost);
schedule_delayed_work(&replenish_rx_work,
msecs_to_jiffies(100));
}
ipa_ctx->stats.rx_q_len = sys->len;
return;
}
static void replenish_rx_work_func(struct work_struct *work)
{
ipa_replenish_rx_cache();
}
/**
* ipa_cleanup_rx() - release RX queue resources
*
*/
void ipa_cleanup_rx(void)
{
struct ipa_rx_pkt_wrapper *rx_pkt;
struct ipa_rx_pkt_wrapper *r;
struct ipa_sys_context *sys = &ipa_ctx->sys[IPA_A5_LAN_WAN_IN];
list_for_each_entry_safe(rx_pkt, r,
&sys->head_desc_list, link) {
list_del(&rx_pkt->link);
dma_unmap_single(NULL, rx_pkt->dma_address, IPA_RX_SKB_SIZE,
DMA_FROM_DEVICE);
dev_kfree_skb(rx_pkt->skb);
kmem_cache_free(ipa_ctx->rx_pkt_wrapper_cache, rx_pkt);
}
}
| gpl-2.0 |
omerjerk/android_kernel_xiaomi_ferrari | drivers/scsi/fnic/fnic_debugfs.c | 2059 | 8886 | /*
* Copyright 2012 Cisco Systems, Inc. All rights reserved.
*
* This program is free software; you may 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.
*
* 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/module.h>
#include <linux/errno.h>
#include <linux/debugfs.h>
#include "fnic.h"
static struct dentry *fnic_trace_debugfs_root;
static struct dentry *fnic_trace_debugfs_file;
static struct dentry *fnic_trace_enable;
/*
* fnic_trace_ctrl_open - Open the trace_enable file
* @inode: The inode pointer.
* @file: The file pointer to attach the trace enable/disable flag.
*
* Description:
* This routine opens a debugsfs file trace_enable.
*
* Returns:
* This function returns zero if successful.
*/
static int fnic_trace_ctrl_open(struct inode *inode, struct file *filp)
{
filp->private_data = inode->i_private;
return 0;
}
/*
* fnic_trace_ctrl_read - Read a trace_enable debugfs file
* @filp: The file pointer to read from.
* @ubuf: The buffer to copy the data to.
* @cnt: The number of bytes to read.
* @ppos: The position in the file to start reading from.
*
* Description:
* This routine reads value of variable fnic_tracing_enabled
* and stores into local @buf. It will start reading file at @ppos and
* copy up to @cnt of data to @ubuf from @buf.
*
* Returns:
* This function returns the amount of data that was read.
*/
static ssize_t fnic_trace_ctrl_read(struct file *filp,
char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[64];
int len;
len = sprintf(buf, "%u\n", fnic_tracing_enabled);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, len);
}
/*
* fnic_trace_ctrl_write - Write to trace_enable debugfs file
* @filp: The file pointer to write from.
* @ubuf: The buffer to copy the data from.
* @cnt: The number of bytes to write.
* @ppos: The position in the file to start writing to.
*
* Description:
* This routine writes data from user buffer @ubuf to buffer @buf and
* sets fnic_tracing_enabled value as per user input.
*
* Returns:
* This function returns the amount of data that was written.
*/
static ssize_t fnic_trace_ctrl_write(struct file *filp,
const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[64];
unsigned long val;
int ret;
if (cnt >= sizeof(buf))
return -EINVAL;
if (copy_from_user(&buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
ret = kstrtoul(buf, 10, &val);
if (ret < 0)
return ret;
fnic_tracing_enabled = val;
(*ppos)++;
return cnt;
}
/*
* fnic_trace_debugfs_open - Open the fnic trace log
* @inode: The inode pointer
* @file: The file pointer to attach the log output
*
* Description:
* This routine is the entry point for the debugfs open file operation.
* It allocates the necessary buffer for the log, fills the buffer from
* the in-memory log and then returns a pointer to that log in
* the private_data field in @file.
*
* Returns:
* This function returns zero if successful. On error it will return
* a negative error value.
*/
static int fnic_trace_debugfs_open(struct inode *inode,
struct file *file)
{
fnic_dbgfs_t *fnic_dbg_prt;
fnic_dbg_prt = kzalloc(sizeof(fnic_dbgfs_t), GFP_KERNEL);
if (!fnic_dbg_prt)
return -ENOMEM;
fnic_dbg_prt->buffer = vmalloc((3*(trace_max_pages * PAGE_SIZE)));
if (!fnic_dbg_prt->buffer) {
kfree(fnic_dbg_prt);
return -ENOMEM;
}
memset((void *)fnic_dbg_prt->buffer, 0,
(3*(trace_max_pages * PAGE_SIZE)));
fnic_dbg_prt->buffer_len = fnic_get_trace_data(fnic_dbg_prt);
file->private_data = fnic_dbg_prt;
return 0;
}
/*
* fnic_trace_debugfs_lseek - Seek through a debugfs file
* @file: The file pointer to seek through.
* @offset: The offset to seek to or the amount to seek by.
* @howto: Indicates how to seek.
*
* Description:
* This routine is the entry point for the debugfs lseek file operation.
* The @howto parameter indicates whether @offset is the offset to directly
* seek to, or if it is a value to seek forward or reverse by. This function
* figures out what the new offset of the debugfs file will be and assigns
* that value to the f_pos field of @file.
*
* Returns:
* This function returns the new offset if successful and returns a negative
* error if unable to process the seek.
*/
static loff_t fnic_trace_debugfs_lseek(struct file *file,
loff_t offset,
int howto)
{
fnic_dbgfs_t *fnic_dbg_prt = file->private_data;
loff_t pos = -1;
switch (howto) {
case 0:
pos = offset;
break;
case 1:
pos = file->f_pos + offset;
break;
case 2:
pos = fnic_dbg_prt->buffer_len + offset;
}
return (pos < 0 || pos > fnic_dbg_prt->buffer_len) ?
-EINVAL : (file->f_pos = pos);
}
/*
* fnic_trace_debugfs_read - Read a debugfs file
* @file: The file pointer to read from.
* @ubuf: The buffer to copy the data to.
* @nbytes: The number of bytes to read.
* @pos: The position in the file to start reading from.
*
* Description:
* This routine reads data from the buffer indicated in the private_data
* field of @file. It will start reading at @pos and copy up to @nbytes of
* data to @ubuf.
*
* Returns:
* This function returns the amount of data that was read (this could be
* less than @nbytes if the end of the file was reached).
*/
static ssize_t fnic_trace_debugfs_read(struct file *file,
char __user *ubuf,
size_t nbytes,
loff_t *pos)
{
fnic_dbgfs_t *fnic_dbg_prt = file->private_data;
int rc = 0;
rc = simple_read_from_buffer(ubuf, nbytes, pos,
fnic_dbg_prt->buffer,
fnic_dbg_prt->buffer_len);
return rc;
}
/*
* fnic_trace_debugfs_release - Release the buffer used to store
* debugfs file data
* @inode: The inode pointer
* @file: The file pointer that contains the buffer to release
*
* Description:
* This routine frees the buffer that was allocated when the debugfs
* file was opened.
*
* Returns:
* This function returns zero.
*/
static int fnic_trace_debugfs_release(struct inode *inode,
struct file *file)
{
fnic_dbgfs_t *fnic_dbg_prt = file->private_data;
vfree(fnic_dbg_prt->buffer);
kfree(fnic_dbg_prt);
return 0;
}
static const struct file_operations fnic_trace_ctrl_fops = {
.owner = THIS_MODULE,
.open = fnic_trace_ctrl_open,
.read = fnic_trace_ctrl_read,
.write = fnic_trace_ctrl_write,
};
static const struct file_operations fnic_trace_debugfs_fops = {
.owner = THIS_MODULE,
.open = fnic_trace_debugfs_open,
.llseek = fnic_trace_debugfs_lseek,
.read = fnic_trace_debugfs_read,
.release = fnic_trace_debugfs_release,
};
/*
* fnic_trace_debugfs_init - Initialize debugfs for fnic trace logging
*
* Description:
* When Debugfs is configured this routine sets up the fnic debugfs
* file system. If not already created, this routine will create the
* fnic directory. It will create file trace to log fnic trace buffer
* output into debugfs and it will also create file trace_enable to
* control enable/disable of trace logging into trace buffer.
*/
int fnic_trace_debugfs_init(void)
{
int rc = -1;
fnic_trace_debugfs_root = debugfs_create_dir("fnic", NULL);
if (!fnic_trace_debugfs_root) {
printk(KERN_DEBUG "Cannot create debugfs root\n");
return rc;
}
fnic_trace_enable = debugfs_create_file("tracing_enable",
S_IFREG|S_IRUGO|S_IWUSR,
fnic_trace_debugfs_root,
NULL, &fnic_trace_ctrl_fops);
if (!fnic_trace_enable) {
printk(KERN_DEBUG "Cannot create trace_enable file"
" under debugfs");
return rc;
}
fnic_trace_debugfs_file = debugfs_create_file("trace",
S_IFREG|S_IRUGO|S_IWUSR,
fnic_trace_debugfs_root,
NULL,
&fnic_trace_debugfs_fops);
if (!fnic_trace_debugfs_file) {
printk(KERN_DEBUG "Cannot create trace file under debugfs");
return rc;
}
rc = 0;
return rc;
}
/*
* fnic_trace_debugfs_terminate - Tear down debugfs infrastructure
*
* Description:
* When Debugfs is configured this routine removes debugfs file system
* elements that are specific to fnic trace logging.
*/
void fnic_trace_debugfs_terminate(void)
{
if (fnic_trace_debugfs_file) {
debugfs_remove(fnic_trace_debugfs_file);
fnic_trace_debugfs_file = NULL;
}
if (fnic_trace_enable) {
debugfs_remove(fnic_trace_enable);
fnic_trace_enable = NULL;
}
if (fnic_trace_debugfs_root) {
debugfs_remove(fnic_trace_debugfs_root);
fnic_trace_debugfs_root = NULL;
}
}
| gpl-2.0 |
OneEducation/kernel-rk310-lollipop-firefly | drivers/tty/serial/8250/serial_cs.c | 2315 | 29934 | /*======================================================================
A driver for PCMCIA serial devices
serial_cs.c 1.134 2002/05/04 05:48:53
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in which
case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
======================================================================*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/serial_core.h>
#include <linux/delay.h>
#include <linux/major.h>
#include <asm/io.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/ciscode.h>
#include <pcmcia/ds.h>
#include <pcmcia/cisreg.h>
#include "8250.h"
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
/* Enable the speaker? */
static int do_sound = 1;
/* Skip strict UART tests? */
static int buggy_uart;
module_param(do_sound, int, 0444);
module_param(buggy_uart, int, 0444);
/*====================================================================*/
/* Table of multi-port card ID's */
struct serial_quirk {
unsigned int manfid;
unsigned int prodid;
int multi; /* 1 = multifunction, > 1 = # ports */
void (*config)(struct pcmcia_device *);
void (*setup)(struct pcmcia_device *, struct uart_8250_port *);
void (*wakeup)(struct pcmcia_device *);
int (*post)(struct pcmcia_device *);
};
struct serial_info {
struct pcmcia_device *p_dev;
int ndev;
int multi;
int slave;
int manfid;
int prodid;
int c950ctrl;
int line[4];
const struct serial_quirk *quirk;
};
struct serial_cfg_mem {
tuple_t tuple;
cisparse_t parse;
u_char buf[256];
};
/*
* vers_1 5.0, "Brain Boxes", "2-Port RS232 card", "r6"
* manfid 0x0160, 0x0104
* This card appears to have a 14.7456MHz clock.
*/
/* Generic Modem: MD55x (GPRS/EDGE) have
* Elan VPU16551 UART with 14.7456MHz oscillator
* manfid 0x015D, 0x4C45
*/
static void quirk_setup_brainboxes_0104(struct pcmcia_device *link, struct uart_8250_port *uart)
{
uart->port.uartclk = 14745600;
}
static int quirk_post_ibm(struct pcmcia_device *link)
{
u8 val;
int ret;
ret = pcmcia_read_config_byte(link, 0x800, &val);
if (ret)
goto failed;
ret = pcmcia_write_config_byte(link, 0x800, val | 1);
if (ret)
goto failed;
return 0;
failed:
return -ENODEV;
}
/*
* Nokia cards are not really multiport cards. Shouldn't this
* be handled by setting the quirk entry .multi = 0 | 1 ?
*/
static void quirk_config_nokia(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
if (info->multi > 1)
info->multi = 1;
}
static void quirk_wakeup_oxsemi(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
if (info->c950ctrl)
outb(12, info->c950ctrl + 1);
}
/* request_region? oxsemi branch does no request_region too... */
/*
* This sequence is needed to properly initialize MC45 attached to OXCF950.
* I tried decreasing these msleep()s, but it worked properly (survived
* 1000 stop/start operations) with these timeouts (or bigger).
*/
static void quirk_wakeup_possio_gcc(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
unsigned int ctrl = info->c950ctrl;
outb(0xA, ctrl + 1);
msleep(100);
outb(0xE, ctrl + 1);
msleep(300);
outb(0xC, ctrl + 1);
msleep(100);
outb(0xE, ctrl + 1);
msleep(200);
outb(0xF, ctrl + 1);
msleep(100);
outb(0xE, ctrl + 1);
msleep(100);
outb(0xC, ctrl + 1);
}
/*
* Socket Dual IO: this enables irq's for second port
*/
static void quirk_config_socket(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
if (info->multi)
link->config_flags |= CONF_ENABLE_ESR;
}
static const struct serial_quirk quirks[] = {
{
.manfid = 0x0160,
.prodid = 0x0104,
.multi = -1,
.setup = quirk_setup_brainboxes_0104,
}, {
.manfid = 0x015D,
.prodid = 0x4C45,
.multi = -1,
.setup = quirk_setup_brainboxes_0104,
}, {
.manfid = MANFID_IBM,
.prodid = ~0,
.multi = -1,
.post = quirk_post_ibm,
}, {
.manfid = MANFID_INTEL,
.prodid = PRODID_INTEL_DUAL_RS232,
.multi = 2,
}, {
.manfid = MANFID_NATINST,
.prodid = PRODID_NATINST_QUAD_RS232,
.multi = 4,
}, {
.manfid = MANFID_NOKIA,
.prodid = ~0,
.multi = -1,
.config = quirk_config_nokia,
}, {
.manfid = MANFID_OMEGA,
.prodid = PRODID_OMEGA_QSP_100,
.multi = 4,
}, {
.manfid = MANFID_OXSEMI,
.prodid = ~0,
.multi = -1,
.wakeup = quirk_wakeup_oxsemi,
}, {
.manfid = MANFID_POSSIO,
.prodid = PRODID_POSSIO_GCC,
.multi = -1,
.wakeup = quirk_wakeup_possio_gcc,
}, {
.manfid = MANFID_QUATECH,
.prodid = PRODID_QUATECH_DUAL_RS232,
.multi = 2,
}, {
.manfid = MANFID_QUATECH,
.prodid = PRODID_QUATECH_DUAL_RS232_D1,
.multi = 2,
}, {
.manfid = MANFID_QUATECH,
.prodid = PRODID_QUATECH_DUAL_RS232_G,
.multi = 2,
}, {
.manfid = MANFID_QUATECH,
.prodid = PRODID_QUATECH_QUAD_RS232,
.multi = 4,
}, {
.manfid = MANFID_SOCKET,
.prodid = PRODID_SOCKET_DUAL_RS232,
.multi = 2,
.config = quirk_config_socket,
}, {
.manfid = MANFID_SOCKET,
.prodid = ~0,
.multi = -1,
.config = quirk_config_socket,
}
};
static int serial_config(struct pcmcia_device * link);
static void serial_remove(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
int i;
dev_dbg(&link->dev, "serial_release\n");
/*
* Recheck to see if the device is still configured.
*/
for (i = 0; i < info->ndev; i++)
serial8250_unregister_port(info->line[i]);
if (!info->slave)
pcmcia_disable_device(link);
}
static int serial_suspend(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
int i;
for (i = 0; i < info->ndev; i++)
serial8250_suspend_port(info->line[i]);
return 0;
}
static int serial_resume(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
int i;
for (i = 0; i < info->ndev; i++)
serial8250_resume_port(info->line[i]);
if (info->quirk && info->quirk->wakeup)
info->quirk->wakeup(link);
return 0;
}
static int serial_probe(struct pcmcia_device *link)
{
struct serial_info *info;
dev_dbg(&link->dev, "serial_attach()\n");
/* Create new serial device */
info = kzalloc(sizeof (*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
info->p_dev = link;
link->priv = info;
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
if (do_sound)
link->config_flags |= CONF_ENABLE_SPKR;
return serial_config(link);
}
static void serial_detach(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
dev_dbg(&link->dev, "serial_detach\n");
/*
* Ensure that the ports have been released.
*/
serial_remove(link);
/* free bits */
kfree(info);
}
/*====================================================================*/
static int setup_serial(struct pcmcia_device *handle, struct serial_info * info,
unsigned int iobase, int irq)
{
struct uart_8250_port uart;
int line;
memset(&uart, 0, sizeof(uart));
uart.port.iobase = iobase;
uart.port.irq = irq;
uart.port.flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_SHARE_IRQ;
uart.port.uartclk = 1843200;
uart.port.dev = &handle->dev;
if (buggy_uart)
uart.port.flags |= UPF_BUGGY_UART;
if (info->quirk && info->quirk->setup)
info->quirk->setup(handle, &uart);
line = serial8250_register_8250_port(&uart);
if (line < 0) {
pr_err("serial_cs: serial8250_register_8250_port() at 0x%04lx, irq %d failed\n",
(unsigned long)iobase, irq);
return -EINVAL;
}
info->line[info->ndev] = line;
info->ndev++;
return 0;
}
/*====================================================================*/
static int pfc_config(struct pcmcia_device *p_dev)
{
unsigned int port = 0;
struct serial_info *info = p_dev->priv;
if ((p_dev->resource[1]->end != 0) &&
(resource_size(p_dev->resource[1]) == 8)) {
port = p_dev->resource[1]->start;
info->slave = 1;
} else if ((info->manfid == MANFID_OSITECH) &&
(resource_size(p_dev->resource[0]) == 0x40)) {
port = p_dev->resource[0]->start + 0x28;
info->slave = 1;
}
if (info->slave)
return setup_serial(p_dev, info, port, p_dev->irq);
dev_warn(&p_dev->dev, "no usable port range found, giving up\n");
return -ENODEV;
}
static int simple_config_check(struct pcmcia_device *p_dev, void *priv_data)
{
static const int size_table[2] = { 8, 16 };
int *try = priv_data;
if (p_dev->resource[0]->start == 0)
return -ENODEV;
if ((*try & 0x1) == 0)
p_dev->io_lines = 16;
if (p_dev->resource[0]->end != size_table[(*try >> 1)])
return -ENODEV;
p_dev->resource[0]->end = 8;
p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_8;
return pcmcia_request_io(p_dev);
}
static int simple_config_check_notpicky(struct pcmcia_device *p_dev,
void *priv_data)
{
static const unsigned int base[5] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, 0x0 };
int j;
if (p_dev->io_lines > 3)
return -ENODEV;
p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_8;
p_dev->resource[0]->end = 8;
for (j = 0; j < 5; j++) {
p_dev->resource[0]->start = base[j];
p_dev->io_lines = base[j] ? 16 : 3;
if (!pcmcia_request_io(p_dev))
return 0;
}
return -ENODEV;
}
static int simple_config(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
int i = -ENODEV, try;
/* First pass: look for a config entry that looks normal.
* Two tries: without IO aliases, then with aliases */
link->config_flags |= CONF_AUTO_SET_VPP;
for (try = 0; try < 4; try++)
if (!pcmcia_loop_config(link, simple_config_check, &try))
goto found_port;
/* Second pass: try to find an entry that isn't picky about
its base address, then try to grab any standard serial port
address, and finally try to get any free port. */
if (!pcmcia_loop_config(link, simple_config_check_notpicky, NULL))
goto found_port;
dev_warn(&link->dev, "no usable port range found, giving up\n");
return -1;
found_port:
if (info->multi && (info->manfid == MANFID_3COM))
link->config_index &= ~(0x08);
/*
* Apply any configuration quirks.
*/
if (info->quirk && info->quirk->config)
info->quirk->config(link);
i = pcmcia_enable_device(link);
if (i != 0)
return -1;
return setup_serial(link, info, link->resource[0]->start, link->irq);
}
static int multi_config_check(struct pcmcia_device *p_dev, void *priv_data)
{
int *multi = priv_data;
if (p_dev->resource[1]->end)
return -EINVAL;
/* The quad port cards have bad CIS's, so just look for a
window larger than 8 ports and assume it will be right */
if (p_dev->resource[0]->end <= 8)
return -EINVAL;
p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_8;
p_dev->resource[0]->end = *multi * 8;
if (pcmcia_request_io(p_dev))
return -ENODEV;
return 0;
}
static int multi_config_check_notpicky(struct pcmcia_device *p_dev,
void *priv_data)
{
int *base2 = priv_data;
if (!p_dev->resource[0]->end || !p_dev->resource[1]->end ||
p_dev->resource[0]->start + 8 != p_dev->resource[1]->start)
return -ENODEV;
p_dev->resource[0]->end = p_dev->resource[1]->end = 8;
p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_8;
if (pcmcia_request_io(p_dev))
return -ENODEV;
*base2 = p_dev->resource[0]->start + 8;
return 0;
}
static int multi_config(struct pcmcia_device *link)
{
struct serial_info *info = link->priv;
int i, base2 = 0;
/* First, look for a generic full-sized window */
if (!pcmcia_loop_config(link, multi_config_check, &info->multi))
base2 = link->resource[0]->start + 8;
else {
/* If that didn't work, look for two windows */
info->multi = 2;
if (pcmcia_loop_config(link, multi_config_check_notpicky,
&base2)) {
dev_warn(&link->dev, "no usable port range "
"found, giving up\n");
return -ENODEV;
}
}
if (!link->irq)
dev_warn(&link->dev, "no usable IRQ found, continuing...\n");
/*
* Apply any configuration quirks.
*/
if (info->quirk && info->quirk->config)
info->quirk->config(link);
i = pcmcia_enable_device(link);
if (i != 0)
return -ENODEV;
/* The Oxford Semiconductor OXCF950 cards are in fact single-port:
* 8 registers are for the UART, the others are extra registers.
* Siemen's MC45 PCMCIA (Possio's GCC) is OXCF950 based too.
*/
if (info->manfid == MANFID_OXSEMI || (info->manfid == MANFID_POSSIO &&
info->prodid == PRODID_POSSIO_GCC)) {
int err;
if (link->config_index == 1 ||
link->config_index == 3) {
err = setup_serial(link, info, base2,
link->irq);
base2 = link->resource[0]->start;
} else {
err = setup_serial(link, info, link->resource[0]->start,
link->irq);
}
info->c950ctrl = base2;
/*
* FIXME: We really should wake up the port prior to
* handing it over to the serial layer.
*/
if (info->quirk && info->quirk->wakeup)
info->quirk->wakeup(link);
return 0;
}
setup_serial(link, info, link->resource[0]->start, link->irq);
for (i = 0; i < info->multi - 1; i++)
setup_serial(link, info, base2 + (8 * i),
link->irq);
return 0;
}
static int serial_check_for_multi(struct pcmcia_device *p_dev, void *priv_data)
{
struct serial_info *info = p_dev->priv;
if (!p_dev->resource[0]->end)
return -EINVAL;
if ((!p_dev->resource[1]->end) && (p_dev->resource[0]->end % 8 == 0))
info->multi = p_dev->resource[0]->end >> 3;
if ((p_dev->resource[1]->end) && (p_dev->resource[0]->end == 8)
&& (p_dev->resource[1]->end == 8))
info->multi = 2;
return 0; /* break */
}
static int serial_config(struct pcmcia_device * link)
{
struct serial_info *info = link->priv;
int i;
dev_dbg(&link->dev, "serial_config\n");
/* Is this a compliant multifunction card? */
info->multi = (link->socket->functions > 1);
/* Is this a multiport card? */
info->manfid = link->manf_id;
info->prodid = link->card_id;
for (i = 0; i < ARRAY_SIZE(quirks); i++)
if ((quirks[i].manfid == ~0 ||
quirks[i].manfid == info->manfid) &&
(quirks[i].prodid == ~0 ||
quirks[i].prodid == info->prodid)) {
info->quirk = &quirks[i];
break;
}
/* Another check for dual-serial cards: look for either serial or
multifunction cards that ask for appropriate IO port ranges */
if ((info->multi == 0) &&
(link->has_func_id) &&
(link->socket->pcmcia_pfc == 0) &&
((link->func_id == CISTPL_FUNCID_MULTI) ||
(link->func_id == CISTPL_FUNCID_SERIAL)))
pcmcia_loop_config(link, serial_check_for_multi, info);
/*
* Apply any multi-port quirk.
*/
if (info->quirk && info->quirk->multi != -1)
info->multi = info->quirk->multi;
dev_info(&link->dev,
"trying to set up [0x%04x:0x%04x] (pfc: %d, multi: %d, quirk: %p)\n",
link->manf_id, link->card_id,
link->socket->pcmcia_pfc, info->multi, info->quirk);
if (link->socket->pcmcia_pfc)
i = pfc_config(link);
else if (info->multi > 1)
i = multi_config(link);
else
i = simple_config(link);
if (i || info->ndev == 0)
goto failed;
/*
* Apply any post-init quirk. FIXME: This should really happen
* before we register the port, since it might already be in use.
*/
if (info->quirk && info->quirk->post)
if (info->quirk->post(link))
goto failed;
return 0;
failed:
dev_warn(&link->dev, "failed to initialize\n");
serial_remove(link);
return -ENODEV;
}
static const struct pcmcia_device_id serial_ids[] = {
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0057, 0x0021),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0089, 0x110a),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0104, 0x000a),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0105, 0x0d0a),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0105, 0x0e0a),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0105, 0xea15),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0109, 0x0501),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0138, 0x110a),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0140, 0x000a),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0143, 0x3341),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0143, 0xc0ab),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x016c, 0x0081),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x021b, 0x0101),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x08a1, 0xc0ab),
PCMCIA_PFC_DEVICE_PROD_ID123(1, "MEGAHERTZ", "CC/XJEM3288", "DATA/FAX/CELL ETHERNET MODEM", 0xf510db04, 0x04cd2988, 0x46a52d63),
PCMCIA_PFC_DEVICE_PROD_ID123(1, "MEGAHERTZ", "CC/XJEM3336", "DATA/FAX/CELL ETHERNET MODEM", 0xf510db04, 0x0143b773, 0x46a52d63),
PCMCIA_PFC_DEVICE_PROD_ID123(1, "MEGAHERTZ", "EM1144T", "PCMCIA MODEM", 0xf510db04, 0x856d66c8, 0xbd6c43ef),
PCMCIA_PFC_DEVICE_PROD_ID123(1, "MEGAHERTZ", "XJEM1144/CCEM1144", "PCMCIA MODEM", 0xf510db04, 0x52d21e1e, 0xbd6c43ef),
PCMCIA_PFC_DEVICE_PROD_ID13(1, "Xircom", "CEM28", 0x2e3ee845, 0x0ea978ea),
PCMCIA_PFC_DEVICE_PROD_ID13(1, "Xircom", "CEM33", 0x2e3ee845, 0x80609023),
PCMCIA_PFC_DEVICE_PROD_ID13(1, "Xircom", "CEM56", 0x2e3ee845, 0xa650c32a),
PCMCIA_PFC_DEVICE_PROD_ID13(1, "Xircom", "REM10", 0x2e3ee845, 0x76df1d29),
PCMCIA_PFC_DEVICE_PROD_ID13(1, "Xircom", "XEM5600", 0x2e3ee845, 0xf1403719),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "AnyCom", "Fast Ethernet + 56K COMBO", 0x578ba6e7, 0xb0ac62c4),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "ATKK", "LM33-PCM-T", 0xba9eb7e2, 0x077c174e),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "D-Link", "DME336T", 0x1a424a1c, 0xb23897ff),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "Gateway 2000", "XJEM3336", 0xdd9989be, 0x662c394c),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "Grey Cell", "GCS3000", 0x2a151fac, 0x48b932ae),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "Linksys", "EtherFast 10&100 + 56K PC Card (PCMLM56)", 0x0733cc81, 0xb3765033),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "LINKSYS", "PCMLM336", 0xf7cb0b07, 0x7a821b58),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "MEGAHERTZ", "XJEM1144/CCEM1144", 0xf510db04, 0x52d21e1e),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "MICRO RESEARCH", "COMBO-L/M-336", 0xb2ced065, 0x3ced0555),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "NEC", "PK-UG-J001" ,0x18df0ba0 ,0x831b1064),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "Ositech", "Trumpcard:Jack of Diamonds Modem+Ethernet", 0xc2f80cd, 0x656947b9),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "Ositech", "Trumpcard:Jack of Hearts Modem+Ethernet", 0xc2f80cd, 0xdc9ba5ed),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "PCMCIAs", "ComboCard", 0xdcfe12d3, 0xcd8906cc),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "PCMCIAs", "LanModem", 0xdcfe12d3, 0xc67c648f),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "TDK", "GlobalNetworker 3410/3412", 0x1eae9475, 0xd9a93bed),
PCMCIA_PFC_DEVICE_PROD_ID12(1, "Xircom", "CreditCard Ethernet+Modem II", 0x2e3ee845, 0xeca401bf),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0032, 0x0e01),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0032, 0x0a05),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0032, 0x0b05),
PCMCIA_PFC_DEVICE_MANF_CARD(1, 0x0032, 0x1101),
PCMCIA_MFC_DEVICE_MANF_CARD(0, 0x0104, 0x0070),
PCMCIA_MFC_DEVICE_MANF_CARD(1, 0x0101, 0x0562),
PCMCIA_MFC_DEVICE_MANF_CARD(1, 0x0104, 0x0070),
PCMCIA_MFC_DEVICE_MANF_CARD(1, 0x016c, 0x0020),
PCMCIA_MFC_DEVICE_PROD_ID123(1, "APEX DATA", "MULTICARD", "ETHERNET-MODEM", 0x11c2da09, 0x7289dc5d, 0xaad95e1f),
PCMCIA_MFC_DEVICE_PROD_ID12(1, "IBM", "Home and Away 28.8 PC Card ", 0xb569a6e5, 0x5bd4ff2c),
PCMCIA_MFC_DEVICE_PROD_ID12(1, "IBM", "Home and Away Credit Card Adapter", 0xb569a6e5, 0x4bdf15c3),
PCMCIA_MFC_DEVICE_PROD_ID12(1, "IBM", "w95 Home and Away Credit Card ", 0xb569a6e5, 0xae911c15),
PCMCIA_MFC_DEVICE_PROD_ID1(1, "Motorola MARQUIS", 0xf03e4e77),
PCMCIA_MFC_DEVICE_PROD_ID2(1, "FAX/Modem/Ethernet Combo Card ", 0x1ed59302),
PCMCIA_DEVICE_MANF_CARD(0x0089, 0x0301),
PCMCIA_DEVICE_MANF_CARD(0x00a4, 0x0276),
PCMCIA_DEVICE_MANF_CARD(0x0101, 0x0039),
PCMCIA_DEVICE_MANF_CARD(0x0104, 0x0006),
PCMCIA_DEVICE_MANF_CARD(0x0105, 0x0101), /* TDK DF2814 */
PCMCIA_DEVICE_MANF_CARD(0x0105, 0x100a), /* Xircom CM-56G */
PCMCIA_DEVICE_MANF_CARD(0x0105, 0x3e0a), /* TDK DF5660 */
PCMCIA_DEVICE_MANF_CARD(0x0105, 0x410a),
PCMCIA_DEVICE_MANF_CARD(0x0107, 0x0002), /* USRobotics 14,400 */
PCMCIA_DEVICE_MANF_CARD(0x010b, 0x0d50),
PCMCIA_DEVICE_MANF_CARD(0x010b, 0x0d51),
PCMCIA_DEVICE_MANF_CARD(0x010b, 0x0d52),
PCMCIA_DEVICE_MANF_CARD(0x010b, 0x0d53),
PCMCIA_DEVICE_MANF_CARD(0x010b, 0xd180),
PCMCIA_DEVICE_MANF_CARD(0x0115, 0x3330), /* USRobotics/SUN 14,400 */
PCMCIA_DEVICE_MANF_CARD(0x0124, 0x0100), /* Nokia DTP-2 ver II */
PCMCIA_DEVICE_MANF_CARD(0x0134, 0x5600), /* LASAT COMMUNICATIONS A/S */
PCMCIA_DEVICE_MANF_CARD(0x0137, 0x000e),
PCMCIA_DEVICE_MANF_CARD(0x0137, 0x001b),
PCMCIA_DEVICE_MANF_CARD(0x0137, 0x0025),
PCMCIA_DEVICE_MANF_CARD(0x0137, 0x0045),
PCMCIA_DEVICE_MANF_CARD(0x0137, 0x0052),
PCMCIA_DEVICE_MANF_CARD(0x016c, 0x0006), /* Psion 56K+Fax */
PCMCIA_DEVICE_MANF_CARD(0x0200, 0x0001), /* MultiMobile */
PCMCIA_DEVICE_PROD_ID134("ADV", "TECH", "COMpad-32/85", 0x67459937, 0x916d02ba, 0x8fbe92ae),
PCMCIA_DEVICE_PROD_ID124("GATEWAY2000", "CC3144", "PCMCIA MODEM", 0x506bccae, 0xcb3685f1, 0xbd6c43ef),
PCMCIA_DEVICE_PROD_ID14("MEGAHERTZ", "PCMCIA MODEM", 0xf510db04, 0xbd6c43ef),
PCMCIA_DEVICE_PROD_ID124("TOSHIBA", "T144PF", "PCMCIA MODEM", 0xb4585a1a, 0x7271409c, 0xbd6c43ef),
PCMCIA_DEVICE_PROD_ID123("FUJITSU", "FC14F ", "MBH10213", 0x6ee5a3d8, 0x30ead12b, 0xb00f05a0),
PCMCIA_DEVICE_PROD_ID123("Novatel Wireless", "Merlin UMTS Modem", "U630", 0x32607776, 0xd9e73b13, 0xe87332e),
PCMCIA_DEVICE_PROD_ID13("MEGAHERTZ", "V.34 PCMCIA MODEM", 0xf510db04, 0xbb2cce4a),
PCMCIA_DEVICE_PROD_ID12("Brain Boxes", "Bluetooth PC Card", 0xee138382, 0xd4ce9b02),
PCMCIA_DEVICE_PROD_ID12("CIRRUS LOGIC", "FAX MODEM", 0xe625f451, 0xcecd6dfa),
PCMCIA_DEVICE_PROD_ID12("COMPAQ", "PCMCIA 28800 FAX/DATA MODEM", 0xa3a3062c, 0x8cbd7c76),
PCMCIA_DEVICE_PROD_ID12("COMPAQ", "PCMCIA 33600 FAX/DATA MODEM", 0xa3a3062c, 0x5a00ce95),
PCMCIA_DEVICE_PROD_ID12("Computerboards, Inc.", "PCM-COM422", 0xd0b78f51, 0x7e2d49ed),
PCMCIA_DEVICE_PROD_ID12("Dr. Neuhaus", "FURY CARD 14K4", 0x76942813, 0x8b96ce65),
PCMCIA_DEVICE_PROD_ID12("IBM", "ISDN/56K/GSM", 0xb569a6e5, 0xfee5297b),
PCMCIA_DEVICE_PROD_ID12("Intelligent", "ANGIA FAX/MODEM", 0xb496e65e, 0xf31602a6),
PCMCIA_DEVICE_PROD_ID12("Intel", "MODEM 2400+", 0x816cc815, 0x412729fb),
PCMCIA_DEVICE_PROD_ID12("Intertex", "IX34-PCMCIA", 0xf8a097e3, 0x97880447),
PCMCIA_DEVICE_PROD_ID12("IOTech Inc ", "PCMCIA Dual RS-232 Serial Port Card", 0x3bd2d898, 0x92abc92f),
PCMCIA_DEVICE_PROD_ID12("MACRONIX", "FAX/MODEM", 0x668388b3, 0x3f9bdf2f),
PCMCIA_DEVICE_PROD_ID12("Multi-Tech", "MT1432LT", 0x5f73be51, 0x0b3e2383),
PCMCIA_DEVICE_PROD_ID12("Multi-Tech", "MT2834LT", 0x5f73be51, 0x4cd7c09e),
PCMCIA_DEVICE_PROD_ID12("OEM ", "C288MX ", 0xb572d360, 0xd2385b7a),
PCMCIA_DEVICE_PROD_ID12("Option International", "V34bis GSM/PSTN Data/Fax Modem", 0x9d7cd6f5, 0x5cb8bf41),
PCMCIA_DEVICE_PROD_ID12("PCMCIA ", "C336MX ", 0x99bcafe9, 0xaa25bcab),
PCMCIA_DEVICE_PROD_ID12("Quatech Inc", "PCMCIA Dual RS-232 Serial Port Card", 0xc4420b35, 0x92abc92f),
PCMCIA_DEVICE_PROD_ID12("Quatech Inc", "Dual RS-232 Serial Port PC Card", 0xc4420b35, 0x031a380d),
PCMCIA_DEVICE_PROD_ID12("Telia", "SurfinBird 560P/A+", 0xe2cdd5e, 0xc9314b38),
PCMCIA_DEVICE_PROD_ID1("Smart Serial Port", 0x2d8ce292),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(1, "PCMCIA", "EN2218-LAN/MODEM", 0x281f1c5d, 0x570f348e, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(1, "PCMCIA", "UE2218-LAN/MODEM", 0x281f1c5d, 0x6fdcacee, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(1, "Psion Dacom", "Gold Card V34 Ethernet", 0xf5f025c2, 0x338e8155, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(1, "Psion Dacom", "Gold Card V34 Ethernet GSM", 0xf5f025c2, 0x4ae85d35, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(1, "LINKSYS", "PCMLM28", 0xf7cb0b07, 0x66881874, "cis/PCMLM28.cis"),
PCMCIA_PFC_DEVICE_CIS_PROD_ID12(1, "TOSHIBA", "Modem/LAN Card", 0xb4585a1a, 0x53f922f8, "cis/PCMLM28.cis"),
PCMCIA_MFC_DEVICE_CIS_PROD_ID12(1, "DAYNA COMMUNICATIONS", "LAN AND MODEM MULTIFUNCTION", 0x8fdf8f89, 0xdd5ed9e8, "cis/DP83903.cis"),
PCMCIA_MFC_DEVICE_CIS_PROD_ID4(1, "NSC MF LAN/Modem", 0x58fc6056, "cis/DP83903.cis"),
PCMCIA_MFC_DEVICE_CIS_MANF_CARD(1, 0x0101, 0x0556, "cis/3CCFEM556.cis"),
PCMCIA_MFC_DEVICE_CIS_MANF_CARD(1, 0x0175, 0x0000, "cis/DP83903.cis"),
PCMCIA_MFC_DEVICE_CIS_MANF_CARD(1, 0x0101, 0x0035, "cis/3CXEM556.cis"),
PCMCIA_MFC_DEVICE_CIS_MANF_CARD(1, 0x0101, 0x003d, "cis/3CXEM556.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("Sierra Wireless", "AC850", 0xd85f6206, 0x42a2c018, "cis/SW_8xx_SER.cis"), /* Sierra Wireless AC850 3G Network Adapter R1 */
PCMCIA_DEVICE_CIS_PROD_ID12("Sierra Wireless", "AC860", 0xd85f6206, 0x698f93db, "cis/SW_8xx_SER.cis"), /* Sierra Wireless AC860 3G Network Adapter R1 */
PCMCIA_DEVICE_CIS_PROD_ID12("Sierra Wireless", "AC710/AC750", 0xd85f6206, 0x761b11e0, "cis/SW_7xx_SER.cis"), /* Sierra Wireless AC710/AC750 GPRS Network Adapter R1 */
PCMCIA_DEVICE_CIS_MANF_CARD(0x0192, 0xa555, "cis/SW_555_SER.cis"), /* Sierra Aircard 555 CDMA 1xrtt Modem -- pre update */
PCMCIA_DEVICE_CIS_MANF_CARD(0x013f, 0xa555, "cis/SW_555_SER.cis"), /* Sierra Aircard 555 CDMA 1xrtt Modem -- post update */
PCMCIA_DEVICE_CIS_PROD_ID12("MultiTech", "PCMCIA 56K DataFax", 0x842047ee, 0xc2efcf03, "cis/MT5634ZLX.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("ADVANTECH", "COMpad-32/85B-2", 0x96913a85, 0x27ab5437, "cis/COMpad2.cis"),
PCMCIA_DEVICE_CIS_PROD_ID12("ADVANTECH", "COMpad-32/85B-4", 0x96913a85, 0xcec8f102, "cis/COMpad4.cis"),
PCMCIA_DEVICE_CIS_PROD_ID123("ADVANTECH", "COMpad-32/85", "1.0", 0x96913a85, 0x8fbe92ae, 0x0877b627, "cis/COMpad2.cis"),
PCMCIA_DEVICE_CIS_PROD_ID2("RS-COM 2P", 0xad20b156, "cis/RS-COM-2P.cis"),
PCMCIA_DEVICE_CIS_MANF_CARD(0x0013, 0x0000, "cis/GLOBETROTTER.cis"),
PCMCIA_DEVICE_PROD_ID12("ELAN DIGITAL SYSTEMS LTD, c1997.","SERIAL CARD: SL100 1.00.",0x19ca78af,0xf964f42b),
PCMCIA_DEVICE_PROD_ID12("ELAN DIGITAL SYSTEMS LTD, c1997.","SERIAL CARD: SL100",0x19ca78af,0x71d98e83),
PCMCIA_DEVICE_PROD_ID12("ELAN DIGITAL SYSTEMS LTD, c1997.","SERIAL CARD: SL232 1.00.",0x19ca78af,0x69fb7490),
PCMCIA_DEVICE_PROD_ID12("ELAN DIGITAL SYSTEMS LTD, c1997.","SERIAL CARD: SL232",0x19ca78af,0xb6bc0235),
PCMCIA_DEVICE_PROD_ID12("ELAN DIGITAL SYSTEMS LTD, c2000.","SERIAL CARD: CF232",0x63f2e0bd,0xb9e175d3),
PCMCIA_DEVICE_PROD_ID12("ELAN DIGITAL SYSTEMS LTD, c2000.","SERIAL CARD: CF232-5",0x63f2e0bd,0xfce33442),
PCMCIA_DEVICE_PROD_ID12("Elan","Serial Port: CF232",0x3beb8cf2,0x171e7190),
PCMCIA_DEVICE_PROD_ID12("Elan","Serial Port: CF232-5",0x3beb8cf2,0x20da4262),
PCMCIA_DEVICE_PROD_ID12("Elan","Serial Port: CF428",0x3beb8cf2,0xea5dd57d),
PCMCIA_DEVICE_PROD_ID12("Elan","Serial Port: CF500",0x3beb8cf2,0xd77255fa),
PCMCIA_DEVICE_PROD_ID12("Elan","Serial Port: IC232",0x3beb8cf2,0x6a709903),
PCMCIA_DEVICE_PROD_ID12("Elan","Serial Port: SL232",0x3beb8cf2,0x18430676),
PCMCIA_DEVICE_PROD_ID12("Elan","Serial Port: XL232",0x3beb8cf2,0x6f933767),
PCMCIA_MFC_DEVICE_PROD_ID12(0,"Elan","Serial Port: CF332",0x3beb8cf2,0x16dc1ba7),
PCMCIA_MFC_DEVICE_PROD_ID12(0,"Elan","Serial Port: SL332",0x3beb8cf2,0x19816c41),
PCMCIA_MFC_DEVICE_PROD_ID12(0,"Elan","Serial Port: SL385",0x3beb8cf2,0x64112029),
PCMCIA_MFC_DEVICE_PROD_ID12(0,"Elan","Serial Port: SL432",0x3beb8cf2,0x1cce7ac4),
PCMCIA_MFC_DEVICE_PROD_ID12(0,"Elan","Serial+Parallel Port: SP230",0x3beb8cf2,0xdb9e58bc),
PCMCIA_MFC_DEVICE_PROD_ID12(1,"Elan","Serial Port: CF332",0x3beb8cf2,0x16dc1ba7),
PCMCIA_MFC_DEVICE_PROD_ID12(1,"Elan","Serial Port: SL332",0x3beb8cf2,0x19816c41),
PCMCIA_MFC_DEVICE_PROD_ID12(1,"Elan","Serial Port: SL385",0x3beb8cf2,0x64112029),
PCMCIA_MFC_DEVICE_PROD_ID12(1,"Elan","Serial Port: SL432",0x3beb8cf2,0x1cce7ac4),
PCMCIA_MFC_DEVICE_PROD_ID12(2,"Elan","Serial Port: SL432",0x3beb8cf2,0x1cce7ac4),
PCMCIA_MFC_DEVICE_PROD_ID12(3,"Elan","Serial Port: SL432",0x3beb8cf2,0x1cce7ac4),
PCMCIA_DEVICE_MANF_CARD(0x0279, 0x950b),
/* too generic */
/* PCMCIA_MFC_DEVICE_MANF_CARD(0, 0x0160, 0x0002), */
/* PCMCIA_MFC_DEVICE_MANF_CARD(1, 0x0160, 0x0002), */
PCMCIA_DEVICE_FUNC_ID(2),
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, serial_ids);
MODULE_FIRMWARE("cis/PCMLM28.cis");
MODULE_FIRMWARE("cis/DP83903.cis");
MODULE_FIRMWARE("cis/3CCFEM556.cis");
MODULE_FIRMWARE("cis/3CXEM556.cis");
MODULE_FIRMWARE("cis/SW_8xx_SER.cis");
MODULE_FIRMWARE("cis/SW_7xx_SER.cis");
MODULE_FIRMWARE("cis/SW_555_SER.cis");
MODULE_FIRMWARE("cis/MT5634ZLX.cis");
MODULE_FIRMWARE("cis/COMpad2.cis");
MODULE_FIRMWARE("cis/COMpad4.cis");
MODULE_FIRMWARE("cis/RS-COM-2P.cis");
static struct pcmcia_driver serial_cs_driver = {
.owner = THIS_MODULE,
.name = "serial_cs",
.probe = serial_probe,
.remove = serial_detach,
.id_table = serial_ids,
.suspend = serial_suspend,
.resume = serial_resume,
};
module_pcmcia_driver(serial_cs_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
daler3/smack-next | arch/powerpc/oprofile/op_model_7450.c | 2315 | 5333 | /*
* arch/powerpc/oprofile/op_model_7450.c
*
* Freescale 745x/744x oprofile support, based on fsl_booke support
* Copyright (C) 2004 Anton Blanchard <anton@au.ibm.com>, IBM
*
* Copyright (c) 2004 Freescale Semiconductor, Inc
*
* Author: Andy Fleming
* Maintainer: Kumar Gala <galak@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/oprofile.h>
#include <linux/smp.h>
#include <asm/ptrace.h>
#include <asm/processor.h>
#include <asm/cputable.h>
#include <asm/page.h>
#include <asm/pmc.h>
#include <asm/oprofile_impl.h>
static unsigned long reset_value[OP_MAX_COUNTER];
static int oprofile_running;
static u32 mmcr0_val, mmcr1_val, mmcr2_val, num_pmcs;
#define MMCR0_PMC1_SHIFT 6
#define MMCR0_PMC2_SHIFT 0
#define MMCR1_PMC3_SHIFT 27
#define MMCR1_PMC4_SHIFT 22
#define MMCR1_PMC5_SHIFT 17
#define MMCR1_PMC6_SHIFT 11
#define mmcr0_event1(event) \
((event << MMCR0_PMC1_SHIFT) & MMCR0_PMC1SEL)
#define mmcr0_event2(event) \
((event << MMCR0_PMC2_SHIFT) & MMCR0_PMC2SEL)
#define mmcr1_event3(event) \
((event << MMCR1_PMC3_SHIFT) & MMCR1_PMC3SEL)
#define mmcr1_event4(event) \
((event << MMCR1_PMC4_SHIFT) & MMCR1_PMC4SEL)
#define mmcr1_event5(event) \
((event << MMCR1_PMC5_SHIFT) & MMCR1_PMC5SEL)
#define mmcr1_event6(event) \
((event << MMCR1_PMC6_SHIFT) & MMCR1_PMC6SEL)
#define MMCR0_INIT (MMCR0_FC | MMCR0_FCS | MMCR0_FCP | MMCR0_FCM1 | MMCR0_FCM0)
/* Unfreezes the counters on this CPU, enables the interrupt,
* enables the counters to trigger the interrupt, and sets the
* counters to only count when the mark bit is not set.
*/
static void pmc_start_ctrs(void)
{
u32 mmcr0 = mfspr(SPRN_MMCR0);
mmcr0 &= ~(MMCR0_FC | MMCR0_FCM0);
mmcr0 |= (MMCR0_FCECE | MMCR0_PMC1CE | MMCR0_PMCnCE | MMCR0_PMXE);
mtspr(SPRN_MMCR0, mmcr0);
}
/* Disables the counters on this CPU, and freezes them */
static void pmc_stop_ctrs(void)
{
u32 mmcr0 = mfspr(SPRN_MMCR0);
mmcr0 |= MMCR0_FC;
mmcr0 &= ~(MMCR0_FCECE | MMCR0_PMC1CE | MMCR0_PMCnCE | MMCR0_PMXE);
mtspr(SPRN_MMCR0, mmcr0);
}
/* Configures the counters on this CPU based on the global
* settings */
static int fsl7450_cpu_setup(struct op_counter_config *ctr)
{
/* freeze all counters */
pmc_stop_ctrs();
mtspr(SPRN_MMCR0, mmcr0_val);
mtspr(SPRN_MMCR1, mmcr1_val);
if (num_pmcs > 4)
mtspr(SPRN_MMCR2, mmcr2_val);
return 0;
}
/* Configures the global settings for the countes on all CPUs. */
static int fsl7450_reg_setup(struct op_counter_config *ctr,
struct op_system_config *sys,
int num_ctrs)
{
int i;
num_pmcs = num_ctrs;
/* Our counters count up, and "count" refers to
* how much before the next interrupt, and we interrupt
* on overflow. So we calculate the starting value
* which will give us "count" until overflow.
* Then we set the events on the enabled counters */
for (i = 0; i < num_ctrs; ++i)
reset_value[i] = 0x80000000UL - ctr[i].count;
/* Set events for Counters 1 & 2 */
mmcr0_val = MMCR0_INIT | mmcr0_event1(ctr[0].event)
| mmcr0_event2(ctr[1].event);
/* Setup user/kernel bits */
if (sys->enable_kernel)
mmcr0_val &= ~(MMCR0_FCS);
if (sys->enable_user)
mmcr0_val &= ~(MMCR0_FCP);
/* Set events for Counters 3-6 */
mmcr1_val = mmcr1_event3(ctr[2].event)
| mmcr1_event4(ctr[3].event);
if (num_ctrs > 4)
mmcr1_val |= mmcr1_event5(ctr[4].event)
| mmcr1_event6(ctr[5].event);
mmcr2_val = 0;
return 0;
}
/* Sets the counters on this CPU to the chosen values, and starts them */
static int fsl7450_start(struct op_counter_config *ctr)
{
int i;
mtmsr(mfmsr() | MSR_PMM);
for (i = 0; i < num_pmcs; ++i) {
if (ctr[i].enabled)
classic_ctr_write(i, reset_value[i]);
else
classic_ctr_write(i, 0);
}
/* Clear the freeze bit, and enable the interrupt.
* The counters won't actually start until the rfi clears
* the PMM bit */
pmc_start_ctrs();
oprofile_running = 1;
return 0;
}
/* Stop the counters on this CPU */
static void fsl7450_stop(void)
{
/* freeze counters */
pmc_stop_ctrs();
oprofile_running = 0;
mb();
}
/* Handle the interrupt on this CPU, and log a sample for each
* event that triggered the interrupt */
static void fsl7450_handle_interrupt(struct pt_regs *regs,
struct op_counter_config *ctr)
{
unsigned long pc;
int is_kernel;
int val;
int i;
/* set the PMM bit (see comment below) */
mtmsr(mfmsr() | MSR_PMM);
pc = mfspr(SPRN_SIAR);
is_kernel = is_kernel_addr(pc);
for (i = 0; i < num_pmcs; ++i) {
val = classic_ctr_read(i);
if (val < 0) {
if (oprofile_running && ctr[i].enabled) {
oprofile_add_ext_sample(pc, regs, i, is_kernel);
classic_ctr_write(i, reset_value[i]);
} else {
classic_ctr_write(i, 0);
}
}
}
/* The freeze bit was set by the interrupt. */
/* Clear the freeze bit, and reenable the interrupt.
* The counters won't actually start until the rfi clears
* the PM/M bit */
pmc_start_ctrs();
}
struct op_powerpc_model op_model_7450= {
.reg_setup = fsl7450_reg_setup,
.cpu_setup = fsl7450_cpu_setup,
.start = fsl7450_start,
.stop = fsl7450_stop,
.handle_interrupt = fsl7450_handle_interrupt,
};
| gpl-2.0 |
Dm47021/android_kernel_samsung_centura_sch738c | security/tomoyo/securityfs_if.c | 2827 | 4258 | /*
* security/tomoyo/common.c
*
* Securityfs interface for TOMOYO.
*
* Copyright (C) 2005-2010 NTT DATA CORPORATION
*/
#include <linux/security.h>
#include "common.h"
/**
* tomoyo_open - open() for /sys/kernel/security/tomoyo/ interface.
*
* @inode: Pointer to "struct inode".
* @file: Pointer to "struct file".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_open(struct inode *inode, struct file *file)
{
const int key = ((u8 *) file->f_path.dentry->d_inode->i_private)
- ((u8 *) NULL);
return tomoyo_open_control(key, file);
}
/**
* tomoyo_release - close() for /sys/kernel/security/tomoyo/ interface.
*
* @inode: Pointer to "struct inode".
* @file: Pointer to "struct file".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_release(struct inode *inode, struct file *file)
{
return tomoyo_close_control(file);
}
/**
* tomoyo_poll - poll() for /proc/ccs/ interface.
*
* @file: Pointer to "struct file".
* @wait: Pointer to "poll_table".
*
* Returns 0 on success, negative value otherwise.
*/
static unsigned int tomoyo_poll(struct file *file, poll_table *wait)
{
return tomoyo_poll_control(file, wait);
}
/**
* tomoyo_read - read() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @buf: Pointer to buffer.
* @count: Size of @buf.
* @ppos: Unused.
*
* Returns bytes read on success, negative value otherwise.
*/
static ssize_t tomoyo_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
return tomoyo_read_control(file, buf, count);
}
/**
* tomoyo_write - write() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @buf: Pointer to buffer.
* @count: Size of @buf.
* @ppos: Unused.
*
* Returns @count on success, negative value otherwise.
*/
static ssize_t tomoyo_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return tomoyo_write_control(file, buf, count);
}
/*
* tomoyo_operations is a "struct file_operations" which is used for handling
* /sys/kernel/security/tomoyo/ interface.
*
* Some files under /sys/kernel/security/tomoyo/ directory accept open(O_RDWR).
* See tomoyo_io_buffer for internals.
*/
static const struct file_operations tomoyo_operations = {
.open = tomoyo_open,
.release = tomoyo_release,
.poll = tomoyo_poll,
.read = tomoyo_read,
.write = tomoyo_write,
.llseek = noop_llseek,
};
/**
* tomoyo_create_entry - Create interface files under /sys/kernel/security/tomoyo/ directory.
*
* @name: The name of the interface file.
* @mode: The permission of the interface file.
* @parent: The parent directory.
* @key: Type of interface.
*
* Returns nothing.
*/
static void __init tomoyo_create_entry(const char *name, const mode_t mode,
struct dentry *parent, const u8 key)
{
securityfs_create_file(name, mode, parent, ((u8 *) NULL) + key,
&tomoyo_operations);
}
/**
* tomoyo_initerface_init - Initialize /sys/kernel/security/tomoyo/ interface.
*
* Returns 0.
*/
static int __init tomoyo_initerface_init(void)
{
struct dentry *tomoyo_dir;
/* Don't create securityfs entries unless registered. */
if (current_cred()->security != &tomoyo_kernel_domain)
return 0;
tomoyo_dir = securityfs_create_dir("tomoyo", NULL);
tomoyo_create_entry("query", 0600, tomoyo_dir,
TOMOYO_QUERY);
tomoyo_create_entry("domain_policy", 0600, tomoyo_dir,
TOMOYO_DOMAINPOLICY);
tomoyo_create_entry("exception_policy", 0600, tomoyo_dir,
TOMOYO_EXCEPTIONPOLICY);
tomoyo_create_entry("self_domain", 0400, tomoyo_dir,
TOMOYO_SELFDOMAIN);
tomoyo_create_entry(".domain_status", 0600, tomoyo_dir,
TOMOYO_DOMAIN_STATUS);
tomoyo_create_entry(".process_status", 0600, tomoyo_dir,
TOMOYO_PROCESS_STATUS);
tomoyo_create_entry("meminfo", 0600, tomoyo_dir,
TOMOYO_MEMINFO);
tomoyo_create_entry("profile", 0600, tomoyo_dir,
TOMOYO_PROFILE);
tomoyo_create_entry("manager", 0600, tomoyo_dir,
TOMOYO_MANAGER);
tomoyo_create_entry("version", 0400, tomoyo_dir,
TOMOYO_VERSION);
return 0;
}
fs_initcall(tomoyo_initerface_init);
| gpl-2.0 |
Dzemiq/android_kernel_samsung_i9300 | arch/arm/mach-msm/clock-pcom.c | 3595 | 3153 | /*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2007-2010, Code Aurora Forum. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/stddef.h>
#include <mach/clk.h>
#include "proc_comm.h"
#include "clock.h"
#include "clock-pcom.h"
/*
* glue for the proc_comm interface
*/
int pc_clk_enable(unsigned id)
{
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_ENABLE, &id, NULL);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
void pc_clk_disable(unsigned id)
{
msm_proc_comm(PCOM_CLKCTL_RPC_DISABLE, &id, NULL);
}
int pc_clk_reset(unsigned id, enum clk_reset_action action)
{
int rc;
if (action == CLK_RESET_ASSERT)
rc = msm_proc_comm(PCOM_CLKCTL_RPC_RESET_ASSERT, &id, NULL);
else
rc = msm_proc_comm(PCOM_CLKCTL_RPC_RESET_DEASSERT, &id, NULL);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_rate(unsigned id, unsigned rate)
{
/* The rate _might_ be rounded off to the nearest KHz value by the
* remote function. So a return value of 0 doesn't necessarily mean
* that the exact rate was set successfully.
*/
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_SET_RATE, &id, &rate);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_min_rate(unsigned id, unsigned rate)
{
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_MIN_RATE, &id, &rate);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_max_rate(unsigned id, unsigned rate)
{
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_MAX_RATE, &id, &rate);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
int pc_clk_set_flags(unsigned id, unsigned flags)
{
int rc = msm_proc_comm(PCOM_CLKCTL_RPC_SET_FLAGS, &id, &flags);
if (rc < 0)
return rc;
else
return (int)id < 0 ? -EINVAL : 0;
}
unsigned pc_clk_get_rate(unsigned id)
{
if (msm_proc_comm(PCOM_CLKCTL_RPC_RATE, &id, NULL))
return 0;
else
return id;
}
unsigned pc_clk_is_enabled(unsigned id)
{
if (msm_proc_comm(PCOM_CLKCTL_RPC_ENABLED, &id, NULL))
return 0;
else
return id;
}
long pc_clk_round_rate(unsigned id, unsigned rate)
{
/* Not really supported; pc_clk_set_rate() does rounding on it's own. */
return rate;
}
static bool pc_clk_is_local(unsigned id)
{
return false;
}
struct clk_ops clk_ops_pcom = {
.enable = pc_clk_enable,
.disable = pc_clk_disable,
.auto_off = pc_clk_disable,
.reset = pc_clk_reset,
.set_rate = pc_clk_set_rate,
.set_min_rate = pc_clk_set_min_rate,
.set_max_rate = pc_clk_set_max_rate,
.set_flags = pc_clk_set_flags,
.get_rate = pc_clk_get_rate,
.is_enabled = pc_clk_is_enabled,
.round_rate = pc_clk_round_rate,
.is_local = pc_clk_is_local,
};
| gpl-2.0 |
RenderBroken/msm8974_G2-CAF_render_kernel | arch/x86/crypto/crc32c-intel.c | 4875 | 5156 | /*
* Using hardware provided CRC32 instruction to accelerate the CRC32 disposal.
* CRC32C polynomial:0x1EDC6F41(BE)/0x82F63B78(LE)
* CRC32 is a new instruction in Intel SSE4.2, the reference can be found at:
* http://www.intel.com/products/processor/manuals/
* Intel(R) 64 and IA-32 Architectures Software Developer's Manual
* Volume 2A: Instruction Set Reference, A-M
*
* Copyright (C) 2008 Intel Corporation
* Authors: Austin Zhang <austin_zhang@linux.intel.com>
* Kent Liu <kent.liu@intel.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <crypto/internal/hash.h>
#include <asm/cpufeature.h>
#include <asm/cpu_device_id.h>
#define CHKSUM_BLOCK_SIZE 1
#define CHKSUM_DIGEST_SIZE 4
#define SCALE_F sizeof(unsigned long)
#ifdef CONFIG_X86_64
#define REX_PRE "0x48, "
#else
#define REX_PRE
#endif
static u32 crc32c_intel_le_hw_byte(u32 crc, unsigned char const *data, size_t length)
{
while (length--) {
__asm__ __volatile__(
".byte 0xf2, 0xf, 0x38, 0xf0, 0xf1"
:"=S"(crc)
:"0"(crc), "c"(*data)
);
data++;
}
return crc;
}
static u32 __pure crc32c_intel_le_hw(u32 crc, unsigned char const *p, size_t len)
{
unsigned int iquotient = len / SCALE_F;
unsigned int iremainder = len % SCALE_F;
unsigned long *ptmp = (unsigned long *)p;
while (iquotient--) {
__asm__ __volatile__(
".byte 0xf2, " REX_PRE "0xf, 0x38, 0xf1, 0xf1;"
:"=S"(crc)
:"0"(crc), "c"(*ptmp)
);
ptmp++;
}
if (iremainder)
crc = crc32c_intel_le_hw_byte(crc, (unsigned char *)ptmp,
iremainder);
return crc;
}
/*
* Setting the seed allows arbitrary accumulators and flexible XOR policy
* If your algorithm starts with ~0, then XOR with ~0 before you set
* the seed.
*/
static int crc32c_intel_setkey(struct crypto_shash *hash, const u8 *key,
unsigned int keylen)
{
u32 *mctx = crypto_shash_ctx(hash);
if (keylen != sizeof(u32)) {
crypto_shash_set_flags(hash, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
*mctx = le32_to_cpup((__le32 *)key);
return 0;
}
static int crc32c_intel_init(struct shash_desc *desc)
{
u32 *mctx = crypto_shash_ctx(desc->tfm);
u32 *crcp = shash_desc_ctx(desc);
*crcp = *mctx;
return 0;
}
static int crc32c_intel_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
u32 *crcp = shash_desc_ctx(desc);
*crcp = crc32c_intel_le_hw(*crcp, data, len);
return 0;
}
static int __crc32c_intel_finup(u32 *crcp, const u8 *data, unsigned int len,
u8 *out)
{
*(__le32 *)out = ~cpu_to_le32(crc32c_intel_le_hw(*crcp, data, len));
return 0;
}
static int crc32c_intel_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return __crc32c_intel_finup(shash_desc_ctx(desc), data, len, out);
}
static int crc32c_intel_final(struct shash_desc *desc, u8 *out)
{
u32 *crcp = shash_desc_ctx(desc);
*(__le32 *)out = ~cpu_to_le32p(crcp);
return 0;
}
static int crc32c_intel_digest(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return __crc32c_intel_finup(crypto_shash_ctx(desc->tfm), data, len,
out);
}
static int crc32c_intel_cra_init(struct crypto_tfm *tfm)
{
u32 *key = crypto_tfm_ctx(tfm);
*key = ~0;
return 0;
}
static struct shash_alg alg = {
.setkey = crc32c_intel_setkey,
.init = crc32c_intel_init,
.update = crc32c_intel_update,
.final = crc32c_intel_final,
.finup = crc32c_intel_finup,
.digest = crc32c_intel_digest,
.descsize = sizeof(u32),
.digestsize = CHKSUM_DIGEST_SIZE,
.base = {
.cra_name = "crc32c",
.cra_driver_name = "crc32c-intel",
.cra_priority = 200,
.cra_blocksize = CHKSUM_BLOCK_SIZE,
.cra_ctxsize = sizeof(u32),
.cra_module = THIS_MODULE,
.cra_init = crc32c_intel_cra_init,
}
};
static const struct x86_cpu_id crc32c_cpu_id[] = {
X86_FEATURE_MATCH(X86_FEATURE_XMM4_2),
{}
};
MODULE_DEVICE_TABLE(x86cpu, crc32c_cpu_id);
static int __init crc32c_intel_mod_init(void)
{
if (!x86_match_cpu(crc32c_cpu_id))
return -ENODEV;
return crypto_register_shash(&alg);
}
static void __exit crc32c_intel_mod_fini(void)
{
crypto_unregister_shash(&alg);
}
module_init(crc32c_intel_mod_init);
module_exit(crc32c_intel_mod_fini);
MODULE_AUTHOR("Austin Zhang <austin.zhang@intel.com>, Kent Liu <kent.liu@intel.com>");
MODULE_DESCRIPTION("CRC32c (Castagnoli) optimization using Intel Hardware.");
MODULE_LICENSE("GPL");
MODULE_ALIAS("crc32c");
MODULE_ALIAS("crc32c-intel");
| gpl-2.0 |
upndwn4par/graviton_n5_kernel | drivers/net/wireless/iwlwifi/iwl-devtrace.c | 4875 | 1765 | /******************************************************************************
*
* Copyright(c) 2009 - 2012 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
*****************************************************************************/
#include <linux/module.h>
/* sparse doesn't like tracepoint macros */
#ifndef __CHECKER__
#include "iwl-trans.h"
#define CREATE_TRACE_POINTS
#include "iwl-devtrace.h"
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_iowrite8);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_ioread32);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_iowrite32);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_rx);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_tx);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_ucode_event);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_ucode_error);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_ucode_cont_event);
EXPORT_TRACEPOINT_SYMBOL(iwlwifi_dev_ucode_wrap_event);
#endif
| gpl-2.0 |
Quaesar/android_kernel_hp_phobos | arch/arm/mach-ks8695/devices.c | 5131 | 5138 | /*
* arch/arm/mach-ks8695/devices.c
*
* Copyright (C) 2006 Andrew Victor
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it 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 <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <mach/irqs.h>
#include <mach/regs-wan.h>
#include <mach/regs-lan.h>
#include <mach/regs-hpna.h>
#include <mach/regs-switch.h>
#include <mach/regs-misc.h>
/* --------------------------------------------------------------------
* Ethernet
* -------------------------------------------------------------------- */
static u64 eth_dmamask = 0xffffffffUL;
static struct resource ks8695_wan_resources[] = {
[0] = {
.start = KS8695_WAN_PA,
.end = KS8695_WAN_PA + 0x00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "WAN RX",
.start = KS8695_IRQ_WAN_RX_STATUS,
.end = KS8695_IRQ_WAN_RX_STATUS,
.flags = IORESOURCE_IRQ,
},
[2] = {
.name = "WAN TX",
.start = KS8695_IRQ_WAN_TX_STATUS,
.end = KS8695_IRQ_WAN_TX_STATUS,
.flags = IORESOURCE_IRQ,
},
[3] = {
.name = "WAN Link",
.start = KS8695_IRQ_WAN_LINK,
.end = KS8695_IRQ_WAN_LINK,
.flags = IORESOURCE_IRQ,
},
[4] = {
.name = "WAN PHY",
.start = KS8695_MISC_PA,
.end = KS8695_MISC_PA + 0x1f,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device ks8695_wan_device = {
.name = "ks8695_ether",
.id = 0,
.dev = {
.dma_mask = ð_dmamask,
.coherent_dma_mask = 0xffffffff,
},
.resource = ks8695_wan_resources,
.num_resources = ARRAY_SIZE(ks8695_wan_resources),
};
static struct resource ks8695_lan_resources[] = {
[0] = {
.start = KS8695_LAN_PA,
.end = KS8695_LAN_PA + 0x00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "LAN RX",
.start = KS8695_IRQ_LAN_RX_STATUS,
.end = KS8695_IRQ_LAN_RX_STATUS,
.flags = IORESOURCE_IRQ,
},
[2] = {
.name = "LAN TX",
.start = KS8695_IRQ_LAN_TX_STATUS,
.end = KS8695_IRQ_LAN_TX_STATUS,
.flags = IORESOURCE_IRQ,
},
[3] = {
.name = "LAN SWITCH",
.start = KS8695_SWITCH_PA,
.end = KS8695_SWITCH_PA + 0x4f,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device ks8695_lan_device = {
.name = "ks8695_ether",
.id = 1,
.dev = {
.dma_mask = ð_dmamask,
.coherent_dma_mask = 0xffffffff,
},
.resource = ks8695_lan_resources,
.num_resources = ARRAY_SIZE(ks8695_lan_resources),
};
static struct resource ks8695_hpna_resources[] = {
[0] = {
.start = KS8695_HPNA_PA,
.end = KS8695_HPNA_PA + 0x00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "HPNA RX",
.start = KS8695_IRQ_HPNA_RX_STATUS,
.end = KS8695_IRQ_HPNA_RX_STATUS,
.flags = IORESOURCE_IRQ,
},
[2] = {
.name = "HPNA TX",
.start = KS8695_IRQ_HPNA_TX_STATUS,
.end = KS8695_IRQ_HPNA_TX_STATUS,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device ks8695_hpna_device = {
.name = "ks8695_ether",
.id = 2,
.dev = {
.dma_mask = ð_dmamask,
.coherent_dma_mask = 0xffffffff,
},
.resource = ks8695_hpna_resources,
.num_resources = ARRAY_SIZE(ks8695_hpna_resources),
};
void __init ks8695_add_device_wan(void)
{
platform_device_register(&ks8695_wan_device);
}
void __init ks8695_add_device_lan(void)
{
platform_device_register(&ks8695_lan_device);
}
void __init ks8696_add_device_hpna(void)
{
platform_device_register(&ks8695_hpna_device);
}
/* --------------------------------------------------------------------
* Watchdog
* -------------------------------------------------------------------- */
static struct platform_device ks8695_wdt_device = {
.name = "ks8695_wdt",
.id = -1,
.num_resources = 0,
};
static void __init ks8695_add_device_watchdog(void)
{
platform_device_register(&ks8695_wdt_device);
}
/* --------------------------------------------------------------------
* LEDs
* -------------------------------------------------------------------- */
#if defined(CONFIG_LEDS)
short ks8695_leds_cpu = -1;
short ks8695_leds_timer = -1;
void __init ks8695_init_leds(u8 cpu_led, u8 timer_led)
{
/* Enable GPIO to access the LEDs */
gpio_direction_output(cpu_led, 1);
gpio_direction_output(timer_led, 1);
ks8695_leds_cpu = cpu_led;
ks8695_leds_timer = timer_led;
}
#else
void __init ks8695_init_leds(u8 cpu_led, u8 timer_led) {}
#endif
/* -------------------------------------------------------------------- */
/*
* These devices are always present and don't need any board-specific
* setup.
*/
static int __init ks8695_add_standard_devices(void)
{
ks8695_add_device_watchdog();
return 0;
}
arch_initcall(ks8695_add_standard_devices);
| gpl-2.0 |
vivilyu/android_kernel_huawei_c8813 | drivers/tty/serial/clps711x.c | 6411 | 13324 | /*
* Driver for CLPS711x serial ports
*
* Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
*
* Copyright 1999 ARM Limited
* Copyright (C) 2000 Deep Blue Solutions Ltd.
*
* 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
*/
#if defined(CONFIG_SERIAL_CLPS711X_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/spinlock.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/hardware/clps7111.h>
#define UART_NR 2
#define SERIAL_CLPS711X_MAJOR 204
#define SERIAL_CLPS711X_MINOR 40
#define SERIAL_CLPS711X_NR UART_NR
/*
* We use the relevant SYSCON register as a base address for these ports.
*/
#define UBRLCR(port) ((port)->iobase + UBRLCR1 - SYSCON1)
#define UARTDR(port) ((port)->iobase + UARTDR1 - SYSCON1)
#define SYSFLG(port) ((port)->iobase + SYSFLG1 - SYSCON1)
#define SYSCON(port) ((port)->iobase + SYSCON1 - SYSCON1)
#define TX_IRQ(port) ((port)->irq)
#define RX_IRQ(port) ((port)->irq + 1)
#define UART_ANY_ERR (UARTDR_FRMERR | UARTDR_PARERR | UARTDR_OVERR)
#define tx_enabled(port) ((port)->unused[0])
static void clps711xuart_stop_tx(struct uart_port *port)
{
if (tx_enabled(port)) {
disable_irq(TX_IRQ(port));
tx_enabled(port) = 0;
}
}
static void clps711xuart_start_tx(struct uart_port *port)
{
if (!tx_enabled(port)) {
enable_irq(TX_IRQ(port));
tx_enabled(port) = 1;
}
}
static void clps711xuart_stop_rx(struct uart_port *port)
{
disable_irq(RX_IRQ(port));
}
static void clps711xuart_enable_ms(struct uart_port *port)
{
}
static irqreturn_t clps711xuart_int_rx(int irq, void *dev_id)
{
struct uart_port *port = dev_id;
struct tty_struct *tty = port->state->port.tty;
unsigned int status, ch, flg;
status = clps_readl(SYSFLG(port));
while (!(status & SYSFLG_URXFE)) {
ch = clps_readl(UARTDR(port));
port->icount.rx++;
flg = TTY_NORMAL;
/*
* Note that the error handling code is
* out of the main execution path
*/
if (unlikely(ch & UART_ANY_ERR)) {
if (ch & UARTDR_PARERR)
port->icount.parity++;
else if (ch & UARTDR_FRMERR)
port->icount.frame++;
if (ch & UARTDR_OVERR)
port->icount.overrun++;
ch &= port->read_status_mask;
if (ch & UARTDR_PARERR)
flg = TTY_PARITY;
else if (ch & UARTDR_FRMERR)
flg = TTY_FRAME;
#ifdef SUPPORT_SYSRQ
port->sysrq = 0;
#endif
}
if (uart_handle_sysrq_char(port, ch))
goto ignore_char;
/*
* CHECK: does overrun affect the current character?
* ASSUMPTION: it does not.
*/
uart_insert_char(port, ch, UARTDR_OVERR, ch, flg);
ignore_char:
status = clps_readl(SYSFLG(port));
}
tty_flip_buffer_push(tty);
return IRQ_HANDLED;
}
static irqreturn_t clps711xuart_int_tx(int irq, void *dev_id)
{
struct uart_port *port = dev_id;
struct circ_buf *xmit = &port->state->xmit;
int count;
if (port->x_char) {
clps_writel(port->x_char, UARTDR(port));
port->icount.tx++;
port->x_char = 0;
return IRQ_HANDLED;
}
if (uart_circ_empty(xmit) || uart_tx_stopped(port))
goto disable_tx_irq;
count = port->fifosize >> 1;
do {
clps_writel(xmit->buf[xmit->tail], UARTDR(port));
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
port->icount.tx++;
if (uart_circ_empty(xmit))
break;
} while (--count > 0);
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(port);
if (uart_circ_empty(xmit)) {
disable_tx_irq:
disable_irq_nosync(TX_IRQ(port));
tx_enabled(port) = 0;
}
return IRQ_HANDLED;
}
static unsigned int clps711xuart_tx_empty(struct uart_port *port)
{
unsigned int status = clps_readl(SYSFLG(port));
return status & SYSFLG_UBUSY ? 0 : TIOCSER_TEMT;
}
static unsigned int clps711xuart_get_mctrl(struct uart_port *port)
{
unsigned int port_addr;
unsigned int result = 0;
unsigned int status;
port_addr = SYSFLG(port);
if (port_addr == SYSFLG1) {
status = clps_readl(SYSFLG1);
if (status & SYSFLG1_DCD)
result |= TIOCM_CAR;
if (status & SYSFLG1_DSR)
result |= TIOCM_DSR;
if (status & SYSFLG1_CTS)
result |= TIOCM_CTS;
}
return result;
}
static void
clps711xuart_set_mctrl_null(struct uart_port *port, unsigned int mctrl)
{
}
static void clps711xuart_break_ctl(struct uart_port *port, int break_state)
{
unsigned long flags;
unsigned int ubrlcr;
spin_lock_irqsave(&port->lock, flags);
ubrlcr = clps_readl(UBRLCR(port));
if (break_state == -1)
ubrlcr |= UBRLCR_BREAK;
else
ubrlcr &= ~UBRLCR_BREAK;
clps_writel(ubrlcr, UBRLCR(port));
spin_unlock_irqrestore(&port->lock, flags);
}
static int clps711xuart_startup(struct uart_port *port)
{
unsigned int syscon;
int retval;
tx_enabled(port) = 1;
/*
* Allocate the IRQs
*/
retval = request_irq(TX_IRQ(port), clps711xuart_int_tx, 0,
"clps711xuart_tx", port);
if (retval)
return retval;
retval = request_irq(RX_IRQ(port), clps711xuart_int_rx, 0,
"clps711xuart_rx", port);
if (retval) {
free_irq(TX_IRQ(port), port);
return retval;
}
/*
* enable the port
*/
syscon = clps_readl(SYSCON(port));
syscon |= SYSCON_UARTEN;
clps_writel(syscon, SYSCON(port));
return 0;
}
static void clps711xuart_shutdown(struct uart_port *port)
{
unsigned int ubrlcr, syscon;
/*
* Free the interrupt
*/
free_irq(TX_IRQ(port), port); /* TX interrupt */
free_irq(RX_IRQ(port), port); /* RX interrupt */
/*
* disable the port
*/
syscon = clps_readl(SYSCON(port));
syscon &= ~SYSCON_UARTEN;
clps_writel(syscon, SYSCON(port));
/*
* disable break condition and fifos
*/
ubrlcr = clps_readl(UBRLCR(port));
ubrlcr &= ~(UBRLCR_FIFOEN | UBRLCR_BREAK);
clps_writel(ubrlcr, UBRLCR(port));
}
static void
clps711xuart_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
unsigned int ubrlcr, baud, quot;
unsigned long flags;
/*
* We don't implement CREAD.
*/
termios->c_cflag |= CREAD;
/*
* Ask the core to calculate the divisor for us.
*/
baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk/16);
quot = uart_get_divisor(port, baud);
switch (termios->c_cflag & CSIZE) {
case CS5:
ubrlcr = UBRLCR_WRDLEN5;
break;
case CS6:
ubrlcr = UBRLCR_WRDLEN6;
break;
case CS7:
ubrlcr = UBRLCR_WRDLEN7;
break;
default: // CS8
ubrlcr = UBRLCR_WRDLEN8;
break;
}
if (termios->c_cflag & CSTOPB)
ubrlcr |= UBRLCR_XSTOP;
if (termios->c_cflag & PARENB) {
ubrlcr |= UBRLCR_PRTEN;
if (!(termios->c_cflag & PARODD))
ubrlcr |= UBRLCR_EVENPRT;
}
if (port->fifosize > 1)
ubrlcr |= UBRLCR_FIFOEN;
spin_lock_irqsave(&port->lock, flags);
/*
* Update the per-port timeout.
*/
uart_update_timeout(port, termios->c_cflag, baud);
port->read_status_mask = UARTDR_OVERR;
if (termios->c_iflag & INPCK)
port->read_status_mask |= UARTDR_PARERR | UARTDR_FRMERR;
/*
* Characters to ignore
*/
port->ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= UARTDR_FRMERR | UARTDR_PARERR;
if (termios->c_iflag & IGNBRK) {
/*
* If we're ignoring parity and break indicators,
* ignore overruns to (for real raw support).
*/
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= UARTDR_OVERR;
}
quot -= 1;
clps_writel(ubrlcr | quot, UBRLCR(port));
spin_unlock_irqrestore(&port->lock, flags);
}
static const char *clps711xuart_type(struct uart_port *port)
{
return port->type == PORT_CLPS711X ? "CLPS711x" : NULL;
}
/*
* Configure/autoconfigure the port.
*/
static void clps711xuart_config_port(struct uart_port *port, int flags)
{
if (flags & UART_CONFIG_TYPE)
port->type = PORT_CLPS711X;
}
static void clps711xuart_release_port(struct uart_port *port)
{
}
static int clps711xuart_request_port(struct uart_port *port)
{
return 0;
}
static struct uart_ops clps711x_pops = {
.tx_empty = clps711xuart_tx_empty,
.set_mctrl = clps711xuart_set_mctrl_null,
.get_mctrl = clps711xuart_get_mctrl,
.stop_tx = clps711xuart_stop_tx,
.start_tx = clps711xuart_start_tx,
.stop_rx = clps711xuart_stop_rx,
.enable_ms = clps711xuart_enable_ms,
.break_ctl = clps711xuart_break_ctl,
.startup = clps711xuart_startup,
.shutdown = clps711xuart_shutdown,
.set_termios = clps711xuart_set_termios,
.type = clps711xuart_type,
.config_port = clps711xuart_config_port,
.release_port = clps711xuart_release_port,
.request_port = clps711xuart_request_port,
};
static struct uart_port clps711x_ports[UART_NR] = {
{
.iobase = SYSCON1,
.irq = IRQ_UTXINT1, /* IRQ_URXINT1, IRQ_UMSINT */
.uartclk = 3686400,
.fifosize = 16,
.ops = &clps711x_pops,
.line = 0,
.flags = UPF_BOOT_AUTOCONF,
},
{
.iobase = SYSCON2,
.irq = IRQ_UTXINT2, /* IRQ_URXINT2 */
.uartclk = 3686400,
.fifosize = 16,
.ops = &clps711x_pops,
.line = 1,
.flags = UPF_BOOT_AUTOCONF,
}
};
#ifdef CONFIG_SERIAL_CLPS711X_CONSOLE
static void clps711xuart_console_putchar(struct uart_port *port, int ch)
{
while (clps_readl(SYSFLG(port)) & SYSFLG_UTXFF)
barrier();
clps_writel(ch, UARTDR(port));
}
/*
* Print a string to the serial port trying not to disturb
* any possible real use of the port...
*
* The console_lock must be held when we get here.
*
* Note that this is called with interrupts already disabled
*/
static void
clps711xuart_console_write(struct console *co, const char *s,
unsigned int count)
{
struct uart_port *port = clps711x_ports + co->index;
unsigned int status, syscon;
/*
* Ensure that the port is enabled.
*/
syscon = clps_readl(SYSCON(port));
clps_writel(syscon | SYSCON_UARTEN, SYSCON(port));
uart_console_write(port, s, count, clps711xuart_console_putchar);
/*
* Finally, wait for transmitter to become empty
* and restore the uart state.
*/
do {
status = clps_readl(SYSFLG(port));
} while (status & SYSFLG_UBUSY);
clps_writel(syscon, SYSCON(port));
}
static void __init
clps711xuart_console_get_options(struct uart_port *port, int *baud,
int *parity, int *bits)
{
if (clps_readl(SYSCON(port)) & SYSCON_UARTEN) {
unsigned int ubrlcr, quot;
ubrlcr = clps_readl(UBRLCR(port));
*parity = 'n';
if (ubrlcr & UBRLCR_PRTEN) {
if (ubrlcr & UBRLCR_EVENPRT)
*parity = 'e';
else
*parity = 'o';
}
if ((ubrlcr & UBRLCR_WRDLEN_MASK) == UBRLCR_WRDLEN7)
*bits = 7;
else
*bits = 8;
quot = ubrlcr & UBRLCR_BAUD_MASK;
*baud = port->uartclk / (16 * (quot + 1));
}
}
static int __init clps711xuart_console_setup(struct console *co, char *options)
{
struct uart_port *port;
int baud = 38400;
int bits = 8;
int parity = 'n';
int flow = 'n';
/*
* Check whether an invalid uart number has been specified, and
* if so, search for the first available port that does have
* console support.
*/
port = uart_get_console(clps711x_ports, UART_NR, co);
if (options)
uart_parse_options(options, &baud, &parity, &bits, &flow);
else
clps711xuart_console_get_options(port, &baud, &parity, &bits);
return uart_set_options(port, co, baud, parity, bits, flow);
}
static struct uart_driver clps711x_reg;
static struct console clps711x_console = {
.name = "ttyCL",
.write = clps711xuart_console_write,
.device = uart_console_device,
.setup = clps711xuart_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &clps711x_reg,
};
static int __init clps711xuart_console_init(void)
{
register_console(&clps711x_console);
return 0;
}
console_initcall(clps711xuart_console_init);
#define CLPS711X_CONSOLE &clps711x_console
#else
#define CLPS711X_CONSOLE NULL
#endif
static struct uart_driver clps711x_reg = {
.driver_name = "ttyCL",
.dev_name = "ttyCL",
.major = SERIAL_CLPS711X_MAJOR,
.minor = SERIAL_CLPS711X_MINOR,
.nr = UART_NR,
.cons = CLPS711X_CONSOLE,
};
static int __init clps711xuart_init(void)
{
int ret, i;
printk(KERN_INFO "Serial: CLPS711x driver\n");
ret = uart_register_driver(&clps711x_reg);
if (ret)
return ret;
for (i = 0; i < UART_NR; i++)
uart_add_one_port(&clps711x_reg, &clps711x_ports[i]);
return 0;
}
static void __exit clps711xuart_exit(void)
{
int i;
for (i = 0; i < UART_NR; i++)
uart_remove_one_port(&clps711x_reg, &clps711x_ports[i]);
uart_unregister_driver(&clps711x_reg);
}
module_init(clps711xuart_init);
module_exit(clps711xuart_exit);
MODULE_AUTHOR("Deep Blue Solutions Ltd");
MODULE_DESCRIPTION("CLPS-711x generic serial driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV(SERIAL_CLPS711X_MAJOR, SERIAL_CLPS711X_MINOR);
| gpl-2.0 |
JianguoWEI/linux-efq-final | drivers/media/video/saa7164/saa7164-i2c.c | 8203 | 3666 | /*
* Driver for the NXP SAA7164 PCIe bridge
*
* Copyright (c) 2010 Steven Toth <stoth@kernellabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/io.h>
#include "saa7164.h"
static int i2c_xfer(struct i2c_adapter *i2c_adap, struct i2c_msg *msgs, int num)
{
struct saa7164_i2c *bus = i2c_adap->algo_data;
struct saa7164_dev *dev = bus->dev;
int i, retval = 0;
dprintk(DBGLVL_I2C, "%s(num = %d)\n", __func__, num);
for (i = 0 ; i < num; i++) {
dprintk(DBGLVL_I2C, "%s(num = %d) addr = 0x%02x len = 0x%x\n",
__func__, num, msgs[i].addr, msgs[i].len);
if (msgs[i].flags & I2C_M_RD) {
/* Unsupported - Yet*/
printk(KERN_ERR "%s() Unsupported - Yet\n", __func__);
continue;
} else if (i + 1 < num && (msgs[i + 1].flags & I2C_M_RD) &&
msgs[i].addr == msgs[i + 1].addr) {
/* write then read from same address */
retval = saa7164_api_i2c_read(bus, msgs[i].addr,
msgs[i].len, msgs[i].buf,
msgs[i+1].len, msgs[i+1].buf
);
i++;
if (retval < 0)
goto err;
} else {
/* write */
retval = saa7164_api_i2c_write(bus, msgs[i].addr,
msgs[i].len, msgs[i].buf);
}
if (retval < 0)
goto err;
}
return num;
err:
return retval;
}
void saa7164_call_i2c_clients(struct saa7164_i2c *bus, unsigned int cmd,
void *arg)
{
if (bus->i2c_rc != 0)
return;
i2c_clients_command(&bus->i2c_adap, cmd, arg);
}
static u32 saa7164_functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm saa7164_i2c_algo_template = {
.master_xfer = i2c_xfer,
.functionality = saa7164_functionality,
};
/* ----------------------------------------------------------------------- */
static struct i2c_adapter saa7164_i2c_adap_template = {
.name = "saa7164",
.owner = THIS_MODULE,
.algo = &saa7164_i2c_algo_template,
};
static struct i2c_client saa7164_i2c_client_template = {
.name = "saa7164 internal",
};
int saa7164_i2c_register(struct saa7164_i2c *bus)
{
struct saa7164_dev *dev = bus->dev;
dprintk(DBGLVL_I2C, "%s(bus = %d)\n", __func__, bus->nr);
memcpy(&bus->i2c_adap, &saa7164_i2c_adap_template,
sizeof(bus->i2c_adap));
memcpy(&bus->i2c_algo, &saa7164_i2c_algo_template,
sizeof(bus->i2c_algo));
memcpy(&bus->i2c_client, &saa7164_i2c_client_template,
sizeof(bus->i2c_client));
bus->i2c_adap.dev.parent = &dev->pci->dev;
strlcpy(bus->i2c_adap.name, bus->dev->name,
sizeof(bus->i2c_adap.name));
bus->i2c_algo.data = bus;
bus->i2c_adap.algo_data = bus;
i2c_set_adapdata(&bus->i2c_adap, bus);
i2c_add_adapter(&bus->i2c_adap);
bus->i2c_client.adapter = &bus->i2c_adap;
if (0 != bus->i2c_rc)
printk(KERN_ERR "%s: i2c bus %d register FAILED\n",
dev->name, bus->nr);
return bus->i2c_rc;
}
int saa7164_i2c_unregister(struct saa7164_i2c *bus)
{
i2c_del_adapter(&bus->i2c_adap);
return 0;
}
| gpl-2.0 |
Dronevery/JetsonTK1-kernel | drivers/ieee1394/pcilynx.c | 12 | 66835 | /*
* pcilynx.c - Texas Instruments PCILynx driver
* Copyright (C) 1999,2000 Andreas Bombe <andreas.bombe@munich.netsurf.de>,
* Stephan Linz <linz@mazet.de>
* Manfred Weihs <weihs@ict.tuwien.ac.at>
*
* 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.
*/
/*
* Contributions:
*
* Manfred Weihs <weihs@ict.tuwien.ac.at>
* reading bus info block (containing GUID) from serial
* eeprom via i2c and storing it in config ROM
* Reworked code for initiating bus resets
* (long, short, with or without hold-off)
* Enhancements in async and iso send code
*/
#include <linux/config.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/wait.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/fs.h>
#include <linux/poll.h>
#include <linux/kdev_t.h>
#include <asm/byteorder.h>
#include <asm/atomic.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include "csr1212.h"
#include "ieee1394.h"
#include "ieee1394_types.h"
#include "hosts.h"
#include "ieee1394_core.h"
#include "highlevel.h"
#include "pcilynx.h"
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
/* print general (card independent) information */
#define PRINT_G(level, fmt, args...) printk(level "pcilynx: " fmt "\n" , ## args)
/* print card specific information */
#define PRINT(level, card, fmt, args...) printk(level "pcilynx%d: " fmt "\n" , card , ## args)
#ifdef CONFIG_IEEE1394_VERBOSEDEBUG
#define PRINT_GD(level, fmt, args...) printk(level "pcilynx: " fmt "\n" , ## args)
#define PRINTD(level, card, fmt, args...) printk(level "pcilynx%d: " fmt "\n" , card , ## args)
#else
#define PRINT_GD(level, fmt, args...) do {} while (0)
#define PRINTD(level, card, fmt, args...) do {} while (0)
#endif
/* Module Parameters */
static int skip_eeprom = 0;
module_param(skip_eeprom, int, 0444);
MODULE_PARM_DESC(skip_eeprom, "Use generic bus info block instead of serial eeprom (default = 0).");
static struct hpsb_host_driver lynx_driver;
static unsigned int card_id;
/*
* I2C stuff
*/
/* the i2c stuff was inspired by i2c-philips-par.c */
static void bit_setscl(void *data, int state)
{
if (state) {
((struct ti_lynx *) data)->i2c_driven_state |= 0x00000040;
} else {
((struct ti_lynx *) data)->i2c_driven_state &= ~0x00000040;
}
reg_write((struct ti_lynx *) data, SERIAL_EEPROM_CONTROL, ((struct ti_lynx *) data)->i2c_driven_state);
}
static void bit_setsda(void *data, int state)
{
if (state) {
((struct ti_lynx *) data)->i2c_driven_state |= 0x00000010;
} else {
((struct ti_lynx *) data)->i2c_driven_state &= ~0x00000010;
}
reg_write((struct ti_lynx *) data, SERIAL_EEPROM_CONTROL, ((struct ti_lynx *) data)->i2c_driven_state);
}
static int bit_getscl(void *data)
{
return reg_read((struct ti_lynx *) data, SERIAL_EEPROM_CONTROL) & 0x00000040;
}
static int bit_getsda(void *data)
{
return reg_read((struct ti_lynx *) data, SERIAL_EEPROM_CONTROL) & 0x00000010;
}
static int bit_reg(struct i2c_client *client)
{
return 0;
}
static int bit_unreg(struct i2c_client *client)
{
return 0;
}
static struct i2c_algo_bit_data bit_data = {
.setsda = bit_setsda,
.setscl = bit_setscl,
.getsda = bit_getsda,
.getscl = bit_getscl,
.udelay = 5,
.mdelay = 5,
.timeout = 100,
};
static struct i2c_adapter bit_ops = {
.id = 0xAA, //FIXME: probably we should get an id in i2c-id.h
.client_register = bit_reg,
.client_unregister = bit_unreg,
.name = "PCILynx I2C",
};
/*
* PCL handling functions.
*/
static pcl_t alloc_pcl(struct ti_lynx *lynx)
{
u8 m;
int i, j;
spin_lock(&lynx->lock);
/* FIXME - use ffz() to make this readable */
for (i = 0; i < (LOCALRAM_SIZE / 1024); i++) {
m = lynx->pcl_bmap[i];
for (j = 0; j < 8; j++) {
if (m & 1<<j) {
continue;
}
m |= 1<<j;
lynx->pcl_bmap[i] = m;
spin_unlock(&lynx->lock);
return 8 * i + j;
}
}
spin_unlock(&lynx->lock);
return -1;
}
#if 0
static void free_pcl(struct ti_lynx *lynx, pcl_t pclid)
{
int off, bit;
off = pclid / 8;
bit = pclid % 8;
if (pclid < 0) {
return;
}
spin_lock(&lynx->lock);
if (lynx->pcl_bmap[off] & 1<<bit) {
lynx->pcl_bmap[off] &= ~(1<<bit);
} else {
PRINT(KERN_ERR, lynx->id,
"attempted to free unallocated PCL %d", pclid);
}
spin_unlock(&lynx->lock);
}
/* functions useful for debugging */
static void pretty_print_pcl(const struct ti_pcl *pcl)
{
int i;
printk("PCL next %08x, userdata %08x, status %08x, remtrans %08x, nextbuf %08x\n",
pcl->next, pcl->user_data, pcl->pcl_status,
pcl->remaining_transfer_count, pcl->next_data_buffer);
printk("PCL");
for (i=0; i<13; i++) {
printk(" c%x:%08x d%x:%08x",
i, pcl->buffer[i].control, i, pcl->buffer[i].pointer);
if (!(i & 0x3) && (i != 12)) printk("\nPCL");
}
printk("\n");
}
static void print_pcl(const struct ti_lynx *lynx, pcl_t pclid)
{
struct ti_pcl pcl;
get_pcl(lynx, pclid, &pcl);
pretty_print_pcl(&pcl);
}
#endif
/***********************************
* IEEE-1394 functionality section *
***********************************/
static int get_phy_reg(struct ti_lynx *lynx, int addr)
{
int retval;
int i = 0;
unsigned long flags;
if (addr > 15) {
PRINT(KERN_ERR, lynx->id,
"%s: PHY register address %d out of range",
__FUNCTION__, addr);
return -1;
}
spin_lock_irqsave(&lynx->phy_reg_lock, flags);
reg_write(lynx, LINK_PHY, LINK_PHY_READ | LINK_PHY_ADDR(addr));
do {
retval = reg_read(lynx, LINK_PHY);
if (i > 10000) {
PRINT(KERN_ERR, lynx->id, "%s: runaway loop, aborting",
__FUNCTION__);
retval = -1;
break;
}
i++;
} while ((retval & 0xf00) != LINK_PHY_RADDR(addr));
reg_write(lynx, LINK_INT_STATUS, LINK_INT_PHY_REG_RCVD);
spin_unlock_irqrestore(&lynx->phy_reg_lock, flags);
if (retval != -1) {
return retval & 0xff;
} else {
return -1;
}
}
static int set_phy_reg(struct ti_lynx *lynx, int addr, int val)
{
unsigned long flags;
if (addr > 15) {
PRINT(KERN_ERR, lynx->id,
"%s: PHY register address %d out of range", __FUNCTION__, addr);
return -1;
}
if (val > 0xff) {
PRINT(KERN_ERR, lynx->id,
"%s: PHY register value %d out of range", __FUNCTION__, val);
return -1;
}
spin_lock_irqsave(&lynx->phy_reg_lock, flags);
reg_write(lynx, LINK_PHY, LINK_PHY_WRITE | LINK_PHY_ADDR(addr)
| LINK_PHY_WDATA(val));
spin_unlock_irqrestore(&lynx->phy_reg_lock, flags);
return 0;
}
static int sel_phy_reg_page(struct ti_lynx *lynx, int page)
{
int reg;
if (page > 7) {
PRINT(KERN_ERR, lynx->id,
"%s: PHY page %d out of range", __FUNCTION__, page);
return -1;
}
reg = get_phy_reg(lynx, 7);
if (reg != -1) {
reg &= 0x1f;
reg |= (page << 5);
set_phy_reg(lynx, 7, reg);
return 0;
} else {
return -1;
}
}
#if 0 /* not needed at this time */
static int sel_phy_reg_port(struct ti_lynx *lynx, int port)
{
int reg;
if (port > 15) {
PRINT(KERN_ERR, lynx->id,
"%s: PHY port %d out of range", __FUNCTION__, port);
return -1;
}
reg = get_phy_reg(lynx, 7);
if (reg != -1) {
reg &= 0xf0;
reg |= port;
set_phy_reg(lynx, 7, reg);
return 0;
} else {
return -1;
}
}
#endif
static u32 get_phy_vendorid(struct ti_lynx *lynx)
{
u32 pvid = 0;
sel_phy_reg_page(lynx, 1);
pvid |= (get_phy_reg(lynx, 10) << 16);
pvid |= (get_phy_reg(lynx, 11) << 8);
pvid |= get_phy_reg(lynx, 12);
PRINT(KERN_INFO, lynx->id, "PHY vendor id 0x%06x", pvid);
return pvid;
}
static u32 get_phy_productid(struct ti_lynx *lynx)
{
u32 id = 0;
sel_phy_reg_page(lynx, 1);
id |= (get_phy_reg(lynx, 13) << 16);
id |= (get_phy_reg(lynx, 14) << 8);
id |= get_phy_reg(lynx, 15);
PRINT(KERN_INFO, lynx->id, "PHY product id 0x%06x", id);
return id;
}
static quadlet_t generate_own_selfid(struct ti_lynx *lynx,
struct hpsb_host *host)
{
quadlet_t lsid;
char phyreg[7];
int i;
phyreg[0] = lynx->phy_reg0;
for (i = 1; i < 7; i++) {
phyreg[i] = get_phy_reg(lynx, i);
}
/* FIXME? We assume a TSB21LV03A phy here. This code doesn't support
more than 3 ports on the PHY anyway. */
lsid = 0x80400000 | ((phyreg[0] & 0xfc) << 22);
lsid |= (phyreg[1] & 0x3f) << 16; /* gap count */
lsid |= (phyreg[2] & 0xc0) << 8; /* max speed */
if (!hpsb_disable_irm)
lsid |= (phyreg[6] & 0x01) << 11; /* contender (phy dependent) */
/* lsid |= 1 << 11; *//* set contender (hack) */
lsid |= (phyreg[6] & 0x10) >> 3; /* initiated reset */
for (i = 0; i < (phyreg[2] & 0xf); i++) { /* ports */
if (phyreg[3 + i] & 0x4) {
lsid |= (((phyreg[3 + i] & 0x8) | 0x10) >> 3)
<< (6 - i*2);
} else {
lsid |= 1 << (6 - i*2);
}
}
cpu_to_be32s(&lsid);
PRINT(KERN_DEBUG, lynx->id, "generated own selfid 0x%x", lsid);
return lsid;
}
static void handle_selfid(struct ti_lynx *lynx, struct hpsb_host *host)
{
quadlet_t *q = lynx->rcv_page;
int phyid, isroot, size;
quadlet_t lsid = 0;
int i;
if (lynx->phy_reg0 == -1 || lynx->selfid_size == -1) return;
size = lynx->selfid_size;
phyid = lynx->phy_reg0;
i = (size > 16 ? 16 : size) / 4 - 1;
while (i >= 0) {
cpu_to_be32s(&q[i]);
i--;
}
if (!lynx->phyic.reg_1394a) {
lsid = generate_own_selfid(lynx, host);
}
isroot = (phyid & 2) != 0;
phyid >>= 2;
PRINT(KERN_INFO, lynx->id, "SelfID process finished (phyid %d, %s)",
phyid, (isroot ? "root" : "not root"));
reg_write(lynx, LINK_ID, (0xffc0 | phyid) << 16);
if (!lynx->phyic.reg_1394a && !size) {
hpsb_selfid_received(host, lsid);
}
while (size > 0) {
struct selfid *sid = (struct selfid *)q;
if (!lynx->phyic.reg_1394a && !sid->extended
&& (sid->phy_id == (phyid + 1))) {
hpsb_selfid_received(host, lsid);
}
if (q[0] == ~q[1]) {
PRINT(KERN_DEBUG, lynx->id, "SelfID packet 0x%x rcvd",
q[0]);
hpsb_selfid_received(host, q[0]);
} else {
PRINT(KERN_INFO, lynx->id,
"inconsistent selfid 0x%x/0x%x", q[0], q[1]);
}
q += 2;
size -= 8;
}
if (!lynx->phyic.reg_1394a && isroot && phyid != 0) {
hpsb_selfid_received(host, lsid);
}
hpsb_selfid_complete(host, phyid, isroot);
if (host->in_bus_reset) return; /* in bus reset again */
if (isroot) reg_set_bits(lynx, LINK_CONTROL, LINK_CONTROL_CYCMASTER); //FIXME: I do not think, we need this here
reg_set_bits(lynx, LINK_CONTROL,
LINK_CONTROL_RCV_CMP_VALID | LINK_CONTROL_TX_ASYNC_EN
| LINK_CONTROL_RX_ASYNC_EN | LINK_CONTROL_CYCTIMEREN);
}
/* This must be called with the respective queue_lock held. */
static void send_next(struct ti_lynx *lynx, int what)
{
struct ti_pcl pcl;
struct lynx_send_data *d;
struct hpsb_packet *packet;
d = (what == hpsb_iso ? &lynx->iso_send : &lynx->async);
if (!list_empty(&d->pcl_queue)) {
PRINT(KERN_ERR, lynx->id, "trying to queue a new packet in nonempty fifo");
BUG();
}
packet = driver_packet(d->queue.next);
list_move_tail(&packet->driver_list, &d->pcl_queue);
d->header_dma = pci_map_single(lynx->dev, packet->header,
packet->header_size, PCI_DMA_TODEVICE);
if (packet->data_size) {
d->data_dma = pci_map_single(lynx->dev, packet->data,
packet->data_size,
PCI_DMA_TODEVICE);
} else {
d->data_dma = 0;
}
pcl.next = PCL_NEXT_INVALID;
pcl.async_error_next = PCL_NEXT_INVALID;
pcl.pcl_status = 0;
pcl.buffer[0].control = packet->speed_code << 14 | packet->header_size;
#ifndef __BIG_ENDIAN
pcl.buffer[0].control |= PCL_BIGENDIAN;
#endif
pcl.buffer[0].pointer = d->header_dma;
pcl.buffer[1].control = PCL_LAST_BUFF | packet->data_size;
pcl.buffer[1].pointer = d->data_dma;
switch (packet->type) {
case hpsb_async:
pcl.buffer[0].control |= PCL_CMD_XMT;
break;
case hpsb_iso:
pcl.buffer[0].control |= PCL_CMD_XMT | PCL_ISOMODE;
break;
case hpsb_raw:
pcl.buffer[0].control |= PCL_CMD_UNFXMT;
break;
}
put_pcl(lynx, d->pcl, &pcl);
run_pcl(lynx, d->pcl_start, d->channel);
}
/* called from subsystem core */
static int lynx_transmit(struct hpsb_host *host, struct hpsb_packet *packet)
{
struct ti_lynx *lynx = host->hostdata;
struct lynx_send_data *d;
unsigned long flags;
if (packet->data_size >= 4096) {
PRINT(KERN_ERR, lynx->id, "transmit packet data too big (%Zd)",
packet->data_size);
return -EOVERFLOW;
}
switch (packet->type) {
case hpsb_async:
case hpsb_raw:
d = &lynx->async;
break;
case hpsb_iso:
d = &lynx->iso_send;
break;
default:
PRINT(KERN_ERR, lynx->id, "invalid packet type %d",
packet->type);
return -EINVAL;
}
if (packet->tcode == TCODE_WRITEQ
|| packet->tcode == TCODE_READQ_RESPONSE) {
cpu_to_be32s(&packet->header[3]);
}
spin_lock_irqsave(&d->queue_lock, flags);
list_add_tail(&packet->driver_list, &d->queue);
if (list_empty(&d->pcl_queue))
send_next(lynx, packet->type);
spin_unlock_irqrestore(&d->queue_lock, flags);
return 0;
}
/* called from subsystem core */
static int lynx_devctl(struct hpsb_host *host, enum devctl_cmd cmd, int arg)
{
struct ti_lynx *lynx = host->hostdata;
int retval = 0;
struct hpsb_packet *packet;
LIST_HEAD(packet_list);
unsigned long flags;
int phy_reg;
switch (cmd) {
case RESET_BUS:
if (reg_read(lynx, LINK_INT_STATUS) & LINK_INT_PHY_BUSRESET) {
retval = 0;
break;
}
switch (arg) {
case SHORT_RESET:
if (lynx->phyic.reg_1394a) {
phy_reg = get_phy_reg(lynx, 5);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
phy_reg |= 0x40;
PRINT(KERN_INFO, lynx->id, "resetting bus (short bus reset) on request");
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
set_phy_reg(lynx, 5, phy_reg); /* set ISBR */
break;
} else {
PRINT(KERN_INFO, lynx->id, "cannot do short bus reset, because of old phy");
/* fall through to long bus reset */
}
case LONG_RESET:
phy_reg = get_phy_reg(lynx, 1);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
phy_reg |= 0x40;
PRINT(KERN_INFO, lynx->id, "resetting bus (long bus reset) on request");
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
set_phy_reg(lynx, 1, phy_reg); /* clear RHB, set IBR */
break;
case SHORT_RESET_NO_FORCE_ROOT:
if (lynx->phyic.reg_1394a) {
phy_reg = get_phy_reg(lynx, 1);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
if (phy_reg & 0x80) {
phy_reg &= ~0x80;
set_phy_reg(lynx, 1, phy_reg); /* clear RHB */
}
phy_reg = get_phy_reg(lynx, 5);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
phy_reg |= 0x40;
PRINT(KERN_INFO, lynx->id, "resetting bus (short bus reset, no force_root) on request");
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
set_phy_reg(lynx, 5, phy_reg); /* set ISBR */
break;
} else {
PRINT(KERN_INFO, lynx->id, "cannot do short bus reset, because of old phy");
/* fall through to long bus reset */
}
case LONG_RESET_NO_FORCE_ROOT:
phy_reg = get_phy_reg(lynx, 1);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
phy_reg &= ~0x80;
phy_reg |= 0x40;
PRINT(KERN_INFO, lynx->id, "resetting bus (long bus reset, no force_root) on request");
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
set_phy_reg(lynx, 1, phy_reg); /* clear RHB, set IBR */
break;
case SHORT_RESET_FORCE_ROOT:
if (lynx->phyic.reg_1394a) {
phy_reg = get_phy_reg(lynx, 1);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
if (!(phy_reg & 0x80)) {
phy_reg |= 0x80;
set_phy_reg(lynx, 1, phy_reg); /* set RHB */
}
phy_reg = get_phy_reg(lynx, 5);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
phy_reg |= 0x40;
PRINT(KERN_INFO, lynx->id, "resetting bus (short bus reset, force_root set) on request");
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
set_phy_reg(lynx, 5, phy_reg); /* set ISBR */
break;
} else {
PRINT(KERN_INFO, lynx->id, "cannot do short bus reset, because of old phy");
/* fall through to long bus reset */
}
case LONG_RESET_FORCE_ROOT:
phy_reg = get_phy_reg(lynx, 1);
if (phy_reg == -1) {
PRINT(KERN_ERR, lynx->id, "cannot reset bus, because read phy reg failed");
retval = -1;
break;
}
phy_reg |= 0xc0;
PRINT(KERN_INFO, lynx->id, "resetting bus (long bus reset, force_root set) on request");
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
set_phy_reg(lynx, 1, phy_reg); /* set IBR and RHB */
break;
default:
PRINT(KERN_ERR, lynx->id, "unknown argument for reset_bus command %d", arg);
retval = -1;
}
break;
case GET_CYCLE_COUNTER:
retval = reg_read(lynx, CYCLE_TIMER);
break;
case SET_CYCLE_COUNTER:
reg_write(lynx, CYCLE_TIMER, arg);
break;
case SET_BUS_ID:
reg_write(lynx, LINK_ID,
(arg << 22) | (reg_read(lynx, LINK_ID) & 0x003f0000));
break;
case ACT_CYCLE_MASTER:
if (arg) {
reg_set_bits(lynx, LINK_CONTROL,
LINK_CONTROL_CYCMASTER);
} else {
reg_clear_bits(lynx, LINK_CONTROL,
LINK_CONTROL_CYCMASTER);
}
break;
case CANCEL_REQUESTS:
spin_lock_irqsave(&lynx->async.queue_lock, flags);
reg_write(lynx, DMA_CHAN_CTRL(CHANNEL_ASYNC_SEND), 0);
list_splice(&lynx->async.queue, &packet_list);
INIT_LIST_HEAD(&lynx->async.queue);
if (list_empty(&lynx->async.pcl_queue)) {
spin_unlock_irqrestore(&lynx->async.queue_lock, flags);
PRINTD(KERN_DEBUG, lynx->id, "no async packet in PCL to cancel");
} else {
struct ti_pcl pcl;
u32 ack;
struct hpsb_packet *packet;
PRINT(KERN_INFO, lynx->id, "cancelling async packet, that was already in PCL");
get_pcl(lynx, lynx->async.pcl, &pcl);
packet = driver_packet(lynx->async.pcl_queue.next);
list_del_init(&packet->driver_list);
pci_unmap_single(lynx->dev, lynx->async.header_dma,
packet->header_size, PCI_DMA_TODEVICE);
if (packet->data_size) {
pci_unmap_single(lynx->dev, lynx->async.data_dma,
packet->data_size, PCI_DMA_TODEVICE);
}
spin_unlock_irqrestore(&lynx->async.queue_lock, flags);
if (pcl.pcl_status & DMA_CHAN_STAT_PKTCMPL) {
if (pcl.pcl_status & DMA_CHAN_STAT_SPECIALACK) {
ack = (pcl.pcl_status >> 15) & 0xf;
PRINTD(KERN_INFO, lynx->id, "special ack %d", ack);
ack = (ack == 1 ? ACKX_TIMEOUT : ACKX_SEND_ERROR);
} else {
ack = (pcl.pcl_status >> 15) & 0xf;
}
} else {
PRINT(KERN_INFO, lynx->id, "async packet was not completed");
ack = ACKX_ABORTED;
}
hpsb_packet_sent(host, packet, ack);
}
while (!list_empty(&packet_list)) {
packet = driver_packet(packet_list.next);
list_del_init(&packet->driver_list);
hpsb_packet_sent(host, packet, ACKX_ABORTED);
}
break;
case ISO_LISTEN_CHANNEL:
spin_lock_irqsave(&lynx->iso_rcv.lock, flags);
if (lynx->iso_rcv.chan_count++ == 0) {
reg_write(lynx, DMA_WORD1_CMP_ENABLE(CHANNEL_ISO_RCV),
DMA_WORD1_CMP_ENABLE_MASTER);
}
spin_unlock_irqrestore(&lynx->iso_rcv.lock, flags);
break;
case ISO_UNLISTEN_CHANNEL:
spin_lock_irqsave(&lynx->iso_rcv.lock, flags);
if (--lynx->iso_rcv.chan_count == 0) {
reg_write(lynx, DMA_WORD1_CMP_ENABLE(CHANNEL_ISO_RCV),
0);
}
spin_unlock_irqrestore(&lynx->iso_rcv.lock, flags);
break;
default:
PRINT(KERN_ERR, lynx->id, "unknown devctl command %d", cmd);
retval = -1;
}
return retval;
}
/***************************************
* IEEE-1394 functionality section END *
***************************************/
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
/* VFS functions for local bus / aux device access. Access to those
* is implemented as a character device instead of block devices
* because buffers are not wanted for this. Therefore llseek (from
* VFS) can be used for these char devices with obvious effects.
*/
static int mem_open(struct inode*, struct file*);
static int mem_release(struct inode*, struct file*);
static unsigned int aux_poll(struct file*, struct poll_table_struct*);
static loff_t mem_llseek(struct file*, loff_t, int);
static ssize_t mem_read (struct file*, char*, size_t, loff_t*);
static ssize_t mem_write(struct file*, const char*, size_t, loff_t*);
static struct file_operations aux_ops = {
.owner = THIS_MODULE,
.read = mem_read,
.write = mem_write,
.poll = aux_poll,
.llseek = mem_llseek,
.open = mem_open,
.release = mem_release,
};
static void aux_setup_pcls(struct ti_lynx *lynx)
{
struct ti_pcl pcl;
pcl.next = PCL_NEXT_INVALID;
pcl.user_data = pcl_bus(lynx, lynx->dmem_pcl);
put_pcl(lynx, lynx->dmem_pcl, &pcl);
}
static int mem_open(struct inode *inode, struct file *file)
{
int cid = iminor(inode);
enum { t_rom, t_aux, t_ram } type;
struct memdata *md;
if (cid < PCILYNX_MINOR_AUX_START) {
/* just for completeness */
return -ENXIO;
} else if (cid < PCILYNX_MINOR_ROM_START) {
cid -= PCILYNX_MINOR_AUX_START;
if (cid >= num_of_cards || !cards[cid].aux_port)
return -ENXIO;
type = t_aux;
} else if (cid < PCILYNX_MINOR_RAM_START) {
cid -= PCILYNX_MINOR_ROM_START;
if (cid >= num_of_cards || !cards[cid].local_rom)
return -ENXIO;
type = t_rom;
} else {
/* WARNING: Know what you are doing when opening RAM.
* It is currently used inside the driver! */
cid -= PCILYNX_MINOR_RAM_START;
if (cid >= num_of_cards || !cards[cid].local_ram)
return -ENXIO;
type = t_ram;
}
md = (struct memdata *)kmalloc(sizeof(struct memdata), SLAB_KERNEL);
if (md == NULL)
return -ENOMEM;
md->lynx = &cards[cid];
md->cid = cid;
switch (type) {
case t_rom:
md->type = rom;
break;
case t_ram:
md->type = ram;
break;
case t_aux:
atomic_set(&md->aux_intr_last_seen,
atomic_read(&cards[cid].aux_intr_seen));
md->type = aux;
break;
}
file->private_data = md;
return 0;
}
static int mem_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
return 0;
}
static unsigned int aux_poll(struct file *file, poll_table *pt)
{
struct memdata *md = (struct memdata *)file->private_data;
int cid = md->cid;
unsigned int mask;
/* reading and writing is always allowed */
mask = POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM;
if (md->type == aux) {
poll_wait(file, &cards[cid].aux_intr_wait, pt);
if (atomic_read(&md->aux_intr_last_seen)
!= atomic_read(&cards[cid].aux_intr_seen)) {
mask |= POLLPRI;
atomic_inc(&md->aux_intr_last_seen);
}
}
return mask;
}
loff_t mem_llseek(struct file *file, loff_t offs, int orig)
{
loff_t newoffs;
switch (orig) {
case 0:
newoffs = offs;
break;
case 1:
newoffs = offs + file->f_pos;
break;
case 2:
newoffs = PCILYNX_MAX_MEMORY + 1 + offs;
break;
default:
return -EINVAL;
}
if (newoffs < 0 || newoffs > PCILYNX_MAX_MEMORY + 1) return -EINVAL;
file->f_pos = newoffs;
return newoffs;
}
/*
* do not DMA if count is too small because this will have a serious impact
* on performance - the value 2400 was found by experiment and may not work
* everywhere as good as here - use mem_mindma option for modules to change
*/
static short mem_mindma = 2400;
module_param(mem_mindma, short, 0444);
MODULE_PARM_DESC(mem_mindma, "Minimum amount of data required to use DMA");
static ssize_t mem_dmaread(struct memdata *md, u32 physbuf, ssize_t count,
int offset)
{
pcltmp_t pcltmp;
struct ti_pcl *pcl;
size_t retval;
int i;
DECLARE_WAITQUEUE(wait, current);
count &= ~3;
count = min(count, 53196);
retval = count;
if (reg_read(md->lynx, DMA_CHAN_CTRL(CHANNEL_LOCALBUS))
& DMA_CHAN_CTRL_BUSY) {
PRINT(KERN_WARNING, md->lynx->id, "DMA ALREADY ACTIVE!");
}
reg_write(md->lynx, LBUS_ADDR, md->type | offset);
pcl = edit_pcl(md->lynx, md->lynx->dmem_pcl, &pcltmp);
pcl->buffer[0].control = PCL_CMD_LBUS_TO_PCI | min(count, 4092);
pcl->buffer[0].pointer = physbuf;
count -= 4092;
i = 0;
while (count > 0) {
i++;
pcl->buffer[i].control = min(count, 4092);
pcl->buffer[i].pointer = physbuf + i * 4092;
count -= 4092;
}
pcl->buffer[i].control |= PCL_LAST_BUFF;
commit_pcl(md->lynx, md->lynx->dmem_pcl, &pcltmp);
set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&md->lynx->mem_dma_intr_wait, &wait);
run_sub_pcl(md->lynx, md->lynx->dmem_pcl, 2, CHANNEL_LOCALBUS);
schedule();
while (reg_read(md->lynx, DMA_CHAN_CTRL(CHANNEL_LOCALBUS))
& DMA_CHAN_CTRL_BUSY) {
if (signal_pending(current)) {
retval = -EINTR;
break;
}
schedule();
}
reg_write(md->lynx, DMA_CHAN_CTRL(CHANNEL_LOCALBUS), 0);
remove_wait_queue(&md->lynx->mem_dma_intr_wait, &wait);
if (reg_read(md->lynx, DMA_CHAN_CTRL(CHANNEL_LOCALBUS))
& DMA_CHAN_CTRL_BUSY) {
PRINT(KERN_ERR, md->lynx->id, "DMA STILL ACTIVE!");
}
return retval;
}
static ssize_t mem_read(struct file *file, char *buffer, size_t count,
loff_t *offset)
{
struct memdata *md = (struct memdata *)file->private_data;
ssize_t bcount;
size_t alignfix;
loff_t off = *offset; /* avoid useless 64bit-arithmetic */
ssize_t retval;
void *membase;
if ((off + count) > PCILYNX_MAX_MEMORY+1) {
count = PCILYNX_MAX_MEMORY+1 - off;
}
if (count == 0 || off > PCILYNX_MAX_MEMORY) {
return -ENOSPC;
}
switch (md->type) {
case rom:
membase = md->lynx->local_rom;
break;
case ram:
membase = md->lynx->local_ram;
break;
case aux:
membase = md->lynx->aux_port;
break;
default:
panic("pcilynx%d: unsupported md->type %d in %s",
md->lynx->id, md->type, __FUNCTION__);
}
down(&md->lynx->mem_dma_mutex);
if (count < mem_mindma) {
memcpy_fromio(md->lynx->mem_dma_buffer, membase+off, count);
goto out;
}
bcount = count;
alignfix = 4 - (off % 4);
if (alignfix != 4) {
if (bcount < alignfix) {
alignfix = bcount;
}
memcpy_fromio(md->lynx->mem_dma_buffer, membase+off,
alignfix);
if (bcount == alignfix) {
goto out;
}
bcount -= alignfix;
off += alignfix;
}
while (bcount >= 4) {
retval = mem_dmaread(md, md->lynx->mem_dma_buffer_dma
+ count - bcount, bcount, off);
if (retval < 0) return retval;
bcount -= retval;
off += retval;
}
if (bcount) {
memcpy_fromio(md->lynx->mem_dma_buffer + count - bcount,
membase+off, bcount);
}
out:
retval = copy_to_user(buffer, md->lynx->mem_dma_buffer, count);
up(&md->lynx->mem_dma_mutex);
if (retval) return -EFAULT;
*offset += count;
return count;
}
static ssize_t mem_write(struct file *file, const char *buffer, size_t count,
loff_t *offset)
{
struct memdata *md = (struct memdata *)file->private_data;
if (((*offset) + count) > PCILYNX_MAX_MEMORY+1) {
count = PCILYNX_MAX_MEMORY+1 - *offset;
}
if (count == 0 || *offset > PCILYNX_MAX_MEMORY) {
return -ENOSPC;
}
/* FIXME: dereferencing pointers to PCI mem doesn't work everywhere */
switch (md->type) {
case aux:
if (copy_from_user(md->lynx->aux_port+(*offset), buffer, count))
return -EFAULT;
break;
case ram:
if (copy_from_user(md->lynx->local_ram+(*offset), buffer, count))
return -EFAULT;
break;
case rom:
/* the ROM may be writeable */
if (copy_from_user(md->lynx->local_rom+(*offset), buffer, count))
return -EFAULT;
break;
}
file->f_pos += count;
return count;
}
#endif /* CONFIG_IEEE1394_PCILYNX_PORTS */
/********************************************************
* Global stuff (interrupt handler, init/shutdown code) *
********************************************************/
static irqreturn_t lynx_irq_handler(int irq, void *dev_id,
struct pt_regs *regs_are_unused)
{
struct ti_lynx *lynx = (struct ti_lynx *)dev_id;
struct hpsb_host *host = lynx->host;
u32 intmask;
u32 linkint;
linkint = reg_read(lynx, LINK_INT_STATUS);
intmask = reg_read(lynx, PCI_INT_STATUS);
if (!(intmask & PCI_INT_INT_PEND))
return IRQ_NONE;
PRINTD(KERN_DEBUG, lynx->id, "interrupt: 0x%08x / 0x%08x", intmask,
linkint);
reg_write(lynx, LINK_INT_STATUS, linkint);
reg_write(lynx, PCI_INT_STATUS, intmask);
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
if (intmask & PCI_INT_AUX_INT) {
atomic_inc(&lynx->aux_intr_seen);
wake_up_interruptible(&lynx->aux_intr_wait);
}
if (intmask & PCI_INT_DMA_HLT(CHANNEL_LOCALBUS)) {
wake_up_interruptible(&lynx->mem_dma_intr_wait);
}
#endif
if (intmask & PCI_INT_1394) {
if (linkint & LINK_INT_PHY_TIMEOUT) {
PRINT(KERN_INFO, lynx->id, "PHY timeout occurred");
}
if (linkint & LINK_INT_PHY_BUSRESET) {
PRINT(KERN_INFO, lynx->id, "bus reset interrupt");
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
if (!host->in_bus_reset)
hpsb_bus_reset(host);
}
if (linkint & LINK_INT_PHY_REG_RCVD) {
u32 reg;
spin_lock(&lynx->phy_reg_lock);
reg = reg_read(lynx, LINK_PHY);
spin_unlock(&lynx->phy_reg_lock);
if (!host->in_bus_reset) {
PRINT(KERN_INFO, lynx->id,
"phy reg received without reset");
} else if (reg & 0xf00) {
PRINT(KERN_INFO, lynx->id,
"unsolicited phy reg %d received",
(reg >> 8) & 0xf);
} else {
lynx->phy_reg0 = reg & 0xff;
handle_selfid(lynx, host);
}
}
if (linkint & LINK_INT_ISO_STUCK) {
PRINT(KERN_INFO, lynx->id, "isochronous transmitter stuck");
}
if (linkint & LINK_INT_ASYNC_STUCK) {
PRINT(KERN_INFO, lynx->id, "asynchronous transmitter stuck");
}
if (linkint & LINK_INT_SENT_REJECT) {
PRINT(KERN_INFO, lynx->id, "sent reject");
}
if (linkint & LINK_INT_TX_INVALID_TC) {
PRINT(KERN_INFO, lynx->id, "invalid transaction code");
}
if (linkint & LINK_INT_GRF_OVERFLOW) {
/* flush FIFO if overflow happens during reset */
if (host->in_bus_reset)
reg_write(lynx, FIFO_CONTROL,
FIFO_CONTROL_GRF_FLUSH);
PRINT(KERN_INFO, lynx->id, "GRF overflow");
}
if (linkint & LINK_INT_ITF_UNDERFLOW) {
PRINT(KERN_INFO, lynx->id, "ITF underflow");
}
if (linkint & LINK_INT_ATF_UNDERFLOW) {
PRINT(KERN_INFO, lynx->id, "ATF underflow");
}
}
if (intmask & PCI_INT_DMA_HLT(CHANNEL_ISO_RCV)) {
PRINTD(KERN_DEBUG, lynx->id, "iso receive");
spin_lock(&lynx->iso_rcv.lock);
lynx->iso_rcv.stat[lynx->iso_rcv.next] =
reg_read(lynx, DMA_CHAN_STAT(CHANNEL_ISO_RCV));
lynx->iso_rcv.used++;
lynx->iso_rcv.next = (lynx->iso_rcv.next + 1) % NUM_ISORCV_PCL;
if ((lynx->iso_rcv.next == lynx->iso_rcv.last)
|| !lynx->iso_rcv.chan_count) {
PRINTD(KERN_DEBUG, lynx->id, "stopped");
reg_write(lynx, DMA_WORD1_CMP_ENABLE(CHANNEL_ISO_RCV), 0);
}
run_sub_pcl(lynx, lynx->iso_rcv.pcl_start, lynx->iso_rcv.next,
CHANNEL_ISO_RCV);
spin_unlock(&lynx->iso_rcv.lock);
tasklet_schedule(&lynx->iso_rcv.tq);
}
if (intmask & PCI_INT_DMA_HLT(CHANNEL_ASYNC_SEND)) {
PRINTD(KERN_DEBUG, lynx->id, "async sent");
spin_lock(&lynx->async.queue_lock);
if (list_empty(&lynx->async.pcl_queue)) {
spin_unlock(&lynx->async.queue_lock);
PRINT(KERN_WARNING, lynx->id, "async dma halted, but no queued packet (maybe it was cancelled)");
} else {
struct ti_pcl pcl;
u32 ack;
struct hpsb_packet *packet;
get_pcl(lynx, lynx->async.pcl, &pcl);
packet = driver_packet(lynx->async.pcl_queue.next);
list_del_init(&packet->driver_list);
pci_unmap_single(lynx->dev, lynx->async.header_dma,
packet->header_size, PCI_DMA_TODEVICE);
if (packet->data_size) {
pci_unmap_single(lynx->dev, lynx->async.data_dma,
packet->data_size, PCI_DMA_TODEVICE);
}
if (!list_empty(&lynx->async.queue)) {
send_next(lynx, hpsb_async);
}
spin_unlock(&lynx->async.queue_lock);
if (pcl.pcl_status & DMA_CHAN_STAT_PKTCMPL) {
if (pcl.pcl_status & DMA_CHAN_STAT_SPECIALACK) {
ack = (pcl.pcl_status >> 15) & 0xf;
PRINTD(KERN_INFO, lynx->id, "special ack %d", ack);
ack = (ack == 1 ? ACKX_TIMEOUT : ACKX_SEND_ERROR);
} else {
ack = (pcl.pcl_status >> 15) & 0xf;
}
} else {
PRINT(KERN_INFO, lynx->id, "async packet was not completed");
ack = ACKX_SEND_ERROR;
}
hpsb_packet_sent(host, packet, ack);
}
}
if (intmask & PCI_INT_DMA_HLT(CHANNEL_ISO_SEND)) {
PRINTD(KERN_DEBUG, lynx->id, "iso sent");
spin_lock(&lynx->iso_send.queue_lock);
if (list_empty(&lynx->iso_send.pcl_queue)) {
spin_unlock(&lynx->iso_send.queue_lock);
PRINT(KERN_ERR, lynx->id, "iso send dma halted, but no queued packet");
} else {
struct ti_pcl pcl;
u32 ack;
struct hpsb_packet *packet;
get_pcl(lynx, lynx->iso_send.pcl, &pcl);
packet = driver_packet(lynx->iso_send.pcl_queue.next);
list_del_init(&packet->driver_list);
pci_unmap_single(lynx->dev, lynx->iso_send.header_dma,
packet->header_size, PCI_DMA_TODEVICE);
if (packet->data_size) {
pci_unmap_single(lynx->dev, lynx->iso_send.data_dma,
packet->data_size, PCI_DMA_TODEVICE);
}
if (!list_empty(&lynx->iso_send.queue)) {
send_next(lynx, hpsb_iso);
}
spin_unlock(&lynx->iso_send.queue_lock);
if (pcl.pcl_status & DMA_CHAN_STAT_PKTCMPL) {
if (pcl.pcl_status & DMA_CHAN_STAT_SPECIALACK) {
ack = (pcl.pcl_status >> 15) & 0xf;
PRINTD(KERN_INFO, lynx->id, "special ack %d", ack);
ack = (ack == 1 ? ACKX_TIMEOUT : ACKX_SEND_ERROR);
} else {
ack = (pcl.pcl_status >> 15) & 0xf;
}
} else {
PRINT(KERN_INFO, lynx->id, "iso send packet was not completed");
ack = ACKX_SEND_ERROR;
}
hpsb_packet_sent(host, packet, ack); //FIXME: maybe we should just use ACK_COMPLETE and ACKX_SEND_ERROR
}
}
if (intmask & PCI_INT_DMA_HLT(CHANNEL_ASYNC_RCV)) {
/* general receive DMA completed */
int stat = reg_read(lynx, DMA_CHAN_STAT(CHANNEL_ASYNC_RCV));
PRINTD(KERN_DEBUG, lynx->id, "received packet size %d",
stat & 0x1fff);
if (stat & DMA_CHAN_STAT_SELFID) {
lynx->selfid_size = stat & 0x1fff;
handle_selfid(lynx, host);
} else {
quadlet_t *q_data = lynx->rcv_page;
if ((*q_data >> 4 & 0xf) == TCODE_READQ_RESPONSE
|| (*q_data >> 4 & 0xf) == TCODE_WRITEQ) {
cpu_to_be32s(q_data + 3);
}
hpsb_packet_received(host, q_data, stat & 0x1fff, 0);
}
run_pcl(lynx, lynx->rcv_pcl_start, CHANNEL_ASYNC_RCV);
}
return IRQ_HANDLED;
}
static void iso_rcv_bh(struct ti_lynx *lynx)
{
unsigned int idx;
quadlet_t *data;
unsigned long flags;
spin_lock_irqsave(&lynx->iso_rcv.lock, flags);
while (lynx->iso_rcv.used) {
idx = lynx->iso_rcv.last;
spin_unlock_irqrestore(&lynx->iso_rcv.lock, flags);
data = lynx->iso_rcv.page[idx / ISORCV_PER_PAGE]
+ (idx % ISORCV_PER_PAGE) * MAX_ISORCV_SIZE;
if ((*data >> 16) + 4 != (lynx->iso_rcv.stat[idx] & 0x1fff)) {
PRINT(KERN_ERR, lynx->id,
"iso length mismatch 0x%08x/0x%08x", *data,
lynx->iso_rcv.stat[idx]);
}
if (lynx->iso_rcv.stat[idx]
& (DMA_CHAN_STAT_PCIERR | DMA_CHAN_STAT_PKTERR)) {
PRINT(KERN_INFO, lynx->id,
"iso receive error on %d to 0x%p", idx, data);
} else {
hpsb_packet_received(lynx->host, data,
lynx->iso_rcv.stat[idx] & 0x1fff,
0);
}
spin_lock_irqsave(&lynx->iso_rcv.lock, flags);
lynx->iso_rcv.last = (idx + 1) % NUM_ISORCV_PCL;
lynx->iso_rcv.used--;
}
if (lynx->iso_rcv.chan_count) {
reg_write(lynx, DMA_WORD1_CMP_ENABLE(CHANNEL_ISO_RCV),
DMA_WORD1_CMP_ENABLE_MASTER);
}
spin_unlock_irqrestore(&lynx->iso_rcv.lock, flags);
}
static void remove_card(struct pci_dev *dev)
{
struct ti_lynx *lynx;
struct device *lynx_dev;
int i;
lynx = pci_get_drvdata(dev);
if (!lynx) return;
pci_set_drvdata(dev, NULL);
lynx_dev = get_device(&lynx->host->device);
switch (lynx->state) {
case is_host:
reg_write(lynx, PCI_INT_ENABLE, 0);
hpsb_remove_host(lynx->host);
case have_intr:
reg_write(lynx, PCI_INT_ENABLE, 0);
free_irq(lynx->dev->irq, lynx);
/* Disable IRM Contender and LCtrl */
if (lynx->phyic.reg_1394a)
set_phy_reg(lynx, 4, ~0xc0 & get_phy_reg(lynx, 4));
/* Let all other nodes know to ignore us */
lynx_devctl(lynx->host, RESET_BUS, LONG_RESET_NO_FORCE_ROOT);
case have_iomappings:
reg_set_bits(lynx, MISC_CONTROL, MISC_CONTROL_SWRESET);
/* Fix buggy cards with autoboot pin not tied low: */
reg_write(lynx, DMA0_CHAN_CTRL, 0);
iounmap(lynx->registers);
iounmap(lynx->local_rom);
iounmap(lynx->local_ram);
iounmap(lynx->aux_port);
case have_1394_buffers:
for (i = 0; i < ISORCV_PAGES; i++) {
if (lynx->iso_rcv.page[i]) {
pci_free_consistent(lynx->dev, PAGE_SIZE,
lynx->iso_rcv.page[i],
lynx->iso_rcv.page_dma[i]);
}
}
pci_free_consistent(lynx->dev, PAGE_SIZE, lynx->rcv_page,
lynx->rcv_page_dma);
case have_aux_buf:
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
pci_free_consistent(lynx->dev, 65536, lynx->mem_dma_buffer,
lynx->mem_dma_buffer_dma);
#endif
case have_pcl_mem:
#ifndef CONFIG_IEEE1394_PCILYNX_LOCALRAM
pci_free_consistent(lynx->dev, LOCALRAM_SIZE, lynx->pcl_mem,
lynx->pcl_mem_dma);
#endif
case clear:
/* do nothing - already freed */
;
}
tasklet_kill(&lynx->iso_rcv.tq);
if (lynx_dev)
put_device(lynx_dev);
}
static int __devinit add_card(struct pci_dev *dev,
const struct pci_device_id *devid_is_unused)
{
#define FAIL(fmt, args...) do { \
PRINT_G(KERN_ERR, fmt , ## args); \
remove_card(dev); \
return error; \
} while (0)
char irq_buf[16];
struct hpsb_host *host;
struct ti_lynx *lynx; /* shortcut to currently handled device */
struct ti_pcl pcl;
u32 *pcli;
int i;
int error;
error = -ENXIO;
if (pci_set_dma_mask(dev, 0xffffffff))
FAIL("DMA address limits not supported for PCILynx hardware");
if (pci_enable_device(dev))
FAIL("failed to enable PCILynx hardware");
pci_set_master(dev);
error = -ENOMEM;
host = hpsb_alloc_host(&lynx_driver, sizeof(struct ti_lynx), &dev->dev);
if (!host) FAIL("failed to allocate control structure memory");
lynx = host->hostdata;
lynx->id = card_id++;
lynx->dev = dev;
lynx->state = clear;
lynx->host = host;
host->pdev = dev;
pci_set_drvdata(dev, lynx);
spin_lock_init(&lynx->lock);
spin_lock_init(&lynx->phy_reg_lock);
#ifndef CONFIG_IEEE1394_PCILYNX_LOCALRAM
lynx->pcl_mem = pci_alloc_consistent(dev, LOCALRAM_SIZE,
&lynx->pcl_mem_dma);
if (lynx->pcl_mem != NULL) {
lynx->state = have_pcl_mem;
PRINT(KERN_INFO, lynx->id,
"allocated PCL memory %d Bytes @ 0x%p", LOCALRAM_SIZE,
lynx->pcl_mem);
} else {
FAIL("failed to allocate PCL memory area");
}
#endif
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
lynx->mem_dma_buffer = pci_alloc_consistent(dev, 65536,
&lynx->mem_dma_buffer_dma);
if (lynx->mem_dma_buffer == NULL) {
FAIL("failed to allocate DMA buffer for aux");
}
lynx->state = have_aux_buf;
#endif
lynx->rcv_page = pci_alloc_consistent(dev, PAGE_SIZE,
&lynx->rcv_page_dma);
if (lynx->rcv_page == NULL) {
FAIL("failed to allocate receive buffer");
}
lynx->state = have_1394_buffers;
for (i = 0; i < ISORCV_PAGES; i++) {
lynx->iso_rcv.page[i] =
pci_alloc_consistent(dev, PAGE_SIZE,
&lynx->iso_rcv.page_dma[i]);
if (lynx->iso_rcv.page[i] == NULL) {
FAIL("failed to allocate iso receive buffers");
}
}
lynx->registers = ioremap_nocache(pci_resource_start(dev,0),
PCILYNX_MAX_REGISTER);
lynx->local_ram = ioremap(pci_resource_start(dev,1), PCILYNX_MAX_MEMORY);
lynx->aux_port = ioremap(pci_resource_start(dev,2), PCILYNX_MAX_MEMORY);
lynx->local_rom = ioremap(pci_resource_start(dev,PCI_ROM_RESOURCE),
PCILYNX_MAX_MEMORY);
lynx->state = have_iomappings;
if (lynx->registers == NULL) {
FAIL("failed to remap registers - card not accessible");
}
#ifdef CONFIG_IEEE1394_PCILYNX_LOCALRAM
if (lynx->local_ram == NULL) {
FAIL("failed to remap local RAM which is required for "
"operation");
}
#endif
reg_set_bits(lynx, MISC_CONTROL, MISC_CONTROL_SWRESET);
/* Fix buggy cards with autoboot pin not tied low: */
reg_write(lynx, DMA0_CHAN_CTRL, 0);
#ifndef __sparc__
sprintf (irq_buf, "%d", dev->irq);
#else
sprintf (irq_buf, "%s", __irq_itoa(dev->irq));
#endif
if (!request_irq(dev->irq, lynx_irq_handler, SA_SHIRQ,
PCILYNX_DRIVER_NAME, lynx)) {
PRINT(KERN_INFO, lynx->id, "allocated interrupt %s", irq_buf);
lynx->state = have_intr;
} else {
FAIL("failed to allocate shared interrupt %s", irq_buf);
}
/* alloc_pcl return values are not checked, it is expected that the
* provided PCL space is sufficient for the initial allocations */
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
if (lynx->aux_port != NULL) {
lynx->dmem_pcl = alloc_pcl(lynx);
aux_setup_pcls(lynx);
sema_init(&lynx->mem_dma_mutex, 1);
}
#endif
lynx->rcv_pcl = alloc_pcl(lynx);
lynx->rcv_pcl_start = alloc_pcl(lynx);
lynx->async.pcl = alloc_pcl(lynx);
lynx->async.pcl_start = alloc_pcl(lynx);
lynx->iso_send.pcl = alloc_pcl(lynx);
lynx->iso_send.pcl_start = alloc_pcl(lynx);
for (i = 0; i < NUM_ISORCV_PCL; i++) {
lynx->iso_rcv.pcl[i] = alloc_pcl(lynx);
}
lynx->iso_rcv.pcl_start = alloc_pcl(lynx);
/* all allocations successful - simple init stuff follows */
reg_write(lynx, PCI_INT_ENABLE, PCI_INT_DMA_ALL);
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
reg_set_bits(lynx, PCI_INT_ENABLE, PCI_INT_AUX_INT);
init_waitqueue_head(&lynx->mem_dma_intr_wait);
init_waitqueue_head(&lynx->aux_intr_wait);
#endif
tasklet_init(&lynx->iso_rcv.tq, (void (*)(unsigned long))iso_rcv_bh,
(unsigned long)lynx);
spin_lock_init(&lynx->iso_rcv.lock);
spin_lock_init(&lynx->async.queue_lock);
lynx->async.channel = CHANNEL_ASYNC_SEND;
spin_lock_init(&lynx->iso_send.queue_lock);
lynx->iso_send.channel = CHANNEL_ISO_SEND;
PRINT(KERN_INFO, lynx->id, "remapped memory spaces reg 0x%p, rom 0x%p, "
"ram 0x%p, aux 0x%p", lynx->registers, lynx->local_rom,
lynx->local_ram, lynx->aux_port);
/* now, looking for PHY register set */
if ((get_phy_reg(lynx, 2) & 0xe0) == 0xe0) {
lynx->phyic.reg_1394a = 1;
PRINT(KERN_INFO, lynx->id,
"found 1394a conform PHY (using extended register set)");
lynx->phyic.vendor = get_phy_vendorid(lynx);
lynx->phyic.product = get_phy_productid(lynx);
} else {
lynx->phyic.reg_1394a = 0;
PRINT(KERN_INFO, lynx->id, "found old 1394 PHY");
}
lynx->selfid_size = -1;
lynx->phy_reg0 = -1;
INIT_LIST_HEAD(&lynx->async.queue);
INIT_LIST_HEAD(&lynx->async.pcl_queue);
INIT_LIST_HEAD(&lynx->iso_send.queue);
INIT_LIST_HEAD(&lynx->iso_send.pcl_queue);
pcl.next = pcl_bus(lynx, lynx->rcv_pcl);
put_pcl(lynx, lynx->rcv_pcl_start, &pcl);
pcl.next = PCL_NEXT_INVALID;
pcl.async_error_next = PCL_NEXT_INVALID;
pcl.buffer[0].control = PCL_CMD_RCV | 16;
#ifndef __BIG_ENDIAN
pcl.buffer[0].control |= PCL_BIGENDIAN;
#endif
pcl.buffer[1].control = PCL_LAST_BUFF | 4080;
pcl.buffer[0].pointer = lynx->rcv_page_dma;
pcl.buffer[1].pointer = lynx->rcv_page_dma + 16;
put_pcl(lynx, lynx->rcv_pcl, &pcl);
pcl.next = pcl_bus(lynx, lynx->async.pcl);
pcl.async_error_next = pcl_bus(lynx, lynx->async.pcl);
put_pcl(lynx, lynx->async.pcl_start, &pcl);
pcl.next = pcl_bus(lynx, lynx->iso_send.pcl);
pcl.async_error_next = PCL_NEXT_INVALID;
put_pcl(lynx, lynx->iso_send.pcl_start, &pcl);
pcl.next = PCL_NEXT_INVALID;
pcl.async_error_next = PCL_NEXT_INVALID;
pcl.buffer[0].control = PCL_CMD_RCV | 4;
#ifndef __BIG_ENDIAN
pcl.buffer[0].control |= PCL_BIGENDIAN;
#endif
pcl.buffer[1].control = PCL_LAST_BUFF | 2044;
for (i = 0; i < NUM_ISORCV_PCL; i++) {
int page = i / ISORCV_PER_PAGE;
int sec = i % ISORCV_PER_PAGE;
pcl.buffer[0].pointer = lynx->iso_rcv.page_dma[page]
+ sec * MAX_ISORCV_SIZE;
pcl.buffer[1].pointer = pcl.buffer[0].pointer + 4;
put_pcl(lynx, lynx->iso_rcv.pcl[i], &pcl);
}
pcli = (u32 *)&pcl;
for (i = 0; i < NUM_ISORCV_PCL; i++) {
pcli[i] = pcl_bus(lynx, lynx->iso_rcv.pcl[i]);
}
put_pcl(lynx, lynx->iso_rcv.pcl_start, &pcl);
/* FIFO sizes from left to right: ITF=48 ATF=48 GRF=160 */
reg_write(lynx, FIFO_SIZES, 0x003030a0);
/* 20 byte threshold before triggering PCI transfer */
reg_write(lynx, DMA_GLOBAL_REGISTER, 0x2<<24);
/* threshold on both send FIFOs before transmitting:
FIFO size - cache line size - 1 */
i = reg_read(lynx, PCI_LATENCY_CACHELINE) & 0xff;
i = 0x30 - i - 1;
reg_write(lynx, FIFO_XMIT_THRESHOLD, (i << 8) | i);
reg_set_bits(lynx, PCI_INT_ENABLE, PCI_INT_1394);
reg_write(lynx, LINK_INT_ENABLE, LINK_INT_PHY_TIMEOUT
| LINK_INT_PHY_REG_RCVD | LINK_INT_PHY_BUSRESET
| LINK_INT_ISO_STUCK | LINK_INT_ASYNC_STUCK
| LINK_INT_SENT_REJECT | LINK_INT_TX_INVALID_TC
| LINK_INT_GRF_OVERFLOW | LINK_INT_ITF_UNDERFLOW
| LINK_INT_ATF_UNDERFLOW);
reg_write(lynx, DMA_WORD0_CMP_VALUE(CHANNEL_ASYNC_RCV), 0);
reg_write(lynx, DMA_WORD0_CMP_ENABLE(CHANNEL_ASYNC_RCV), 0xa<<4);
reg_write(lynx, DMA_WORD1_CMP_VALUE(CHANNEL_ASYNC_RCV), 0);
reg_write(lynx, DMA_WORD1_CMP_ENABLE(CHANNEL_ASYNC_RCV),
DMA_WORD1_CMP_MATCH_LOCAL_NODE | DMA_WORD1_CMP_MATCH_BROADCAST
| DMA_WORD1_CMP_MATCH_EXACT | DMA_WORD1_CMP_MATCH_BUS_BCAST
| DMA_WORD1_CMP_ENABLE_SELF_ID | DMA_WORD1_CMP_ENABLE_MASTER);
run_pcl(lynx, lynx->rcv_pcl_start, CHANNEL_ASYNC_RCV);
reg_write(lynx, DMA_WORD0_CMP_VALUE(CHANNEL_ISO_RCV), 0);
reg_write(lynx, DMA_WORD0_CMP_ENABLE(CHANNEL_ISO_RCV), 0x9<<4);
reg_write(lynx, DMA_WORD1_CMP_VALUE(CHANNEL_ISO_RCV), 0);
reg_write(lynx, DMA_WORD1_CMP_ENABLE(CHANNEL_ISO_RCV), 0);
run_sub_pcl(lynx, lynx->iso_rcv.pcl_start, 0, CHANNEL_ISO_RCV);
reg_write(lynx, LINK_CONTROL, LINK_CONTROL_RCV_CMP_VALID
| LINK_CONTROL_TX_ISO_EN | LINK_CONTROL_RX_ISO_EN
| LINK_CONTROL_TX_ASYNC_EN | LINK_CONTROL_RX_ASYNC_EN
| LINK_CONTROL_RESET_TX | LINK_CONTROL_RESET_RX);
if (!lynx->phyic.reg_1394a) {
if (!hpsb_disable_irm) {
/* attempt to enable contender bit -FIXME- would this
* work elsewhere? */
reg_set_bits(lynx, GPIO_CTRL_A, 0x1);
reg_write(lynx, GPIO_DATA_BASE + 0x3c, 0x1);
}
} else {
/* set the contender (if appropriate) and LCtrl bit in the
* extended PHY register set. (Should check that PHY_02_EXTENDED
* is set in register 2?)
*/
i = get_phy_reg(lynx, 4);
i |= PHY_04_LCTRL;
if (hpsb_disable_irm)
i &= !PHY_04_CONTENDER;
else
i |= PHY_04_CONTENDER;
if (i != -1) set_phy_reg(lynx, 4, i);
}
if (!skip_eeprom)
{
/* needed for i2c communication with serial eeprom */
struct i2c_adapter *i2c_ad;
struct i2c_algo_bit_data i2c_adapter_data;
error = -ENOMEM;
i2c_ad = kmalloc(sizeof(struct i2c_adapter), SLAB_KERNEL);
if (!i2c_ad) FAIL("failed to allocate I2C adapter memory");
memcpy(i2c_ad, &bit_ops, sizeof(struct i2c_adapter));
i2c_adapter_data = bit_data;
i2c_ad->algo_data = &i2c_adapter_data;
i2c_adapter_data.data = lynx;
PRINTD(KERN_DEBUG, lynx->id,"original eeprom control: %d",
reg_read(lynx, SERIAL_EEPROM_CONTROL));
/* reset hardware to sane state */
lynx->i2c_driven_state = 0x00000070;
reg_write(lynx, SERIAL_EEPROM_CONTROL, lynx->i2c_driven_state);
if (i2c_bit_add_bus(i2c_ad) < 0)
{
kfree(i2c_ad);
error = -ENXIO;
FAIL("unable to register i2c");
}
else
{
/* do i2c stuff */
unsigned char i2c_cmd = 0x10;
struct i2c_msg msg[2] = { { 0x50, 0, 1, &i2c_cmd },
{ 0x50, I2C_M_RD, 20, (unsigned char*) lynx->bus_info_block }
};
#ifdef CONFIG_IEEE1394_VERBOSEDEBUG
union i2c_smbus_data data;
if (i2c_smbus_xfer(i2c_ad, 80, 0, I2C_SMBUS_WRITE, 0, I2C_SMBUS_BYTE,NULL))
PRINT(KERN_ERR, lynx->id,"eeprom read start has failed");
else
{
u16 addr;
for (addr=0x00; addr < 0x100; addr++) {
if (i2c_smbus_xfer(i2c_ad, 80, 0, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE,& data)) {
PRINT(KERN_ERR, lynx->id, "unable to read i2c %x", addr);
break;
}
else
PRINT(KERN_DEBUG, lynx->id,"got serial eeprom data at %x: %x",addr, data.byte);
}
}
#endif
/* we use i2c_transfer, because i2c_smbus_read_block_data does not work properly and we
do it more efficiently in one transaction rather then using several reads */
if (i2c_transfer(i2c_ad, msg, 2) < 0) {
PRINT(KERN_ERR, lynx->id, "unable to read bus info block from i2c");
} else {
int i;
PRINT(KERN_INFO, lynx->id, "got bus info block from serial eeprom");
/* FIXME: probably we shoud rewrite the max_rec, max_ROM(1394a),
* generation(1394a) and link_spd(1394a) field and recalculate
* the CRC */
for (i = 0; i < 5 ; i++)
PRINTD(KERN_DEBUG, lynx->id, "Businfo block quadlet %i: %08x",
i, be32_to_cpu(lynx->bus_info_block[i]));
/* info_length, crc_length and 1394 magic number to check, if it is really a bus info block */
if (((be32_to_cpu(lynx->bus_info_block[0]) & 0xffff0000) == 0x04040000) &&
(lynx->bus_info_block[1] == __constant_cpu_to_be32(0x31333934)))
{
PRINT(KERN_DEBUG, lynx->id, "read a valid bus info block from");
} else {
kfree(i2c_ad);
error = -ENXIO;
FAIL("read something from serial eeprom, but it does not seem to be a valid bus info block");
}
}
i2c_bit_del_bus(i2c_ad);
kfree(i2c_ad);
}
}
host->csr.guid_hi = be32_to_cpu(lynx->bus_info_block[3]);
host->csr.guid_lo = be32_to_cpu(lynx->bus_info_block[4]);
host->csr.cyc_clk_acc = (be32_to_cpu(lynx->bus_info_block[2]) >> 16) & 0xff;
host->csr.max_rec = (be32_to_cpu(lynx->bus_info_block[2]) >> 12) & 0xf;
if (!lynx->phyic.reg_1394a)
host->csr.lnk_spd = (get_phy_reg(lynx, 2) & 0xc0) >> 6;
else
host->csr.lnk_spd = be32_to_cpu(lynx->bus_info_block[2]) & 0x7;
if (hpsb_add_host(host)) {
error = -ENOMEM;
FAIL("Failed to register host with highlevel");
}
lynx->state = is_host;
return 0;
#undef FAIL
}
static struct pci_device_id pci_table[] = {
{
.vendor = PCI_VENDOR_ID_TI,
.device = PCI_DEVICE_ID_TI_PCILYNX,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ } /* Terminating entry */
};
static struct pci_driver lynx_pci_driver = {
.name = PCILYNX_DRIVER_NAME,
.id_table = pci_table,
.probe = add_card,
.remove = remove_card,
};
static struct hpsb_host_driver lynx_driver = {
.owner = THIS_MODULE,
.name = PCILYNX_DRIVER_NAME,
.set_hw_config_rom = NULL,
.transmit_packet = lynx_transmit,
.devctl = lynx_devctl,
.isoctl = NULL,
};
MODULE_AUTHOR("Andreas E. Bombe <andreas.bombe@munich.netsurf.de>");
MODULE_DESCRIPTION("driver for Texas Instruments PCI Lynx IEEE-1394 controller");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("pcilynx");
MODULE_DEVICE_TABLE(pci, pci_table);
static int __init pcilynx_init(void)
{
int ret;
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
if (register_chrdev(PCILYNX_MAJOR, PCILYNX_DRIVER_NAME, &aux_ops)) {
PRINT_G(KERN_ERR, "allocation of char major number %d failed",
PCILYNX_MAJOR);
return -EBUSY;
}
#endif
ret = pci_register_driver(&lynx_pci_driver);
if (ret < 0) {
PRINT_G(KERN_ERR, "PCI module init failed");
goto free_char_dev;
}
return 0;
free_char_dev:
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
unregister_chrdev(PCILYNX_MAJOR, PCILYNX_DRIVER_NAME);
#endif
return ret;
}
static void __exit pcilynx_cleanup(void)
{
pci_unregister_driver(&lynx_pci_driver);
#ifdef CONFIG_IEEE1394_PCILYNX_PORTS
unregister_chrdev(PCILYNX_MAJOR, PCILYNX_DRIVER_NAME);
#endif
}
module_init(pcilynx_init);
module_exit(pcilynx_cleanup);
| gpl-2.0 |
deafgoat/mysql-server | storage/heap/hp_scan.c | 12 | 2221 | /* Copyright (c) 2000, 2015, Oracle and/or its affiliates. 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 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
/* Scan through all rows */
#include "heapdef.h"
/*
Returns one of following values:
0 = Ok.
HA_ERR_RECORD_DELETED = Record is deleted.
HA_ERR_END_OF_FILE = EOF.
*/
int heap_scan_init(HP_INFO *info)
{
DBUG_ENTER("heap_scan_init");
info->lastinx= -1;
info->current_record= (ulong) ~0L; /* No current record */
info->update=0;
info->next_block=0;
DBUG_RETURN(0);
}
int heap_scan(HP_INFO *info, uchar *record)
{
HP_SHARE *share=info->s;
ulong pos;
DBUG_ENTER("heap_scan");
pos= ++info->current_record;
if (pos < info->next_block)
{
info->current_ptr+=share->block.recbuffer;
}
else
{
info->next_block+=share->block.records_in_block;
if (info->next_block >= share->records+share->deleted)
{
info->next_block= share->records+share->deleted;
if (pos >= info->next_block)
{
info->update= 0;
set_my_errno(HA_ERR_END_OF_FILE);
DBUG_RETURN(HA_ERR_END_OF_FILE);
}
}
hp_find_record(info, pos);
}
if (!info->current_ptr[share->reclength])
{
DBUG_PRINT("warning",("Found deleted record"));
info->update= HA_STATE_PREV_FOUND | HA_STATE_NEXT_FOUND;
set_my_errno(HA_ERR_RECORD_DELETED);
DBUG_RETURN(HA_ERR_RECORD_DELETED);
}
info->update= HA_STATE_PREV_FOUND | HA_STATE_NEXT_FOUND | HA_STATE_AKTIV;
memcpy(record,info->current_ptr,(size_t) share->reclength);
info->current_hash_ptr=0; /* Can't use read_next */
DBUG_RETURN(0);
} /* heap_scan */
| gpl-2.0 |
g-k-r/bluez | obexd/client/map.c | 12 | 50135 | /*
*
* OBEX Client
*
* Copyright (C) 2011 Bartosz Szatkowski <bulislaw@linux.com> for Comarch
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
#include <stdlib.h>
#include <glib.h>
#include <gdbus/gdbus.h>
#include <gobex/gobex-apparam.h>
#include <bluetooth/sdp.h>
#include "dbus.h"
#include "log.h"
#include "map_ap.h"
#include "map-event.h"
#include "map.h"
#include "transfer.h"
#include "session.h"
#include "driver.h"
#define OBEX_MAS_UUID \
"\xBB\x58\x2B\x40\x42\x0C\x11\xDB\xB0\xDE\x08\x00\x20\x0C\x9A\x66"
#define OBEX_MAS_UUID_LEN 16
#define MAP_INTERFACE "org.bluez.obex.MessageAccess1"
#define MAP_MSG_INTERFACE "org.bluez.obex.Message1"
#define ERROR_INTERFACE "org.bluez.obex.Error"
#define MAS_UUID "00001132-0000-1000-8000-00805f9b34fb"
#define DEFAULT_COUNT 1024
#define DEFAULT_OFFSET 0
#define CHARSET_NATIVE 0
#define CHARSET_UTF8 1
static const char * const filter_list[] = {
"subject",
"timestamp",
"sender",
"sender-address",
"recipient",
"recipient-address",
"type",
"size",
"status",
"text",
"attachment",
"priority",
"read",
"sent",
"protected",
"replyto",
NULL
};
#define FILTER_BIT_MAX 15
#define FILTER_ALL 0x0000FFFF
#define FILTER_READ_STATUS_NONE 0x00
#define FILTER_READ_STATUS_ONLY_UNREAD 0x01
#define FILTER_READ_STATUS_ONLY_READ 0x02
#define FILTER_PRIORITY_NONE 0x00
#define FILTER_PRIORITY_ONLY_HIGH 0x01
#define FILTER_PRIORITY_ONLY_NONHIGH 0x02
#define STATUS_READ 0
#define STATUS_DELETE 1
#define FILLER_BYTE 0x30
struct map_data {
struct obc_session *session;
GHashTable *messages;
int16_t mas_instance_id;
uint8_t supported_message_types;
};
struct pending_request {
struct map_data *map;
DBusMessage *msg;
char *folder;
};
#define MAP_MSG_FLAG_PRIORITY 0x01
#define MAP_MSG_FLAG_READ 0x02
#define MAP_MSG_FLAG_SENT 0x04
#define MAP_MSG_FLAG_PROTECTED 0x08
#define MAP_MSG_FLAG_TEXT 0x10
struct map_msg {
struct map_data *data;
char *path;
uint64_t handle;
char *subject;
char *timestamp;
char *sender;
char *sender_address;
char *replyto;
char *recipient;
char *recipient_address;
char *type;
uint64_t size;
char *status;
uint64_t attachment_size;
uint8_t flags;
char *folder;
GDBusPendingPropertySet pending;
};
struct map_parser {
struct pending_request *request;
DBusMessageIter *iter;
};
static DBusConnection *conn = NULL;
static struct pending_request *pending_request_new(struct map_data *map,
DBusMessage *message)
{
struct pending_request *p;
p = g_new0(struct pending_request, 1);
p->map = map;
p->msg = dbus_message_ref(message);
return p;
}
static void pending_request_free(struct pending_request *p)
{
dbus_message_unref(p->msg);
g_free(p->folder);
g_free(p);
}
static void simple_cb(struct obc_session *session,
struct obc_transfer *transfer,
GError *err, void *user_data)
{
struct pending_request *request = user_data;
DBusMessage *reply;
if (err != NULL)
reply = g_dbus_create_error(request->msg,
ERROR_INTERFACE ".Failed",
"%s", err->message);
else
reply = dbus_message_new_method_return(request->msg);
g_dbus_send_message(conn, reply);
pending_request_free(request);
}
static DBusMessage *map_setpath(DBusConnection *connection,
DBusMessage *message, void *user_data)
{
struct map_data *map = user_data;
const char *folder;
struct pending_request *request;
GError *err = NULL;
if (dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &folder,
DBUS_TYPE_INVALID) == FALSE)
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments",
NULL);
request = pending_request_new(map, message);
obc_session_setpath(map->session, folder, simple_cb, request, &err);
if (err != NULL) {
DBusMessage *reply;
reply = g_dbus_create_error(message,
ERROR_INTERFACE ".Failed",
"%s", err->message);
g_error_free(err);
pending_request_free(request);
return reply;
}
return NULL;
}
static void folder_element(GMarkupParseContext *ctxt, const char *element,
const char **names, const char **values,
gpointer user_data, GError **gerr)
{
DBusMessageIter dict, *iter = user_data;
const char *key;
int i;
if (strcasecmp("folder", element) != 0)
return;
dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
for (i = 0, key = names[i]; key; key = names[++i]) {
if (strcasecmp("name", key) == 0)
obex_dbus_dict_append(&dict, "Name", DBUS_TYPE_STRING,
&values[i]);
}
dbus_message_iter_close_container(iter, &dict);
}
static const GMarkupParser folder_parser = {
folder_element,
NULL,
NULL,
NULL,
NULL
};
static void folder_listing_cb(struct obc_session *session,
struct obc_transfer *transfer,
GError *err, void *user_data)
{
struct pending_request *request = user_data;
GMarkupParseContext *ctxt;
DBusMessage *reply;
DBusMessageIter iter, array;
char *contents;
size_t size;
int perr;
if (err != NULL) {
reply = g_dbus_create_error(request->msg,
ERROR_INTERFACE ".Failed",
"%s", err->message);
goto done;
}
perr = obc_transfer_get_contents(transfer, &contents, &size);
if (perr < 0) {
reply = g_dbus_create_error(request->msg,
ERROR_INTERFACE ".Failed",
"Error reading contents: %s",
strerror(-perr));
goto done;
}
reply = dbus_message_new_method_return(request->msg);
if (reply == NULL)
return;
dbus_message_iter_init_append(reply, &iter);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
DBUS_TYPE_ARRAY_AS_STRING
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &array);
ctxt = g_markup_parse_context_new(&folder_parser, 0, &array, NULL);
g_markup_parse_context_parse(ctxt, contents, size, NULL);
g_markup_parse_context_free(ctxt);
dbus_message_iter_close_container(&iter, &array);
g_free(contents);
done:
g_dbus_send_message(conn, reply);
pending_request_free(request);
}
static DBusMessage *get_folder_listing(struct map_data *map,
DBusMessage *message,
GObexApparam *apparam)
{
struct pending_request *request;
struct obc_transfer *transfer;
GError *err = NULL;
DBusMessage *reply;
transfer = obc_transfer_get("x-obex/folder-listing", NULL, NULL, &err);
if (transfer == NULL) {
g_obex_apparam_free(apparam);
goto fail;
}
obc_transfer_set_apparam(transfer, apparam);
request = pending_request_new(map, message);
if (!obc_session_queue(map->session, transfer, folder_listing_cb,
request, &err)) {
pending_request_free(request);
goto fail;
}
return NULL;
fail:
reply = g_dbus_create_error(message, ERROR_INTERFACE ".Failed", "%s",
err->message);
g_error_free(err);
return reply;
}
static GObexApparam *parse_offset(GObexApparam *apparam, DBusMessageIter *iter)
{
guint16 num;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_UINT16)
return NULL;
dbus_message_iter_get_basic(iter, &num);
return g_obex_apparam_set_uint16(apparam, MAP_AP_STARTOFFSET, num);
}
static GObexApparam *parse_max_count(GObexApparam *apparam,
DBusMessageIter *iter)
{
guint16 num;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_UINT16)
return NULL;
dbus_message_iter_get_basic(iter, &num);
return g_obex_apparam_set_uint16(apparam, MAP_AP_MAXLISTCOUNT, num);
}
static GObexApparam *parse_folder_filters(GObexApparam *apparam,
DBusMessageIter *iter)
{
DBusMessageIter array;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
return NULL;
dbus_message_iter_recurse(iter, &array);
while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_DICT_ENTRY) {
const char *key;
DBusMessageIter value, entry;
dbus_message_iter_recurse(&array, &entry);
dbus_message_iter_get_basic(&entry, &key);
dbus_message_iter_next(&entry);
dbus_message_iter_recurse(&entry, &value);
if (strcasecmp(key, "Offset") == 0) {
if (parse_offset(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "MaxCount") == 0) {
if (parse_max_count(apparam, &value) == NULL)
return NULL;
}
dbus_message_iter_next(&array);
}
return apparam;
}
static DBusMessage *map_list_folders(DBusConnection *connection,
DBusMessage *message, void *user_data)
{
struct map_data *map = user_data;
GObexApparam *apparam;
DBusMessageIter args;
dbus_message_iter_init(message, &args);
apparam = g_obex_apparam_set_uint16(NULL, MAP_AP_MAXLISTCOUNT,
DEFAULT_COUNT);
apparam = g_obex_apparam_set_uint16(apparam, MAP_AP_STARTOFFSET,
DEFAULT_OFFSET);
if (parse_folder_filters(apparam, &args) == NULL) {
g_obex_apparam_free(apparam);
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments", NULL);
}
return get_folder_listing(map, message, apparam);
}
static void map_msg_free(void *data)
{
struct map_msg *msg = data;
g_free(msg->path);
g_free(msg->subject);
g_free(msg->folder);
g_free(msg->timestamp);
g_free(msg->sender);
g_free(msg->sender_address);
g_free(msg->replyto);
g_free(msg->recipient);
g_free(msg->recipient_address);
g_free(msg->type);
g_free(msg->status);
g_free(msg);
}
static DBusMessage *map_msg_get(DBusConnection *connection,
DBusMessage *message, void *user_data)
{
struct map_msg *msg = user_data;
struct obc_transfer *transfer;
const char *target_file;
gboolean attachment;
GError *err = NULL;
DBusMessage *reply;
GObexApparam *apparam;
char handle[17];
if (dbus_message_get_args(message, NULL,
DBUS_TYPE_STRING, &target_file,
DBUS_TYPE_BOOLEAN, &attachment,
DBUS_TYPE_INVALID) == FALSE)
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments", NULL);
if (snprintf(handle, sizeof(handle), "%" PRIx64, msg->handle) < 0)
goto fail;
transfer = obc_transfer_get("x-bt/message", handle, target_file, &err);
if (transfer == NULL)
goto fail;
apparam = g_obex_apparam_set_uint8(NULL, MAP_AP_ATTACHMENT,
attachment);
apparam = g_obex_apparam_set_uint8(apparam, MAP_AP_CHARSET,
CHARSET_UTF8);
obc_transfer_set_apparam(transfer, apparam);
if (!obc_session_queue(msg->data->session, transfer, NULL, NULL, &err))
goto fail;
return obc_transfer_create_dbus_reply(transfer, message);
fail:
reply = g_dbus_create_error(message, ERROR_INTERFACE ".Failed", "%s",
err->message);
g_error_free(err);
return reply;
}
static void set_message_status_cb(struct obc_session *session,
struct obc_transfer *transfer,
GError *err, void *user_data)
{
struct map_msg *msg = user_data;
if (err != NULL) {
g_dbus_pending_property_error(msg->pending,
ERROR_INTERFACE ".Failed",
"%s", err->message);
goto done;
}
g_dbus_pending_property_success(msg->pending);
done:
msg->pending = 0;
}
static gboolean get_folder(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->folder);
return TRUE;
}
static gboolean subject_exists(const GDBusPropertyTable *property, void *data)
{
struct map_msg *msg = data;
return msg->subject != NULL;
}
static gboolean get_subject(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->subject);
return TRUE;
}
static gboolean timestamp_exists(const GDBusPropertyTable *property, void *data)
{
struct map_msg *msg = data;
return msg->timestamp != NULL;
}
static gboolean get_timestamp(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->timestamp);
return TRUE;
}
static gboolean sender_exists(const GDBusPropertyTable *property, void *data)
{
struct map_msg *msg = data;
return msg->sender != NULL;
}
static gboolean get_sender(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->sender);
return TRUE;
}
static gboolean sender_address_exists(const GDBusPropertyTable *property,
void *data)
{
struct map_msg *msg = data;
return msg->sender_address != NULL;
}
static gboolean get_sender_address(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING,
&msg->sender_address);
return TRUE;
}
static gboolean replyto_exists(const GDBusPropertyTable *property, void *data)
{
struct map_msg *msg = data;
return msg->replyto != NULL;
}
static gboolean get_replyto(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->replyto);
return TRUE;
}
static gboolean recipient_exists(const GDBusPropertyTable *property, void *data)
{
struct map_msg *msg = data;
return msg->recipient != NULL;
}
static gboolean get_recipient(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->recipient);
return TRUE;
}
static gboolean recipient_address_exists(const GDBusPropertyTable *property,
void *data)
{
struct map_msg *msg = data;
return msg->recipient_address != NULL;
}
static gboolean get_recipient_address(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING,
&msg->recipient_address);
return TRUE;
}
static gboolean type_exists(const GDBusPropertyTable *property, void *data)
{
struct map_msg *msg = data;
return msg->type != NULL;
}
static gboolean get_type(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->type);
return TRUE;
}
static gboolean get_size(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT64, &msg->size);
return TRUE;
}
static gboolean reception_status_exists(const GDBusPropertyTable *property,
void *data)
{
struct map_msg *msg = data;
return msg->status != NULL;
}
static gboolean get_reception_status(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &msg->status);
return TRUE;
}
static gboolean get_attachment_size(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct map_msg *msg = data;
dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT64,
&msg->attachment_size);
return TRUE;
}
static gboolean get_flag(const GDBusPropertyTable *property,
DBusMessageIter *iter, uint8_t flag,
void *data)
{
struct map_msg *msg = data;
dbus_bool_t value = (msg->flags & flag) != 0;
dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &value);
return TRUE;
}
static gboolean get_priority(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
return get_flag(property, iter, MAP_MSG_FLAG_PRIORITY, data);
}
static gboolean get_read(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
return get_flag(property, iter, MAP_MSG_FLAG_READ, data);
}
static gboolean get_sent(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
return get_flag(property, iter, MAP_MSG_FLAG_SENT, data);
}
static gboolean get_protected(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
return get_flag(property, iter, MAP_MSG_FLAG_PROTECTED, data);
}
static gboolean get_text(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
return get_flag(property, iter, MAP_MSG_FLAG_TEXT, data);
}
static void set_status(const GDBusPropertyTable *property,
DBusMessageIter *iter, GDBusPendingPropertySet id,
uint8_t status, void *data)
{
struct map_msg *msg = data;
struct obc_transfer *transfer;
gboolean value;
GError *err = NULL;
GObexApparam *apparam;
char contents[1];
char handle[17];
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_BOOLEAN) {
g_dbus_pending_property_error(id,
ERROR_INTERFACE ".InvalidArguments",
"Invalid arguments in method call");
return;
}
dbus_message_iter_get_basic(iter, &value);
contents[0] = FILLER_BYTE;
if (snprintf(handle, sizeof(handle), "%" PRIx64, msg->handle) < 0)
goto fail;
transfer = obc_transfer_put("x-bt/messageStatus", handle, NULL,
contents, sizeof(contents), &err);
if (transfer == NULL)
goto fail;
apparam = g_obex_apparam_set_uint8(NULL, MAP_AP_STATUSINDICATOR,
status);
apparam = g_obex_apparam_set_uint8(apparam, MAP_AP_STATUSVALUE,
value);
obc_transfer_set_apparam(transfer, apparam);
if (!obc_session_queue(msg->data->session, transfer,
set_message_status_cb, msg, &err))
goto fail;
msg->pending = id;
return;
fail:
g_dbus_pending_property_error(id, ERROR_INTERFACE ".Failed", "%s",
err->message);
g_error_free(err);
}
static void set_read(const GDBusPropertyTable *property,
DBusMessageIter *iter, GDBusPendingPropertySet id,
void *data)
{
set_status(property, iter, id, STATUS_READ, data);
}
static void set_deleted(const GDBusPropertyTable *property,
DBusMessageIter *iter, GDBusPendingPropertySet id,
void *data)
{
set_status(property, iter, id, STATUS_DELETE, data);
}
static const GDBusMethodTable map_msg_methods[] = {
{ GDBUS_METHOD("Get",
GDBUS_ARGS({ "targetfile", "s" },
{ "attachment", "b" }),
GDBUS_ARGS({ "transfer", "o" },
{ "properties", "a{sv}" }),
map_msg_get) },
{ }
};
static const GDBusPropertyTable map_msg_properties[] = {
{ "Folder", "s", get_folder },
{ "Subject", "s", get_subject, NULL, subject_exists },
{ "Timestamp", "s", get_timestamp, NULL, timestamp_exists },
{ "Sender", "s", get_sender, NULL, sender_exists },
{ "SenderAddress", "s", get_sender_address, NULL,
sender_address_exists },
{ "ReplyTo", "s", get_replyto, NULL, replyto_exists },
{ "Recipient", "s", get_recipient, NULL, recipient_exists },
{ "RecipientAddress", "s", get_recipient_address, NULL,
recipient_address_exists },
{ "Type", "s", get_type, NULL, type_exists },
{ "Size", "t", get_size },
{ "Text", "b", get_text },
{ "Status", "s", get_reception_status, NULL, reception_status_exists },
{ "AttachmentSize", "t", get_attachment_size },
{ "Priority", "b", get_priority },
{ "Read", "b", get_read, set_read },
{ "Sent", "b", get_sent },
{ "Protected", "b", get_protected },
{ "Deleted", "b", NULL, set_deleted },
{ }
};
static void parse_type(struct map_msg *msg, const char *value)
{
const char *type = NULL;
if (strcasecmp(value, "SMS_GSM") == 0)
type = "sms-gsm";
else if (strcasecmp(value, "SMS_CDMA") == 0)
type = "sms-cdma";
else if (strcasecmp(value, "EMAIL") == 0)
type = "email";
else if (strcasecmp(value, "MMS") == 0)
type = "mms";
if (g_strcmp0(msg->type, type) == 0)
return;
g_free(msg->type);
msg->type = g_strdup(type);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Type");
}
static struct map_msg *map_msg_create(struct map_data *data, uint64_t handle,
const char *folder, const char *type)
{
struct map_msg *msg;
msg = g_new0(struct map_msg, 1);
msg->data = data;
msg->handle = handle;
msg->path = g_strdup_printf("%s/message%" PRIu64,
obc_session_get_path(data->session),
msg->handle);
msg->folder = g_strdup(folder);
if (!g_dbus_register_interface(conn, msg->path, MAP_MSG_INTERFACE,
map_msg_methods, NULL,
map_msg_properties,
msg, map_msg_free)) {
map_msg_free(msg);
return NULL;
}
g_hash_table_insert(data->messages, &msg->handle, msg);
if (type)
parse_type(msg, type);
return msg;
}
static void parse_subject(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->subject, value) == 0)
return;
g_free(msg->subject);
msg->subject = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Subject");
}
static void parse_datetime(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->timestamp, value) == 0)
return;
g_free(msg->timestamp);
msg->timestamp = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Timestamp");
}
static void parse_sender(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->sender, value) == 0)
return;
g_free(msg->sender);
msg->sender = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Sender");
}
static void parse_sender_address(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->sender_address, value) == 0)
return;
g_free(msg->sender_address);
msg->sender_address = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "SenderAddress");
}
static void parse_replyto(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->replyto, value) == 0)
return;
g_free(msg->replyto);
msg->replyto = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "ReplyTo");
}
static void parse_recipient(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->recipient, value) == 0)
return;
g_free(msg->recipient);
msg->recipient = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Recipient");
}
static void parse_recipient_address(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->recipient_address, value) == 0)
return;
g_free(msg->recipient_address);
msg->recipient_address = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "RecipientAddress");
}
static void parse_size(struct map_msg *msg, const char *value)
{
uint64_t size = g_ascii_strtoll(value, NULL, 10);
if (msg->size == size)
return;
msg->size = size;
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Size");
}
static void parse_text(struct map_msg *msg, const char *value)
{
gboolean flag = strcasecmp(value, "no") != 0;
uint8_t oldflags = msg->flags;
if (flag)
msg->flags |= MAP_MSG_FLAG_TEXT;
else
msg->flags &= ~MAP_MSG_FLAG_TEXT;
if (msg->flags != oldflags)
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Text");
}
static void parse_status(struct map_msg *msg, const char *value)
{
if (g_strcmp0(msg->status, value) == 0)
return;
g_free(msg->status);
msg->status = g_strdup(value);
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Status");
}
static void parse_attachment_size(struct map_msg *msg, const char *value)
{
uint64_t attachment_size = g_ascii_strtoll(value, NULL, 10);
if (msg->attachment_size == attachment_size)
return;
msg->attachment_size = attachment_size;
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "AttachmentSize");
}
static void parse_priority(struct map_msg *msg, const char *value)
{
gboolean flag = strcasecmp(value, "no") != 0;
uint8_t oldflags = msg->flags;
if (flag)
msg->flags |= MAP_MSG_FLAG_PRIORITY;
else
msg->flags &= ~MAP_MSG_FLAG_PRIORITY;
if (msg->flags != oldflags)
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Priority");
}
static void parse_read(struct map_msg *msg, const char *value)
{
gboolean flag = strcasecmp(value, "no") != 0;
uint8_t oldflags = msg->flags;
if (flag)
msg->flags |= MAP_MSG_FLAG_READ;
else
msg->flags &= ~MAP_MSG_FLAG_READ;
if (msg->flags != oldflags)
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Read");
}
static void parse_sent(struct map_msg *msg, const char *value)
{
gboolean flag = strcasecmp(value, "no") != 0;
uint8_t oldflags = msg->flags;
if (flag)
msg->flags |= MAP_MSG_FLAG_SENT;
else
msg->flags &= ~MAP_MSG_FLAG_SENT;
if (msg->flags != oldflags)
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Sent");
}
static void parse_protected(struct map_msg *msg, const char *value)
{
gboolean flag = strcasecmp(value, "no") != 0;
uint8_t oldflags = msg->flags;
if (flag)
msg->flags |= MAP_MSG_FLAG_PROTECTED;
else
msg->flags &= ~MAP_MSG_FLAG_PROTECTED;
if (msg->flags != oldflags)
g_dbus_emit_property_changed(conn, msg->path,
MAP_MSG_INTERFACE, "Protected");
}
static struct map_msg_parser {
const char *name;
void (*func) (struct map_msg *msg, const char *value);
} msg_parsers[] = {
{ "subject", parse_subject },
{ "datetime", parse_datetime },
{ "sender_name", parse_sender },
{ "sender_addressing", parse_sender_address },
{ "replyto_addressing", parse_replyto },
{ "recipient_name", parse_recipient },
{ "recipient_addressing", parse_recipient_address },
{ "type", parse_type },
{ "size", parse_size },
{ "text", parse_text },
{ "reception_status", parse_status },
{ "attachment_size", parse_attachment_size },
{ "priority", parse_priority },
{ "read", parse_read },
{ "sent", parse_sent },
{ "protected", parse_protected },
{ }
};
static void msg_element(GMarkupParseContext *ctxt, const char *element,
const char **names, const char **values,
gpointer user_data, GError **gerr)
{
struct map_parser *parser = user_data;
struct map_data *data = parser->request->map;
DBusMessageIter entry, *iter = parser->iter;
struct map_msg *msg;
const char *key;
int i;
uint64_t handle;
if (strcasecmp("msg", element) != 0)
return;
for (i = 0, key = names[i]; key; key = names[++i]) {
if (strcasecmp(key, "handle") == 0)
break;
}
handle = strtoull(values[i], NULL, 16);
msg = g_hash_table_lookup(data->messages, &handle);
if (msg == NULL) {
msg = map_msg_create(data, handle, parser->request->folder,
NULL);
if (msg == NULL)
return;
}
dbus_message_iter_open_container(iter, DBUS_TYPE_DICT_ENTRY, NULL,
&entry);
dbus_message_iter_append_basic(&entry, DBUS_TYPE_OBJECT_PATH,
&msg->path);
for (i = 0, key = names[i]; key; key = names[++i]) {
struct map_msg_parser *parser;
for (parser = msg_parsers; parser && parser->name; parser++) {
if (strcasecmp(key, parser->name) == 0) {
parser->func(msg, values[i]);
break;
}
}
}
g_dbus_get_properties(conn, msg->path, MAP_MSG_INTERFACE, &entry);
dbus_message_iter_close_container(iter, &entry);
}
static const GMarkupParser msg_parser = {
msg_element,
NULL,
NULL,
NULL,
NULL
};
static void message_listing_cb(struct obc_session *session,
struct obc_transfer *transfer,
GError *err, void *user_data)
{
struct pending_request *request = user_data;
struct map_parser *parser;
GMarkupParseContext *ctxt;
DBusMessage *reply;
DBusMessageIter iter, array;
char *contents;
size_t size;
int perr;
if (err != NULL) {
reply = g_dbus_create_error(request->msg,
ERROR_INTERFACE ".Failed",
"%s", err->message);
goto done;
}
perr = obc_transfer_get_contents(transfer, &contents, &size);
if (perr < 0) {
reply = g_dbus_create_error(request->msg,
ERROR_INTERFACE ".Failed",
"Error reading contents: %s",
strerror(-perr));
goto done;
}
reply = dbus_message_new_method_return(request->msg);
if (reply == NULL)
return;
dbus_message_iter_init_append(reply, &iter);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_OBJECT_PATH_AS_STRING
DBUS_TYPE_ARRAY_AS_STRING
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING
DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
&array);
parser = g_new(struct map_parser, 1);
parser->request = request;
parser->iter = &array;
ctxt = g_markup_parse_context_new(&msg_parser, 0, parser, NULL);
g_markup_parse_context_parse(ctxt, contents, size, NULL);
g_markup_parse_context_free(ctxt);
dbus_message_iter_close_container(&iter, &array);
g_free(contents);
g_free(parser);
done:
g_dbus_send_message(conn, reply);
pending_request_free(request);
}
static char *get_absolute_folder(struct map_data *map, const char *subfolder)
{
const char *root = obc_session_get_folder(map->session);
if (!subfolder || strlen(subfolder) == 0)
return g_strdup(root);
else if (g_str_has_suffix(root, "/"))
return g_strconcat(root, subfolder, NULL);
else
return g_strconcat(root, "/", subfolder, NULL);
}
static DBusMessage *get_message_listing(struct map_data *map,
DBusMessage *message,
const char *folder,
GObexApparam *apparam)
{
struct pending_request *request;
struct obc_transfer *transfer;
GError *err = NULL;
DBusMessage *reply;
transfer = obc_transfer_get("x-bt/MAP-msg-listing", folder, NULL, &err);
if (transfer == NULL) {
g_obex_apparam_free(apparam);
goto fail;
}
obc_transfer_set_apparam(transfer, apparam);
request = pending_request_new(map, message);
request->folder = get_absolute_folder(map, folder);
if (!obc_session_queue(map->session, transfer, message_listing_cb,
request, &err)) {
pending_request_free(request);
goto fail;
}
return NULL;
fail:
reply = g_dbus_create_error(message, ERROR_INTERFACE ".Failed", "%s",
err->message);
g_error_free(err);
return reply;
}
static GObexApparam *parse_subject_length(GObexApparam *apparam,
DBusMessageIter *iter)
{
guint8 num;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_BYTE)
return NULL;
dbus_message_iter_get_basic(iter, &num);
return g_obex_apparam_set_uint8(apparam, MAP_AP_SUBJECTLENGTH, num);
}
static uint64_t get_filter_mask(const char *filterstr)
{
int i;
if (!filterstr)
return 0;
if (!g_ascii_strcasecmp(filterstr, "ALL"))
return FILTER_ALL;
for (i = 0; filter_list[i] != NULL; i++)
if (!g_ascii_strcasecmp(filterstr, filter_list[i]))
return 1ULL << i;
return 0;
}
static int set_field(guint32 *filter, const char *filterstr)
{
guint64 mask;
mask = get_filter_mask(filterstr);
if (mask == 0)
return -EINVAL;
*filter |= mask;
return 0;
}
static GObexApparam *parse_fields(GObexApparam *apparam, DBusMessageIter *iter)
{
DBusMessageIter array;
guint32 filter = 0;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
return NULL;
dbus_message_iter_recurse(iter, &array);
while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_STRING) {
const char *string;
dbus_message_iter_get_basic(&array, &string);
if (set_field(&filter, string) < 0)
return NULL;
dbus_message_iter_next(&array);
}
return g_obex_apparam_set_uint32(apparam, MAP_AP_PARAMETERMASK,
filter);
}
static GObexApparam *parse_filter_type(GObexApparam *apparam,
DBusMessageIter *iter)
{
DBusMessageIter array;
guint8 types = 0;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
return NULL;
dbus_message_iter_recurse(iter, &array);
while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_STRING) {
const char *string;
dbus_message_iter_get_basic(&array, &string);
if (!g_ascii_strcasecmp(string, "sms"))
types |= 0x03; /* sms-gsm and sms-cdma */
else if (!g_ascii_strcasecmp(string, "email"))
types |= 0x04; /* email */
else if (!g_ascii_strcasecmp(string, "mms"))
types |= 0x08; /* mms */
else
return NULL;
dbus_message_iter_next(&array);
}
return g_obex_apparam_set_uint8(apparam, MAP_AP_FILTERMESSAGETYPE,
types);
}
static GObexApparam *parse_period_begin(GObexApparam *apparam,
DBusMessageIter *iter)
{
const char *string;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING)
return NULL;
dbus_message_iter_get_basic(iter, &string);
return g_obex_apparam_set_string(apparam, MAP_AP_FILTERPERIODBEGIN,
string);
}
static GObexApparam *parse_period_end(GObexApparam *apparam,
DBusMessageIter *iter)
{
const char *string;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING)
return NULL;
dbus_message_iter_get_basic(iter, &string);
return g_obex_apparam_set_string(apparam, MAP_AP_FILTERPERIODEND,
string);
}
static GObexApparam *parse_filter_read(GObexApparam *apparam,
DBusMessageIter *iter)
{
guint8 status = FILTER_READ_STATUS_NONE;
dbus_bool_t dbus_status = FALSE;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_BOOLEAN)
return NULL;
dbus_message_iter_get_basic(iter, &dbus_status);
if (dbus_status)
status = FILTER_READ_STATUS_ONLY_READ;
else
status = FILTER_READ_STATUS_ONLY_UNREAD;
return g_obex_apparam_set_uint8(apparam, MAP_AP_FILTERREADSTATUS,
status);
}
static GObexApparam *parse_filter_recipient(GObexApparam *apparam,
DBusMessageIter *iter)
{
const char *string;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING)
return NULL;
dbus_message_iter_get_basic(iter, &string);
return g_obex_apparam_set_string(apparam, MAP_AP_FILTERRECIPIENT,
string);
}
static GObexApparam *parse_filter_sender(GObexApparam *apparam,
DBusMessageIter *iter)
{
const char *string;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING)
return NULL;
dbus_message_iter_get_basic(iter, &string);
return g_obex_apparam_set_string(apparam, MAP_AP_FILTERORIGINATOR,
string);
}
static GObexApparam *parse_filter_priority(GObexApparam *apparam,
DBusMessageIter *iter)
{
guint8 priority = FILTER_PRIORITY_NONE;
dbus_bool_t dbus_priority = FALSE;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_BOOLEAN)
return NULL;
dbus_message_iter_get_basic(iter, &dbus_priority);
if (dbus_priority)
priority = FILTER_PRIORITY_ONLY_HIGH;
else
priority = FILTER_PRIORITY_ONLY_NONHIGH;
return g_obex_apparam_set_uint8(apparam, MAP_AP_FILTERPRIORITY,
priority);
}
static GObexApparam *parse_message_filters(GObexApparam *apparam,
DBusMessageIter *iter)
{
DBusMessageIter array;
DBG("");
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
return NULL;
dbus_message_iter_recurse(iter, &array);
while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_DICT_ENTRY) {
const char *key;
DBusMessageIter value, entry;
dbus_message_iter_recurse(&array, &entry);
dbus_message_iter_get_basic(&entry, &key);
dbus_message_iter_next(&entry);
dbus_message_iter_recurse(&entry, &value);
if (strcasecmp(key, "Offset") == 0) {
if (parse_offset(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "MaxCount") == 0) {
if (parse_max_count(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "SubjectLength") == 0) {
if (parse_subject_length(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Fields") == 0) {
if (parse_fields(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Types") == 0) {
if (parse_filter_type(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "PeriodBegin") == 0) {
if (parse_period_begin(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "PeriodEnd") == 0) {
if (parse_period_end(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Read") == 0) {
if (parse_filter_read(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Recipient") == 0) {
if (parse_filter_recipient(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Sender") == 0) {
if (parse_filter_sender(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Priority") == 0) {
if (parse_filter_priority(apparam, &value) == NULL)
return NULL;
}
dbus_message_iter_next(&array);
}
return apparam;
}
static DBusMessage *map_list_messages(DBusConnection *connection,
DBusMessage *message, void *user_data)
{
struct map_data *map = user_data;
const char *folder;
GObexApparam *apparam;
DBusMessageIter args;
dbus_message_iter_init(message, &args);
if (dbus_message_iter_get_arg_type(&args) != DBUS_TYPE_STRING)
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments", NULL);
dbus_message_iter_get_basic(&args, &folder);
apparam = g_obex_apparam_set_uint16(NULL, MAP_AP_MAXLISTCOUNT,
DEFAULT_COUNT);
apparam = g_obex_apparam_set_uint16(apparam, MAP_AP_STARTOFFSET,
DEFAULT_OFFSET);
dbus_message_iter_next(&args);
if (parse_message_filters(apparam, &args) == NULL) {
g_obex_apparam_free(apparam);
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments", NULL);
}
return get_message_listing(map, message, folder, apparam);
}
static char **get_filter_strs(uint64_t filter, int *size)
{
char **list, **item;
int i;
list = g_malloc0(sizeof(char **) * (FILTER_BIT_MAX + 2));
item = list;
for (i = 0; filter_list[i] != NULL; i++)
if (filter & (1ULL << i))
*(item++) = g_strdup(filter_list[i]);
*item = NULL;
*size = item - list;
return list;
}
static DBusMessage *map_list_filter_fields(DBusConnection *connection,
DBusMessage *message, void *user_data)
{
char **filters = NULL;
int size;
DBusMessage *reply;
filters = get_filter_strs(FILTER_ALL, &size);
reply = dbus_message_new_method_return(message);
dbus_message_append_args(reply, DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING, &filters, size,
DBUS_TYPE_INVALID);
g_strfreev(filters);
return reply;
}
static void update_inbox_cb(struct obc_session *session,
struct obc_transfer *transfer,
GError *err, void *user_data)
{
struct pending_request *request = user_data;
DBusMessage *reply;
if (err != NULL) {
reply = g_dbus_create_error(request->msg,
ERROR_INTERFACE ".Failed",
"%s", err->message);
goto done;
}
reply = dbus_message_new_method_return(request->msg);
done:
g_dbus_send_message(conn, reply);
pending_request_free(request);
}
static DBusMessage *map_update_inbox(DBusConnection *connection,
DBusMessage *message, void *user_data)
{
struct map_data *map = user_data;
DBusMessage *reply;
char contents[1];
struct obc_transfer *transfer;
GError *err = NULL;
struct pending_request *request;
contents[0] = FILLER_BYTE;
transfer = obc_transfer_put("x-bt/MAP-messageUpdate", NULL, NULL,
contents, sizeof(contents),
&err);
if (transfer == NULL)
goto fail;
request = pending_request_new(map, message);
if (!obc_session_queue(map->session, transfer, update_inbox_cb,
request, &err)) {
pending_request_free(request);
goto fail;
}
return NULL;
fail:
reply = g_dbus_create_error(message, ERROR_INTERFACE ".Failed", "%s",
err->message);
g_error_free(err);
return reply;
}
static DBusMessage *push_message(struct map_data *map,
DBusMessage *message,
const char *filename,
const char *folder,
GObexApparam *apparam)
{
struct obc_transfer *transfer;
GError *err = NULL;
DBusMessage *reply;
transfer = obc_transfer_put("x-bt/message", folder, filename,
NULL, 0, &err);
if (transfer == NULL) {
g_obex_apparam_free(apparam);
goto fail;
}
obc_transfer_set_apparam(transfer, apparam);
if (!obc_session_queue(map->session, transfer, NULL, NULL, &err))
goto fail;
return obc_transfer_create_dbus_reply(transfer, message);
fail:
reply = g_dbus_create_error(message, ERROR_INTERFACE ".Failed", "%s",
err->message);
g_error_free(err);
return reply;
}
static GObexApparam *parse_transparent(GObexApparam *apparam,
DBusMessageIter *iter)
{
dbus_bool_t transparent;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_BOOLEAN)
return NULL;
dbus_message_iter_get_basic(iter, &transparent);
return g_obex_apparam_set_uint8(apparam, MAP_AP_TRANSPARENT,
transparent ? TRUE : FALSE);
}
static GObexApparam *parse_retry(GObexApparam *apparam, DBusMessageIter *iter)
{
dbus_bool_t retry;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_BOOLEAN)
return NULL;
dbus_message_iter_get_basic(iter, &retry);
return g_obex_apparam_set_uint8(apparam, MAP_AP_RETRY,
retry ? TRUE : FALSE);
}
static GObexApparam *parse_charset(GObexApparam *apparam, DBusMessageIter *iter)
{
guint8 charset = 0;
const char *string;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING)
return NULL;
dbus_message_iter_get_basic(iter, &string);
if (strcasecmp(string, "native") == 0)
charset = CHARSET_NATIVE;
else if (strcasecmp(string, "utf8") == 0)
charset = CHARSET_UTF8;
else
return NULL;
return g_obex_apparam_set_uint8(apparam, MAP_AP_CHARSET, charset);
}
static GObexApparam *parse_push_options(GObexApparam *apparam,
DBusMessageIter *iter)
{
DBusMessageIter array;
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
return NULL;
dbus_message_iter_recurse(iter, &array);
while (dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_DICT_ENTRY) {
const char *key;
DBusMessageIter value, entry;
dbus_message_iter_recurse(&array, &entry);
dbus_message_iter_get_basic(&entry, &key);
dbus_message_iter_next(&entry);
dbus_message_iter_recurse(&entry, &value);
if (strcasecmp(key, "Transparent") == 0) {
if (parse_transparent(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Retry") == 0) {
if (parse_retry(apparam, &value) == NULL)
return NULL;
} else if (strcasecmp(key, "Charset") == 0) {
if (parse_charset(apparam, &value) == NULL)
return NULL;
}
dbus_message_iter_next(&array);
}
return apparam;
}
static DBusMessage *map_push_message(DBusConnection *connection,
DBusMessage *message, void *user_data)
{
struct map_data *map = user_data;
char *filename;
char *folder;
GObexApparam *apparam;
DBusMessageIter args;
dbus_message_iter_init(message, &args);
if (dbus_message_iter_get_arg_type(&args) != DBUS_TYPE_STRING)
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments", NULL);
dbus_message_iter_get_basic(&args, &filename);
dbus_message_iter_next(&args);
if (dbus_message_iter_get_arg_type(&args) != DBUS_TYPE_STRING) {
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments", NULL);
}
dbus_message_iter_get_basic(&args, &folder);
dbus_message_iter_next(&args);
apparam = g_obex_apparam_set_uint8(NULL, MAP_AP_CHARSET, CHARSET_UTF8);
if (parse_push_options(apparam, &args) == NULL) {
g_obex_apparam_free(apparam);
return g_dbus_create_error(message,
ERROR_INTERFACE ".InvalidArguments", NULL);
}
return push_message(map, message, filename, folder, apparam);
}
static const GDBusMethodTable map_methods[] = {
{ GDBUS_ASYNC_METHOD("SetFolder",
GDBUS_ARGS({ "name", "s" }), NULL,
map_setpath) },
{ GDBUS_ASYNC_METHOD("ListFolders",
GDBUS_ARGS({ "filters", "a{sv}" }),
GDBUS_ARGS({ "content", "aa{sv}" }),
map_list_folders) },
{ GDBUS_ASYNC_METHOD("ListMessages",
GDBUS_ARGS({ "folder", "s" }, { "filter", "a{sv}" }),
GDBUS_ARGS({ "messages", "a{oa{sv}}" }),
map_list_messages) },
{ GDBUS_METHOD("ListFilterFields",
NULL,
GDBUS_ARGS({ "fields", "as" }),
map_list_filter_fields) },
{ GDBUS_ASYNC_METHOD("UpdateInbox",
NULL,
NULL,
map_update_inbox) },
{ GDBUS_ASYNC_METHOD("PushMessage",
GDBUS_ARGS({ "file", "s" }, { "folder", "s" },
{ "args", "a{sv}" }),
GDBUS_ARGS({ "transfer", "o" },
{ "properties", "a{sv}" }),
map_push_message) },
{ }
};
static void map_msg_remove(void *data)
{
struct map_msg *msg = data;
char *path;
path = msg->path;
msg->path = NULL;
g_dbus_unregister_interface(conn, path, MAP_MSG_INTERFACE);
g_free(path);
}
static void map_handle_new_message(struct map_data *map,
struct map_event *event)
{
struct map_msg *msg;
msg = g_hash_table_lookup(map->messages, &event->handle);
/* New message event can be used if a new message replaces an old one */
if (msg)
g_hash_table_remove(map->messages, &event->handle);
map_msg_create(map, event->handle, event->folder, event->msg_type);
}
static void map_handle_status_changed(struct map_data *map,
struct map_event *event,
const char *status)
{
struct map_msg *msg;
msg = g_hash_table_lookup(map->messages, &event->handle);
if (msg == NULL)
return;
if (g_strcmp0(msg->status, status) == 0)
return;
g_free(msg->status);
msg->status = g_strdup(status);
g_dbus_emit_property_changed(conn, msg->path, MAP_MSG_INTERFACE,
"Status");
}
static void map_handle_folder_changed(struct map_data *map,
struct map_event *event,
const char *folder)
{
struct map_msg *msg;
if (!folder)
return;
msg = g_hash_table_lookup(map->messages, &event->handle);
if (!msg)
return;
if (g_strcmp0(msg->folder, folder) == 0)
return;
g_free(msg->folder);
msg->folder = g_strdup(folder);
g_dbus_emit_property_changed(conn, msg->path, MAP_MSG_INTERFACE,
"Folder");
}
static void map_handle_notification(struct map_event *event, void *user_data)
{
struct map_data *map = user_data;
DBG("Event report for %s:%d", obc_session_get_destination(map->session),
map->mas_instance_id);
DBG("type=%x handle=%" PRIx64 " folder=%s old_folder=%s msg_type=%s",
event->type, event->handle, event->folder, event->old_folder,
event->msg_type);
switch (event->type) {
case MAP_ET_NEW_MESSAGE:
map_handle_new_message(map, event);
break;
case MAP_ET_DELIVERY_SUCCESS:
map_handle_status_changed(map, event, "delivery-success");
break;
case MAP_ET_SENDING_SUCCESS:
map_handle_status_changed(map, event, "sending-success");
break;
case MAP_ET_DELIVERY_FAILURE:
map_handle_status_changed(map, event, "delivery-failure");
break;
case MAP_ET_SENDING_FAILURE:
map_handle_status_changed(map, event, "sending-failure");
break;
case MAP_ET_MESSAGE_DELETED:
map_handle_folder_changed(map, event, "/telecom/msg/deleted");
break;
case MAP_ET_MESSAGE_SHIFT:
map_handle_folder_changed(map, event, event->folder);
break;
default:
break;
}
}
static bool set_notification_registration(struct map_data *map, bool status)
{
struct obc_transfer *transfer;
GError *err = NULL;
GObexApparam *apparam;
char contents[1];
const char *address;
address = obc_session_get_destination(map->session);
if (!address || map->mas_instance_id < 0)
return FALSE;
if (status) {
map_register_event_handler(map->session, map->mas_instance_id,
&map_handle_notification, map);
} else {
map_unregister_event_handler(map->session,
map->mas_instance_id);
}
contents[0] = FILLER_BYTE;
transfer = obc_transfer_put("x-bt/MAP-NotificationRegistration", NULL,
NULL, contents, sizeof(contents), &err);
if (transfer == NULL)
return false;
apparam = g_obex_apparam_set_uint8(NULL, MAP_AP_NOTIFICATIONSTATUS,
status);
obc_transfer_set_apparam(transfer, apparam);
if (obc_session_queue(map->session, transfer, NULL, map, &err))
return true;
return false;
}
static void map_free(void *data)
{
struct map_data *map = data;
set_notification_registration(map, false);
obc_session_unref(map->session);
g_hash_table_unref(map->messages);
g_free(map);
}
static void parse_service_record(struct map_data *map)
{
const void *data;
/* MAS instance id */
map->mas_instance_id = -1;
data = obc_session_get_attribute(map->session,
SDP_ATTR_MAS_INSTANCE_ID);
if (data != NULL)
map->mas_instance_id = *(uint8_t *)data;
else
DBG("Failed to read MAS instance id");
/* Supported Message Types */
data = obc_session_get_attribute(map->session,
SDP_ATTR_SUPPORTED_MESSAGE_TYPES);
if (data != NULL)
map->supported_message_types = *(uint8_t *)data;
else
DBG("Failed to read supported message types");
}
static int map_probe(struct obc_session *session)
{
struct map_data *map;
const char *path;
path = obc_session_get_path(session);
map = g_try_new0(struct map_data, 1);
if (!map)
return -ENOMEM;
map->session = obc_session_ref(session);
map->messages = g_hash_table_new_full(g_int64_hash, g_int64_equal, NULL,
map_msg_remove);
parse_service_record(map);
DBG("%s, instance id %d", path, map->mas_instance_id);
set_notification_registration(map, true);
if (!g_dbus_register_interface(conn, path, MAP_INTERFACE, map_methods,
NULL, NULL, map, map_free)) {
map_free(map);
return -ENOMEM;
}
return 0;
}
static void map_remove(struct obc_session *session)
{
const char *path = obc_session_get_path(session);
DBG("%s", path);
g_dbus_unregister_interface(conn, path, MAP_INTERFACE);
}
static struct obc_driver map = {
.service = "MAP",
.uuid = MAS_UUID,
.target = OBEX_MAS_UUID,
.target_len = OBEX_MAS_UUID_LEN,
.probe = map_probe,
.remove = map_remove
};
int map_init(void)
{
int err;
DBG("");
conn = dbus_bus_get(DBUS_BUS_SESSION, NULL);
if (!conn)
return -EIO;
err = obc_driver_register(&map);
if (err < 0) {
dbus_connection_unref(conn);
conn = NULL;
return err;
}
return 0;
}
void map_exit(void)
{
DBG("");
dbus_connection_unref(conn);
conn = NULL;
obc_driver_unregister(&map);
}
| gpl-2.0 |
NewSTE/android_kernel_sony_u8500 | drivers/char/tty_io.c | 12 | 79681 | /*
* linux/drivers/char/tty_io.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* 'tty_io.c' gives an orthogonal feeling to tty's, be they consoles
* or rs-channels. It also implements echoing, cooked mode etc.
*
* Kill-line thanks to John T Kohl, who also corrected VMIN = VTIME = 0.
*
* Modified by Theodore Ts'o, 9/14/92, to dynamically allocate the
* tty_struct and tty_queue structures. Previously there was an array
* of 256 tty_struct's which was statically allocated, and the
* tty_queue structures were allocated at boot time. Both are now
* dynamically allocated only when the tty is open.
*
* Also restructured routines so that there is more of a separation
* between the high-level tty routines (tty_io.c and tty_ioctl.c) and
* the low-level tty routines (serial.c, pty.c, console.c). This
* makes for cleaner and more compact code. -TYT, 9/17/92
*
* Modified by Fred N. van Kempen, 01/29/93, to add line disciplines
* which can be dynamically activated and de-activated by the line
* discipline handling modules (like SLIP).
*
* NOTE: pay no attention to the line discipline code (yet); its
* interface is still subject to change in this version...
* -- TYT, 1/31/92
*
* Added functionality to the OPOST tty handling. No delays, but all
* other bits should be there.
* -- Nick Holloway <alfie@dcs.warwick.ac.uk>, 27th May 1993.
*
* Rewrote canonical mode and added more termios flags.
* -- julian@uhunix.uhcc.hawaii.edu (J. Cowley), 13Jan94
*
* Reorganized FASYNC support so mouse code can share it.
* -- ctm@ardi.com, 9Sep95
*
* New TIOCLINUX variants added.
* -- mj@k332.feld.cvut.cz, 19-Nov-95
*
* Restrict vt switching via ioctl()
* -- grif@cs.ucr.edu, 5-Dec-95
*
* Move console and virtual terminal code to more appropriate files,
* implement CONFIG_VT and generalize console device interface.
* -- Marko Kohtala <Marko.Kohtala@hut.fi>, March 97
*
* Rewrote tty_init_dev and tty_release_dev to eliminate races.
* -- Bill Hawes <whawes@star.net>, June 97
*
* Added devfs support.
* -- C. Scott Ananian <cananian@alumni.princeton.edu>, 13-Jan-1998
*
* Added support for a Unix98-style ptmx device.
* -- C. Scott Ananian <cananian@alumni.princeton.edu>, 14-Jan-1998
*
* Reduced memory usage for older ARM systems
* -- Russell King <rmk@arm.linux.org.uk>
*
* Move do_SAK() into process context. Less stack use in devfs functions.
* alloc_tty_struct() always uses kmalloc()
* -- Andrew Morton <andrewm@uow.edu.eu> 17Mar01
*/
#include <linux/types.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/devpts_fs.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/console.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/kd.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/smp_lock.h>
#include <linux/device.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <asm/system.h>
#include <linux/kbd_kern.h>
#include <linux/vt_kern.h>
#include <linux/selection.h>
#include <linux/kmod.h>
#include <linux/nsproxy.h>
#undef TTY_DEBUG_HANGUP
#define TTY_PARANOIA_CHECK 1
#define CHECK_TTY_COUNT 1
struct ktermios tty_std_termios = { /* for the benefit of tty drivers */
.c_iflag = ICRNL | IXON,
.c_oflag = OPOST | ONLCR,
.c_cflag = B38400 | CS8 | CREAD | HUPCL,
.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |
ECHOCTL | ECHOKE | IEXTEN,
.c_cc = INIT_C_CC,
.c_ispeed = 38400,
.c_ospeed = 38400
};
EXPORT_SYMBOL(tty_std_termios);
/* This list gets poked at by procfs and various bits of boot up code. This
could do with some rationalisation such as pulling the tty proc function
into this file */
LIST_HEAD(tty_drivers); /* linked list of tty drivers */
/* Mutex to protect creating and releasing a tty. This is shared with
vt.c for deeply disgusting hack reasons */
DEFINE_MUTEX(tty_mutex);
EXPORT_SYMBOL(tty_mutex);
static ssize_t tty_read(struct file *, char __user *, size_t, loff_t *);
static ssize_t tty_write(struct file *, const char __user *, size_t, loff_t *);
ssize_t redirected_tty_write(struct file *, const char __user *,
size_t, loff_t *);
static unsigned int tty_poll(struct file *, poll_table *);
static int tty_open(struct inode *, struct file *);
long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
#ifdef CONFIG_COMPAT
static long tty_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg);
#else
#define tty_compat_ioctl NULL
#endif
static int tty_fasync(int fd, struct file *filp, int on);
static void release_tty(struct tty_struct *tty, int idx);
static void __proc_set_tty(struct task_struct *tsk, struct tty_struct *tty);
static void proc_set_tty(struct task_struct *tsk, struct tty_struct *tty);
/**
* alloc_tty_struct - allocate a tty object
*
* Return a new empty tty structure. The data fields have not
* been initialized in any way but has been zeroed
*
* Locking: none
*/
struct tty_struct *alloc_tty_struct(void)
{
return kzalloc(sizeof(struct tty_struct), GFP_KERNEL);
}
/**
* free_tty_struct - free a disused tty
* @tty: tty struct to free
*
* Free the write buffers, tty queue and tty memory itself.
*
* Locking: none. Must be called after tty is definitely unused
*/
void free_tty_struct(struct tty_struct *tty)
{
kfree(tty->write_buf);
tty_buffer_free_all(tty);
kfree(tty);
}
#define TTY_NUMBER(tty) ((tty)->index + (tty)->driver->name_base)
/**
* tty_name - return tty naming
* @tty: tty structure
* @buf: buffer for output
*
* Convert a tty structure into a name. The name reflects the kernel
* naming policy and if udev is in use may not reflect user space
*
* Locking: none
*/
char *tty_name(struct tty_struct *tty, char *buf)
{
if (!tty) /* Hmm. NULL pointer. That's fun. */
strcpy(buf, "NULL tty");
else
strcpy(buf, tty->name);
return buf;
}
EXPORT_SYMBOL(tty_name);
int tty_paranoia_check(struct tty_struct *tty, struct inode *inode,
const char *routine)
{
#ifdef TTY_PARANOIA_CHECK
if (!tty) {
printk(KERN_WARNING
"null TTY for (%d:%d) in %s\n",
imajor(inode), iminor(inode), routine);
return 1;
}
if (tty->magic != TTY_MAGIC) {
printk(KERN_WARNING
"bad magic number for tty struct (%d:%d) in %s\n",
imajor(inode), iminor(inode), routine);
return 1;
}
#endif
return 0;
}
static int check_tty_count(struct tty_struct *tty, const char *routine)
{
#ifdef CHECK_TTY_COUNT
struct list_head *p;
int count = 0;
file_list_lock();
list_for_each(p, &tty->tty_files) {
count++;
}
file_list_unlock();
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_SLAVE &&
tty->link && tty->link->count)
count++;
if (tty->count != count) {
printk(KERN_WARNING "Warning: dev (%s) tty->count(%d) "
"!= #fd's(%d) in %s\n",
tty->name, tty->count, count, routine);
return count;
}
#endif
return 0;
}
/**
* get_tty_driver - find device of a tty
* @dev_t: device identifier
* @index: returns the index of the tty
*
* This routine returns a tty driver structure, given a device number
* and also passes back the index number.
*
* Locking: caller must hold tty_mutex
*/
static struct tty_driver *get_tty_driver(dev_t device, int *index)
{
struct tty_driver *p;
list_for_each_entry(p, &tty_drivers, tty_drivers) {
dev_t base = MKDEV(p->major, p->minor_start);
if (device < base || device >= base + p->num)
continue;
*index = device - base;
return tty_driver_kref_get(p);
}
return NULL;
}
#ifdef CONFIG_CONSOLE_POLL
/**
* tty_find_polling_driver - find device of a polled tty
* @name: name string to match
* @line: pointer to resulting tty line nr
*
* This routine returns a tty driver structure, given a name
* and the condition that the tty driver is capable of polled
* operation.
*/
struct tty_driver *tty_find_polling_driver(char *name, int *line)
{
struct tty_driver *p, *res = NULL;
int tty_line = 0;
int len;
char *str, *stp;
for (str = name; *str; str++)
if ((*str >= '0' && *str <= '9') || *str == ',')
break;
if (!*str)
return NULL;
len = str - name;
tty_line = simple_strtoul(str, &str, 10);
mutex_lock(&tty_mutex);
/* Search through the tty devices to look for a match */
list_for_each_entry(p, &tty_drivers, tty_drivers) {
if (strncmp(name, p->name, len) != 0)
continue;
stp = str;
if (*stp == ',')
stp++;
if (*stp == '\0')
stp = NULL;
if (tty_line >= 0 && tty_line <= p->num && p->ops &&
p->ops->poll_init && !p->ops->poll_init(p, tty_line, stp)) {
res = tty_driver_kref_get(p);
*line = tty_line;
break;
}
}
mutex_unlock(&tty_mutex);
return res;
}
EXPORT_SYMBOL_GPL(tty_find_polling_driver);
#endif
/**
* tty_check_change - check for POSIX terminal changes
* @tty: tty to check
*
* If we try to write to, or set the state of, a terminal and we're
* not in the foreground, send a SIGTTOU. If the signal is blocked or
* ignored, go ahead and perform the operation. (POSIX 7.2)
*
* Locking: ctrl_lock
*/
int tty_check_change(struct tty_struct *tty)
{
unsigned long flags;
int ret = 0;
if (current->signal->tty != tty)
return 0;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (!tty->pgrp) {
printk(KERN_WARNING "tty_check_change: tty->pgrp == NULL!\n");
goto out_unlock;
}
if (task_pgrp(current) == tty->pgrp)
goto out_unlock;
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
if (is_ignored(SIGTTOU))
goto out;
if (is_current_pgrp_orphaned()) {
ret = -EIO;
goto out;
}
kill_pgrp(task_pgrp(current), SIGTTOU, 1);
set_thread_flag(TIF_SIGPENDING);
ret = -ERESTARTSYS;
out:
return ret;
out_unlock:
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
return ret;
}
EXPORT_SYMBOL(tty_check_change);
static ssize_t hung_up_tty_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return 0;
}
static ssize_t hung_up_tty_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return -EIO;
}
/* No kernel lock held - none needed ;) */
static unsigned int hung_up_tty_poll(struct file *filp, poll_table *wait)
{
return POLLIN | POLLOUT | POLLERR | POLLHUP | POLLRDNORM | POLLWRNORM;
}
static long hung_up_tty_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
}
static long hung_up_tty_compat_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
}
static const struct file_operations tty_fops = {
.llseek = no_llseek,
.read = tty_read,
.write = tty_write,
.poll = tty_poll,
.unlocked_ioctl = tty_ioctl,
.compat_ioctl = tty_compat_ioctl,
.open = tty_open,
.release = tty_release,
.fasync = tty_fasync,
};
static const struct file_operations console_fops = {
.llseek = no_llseek,
.read = tty_read,
.write = redirected_tty_write,
.poll = tty_poll,
.unlocked_ioctl = tty_ioctl,
.compat_ioctl = tty_compat_ioctl,
.open = tty_open,
.release = tty_release,
.fasync = tty_fasync,
};
static const struct file_operations hung_up_tty_fops = {
.llseek = no_llseek,
.read = hung_up_tty_read,
.write = hung_up_tty_write,
.poll = hung_up_tty_poll,
.unlocked_ioctl = hung_up_tty_ioctl,
.compat_ioctl = hung_up_tty_compat_ioctl,
.release = tty_release,
};
static DEFINE_SPINLOCK(redirect_lock);
static struct file *redirect;
/**
* tty_wakeup - request more data
* @tty: terminal
*
* Internal and external helper for wakeups of tty. This function
* informs the line discipline if present that the driver is ready
* to receive more output data.
*/
void tty_wakeup(struct tty_struct *tty)
{
struct tty_ldisc *ld;
if (test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) {
ld = tty_ldisc_ref(tty);
if (ld) {
if (ld->ops->write_wakeup)
ld->ops->write_wakeup(tty);
tty_ldisc_deref(ld);
}
}
wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
}
EXPORT_SYMBOL_GPL(tty_wakeup);
/**
* do_tty_hangup - actual handler for hangup events
* @work: tty device
*
* This can be called by the "eventd" kernel thread. That is process
* synchronous but doesn't hold any locks, so we need to make sure we
* have the appropriate locks for what we're doing.
*
* The hangup event clears any pending redirections onto the hung up
* device. It ensures future writes will error and it does the needed
* line discipline hangup and signal delivery. The tty object itself
* remains intact.
*
* Locking:
* BKL
* redirect lock for undoing redirection
* file list lock for manipulating list of ttys
* tty_ldisc_lock from called functions
* termios_mutex resetting termios data
* tasklist_lock to walk task list for hangup event
* ->siglock to protect ->signal/->sighand
*/
static void do_tty_hangup(struct work_struct *work)
{
struct tty_struct *tty =
container_of(work, struct tty_struct, hangup_work);
struct file *cons_filp = NULL;
struct file *filp, *f = NULL;
struct task_struct *p;
int closecount = 0, n;
unsigned long flags;
int refs = 0;
if (!tty)
return;
spin_lock(&redirect_lock);
if (redirect && redirect->private_data == tty) {
f = redirect;
redirect = NULL;
}
spin_unlock(&redirect_lock);
/* inuse_filps is protected by the single kernel lock */
lock_kernel();
check_tty_count(tty, "do_tty_hangup");
file_list_lock();
/* This breaks for file handles being sent over AF_UNIX sockets ? */
list_for_each_entry(filp, &tty->tty_files, f_u.fu_list) {
if (filp->f_op->write == redirected_tty_write)
cons_filp = filp;
if (filp->f_op->write != tty_write)
continue;
closecount++;
tty_fasync(-1, filp, 0); /* can't block */
filp->f_op = &hung_up_tty_fops;
}
file_list_unlock();
tty_ldisc_hangup(tty);
read_lock(&tasklist_lock);
if (tty->session) {
do_each_pid_task(tty->session, PIDTYPE_SID, p) {
spin_lock_irq(&p->sighand->siglock);
if (p->signal->tty == tty) {
p->signal->tty = NULL;
/* We defer the dereferences outside fo
the tasklist lock */
refs++;
}
if (!p->signal->leader) {
spin_unlock_irq(&p->sighand->siglock);
continue;
}
__group_send_sig_info(SIGHUP, SEND_SIG_PRIV, p);
__group_send_sig_info(SIGCONT, SEND_SIG_PRIV, p);
put_pid(p->signal->tty_old_pgrp); /* A noop */
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (tty->pgrp)
p->signal->tty_old_pgrp = get_pid(tty->pgrp);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
spin_unlock_irq(&p->sighand->siglock);
} while_each_pid_task(tty->session, PIDTYPE_SID, p);
}
read_unlock(&tasklist_lock);
spin_lock_irqsave(&tty->ctrl_lock, flags);
clear_bit(TTY_THROTTLED, &tty->flags);
clear_bit(TTY_PUSH, &tty->flags);
clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
put_pid(tty->session);
put_pid(tty->pgrp);
tty->session = NULL;
tty->pgrp = NULL;
tty->ctrl_status = 0;
set_bit(TTY_HUPPED, &tty->flags);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
/* Account for the p->signal references we killed */
while (refs--)
tty_kref_put(tty);
/*
* If one of the devices matches a console pointer, we
* cannot just call hangup() because that will cause
* tty->count and state->count to go out of sync.
* So we just call close() the right number of times.
*/
if (cons_filp) {
if (tty->ops->close)
for (n = 0; n < closecount; n++)
tty->ops->close(tty, cons_filp);
} else if (tty->ops->hangup)
(tty->ops->hangup)(tty);
/*
* We don't want to have driver/ldisc interactions beyond
* the ones we did here. The driver layer expects no
* calls after ->hangup() from the ldisc side. However we
* can't yet guarantee all that.
*/
set_bit(TTY_HUPPED, &tty->flags);
tty_ldisc_enable(tty);
unlock_kernel();
if (f)
fput(f);
}
/**
* tty_hangup - trigger a hangup event
* @tty: tty to hangup
*
* A carrier loss (virtual or otherwise) has occurred on this like
* schedule a hangup sequence to run after this event.
*/
void tty_hangup(struct tty_struct *tty)
{
#ifdef TTY_DEBUG_HANGUP
char buf[64];
printk(KERN_DEBUG "%s hangup...\n", tty_name(tty, buf));
#endif
schedule_work(&tty->hangup_work);
}
EXPORT_SYMBOL(tty_hangup);
/**
* tty_vhangup - process vhangup
* @tty: tty to hangup
*
* The user has asked via system call for the terminal to be hung up.
* We do this synchronously so that when the syscall returns the process
* is complete. That guarantee is necessary for security reasons.
*/
void tty_vhangup(struct tty_struct *tty)
{
#ifdef TTY_DEBUG_HANGUP
char buf[64];
printk(KERN_DEBUG "%s vhangup...\n", tty_name(tty, buf));
#endif
do_tty_hangup(&tty->hangup_work);
}
EXPORT_SYMBOL(tty_vhangup);
/**
* tty_vhangup_self - process vhangup for own ctty
*
* Perform a vhangup on the current controlling tty
*/
void tty_vhangup_self(void)
{
struct tty_struct *tty;
tty = get_current_tty();
if (tty) {
tty_vhangup(tty);
tty_kref_put(tty);
}
}
/**
* tty_hung_up_p - was tty hung up
* @filp: file pointer of tty
*
* Return true if the tty has been subject to a vhangup or a carrier
* loss
*/
int tty_hung_up_p(struct file *filp)
{
return (filp->f_op == &hung_up_tty_fops);
}
EXPORT_SYMBOL(tty_hung_up_p);
static void session_clear_tty(struct pid *session)
{
struct task_struct *p;
do_each_pid_task(session, PIDTYPE_SID, p) {
proc_clear_tty(p);
} while_each_pid_task(session, PIDTYPE_SID, p);
}
/**
* disassociate_ctty - disconnect controlling tty
* @on_exit: true if exiting so need to "hang up" the session
*
* This function is typically called only by the session leader, when
* it wants to disassociate itself from its controlling tty.
*
* It performs the following functions:
* (1) Sends a SIGHUP and SIGCONT to the foreground process group
* (2) Clears the tty from being controlling the session
* (3) Clears the controlling tty for all processes in the
* session group.
*
* The argument on_exit is set to 1 if called when a process is
* exiting; it is 0 if called by the ioctl TIOCNOTTY.
*
* Locking:
* BKL is taken for hysterical raisins
* tty_mutex is taken to protect tty
* ->siglock is taken to protect ->signal/->sighand
* tasklist_lock is taken to walk process list for sessions
* ->siglock is taken to protect ->signal/->sighand
*/
void disassociate_ctty(int on_exit)
{
struct tty_struct *tty;
struct pid *tty_pgrp = NULL;
if (!current->signal->leader)
return;
tty = get_current_tty();
if (tty) {
tty_pgrp = get_pid(tty->pgrp);
lock_kernel();
if (on_exit && tty->driver->type != TTY_DRIVER_TYPE_PTY)
tty_vhangup(tty);
unlock_kernel();
tty_kref_put(tty);
} else if (on_exit) {
struct pid *old_pgrp;
spin_lock_irq(¤t->sighand->siglock);
old_pgrp = current->signal->tty_old_pgrp;
current->signal->tty_old_pgrp = NULL;
spin_unlock_irq(¤t->sighand->siglock);
if (old_pgrp) {
kill_pgrp(old_pgrp, SIGHUP, on_exit);
kill_pgrp(old_pgrp, SIGCONT, on_exit);
put_pid(old_pgrp);
}
return;
}
if (tty_pgrp) {
kill_pgrp(tty_pgrp, SIGHUP, on_exit);
if (!on_exit)
kill_pgrp(tty_pgrp, SIGCONT, on_exit);
put_pid(tty_pgrp);
}
spin_lock_irq(¤t->sighand->siglock);
put_pid(current->signal->tty_old_pgrp);
current->signal->tty_old_pgrp = NULL;
spin_unlock_irq(¤t->sighand->siglock);
tty = get_current_tty();
if (tty) {
unsigned long flags;
spin_lock_irqsave(&tty->ctrl_lock, flags);
put_pid(tty->session);
put_pid(tty->pgrp);
tty->session = NULL;
tty->pgrp = NULL;
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
tty_kref_put(tty);
} else {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error attempted to write to tty [0x%p]"
" = NULL", tty);
#endif
}
/* Now clear signal->tty under the lock */
read_lock(&tasklist_lock);
session_clear_tty(task_session(current));
read_unlock(&tasklist_lock);
}
/**
*
* no_tty - Ensure the current process does not have a controlling tty
*/
void no_tty(void)
{
struct task_struct *tsk = current;
lock_kernel();
disassociate_ctty(0);
unlock_kernel();
proc_clear_tty(tsk);
}
/**
* stop_tty - propagate flow control
* @tty: tty to stop
*
* Perform flow control to the driver. For PTY/TTY pairs we
* must also propagate the TIOCKPKT status. May be called
* on an already stopped device and will not re-call the driver
* method.
*
* This functionality is used by both the line disciplines for
* halting incoming flow and by the driver. It may therefore be
* called from any context, may be under the tty atomic_write_lock
* but not always.
*
* Locking:
* Uses the tty control lock internally
*/
void stop_tty(struct tty_struct *tty)
{
unsigned long flags;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (tty->stopped) {
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
return;
}
tty->stopped = 1;
if (tty->link && tty->link->packet) {
tty->ctrl_status &= ~TIOCPKT_START;
tty->ctrl_status |= TIOCPKT_STOP;
wake_up_interruptible_poll(&tty->link->read_wait, POLLIN);
}
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
if (tty->ops->stop)
(tty->ops->stop)(tty);
}
EXPORT_SYMBOL(stop_tty);
/**
* start_tty - propagate flow control
* @tty: tty to start
*
* Start a tty that has been stopped if at all possible. Perform
* any necessary wakeups and propagate the TIOCPKT status. If this
* is the tty was previous stopped and is being started then the
* driver start method is invoked and the line discipline woken.
*
* Locking:
* ctrl_lock
*/
void start_tty(struct tty_struct *tty)
{
unsigned long flags;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (!tty->stopped || tty->flow_stopped) {
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
return;
}
tty->stopped = 0;
if (tty->link && tty->link->packet) {
tty->ctrl_status &= ~TIOCPKT_STOP;
tty->ctrl_status |= TIOCPKT_START;
wake_up_interruptible_poll(&tty->link->read_wait, POLLIN);
}
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
if (tty->ops->start)
(tty->ops->start)(tty);
/* If we have a running line discipline it may need kicking */
tty_wakeup(tty);
}
EXPORT_SYMBOL(start_tty);
/**
* tty_read - read method for tty device files
* @file: pointer to tty file
* @buf: user buffer
* @count: size of user buffer
* @ppos: unused
*
* Perform the read system call function on this terminal device. Checks
* for hung up devices before calling the line discipline method.
*
* Locking:
* Locks the line discipline internally while needed. Multiple
* read calls may be outstanding in parallel.
*/
static ssize_t tty_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
int i;
struct tty_struct *tty;
struct inode *inode;
struct tty_ldisc *ld;
tty = (struct tty_struct *)file->private_data;
inode = file->f_path.dentry->d_inode;
if (tty_paranoia_check(tty, inode, "tty_read"))
return -EIO;
if (!tty || (test_bit(TTY_IO_ERROR, &tty->flags)))
return -EIO;
/* We want to wait for the line discipline to sort out in this
situation */
ld = tty_ldisc_ref_wait(tty);
if (ld->ops->read)
i = (ld->ops->read)(tty, file, buf, count);
else
i = -EIO;
tty_ldisc_deref(ld);
if (i > 0)
inode->i_atime = current_fs_time(inode->i_sb);
return i;
}
void tty_write_unlock(struct tty_struct *tty)
{
mutex_unlock(&tty->atomic_write_lock);
wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
}
int tty_write_lock(struct tty_struct *tty, int ndelay)
{
if (!mutex_trylock(&tty->atomic_write_lock)) {
if (ndelay)
return -EAGAIN;
if (mutex_lock_interruptible(&tty->atomic_write_lock))
return -ERESTARTSYS;
}
return 0;
}
/*
* Split writes up in sane blocksizes to avoid
* denial-of-service type attacks
*/
static inline ssize_t do_tty_write(
ssize_t (*write)(struct tty_struct *, struct file *, const unsigned char *, size_t),
struct tty_struct *tty,
struct file *file,
const char __user *buf,
size_t count)
{
ssize_t ret, written = 0;
unsigned int chunk;
ret = tty_write_lock(tty, file->f_flags & O_NDELAY);
if (ret < 0)
return ret;
/*
* We chunk up writes into a temporary buffer. This
* simplifies low-level drivers immensely, since they
* don't have locking issues and user mode accesses.
*
* But if TTY_NO_WRITE_SPLIT is set, we should use a
* big chunk-size..
*
* The default chunk-size is 2kB, because the NTTY
* layer has problems with bigger chunks. It will
* claim to be able to handle more characters than
* it actually does.
*
* FIXME: This can probably go away now except that 64K chunks
* are too likely to fail unless switched to vmalloc...
*/
chunk = 2048;
if (test_bit(TTY_NO_WRITE_SPLIT, &tty->flags))
chunk = 65536;
if (count < chunk)
chunk = count;
/* write_buf/write_cnt is protected by the atomic_write_lock mutex */
if (tty->write_cnt < chunk) {
unsigned char *buf_chunk;
if (chunk < 1024)
chunk = 1024;
buf_chunk = kmalloc(chunk, GFP_KERNEL);
if (!buf_chunk) {
ret = -ENOMEM;
goto out;
}
kfree(tty->write_buf);
tty->write_cnt = chunk;
tty->write_buf = buf_chunk;
}
/* Do the write .. */
for (;;) {
size_t size = count;
if (size > chunk)
size = chunk;
ret = -EFAULT;
if (copy_from_user(tty->write_buf, buf, size))
break;
ret = write(tty, file, tty->write_buf, size);
if (ret <= 0)
break;
written += ret;
buf += ret;
count -= ret;
if (!count)
break;
ret = -ERESTARTSYS;
if (signal_pending(current))
break;
cond_resched();
}
if (written) {
struct inode *inode = file->f_path.dentry->d_inode;
inode->i_mtime = current_fs_time(inode->i_sb);
ret = written;
}
out:
tty_write_unlock(tty);
return ret;
}
/**
* tty_write_message - write a message to a certain tty, not just the console.
* @tty: the destination tty_struct
* @msg: the message to write
*
* This is used for messages that need to be redirected to a specific tty.
* We don't put it into the syslog queue right now maybe in the future if
* really needed.
*
* We must still hold the BKL and test the CLOSING flag for the moment.
*/
void tty_write_message(struct tty_struct *tty, char *msg)
{
if (tty) {
mutex_lock(&tty->atomic_write_lock);
lock_kernel();
if (tty->ops->write && !test_bit(TTY_CLOSING, &tty->flags)) {
unlock_kernel();
tty->ops->write(tty, msg, strlen(msg));
} else
unlock_kernel();
tty_write_unlock(tty);
}
return;
}
/**
* tty_write - write method for tty device file
* @file: tty file pointer
* @buf: user data to write
* @count: bytes to write
* @ppos: unused
*
* Write data to a tty device via the line discipline.
*
* Locking:
* Locks the line discipline as required
* Writes to the tty driver are serialized by the atomic_write_lock
* and are then processed in chunks to the device. The line discipline
* write method will not be invoked in parallel for each device.
*/
static ssize_t tty_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct tty_struct *tty;
struct inode *inode = file->f_path.dentry->d_inode;
ssize_t ret;
struct tty_ldisc *ld;
tty = (struct tty_struct *)file->private_data;
if (tty_paranoia_check(tty, inode, "tty_write"))
return -EIO;
if (!tty || !tty->ops->write ||
(test_bit(TTY_IO_ERROR, &tty->flags)))
return -EIO;
/* Short term debug to catch buggy drivers */
if (tty->ops->write_room == NULL)
printk(KERN_ERR "tty driver %s lacks a write_room method.\n",
tty->driver->name);
ld = tty_ldisc_ref_wait(tty);
if (!ld->ops->write)
ret = -EIO;
else
ret = do_tty_write(ld->ops->write, tty, file, buf, count);
tty_ldisc_deref(ld);
return ret;
}
ssize_t redirected_tty_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct file *p = NULL;
spin_lock(&redirect_lock);
if (redirect) {
get_file(redirect);
p = redirect;
}
spin_unlock(&redirect_lock);
if (p) {
ssize_t res;
res = vfs_write(p, buf, count, &p->f_pos);
fput(p);
return res;
}
return tty_write(file, buf, count, ppos);
}
static char ptychar[] = "pqrstuvwxyzabcde";
/**
* pty_line_name - generate name for a pty
* @driver: the tty driver in use
* @index: the minor number
* @p: output buffer of at least 6 bytes
*
* Generate a name from a driver reference and write it to the output
* buffer.
*
* Locking: None
*/
static void pty_line_name(struct tty_driver *driver, int index, char *p)
{
int i = index + driver->name_base;
/* ->name is initialized to "ttyp", but "tty" is expected */
sprintf(p, "%s%c%x",
driver->subtype == PTY_TYPE_SLAVE ? "tty" : driver->name,
ptychar[i >> 4 & 0xf], i & 0xf);
}
/**
* tty_line_name - generate name for a tty
* @driver: the tty driver in use
* @index: the minor number
* @p: output buffer of at least 7 bytes
*
* Generate a name from a driver reference and write it to the output
* buffer.
*
* Locking: None
*/
static void tty_line_name(struct tty_driver *driver, int index, char *p)
{
sprintf(p, "%s%d", driver->name, index + driver->name_base);
}
/**
* tty_driver_lookup_tty() - find an existing tty, if any
* @driver: the driver for the tty
* @idx: the minor number
*
* Return the tty, if found or ERR_PTR() otherwise.
*
* Locking: tty_mutex must be held. If tty is found, the mutex must
* be held until the 'fast-open' is also done. Will change once we
* have refcounting in the driver and per driver locking
*/
static struct tty_struct *tty_driver_lookup_tty(struct tty_driver *driver,
struct inode *inode, int idx)
{
struct tty_struct *tty;
if (driver->ops->lookup)
return driver->ops->lookup(driver, inode, idx);
tty = driver->ttys[idx];
return tty;
}
/**
* tty_init_termios - helper for termios setup
* @tty: the tty to set up
*
* Initialise the termios structures for this tty. Thus runs under
* the tty_mutex currently so we can be relaxed about ordering.
*/
int tty_init_termios(struct tty_struct *tty)
{
struct ktermios *tp;
int idx = tty->index;
tp = tty->driver->termios[idx];
if (tp == NULL) {
tp = kzalloc(sizeof(struct ktermios[2]), GFP_KERNEL);
if (tp == NULL)
return -ENOMEM;
memcpy(tp, &tty->driver->init_termios,
sizeof(struct ktermios));
tty->driver->termios[idx] = tp;
}
tty->termios = tp;
tty->termios_locked = tp + 1;
/* Compatibility until drivers always set this */
tty->termios->c_ispeed = tty_termios_input_baud_rate(tty->termios);
tty->termios->c_ospeed = tty_termios_baud_rate(tty->termios);
return 0;
}
EXPORT_SYMBOL_GPL(tty_init_termios);
/**
* tty_driver_install_tty() - install a tty entry in the driver
* @driver: the driver for the tty
* @tty: the tty
*
* Install a tty object into the driver tables. The tty->index field
* will be set by the time this is called. This method is responsible
* for ensuring any need additional structures are allocated and
* configured.
*
* Locking: tty_mutex for now
*/
static int tty_driver_install_tty(struct tty_driver *driver,
struct tty_struct *tty)
{
int idx = tty->index;
int ret;
if (driver->ops->install) {
lock_kernel();
ret = driver->ops->install(driver, tty);
unlock_kernel();
return ret;
}
if (tty_init_termios(tty) == 0) {
lock_kernel();
tty_driver_kref_get(driver);
tty->count++;
driver->ttys[idx] = tty;
unlock_kernel();
return 0;
}
return -ENOMEM;
}
/**
* tty_driver_remove_tty() - remove a tty from the driver tables
* @driver: the driver for the tty
* @idx: the minor number
*
* Remvoe a tty object from the driver tables. The tty->index field
* will be set by the time this is called.
*
* Locking: tty_mutex for now
*/
static void tty_driver_remove_tty(struct tty_driver *driver,
struct tty_struct *tty)
{
if (driver->ops->remove)
driver->ops->remove(driver, tty);
else
driver->ttys[tty->index] = NULL;
}
/*
* tty_reopen() - fast re-open of an open tty
* @tty - the tty to open
*
* Return 0 on success, -errno on error.
*
* Locking: tty_mutex must be held from the time the tty was found
* till this open completes.
*/
static int tty_reopen(struct tty_struct *tty)
{
struct tty_driver *driver = tty->driver;
if (test_bit(TTY_CLOSING, &tty->flags))
return -EIO;
if (driver->type == TTY_DRIVER_TYPE_PTY &&
driver->subtype == PTY_TYPE_MASTER) {
/*
* special case for PTY masters: only one open permitted,
* and the slave side open count is incremented as well.
*/
if (tty->count)
return -EIO;
tty->link->count++;
}
tty->count++;
tty->driver = driver; /* N.B. why do this every time?? */
mutex_lock(&tty->ldisc_mutex);
WARN_ON(!test_bit(TTY_LDISC, &tty->flags));
mutex_unlock(&tty->ldisc_mutex);
return 0;
}
/**
* tty_init_dev - initialise a tty device
* @driver: tty driver we are opening a device on
* @idx: device index
* @ret_tty: returned tty structure
* @first_ok: ok to open a new device (used by ptmx)
*
* Prepare a tty device. This may not be a "new" clean device but
* could also be an active device. The pty drivers require special
* handling because of this.
*
* Locking:
* The function is called under the tty_mutex, which
* protects us from the tty struct or driver itself going away.
*
* On exit the tty device has the line discipline attached and
* a reference count of 1. If a pair was created for pty/tty use
* and the other was a pty master then it too has a reference count of 1.
*
* WSH 06/09/97: Rewritten to remove races and properly clean up after a
* failed open. The new code protects the open with a mutex, so it's
* really quite straightforward. The mutex locking can probably be
* relaxed for the (most common) case of reopening a tty.
*/
struct tty_struct *tty_init_dev(struct tty_driver *driver, int idx,
int first_ok)
{
struct tty_struct *tty;
int retval;
lock_kernel();
/* Check if pty master is being opened multiple times */
if (driver->subtype == PTY_TYPE_MASTER &&
(driver->flags & TTY_DRIVER_DEVPTS_MEM) && !first_ok) {
unlock_kernel();
return ERR_PTR(-EIO);
}
unlock_kernel();
/*
* First time open is complex, especially for PTY devices.
* This code guarantees that either everything succeeds and the
* TTY is ready for operation, or else the table slots are vacated
* and the allocated memory released. (Except that the termios
* and locked termios may be retained.)
*/
if (!try_module_get(driver->owner))
return ERR_PTR(-ENODEV);
tty = alloc_tty_struct();
if (!tty)
goto fail_no_mem;
initialize_tty_struct(tty, driver, idx);
retval = tty_driver_install_tty(driver, tty);
if (retval < 0) {
free_tty_struct(tty);
module_put(driver->owner);
return ERR_PTR(retval);
}
/*
* Structures all installed ... call the ldisc open routines.
* If we fail here just call release_tty to clean up. No need
* to decrement the use counts, as release_tty doesn't care.
*/
retval = tty_ldisc_setup(tty, tty->link);
if (retval)
goto release_mem_out;
return tty;
fail_no_mem:
module_put(driver->owner);
return ERR_PTR(-ENOMEM);
/* call the tty release_tty routine to clean out this slot */
release_mem_out:
if (printk_ratelimit())
printk(KERN_INFO "tty_init_dev: ldisc open failed, "
"clearing slot %d\n", idx);
lock_kernel();
release_tty(tty, idx);
unlock_kernel();
return ERR_PTR(retval);
}
void tty_free_termios(struct tty_struct *tty)
{
struct ktermios *tp;
int idx = tty->index;
/* Kill this flag and push into drivers for locking etc */
if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS) {
/* FIXME: Locking on ->termios array */
tp = tty->termios;
tty->driver->termios[idx] = NULL;
kfree(tp);
}
}
EXPORT_SYMBOL(tty_free_termios);
void tty_shutdown(struct tty_struct *tty)
{
tty_driver_remove_tty(tty->driver, tty);
tty_free_termios(tty);
}
EXPORT_SYMBOL(tty_shutdown);
/**
* release_one_tty - release tty structure memory
* @kref: kref of tty we are obliterating
*
* Releases memory associated with a tty structure, and clears out the
* driver table slots. This function is called when a device is no longer
* in use. It also gets called when setup of a device fails.
*
* Locking:
* tty_mutex - sometimes only
* takes the file list lock internally when working on the list
* of ttys that the driver keeps.
*
* This method gets called from a work queue so that the driver private
* cleanup ops can sleep (needed for USB at least)
*/
static void release_one_tty(struct work_struct *work)
{
struct tty_struct *tty =
container_of(work, struct tty_struct, hangup_work);
struct tty_driver *driver = tty->driver;
if (tty->ops->cleanup)
tty->ops->cleanup(tty);
tty->magic = 0;
tty_driver_kref_put(driver);
module_put(driver->owner);
file_list_lock();
list_del_init(&tty->tty_files);
file_list_unlock();
put_pid(tty->pgrp);
put_pid(tty->session);
free_tty_struct(tty);
}
static void queue_release_one_tty(struct kref *kref)
{
struct tty_struct *tty = container_of(kref, struct tty_struct, kref);
if (tty->ops->shutdown)
tty->ops->shutdown(tty);
else
tty_shutdown(tty);
/* The hangup queue is now free so we can reuse it rather than
waste a chunk of memory for each port */
INIT_WORK(&tty->hangup_work, release_one_tty);
schedule_work(&tty->hangup_work);
}
/**
* tty_kref_put - release a tty kref
* @tty: tty device
*
* Release a reference to a tty device and if need be let the kref
* layer destruct the object for us
*/
void tty_kref_put(struct tty_struct *tty)
{
if (tty)
kref_put(&tty->kref, queue_release_one_tty);
}
EXPORT_SYMBOL(tty_kref_put);
/**
* release_tty - release tty structure memory
*
* Release both @tty and a possible linked partner (think pty pair),
* and decrement the refcount of the backing module.
*
* Locking:
* tty_mutex - sometimes only
* takes the file list lock internally when working on the list
* of ttys that the driver keeps.
* FIXME: should we require tty_mutex is held here ??
*
*/
static void release_tty(struct tty_struct *tty, int idx)
{
/* This should always be true but check for the moment */
WARN_ON(tty->index != idx);
if (tty->link)
tty_kref_put(tty->link);
tty_kref_put(tty);
}
/**
* tty_release - vfs callback for close
* @inode: inode of tty
* @filp: file pointer for handle to tty
*
* Called the last time each file handle is closed that references
* this tty. There may however be several such references.
*
* Locking:
* Takes bkl. See tty_release_dev
*
* Even releasing the tty structures is a tricky business.. We have
* to be very careful that the structures are all released at the
* same time, as interrupts might otherwise get the wrong pointers.
*
* WSH 09/09/97: rewritten to avoid some nasty race conditions that could
* lead to double frees or releasing memory still in use.
*/
int tty_release(struct inode *inode, struct file *filp)
{
struct tty_struct *tty, *o_tty;
int pty_master, tty_closing, o_tty_closing, do_sleep;
int devpts;
int idx;
char buf[64];
tty = (struct tty_struct *)filp->private_data;
if (tty_paranoia_check(tty, inode, "tty_release_dev"))
return 0;
lock_kernel();
check_tty_count(tty, "tty_release_dev");
tty_fasync(-1, filp, 0);
idx = tty->index;
pty_master = (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER);
devpts = (tty->driver->flags & TTY_DRIVER_DEVPTS_MEM) != 0;
o_tty = tty->link;
#ifdef TTY_PARANOIA_CHECK
if (idx < 0 || idx >= tty->driver->num) {
printk(KERN_DEBUG "tty_release_dev: bad idx when trying to "
"free (%s)\n", tty->name);
unlock_kernel();
return 0;
}
if (!devpts) {
if (tty != tty->driver->ttys[idx]) {
unlock_kernel();
printk(KERN_DEBUG "tty_release_dev: driver.table[%d] not tty "
"for (%s)\n", idx, tty->name);
return 0;
}
if (tty->termios != tty->driver->termios[idx]) {
unlock_kernel();
printk(KERN_DEBUG "tty_release_dev: driver.termios[%d] not termios "
"for (%s)\n",
idx, tty->name);
return 0;
}
}
#endif
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "tty_release_dev of %s (tty count=%d)...",
tty_name(tty, buf), tty->count);
#endif
#ifdef TTY_PARANOIA_CHECK
if (tty->driver->other &&
!(tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
if (o_tty != tty->driver->other->ttys[idx]) {
unlock_kernel();
printk(KERN_DEBUG "tty_release_dev: other->table[%d] "
"not o_tty for (%s)\n",
idx, tty->name);
return 0 ;
}
if (o_tty->termios != tty->driver->other->termios[idx]) {
unlock_kernel();
printk(KERN_DEBUG "tty_release_dev: other->termios[%d] "
"not o_termios for (%s)\n",
idx, tty->name);
return 0;
}
if (o_tty->link != tty) {
unlock_kernel();
printk(KERN_DEBUG "tty_release_dev: bad pty pointers\n");
return 0;
}
}
#endif
if (tty->ops->close)
tty->ops->close(tty, filp);
unlock_kernel();
/*
* Sanity check: if tty->count is going to zero, there shouldn't be
* any waiters on tty->read_wait or tty->write_wait. We test the
* wait queues and kick everyone out _before_ actually starting to
* close. This ensures that we won't block while releasing the tty
* structure.
*
* The test for the o_tty closing is necessary, since the master and
* slave sides may close in any order. If the slave side closes out
* first, its count will be one, since the master side holds an open.
* Thus this test wouldn't be triggered at the time the slave closes,
* so we do it now.
*
* Note that it's possible for the tty to be opened again while we're
* flushing out waiters. By recalculating the closing flags before
* each iteration we avoid any problems.
*/
while (1) {
/* Guard against races with tty->count changes elsewhere and
opens on /dev/tty */
mutex_lock(&tty_mutex);
lock_kernel();
tty_closing = tty->count <= 1;
o_tty_closing = o_tty &&
(o_tty->count <= (pty_master ? 1 : 0));
do_sleep = 0;
if (tty_closing) {
if (waitqueue_active(&tty->read_wait)) {
wake_up_poll(&tty->read_wait, POLLIN);
do_sleep++;
}
if (waitqueue_active(&tty->write_wait)) {
wake_up_poll(&tty->write_wait, POLLOUT);
do_sleep++;
}
}
if (o_tty_closing) {
if (waitqueue_active(&o_tty->read_wait)) {
wake_up_poll(&o_tty->read_wait, POLLIN);
do_sleep++;
}
if (waitqueue_active(&o_tty->write_wait)) {
wake_up_poll(&o_tty->write_wait, POLLOUT);
do_sleep++;
}
}
if (!do_sleep)
break;
printk(KERN_WARNING "tty_release_dev: %s: read/write wait queue "
"active!\n", tty_name(tty, buf));
unlock_kernel();
mutex_unlock(&tty_mutex);
schedule();
}
/*
* The closing flags are now consistent with the open counts on
* both sides, and we've completed the last operation that could
* block, so it's safe to proceed with closing.
*/
if (pty_master) {
if (--o_tty->count < 0) {
printk(KERN_WARNING "tty_release_dev: bad pty slave count "
"(%d) for %s\n",
o_tty->count, tty_name(o_tty, buf));
o_tty->count = 0;
}
}
if (--tty->count < 0) {
printk(KERN_WARNING "tty_release_dev: bad tty->count (%d) for %s\n",
tty->count, tty_name(tty, buf));
tty->count = 0;
}
/*
* We've decremented tty->count, so we need to remove this file
* descriptor off the tty->tty_files list; this serves two
* purposes:
* - check_tty_count sees the correct number of file descriptors
* associated with this tty.
* - do_tty_hangup no longer sees this file descriptor as
* something that needs to be handled for hangups.
*/
file_kill(filp);
filp->private_data = NULL;
/*
* Perform some housekeeping before deciding whether to return.
*
* Set the TTY_CLOSING flag if this was the last open. In the
* case of a pty we may have to wait around for the other side
* to close, and TTY_CLOSING makes sure we can't be reopened.
*/
if (tty_closing)
set_bit(TTY_CLOSING, &tty->flags);
if (o_tty_closing)
set_bit(TTY_CLOSING, &o_tty->flags);
/*
* If _either_ side is closing, make sure there aren't any
* processes that still think tty or o_tty is their controlling
* tty.
*/
if (tty_closing || o_tty_closing) {
read_lock(&tasklist_lock);
session_clear_tty(tty->session);
if (o_tty)
session_clear_tty(o_tty->session);
read_unlock(&tasklist_lock);
}
mutex_unlock(&tty_mutex);
/* check whether both sides are closing ... */
if (!tty_closing || (o_tty && !o_tty_closing)) {
unlock_kernel();
return 0;
}
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "freeing tty structure...");
#endif
/*
* Ask the line discipline code to release its structures
*/
tty_ldisc_release(tty, o_tty);
/*
* The release_tty function takes care of the details of clearing
* the slots and preserving the termios structure.
*/
release_tty(tty, idx);
/* Make this pty number available for reallocation */
if (devpts)
devpts_kill_index(inode, idx);
unlock_kernel();
return 0;
}
/**
* tty_open - open a tty device
* @inode: inode of device file
* @filp: file pointer to tty
*
* tty_open and tty_release keep up the tty count that contains the
* number of opens done on a tty. We cannot use the inode-count, as
* different inodes might point to the same tty.
*
* Open-counting is needed for pty masters, as well as for keeping
* track of serial lines: DTR is dropped when the last close happens.
* (This is not done solely through tty->count, now. - Ted 1/27/92)
*
* The termios state of a pty is reset on first open so that
* settings don't persist across reuse.
*
* Locking: tty_mutex protects tty, get_tty_driver and tty_init_dev work.
* tty->count should protect the rest.
* ->siglock protects ->signal/->sighand
*/
static int tty_open(struct inode *inode, struct file *filp)
{
struct tty_struct *tty = NULL;
int noctty, retval;
struct tty_driver *driver;
int index;
dev_t device = inode->i_rdev;
unsigned saved_flags = filp->f_flags;
nonseekable_open(inode, filp);
retry_open:
noctty = filp->f_flags & O_NOCTTY;
index = -1;
retval = 0;
mutex_lock(&tty_mutex);
lock_kernel();
if (device == MKDEV(TTYAUX_MAJOR, 0)) {
tty = get_current_tty();
if (!tty) {
unlock_kernel();
mutex_unlock(&tty_mutex);
return -ENXIO;
}
driver = tty_driver_kref_get(tty->driver);
index = tty->index;
filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
/* noctty = 1; */
/* FIXME: Should we take a driver reference ? */
tty_kref_put(tty);
goto got_driver;
}
#ifdef CONFIG_VT
if (device == MKDEV(TTY_MAJOR, 0)) {
extern struct tty_driver *console_driver;
driver = tty_driver_kref_get(console_driver);
index = fg_console;
noctty = 1;
goto got_driver;
}
#endif
if (device == MKDEV(TTYAUX_MAJOR, 1)) {
struct tty_driver *console_driver = console_device(&index);
if (console_driver) {
driver = tty_driver_kref_get(console_driver);
if (driver) {
/* Don't let /dev/console block */
filp->f_flags |= O_NONBLOCK;
noctty = 1;
goto got_driver;
}
}
unlock_kernel();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
driver = get_tty_driver(device, &index);
if (!driver) {
unlock_kernel();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
got_driver:
if (!tty) {
/* check whether we're reopening an existing tty */
tty = tty_driver_lookup_tty(driver, inode, index);
if (IS_ERR(tty)) {
unlock_kernel();
mutex_unlock(&tty_mutex);
return PTR_ERR(tty);
}
}
if (tty) {
retval = tty_reopen(tty);
if (retval)
tty = ERR_PTR(retval);
} else
tty = tty_init_dev(driver, index, 0);
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
if (IS_ERR(tty)) {
unlock_kernel();
return PTR_ERR(tty);
}
filp->private_data = tty;
file_move(filp, &tty->tty_files);
check_tty_count(tty, "tty_open");
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
noctty = 1;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "opening %s...", tty->name);
#endif
if (!retval) {
if (tty->ops->open)
retval = tty->ops->open(tty, filp);
else
retval = -ENODEV;
}
filp->f_flags = saved_flags;
if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) &&
!capable(CAP_SYS_ADMIN))
retval = -EBUSY;
if (retval) {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error %d in opening %s...", retval,
tty->name);
#endif
tty_release(inode, filp);
if (retval != -ERESTARTSYS) {
unlock_kernel();
return retval;
}
if (signal_pending(current)) {
unlock_kernel();
return retval;
}
schedule();
/*
* Need to reset f_op in case a hangup happened.
*/
if (filp->f_op == &hung_up_tty_fops)
filp->f_op = &tty_fops;
unlock_kernel();
goto retry_open;
}
unlock_kernel();
mutex_lock(&tty_mutex);
lock_kernel();
spin_lock_irq(¤t->sighand->siglock);
if (!noctty &&
current->signal->leader &&
!current->signal->tty &&
tty->session == NULL)
__proc_set_tty(current, tty);
spin_unlock_irq(¤t->sighand->siglock);
unlock_kernel();
mutex_unlock(&tty_mutex);
return 0;
}
/**
* tty_poll - check tty status
* @filp: file being polled
* @wait: poll wait structures to update
*
* Call the line discipline polling method to obtain the poll
* status of the device.
*
* Locking: locks called line discipline but ldisc poll method
* may be re-entered freely by other callers.
*/
static unsigned int tty_poll(struct file *filp, poll_table *wait)
{
struct tty_struct *tty;
struct tty_ldisc *ld;
int ret = 0;
tty = (struct tty_struct *)filp->private_data;
if (tty_paranoia_check(tty, filp->f_path.dentry->d_inode, "tty_poll"))
return 0;
ld = tty_ldisc_ref_wait(tty);
if (ld->ops->poll)
ret = (ld->ops->poll)(tty, filp, wait);
tty_ldisc_deref(ld);
return ret;
}
static int tty_fasync(int fd, struct file *filp, int on)
{
struct tty_struct *tty;
unsigned long flags;
int retval = 0;
lock_kernel();
tty = (struct tty_struct *)filp->private_data;
if (tty_paranoia_check(tty, filp->f_path.dentry->d_inode, "tty_fasync"))
goto out;
retval = fasync_helper(fd, filp, on, &tty->fasync);
if (retval <= 0)
goto out;
if (on) {
enum pid_type type;
struct pid *pid;
if (!waitqueue_active(&tty->read_wait))
tty->minimum_to_wake = 1;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (tty->pgrp) {
pid = tty->pgrp;
type = PIDTYPE_PGID;
} else {
pid = task_pid(current);
type = PIDTYPE_PID;
}
get_pid(pid);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
retval = __f_setown(filp, pid, type, 0);
put_pid(pid);
if (retval)
goto out;
} else {
if (!tty->fasync && !waitqueue_active(&tty->read_wait))
tty->minimum_to_wake = N_TTY_BUF_SIZE;
}
retval = 0;
out:
unlock_kernel();
return retval;
}
/**
* tiocsti - fake input character
* @tty: tty to fake input into
* @p: pointer to character
*
* Fake input to a tty device. Does the necessary locking and
* input management.
*
* FIXME: does not honour flow control ??
*
* Locking:
* Called functions take tty_ldisc_lock
* current->signal->tty check is safe without locks
*
* FIXME: may race normal receive processing
*/
static int tiocsti(struct tty_struct *tty, char __user *p)
{
char ch, mbz = 0;
struct tty_ldisc *ld;
if ((current->signal->tty != tty) && !capable(CAP_SYS_ADMIN))
return -EPERM;
if (get_user(ch, p))
return -EFAULT;
tty_audit_tiocsti(tty, ch);
ld = tty_ldisc_ref_wait(tty);
ld->ops->receive_buf(tty, &ch, &mbz, 1);
tty_ldisc_deref(ld);
return 0;
}
/**
* tiocgwinsz - implement window query ioctl
* @tty; tty
* @arg: user buffer for result
*
* Copies the kernel idea of the window size into the user buffer.
*
* Locking: tty->termios_mutex is taken to ensure the winsize data
* is consistent.
*/
static int tiocgwinsz(struct tty_struct *tty, struct winsize __user *arg)
{
int err;
mutex_lock(&tty->termios_mutex);
err = copy_to_user(arg, &tty->winsize, sizeof(*arg));
mutex_unlock(&tty->termios_mutex);
return err ? -EFAULT: 0;
}
/**
* tty_do_resize - resize event
* @tty: tty being resized
* @rows: rows (character)
* @cols: cols (character)
*
* Update the termios variables and send the necessary signals to
* peform a terminal resize correctly
*/
int tty_do_resize(struct tty_struct *tty, struct winsize *ws)
{
struct pid *pgrp;
unsigned long flags;
/* Lock the tty */
mutex_lock(&tty->termios_mutex);
if (!memcmp(ws, &tty->winsize, sizeof(*ws)))
goto done;
/* Get the PID values and reference them so we can
avoid holding the tty ctrl lock while sending signals */
spin_lock_irqsave(&tty->ctrl_lock, flags);
pgrp = get_pid(tty->pgrp);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
if (pgrp)
kill_pgrp(pgrp, SIGWINCH, 1);
put_pid(pgrp);
tty->winsize = *ws;
done:
mutex_unlock(&tty->termios_mutex);
return 0;
}
/**
* tiocswinsz - implement window size set ioctl
* @tty; tty side of tty
* @arg: user buffer for result
*
* Copies the user idea of the window size to the kernel. Traditionally
* this is just advisory information but for the Linux console it
* actually has driver level meaning and triggers a VC resize.
*
* Locking:
* Driver dependant. The default do_resize method takes the
* tty termios mutex and ctrl_lock. The console takes its own lock
* then calls into the default method.
*/
static int tiocswinsz(struct tty_struct *tty, struct winsize __user *arg)
{
struct winsize tmp_ws;
if (copy_from_user(&tmp_ws, arg, sizeof(*arg)))
return -EFAULT;
if (tty->ops->resize)
return tty->ops->resize(tty, &tmp_ws);
else
return tty_do_resize(tty, &tmp_ws);
}
/**
* tioccons - allow admin to move logical console
* @file: the file to become console
*
* Allow the adminstrator to move the redirected console device
*
* Locking: uses redirect_lock to guard the redirect information
*/
static int tioccons(struct file *file)
{
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (file->f_op->write == redirected_tty_write) {
struct file *f;
spin_lock(&redirect_lock);
f = redirect;
redirect = NULL;
spin_unlock(&redirect_lock);
if (f)
fput(f);
return 0;
}
spin_lock(&redirect_lock);
if (redirect) {
spin_unlock(&redirect_lock);
return -EBUSY;
}
get_file(file);
redirect = file;
spin_unlock(&redirect_lock);
return 0;
}
/**
* fionbio - non blocking ioctl
* @file: file to set blocking value
* @p: user parameter
*
* Historical tty interfaces had a blocking control ioctl before
* the generic functionality existed. This piece of history is preserved
* in the expected tty API of posix OS's.
*
* Locking: none, the open file handle ensures it won't go away.
*/
static int fionbio(struct file *file, int __user *p)
{
int nonblock;
if (get_user(nonblock, p))
return -EFAULT;
spin_lock(&file->f_lock);
if (nonblock)
file->f_flags |= O_NONBLOCK;
else
file->f_flags &= ~O_NONBLOCK;
spin_unlock(&file->f_lock);
return 0;
}
/**
* tiocsctty - set controlling tty
* @tty: tty structure
* @arg: user argument
*
* This ioctl is used to manage job control. It permits a session
* leader to set this tty as the controlling tty for the session.
*
* Locking:
* Takes tty_mutex() to protect tty instance
* Takes tasklist_lock internally to walk sessions
* Takes ->siglock() when updating signal->tty
*/
static int tiocsctty(struct tty_struct *tty, int arg)
{
int ret = 0;
if (current->signal->leader && (task_session(current) == tty->session))
return ret;
mutex_lock(&tty_mutex);
/*
* The process must be a session leader and
* not have a controlling tty already.
*/
if (!current->signal->leader || current->signal->tty) {
ret = -EPERM;
goto unlock;
}
if (tty->session) {
/*
* This tty is already the controlling
* tty for another session group!
*/
if (arg == 1 && capable(CAP_SYS_ADMIN)) {
/*
* Steal it away
*/
read_lock(&tasklist_lock);
session_clear_tty(tty->session);
read_unlock(&tasklist_lock);
} else {
ret = -EPERM;
goto unlock;
}
}
proc_set_tty(current, tty);
unlock:
mutex_unlock(&tty_mutex);
return ret;
}
/**
* tty_get_pgrp - return a ref counted pgrp pid
* @tty: tty to read
*
* Returns a refcounted instance of the pid struct for the process
* group controlling the tty.
*/
struct pid *tty_get_pgrp(struct tty_struct *tty)
{
unsigned long flags;
struct pid *pgrp;
spin_lock_irqsave(&tty->ctrl_lock, flags);
pgrp = get_pid(tty->pgrp);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
return pgrp;
}
EXPORT_SYMBOL_GPL(tty_get_pgrp);
/**
* tiocgpgrp - get process group
* @tty: tty passed by user
* @real_tty: tty side of the tty pased by the user if a pty else the tty
* @p: returned pid
*
* Obtain the process group of the tty. If there is no process group
* return an error.
*
* Locking: none. Reference to current->signal->tty is safe.
*/
static int tiocgpgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
{
struct pid *pid;
int ret;
/*
* (tty == real_tty) is a cheap way of
* testing if the tty is NOT a master pty.
*/
if (tty == real_tty && current->signal->tty != real_tty)
return -ENOTTY;
pid = tty_get_pgrp(real_tty);
ret = put_user(pid_vnr(pid), p);
put_pid(pid);
return ret;
}
/**
* tiocspgrp - attempt to set process group
* @tty: tty passed by user
* @real_tty: tty side device matching tty passed by user
* @p: pid pointer
*
* Set the process group of the tty to the session passed. Only
* permitted where the tty session is our session.
*
* Locking: RCU, ctrl lock
*/
static int tiocspgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
{
struct pid *pgrp;
pid_t pgrp_nr;
int retval = tty_check_change(real_tty);
unsigned long flags;
if (retval == -EIO)
return -ENOTTY;
if (retval)
return retval;
if (!current->signal->tty ||
(current->signal->tty != real_tty) ||
(real_tty->session != task_session(current)))
return -ENOTTY;
if (get_user(pgrp_nr, p))
return -EFAULT;
if (pgrp_nr < 0)
return -EINVAL;
rcu_read_lock();
pgrp = find_vpid(pgrp_nr);
retval = -ESRCH;
if (!pgrp)
goto out_unlock;
retval = -EPERM;
if (session_of_pgrp(pgrp) != task_session(current))
goto out_unlock;
retval = 0;
spin_lock_irqsave(&tty->ctrl_lock, flags);
put_pid(real_tty->pgrp);
real_tty->pgrp = get_pid(pgrp);
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
out_unlock:
rcu_read_unlock();
return retval;
}
/**
* tiocgsid - get session id
* @tty: tty passed by user
* @real_tty: tty side of the tty pased by the user if a pty else the tty
* @p: pointer to returned session id
*
* Obtain the session id of the tty. If there is no session
* return an error.
*
* Locking: none. Reference to current->signal->tty is safe.
*/
static int tiocgsid(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
{
/*
* (tty == real_tty) is a cheap way of
* testing if the tty is NOT a master pty.
*/
if (tty == real_tty && current->signal->tty != real_tty)
return -ENOTTY;
if (!real_tty->session)
return -ENOTTY;
return put_user(pid_vnr(real_tty->session), p);
}
/**
* tiocsetd - set line discipline
* @tty: tty device
* @p: pointer to user data
*
* Set the line discipline according to user request.
*
* Locking: see tty_set_ldisc, this function is just a helper
*/
static int tiocsetd(struct tty_struct *tty, int __user *p)
{
int ldisc;
int ret;
if (get_user(ldisc, p))
return -EFAULT;
ret = tty_set_ldisc(tty, ldisc);
return ret;
}
/**
* send_break - performed time break
* @tty: device to break on
* @duration: timeout in mS
*
* Perform a timed break on hardware that lacks its own driver level
* timed break functionality.
*
* Locking:
* atomic_write_lock serializes
*
*/
static int send_break(struct tty_struct *tty, unsigned int duration)
{
int retval;
if (tty->ops->break_ctl == NULL)
return 0;
if (tty->driver->flags & TTY_DRIVER_HARDWARE_BREAK)
retval = tty->ops->break_ctl(tty, duration);
else {
/* Do the work ourselves */
if (tty_write_lock(tty, 0) < 0)
return -EINTR;
retval = tty->ops->break_ctl(tty, -1);
if (retval)
goto out;
if (!signal_pending(current))
msleep_interruptible(duration);
retval = tty->ops->break_ctl(tty, 0);
out:
tty_write_unlock(tty);
if (signal_pending(current))
retval = -EINTR;
}
return retval;
}
/**
* tty_tiocmget - get modem status
* @tty: tty device
* @file: user file pointer
* @p: pointer to result
*
* Obtain the modem status bits from the tty driver if the feature
* is supported. Return -EINVAL if it is not available.
*
* Locking: none (up to the driver)
*/
static int tty_tiocmget(struct tty_struct *tty, struct file *file, int __user *p)
{
int retval = -EINVAL;
if (tty->ops->tiocmget) {
retval = tty->ops->tiocmget(tty, file);
if (retval >= 0)
retval = put_user(retval, p);
}
return retval;
}
/**
* tty_tiocmset - set modem status
* @tty: tty device
* @file: user file pointer
* @cmd: command - clear bits, set bits or set all
* @p: pointer to desired bits
*
* Set the modem status bits from the tty driver if the feature
* is supported. Return -EINVAL if it is not available.
*
* Locking: none (up to the driver)
*/
static int tty_tiocmset(struct tty_struct *tty, struct file *file, unsigned int cmd,
unsigned __user *p)
{
int retval;
unsigned int set, clear, val;
if (tty->ops->tiocmset == NULL)
return -EINVAL;
retval = get_user(val, p);
if (retval)
return retval;
set = clear = 0;
switch (cmd) {
case TIOCMBIS:
set = val;
break;
case TIOCMBIC:
clear = val;
break;
case TIOCMSET:
set = val;
clear = ~val;
break;
}
set &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
clear &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
return tty->ops->tiocmset(tty, file, set, clear);
}
struct tty_struct *tty_pair_get_tty(struct tty_struct *tty)
{
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
tty = tty->link;
return tty;
}
EXPORT_SYMBOL(tty_pair_get_tty);
struct tty_struct *tty_pair_get_pty(struct tty_struct *tty)
{
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
return tty;
return tty->link;
}
EXPORT_SYMBOL(tty_pair_get_pty);
/*
* Split this up, as gcc can choke on it otherwise..
*/
long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct tty_struct *tty, *real_tty;
void __user *p = (void __user *)arg;
int retval;
struct tty_ldisc *ld;
struct inode *inode = file->f_dentry->d_inode;
tty = (struct tty_struct *)file->private_data;
if (tty_paranoia_check(tty, inode, "tty_ioctl"))
return -EINVAL;
real_tty = tty_pair_get_tty(tty);
/*
* Factor out some common prep work
*/
switch (cmd) {
case TIOCSETD:
case TIOCSBRK:
case TIOCCBRK:
case TCSBRK:
case TCSBRKP:
retval = tty_check_change(tty);
if (retval)
return retval;
if (cmd != TIOCCBRK) {
tty_wait_until_sent(tty, 0);
if (signal_pending(current))
return -EINTR;
}
break;
}
/*
* Now do the stuff.
*/
switch (cmd) {
case TIOCSTI:
return tiocsti(tty, p);
case TIOCGWINSZ:
return tiocgwinsz(real_tty, p);
case TIOCSWINSZ:
return tiocswinsz(real_tty, p);
case TIOCCONS:
return real_tty != tty ? -EINVAL : tioccons(file);
case FIONBIO:
return fionbio(file, p);
case TIOCEXCL:
set_bit(TTY_EXCLUSIVE, &tty->flags);
return 0;
case TIOCNXCL:
clear_bit(TTY_EXCLUSIVE, &tty->flags);
return 0;
case TIOCNOTTY:
if (current->signal->tty != tty)
return -ENOTTY;
no_tty();
return 0;
case TIOCSCTTY:
return tiocsctty(tty, arg);
case TIOCGPGRP:
return tiocgpgrp(tty, real_tty, p);
case TIOCSPGRP:
return tiocspgrp(tty, real_tty, p);
case TIOCGSID:
return tiocgsid(tty, real_tty, p);
case TIOCGETD:
return put_user(tty->ldisc->ops->num, (int __user *)p);
case TIOCSETD:
return tiocsetd(tty, p);
/*
* Break handling
*/
case TIOCSBRK: /* Turn break on, unconditionally */
if (tty->ops->break_ctl)
return tty->ops->break_ctl(tty, -1);
return 0;
case TIOCCBRK: /* Turn break off, unconditionally */
if (tty->ops->break_ctl)
return tty->ops->break_ctl(tty, 0);
return 0;
case TCSBRK: /* SVID version: non-zero arg --> no break */
/* non-zero arg means wait for all output data
* to be sent (performed above) but don't send break.
* This is used by the tcdrain() termios function.
*/
if (!arg)
return send_break(tty, 250);
return 0;
case TCSBRKP: /* support for POSIX tcsendbreak() */
return send_break(tty, arg ? arg*100 : 250);
case TIOCMGET:
return tty_tiocmget(tty, file, p);
case TIOCMSET:
case TIOCMBIC:
case TIOCMBIS:
return tty_tiocmset(tty, file, cmd, p);
case TCFLSH:
switch (arg) {
case TCIFLUSH:
case TCIOFLUSH:
/* flush tty buffer and allow ldisc to process ioctl */
tty_buffer_flush(tty);
break;
}
break;
}
if (tty->ops->ioctl) {
retval = (tty->ops->ioctl)(tty, file, cmd, arg);
if (retval != -ENOIOCTLCMD)
return retval;
}
ld = tty_ldisc_ref_wait(tty);
retval = -EINVAL;
if (ld->ops->ioctl) {
retval = ld->ops->ioctl(tty, file, cmd, arg);
if (retval == -ENOIOCTLCMD)
retval = -EINVAL;
}
tty_ldisc_deref(ld);
return retval;
}
#ifdef CONFIG_COMPAT
static long tty_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct inode *inode = file->f_dentry->d_inode;
struct tty_struct *tty = file->private_data;
struct tty_ldisc *ld;
int retval = -ENOIOCTLCMD;
if (tty_paranoia_check(tty, inode, "tty_ioctl"))
return -EINVAL;
if (tty->ops->compat_ioctl) {
retval = (tty->ops->compat_ioctl)(tty, file, cmd, arg);
if (retval != -ENOIOCTLCMD)
return retval;
}
ld = tty_ldisc_ref_wait(tty);
if (ld->ops->compat_ioctl)
retval = ld->ops->compat_ioctl(tty, file, cmd, arg);
tty_ldisc_deref(ld);
return retval;
}
#endif
/*
* This implements the "Secure Attention Key" --- the idea is to
* prevent trojan horses by killing all processes associated with this
* tty when the user hits the "Secure Attention Key". Required for
* super-paranoid applications --- see the Orange Book for more details.
*
* This code could be nicer; ideally it should send a HUP, wait a few
* seconds, then send a INT, and then a KILL signal. But you then
* have to coordinate with the init process, since all processes associated
* with the current tty must be dead before the new getty is allowed
* to spawn.
*
* Now, if it would be correct ;-/ The current code has a nasty hole -
* it doesn't catch files in flight. We may send the descriptor to ourselves
* via AF_UNIX socket, close it and later fetch from socket. FIXME.
*
* Nasty bug: do_SAK is being called in interrupt context. This can
* deadlock. We punt it up to process context. AKPM - 16Mar2001
*/
void __do_SAK(struct tty_struct *tty)
{
#ifdef TTY_SOFT_SAK
tty_hangup(tty);
#else
struct task_struct *g, *p;
struct pid *session;
int i;
struct file *filp;
struct fdtable *fdt;
if (!tty)
return;
session = tty->session;
tty_ldisc_flush(tty);
tty_driver_flush_buffer(tty);
read_lock(&tasklist_lock);
/* Kill the entire session */
do_each_pid_task(session, PIDTYPE_SID, p) {
printk(KERN_NOTICE "SAK: killed process %d"
" (%s): task_session(p)==tty->session\n",
task_pid_nr(p), p->comm);
send_sig(SIGKILL, p, 1);
} while_each_pid_task(session, PIDTYPE_SID, p);
/* Now kill any processes that happen to have the
* tty open.
*/
do_each_thread(g, p) {
if (p->signal->tty == tty) {
printk(KERN_NOTICE "SAK: killed process %d"
" (%s): task_session(p)==tty->session\n",
task_pid_nr(p), p->comm);
send_sig(SIGKILL, p, 1);
continue;
}
task_lock(p);
if (p->files) {
/*
* We don't take a ref to the file, so we must
* hold ->file_lock instead.
*/
spin_lock(&p->files->file_lock);
fdt = files_fdtable(p->files);
for (i = 0; i < fdt->max_fds; i++) {
filp = fcheck_files(p->files, i);
if (!filp)
continue;
if (filp->f_op->read == tty_read &&
filp->private_data == tty) {
printk(KERN_NOTICE "SAK: killed process %d"
" (%s): fd#%d opened to the tty\n",
task_pid_nr(p), p->comm, i);
force_sig(SIGKILL, p);
break;
}
}
spin_unlock(&p->files->file_lock);
}
task_unlock(p);
} while_each_thread(g, p);
read_unlock(&tasklist_lock);
#endif
}
static void do_SAK_work(struct work_struct *work)
{
struct tty_struct *tty =
container_of(work, struct tty_struct, SAK_work);
__do_SAK(tty);
}
/*
* The tq handling here is a little racy - tty->SAK_work may already be queued.
* Fortunately we don't need to worry, because if ->SAK_work is already queued,
* the values which we write to it will be identical to the values which it
* already has. --akpm
*/
void do_SAK(struct tty_struct *tty)
{
if (!tty)
return;
schedule_work(&tty->SAK_work);
}
EXPORT_SYMBOL(do_SAK);
/**
* initialize_tty_struct
* @tty: tty to initialize
*
* This subroutine initializes a tty structure that has been newly
* allocated.
*
* Locking: none - tty in question must not be exposed at this point
*/
void initialize_tty_struct(struct tty_struct *tty,
struct tty_driver *driver, int idx)
{
memset(tty, 0, sizeof(struct tty_struct));
kref_init(&tty->kref);
tty->magic = TTY_MAGIC;
tty_ldisc_init(tty);
tty->session = NULL;
tty->pgrp = NULL;
tty->overrun_time = jiffies;
tty->buf.head = tty->buf.tail = NULL;
tty_buffer_init(tty);
mutex_init(&tty->termios_mutex);
mutex_init(&tty->ldisc_mutex);
init_waitqueue_head(&tty->write_wait);
init_waitqueue_head(&tty->read_wait);
INIT_WORK(&tty->hangup_work, do_tty_hangup);
mutex_init(&tty->atomic_read_lock);
mutex_init(&tty->atomic_write_lock);
mutex_init(&tty->output_lock);
mutex_init(&tty->echo_lock);
spin_lock_init(&tty->read_lock);
spin_lock_init(&tty->ctrl_lock);
INIT_LIST_HEAD(&tty->tty_files);
INIT_WORK(&tty->SAK_work, do_SAK_work);
tty->driver = driver;
tty->ops = driver->ops;
tty->index = idx;
tty_line_name(driver, idx, tty->name);
}
/**
* tty_put_char - write one character to a tty
* @tty: tty
* @ch: character
*
* Write one byte to the tty using the provided put_char method
* if present. Returns the number of characters successfully output.
*
* Note: the specific put_char operation in the driver layer may go
* away soon. Don't call it directly, use this method
*/
int tty_put_char(struct tty_struct *tty, unsigned char ch)
{
if (tty->ops->put_char)
return tty->ops->put_char(tty, ch);
return tty->ops->write(tty, &ch, 1);
}
EXPORT_SYMBOL_GPL(tty_put_char);
struct class *tty_class;
/**
* tty_register_device - register a tty device
* @driver: the tty driver that describes the tty device
* @index: the index in the tty driver for this tty device
* @device: a struct device that is associated with this tty device.
* This field is optional, if there is no known struct device
* for this tty device it can be set to NULL safely.
*
* Returns a pointer to the struct device for this tty device
* (or ERR_PTR(-EFOO) on error).
*
* This call is required to be made to register an individual tty device
* if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set. If
* that bit is not set, this function should not be called by a tty
* driver.
*
* Locking: ??
*/
struct device *tty_register_device(struct tty_driver *driver, unsigned index,
struct device *device)
{
char name[64];
dev_t dev = MKDEV(driver->major, driver->minor_start) + index;
if (index >= driver->num) {
printk(KERN_ERR "Attempt to register invalid tty line number "
" (%d).\n", index);
return ERR_PTR(-EINVAL);
}
if (driver->type == TTY_DRIVER_TYPE_PTY)
pty_line_name(driver, index, name);
else
tty_line_name(driver, index, name);
return device_create(tty_class, device, dev, NULL, name);
}
EXPORT_SYMBOL(tty_register_device);
/**
* tty_unregister_device - unregister a tty device
* @driver: the tty driver that describes the tty device
* @index: the index in the tty driver for this tty device
*
* If a tty device is registered with a call to tty_register_device() then
* this function must be called when the tty device is gone.
*
* Locking: ??
*/
void tty_unregister_device(struct tty_driver *driver, unsigned index)
{
device_destroy(tty_class,
MKDEV(driver->major, driver->minor_start) + index);
}
EXPORT_SYMBOL(tty_unregister_device);
struct tty_driver *alloc_tty_driver(int lines)
{
struct tty_driver *driver;
driver = kzalloc(sizeof(struct tty_driver), GFP_KERNEL);
if (driver) {
kref_init(&driver->kref);
driver->magic = TTY_DRIVER_MAGIC;
driver->num = lines;
/* later we'll move allocation of tables here */
}
return driver;
}
EXPORT_SYMBOL(alloc_tty_driver);
static void destruct_tty_driver(struct kref *kref)
{
struct tty_driver *driver = container_of(kref, struct tty_driver, kref);
int i;
struct ktermios *tp;
void *p;
if (driver->flags & TTY_DRIVER_INSTALLED) {
/*
* Free the termios and termios_locked structures because
* we don't want to get memory leaks when modular tty
* drivers are removed from the kernel.
*/
for (i = 0; i < driver->num; i++) {
tp = driver->termios[i];
if (tp) {
driver->termios[i] = NULL;
kfree(tp);
}
if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV))
tty_unregister_device(driver, i);
}
p = driver->ttys;
proc_tty_unregister_driver(driver);
driver->ttys = NULL;
driver->termios = NULL;
kfree(p);
cdev_del(&driver->cdev);
}
kfree(driver);
}
void tty_driver_kref_put(struct tty_driver *driver)
{
kref_put(&driver->kref, destruct_tty_driver);
}
EXPORT_SYMBOL(tty_driver_kref_put);
void tty_set_operations(struct tty_driver *driver,
const struct tty_operations *op)
{
driver->ops = op;
};
EXPORT_SYMBOL(tty_set_operations);
void put_tty_driver(struct tty_driver *d)
{
tty_driver_kref_put(d);
}
EXPORT_SYMBOL(put_tty_driver);
/*
* Called by a tty driver to register itself.
*/
int tty_register_driver(struct tty_driver *driver)
{
int error;
int i;
dev_t dev;
void **p = NULL;
if (!(driver->flags & TTY_DRIVER_DEVPTS_MEM) && driver->num) {
p = kzalloc(driver->num * 2 * sizeof(void *), GFP_KERNEL);
if (!p)
return -ENOMEM;
}
if (!driver->major) {
error = alloc_chrdev_region(&dev, driver->minor_start,
driver->num, driver->name);
if (!error) {
driver->major = MAJOR(dev);
driver->minor_start = MINOR(dev);
}
} else {
dev = MKDEV(driver->major, driver->minor_start);
error = register_chrdev_region(dev, driver->num, driver->name);
}
if (error < 0) {
kfree(p);
return error;
}
if (p) {
driver->ttys = (struct tty_struct **)p;
driver->termios = (struct ktermios **)(p + driver->num);
} else {
driver->ttys = NULL;
driver->termios = NULL;
}
cdev_init(&driver->cdev, &tty_fops);
driver->cdev.owner = driver->owner;
error = cdev_add(&driver->cdev, dev, driver->num);
if (error) {
unregister_chrdev_region(dev, driver->num);
driver->ttys = NULL;
driver->termios = NULL;
kfree(p);
return error;
}
mutex_lock(&tty_mutex);
list_add(&driver->tty_drivers, &tty_drivers);
mutex_unlock(&tty_mutex);
if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV)) {
for (i = 0; i < driver->num; i++)
tty_register_device(driver, i, NULL);
}
proc_tty_register_driver(driver);
driver->flags |= TTY_DRIVER_INSTALLED;
return 0;
}
EXPORT_SYMBOL(tty_register_driver);
/*
* Called by a tty driver to unregister itself.
*/
int tty_unregister_driver(struct tty_driver *driver)
{
#if 0
/* FIXME */
if (driver->refcount)
return -EBUSY;
#endif
unregister_chrdev_region(MKDEV(driver->major, driver->minor_start),
driver->num);
mutex_lock(&tty_mutex);
list_del(&driver->tty_drivers);
mutex_unlock(&tty_mutex);
return 0;
}
EXPORT_SYMBOL(tty_unregister_driver);
dev_t tty_devnum(struct tty_struct *tty)
{
return MKDEV(tty->driver->major, tty->driver->minor_start) + tty->index;
}
EXPORT_SYMBOL(tty_devnum);
void proc_clear_tty(struct task_struct *p)
{
unsigned long flags;
struct tty_struct *tty;
spin_lock_irqsave(&p->sighand->siglock, flags);
tty = p->signal->tty;
p->signal->tty = NULL;
spin_unlock_irqrestore(&p->sighand->siglock, flags);
tty_kref_put(tty);
}
/* Called under the sighand lock */
static void __proc_set_tty(struct task_struct *tsk, struct tty_struct *tty)
{
if (tty) {
unsigned long flags;
/* We should not have a session or pgrp to put here but.... */
spin_lock_irqsave(&tty->ctrl_lock, flags);
put_pid(tty->session);
put_pid(tty->pgrp);
tty->pgrp = get_pid(task_pgrp(tsk));
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
tty->session = get_pid(task_session(tsk));
if (tsk->signal->tty) {
printk(KERN_DEBUG "tty not NULL!!\n");
tty_kref_put(tsk->signal->tty);
}
}
put_pid(tsk->signal->tty_old_pgrp);
tsk->signal->tty = tty_kref_get(tty);
tsk->signal->tty_old_pgrp = NULL;
}
static void proc_set_tty(struct task_struct *tsk, struct tty_struct *tty)
{
spin_lock_irq(&tsk->sighand->siglock);
__proc_set_tty(tsk, tty);
spin_unlock_irq(&tsk->sighand->siglock);
}
struct tty_struct *get_current_tty(void)
{
struct tty_struct *tty;
unsigned long flags;
spin_lock_irqsave(¤t->sighand->siglock, flags);
tty = tty_kref_get(current->signal->tty);
spin_unlock_irqrestore(¤t->sighand->siglock, flags);
return tty;
}
EXPORT_SYMBOL_GPL(get_current_tty);
void tty_default_fops(struct file_operations *fops)
{
*fops = tty_fops;
}
/*
* Initialize the console device. This is called *early*, so
* we can't necessarily depend on lots of kernel help here.
* Just do some early initializations, and do the complex setup
* later.
*/
void __init console_init(void)
{
initcall_t *call;
/* Setup the default TTY line discipline. */
tty_ldisc_begin();
/*
* set up the console device so that later boot sequences can
* inform about problems etc..
*/
call = __con_initcall_start;
while (call < __con_initcall_end) {
(*call)();
call++;
}
}
static char *tty_devnode(struct device *dev, mode_t *mode)
{
if (!mode)
return NULL;
if (dev->devt == MKDEV(TTYAUX_MAJOR, 0) ||
dev->devt == MKDEV(TTYAUX_MAJOR, 2))
*mode = 0666;
return NULL;
}
static int __init tty_class_init(void)
{
tty_class = class_create(THIS_MODULE, "tty");
if (IS_ERR(tty_class))
return PTR_ERR(tty_class);
tty_class->devnode = tty_devnode;
return 0;
}
postcore_initcall(tty_class_init);
/* 3/2004 jmc: why do these devices exist? */
static struct cdev tty_cdev, console_cdev;
/*
* Ok, now we can initialize the rest of the tty devices and can count
* on memory allocations, interrupts etc..
*/
int __init tty_init(void)
{
cdev_init(&tty_cdev, &tty_fops);
if (cdev_add(&tty_cdev, MKDEV(TTYAUX_MAJOR, 0), 1) ||
register_chrdev_region(MKDEV(TTYAUX_MAJOR, 0), 1, "/dev/tty") < 0)
panic("Couldn't register /dev/tty driver\n");
device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 0), NULL,
"tty");
cdev_init(&console_cdev, &console_fops);
if (cdev_add(&console_cdev, MKDEV(TTYAUX_MAJOR, 1), 1) ||
register_chrdev_region(MKDEV(TTYAUX_MAJOR, 1), 1, "/dev/console") < 0)
panic("Couldn't register /dev/console driver\n");
device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 1), NULL,
"console");
#ifdef CONFIG_VT
vty_init(&console_fops);
#endif
return 0;
}
| gpl-2.0 |
novaspirit/tf101-linux-2.6.36 | kernel/kmod.c | 12 | 12130 | /*
kmod, the new module loader (replaces kerneld)
Kirk Petersen
Reorganized not to be a daemon by Adam Richter, with guidance
from Greg Zornetzer.
Modified to avoid chroot and file sharing problems.
Mikael Pettersson
Limit the concurrent number of kmod modprobes to catch loops from
"modprobe needs a service that is in a module".
Keith Owens <kaos@ocs.com.au> December 1999
Unblock all signals when we exec a usermode process.
Shuu Yamaguchi <shuu@wondernetworkresources.com> December 2000
call_usermodehelper wait flag, and remove exec_usermodehelper.
Rusty Russell <rusty@rustcorp.com.au> Jan 2003
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/syscalls.h>
#include <linux/unistd.h>
#include <linux/kmod.h>
#include <linux/slab.h>
#include <linux/completion.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/workqueue.h>
#include <linux/security.h>
#include <linux/mount.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/resource.h>
#include <linux/notifier.h>
#include <linux/suspend.h>
#include <asm/uaccess.h>
#include <trace/events/module.h>
extern int max_threads;
static struct workqueue_struct *khelper_wq;
#ifdef CONFIG_MODULES
/*
modprobe_path is set via /proc/sys.
*/
char modprobe_path[KMOD_PATH_LEN] = "/sbin/modprobe";
/**
* __request_module - try to load a kernel module
* @wait: wait (or not) for the operation to complete
* @fmt: printf style format string for the name of the module
* @...: arguments as specified in the format string
*
* Load a module using the user mode module loader. The function returns
* zero on success or a negative errno code on failure. Note that a
* successful module load does not mean the module did not then unload
* and exit on an error of its own. Callers must check that the service
* they requested is now available not blindly invoke it.
*
* If module auto-loading support is disabled then this function
* becomes a no-operation.
*/
int __request_module(bool wait, const char *fmt, ...)
{
va_list args;
char module_name[MODULE_NAME_LEN];
unsigned int max_modprobes;
int ret;
char *argv[] = { modprobe_path, "-q", "--", module_name, NULL };
static char *envp[] = { "HOME=/",
"TERM=linux",
"PATH=/sbin:/usr/sbin:/bin:/usr/bin",
NULL };
static atomic_t kmod_concurrent = ATOMIC_INIT(0);
#define MAX_KMOD_CONCURRENT 50 /* Completely arbitrary value - KAO */
static int kmod_loop_msg;
va_start(args, fmt);
ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
va_end(args);
if (ret >= MODULE_NAME_LEN)
return -ENAMETOOLONG;
ret = security_kernel_module_request(module_name);
if (ret)
return ret;
/* If modprobe needs a service that is in a module, we get a recursive
* loop. Limit the number of running kmod threads to max_threads/2 or
* MAX_KMOD_CONCURRENT, whichever is the smaller. A cleaner method
* would be to run the parents of this process, counting how many times
* kmod was invoked. That would mean accessing the internals of the
* process tables to get the command line, proc_pid_cmdline is static
* and it is not worth changing the proc code just to handle this case.
* KAO.
*
* "trace the ppid" is simple, but will fail if someone's
* parent exits. I think this is as good as it gets. --RR
*/
max_modprobes = min(max_threads/2, MAX_KMOD_CONCURRENT);
atomic_inc(&kmod_concurrent);
if (atomic_read(&kmod_concurrent) > max_modprobes) {
/* We may be blaming an innocent here, but unlikely */
if (kmod_loop_msg++ < 5)
printk(KERN_ERR
"request_module: runaway loop modprobe %s\n",
module_name);
atomic_dec(&kmod_concurrent);
return -ENOMEM;
}
trace_module_request(module_name, wait, _RET_IP_);
ret = call_usermodehelper_fns(modprobe_path, argv, envp,
wait ? UMH_WAIT_PROC : UMH_WAIT_EXEC,
NULL, NULL, NULL);
atomic_dec(&kmod_concurrent);
return ret;
}
EXPORT_SYMBOL(__request_module);
#endif /* CONFIG_MODULES */
/*
* This is the task which runs the usermode application
*/
static int ____call_usermodehelper(void *data)
{
struct subprocess_info *sub_info = data;
int retval;
spin_lock_irq(¤t->sighand->siglock);
flush_signal_handlers(current, 1);
spin_unlock_irq(¤t->sighand->siglock);
/* We can run anywhere, unlike our parent keventd(). */
set_cpus_allowed_ptr(current, cpu_all_mask);
/*
* Our parent is keventd, which runs with elevated scheduling priority.
* Avoid propagating that into the userspace child.
*/
set_user_nice(current, 0);
if (sub_info->init) {
retval = sub_info->init(sub_info);
if (retval)
goto fail;
}
retval = kernel_execve(sub_info->path,
(const char *const *)sub_info->argv,
(const char *const *)sub_info->envp);
/* Exec failed? */
fail:
sub_info->retval = retval;
do_exit(0);
}
void call_usermodehelper_freeinfo(struct subprocess_info *info)
{
if (info->cleanup)
(*info->cleanup)(info);
kfree(info);
}
EXPORT_SYMBOL(call_usermodehelper_freeinfo);
/* Keventd can't block, but this (a child) can. */
static int wait_for_helper(void *data)
{
struct subprocess_info *sub_info = data;
pid_t pid;
/* If SIGCLD is ignored sys_wait4 won't populate the status. */
spin_lock_irq(¤t->sighand->siglock);
current->sighand->action[SIGCHLD-1].sa.sa_handler = SIG_DFL;
spin_unlock_irq(¤t->sighand->siglock);
pid = kernel_thread(____call_usermodehelper, sub_info, SIGCHLD);
if (pid < 0) {
sub_info->retval = pid;
} else {
int ret = -ECHILD;
/*
* Normally it is bogus to call wait4() from in-kernel because
* wait4() wants to write the exit code to a userspace address.
* But wait_for_helper() always runs as keventd, and put_user()
* to a kernel address works OK for kernel threads, due to their
* having an mm_segment_t which spans the entire address space.
*
* Thus the __user pointer cast is valid here.
*/
sys_wait4(pid, (int __user *)&ret, 0, NULL);
/*
* If ret is 0, either ____call_usermodehelper failed and the
* real error code is already in sub_info->retval or
* sub_info->retval is 0 anyway, so don't mess with it then.
*/
if (ret)
sub_info->retval = ret;
}
complete(sub_info->complete);
return 0;
}
/* This is run by khelper thread */
static void __call_usermodehelper(struct work_struct *work)
{
struct subprocess_info *sub_info =
container_of(work, struct subprocess_info, work);
enum umh_wait wait = sub_info->wait;
pid_t pid;
/* CLONE_VFORK: wait until the usermode helper has execve'd
* successfully We need the data structures to stay around
* until that is done. */
if (wait == UMH_WAIT_PROC)
pid = kernel_thread(wait_for_helper, sub_info,
CLONE_FS | CLONE_FILES | SIGCHLD);
else
pid = kernel_thread(____call_usermodehelper, sub_info,
CLONE_VFORK | SIGCHLD);
switch (wait) {
case UMH_NO_WAIT:
call_usermodehelper_freeinfo(sub_info);
break;
case UMH_WAIT_PROC:
if (pid > 0)
break;
/* FALLTHROUGH */
case UMH_WAIT_EXEC:
if (pid < 0)
sub_info->retval = pid;
complete(sub_info->complete);
}
}
#ifdef CONFIG_PM_SLEEP
/*
* If set, call_usermodehelper_exec() will exit immediately returning -EBUSY
* (used for preventing user land processes from being created after the user
* land has been frozen during a system-wide hibernation or suspend operation).
*/
static int usermodehelper_disabled;
/* Number of helpers running */
static atomic_t running_helpers = ATOMIC_INIT(0);
/*
* Wait queue head used by usermodehelper_pm_callback() to wait for all running
* helpers to finish.
*/
static DECLARE_WAIT_QUEUE_HEAD(running_helpers_waitq);
/*
* Time to wait for running_helpers to become zero before the setting of
* usermodehelper_disabled in usermodehelper_pm_callback() fails
*/
#define RUNNING_HELPERS_TIMEOUT (5 * HZ)
/**
* usermodehelper_disable - prevent new helpers from being started
*/
int usermodehelper_disable(void)
{
long retval;
usermodehelper_disabled = 1;
smp_mb();
printk("u_d+\n");
/*
* From now on call_usermodehelper_exec() won't start any new
* helpers, so it is sufficient if running_helpers turns out to
* be zero at one point (it may be increased later, but that
* doesn't matter).
*/
retval = wait_event_timeout(running_helpers_waitq,
atomic_read(&running_helpers) == 0,
RUNNING_HELPERS_TIMEOUT);
printk("u_d-\n");
if (retval)
return 0;
usermodehelper_disabled = 0;
return -EAGAIN;
}
/**
* usermodehelper_enable - allow new helpers to be started again
*/
void usermodehelper_enable(void)
{
usermodehelper_disabled = 0;
}
static void helper_lock(void)
{
atomic_inc(&running_helpers);
smp_mb__after_atomic_inc();
}
static void helper_unlock(void)
{
if (atomic_dec_and_test(&running_helpers))
wake_up(&running_helpers_waitq);
}
#else /* CONFIG_PM_SLEEP */
#define usermodehelper_disabled 0
static inline void helper_lock(void) {}
static inline void helper_unlock(void) {}
#endif /* CONFIG_PM_SLEEP */
/**
* call_usermodehelper_setup - prepare to call a usermode helper
* @path: path to usermode executable
* @argv: arg vector for process
* @envp: environment for process
* @gfp_mask: gfp mask for memory allocation
*
* Returns either %NULL on allocation failure, or a subprocess_info
* structure. This should be passed to call_usermodehelper_exec to
* exec the process and free the structure.
*/
struct subprocess_info *call_usermodehelper_setup(char *path, char **argv,
char **envp, gfp_t gfp_mask)
{
struct subprocess_info *sub_info;
sub_info = kzalloc(sizeof(struct subprocess_info), gfp_mask);
if (!sub_info)
goto out;
INIT_WORK(&sub_info->work, __call_usermodehelper);
sub_info->path = path;
sub_info->argv = argv;
sub_info->envp = envp;
out:
return sub_info;
}
EXPORT_SYMBOL(call_usermodehelper_setup);
/**
* call_usermodehelper_setfns - set a cleanup/init function
* @info: a subprocess_info returned by call_usermodehelper_setup
* @cleanup: a cleanup function
* @init: an init function
* @data: arbitrary context sensitive data
*
* The init function is used to customize the helper process prior to
* exec. A non-zero return code causes the process to error out, exit,
* and return the failure to the calling process
*
* The cleanup function is just before ethe subprocess_info is about to
* be freed. This can be used for freeing the argv and envp. The
* Function must be runnable in either a process context or the
* context in which call_usermodehelper_exec is called.
*/
void call_usermodehelper_setfns(struct subprocess_info *info,
int (*init)(struct subprocess_info *info),
void (*cleanup)(struct subprocess_info *info),
void *data)
{
info->cleanup = cleanup;
info->init = init;
info->data = data;
}
EXPORT_SYMBOL(call_usermodehelper_setfns);
/**
* call_usermodehelper_exec - start a usermode application
* @sub_info: information about the subprocessa
* @wait: wait for the application to finish and return status.
* when -1 don't wait at all, but you get no useful error back when
* the program couldn't be exec'ed. This makes it safe to call
* from interrupt context.
*
* Runs a user-space application. The application is started
* asynchronously if wait is not set, and runs as a child of keventd.
* (ie. it runs with full root capabilities).
*/
int call_usermodehelper_exec(struct subprocess_info *sub_info,
enum umh_wait wait)
{
DECLARE_COMPLETION_ONSTACK(done);
int retval = 0;
helper_lock();
if (sub_info->path[0] == '\0')
goto out;
if (!khelper_wq || usermodehelper_disabled) {
retval = -EBUSY;
goto out;
}
sub_info->complete = &done;
sub_info->wait = wait;
queue_work(khelper_wq, &sub_info->work);
if (wait == UMH_NO_WAIT) /* task has freed sub_info */
goto unlock;
wait_for_completion(&done);
retval = sub_info->retval;
out:
call_usermodehelper_freeinfo(sub_info);
unlock:
helper_unlock();
return retval;
}
EXPORT_SYMBOL(call_usermodehelper_exec);
void __init usermodehelper_init(void)
{
khelper_wq = create_singlethread_workqueue("khelper");
BUG_ON(!khelper_wq);
}
| gpl-2.0 |
supergis/QGIS | src/gui/editorwidgets/qgsuniquevaluesconfigdlg.cpp | 12 | 1468 | /***************************************************************************
qgsuniquevaluesconfigdlg.cpp
--------------------------------------
Date : 5.1.2014
Copyright : (C) 2014 Matthias Kuhn
Email : matthias at opengis dot ch
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsuniquevaluesconfigdlg.h"
QgsUniqueValuesConfigDlg::QgsUniqueValuesConfigDlg( QgsVectorLayer* vl, int fieldIdx, QWidget *parent ) :
QgsEditorConfigWidget( vl, fieldIdx, parent )
{
setupUi( this );
}
QgsEditorWidgetConfig QgsUniqueValuesConfigDlg::config()
{
QgsEditorWidgetConfig cfg;
cfg.insert( "Editable", editableUniqueValues->isChecked() );
return cfg;
}
void QgsUniqueValuesConfigDlg::setConfig( const QgsEditorWidgetConfig& config )
{
editableUniqueValues->setChecked( config.value( "Editable", false ).toBool() );
}
| gpl-2.0 |
GalaxyTab4/bliss_kernel_samsung_millet | drivers/media/platform/msm/camera_v2/sensor/s5k6b2yx.c | 268 | 2995 | /* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "msm_sensor.h"
#define S5K6B2YX_SENSOR_NAME "s5k6b2yx"
DEFINE_MSM_MUTEX(s5k6b2yx_mut);
static struct msm_sensor_ctrl_t s5k6b2yx_s_ctrl;
static struct v4l2_subdev_info s5k6b2yx_subdev_info[] = {
{
.code = V4L2_MBUS_FMT_SBGGR10_1X10,
.colorspace = V4L2_COLORSPACE_JPEG,
.fmt = 1,
.order = 0,
},
};
static const struct i2c_device_id s5k6b2yx_i2c_id[] = {
{S5K6B2YX_SENSOR_NAME, (kernel_ulong_t)&s5k6b2yx_s_ctrl},
{ }
};
static int32_t msm_s5k6b2yx_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
return msm_sensor_i2c_probe(client, id, &s5k6b2yx_s_ctrl);
}
static struct i2c_driver s5k6b2yx_i2c_driver = {
.id_table = s5k6b2yx_i2c_id,
.probe = msm_s5k6b2yx_i2c_probe,
.driver = {
.name = S5K6B2YX_SENSOR_NAME,
},
};
static struct msm_camera_i2c_client s5k6b2yx_sensor_i2c_client = {
.addr_type = MSM_CAMERA_I2C_WORD_ADDR,
};
static const struct of_device_id s5k6b2yx_dt_match[] = {
{.compatible = "qcom,s5k6b2yx", .data = &s5k6b2yx_s_ctrl},
{}
};
MODULE_DEVICE_TABLE(of, s5k6b2yx_dt_match);
static struct platform_driver s5k6b2yx_platform_driver = {
.driver = {
.name = "qcom,s5k6b2yx",
.owner = THIS_MODULE,
.of_match_table = s5k6b2yx_dt_match,
},
};
static int32_t s5k6b2yx_platform_probe(struct platform_device *pdev)
{
int32_t rc = 0;
const struct of_device_id *match;
match = of_match_device(s5k6b2yx_dt_match, &pdev->dev);
rc = msm_sensor_platform_probe(pdev, match->data);
return rc;
}
static int __init s5k6b2yx_init_module(void)
{
int32_t rc = 0;
pr_info("%s:%d\n", __func__, __LINE__);
rc = platform_driver_probe(&s5k6b2yx_platform_driver,
s5k6b2yx_platform_probe);
if (!rc)
return rc;
pr_err("%s:%d rc %d\n", __func__, __LINE__, rc);
return i2c_add_driver(&s5k6b2yx_i2c_driver);
}
static void __exit s5k6b2yx_exit_module(void)
{
pr_info("%s:%d\n", __func__, __LINE__);
if (s5k6b2yx_s_ctrl.pdev) {
msm_sensor_free_sensor_data(&s5k6b2yx_s_ctrl);
platform_driver_unregister(&s5k6b2yx_platform_driver);
} else
i2c_del_driver(&s5k6b2yx_i2c_driver);
return;
}
static struct msm_sensor_ctrl_t s5k6b2yx_s_ctrl = {
.sensor_i2c_client = &s5k6b2yx_sensor_i2c_client,
.msm_sensor_mutex = &s5k6b2yx_mut,
.sensor_v4l2_subdev_info = s5k6b2yx_subdev_info,
.sensor_v4l2_subdev_info_size = ARRAY_SIZE(s5k6b2yx_subdev_info),
};
module_init(s5k6b2yx_init_module);
module_exit(s5k6b2yx_exit_module);
MODULE_DESCRIPTION("s5k6b2yx");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
shuiziliuBUPT/linuxkernel | drivers/gpu/drm/omapdrm/omap_plane.c | 268 | 11791 | /*
* drivers/gpu/drm/omapdrm/omap_plane.c
*
* Copyright (C) 2011 Texas Instruments
* Author: Rob Clark <rob.clark@linaro.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.
*
* 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 "drm_flip_work.h"
#include "omap_drv.h"
#include "omap_dmm_tiler.h"
/* some hackery because omapdss has an 'enum omap_plane' (which would be
* better named omap_plane_id).. and compiler seems unhappy about having
* both a 'struct omap_plane' and 'enum omap_plane'
*/
#define omap_plane _omap_plane
/*
* plane funcs
*/
struct callback {
void (*fxn)(void *);
void *arg;
};
#define to_omap_plane(x) container_of(x, struct omap_plane, base)
struct omap_plane {
struct drm_plane base;
int id; /* TODO rename omap_plane -> omap_plane_id in omapdss so I can use the enum */
const char *name;
struct omap_overlay_info info;
struct omap_drm_apply apply;
/* position/orientation of scanout within the fb: */
struct omap_drm_window win;
bool enabled;
/* last fb that we pinned: */
struct drm_framebuffer *pinned_fb;
uint32_t nformats;
uint32_t formats[32];
struct omap_drm_irq error_irq;
/* for deferring bo unpin's until next post_apply(): */
struct drm_flip_work unpin_work;
// XXX maybe get rid of this and handle vblank in crtc too?
struct callback apply_done_cb;
};
static void unpin_worker(struct drm_flip_work *work, void *val)
{
struct omap_plane *omap_plane =
container_of(work, struct omap_plane, unpin_work);
struct drm_device *dev = omap_plane->base.dev;
omap_framebuffer_unpin(val);
mutex_lock(&dev->mode_config.mutex);
drm_framebuffer_unreference(val);
mutex_unlock(&dev->mode_config.mutex);
}
/* update which fb (if any) is pinned for scanout */
static int update_pin(struct drm_plane *plane, struct drm_framebuffer *fb)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
struct drm_framebuffer *pinned_fb = omap_plane->pinned_fb;
if (pinned_fb != fb) {
int ret = 0;
DBG("%p -> %p", pinned_fb, fb);
if (fb) {
drm_framebuffer_reference(fb);
ret = omap_framebuffer_pin(fb);
}
if (pinned_fb)
drm_flip_work_queue(&omap_plane->unpin_work, pinned_fb);
if (ret) {
dev_err(plane->dev->dev, "could not swap %p -> %p\n",
omap_plane->pinned_fb, fb);
drm_framebuffer_unreference(fb);
omap_plane->pinned_fb = NULL;
return ret;
}
omap_plane->pinned_fb = fb;
}
return 0;
}
static void omap_plane_pre_apply(struct omap_drm_apply *apply)
{
struct omap_plane *omap_plane =
container_of(apply, struct omap_plane, apply);
struct omap_drm_window *win = &omap_plane->win;
struct drm_plane *plane = &omap_plane->base;
struct drm_device *dev = plane->dev;
struct omap_overlay_info *info = &omap_plane->info;
struct drm_crtc *crtc = plane->crtc;
enum omap_channel channel;
bool enabled = omap_plane->enabled && crtc;
bool ilace, replication;
int ret;
DBG("%s, enabled=%d", omap_plane->name, enabled);
/* if fb has changed, pin new fb: */
update_pin(plane, enabled ? plane->fb : NULL);
if (!enabled) {
dispc_ovl_enable(omap_plane->id, false);
return;
}
channel = omap_crtc_channel(crtc);
/* update scanout: */
omap_framebuffer_update_scanout(plane->fb, win, info);
DBG("%dx%d -> %dx%d (%d)", info->width, info->height,
info->out_width, info->out_height,
info->screen_width);
DBG("%d,%d %08x %08x", info->pos_x, info->pos_y,
info->paddr, info->p_uv_addr);
/* TODO: */
ilace = false;
replication = false;
/* and finally, update omapdss: */
ret = dispc_ovl_setup(omap_plane->id, info,
replication, omap_crtc_timings(crtc), false);
if (ret) {
dev_err(dev->dev, "dispc_ovl_setup failed: %d\n", ret);
return;
}
dispc_ovl_enable(omap_plane->id, true);
dispc_ovl_set_channel_out(omap_plane->id, channel);
}
static void omap_plane_post_apply(struct omap_drm_apply *apply)
{
struct omap_plane *omap_plane =
container_of(apply, struct omap_plane, apply);
struct drm_plane *plane = &omap_plane->base;
struct omap_drm_private *priv = plane->dev->dev_private;
struct omap_overlay_info *info = &omap_plane->info;
struct callback cb;
cb = omap_plane->apply_done_cb;
omap_plane->apply_done_cb.fxn = NULL;
drm_flip_work_commit(&omap_plane->unpin_work, priv->wq);
if (cb.fxn)
cb.fxn(cb.arg);
if (omap_plane->enabled) {
omap_framebuffer_flush(plane->fb, info->pos_x, info->pos_y,
info->out_width, info->out_height);
}
}
static int apply(struct drm_plane *plane)
{
if (plane->crtc) {
struct omap_plane *omap_plane = to_omap_plane(plane);
return omap_crtc_apply(plane->crtc, &omap_plane->apply);
}
return 0;
}
int omap_plane_mode_set(struct drm_plane *plane,
struct drm_crtc *crtc, struct drm_framebuffer *fb,
int crtc_x, int crtc_y,
unsigned int crtc_w, unsigned int crtc_h,
uint32_t src_x, uint32_t src_y,
uint32_t src_w, uint32_t src_h,
void (*fxn)(void *), void *arg)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
struct omap_drm_window *win = &omap_plane->win;
win->crtc_x = crtc_x;
win->crtc_y = crtc_y;
win->crtc_w = crtc_w;
win->crtc_h = crtc_h;
/* src values are in Q16 fixed point, convert to integer: */
win->src_x = src_x >> 16;
win->src_y = src_y >> 16;
win->src_w = src_w >> 16;
win->src_h = src_h >> 16;
if (fxn) {
/* omap_crtc should ensure that a new page flip
* isn't permitted while there is one pending:
*/
BUG_ON(omap_plane->apply_done_cb.fxn);
omap_plane->apply_done_cb.fxn = fxn;
omap_plane->apply_done_cb.arg = arg;
}
plane->fb = fb;
plane->crtc = crtc;
return apply(plane);
}
static int omap_plane_update(struct drm_plane *plane,
struct drm_crtc *crtc, struct drm_framebuffer *fb,
int crtc_x, int crtc_y,
unsigned int crtc_w, unsigned int crtc_h,
uint32_t src_x, uint32_t src_y,
uint32_t src_w, uint32_t src_h)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
omap_plane->enabled = true;
if (plane->fb)
drm_framebuffer_unreference(plane->fb);
drm_framebuffer_reference(fb);
return omap_plane_mode_set(plane, crtc, fb,
crtc_x, crtc_y, crtc_w, crtc_h,
src_x, src_y, src_w, src_h,
NULL, NULL);
}
static int omap_plane_disable(struct drm_plane *plane)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
omap_plane->win.rotation = BIT(DRM_ROTATE_0);
return omap_plane_dpms(plane, DRM_MODE_DPMS_OFF);
}
static void omap_plane_destroy(struct drm_plane *plane)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
DBG("%s", omap_plane->name);
omap_irq_unregister(plane->dev, &omap_plane->error_irq);
omap_plane_disable(plane);
drm_plane_cleanup(plane);
drm_flip_work_cleanup(&omap_plane->unpin_work);
kfree(omap_plane);
}
int omap_plane_dpms(struct drm_plane *plane, int mode)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
bool enabled = (mode == DRM_MODE_DPMS_ON);
int ret = 0;
if (enabled != omap_plane->enabled) {
omap_plane->enabled = enabled;
ret = apply(plane);
}
return ret;
}
/* helper to install properties which are common to planes and crtcs */
void omap_plane_install_properties(struct drm_plane *plane,
struct drm_mode_object *obj)
{
struct drm_device *dev = plane->dev;
struct omap_drm_private *priv = dev->dev_private;
struct drm_property *prop;
if (priv->has_dmm) {
prop = priv->rotation_prop;
if (!prop) {
const struct drm_prop_enum_list props[] = {
{ DRM_ROTATE_0, "rotate-0" },
{ DRM_ROTATE_90, "rotate-90" },
{ DRM_ROTATE_180, "rotate-180" },
{ DRM_ROTATE_270, "rotate-270" },
{ DRM_REFLECT_X, "reflect-x" },
{ DRM_REFLECT_Y, "reflect-y" },
};
prop = drm_property_create_bitmask(dev, 0, "rotation",
props, ARRAY_SIZE(props));
if (prop == NULL)
return;
priv->rotation_prop = prop;
}
drm_object_attach_property(obj, prop, 0);
}
prop = priv->zorder_prop;
if (!prop) {
prop = drm_property_create_range(dev, 0, "zorder", 0, 3);
if (prop == NULL)
return;
priv->zorder_prop = prop;
}
drm_object_attach_property(obj, prop, 0);
}
int omap_plane_set_property(struct drm_plane *plane,
struct drm_property *property, uint64_t val)
{
struct omap_plane *omap_plane = to_omap_plane(plane);
struct omap_drm_private *priv = plane->dev->dev_private;
int ret = -EINVAL;
if (property == priv->rotation_prop) {
DBG("%s: rotation: %02x", omap_plane->name, (uint32_t)val);
omap_plane->win.rotation = val;
ret = apply(plane);
} else if (property == priv->zorder_prop) {
DBG("%s: zorder: %02x", omap_plane->name, (uint32_t)val);
omap_plane->info.zorder = val;
ret = apply(plane);
}
return ret;
}
static const struct drm_plane_funcs omap_plane_funcs = {
.update_plane = omap_plane_update,
.disable_plane = omap_plane_disable,
.destroy = omap_plane_destroy,
.set_property = omap_plane_set_property,
};
static void omap_plane_error_irq(struct omap_drm_irq *irq, uint32_t irqstatus)
{
struct omap_plane *omap_plane =
container_of(irq, struct omap_plane, error_irq);
DRM_ERROR("%s: errors: %08x\n", omap_plane->name, irqstatus);
}
static const char *plane_names[] = {
[OMAP_DSS_GFX] = "gfx",
[OMAP_DSS_VIDEO1] = "vid1",
[OMAP_DSS_VIDEO2] = "vid2",
[OMAP_DSS_VIDEO3] = "vid3",
};
static const uint32_t error_irqs[] = {
[OMAP_DSS_GFX] = DISPC_IRQ_GFX_FIFO_UNDERFLOW,
[OMAP_DSS_VIDEO1] = DISPC_IRQ_VID1_FIFO_UNDERFLOW,
[OMAP_DSS_VIDEO2] = DISPC_IRQ_VID2_FIFO_UNDERFLOW,
[OMAP_DSS_VIDEO3] = DISPC_IRQ_VID3_FIFO_UNDERFLOW,
};
/* initialize plane */
struct drm_plane *omap_plane_init(struct drm_device *dev,
int id, bool private_plane)
{
struct omap_drm_private *priv = dev->dev_private;
struct drm_plane *plane = NULL;
struct omap_plane *omap_plane;
struct omap_overlay_info *info;
int ret;
DBG("%s: priv=%d", plane_names[id], private_plane);
omap_plane = kzalloc(sizeof(*omap_plane), GFP_KERNEL);
if (!omap_plane)
goto fail;
ret = drm_flip_work_init(&omap_plane->unpin_work, 16,
"unpin", unpin_worker);
if (ret) {
dev_err(dev->dev, "could not allocate unpin FIFO\n");
goto fail;
}
omap_plane->nformats = omap_framebuffer_get_formats(
omap_plane->formats, ARRAY_SIZE(omap_plane->formats),
dss_feat_get_supported_color_modes(id));
omap_plane->id = id;
omap_plane->name = plane_names[id];
plane = &omap_plane->base;
omap_plane->apply.pre_apply = omap_plane_pre_apply;
omap_plane->apply.post_apply = omap_plane_post_apply;
omap_plane->error_irq.irqmask = error_irqs[id];
omap_plane->error_irq.irq = omap_plane_error_irq;
omap_irq_register(dev, &omap_plane->error_irq);
drm_plane_init(dev, plane, (1 << priv->num_crtcs) - 1, &omap_plane_funcs,
omap_plane->formats, omap_plane->nformats, private_plane);
omap_plane_install_properties(plane, &plane->base);
/* get our starting configuration, set defaults for parameters
* we don't currently use, etc:
*/
info = &omap_plane->info;
info->rotation_type = OMAP_DSS_ROT_DMA;
info->rotation = OMAP_DSS_ROT_0;
info->global_alpha = 0xff;
info->mirror = 0;
/* Set defaults depending on whether we are a CRTC or overlay
* layer.
* TODO add ioctl to give userspace an API to change this.. this
* will come in a subsequent patch.
*/
if (private_plane)
omap_plane->info.zorder = 0;
else
omap_plane->info.zorder = id;
return plane;
fail:
if (plane)
omap_plane_destroy(plane);
return NULL;
}
| gpl-2.0 |
diegolagoglez/git | hashmap.c | 268 | 6447 | /*
* Generic implementation of hash-based key value mappings.
*/
#include "cache.h"
#include "hashmap.h"
#define FNV32_BASE ((unsigned int) 0x811c9dc5)
#define FNV32_PRIME ((unsigned int) 0x01000193)
unsigned int strhash(const char *str)
{
unsigned int c, hash = FNV32_BASE;
while ((c = (unsigned char) *str++))
hash = (hash * FNV32_PRIME) ^ c;
return hash;
}
unsigned int strihash(const char *str)
{
unsigned int c, hash = FNV32_BASE;
while ((c = (unsigned char) *str++)) {
if (c >= 'a' && c <= 'z')
c -= 'a' - 'A';
hash = (hash * FNV32_PRIME) ^ c;
}
return hash;
}
unsigned int memhash(const void *buf, size_t len)
{
unsigned int hash = FNV32_BASE;
unsigned char *ucbuf = (unsigned char *) buf;
while (len--) {
unsigned int c = *ucbuf++;
hash = (hash * FNV32_PRIME) ^ c;
}
return hash;
}
unsigned int memihash(const void *buf, size_t len)
{
unsigned int hash = FNV32_BASE;
unsigned char *ucbuf = (unsigned char *) buf;
while (len--) {
unsigned int c = *ucbuf++;
if (c >= 'a' && c <= 'z')
c -= 'a' - 'A';
hash = (hash * FNV32_PRIME) ^ c;
}
return hash;
}
#define HASHMAP_INITIAL_SIZE 64
/* grow / shrink by 2^2 */
#define HASHMAP_RESIZE_BITS 2
/* load factor in percent */
#define HASHMAP_LOAD_FACTOR 80
static void alloc_table(struct hashmap *map, unsigned int size)
{
map->tablesize = size;
map->table = xcalloc(size, sizeof(struct hashmap_entry *));
/* calculate resize thresholds for new size */
map->grow_at = (unsigned int) ((uint64_t) size * HASHMAP_LOAD_FACTOR / 100);
if (size <= HASHMAP_INITIAL_SIZE)
map->shrink_at = 0;
else
/*
* The shrink-threshold must be slightly smaller than
* (grow-threshold / resize-factor) to prevent erratic resizing,
* thus we divide by (resize-factor + 1).
*/
map->shrink_at = map->grow_at / ((1 << HASHMAP_RESIZE_BITS) + 1);
}
static inline int entry_equals(const struct hashmap *map,
const struct hashmap_entry *e1, const struct hashmap_entry *e2,
const void *keydata)
{
return (e1 == e2) || (e1->hash == e2->hash && !map->cmpfn(e1, e2, keydata));
}
static inline unsigned int bucket(const struct hashmap *map,
const struct hashmap_entry *key)
{
return key->hash & (map->tablesize - 1);
}
static void rehash(struct hashmap *map, unsigned int newsize)
{
unsigned int i, oldsize = map->tablesize;
struct hashmap_entry **oldtable = map->table;
alloc_table(map, newsize);
for (i = 0; i < oldsize; i++) {
struct hashmap_entry *e = oldtable[i];
while (e) {
struct hashmap_entry *next = e->next;
unsigned int b = bucket(map, e);
e->next = map->table[b];
map->table[b] = e;
e = next;
}
}
free(oldtable);
}
static inline struct hashmap_entry **find_entry_ptr(const struct hashmap *map,
const struct hashmap_entry *key, const void *keydata)
{
struct hashmap_entry **e = &map->table[bucket(map, key)];
while (*e && !entry_equals(map, *e, key, keydata))
e = &(*e)->next;
return e;
}
static int always_equal(const void *unused1, const void *unused2, const void *unused3)
{
return 0;
}
void hashmap_init(struct hashmap *map, hashmap_cmp_fn equals_function,
size_t initial_size)
{
unsigned int size = HASHMAP_INITIAL_SIZE;
map->size = 0;
map->cmpfn = equals_function ? equals_function : always_equal;
/* calculate initial table size and allocate the table */
initial_size = (unsigned int) ((uint64_t) initial_size * 100
/ HASHMAP_LOAD_FACTOR);
while (initial_size > size)
size <<= HASHMAP_RESIZE_BITS;
alloc_table(map, size);
}
void hashmap_free(struct hashmap *map, int free_entries)
{
if (!map || !map->table)
return;
if (free_entries) {
struct hashmap_iter iter;
struct hashmap_entry *e;
hashmap_iter_init(map, &iter);
while ((e = hashmap_iter_next(&iter)))
free(e);
}
free(map->table);
memset(map, 0, sizeof(*map));
}
void *hashmap_get(const struct hashmap *map, const void *key, const void *keydata)
{
return *find_entry_ptr(map, key, keydata);
}
void *hashmap_get_next(const struct hashmap *map, const void *entry)
{
struct hashmap_entry *e = ((struct hashmap_entry *) entry)->next;
for (; e; e = e->next)
if (entry_equals(map, entry, e, NULL))
return e;
return NULL;
}
void hashmap_add(struct hashmap *map, void *entry)
{
unsigned int b = bucket(map, entry);
/* add entry */
((struct hashmap_entry *) entry)->next = map->table[b];
map->table[b] = entry;
/* fix size and rehash if appropriate */
map->size++;
if (map->size > map->grow_at)
rehash(map, map->tablesize << HASHMAP_RESIZE_BITS);
}
void *hashmap_remove(struct hashmap *map, const void *key, const void *keydata)
{
struct hashmap_entry *old;
struct hashmap_entry **e = find_entry_ptr(map, key, keydata);
if (!*e)
return NULL;
/* remove existing entry */
old = *e;
*e = old->next;
old->next = NULL;
/* fix size and rehash if appropriate */
map->size--;
if (map->size < map->shrink_at)
rehash(map, map->tablesize >> HASHMAP_RESIZE_BITS);
return old;
}
void *hashmap_put(struct hashmap *map, void *entry)
{
struct hashmap_entry *old = hashmap_remove(map, entry, NULL);
hashmap_add(map, entry);
return old;
}
void hashmap_iter_init(struct hashmap *map, struct hashmap_iter *iter)
{
iter->map = map;
iter->tablepos = 0;
iter->next = NULL;
}
void *hashmap_iter_next(struct hashmap_iter *iter)
{
struct hashmap_entry *current = iter->next;
for (;;) {
if (current) {
iter->next = current->next;
return current;
}
if (iter->tablepos >= iter->map->tablesize)
return NULL;
current = iter->map->table[iter->tablepos++];
}
}
struct pool_entry {
struct hashmap_entry ent;
size_t len;
unsigned char data[FLEX_ARRAY];
};
static int pool_entry_cmp(const struct pool_entry *e1,
const struct pool_entry *e2,
const unsigned char *keydata)
{
return e1->data != keydata &&
(e1->len != e2->len || memcmp(e1->data, keydata, e1->len));
}
const void *memintern(const void *data, size_t len)
{
static struct hashmap map;
struct pool_entry key, *e;
/* initialize string pool hashmap */
if (!map.tablesize)
hashmap_init(&map, (hashmap_cmp_fn) pool_entry_cmp, 0);
/* lookup interned string in pool */
hashmap_entry_init(&key, memhash(data, len));
key.len = len;
e = hashmap_get(&map, &key, data);
if (!e) {
/* not found: create it */
e = xmallocz(sizeof(struct pool_entry) + len);
hashmap_entry_init(e, key.ent.hash);
e->len = len;
memcpy(e->data, data, len);
hashmap_add(&map, e);
}
return e->data;
}
| gpl-2.0 |
LorDClockaN/Ace_CM7_kernel | drivers/media/dvb/dvb-usb/dib0700_core.c | 524 | 11979 | /* Linux driver for devices based on the DiBcom DiB0700 USB bridge
*
* 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.
*
* Copyright (C) 2005-6 DiBcom, SA
*/
#include "dib0700.h"
/* debug */
int dvb_usb_dib0700_debug;
module_param_named(debug,dvb_usb_dib0700_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=info,2=fw,4=fwdata,8=data (or-able))." DVB_USB_DEBUG_STATUS);
int dvb_usb_dib0700_ir_proto = 1;
module_param(dvb_usb_dib0700_ir_proto, int, 0644);
MODULE_PARM_DESC(dvb_usb_dib0700_ir_proto, "set ir protocol (0=NEC, 1=RC5 (default), 2=RC6).");
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
int dib0700_get_version(struct dvb_usb_device *d, u32 *hwversion,
u32 *romversion, u32 *ramversion, u32 *fwtype)
{
u8 b[16];
int ret = usb_control_msg(d->udev, usb_rcvctrlpipe(d->udev, 0),
REQUEST_GET_VERSION,
USB_TYPE_VENDOR | USB_DIR_IN, 0, 0,
b, sizeof(b), USB_CTRL_GET_TIMEOUT);
*hwversion = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
*romversion = (b[4] << 24) | (b[5] << 16) | (b[6] << 8) | b[7];
*ramversion = (b[8] << 24) | (b[9] << 16) | (b[10] << 8) | b[11];
*fwtype = (b[12] << 24) | (b[13] << 16) | (b[14] << 8) | b[15];
return ret;
}
/* expecting rx buffer: request data[0] data[1] ... data[2] */
static int dib0700_ctrl_wr(struct dvb_usb_device *d, u8 *tx, u8 txlen)
{
int status;
deb_data(">>> ");
debug_dump(tx,txlen,deb_data);
status = usb_control_msg(d->udev, usb_sndctrlpipe(d->udev,0),
tx[0], USB_TYPE_VENDOR | USB_DIR_OUT, 0, 0, tx, txlen,
USB_CTRL_GET_TIMEOUT);
if (status != txlen)
deb_data("ep 0 write error (status = %d, len: %d)\n",status,txlen);
return status < 0 ? status : 0;
}
/* expecting tx buffer: request data[0] ... data[n] (n <= 4) */
int dib0700_ctrl_rd(struct dvb_usb_device *d, u8 *tx, u8 txlen, u8 *rx, u8 rxlen)
{
u16 index, value;
int status;
if (txlen < 2) {
err("tx buffer length is smaller than 2. Makes no sense.");
return -EINVAL;
}
if (txlen > 4) {
err("tx buffer length is larger than 4. Not supported.");
return -EINVAL;
}
deb_data(">>> ");
debug_dump(tx,txlen,deb_data);
value = ((txlen - 2) << 8) | tx[1];
index = 0;
if (txlen > 2)
index |= (tx[2] << 8);
if (txlen > 3)
index |= tx[3];
status = usb_control_msg(d->udev, usb_rcvctrlpipe(d->udev,0), tx[0],
USB_TYPE_VENDOR | USB_DIR_IN, value, index, rx, rxlen,
USB_CTRL_GET_TIMEOUT);
if (status < 0)
deb_info("ep 0 read error (status = %d)\n",status);
deb_data("<<< ");
debug_dump(rx,rxlen,deb_data);
return status; /* length in case of success */
}
int dib0700_set_gpio(struct dvb_usb_device *d, enum dib07x0_gpios gpio, u8 gpio_dir, u8 gpio_val)
{
u8 buf[3] = { REQUEST_SET_GPIO, gpio, ((gpio_dir & 0x01) << 7) | ((gpio_val & 0x01) << 6) };
return dib0700_ctrl_wr(d,buf,3);
}
/*
* I2C master xfer function (supported in 1.20 firmware)
*/
static int dib0700_i2c_xfer_new(struct i2c_adapter *adap, struct i2c_msg *msg,
int num)
{
/* The new i2c firmware messages are more reliable and in particular
properly support i2c read calls not preceded by a write */
struct dvb_usb_device *d = i2c_get_adapdata(adap);
uint8_t bus_mode = 1; /* 0=eeprom bus, 1=frontend bus */
uint8_t gen_mode = 0; /* 0=master i2c, 1=gpio i2c */
uint8_t en_start = 0;
uint8_t en_stop = 0;
uint8_t buf[255]; /* TBV: malloc ? */
int result, i;
/* Ensure nobody else hits the i2c bus while we're sending our
sequence of messages, (such as the remote control thread) */
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
if (i == 0) {
/* First message in the transaction */
en_start = 1;
} else if (!(msg[i].flags & I2C_M_NOSTART)) {
/* Device supports repeated-start */
en_start = 1;
} else {
/* Not the first packet and device doesn't support
repeated start */
en_start = 0;
}
if (i == (num - 1)) {
/* Last message in the transaction */
en_stop = 1;
}
if (msg[i].flags & I2C_M_RD) {
/* Read request */
u16 index, value;
uint8_t i2c_dest;
i2c_dest = (msg[i].addr << 1);
value = ((en_start << 7) | (en_stop << 6) |
(msg[i].len & 0x3F)) << 8 | i2c_dest;
/* I2C ctrl + FE bus; */
index = ((gen_mode<<6)&0xC0) | ((bus_mode<<4)&0x30);
result = usb_control_msg(d->udev,
usb_rcvctrlpipe(d->udev, 0),
REQUEST_NEW_I2C_READ,
USB_TYPE_VENDOR | USB_DIR_IN,
value, index, msg[i].buf,
msg[i].len,
USB_CTRL_GET_TIMEOUT);
if (result < 0) {
err("i2c read error (status = %d)\n", result);
break;
}
deb_data("<<< ");
debug_dump(msg[i].buf, msg[i].len, deb_data);
} else {
/* Write request */
buf[0] = REQUEST_NEW_I2C_WRITE;
buf[1] = (msg[i].addr << 1);
buf[2] = (en_start << 7) | (en_stop << 6) |
(msg[i].len & 0x3F);
/* I2C ctrl + FE bus; */
buf[3] = ((gen_mode<<6)&0xC0) | ((bus_mode<<4)&0x30);
/* The Actual i2c payload */
memcpy(&buf[4], msg[i].buf, msg[i].len);
deb_data(">>> ");
debug_dump(buf, msg[i].len + 4, deb_data);
result = usb_control_msg(d->udev,
usb_sndctrlpipe(d->udev, 0),
REQUEST_NEW_I2C_WRITE,
USB_TYPE_VENDOR | USB_DIR_OUT,
0, 0, buf, msg[i].len + 4,
USB_CTRL_GET_TIMEOUT);
if (result < 0) {
err("i2c write error (status = %d)\n", result);
break;
}
}
}
mutex_unlock(&d->i2c_mutex);
return i;
}
/*
* I2C master xfer function (pre-1.20 firmware)
*/
static int dib0700_i2c_xfer_legacy(struct i2c_adapter *adap,
struct i2c_msg *msg, int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
int i,len;
u8 buf[255];
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
/* fill in the address */
buf[1] = (msg[i].addr << 1);
/* fill the buffer */
memcpy(&buf[2], msg[i].buf, msg[i].len);
/* write/read request */
if (i+1 < num && (msg[i+1].flags & I2C_M_RD)) {
buf[0] = REQUEST_I2C_READ;
buf[1] |= 1;
/* special thing in the current firmware: when length is zero the read-failed */
if ((len = dib0700_ctrl_rd(d, buf, msg[i].len + 2, msg[i+1].buf, msg[i+1].len)) <= 0) {
deb_info("I2C read failed on address 0x%02x\n",
msg[i].addr);
break;
}
msg[i+1].len = len;
i++;
} else {
buf[0] = REQUEST_I2C_WRITE;
if (dib0700_ctrl_wr(d, buf, msg[i].len + 2) < 0)
break;
}
}
mutex_unlock(&d->i2c_mutex);
return i;
}
static int dib0700_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msg,
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
struct dib0700_state *st = d->priv;
if (st->fw_use_new_i2c_api == 1) {
/* User running at least fw 1.20 */
return dib0700_i2c_xfer_new(adap, msg, num);
} else {
/* Use legacy calls */
return dib0700_i2c_xfer_legacy(adap, msg, num);
}
}
static u32 dib0700_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
struct i2c_algorithm dib0700_i2c_algo = {
.master_xfer = dib0700_i2c_xfer,
.functionality = dib0700_i2c_func,
};
int dib0700_identify_state(struct usb_device *udev, struct dvb_usb_device_properties *props,
struct dvb_usb_device_description **desc, int *cold)
{
u8 b[16];
s16 ret = usb_control_msg(udev, usb_rcvctrlpipe(udev,0),
REQUEST_GET_VERSION, USB_TYPE_VENDOR | USB_DIR_IN, 0, 0, b, 16, USB_CTRL_GET_TIMEOUT);
deb_info("FW GET_VERSION length: %d\n",ret);
*cold = ret <= 0;
deb_info("cold: %d\n", *cold);
return 0;
}
static int dib0700_set_clock(struct dvb_usb_device *d, u8 en_pll,
u8 pll_src, u8 pll_range, u8 clock_gpio3, u16 pll_prediv,
u16 pll_loopdiv, u16 free_div, u16 dsuScaler)
{
u8 b[10];
b[0] = REQUEST_SET_CLOCK;
b[1] = (en_pll << 7) | (pll_src << 6) | (pll_range << 5) | (clock_gpio3 << 4);
b[2] = (pll_prediv >> 8) & 0xff; // MSB
b[3] = pll_prediv & 0xff; // LSB
b[4] = (pll_loopdiv >> 8) & 0xff; // MSB
b[5] = pll_loopdiv & 0xff; // LSB
b[6] = (free_div >> 8) & 0xff; // MSB
b[7] = free_div & 0xff; // LSB
b[8] = (dsuScaler >> 8) & 0xff; // MSB
b[9] = dsuScaler & 0xff; // LSB
return dib0700_ctrl_wr(d, b, 10);
}
int dib0700_ctrl_clock(struct dvb_usb_device *d, u32 clk_MHz, u8 clock_out_gp3)
{
switch (clk_MHz) {
case 72: dib0700_set_clock(d, 1, 0, 1, clock_out_gp3, 2, 24, 0, 0x4c); break;
default: return -EINVAL;
}
return 0;
}
static int dib0700_jumpram(struct usb_device *udev, u32 address)
{
int ret, actlen;
u8 buf[8] = { REQUEST_JUMPRAM, 0, 0, 0,
(address >> 24) & 0xff,
(address >> 16) & 0xff,
(address >> 8) & 0xff,
address & 0xff };
if ((ret = usb_bulk_msg(udev, usb_sndbulkpipe(udev, 0x01),buf,8,&actlen,1000)) < 0) {
deb_fw("jumpram to 0x%x failed\n",address);
return ret;
}
if (actlen != 8) {
deb_fw("jumpram to 0x%x failed\n",address);
return -EIO;
}
return 0;
}
int dib0700_download_firmware(struct usb_device *udev, const struct firmware *fw)
{
struct hexline hx;
int pos = 0, ret, act_len;
u8 buf[260];
while ((ret = dvb_usb_get_hexline(fw, &hx, &pos)) > 0) {
deb_fwdata("writing to address 0x%08x (buffer: 0x%02x %02x)\n",hx.addr, hx.len, hx.chk);
buf[0] = hx.len;
buf[1] = (hx.addr >> 8) & 0xff;
buf[2] = hx.addr & 0xff;
buf[3] = hx.type;
memcpy(&buf[4],hx.data,hx.len);
buf[4+hx.len] = hx.chk;
ret = usb_bulk_msg(udev,
usb_sndbulkpipe(udev, 0x01),
buf,
hx.len + 5,
&act_len,
1000);
if (ret < 0) {
err("firmware download failed at %d with %d",pos,ret);
return ret;
}
}
if (ret == 0) {
/* start the firmware */
if ((ret = dib0700_jumpram(udev, 0x70000000)) == 0) {
info("firmware started successfully.");
msleep(500);
}
} else
ret = -EIO;
return ret;
}
int dib0700_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
struct dib0700_state *st = adap->dev->priv;
u8 b[4];
b[0] = REQUEST_ENABLE_VIDEO;
b[1] = (onoff << 4) | 0x00; /* this bit gives a kind of command, rather than enabling something or not */
if (st->disable_streaming_master_mode == 1)
b[2] = 0x00;
else
b[2] = (0x01 << 4); /* Master mode */
b[3] = 0x00;
deb_info("modifying (%d) streaming state for %d\n", onoff, adap->id);
if (onoff)
st->channel_state |= 1 << adap->id;
else
st->channel_state &= ~(1 << adap->id);
b[2] |= st->channel_state;
deb_info("data for streaming: %x %x\n",b[1],b[2]);
return dib0700_ctrl_wr(adap->dev, b, 4);
}
int dib0700_rc_setup(struct dvb_usb_device *d)
{
u8 rc_setup[3] = {REQUEST_SET_RC, dvb_usb_dib0700_ir_proto, 0};
int i = dib0700_ctrl_wr(d, rc_setup, 3);
if (i<0) {
err("ir protocol setup failed");
return -1;
}
return 0;
}
static int dib0700_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
int i;
struct dvb_usb_device *dev;
for (i = 0; i < dib0700_device_count; i++)
if (dvb_usb_device_init(intf, &dib0700_devices[i], THIS_MODULE,
&dev, adapter_nr) == 0)
{
dib0700_rc_setup(dev);
return 0;
}
return -ENODEV;
}
static struct usb_driver dib0700_driver = {
.name = "dvb_usb_dib0700",
.probe = dib0700_probe,
.disconnect = dvb_usb_device_exit,
.id_table = dib0700_usb_id_table,
};
/* module stuff */
static int __init dib0700_module_init(void)
{
int result;
info("loaded with support for %d different device-types", dib0700_device_count);
if ((result = usb_register(&dib0700_driver))) {
err("usb_register failed. Error number %d",result);
return result;
}
return 0;
}
static void __exit dib0700_module_exit(void)
{
/* deregister this driver from the USB subsystem */
usb_deregister(&dib0700_driver);
}
module_init (dib0700_module_init);
module_exit (dib0700_module_exit);
MODULE_AUTHOR("Patrick Boettcher <pboettcher@dibcom.fr>");
MODULE_DESCRIPTION("Driver for devices based on DiBcom DiB0700 - USB bridge");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL");
| gpl-2.0 |
thestealth131205/k2_u-ul | drivers/gpu/drm/radeon/radeon_atombios.c | 524 | 104863 | /*
* Copyright 2007-8 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
*/
#include "drmP.h"
#include "radeon_drm.h"
#include "radeon.h"
#include "atom.h"
#include "atom-bits.h"
/* from radeon_encoder.c */
extern uint32_t
radeon_get_encoder_enum(struct drm_device *dev, uint32_t supported_device,
uint8_t dac);
extern void radeon_link_encoder_connector(struct drm_device *dev);
extern void
radeon_add_atom_encoder(struct drm_device *dev, uint32_t encoder_enum,
uint32_t supported_device, u16 caps);
/* from radeon_connector.c */
extern void
radeon_add_atom_connector(struct drm_device *dev,
uint32_t connector_id,
uint32_t supported_device,
int connector_type,
struct radeon_i2c_bus_rec *i2c_bus,
uint32_t igp_lane_info,
uint16_t connector_object_id,
struct radeon_hpd *hpd,
struct radeon_router *router);
/* from radeon_legacy_encoder.c */
extern void
radeon_add_legacy_encoder(struct drm_device *dev, uint32_t encoder_enum,
uint32_t supported_device);
/* local */
static int radeon_atom_get_max_vddc(struct radeon_device *rdev, u8 voltage_type,
u16 voltage_id, u16 *voltage);
union atom_supported_devices {
struct _ATOM_SUPPORTED_DEVICES_INFO info;
struct _ATOM_SUPPORTED_DEVICES_INFO_2 info_2;
struct _ATOM_SUPPORTED_DEVICES_INFO_2d1 info_2d1;
};
static void radeon_lookup_i2c_gpio_quirks(struct radeon_device *rdev,
ATOM_GPIO_I2C_ASSIGMENT *gpio,
u8 index)
{
/* r4xx mask is technically not used by the hw, so patch in the legacy mask bits */
if ((rdev->family == CHIP_R420) ||
(rdev->family == CHIP_R423) ||
(rdev->family == CHIP_RV410)) {
if ((le16_to_cpu(gpio->usClkMaskRegisterIndex) == 0x0018) ||
(le16_to_cpu(gpio->usClkMaskRegisterIndex) == 0x0019) ||
(le16_to_cpu(gpio->usClkMaskRegisterIndex) == 0x001a)) {
gpio->ucClkMaskShift = 0x19;
gpio->ucDataMaskShift = 0x18;
}
}
/* some evergreen boards have bad data for this entry */
if (ASIC_IS_DCE4(rdev)) {
if ((index == 7) &&
(le16_to_cpu(gpio->usClkMaskRegisterIndex) == 0x1936) &&
(gpio->sucI2cId.ucAccess == 0)) {
gpio->sucI2cId.ucAccess = 0x97;
gpio->ucDataMaskShift = 8;
gpio->ucDataEnShift = 8;
gpio->ucDataY_Shift = 8;
gpio->ucDataA_Shift = 8;
}
}
/* some DCE3 boards have bad data for this entry */
if (ASIC_IS_DCE3(rdev)) {
if ((index == 4) &&
(le16_to_cpu(gpio->usClkMaskRegisterIndex) == 0x1fda) &&
(gpio->sucI2cId.ucAccess == 0x94))
gpio->sucI2cId.ucAccess = 0x14;
}
}
static struct radeon_i2c_bus_rec radeon_get_bus_rec_for_i2c_gpio(ATOM_GPIO_I2C_ASSIGMENT *gpio)
{
struct radeon_i2c_bus_rec i2c;
memset(&i2c, 0, sizeof(struct radeon_i2c_bus_rec));
i2c.mask_clk_reg = le16_to_cpu(gpio->usClkMaskRegisterIndex) * 4;
i2c.mask_data_reg = le16_to_cpu(gpio->usDataMaskRegisterIndex) * 4;
i2c.en_clk_reg = le16_to_cpu(gpio->usClkEnRegisterIndex) * 4;
i2c.en_data_reg = le16_to_cpu(gpio->usDataEnRegisterIndex) * 4;
i2c.y_clk_reg = le16_to_cpu(gpio->usClkY_RegisterIndex) * 4;
i2c.y_data_reg = le16_to_cpu(gpio->usDataY_RegisterIndex) * 4;
i2c.a_clk_reg = le16_to_cpu(gpio->usClkA_RegisterIndex) * 4;
i2c.a_data_reg = le16_to_cpu(gpio->usDataA_RegisterIndex) * 4;
i2c.mask_clk_mask = (1 << gpio->ucClkMaskShift);
i2c.mask_data_mask = (1 << gpio->ucDataMaskShift);
i2c.en_clk_mask = (1 << gpio->ucClkEnShift);
i2c.en_data_mask = (1 << gpio->ucDataEnShift);
i2c.y_clk_mask = (1 << gpio->ucClkY_Shift);
i2c.y_data_mask = (1 << gpio->ucDataY_Shift);
i2c.a_clk_mask = (1 << gpio->ucClkA_Shift);
i2c.a_data_mask = (1 << gpio->ucDataA_Shift);
if (gpio->sucI2cId.sbfAccess.bfHW_Capable)
i2c.hw_capable = true;
else
i2c.hw_capable = false;
if (gpio->sucI2cId.ucAccess == 0xa0)
i2c.mm_i2c = true;
else
i2c.mm_i2c = false;
i2c.i2c_id = gpio->sucI2cId.ucAccess;
if (i2c.mask_clk_reg)
i2c.valid = true;
else
i2c.valid = false;
return i2c;
}
static struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rdev,
uint8_t id)
{
struct atom_context *ctx = rdev->mode_info.atom_context;
ATOM_GPIO_I2C_ASSIGMENT *gpio;
struct radeon_i2c_bus_rec i2c;
int index = GetIndexIntoMasterTable(DATA, GPIO_I2C_Info);
struct _ATOM_GPIO_I2C_INFO *i2c_info;
uint16_t data_offset, size;
int i, num_indices;
memset(&i2c, 0, sizeof(struct radeon_i2c_bus_rec));
i2c.valid = false;
if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) {
i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset);
num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) /
sizeof(ATOM_GPIO_I2C_ASSIGMENT);
for (i = 0; i < num_indices; i++) {
gpio = &i2c_info->asGPIO_Info[i];
radeon_lookup_i2c_gpio_quirks(rdev, gpio, i);
if (gpio->sucI2cId.ucAccess == id) {
i2c = radeon_get_bus_rec_for_i2c_gpio(gpio);
break;
}
}
}
return i2c;
}
void radeon_atombios_i2c_init(struct radeon_device *rdev)
{
struct atom_context *ctx = rdev->mode_info.atom_context;
ATOM_GPIO_I2C_ASSIGMENT *gpio;
struct radeon_i2c_bus_rec i2c;
int index = GetIndexIntoMasterTable(DATA, GPIO_I2C_Info);
struct _ATOM_GPIO_I2C_INFO *i2c_info;
uint16_t data_offset, size;
int i, num_indices;
char stmp[32];
if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) {
i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset);
num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) /
sizeof(ATOM_GPIO_I2C_ASSIGMENT);
for (i = 0; i < num_indices; i++) {
gpio = &i2c_info->asGPIO_Info[i];
radeon_lookup_i2c_gpio_quirks(rdev, gpio, i);
i2c = radeon_get_bus_rec_for_i2c_gpio(gpio);
if (i2c.valid) {
sprintf(stmp, "0x%x", i2c.i2c_id);
rdev->i2c_bus[i] = radeon_i2c_create(rdev->ddev, &i2c, stmp);
}
}
}
}
static struct radeon_gpio_rec radeon_lookup_gpio(struct radeon_device *rdev,
u8 id)
{
struct atom_context *ctx = rdev->mode_info.atom_context;
struct radeon_gpio_rec gpio;
int index = GetIndexIntoMasterTable(DATA, GPIO_Pin_LUT);
struct _ATOM_GPIO_PIN_LUT *gpio_info;
ATOM_GPIO_PIN_ASSIGNMENT *pin;
u16 data_offset, size;
int i, num_indices;
memset(&gpio, 0, sizeof(struct radeon_gpio_rec));
gpio.valid = false;
if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) {
gpio_info = (struct _ATOM_GPIO_PIN_LUT *)(ctx->bios + data_offset);
num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) /
sizeof(ATOM_GPIO_PIN_ASSIGNMENT);
for (i = 0; i < num_indices; i++) {
pin = &gpio_info->asGPIO_Pin[i];
if (id == pin->ucGPIO_ID) {
gpio.id = pin->ucGPIO_ID;
gpio.reg = le16_to_cpu(pin->usGpioPin_AIndex) * 4;
gpio.mask = (1 << pin->ucGpioPinBitShift);
gpio.valid = true;
break;
}
}
}
return gpio;
}
static struct radeon_hpd radeon_atom_get_hpd_info_from_gpio(struct radeon_device *rdev,
struct radeon_gpio_rec *gpio)
{
struct radeon_hpd hpd;
u32 reg;
memset(&hpd, 0, sizeof(struct radeon_hpd));
if (ASIC_IS_DCE6(rdev))
reg = SI_DC_GPIO_HPD_A;
else if (ASIC_IS_DCE4(rdev))
reg = EVERGREEN_DC_GPIO_HPD_A;
else
reg = AVIVO_DC_GPIO_HPD_A;
hpd.gpio = *gpio;
if (gpio->reg == reg) {
switch(gpio->mask) {
case (1 << 0):
hpd.hpd = RADEON_HPD_1;
break;
case (1 << 8):
hpd.hpd = RADEON_HPD_2;
break;
case (1 << 16):
hpd.hpd = RADEON_HPD_3;
break;
case (1 << 24):
hpd.hpd = RADEON_HPD_4;
break;
case (1 << 26):
hpd.hpd = RADEON_HPD_5;
break;
case (1 << 28):
hpd.hpd = RADEON_HPD_6;
break;
default:
hpd.hpd = RADEON_HPD_NONE;
break;
}
} else
hpd.hpd = RADEON_HPD_NONE;
return hpd;
}
static bool radeon_atom_apply_quirks(struct drm_device *dev,
uint32_t supported_device,
int *connector_type,
struct radeon_i2c_bus_rec *i2c_bus,
uint16_t *line_mux,
struct radeon_hpd *hpd)
{
/* Asus M2A-VM HDMI board lists the DVI port as HDMI */
if ((dev->pdev->device == 0x791e) &&
(dev->pdev->subsystem_vendor == 0x1043) &&
(dev->pdev->subsystem_device == 0x826d)) {
if ((*connector_type == DRM_MODE_CONNECTOR_HDMIA) &&
(supported_device == ATOM_DEVICE_DFP3_SUPPORT))
*connector_type = DRM_MODE_CONNECTOR_DVID;
}
/* Asrock RS600 board lists the DVI port as HDMI */
if ((dev->pdev->device == 0x7941) &&
(dev->pdev->subsystem_vendor == 0x1849) &&
(dev->pdev->subsystem_device == 0x7941)) {
if ((*connector_type == DRM_MODE_CONNECTOR_HDMIA) &&
(supported_device == ATOM_DEVICE_DFP3_SUPPORT))
*connector_type = DRM_MODE_CONNECTOR_DVID;
}
/* MSI K9A2GM V2/V3 board has no HDMI or DVI */
if ((dev->pdev->device == 0x796e) &&
(dev->pdev->subsystem_vendor == 0x1462) &&
(dev->pdev->subsystem_device == 0x7302)) {
if ((supported_device == ATOM_DEVICE_DFP2_SUPPORT) ||
(supported_device == ATOM_DEVICE_DFP3_SUPPORT))
return false;
}
/* a-bit f-i90hd - ciaranm on #radeonhd - this board has no DVI */
if ((dev->pdev->device == 0x7941) &&
(dev->pdev->subsystem_vendor == 0x147b) &&
(dev->pdev->subsystem_device == 0x2412)) {
if (*connector_type == DRM_MODE_CONNECTOR_DVII)
return false;
}
/* Falcon NW laptop lists vga ddc line for LVDS */
if ((dev->pdev->device == 0x5653) &&
(dev->pdev->subsystem_vendor == 0x1462) &&
(dev->pdev->subsystem_device == 0x0291)) {
if (*connector_type == DRM_MODE_CONNECTOR_LVDS) {
i2c_bus->valid = false;
*line_mux = 53;
}
}
/* HIS X1300 is DVI+VGA, not DVI+DVI */
if ((dev->pdev->device == 0x7146) &&
(dev->pdev->subsystem_vendor == 0x17af) &&
(dev->pdev->subsystem_device == 0x2058)) {
if (supported_device == ATOM_DEVICE_DFP1_SUPPORT)
return false;
}
/* Gigabyte X1300 is DVI+VGA, not DVI+DVI */
if ((dev->pdev->device == 0x7142) &&
(dev->pdev->subsystem_vendor == 0x1458) &&
(dev->pdev->subsystem_device == 0x2134)) {
if (supported_device == ATOM_DEVICE_DFP1_SUPPORT)
return false;
}
/* Funky macbooks */
if ((dev->pdev->device == 0x71C5) &&
(dev->pdev->subsystem_vendor == 0x106b) &&
(dev->pdev->subsystem_device == 0x0080)) {
if ((supported_device == ATOM_DEVICE_CRT1_SUPPORT) ||
(supported_device == ATOM_DEVICE_DFP2_SUPPORT))
return false;
if (supported_device == ATOM_DEVICE_CRT2_SUPPORT)
*line_mux = 0x90;
}
/* mac rv630, rv730, others */
if ((supported_device == ATOM_DEVICE_TV1_SUPPORT) &&
(*connector_type == DRM_MODE_CONNECTOR_DVII)) {
*connector_type = DRM_MODE_CONNECTOR_9PinDIN;
*line_mux = CONNECTOR_7PIN_DIN_ENUM_ID1;
}
/* ASUS HD 3600 XT board lists the DVI port as HDMI */
if ((dev->pdev->device == 0x9598) &&
(dev->pdev->subsystem_vendor == 0x1043) &&
(dev->pdev->subsystem_device == 0x01da)) {
if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) {
*connector_type = DRM_MODE_CONNECTOR_DVII;
}
}
/* ASUS HD 3600 board lists the DVI port as HDMI */
if ((dev->pdev->device == 0x9598) &&
(dev->pdev->subsystem_vendor == 0x1043) &&
(dev->pdev->subsystem_device == 0x01e4)) {
if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) {
*connector_type = DRM_MODE_CONNECTOR_DVII;
}
}
/* ASUS HD 3450 board lists the DVI port as HDMI */
if ((dev->pdev->device == 0x95C5) &&
(dev->pdev->subsystem_vendor == 0x1043) &&
(dev->pdev->subsystem_device == 0x01e2)) {
if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) {
*connector_type = DRM_MODE_CONNECTOR_DVII;
}
}
/* some BIOSes seem to report DAC on HDMI - usually this is a board with
* HDMI + VGA reporting as HDMI
*/
if (*connector_type == DRM_MODE_CONNECTOR_HDMIA) {
if (supported_device & (ATOM_DEVICE_CRT_SUPPORT)) {
*connector_type = DRM_MODE_CONNECTOR_VGA;
*line_mux = 0;
}
}
/* Acer laptop (Acer TravelMate 5730/5730G) has an HDMI port
* on the laptop and a DVI port on the docking station and
* both share the same encoder, hpd pin, and ddc line.
* So while the bios table is technically correct,
* we drop the DVI port here since xrandr has no concept of
* encoders and will try and drive both connectors
* with different crtcs which isn't possible on the hardware
* side and leaves no crtcs for LVDS or VGA.
*/
if (((dev->pdev->device == 0x95c4) || (dev->pdev->device == 0x9591)) &&
(dev->pdev->subsystem_vendor == 0x1025) &&
(dev->pdev->subsystem_device == 0x013c)) {
if ((*connector_type == DRM_MODE_CONNECTOR_DVII) &&
(supported_device == ATOM_DEVICE_DFP1_SUPPORT)) {
/* actually it's a DVI-D port not DVI-I */
*connector_type = DRM_MODE_CONNECTOR_DVID;
return false;
}
}
/* XFX Pine Group device rv730 reports no VGA DDC lines
* even though they are wired up to record 0x93
*/
if ((dev->pdev->device == 0x9498) &&
(dev->pdev->subsystem_vendor == 0x1682) &&
(dev->pdev->subsystem_device == 0x2452) &&
(i2c_bus->valid == false) &&
!(supported_device & (ATOM_DEVICE_TV_SUPPORT | ATOM_DEVICE_CV_SUPPORT))) {
struct radeon_device *rdev = dev->dev_private;
*i2c_bus = radeon_lookup_i2c_gpio(rdev, 0x93);
}
/* Fujitsu D3003-S2 board lists DVI-I as DVI-D and VGA */
if ((dev->pdev->device == 0x9802) &&
(dev->pdev->subsystem_vendor == 0x1734) &&
(dev->pdev->subsystem_device == 0x11bd)) {
if (*connector_type == DRM_MODE_CONNECTOR_VGA) {
*connector_type = DRM_MODE_CONNECTOR_DVII;
*line_mux = 0x3103;
} else if (*connector_type == DRM_MODE_CONNECTOR_DVID) {
*connector_type = DRM_MODE_CONNECTOR_DVII;
}
}
return true;
}
const int supported_devices_connector_convert[] = {
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_VGA,
DRM_MODE_CONNECTOR_DVII,
DRM_MODE_CONNECTOR_DVID,
DRM_MODE_CONNECTOR_DVIA,
DRM_MODE_CONNECTOR_SVIDEO,
DRM_MODE_CONNECTOR_Composite,
DRM_MODE_CONNECTOR_LVDS,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_HDMIA,
DRM_MODE_CONNECTOR_HDMIB,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_9PinDIN,
DRM_MODE_CONNECTOR_DisplayPort
};
const uint16_t supported_devices_connector_object_id_convert[] = {
CONNECTOR_OBJECT_ID_NONE,
CONNECTOR_OBJECT_ID_VGA,
CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I, /* not all boards support DL */
CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D, /* not all boards support DL */
CONNECTOR_OBJECT_ID_VGA, /* technically DVI-A */
CONNECTOR_OBJECT_ID_COMPOSITE,
CONNECTOR_OBJECT_ID_SVIDEO,
CONNECTOR_OBJECT_ID_LVDS,
CONNECTOR_OBJECT_ID_9PIN_DIN,
CONNECTOR_OBJECT_ID_9PIN_DIN,
CONNECTOR_OBJECT_ID_DISPLAYPORT,
CONNECTOR_OBJECT_ID_HDMI_TYPE_A,
CONNECTOR_OBJECT_ID_HDMI_TYPE_B,
CONNECTOR_OBJECT_ID_SVIDEO
};
const int object_connector_convert[] = {
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_DVII,
DRM_MODE_CONNECTOR_DVII,
DRM_MODE_CONNECTOR_DVID,
DRM_MODE_CONNECTOR_DVID,
DRM_MODE_CONNECTOR_VGA,
DRM_MODE_CONNECTOR_Composite,
DRM_MODE_CONNECTOR_SVIDEO,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_9PinDIN,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_HDMIA,
DRM_MODE_CONNECTOR_HDMIB,
DRM_MODE_CONNECTOR_LVDS,
DRM_MODE_CONNECTOR_9PinDIN,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_Unknown,
DRM_MODE_CONNECTOR_DisplayPort,
DRM_MODE_CONNECTOR_eDP,
DRM_MODE_CONNECTOR_Unknown
};
bool radeon_get_atom_connector_info_from_object_table(struct drm_device *dev)
{
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
struct atom_context *ctx = mode_info->atom_context;
int index = GetIndexIntoMasterTable(DATA, Object_Header);
u16 size, data_offset;
u8 frev, crev;
ATOM_CONNECTOR_OBJECT_TABLE *con_obj;
ATOM_ENCODER_OBJECT_TABLE *enc_obj;
ATOM_OBJECT_TABLE *router_obj;
ATOM_DISPLAY_OBJECT_PATH_TABLE *path_obj;
ATOM_OBJECT_HEADER *obj_header;
int i, j, k, path_size, device_support;
int connector_type;
u16 igp_lane_info, conn_id, connector_object_id;
struct radeon_i2c_bus_rec ddc_bus;
struct radeon_router router;
struct radeon_gpio_rec gpio;
struct radeon_hpd hpd;
if (!atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset))
return false;
if (crev < 2)
return false;
obj_header = (ATOM_OBJECT_HEADER *) (ctx->bios + data_offset);
path_obj = (ATOM_DISPLAY_OBJECT_PATH_TABLE *)
(ctx->bios + data_offset +
le16_to_cpu(obj_header->usDisplayPathTableOffset));
con_obj = (ATOM_CONNECTOR_OBJECT_TABLE *)
(ctx->bios + data_offset +
le16_to_cpu(obj_header->usConnectorObjectTableOffset));
enc_obj = (ATOM_ENCODER_OBJECT_TABLE *)
(ctx->bios + data_offset +
le16_to_cpu(obj_header->usEncoderObjectTableOffset));
router_obj = (ATOM_OBJECT_TABLE *)
(ctx->bios + data_offset +
le16_to_cpu(obj_header->usRouterObjectTableOffset));
device_support = le16_to_cpu(obj_header->usDeviceSupport);
path_size = 0;
for (i = 0; i < path_obj->ucNumOfDispPath; i++) {
uint8_t *addr = (uint8_t *) path_obj->asDispPath;
ATOM_DISPLAY_OBJECT_PATH *path;
addr += path_size;
path = (ATOM_DISPLAY_OBJECT_PATH *) addr;
path_size += le16_to_cpu(path->usSize);
if (device_support & le16_to_cpu(path->usDeviceTag)) {
uint8_t con_obj_id, con_obj_num, con_obj_type;
con_obj_id =
(le16_to_cpu(path->usConnObjectId) & OBJECT_ID_MASK)
>> OBJECT_ID_SHIFT;
con_obj_num =
(le16_to_cpu(path->usConnObjectId) & ENUM_ID_MASK)
>> ENUM_ID_SHIFT;
con_obj_type =
(le16_to_cpu(path->usConnObjectId) &
OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT;
/* TODO CV support */
if (le16_to_cpu(path->usDeviceTag) ==
ATOM_DEVICE_CV_SUPPORT)
continue;
/* IGP chips */
if ((rdev->flags & RADEON_IS_IGP) &&
(con_obj_id ==
CONNECTOR_OBJECT_ID_PCIE_CONNECTOR)) {
uint16_t igp_offset = 0;
ATOM_INTEGRATED_SYSTEM_INFO_V2 *igp_obj;
index =
GetIndexIntoMasterTable(DATA,
IntegratedSystemInfo);
if (atom_parse_data_header(ctx, index, &size, &frev,
&crev, &igp_offset)) {
if (crev >= 2) {
igp_obj =
(ATOM_INTEGRATED_SYSTEM_INFO_V2
*) (ctx->bios + igp_offset);
if (igp_obj) {
uint32_t slot_config, ct;
if (con_obj_num == 1)
slot_config =
igp_obj->
ulDDISlot1Config;
else
slot_config =
igp_obj->
ulDDISlot2Config;
ct = (slot_config >> 16) & 0xff;
connector_type =
object_connector_convert
[ct];
connector_object_id = ct;
igp_lane_info =
slot_config & 0xffff;
} else
continue;
} else
continue;
} else {
igp_lane_info = 0;
connector_type =
object_connector_convert[con_obj_id];
connector_object_id = con_obj_id;
}
} else {
igp_lane_info = 0;
connector_type =
object_connector_convert[con_obj_id];
connector_object_id = con_obj_id;
}
if (connector_type == DRM_MODE_CONNECTOR_Unknown)
continue;
router.ddc_valid = false;
router.cd_valid = false;
for (j = 0; j < ((le16_to_cpu(path->usSize) - 8) / 2); j++) {
uint8_t grph_obj_id, grph_obj_num, grph_obj_type;
grph_obj_id =
(le16_to_cpu(path->usGraphicObjIds[j]) &
OBJECT_ID_MASK) >> OBJECT_ID_SHIFT;
grph_obj_num =
(le16_to_cpu(path->usGraphicObjIds[j]) &
ENUM_ID_MASK) >> ENUM_ID_SHIFT;
grph_obj_type =
(le16_to_cpu(path->usGraphicObjIds[j]) &
OBJECT_TYPE_MASK) >> OBJECT_TYPE_SHIFT;
if (grph_obj_type == GRAPH_OBJECT_TYPE_ENCODER) {
for (k = 0; k < enc_obj->ucNumberOfObjects; k++) {
u16 encoder_obj = le16_to_cpu(enc_obj->asObjects[k].usObjectID);
if (le16_to_cpu(path->usGraphicObjIds[j]) == encoder_obj) {
ATOM_COMMON_RECORD_HEADER *record = (ATOM_COMMON_RECORD_HEADER *)
(ctx->bios + data_offset +
le16_to_cpu(enc_obj->asObjects[k].usRecordOffset));
ATOM_ENCODER_CAP_RECORD *cap_record;
u16 caps = 0;
while (record->ucRecordSize > 0 &&
record->ucRecordType > 0 &&
record->ucRecordType <= ATOM_MAX_OBJECT_RECORD_NUMBER) {
switch (record->ucRecordType) {
case ATOM_ENCODER_CAP_RECORD_TYPE:
cap_record =(ATOM_ENCODER_CAP_RECORD *)
record;
caps = le16_to_cpu(cap_record->usEncoderCap);
break;
}
record = (ATOM_COMMON_RECORD_HEADER *)
((char *)record + record->ucRecordSize);
}
radeon_add_atom_encoder(dev,
encoder_obj,
le16_to_cpu
(path->
usDeviceTag),
caps);
}
}
} else if (grph_obj_type == GRAPH_OBJECT_TYPE_ROUTER) {
for (k = 0; k < router_obj->ucNumberOfObjects; k++) {
u16 router_obj_id = le16_to_cpu(router_obj->asObjects[k].usObjectID);
if (le16_to_cpu(path->usGraphicObjIds[j]) == router_obj_id) {
ATOM_COMMON_RECORD_HEADER *record = (ATOM_COMMON_RECORD_HEADER *)
(ctx->bios + data_offset +
le16_to_cpu(router_obj->asObjects[k].usRecordOffset));
ATOM_I2C_RECORD *i2c_record;
ATOM_I2C_ID_CONFIG_ACCESS *i2c_config;
ATOM_ROUTER_DDC_PATH_SELECT_RECORD *ddc_path;
ATOM_ROUTER_DATA_CLOCK_PATH_SELECT_RECORD *cd_path;
ATOM_SRC_DST_TABLE_FOR_ONE_OBJECT *router_src_dst_table =
(ATOM_SRC_DST_TABLE_FOR_ONE_OBJECT *)
(ctx->bios + data_offset +
le16_to_cpu(router_obj->asObjects[k].usSrcDstTableOffset));
int enum_id;
router.router_id = router_obj_id;
for (enum_id = 0; enum_id < router_src_dst_table->ucNumberOfDst;
enum_id++) {
if (le16_to_cpu(path->usConnObjectId) ==
le16_to_cpu(router_src_dst_table->usDstObjectID[enum_id]))
break;
}
while (record->ucRecordSize > 0 &&
record->ucRecordType > 0 &&
record->ucRecordType <= ATOM_MAX_OBJECT_RECORD_NUMBER) {
switch (record->ucRecordType) {
case ATOM_I2C_RECORD_TYPE:
i2c_record =
(ATOM_I2C_RECORD *)
record;
i2c_config =
(ATOM_I2C_ID_CONFIG_ACCESS *)
&i2c_record->sucI2cId;
router.i2c_info =
radeon_lookup_i2c_gpio(rdev,
i2c_config->
ucAccess);
router.i2c_addr = i2c_record->ucI2CAddr >> 1;
break;
case ATOM_ROUTER_DDC_PATH_SELECT_RECORD_TYPE:
ddc_path = (ATOM_ROUTER_DDC_PATH_SELECT_RECORD *)
record;
router.ddc_valid = true;
router.ddc_mux_type = ddc_path->ucMuxType;
router.ddc_mux_control_pin = ddc_path->ucMuxControlPin;
router.ddc_mux_state = ddc_path->ucMuxState[enum_id];
break;
case ATOM_ROUTER_DATA_CLOCK_PATH_SELECT_RECORD_TYPE:
cd_path = (ATOM_ROUTER_DATA_CLOCK_PATH_SELECT_RECORD *)
record;
router.cd_valid = true;
router.cd_mux_type = cd_path->ucMuxType;
router.cd_mux_control_pin = cd_path->ucMuxControlPin;
router.cd_mux_state = cd_path->ucMuxState[enum_id];
break;
}
record = (ATOM_COMMON_RECORD_HEADER *)
((char *)record + record->ucRecordSize);
}
}
}
}
}
/* look up gpio for ddc, hpd */
ddc_bus.valid = false;
hpd.hpd = RADEON_HPD_NONE;
if ((le16_to_cpu(path->usDeviceTag) &
(ATOM_DEVICE_TV_SUPPORT | ATOM_DEVICE_CV_SUPPORT)) == 0) {
for (j = 0; j < con_obj->ucNumberOfObjects; j++) {
if (le16_to_cpu(path->usConnObjectId) ==
le16_to_cpu(con_obj->asObjects[j].
usObjectID)) {
ATOM_COMMON_RECORD_HEADER
*record =
(ATOM_COMMON_RECORD_HEADER
*)
(ctx->bios + data_offset +
le16_to_cpu(con_obj->
asObjects[j].
usRecordOffset));
ATOM_I2C_RECORD *i2c_record;
ATOM_HPD_INT_RECORD *hpd_record;
ATOM_I2C_ID_CONFIG_ACCESS *i2c_config;
while (record->ucRecordSize > 0 &&
record->ucRecordType > 0 &&
record->ucRecordType <= ATOM_MAX_OBJECT_RECORD_NUMBER) {
switch (record->ucRecordType) {
case ATOM_I2C_RECORD_TYPE:
i2c_record =
(ATOM_I2C_RECORD *)
record;
i2c_config =
(ATOM_I2C_ID_CONFIG_ACCESS *)
&i2c_record->sucI2cId;
ddc_bus = radeon_lookup_i2c_gpio(rdev,
i2c_config->
ucAccess);
break;
case ATOM_HPD_INT_RECORD_TYPE:
hpd_record =
(ATOM_HPD_INT_RECORD *)
record;
gpio = radeon_lookup_gpio(rdev,
hpd_record->ucHPDIntGPIOID);
hpd = radeon_atom_get_hpd_info_from_gpio(rdev, &gpio);
hpd.plugged_state = hpd_record->ucPlugged_PinState;
break;
}
record =
(ATOM_COMMON_RECORD_HEADER
*) ((char *)record
+
record->
ucRecordSize);
}
break;
}
}
}
/* needed for aux chan transactions */
ddc_bus.hpd = hpd.hpd;
conn_id = le16_to_cpu(path->usConnObjectId);
if (!radeon_atom_apply_quirks
(dev, le16_to_cpu(path->usDeviceTag), &connector_type,
&ddc_bus, &conn_id, &hpd))
continue;
radeon_add_atom_connector(dev,
conn_id,
le16_to_cpu(path->
usDeviceTag),
connector_type, &ddc_bus,
igp_lane_info,
connector_object_id,
&hpd,
&router);
}
}
radeon_link_encoder_connector(dev);
return true;
}
static uint16_t atombios_get_connector_object_id(struct drm_device *dev,
int connector_type,
uint16_t devices)
{
struct radeon_device *rdev = dev->dev_private;
if (rdev->flags & RADEON_IS_IGP) {
return supported_devices_connector_object_id_convert
[connector_type];
} else if (((connector_type == DRM_MODE_CONNECTOR_DVII) ||
(connector_type == DRM_MODE_CONNECTOR_DVID)) &&
(devices & ATOM_DEVICE_DFP2_SUPPORT)) {
struct radeon_mode_info *mode_info = &rdev->mode_info;
struct atom_context *ctx = mode_info->atom_context;
int index = GetIndexIntoMasterTable(DATA, XTMDS_Info);
uint16_t size, data_offset;
uint8_t frev, crev;
ATOM_XTMDS_INFO *xtmds;
if (atom_parse_data_header(ctx, index, &size, &frev, &crev, &data_offset)) {
xtmds = (ATOM_XTMDS_INFO *)(ctx->bios + data_offset);
if (xtmds->ucSupportedLink & ATOM_XTMDS_SUPPORTED_DUALLINK) {
if (connector_type == DRM_MODE_CONNECTOR_DVII)
return CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_I;
else
return CONNECTOR_OBJECT_ID_DUAL_LINK_DVI_D;
} else {
if (connector_type == DRM_MODE_CONNECTOR_DVII)
return CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_I;
else
return CONNECTOR_OBJECT_ID_SINGLE_LINK_DVI_D;
}
} else
return supported_devices_connector_object_id_convert
[connector_type];
} else {
return supported_devices_connector_object_id_convert
[connector_type];
}
}
struct bios_connector {
bool valid;
uint16_t line_mux;
uint16_t devices;
int connector_type;
struct radeon_i2c_bus_rec ddc_bus;
struct radeon_hpd hpd;
};
bool radeon_get_atom_connector_info_from_supported_devices_table(struct
drm_device
*dev)
{
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
struct atom_context *ctx = mode_info->atom_context;
int index = GetIndexIntoMasterTable(DATA, SupportedDevicesInfo);
uint16_t size, data_offset;
uint8_t frev, crev;
uint16_t device_support;
uint8_t dac;
union atom_supported_devices *supported_devices;
int i, j, max_device;
struct bios_connector *bios_connectors;
size_t bc_size = sizeof(*bios_connectors) * ATOM_MAX_SUPPORTED_DEVICE;
struct radeon_router router;
router.ddc_valid = false;
router.cd_valid = false;
bios_connectors = kzalloc(bc_size, GFP_KERNEL);
if (!bios_connectors)
return false;
if (!atom_parse_data_header(ctx, index, &size, &frev, &crev,
&data_offset)) {
kfree(bios_connectors);
return false;
}
supported_devices =
(union atom_supported_devices *)(ctx->bios + data_offset);
device_support = le16_to_cpu(supported_devices->info.usDeviceSupport);
if (frev > 1)
max_device = ATOM_MAX_SUPPORTED_DEVICE;
else
max_device = ATOM_MAX_SUPPORTED_DEVICE_INFO;
for (i = 0; i < max_device; i++) {
ATOM_CONNECTOR_INFO_I2C ci =
supported_devices->info.asConnInfo[i];
bios_connectors[i].valid = false;
if (!(device_support & (1 << i))) {
continue;
}
if (i == ATOM_DEVICE_CV_INDEX) {
DRM_DEBUG_KMS("Skipping Component Video\n");
continue;
}
bios_connectors[i].connector_type =
supported_devices_connector_convert[ci.sucConnectorInfo.
sbfAccess.
bfConnectorType];
if (bios_connectors[i].connector_type ==
DRM_MODE_CONNECTOR_Unknown)
continue;
dac = ci.sucConnectorInfo.sbfAccess.bfAssociatedDAC;
bios_connectors[i].line_mux =
ci.sucI2cId.ucAccess;
/* give tv unique connector ids */
if (i == ATOM_DEVICE_TV1_INDEX) {
bios_connectors[i].ddc_bus.valid = false;
bios_connectors[i].line_mux = 50;
} else if (i == ATOM_DEVICE_TV2_INDEX) {
bios_connectors[i].ddc_bus.valid = false;
bios_connectors[i].line_mux = 51;
} else if (i == ATOM_DEVICE_CV_INDEX) {
bios_connectors[i].ddc_bus.valid = false;
bios_connectors[i].line_mux = 52;
} else
bios_connectors[i].ddc_bus =
radeon_lookup_i2c_gpio(rdev,
bios_connectors[i].line_mux);
if ((crev > 1) && (frev > 1)) {
u8 isb = supported_devices->info_2d1.asIntSrcInfo[i].ucIntSrcBitmap;
switch (isb) {
case 0x4:
bios_connectors[i].hpd.hpd = RADEON_HPD_1;
break;
case 0xa:
bios_connectors[i].hpd.hpd = RADEON_HPD_2;
break;
default:
bios_connectors[i].hpd.hpd = RADEON_HPD_NONE;
break;
}
} else {
if (i == ATOM_DEVICE_DFP1_INDEX)
bios_connectors[i].hpd.hpd = RADEON_HPD_1;
else if (i == ATOM_DEVICE_DFP2_INDEX)
bios_connectors[i].hpd.hpd = RADEON_HPD_2;
else
bios_connectors[i].hpd.hpd = RADEON_HPD_NONE;
}
/* Always set the connector type to VGA for CRT1/CRT2. if they are
* shared with a DVI port, we'll pick up the DVI connector when we
* merge the outputs. Some bioses incorrectly list VGA ports as DVI.
*/
if (i == ATOM_DEVICE_CRT1_INDEX || i == ATOM_DEVICE_CRT2_INDEX)
bios_connectors[i].connector_type =
DRM_MODE_CONNECTOR_VGA;
if (!radeon_atom_apply_quirks
(dev, (1 << i), &bios_connectors[i].connector_type,
&bios_connectors[i].ddc_bus, &bios_connectors[i].line_mux,
&bios_connectors[i].hpd))
continue;
bios_connectors[i].valid = true;
bios_connectors[i].devices = (1 << i);
if (ASIC_IS_AVIVO(rdev) || radeon_r4xx_atom)
radeon_add_atom_encoder(dev,
radeon_get_encoder_enum(dev,
(1 << i),
dac),
(1 << i),
0);
else
radeon_add_legacy_encoder(dev,
radeon_get_encoder_enum(dev,
(1 << i),
dac),
(1 << i));
}
/* combine shared connectors */
for (i = 0; i < max_device; i++) {
if (bios_connectors[i].valid) {
for (j = 0; j < max_device; j++) {
if (bios_connectors[j].valid && (i != j)) {
if (bios_connectors[i].line_mux ==
bios_connectors[j].line_mux) {
/* make sure not to combine LVDS */
if (bios_connectors[i].devices & (ATOM_DEVICE_LCD_SUPPORT)) {
bios_connectors[i].line_mux = 53;
bios_connectors[i].ddc_bus.valid = false;
continue;
}
if (bios_connectors[j].devices & (ATOM_DEVICE_LCD_SUPPORT)) {
bios_connectors[j].line_mux = 53;
bios_connectors[j].ddc_bus.valid = false;
continue;
}
/* combine analog and digital for DVI-I */
if (((bios_connectors[i].devices & (ATOM_DEVICE_DFP_SUPPORT)) &&
(bios_connectors[j].devices & (ATOM_DEVICE_CRT_SUPPORT))) ||
((bios_connectors[j].devices & (ATOM_DEVICE_DFP_SUPPORT)) &&
(bios_connectors[i].devices & (ATOM_DEVICE_CRT_SUPPORT)))) {
bios_connectors[i].devices |=
bios_connectors[j].devices;
bios_connectors[i].connector_type =
DRM_MODE_CONNECTOR_DVII;
if (bios_connectors[j].devices & (ATOM_DEVICE_DFP_SUPPORT))
bios_connectors[i].hpd =
bios_connectors[j].hpd;
bios_connectors[j].valid = false;
}
}
}
}
}
}
/* add the connectors */
for (i = 0; i < max_device; i++) {
if (bios_connectors[i].valid) {
uint16_t connector_object_id =
atombios_get_connector_object_id(dev,
bios_connectors[i].connector_type,
bios_connectors[i].devices);
radeon_add_atom_connector(dev,
bios_connectors[i].line_mux,
bios_connectors[i].devices,
bios_connectors[i].
connector_type,
&bios_connectors[i].ddc_bus,
0,
connector_object_id,
&bios_connectors[i].hpd,
&router);
}
}
radeon_link_encoder_connector(dev);
kfree(bios_connectors);
return true;
}
union firmware_info {
ATOM_FIRMWARE_INFO info;
ATOM_FIRMWARE_INFO_V1_2 info_12;
ATOM_FIRMWARE_INFO_V1_3 info_13;
ATOM_FIRMWARE_INFO_V1_4 info_14;
ATOM_FIRMWARE_INFO_V2_1 info_21;
ATOM_FIRMWARE_INFO_V2_2 info_22;
};
bool radeon_atom_get_clock_info(struct drm_device *dev)
{
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, FirmwareInfo);
union firmware_info *firmware_info;
uint8_t frev, crev;
struct radeon_pll *p1pll = &rdev->clock.p1pll;
struct radeon_pll *p2pll = &rdev->clock.p2pll;
struct radeon_pll *dcpll = &rdev->clock.dcpll;
struct radeon_pll *spll = &rdev->clock.spll;
struct radeon_pll *mpll = &rdev->clock.mpll;
uint16_t data_offset;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
firmware_info =
(union firmware_info *)(mode_info->atom_context->bios +
data_offset);
/* pixel clocks */
p1pll->reference_freq =
le16_to_cpu(firmware_info->info.usReferenceClock);
p1pll->reference_div = 0;
if (crev < 2)
p1pll->pll_out_min =
le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Output);
else
p1pll->pll_out_min =
le32_to_cpu(firmware_info->info_12.ulMinPixelClockPLL_Output);
p1pll->pll_out_max =
le32_to_cpu(firmware_info->info.ulMaxPixelClockPLL_Output);
if (crev >= 4) {
p1pll->lcd_pll_out_min =
le16_to_cpu(firmware_info->info_14.usLcdMinPixelClockPLL_Output) * 100;
if (p1pll->lcd_pll_out_min == 0)
p1pll->lcd_pll_out_min = p1pll->pll_out_min;
p1pll->lcd_pll_out_max =
le16_to_cpu(firmware_info->info_14.usLcdMaxPixelClockPLL_Output) * 100;
if (p1pll->lcd_pll_out_max == 0)
p1pll->lcd_pll_out_max = p1pll->pll_out_max;
} else {
p1pll->lcd_pll_out_min = p1pll->pll_out_min;
p1pll->lcd_pll_out_max = p1pll->pll_out_max;
}
if (p1pll->pll_out_min == 0) {
if (ASIC_IS_AVIVO(rdev))
p1pll->pll_out_min = 64800;
else
p1pll->pll_out_min = 20000;
}
p1pll->pll_in_min =
le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Input);
p1pll->pll_in_max =
le16_to_cpu(firmware_info->info.usMaxPixelClockPLL_Input);
*p2pll = *p1pll;
/* system clock */
if (ASIC_IS_DCE4(rdev))
spll->reference_freq =
le16_to_cpu(firmware_info->info_21.usCoreReferenceClock);
else
spll->reference_freq =
le16_to_cpu(firmware_info->info.usReferenceClock);
spll->reference_div = 0;
spll->pll_out_min =
le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Output);
spll->pll_out_max =
le32_to_cpu(firmware_info->info.ulMaxEngineClockPLL_Output);
/* ??? */
if (spll->pll_out_min == 0) {
if (ASIC_IS_AVIVO(rdev))
spll->pll_out_min = 64800;
else
spll->pll_out_min = 20000;
}
spll->pll_in_min =
le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Input);
spll->pll_in_max =
le16_to_cpu(firmware_info->info.usMaxEngineClockPLL_Input);
/* memory clock */
if (ASIC_IS_DCE4(rdev))
mpll->reference_freq =
le16_to_cpu(firmware_info->info_21.usMemoryReferenceClock);
else
mpll->reference_freq =
le16_to_cpu(firmware_info->info.usReferenceClock);
mpll->reference_div = 0;
mpll->pll_out_min =
le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Output);
mpll->pll_out_max =
le32_to_cpu(firmware_info->info.ulMaxMemoryClockPLL_Output);
/* ??? */
if (mpll->pll_out_min == 0) {
if (ASIC_IS_AVIVO(rdev))
mpll->pll_out_min = 64800;
else
mpll->pll_out_min = 20000;
}
mpll->pll_in_min =
le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Input);
mpll->pll_in_max =
le16_to_cpu(firmware_info->info.usMaxMemoryClockPLL_Input);
rdev->clock.default_sclk =
le32_to_cpu(firmware_info->info.ulDefaultEngineClock);
rdev->clock.default_mclk =
le32_to_cpu(firmware_info->info.ulDefaultMemoryClock);
if (ASIC_IS_DCE4(rdev)) {
rdev->clock.default_dispclk =
le32_to_cpu(firmware_info->info_21.ulDefaultDispEngineClkFreq);
if (rdev->clock.default_dispclk == 0) {
if (ASIC_IS_DCE5(rdev))
rdev->clock.default_dispclk = 54000; /* 540 Mhz */
else
rdev->clock.default_dispclk = 60000; /* 600 Mhz */
}
rdev->clock.dp_extclk =
le16_to_cpu(firmware_info->info_21.usUniphyDPModeExtClkFreq);
}
*dcpll = *p1pll;
rdev->clock.max_pixel_clock = le16_to_cpu(firmware_info->info.usMaxPixelClock);
if (rdev->clock.max_pixel_clock == 0)
rdev->clock.max_pixel_clock = 40000;
return true;
}
return false;
}
union igp_info {
struct _ATOM_INTEGRATED_SYSTEM_INFO info;
struct _ATOM_INTEGRATED_SYSTEM_INFO_V2 info_2;
};
bool radeon_atombios_sideport_present(struct radeon_device *rdev)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, IntegratedSystemInfo);
union igp_info *igp_info;
u8 frev, crev;
u16 data_offset;
/* sideport is AMD only */
if (rdev->family == CHIP_RS600)
return false;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
igp_info = (union igp_info *)(mode_info->atom_context->bios +
data_offset);
switch (crev) {
case 1:
if (le32_to_cpu(igp_info->info.ulBootUpMemoryClock))
return true;
break;
case 2:
if (le32_to_cpu(igp_info->info_2.ulBootUpSidePortClock))
return true;
break;
default:
DRM_ERROR("Unsupported IGP table: %d %d\n", frev, crev);
break;
}
}
return false;
}
bool radeon_atombios_get_tmds_info(struct radeon_encoder *encoder,
struct radeon_encoder_int_tmds *tmds)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, TMDS_Info);
uint16_t data_offset;
struct _ATOM_TMDS_INFO *tmds_info;
uint8_t frev, crev;
uint16_t maxfreq;
int i;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
tmds_info =
(struct _ATOM_TMDS_INFO *)(mode_info->atom_context->bios +
data_offset);
maxfreq = le16_to_cpu(tmds_info->usMaxFrequency);
for (i = 0; i < 4; i++) {
tmds->tmds_pll[i].freq =
le16_to_cpu(tmds_info->asMiscInfo[i].usFrequency);
tmds->tmds_pll[i].value =
tmds_info->asMiscInfo[i].ucPLL_ChargePump & 0x3f;
tmds->tmds_pll[i].value |=
(tmds_info->asMiscInfo[i].
ucPLL_VCO_Gain & 0x3f) << 6;
tmds->tmds_pll[i].value |=
(tmds_info->asMiscInfo[i].
ucPLL_DutyCycle & 0xf) << 12;
tmds->tmds_pll[i].value |=
(tmds_info->asMiscInfo[i].
ucPLL_VoltageSwing & 0xf) << 16;
DRM_DEBUG_KMS("TMDS PLL From ATOMBIOS %u %x\n",
tmds->tmds_pll[i].freq,
tmds->tmds_pll[i].value);
if (maxfreq == tmds->tmds_pll[i].freq) {
tmds->tmds_pll[i].freq = 0xffffffff;
break;
}
}
return true;
}
return false;
}
bool radeon_atombios_get_ppll_ss_info(struct radeon_device *rdev,
struct radeon_atom_ss *ss,
int id)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, PPLL_SS_Info);
uint16_t data_offset, size;
struct _ATOM_SPREAD_SPECTRUM_INFO *ss_info;
uint8_t frev, crev;
int i, num_indices;
memset(ss, 0, sizeof(struct radeon_atom_ss));
if (atom_parse_data_header(mode_info->atom_context, index, &size,
&frev, &crev, &data_offset)) {
ss_info =
(struct _ATOM_SPREAD_SPECTRUM_INFO *)(mode_info->atom_context->bios + data_offset);
num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) /
sizeof(ATOM_SPREAD_SPECTRUM_ASSIGNMENT);
for (i = 0; i < num_indices; i++) {
if (ss_info->asSS_Info[i].ucSS_Id == id) {
ss->percentage =
le16_to_cpu(ss_info->asSS_Info[i].usSpreadSpectrumPercentage);
ss->type = ss_info->asSS_Info[i].ucSpreadSpectrumType;
ss->step = ss_info->asSS_Info[i].ucSS_Step;
ss->delay = ss_info->asSS_Info[i].ucSS_Delay;
ss->range = ss_info->asSS_Info[i].ucSS_Range;
ss->refdiv = ss_info->asSS_Info[i].ucRecommendedRef_Div;
return true;
}
}
}
return false;
}
static void radeon_atombios_get_igp_ss_overrides(struct radeon_device *rdev,
struct radeon_atom_ss *ss,
int id)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, IntegratedSystemInfo);
u16 data_offset, size;
struct _ATOM_INTEGRATED_SYSTEM_INFO_V6 *igp_info;
u8 frev, crev;
u16 percentage = 0, rate = 0;
/* get any igp specific overrides */
if (atom_parse_data_header(mode_info->atom_context, index, &size,
&frev, &crev, &data_offset)) {
igp_info = (struct _ATOM_INTEGRATED_SYSTEM_INFO_V6 *)
(mode_info->atom_context->bios + data_offset);
switch (id) {
case ASIC_INTERNAL_SS_ON_TMDS:
percentage = le16_to_cpu(igp_info->usDVISSPercentage);
rate = le16_to_cpu(igp_info->usDVISSpreadRateIn10Hz);
break;
case ASIC_INTERNAL_SS_ON_HDMI:
percentage = le16_to_cpu(igp_info->usHDMISSPercentage);
rate = le16_to_cpu(igp_info->usHDMISSpreadRateIn10Hz);
break;
case ASIC_INTERNAL_SS_ON_LVDS:
percentage = le16_to_cpu(igp_info->usLvdsSSPercentage);
rate = le16_to_cpu(igp_info->usLvdsSSpreadRateIn10Hz);
break;
}
if (percentage)
ss->percentage = percentage;
if (rate)
ss->rate = rate;
}
}
union asic_ss_info {
struct _ATOM_ASIC_INTERNAL_SS_INFO info;
struct _ATOM_ASIC_INTERNAL_SS_INFO_V2 info_2;
struct _ATOM_ASIC_INTERNAL_SS_INFO_V3 info_3;
};
bool radeon_atombios_get_asic_ss_info(struct radeon_device *rdev,
struct radeon_atom_ss *ss,
int id, u32 clock)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, ASIC_InternalSS_Info);
uint16_t data_offset, size;
union asic_ss_info *ss_info;
uint8_t frev, crev;
int i, num_indices;
memset(ss, 0, sizeof(struct radeon_atom_ss));
if (atom_parse_data_header(mode_info->atom_context, index, &size,
&frev, &crev, &data_offset)) {
ss_info =
(union asic_ss_info *)(mode_info->atom_context->bios + data_offset);
switch (frev) {
case 1:
num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) /
sizeof(ATOM_ASIC_SS_ASSIGNMENT);
for (i = 0; i < num_indices; i++) {
if ((ss_info->info.asSpreadSpectrum[i].ucClockIndication == id) &&
(clock <= le32_to_cpu(ss_info->info.asSpreadSpectrum[i].ulTargetClockRange))) {
ss->percentage =
le16_to_cpu(ss_info->info.asSpreadSpectrum[i].usSpreadSpectrumPercentage);
ss->type = ss_info->info.asSpreadSpectrum[i].ucSpreadSpectrumMode;
ss->rate = le16_to_cpu(ss_info->info.asSpreadSpectrum[i].usSpreadRateInKhz);
return true;
}
}
break;
case 2:
num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) /
sizeof(ATOM_ASIC_SS_ASSIGNMENT_V2);
for (i = 0; i < num_indices; i++) {
if ((ss_info->info_2.asSpreadSpectrum[i].ucClockIndication == id) &&
(clock <= le32_to_cpu(ss_info->info_2.asSpreadSpectrum[i].ulTargetClockRange))) {
ss->percentage =
le16_to_cpu(ss_info->info_2.asSpreadSpectrum[i].usSpreadSpectrumPercentage);
ss->type = ss_info->info_2.asSpreadSpectrum[i].ucSpreadSpectrumMode;
ss->rate = le16_to_cpu(ss_info->info_2.asSpreadSpectrum[i].usSpreadRateIn10Hz);
return true;
}
}
break;
case 3:
num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) /
sizeof(ATOM_ASIC_SS_ASSIGNMENT_V3);
for (i = 0; i < num_indices; i++) {
if ((ss_info->info_3.asSpreadSpectrum[i].ucClockIndication == id) &&
(clock <= le32_to_cpu(ss_info->info_3.asSpreadSpectrum[i].ulTargetClockRange))) {
ss->percentage =
le16_to_cpu(ss_info->info_3.asSpreadSpectrum[i].usSpreadSpectrumPercentage);
ss->type = ss_info->info_3.asSpreadSpectrum[i].ucSpreadSpectrumMode;
ss->rate = le16_to_cpu(ss_info->info_3.asSpreadSpectrum[i].usSpreadRateIn10Hz);
if (rdev->flags & RADEON_IS_IGP)
radeon_atombios_get_igp_ss_overrides(rdev, ss, id);
return true;
}
}
break;
default:
DRM_ERROR("Unsupported ASIC_InternalSS_Info table: %d %d\n", frev, crev);
break;
}
}
return false;
}
union lvds_info {
struct _ATOM_LVDS_INFO info;
struct _ATOM_LVDS_INFO_V12 info_12;
};
struct radeon_encoder_atom_dig *radeon_atombios_get_lvds_info(struct
radeon_encoder
*encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, LVDS_Info);
uint16_t data_offset, misc;
union lvds_info *lvds_info;
uint8_t frev, crev;
struct radeon_encoder_atom_dig *lvds = NULL;
int encoder_enum = (encoder->encoder_enum & ENUM_ID_MASK) >> ENUM_ID_SHIFT;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
lvds_info =
(union lvds_info *)(mode_info->atom_context->bios + data_offset);
lvds =
kzalloc(sizeof(struct radeon_encoder_atom_dig), GFP_KERNEL);
if (!lvds)
return NULL;
lvds->native_mode.clock =
le16_to_cpu(lvds_info->info.sLCDTiming.usPixClk) * 10;
lvds->native_mode.hdisplay =
le16_to_cpu(lvds_info->info.sLCDTiming.usHActive);
lvds->native_mode.vdisplay =
le16_to_cpu(lvds_info->info.sLCDTiming.usVActive);
lvds->native_mode.htotal = lvds->native_mode.hdisplay +
le16_to_cpu(lvds_info->info.sLCDTiming.usHBlanking_Time);
lvds->native_mode.hsync_start = lvds->native_mode.hdisplay +
le16_to_cpu(lvds_info->info.sLCDTiming.usHSyncOffset);
lvds->native_mode.hsync_end = lvds->native_mode.hsync_start +
le16_to_cpu(lvds_info->info.sLCDTiming.usHSyncWidth);
lvds->native_mode.vtotal = lvds->native_mode.vdisplay +
le16_to_cpu(lvds_info->info.sLCDTiming.usVBlanking_Time);
lvds->native_mode.vsync_start = lvds->native_mode.vdisplay +
le16_to_cpu(lvds_info->info.sLCDTiming.usVSyncOffset);
lvds->native_mode.vsync_end = lvds->native_mode.vsync_start +
le16_to_cpu(lvds_info->info.sLCDTiming.usVSyncWidth);
lvds->panel_pwr_delay =
le16_to_cpu(lvds_info->info.usOffDelayInMs);
lvds->lcd_misc = lvds_info->info.ucLVDS_Misc;
misc = le16_to_cpu(lvds_info->info.sLCDTiming.susModeMiscInfo.usAccess);
if (misc & ATOM_VSYNC_POLARITY)
lvds->native_mode.flags |= DRM_MODE_FLAG_NVSYNC;
if (misc & ATOM_HSYNC_POLARITY)
lvds->native_mode.flags |= DRM_MODE_FLAG_NHSYNC;
if (misc & ATOM_COMPOSITESYNC)
lvds->native_mode.flags |= DRM_MODE_FLAG_CSYNC;
if (misc & ATOM_INTERLACE)
lvds->native_mode.flags |= DRM_MODE_FLAG_INTERLACE;
if (misc & ATOM_DOUBLE_CLOCK_MODE)
lvds->native_mode.flags |= DRM_MODE_FLAG_DBLSCAN;
lvds->native_mode.width_mm = le16_to_cpu(lvds_info->info.sLCDTiming.usImageHSize);
lvds->native_mode.height_mm = le16_to_cpu(lvds_info->info.sLCDTiming.usImageVSize);
/* set crtc values */
drm_mode_set_crtcinfo(&lvds->native_mode, CRTC_INTERLACE_HALVE_V);
lvds->lcd_ss_id = lvds_info->info.ucSS_Id;
encoder->native_mode = lvds->native_mode;
if (encoder_enum == 2)
lvds->linkb = true;
else
lvds->linkb = false;
/* parse the lcd record table */
if (le16_to_cpu(lvds_info->info.usModePatchTableOffset)) {
ATOM_FAKE_EDID_PATCH_RECORD *fake_edid_record;
ATOM_PANEL_RESOLUTION_PATCH_RECORD *panel_res_record;
bool bad_record = false;
u8 *record;
if ((frev == 1) && (crev < 2))
/* absolute */
record = (u8 *)(mode_info->atom_context->bios +
le16_to_cpu(lvds_info->info.usModePatchTableOffset));
else
/* relative */
record = (u8 *)(mode_info->atom_context->bios +
data_offset +
le16_to_cpu(lvds_info->info.usModePatchTableOffset));
while (*record != ATOM_RECORD_END_TYPE) {
switch (*record) {
case LCD_MODE_PATCH_RECORD_MODE_TYPE:
record += sizeof(ATOM_PATCH_RECORD_MODE);
break;
case LCD_RTS_RECORD_TYPE:
record += sizeof(ATOM_LCD_RTS_RECORD);
break;
case LCD_CAP_RECORD_TYPE:
record += sizeof(ATOM_LCD_MODE_CONTROL_CAP);
break;
case LCD_FAKE_EDID_PATCH_RECORD_TYPE:
fake_edid_record = (ATOM_FAKE_EDID_PATCH_RECORD *)record;
if (fake_edid_record->ucFakeEDIDLength) {
struct edid *edid;
int edid_size =
max((int)EDID_LENGTH, (int)fake_edid_record->ucFakeEDIDLength);
edid = kmalloc(edid_size, GFP_KERNEL);
if (edid) {
memcpy((u8 *)edid, (u8 *)&fake_edid_record->ucFakeEDIDString[0],
fake_edid_record->ucFakeEDIDLength);
if (drm_edid_is_valid(edid)) {
rdev->mode_info.bios_hardcoded_edid = edid;
rdev->mode_info.bios_hardcoded_edid_size = edid_size;
} else
kfree(edid);
}
}
record += sizeof(ATOM_FAKE_EDID_PATCH_RECORD);
break;
case LCD_PANEL_RESOLUTION_RECORD_TYPE:
panel_res_record = (ATOM_PANEL_RESOLUTION_PATCH_RECORD *)record;
lvds->native_mode.width_mm = panel_res_record->usHSize;
lvds->native_mode.height_mm = panel_res_record->usVSize;
record += sizeof(ATOM_PANEL_RESOLUTION_PATCH_RECORD);
break;
default:
DRM_ERROR("Bad LCD record %d\n", *record);
bad_record = true;
break;
}
if (bad_record)
break;
}
}
}
return lvds;
}
struct radeon_encoder_primary_dac *
radeon_atombios_get_primary_dac_info(struct radeon_encoder *encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, CompassionateData);
uint16_t data_offset;
struct _COMPASSIONATE_DATA *dac_info;
uint8_t frev, crev;
uint8_t bg, dac;
struct radeon_encoder_primary_dac *p_dac = NULL;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
dac_info = (struct _COMPASSIONATE_DATA *)
(mode_info->atom_context->bios + data_offset);
p_dac = kzalloc(sizeof(struct radeon_encoder_primary_dac), GFP_KERNEL);
if (!p_dac)
return NULL;
bg = dac_info->ucDAC1_BG_Adjustment;
dac = dac_info->ucDAC1_DAC_Adjustment;
p_dac->ps2_pdac_adj = (bg << 8) | (dac);
}
return p_dac;
}
bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index,
struct drm_display_mode *mode)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
ATOM_ANALOG_TV_INFO *tv_info;
ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2;
ATOM_DTD_FORMAT *dtd_timings;
int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info);
u8 frev, crev;
u16 data_offset, misc;
if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL,
&frev, &crev, &data_offset))
return false;
switch (crev) {
case 1:
tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset);
if (index >= MAX_SUPPORTED_TV_TIMING)
return false;
mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total);
mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp);
mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart);
mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) +
le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth);
mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total);
mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp);
mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart);
mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) +
le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth);
mode->flags = 0;
misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess);
if (misc & ATOM_VSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NVSYNC;
if (misc & ATOM_HSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NHSYNC;
if (misc & ATOM_COMPOSITESYNC)
mode->flags |= DRM_MODE_FLAG_CSYNC;
if (misc & ATOM_INTERLACE)
mode->flags |= DRM_MODE_FLAG_INTERLACE;
if (misc & ATOM_DOUBLE_CLOCK_MODE)
mode->flags |= DRM_MODE_FLAG_DBLSCAN;
mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10;
if (index == 1) {
/* PAL timings appear to have wrong values for totals */
mode->crtc_htotal -= 1;
mode->crtc_vtotal -= 1;
}
break;
case 2:
tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset);
if (index >= MAX_SUPPORTED_TV_TIMING_V1_2)
return false;
dtd_timings = &tv_info_v1_2->aModeTimings[index];
mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) +
le16_to_cpu(dtd_timings->usHBlanking_Time);
mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive);
mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) +
le16_to_cpu(dtd_timings->usHSyncOffset);
mode->crtc_hsync_end = mode->crtc_hsync_start +
le16_to_cpu(dtd_timings->usHSyncWidth);
mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) +
le16_to_cpu(dtd_timings->usVBlanking_Time);
mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive);
mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) +
le16_to_cpu(dtd_timings->usVSyncOffset);
mode->crtc_vsync_end = mode->crtc_vsync_start +
le16_to_cpu(dtd_timings->usVSyncWidth);
mode->flags = 0;
misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess);
if (misc & ATOM_VSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NVSYNC;
if (misc & ATOM_HSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NHSYNC;
if (misc & ATOM_COMPOSITESYNC)
mode->flags |= DRM_MODE_FLAG_CSYNC;
if (misc & ATOM_INTERLACE)
mode->flags |= DRM_MODE_FLAG_INTERLACE;
if (misc & ATOM_DOUBLE_CLOCK_MODE)
mode->flags |= DRM_MODE_FLAG_DBLSCAN;
mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10;
break;
}
return true;
}
enum radeon_tv_std
radeon_atombios_get_tv_info(struct radeon_device *rdev)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, AnalogTV_Info);
uint16_t data_offset;
uint8_t frev, crev;
struct _ATOM_ANALOG_TV_INFO *tv_info;
enum radeon_tv_std tv_std = TV_STD_NTSC;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
tv_info = (struct _ATOM_ANALOG_TV_INFO *)
(mode_info->atom_context->bios + data_offset);
switch (tv_info->ucTV_BootUpDefaultStandard) {
case ATOM_TV_NTSC:
tv_std = TV_STD_NTSC;
DRM_DEBUG_KMS("Default TV standard: NTSC\n");
break;
case ATOM_TV_NTSCJ:
tv_std = TV_STD_NTSC_J;
DRM_DEBUG_KMS("Default TV standard: NTSC-J\n");
break;
case ATOM_TV_PAL:
tv_std = TV_STD_PAL;
DRM_DEBUG_KMS("Default TV standard: PAL\n");
break;
case ATOM_TV_PALM:
tv_std = TV_STD_PAL_M;
DRM_DEBUG_KMS("Default TV standard: PAL-M\n");
break;
case ATOM_TV_PALN:
tv_std = TV_STD_PAL_N;
DRM_DEBUG_KMS("Default TV standard: PAL-N\n");
break;
case ATOM_TV_PALCN:
tv_std = TV_STD_PAL_CN;
DRM_DEBUG_KMS("Default TV standard: PAL-CN\n");
break;
case ATOM_TV_PAL60:
tv_std = TV_STD_PAL_60;
DRM_DEBUG_KMS("Default TV standard: PAL-60\n");
break;
case ATOM_TV_SECAM:
tv_std = TV_STD_SECAM;
DRM_DEBUG_KMS("Default TV standard: SECAM\n");
break;
default:
tv_std = TV_STD_NTSC;
DRM_DEBUG_KMS("Unknown TV standard; defaulting to NTSC\n");
break;
}
}
return tv_std;
}
struct radeon_encoder_tv_dac *
radeon_atombios_get_tv_dac_info(struct radeon_encoder *encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, CompassionateData);
uint16_t data_offset;
struct _COMPASSIONATE_DATA *dac_info;
uint8_t frev, crev;
uint8_t bg, dac;
struct radeon_encoder_tv_dac *tv_dac = NULL;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
dac_info = (struct _COMPASSIONATE_DATA *)
(mode_info->atom_context->bios + data_offset);
tv_dac = kzalloc(sizeof(struct radeon_encoder_tv_dac), GFP_KERNEL);
if (!tv_dac)
return NULL;
bg = dac_info->ucDAC2_CRT2_BG_Adjustment;
dac = dac_info->ucDAC2_CRT2_DAC_Adjustment;
tv_dac->ps2_tvdac_adj = (bg << 16) | (dac << 20);
bg = dac_info->ucDAC2_PAL_BG_Adjustment;
dac = dac_info->ucDAC2_PAL_DAC_Adjustment;
tv_dac->pal_tvdac_adj = (bg << 16) | (dac << 20);
bg = dac_info->ucDAC2_NTSC_BG_Adjustment;
dac = dac_info->ucDAC2_NTSC_DAC_Adjustment;
tv_dac->ntsc_tvdac_adj = (bg << 16) | (dac << 20);
tv_dac->tv_std = radeon_atombios_get_tv_info(rdev);
}
return tv_dac;
}
static const char *thermal_controller_names[] = {
"NONE",
"lm63",
"adm1032",
"adm1030",
"max6649",
"lm64",
"f75375",
"asc7xxx",
};
static const char *pp_lib_thermal_controller_names[] = {
"NONE",
"lm63",
"adm1032",
"adm1030",
"max6649",
"lm64",
"f75375",
"RV6xx",
"RV770",
"adt7473",
"NONE",
"External GPIO",
"Evergreen",
"emc2103",
"Sumo",
"Northern Islands",
"Southern Islands",
"lm96163",
};
union power_info {
struct _ATOM_POWERPLAY_INFO info;
struct _ATOM_POWERPLAY_INFO_V2 info_2;
struct _ATOM_POWERPLAY_INFO_V3 info_3;
struct _ATOM_PPLIB_POWERPLAYTABLE pplib;
struct _ATOM_PPLIB_POWERPLAYTABLE2 pplib2;
struct _ATOM_PPLIB_POWERPLAYTABLE3 pplib3;
};
union pplib_clock_info {
struct _ATOM_PPLIB_R600_CLOCK_INFO r600;
struct _ATOM_PPLIB_RS780_CLOCK_INFO rs780;
struct _ATOM_PPLIB_EVERGREEN_CLOCK_INFO evergreen;
struct _ATOM_PPLIB_SUMO_CLOCK_INFO sumo;
struct _ATOM_PPLIB_SI_CLOCK_INFO si;
};
union pplib_power_state {
struct _ATOM_PPLIB_STATE v1;
struct _ATOM_PPLIB_STATE_V2 v2;
};
static void radeon_atombios_parse_misc_flags_1_3(struct radeon_device *rdev,
int state_index,
u32 misc, u32 misc2)
{
rdev->pm.power_state[state_index].misc = misc;
rdev->pm.power_state[state_index].misc2 = misc2;
/* order matters! */
if (misc & ATOM_PM_MISCINFO_POWER_SAVING_MODE)
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_POWERSAVE;
if (misc & ATOM_PM_MISCINFO_DEFAULT_DC_STATE_ENTRY_TRUE)
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_BATTERY;
if (misc & ATOM_PM_MISCINFO_DEFAULT_LOW_DC_STATE_ENTRY_TRUE)
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_BATTERY;
if (misc & ATOM_PM_MISCINFO_LOAD_BALANCE_EN)
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_BALANCED;
if (misc & ATOM_PM_MISCINFO_3D_ACCELERATION_EN) {
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_PERFORMANCE;
rdev->pm.power_state[state_index].flags &=
~RADEON_PM_STATE_SINGLE_DISPLAY_ONLY;
}
if (misc2 & ATOM_PM_MISCINFO2_SYSTEM_AC_LITE_MODE)
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_BALANCED;
if (misc & ATOM_PM_MISCINFO_DRIVER_DEFAULT_MODE) {
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_DEFAULT;
rdev->pm.default_power_state_index = state_index;
rdev->pm.power_state[state_index].default_clock_mode =
&rdev->pm.power_state[state_index].clock_info[0];
} else if (state_index == 0) {
rdev->pm.power_state[state_index].clock_info[0].flags |=
RADEON_PM_MODE_NO_DISPLAY;
}
}
static int radeon_atombios_parse_power_table_1_3(struct radeon_device *rdev)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
u32 misc, misc2 = 0;
int num_modes = 0, i;
int state_index = 0;
struct radeon_i2c_bus_rec i2c_bus;
union power_info *power_info;
int index = GetIndexIntoMasterTable(DATA, PowerPlayInfo);
u16 data_offset;
u8 frev, crev;
if (!atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset))
return state_index;
power_info = (union power_info *)(mode_info->atom_context->bios + data_offset);
/* add the i2c bus for thermal/fan chip */
if (power_info->info.ucOverdriveThermalController > 0) {
DRM_INFO("Possible %s thermal controller at 0x%02x\n",
thermal_controller_names[power_info->info.ucOverdriveThermalController],
power_info->info.ucOverdriveControllerAddress >> 1);
i2c_bus = radeon_lookup_i2c_gpio(rdev, power_info->info.ucOverdriveI2cLine);
rdev->pm.i2c_bus = radeon_i2c_lookup(rdev, &i2c_bus);
if (rdev->pm.i2c_bus) {
struct i2c_board_info info = { };
const char *name = thermal_controller_names[power_info->info.
ucOverdriveThermalController];
info.addr = power_info->info.ucOverdriveControllerAddress >> 1;
strlcpy(info.type, name, sizeof(info.type));
i2c_new_device(&rdev->pm.i2c_bus->adapter, &info);
}
}
num_modes = power_info->info.ucNumOfPowerModeEntries;
if (num_modes > ATOM_MAX_NUMBEROF_POWER_BLOCK)
num_modes = ATOM_MAX_NUMBEROF_POWER_BLOCK;
rdev->pm.power_state = kzalloc(sizeof(struct radeon_power_state) * num_modes, GFP_KERNEL);
if (!rdev->pm.power_state)
return state_index;
/* last mode is usually default, array is low to high */
for (i = 0; i < num_modes; i++) {
rdev->pm.power_state[state_index].clock_info =
kzalloc(sizeof(struct radeon_pm_clock_info) * 1, GFP_KERNEL);
if (!rdev->pm.power_state[state_index].clock_info)
return state_index;
rdev->pm.power_state[state_index].num_clock_modes = 1;
rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_NONE;
switch (frev) {
case 1:
rdev->pm.power_state[state_index].clock_info[0].mclk =
le16_to_cpu(power_info->info.asPowerPlayInfo[i].usMemoryClock);
rdev->pm.power_state[state_index].clock_info[0].sclk =
le16_to_cpu(power_info->info.asPowerPlayInfo[i].usEngineClock);
/* skip invalid modes */
if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) ||
(rdev->pm.power_state[state_index].clock_info[0].sclk == 0))
continue;
rdev->pm.power_state[state_index].pcie_lanes =
power_info->info.asPowerPlayInfo[i].ucNumPciELanes;
misc = le32_to_cpu(power_info->info.asPowerPlayInfo[i].ulMiscInfo);
if ((misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) ||
(misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH)) {
rdev->pm.power_state[state_index].clock_info[0].voltage.type =
VOLTAGE_GPIO;
rdev->pm.power_state[state_index].clock_info[0].voltage.gpio =
radeon_lookup_gpio(rdev,
power_info->info.asPowerPlayInfo[i].ucVoltageDropIndex);
if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH)
rdev->pm.power_state[state_index].clock_info[0].voltage.active_high =
true;
else
rdev->pm.power_state[state_index].clock_info[0].voltage.active_high =
false;
} else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) {
rdev->pm.power_state[state_index].clock_info[0].voltage.type =
VOLTAGE_VDDC;
rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id =
power_info->info.asPowerPlayInfo[i].ucVoltageDropIndex;
}
rdev->pm.power_state[state_index].flags = RADEON_PM_STATE_SINGLE_DISPLAY_ONLY;
radeon_atombios_parse_misc_flags_1_3(rdev, state_index, misc, 0);
state_index++;
break;
case 2:
rdev->pm.power_state[state_index].clock_info[0].mclk =
le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMemoryClock);
rdev->pm.power_state[state_index].clock_info[0].sclk =
le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulEngineClock);
/* skip invalid modes */
if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) ||
(rdev->pm.power_state[state_index].clock_info[0].sclk == 0))
continue;
rdev->pm.power_state[state_index].pcie_lanes =
power_info->info_2.asPowerPlayInfo[i].ucNumPciELanes;
misc = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMiscInfo);
misc2 = le32_to_cpu(power_info->info_2.asPowerPlayInfo[i].ulMiscInfo2);
if ((misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) ||
(misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH)) {
rdev->pm.power_state[state_index].clock_info[0].voltage.type =
VOLTAGE_GPIO;
rdev->pm.power_state[state_index].clock_info[0].voltage.gpio =
radeon_lookup_gpio(rdev,
power_info->info_2.asPowerPlayInfo[i].ucVoltageDropIndex);
if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH)
rdev->pm.power_state[state_index].clock_info[0].voltage.active_high =
true;
else
rdev->pm.power_state[state_index].clock_info[0].voltage.active_high =
false;
} else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) {
rdev->pm.power_state[state_index].clock_info[0].voltage.type =
VOLTAGE_VDDC;
rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id =
power_info->info_2.asPowerPlayInfo[i].ucVoltageDropIndex;
}
rdev->pm.power_state[state_index].flags = RADEON_PM_STATE_SINGLE_DISPLAY_ONLY;
radeon_atombios_parse_misc_flags_1_3(rdev, state_index, misc, misc2);
state_index++;
break;
case 3:
rdev->pm.power_state[state_index].clock_info[0].mclk =
le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMemoryClock);
rdev->pm.power_state[state_index].clock_info[0].sclk =
le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulEngineClock);
/* skip invalid modes */
if ((rdev->pm.power_state[state_index].clock_info[0].mclk == 0) ||
(rdev->pm.power_state[state_index].clock_info[0].sclk == 0))
continue;
rdev->pm.power_state[state_index].pcie_lanes =
power_info->info_3.asPowerPlayInfo[i].ucNumPciELanes;
misc = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMiscInfo);
misc2 = le32_to_cpu(power_info->info_3.asPowerPlayInfo[i].ulMiscInfo2);
if ((misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) ||
(misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH)) {
rdev->pm.power_state[state_index].clock_info[0].voltage.type =
VOLTAGE_GPIO;
rdev->pm.power_state[state_index].clock_info[0].voltage.gpio =
radeon_lookup_gpio(rdev,
power_info->info_3.asPowerPlayInfo[i].ucVoltageDropIndex);
if (misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_ACTIVE_HIGH)
rdev->pm.power_state[state_index].clock_info[0].voltage.active_high =
true;
else
rdev->pm.power_state[state_index].clock_info[0].voltage.active_high =
false;
} else if (misc & ATOM_PM_MISCINFO_PROGRAM_VOLTAGE) {
rdev->pm.power_state[state_index].clock_info[0].voltage.type =
VOLTAGE_VDDC;
rdev->pm.power_state[state_index].clock_info[0].voltage.vddc_id =
power_info->info_3.asPowerPlayInfo[i].ucVoltageDropIndex;
if (misc2 & ATOM_PM_MISCINFO2_VDDCI_DYNAMIC_VOLTAGE_EN) {
rdev->pm.power_state[state_index].clock_info[0].voltage.vddci_enabled =
true;
rdev->pm.power_state[state_index].clock_info[0].voltage.vddci_id =
power_info->info_3.asPowerPlayInfo[i].ucVDDCI_VoltageDropIndex;
}
}
rdev->pm.power_state[state_index].flags = RADEON_PM_STATE_SINGLE_DISPLAY_ONLY;
radeon_atombios_parse_misc_flags_1_3(rdev, state_index, misc, misc2);
state_index++;
break;
}
}
/* last mode is usually default */
if (rdev->pm.default_power_state_index == -1) {
rdev->pm.power_state[state_index - 1].type =
POWER_STATE_TYPE_DEFAULT;
rdev->pm.default_power_state_index = state_index - 1;
rdev->pm.power_state[state_index - 1].default_clock_mode =
&rdev->pm.power_state[state_index - 1].clock_info[0];
rdev->pm.power_state[state_index].flags &=
~RADEON_PM_STATE_SINGLE_DISPLAY_ONLY;
rdev->pm.power_state[state_index].misc = 0;
rdev->pm.power_state[state_index].misc2 = 0;
}
return state_index;
}
static void radeon_atombios_add_pplib_thermal_controller(struct radeon_device *rdev,
ATOM_PPLIB_THERMALCONTROLLER *controller)
{
struct radeon_i2c_bus_rec i2c_bus;
/* add the i2c bus for thermal/fan chip */
if (controller->ucType > 0) {
if (controller->ucType == ATOM_PP_THERMALCONTROLLER_RV6xx) {
DRM_INFO("Internal thermal controller %s fan control\n",
(controller->ucFanParameters &
ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with");
rdev->pm.int_thermal_type = THERMAL_TYPE_RV6XX;
} else if (controller->ucType == ATOM_PP_THERMALCONTROLLER_RV770) {
DRM_INFO("Internal thermal controller %s fan control\n",
(controller->ucFanParameters &
ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with");
rdev->pm.int_thermal_type = THERMAL_TYPE_RV770;
} else if (controller->ucType == ATOM_PP_THERMALCONTROLLER_EVERGREEN) {
DRM_INFO("Internal thermal controller %s fan control\n",
(controller->ucFanParameters &
ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with");
rdev->pm.int_thermal_type = THERMAL_TYPE_EVERGREEN;
} else if (controller->ucType == ATOM_PP_THERMALCONTROLLER_SUMO) {
DRM_INFO("Internal thermal controller %s fan control\n",
(controller->ucFanParameters &
ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with");
rdev->pm.int_thermal_type = THERMAL_TYPE_SUMO;
} else if (controller->ucType == ATOM_PP_THERMALCONTROLLER_NISLANDS) {
DRM_INFO("Internal thermal controller %s fan control\n",
(controller->ucFanParameters &
ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with");
rdev->pm.int_thermal_type = THERMAL_TYPE_NI;
} else if (controller->ucType == ATOM_PP_THERMALCONTROLLER_SISLANDS) {
DRM_INFO("Internal thermal controller %s fan control\n",
(controller->ucFanParameters &
ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with");
rdev->pm.int_thermal_type = THERMAL_TYPE_SI;
} else if ((controller->ucType ==
ATOM_PP_THERMALCONTROLLER_EXTERNAL_GPIO) ||
(controller->ucType ==
ATOM_PP_THERMALCONTROLLER_ADT7473_WITH_INTERNAL) ||
(controller->ucType ==
ATOM_PP_THERMALCONTROLLER_EMC2103_WITH_INTERNAL)) {
DRM_INFO("Special thermal controller config\n");
} else {
DRM_INFO("Possible %s thermal controller at 0x%02x %s fan control\n",
pp_lib_thermal_controller_names[controller->ucType],
controller->ucI2cAddress >> 1,
(controller->ucFanParameters &
ATOM_PP_FANPARAMETERS_NOFAN) ? "without" : "with");
i2c_bus = radeon_lookup_i2c_gpio(rdev, controller->ucI2cLine);
rdev->pm.i2c_bus = radeon_i2c_lookup(rdev, &i2c_bus);
if (rdev->pm.i2c_bus) {
struct i2c_board_info info = { };
const char *name = pp_lib_thermal_controller_names[controller->ucType];
info.addr = controller->ucI2cAddress >> 1;
strlcpy(info.type, name, sizeof(info.type));
i2c_new_device(&rdev->pm.i2c_bus->adapter, &info);
}
}
}
}
static void radeon_atombios_get_default_voltages(struct radeon_device *rdev,
u16 *vddc, u16 *vddci)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, FirmwareInfo);
u8 frev, crev;
u16 data_offset;
union firmware_info *firmware_info;
*vddc = 0;
*vddci = 0;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
firmware_info =
(union firmware_info *)(mode_info->atom_context->bios +
data_offset);
*vddc = le16_to_cpu(firmware_info->info_14.usBootUpVDDCVoltage);
if ((frev == 2) && (crev >= 2))
*vddci = le16_to_cpu(firmware_info->info_22.usBootUpVDDCIVoltage);
}
}
static void radeon_atombios_parse_pplib_non_clock_info(struct radeon_device *rdev,
int state_index, int mode_index,
struct _ATOM_PPLIB_NONCLOCK_INFO *non_clock_info)
{
int j;
u32 misc = le32_to_cpu(non_clock_info->ulCapsAndSettings);
u32 misc2 = le16_to_cpu(non_clock_info->usClassification);
u16 vddc, vddci;
radeon_atombios_get_default_voltages(rdev, &vddc, &vddci);
rdev->pm.power_state[state_index].misc = misc;
rdev->pm.power_state[state_index].misc2 = misc2;
rdev->pm.power_state[state_index].pcie_lanes =
((misc & ATOM_PPLIB_PCIE_LINK_WIDTH_MASK) >>
ATOM_PPLIB_PCIE_LINK_WIDTH_SHIFT) + 1;
switch (misc2 & ATOM_PPLIB_CLASSIFICATION_UI_MASK) {
case ATOM_PPLIB_CLASSIFICATION_UI_BATTERY:
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_BATTERY;
break;
case ATOM_PPLIB_CLASSIFICATION_UI_BALANCED:
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_BALANCED;
break;
case ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE:
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_PERFORMANCE;
break;
case ATOM_PPLIB_CLASSIFICATION_UI_NONE:
if (misc2 & ATOM_PPLIB_CLASSIFICATION_3DPERFORMANCE)
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_PERFORMANCE;
break;
}
rdev->pm.power_state[state_index].flags = 0;
if (misc & ATOM_PPLIB_SINGLE_DISPLAY_ONLY)
rdev->pm.power_state[state_index].flags |=
RADEON_PM_STATE_SINGLE_DISPLAY_ONLY;
if (misc2 & ATOM_PPLIB_CLASSIFICATION_BOOT) {
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_DEFAULT;
rdev->pm.default_power_state_index = state_index;
rdev->pm.power_state[state_index].default_clock_mode =
&rdev->pm.power_state[state_index].clock_info[mode_index - 1];
if (ASIC_IS_DCE5(rdev) && !(rdev->flags & RADEON_IS_IGP)) {
/* NI chips post without MC ucode, so default clocks are strobe mode only */
rdev->pm.default_sclk = rdev->pm.power_state[state_index].clock_info[0].sclk;
rdev->pm.default_mclk = rdev->pm.power_state[state_index].clock_info[0].mclk;
rdev->pm.default_vddc = rdev->pm.power_state[state_index].clock_info[0].voltage.voltage;
rdev->pm.default_vddci = rdev->pm.power_state[state_index].clock_info[0].voltage.vddci;
} else {
/* patch the table values with the default slck/mclk from firmware info */
for (j = 0; j < mode_index; j++) {
rdev->pm.power_state[state_index].clock_info[j].mclk =
rdev->clock.default_mclk;
rdev->pm.power_state[state_index].clock_info[j].sclk =
rdev->clock.default_sclk;
if (vddc)
rdev->pm.power_state[state_index].clock_info[j].voltage.voltage =
vddc;
}
}
}
}
static bool radeon_atombios_parse_pplib_clock_info(struct radeon_device *rdev,
int state_index, int mode_index,
union pplib_clock_info *clock_info)
{
u32 sclk, mclk;
u16 vddc;
if (rdev->flags & RADEON_IS_IGP) {
if (rdev->family >= CHIP_PALM) {
sclk = le16_to_cpu(clock_info->sumo.usEngineClockLow);
sclk |= clock_info->sumo.ucEngineClockHigh << 16;
rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk;
} else {
sclk = le16_to_cpu(clock_info->rs780.usLowEngineClockLow);
sclk |= clock_info->rs780.ucLowEngineClockHigh << 16;
rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk;
}
} else if (ASIC_IS_DCE6(rdev)) {
sclk = le16_to_cpu(clock_info->si.usEngineClockLow);
sclk |= clock_info->si.ucEngineClockHigh << 16;
mclk = le16_to_cpu(clock_info->si.usMemoryClockLow);
mclk |= clock_info->si.ucMemoryClockHigh << 16;
rdev->pm.power_state[state_index].clock_info[mode_index].mclk = mclk;
rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk;
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.type =
VOLTAGE_SW;
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage =
le16_to_cpu(clock_info->si.usVDDC);
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.vddci =
le16_to_cpu(clock_info->si.usVDDCI);
} else if (ASIC_IS_DCE4(rdev)) {
sclk = le16_to_cpu(clock_info->evergreen.usEngineClockLow);
sclk |= clock_info->evergreen.ucEngineClockHigh << 16;
mclk = le16_to_cpu(clock_info->evergreen.usMemoryClockLow);
mclk |= clock_info->evergreen.ucMemoryClockHigh << 16;
rdev->pm.power_state[state_index].clock_info[mode_index].mclk = mclk;
rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk;
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.type =
VOLTAGE_SW;
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage =
le16_to_cpu(clock_info->evergreen.usVDDC);
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.vddci =
le16_to_cpu(clock_info->evergreen.usVDDCI);
} else {
sclk = le16_to_cpu(clock_info->r600.usEngineClockLow);
sclk |= clock_info->r600.ucEngineClockHigh << 16;
mclk = le16_to_cpu(clock_info->r600.usMemoryClockLow);
mclk |= clock_info->r600.ucMemoryClockHigh << 16;
rdev->pm.power_state[state_index].clock_info[mode_index].mclk = mclk;
rdev->pm.power_state[state_index].clock_info[mode_index].sclk = sclk;
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.type =
VOLTAGE_SW;
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage =
le16_to_cpu(clock_info->r600.usVDDC);
}
/* patch up vddc if necessary */
switch (rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage) {
case ATOM_VIRTUAL_VOLTAGE_ID0:
case ATOM_VIRTUAL_VOLTAGE_ID1:
case ATOM_VIRTUAL_VOLTAGE_ID2:
case ATOM_VIRTUAL_VOLTAGE_ID3:
if (radeon_atom_get_max_vddc(rdev, VOLTAGE_TYPE_VDDC,
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage,
&vddc) == 0)
rdev->pm.power_state[state_index].clock_info[mode_index].voltage.voltage = vddc;
break;
default:
break;
}
if (rdev->flags & RADEON_IS_IGP) {
/* skip invalid modes */
if (rdev->pm.power_state[state_index].clock_info[mode_index].sclk == 0)
return false;
} else {
/* skip invalid modes */
if ((rdev->pm.power_state[state_index].clock_info[mode_index].mclk == 0) ||
(rdev->pm.power_state[state_index].clock_info[mode_index].sclk == 0))
return false;
}
return true;
}
static int radeon_atombios_parse_power_table_4_5(struct radeon_device *rdev)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
struct _ATOM_PPLIB_NONCLOCK_INFO *non_clock_info;
union pplib_power_state *power_state;
int i, j;
int state_index = 0, mode_index = 0;
union pplib_clock_info *clock_info;
bool valid;
union power_info *power_info;
int index = GetIndexIntoMasterTable(DATA, PowerPlayInfo);
u16 data_offset;
u8 frev, crev;
if (!atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset))
return state_index;
power_info = (union power_info *)(mode_info->atom_context->bios + data_offset);
radeon_atombios_add_pplib_thermal_controller(rdev, &power_info->pplib.sThermalController);
rdev->pm.power_state = kzalloc(sizeof(struct radeon_power_state) *
power_info->pplib.ucNumStates, GFP_KERNEL);
if (!rdev->pm.power_state)
return state_index;
/* first mode is usually default, followed by low to high */
for (i = 0; i < power_info->pplib.ucNumStates; i++) {
mode_index = 0;
power_state = (union pplib_power_state *)
(mode_info->atom_context->bios + data_offset +
le16_to_cpu(power_info->pplib.usStateArrayOffset) +
i * power_info->pplib.ucStateEntrySize);
non_clock_info = (struct _ATOM_PPLIB_NONCLOCK_INFO *)
(mode_info->atom_context->bios + data_offset +
le16_to_cpu(power_info->pplib.usNonClockInfoArrayOffset) +
(power_state->v1.ucNonClockStateIndex *
power_info->pplib.ucNonClockSize));
rdev->pm.power_state[i].clock_info = kzalloc(sizeof(struct radeon_pm_clock_info) *
((power_info->pplib.ucStateEntrySize - 1) ?
(power_info->pplib.ucStateEntrySize - 1) : 1),
GFP_KERNEL);
if (!rdev->pm.power_state[i].clock_info)
return state_index;
if (power_info->pplib.ucStateEntrySize - 1) {
for (j = 0; j < (power_info->pplib.ucStateEntrySize - 1); j++) {
clock_info = (union pplib_clock_info *)
(mode_info->atom_context->bios + data_offset +
le16_to_cpu(power_info->pplib.usClockInfoArrayOffset) +
(power_state->v1.ucClockStateIndices[j] *
power_info->pplib.ucClockInfoSize));
valid = radeon_atombios_parse_pplib_clock_info(rdev,
state_index, mode_index,
clock_info);
if (valid)
mode_index++;
}
} else {
rdev->pm.power_state[state_index].clock_info[0].mclk =
rdev->clock.default_mclk;
rdev->pm.power_state[state_index].clock_info[0].sclk =
rdev->clock.default_sclk;
mode_index++;
}
rdev->pm.power_state[state_index].num_clock_modes = mode_index;
if (mode_index) {
radeon_atombios_parse_pplib_non_clock_info(rdev, state_index, mode_index,
non_clock_info);
state_index++;
}
}
/* if multiple clock modes, mark the lowest as no display */
for (i = 0; i < state_index; i++) {
if (rdev->pm.power_state[i].num_clock_modes > 1)
rdev->pm.power_state[i].clock_info[0].flags |=
RADEON_PM_MODE_NO_DISPLAY;
}
/* first mode is usually default */
if (rdev->pm.default_power_state_index == -1) {
rdev->pm.power_state[0].type =
POWER_STATE_TYPE_DEFAULT;
rdev->pm.default_power_state_index = 0;
rdev->pm.power_state[0].default_clock_mode =
&rdev->pm.power_state[0].clock_info[0];
}
return state_index;
}
static int radeon_atombios_parse_power_table_6(struct radeon_device *rdev)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
struct _ATOM_PPLIB_NONCLOCK_INFO *non_clock_info;
union pplib_power_state *power_state;
int i, j, non_clock_array_index, clock_array_index;
int state_index = 0, mode_index = 0;
union pplib_clock_info *clock_info;
struct _StateArray *state_array;
struct _ClockInfoArray *clock_info_array;
struct _NonClockInfoArray *non_clock_info_array;
bool valid;
union power_info *power_info;
int index = GetIndexIntoMasterTable(DATA, PowerPlayInfo);
u16 data_offset;
u8 frev, crev;
if (!atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset))
return state_index;
power_info = (union power_info *)(mode_info->atom_context->bios + data_offset);
radeon_atombios_add_pplib_thermal_controller(rdev, &power_info->pplib.sThermalController);
state_array = (struct _StateArray *)
(mode_info->atom_context->bios + data_offset +
le16_to_cpu(power_info->pplib.usStateArrayOffset));
clock_info_array = (struct _ClockInfoArray *)
(mode_info->atom_context->bios + data_offset +
le16_to_cpu(power_info->pplib.usClockInfoArrayOffset));
non_clock_info_array = (struct _NonClockInfoArray *)
(mode_info->atom_context->bios + data_offset +
le16_to_cpu(power_info->pplib.usNonClockInfoArrayOffset));
rdev->pm.power_state = kzalloc(sizeof(struct radeon_power_state) *
state_array->ucNumEntries, GFP_KERNEL);
if (!rdev->pm.power_state)
return state_index;
for (i = 0; i < state_array->ucNumEntries; i++) {
mode_index = 0;
power_state = (union pplib_power_state *)&state_array->states[i];
/* XXX this might be an inagua bug... */
non_clock_array_index = i; /* power_state->v2.nonClockInfoIndex */
non_clock_info = (struct _ATOM_PPLIB_NONCLOCK_INFO *)
&non_clock_info_array->nonClockInfo[non_clock_array_index];
rdev->pm.power_state[i].clock_info = kzalloc(sizeof(struct radeon_pm_clock_info) *
(power_state->v2.ucNumDPMLevels ?
power_state->v2.ucNumDPMLevels : 1),
GFP_KERNEL);
if (!rdev->pm.power_state[i].clock_info)
return state_index;
if (power_state->v2.ucNumDPMLevels) {
for (j = 0; j < power_state->v2.ucNumDPMLevels; j++) {
clock_array_index = power_state->v2.clockInfoIndex[j];
/* XXX this might be an inagua bug... */
if (clock_array_index >= clock_info_array->ucNumEntries)
continue;
clock_info = (union pplib_clock_info *)
&clock_info_array->clockInfo[clock_array_index * clock_info_array->ucEntrySize];
valid = radeon_atombios_parse_pplib_clock_info(rdev,
state_index, mode_index,
clock_info);
if (valid)
mode_index++;
}
} else {
rdev->pm.power_state[state_index].clock_info[0].mclk =
rdev->clock.default_mclk;
rdev->pm.power_state[state_index].clock_info[0].sclk =
rdev->clock.default_sclk;
mode_index++;
}
rdev->pm.power_state[state_index].num_clock_modes = mode_index;
if (mode_index) {
radeon_atombios_parse_pplib_non_clock_info(rdev, state_index, mode_index,
non_clock_info);
state_index++;
}
}
/* if multiple clock modes, mark the lowest as no display */
for (i = 0; i < state_index; i++) {
if (rdev->pm.power_state[i].num_clock_modes > 1)
rdev->pm.power_state[i].clock_info[0].flags |=
RADEON_PM_MODE_NO_DISPLAY;
}
/* first mode is usually default */
if (rdev->pm.default_power_state_index == -1) {
rdev->pm.power_state[0].type =
POWER_STATE_TYPE_DEFAULT;
rdev->pm.default_power_state_index = 0;
rdev->pm.power_state[0].default_clock_mode =
&rdev->pm.power_state[0].clock_info[0];
}
return state_index;
}
void radeon_atombios_get_power_modes(struct radeon_device *rdev)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, PowerPlayInfo);
u16 data_offset;
u8 frev, crev;
int state_index = 0;
rdev->pm.default_power_state_index = -1;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
switch (frev) {
case 1:
case 2:
case 3:
state_index = radeon_atombios_parse_power_table_1_3(rdev);
break;
case 4:
case 5:
state_index = radeon_atombios_parse_power_table_4_5(rdev);
break;
case 6:
state_index = radeon_atombios_parse_power_table_6(rdev);
break;
default:
break;
}
} else {
rdev->pm.power_state = kzalloc(sizeof(struct radeon_power_state), GFP_KERNEL);
if (rdev->pm.power_state) {
rdev->pm.power_state[0].clock_info =
kzalloc(sizeof(struct radeon_pm_clock_info) * 1, GFP_KERNEL);
if (rdev->pm.power_state[0].clock_info) {
/* add the default mode */
rdev->pm.power_state[state_index].type =
POWER_STATE_TYPE_DEFAULT;
rdev->pm.power_state[state_index].num_clock_modes = 1;
rdev->pm.power_state[state_index].clock_info[0].mclk = rdev->clock.default_mclk;
rdev->pm.power_state[state_index].clock_info[0].sclk = rdev->clock.default_sclk;
rdev->pm.power_state[state_index].default_clock_mode =
&rdev->pm.power_state[state_index].clock_info[0];
rdev->pm.power_state[state_index].clock_info[0].voltage.type = VOLTAGE_NONE;
rdev->pm.power_state[state_index].pcie_lanes = 16;
rdev->pm.default_power_state_index = state_index;
rdev->pm.power_state[state_index].flags = 0;
state_index++;
}
}
}
rdev->pm.num_power_states = state_index;
rdev->pm.current_power_state_index = rdev->pm.default_power_state_index;
rdev->pm.current_clock_mode_index = 0;
if (rdev->pm.default_power_state_index >= 0)
rdev->pm.current_vddc =
rdev->pm.power_state[rdev->pm.default_power_state_index].clock_info[0].voltage.voltage;
else
rdev->pm.current_vddc = 0;
}
void radeon_atom_set_clock_gating(struct radeon_device *rdev, int enable)
{
DYNAMIC_CLOCK_GATING_PS_ALLOCATION args;
int index = GetIndexIntoMasterTable(COMMAND, DynamicClockGating);
args.ucEnable = enable;
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
}
uint32_t radeon_atom_get_engine_clock(struct radeon_device *rdev)
{
GET_ENGINE_CLOCK_PS_ALLOCATION args;
int index = GetIndexIntoMasterTable(COMMAND, GetEngineClock);
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
return le32_to_cpu(args.ulReturnEngineClock);
}
uint32_t radeon_atom_get_memory_clock(struct radeon_device *rdev)
{
GET_MEMORY_CLOCK_PS_ALLOCATION args;
int index = GetIndexIntoMasterTable(COMMAND, GetMemoryClock);
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
return le32_to_cpu(args.ulReturnMemoryClock);
}
void radeon_atom_set_engine_clock(struct radeon_device *rdev,
uint32_t eng_clock)
{
SET_ENGINE_CLOCK_PS_ALLOCATION args;
int index = GetIndexIntoMasterTable(COMMAND, SetEngineClock);
args.ulTargetEngineClock = cpu_to_le32(eng_clock); /* 10 khz */
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
}
void radeon_atom_set_memory_clock(struct radeon_device *rdev,
uint32_t mem_clock)
{
SET_MEMORY_CLOCK_PS_ALLOCATION args;
int index = GetIndexIntoMasterTable(COMMAND, SetMemoryClock);
if (rdev->flags & RADEON_IS_IGP)
return;
args.ulTargetMemoryClock = cpu_to_le32(mem_clock); /* 10 khz */
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
}
union set_voltage {
struct _SET_VOLTAGE_PS_ALLOCATION alloc;
struct _SET_VOLTAGE_PARAMETERS v1;
struct _SET_VOLTAGE_PARAMETERS_V2 v2;
struct _SET_VOLTAGE_PARAMETERS_V1_3 v3;
};
void radeon_atom_set_voltage(struct radeon_device *rdev, u16 voltage_level, u8 voltage_type)
{
union set_voltage args;
int index = GetIndexIntoMasterTable(COMMAND, SetVoltage);
u8 frev, crev, volt_index = voltage_level;
if (!atom_parse_cmd_header(rdev->mode_info.atom_context, index, &frev, &crev))
return;
/* 0xff01 is a flag rather then an actual voltage */
if (voltage_level == 0xff01)
return;
switch (crev) {
case 1:
args.v1.ucVoltageType = voltage_type;
args.v1.ucVoltageMode = SET_ASIC_VOLTAGE_MODE_ALL_SOURCE;
args.v1.ucVoltageIndex = volt_index;
break;
case 2:
args.v2.ucVoltageType = voltage_type;
args.v2.ucVoltageMode = SET_ASIC_VOLTAGE_MODE_SET_VOLTAGE;
args.v2.usVoltageLevel = cpu_to_le16(voltage_level);
break;
case 3:
args.v3.ucVoltageType = voltage_type;
args.v3.ucVoltageMode = ATOM_SET_VOLTAGE;
args.v3.usVoltageLevel = cpu_to_le16(voltage_level);
break;
default:
DRM_ERROR("Unknown table version %d, %d\n", frev, crev);
return;
}
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
}
static int radeon_atom_get_max_vddc(struct radeon_device *rdev, u8 voltage_type,
u16 voltage_id, u16 *voltage)
{
union set_voltage args;
int index = GetIndexIntoMasterTable(COMMAND, SetVoltage);
u8 frev, crev;
if (!atom_parse_cmd_header(rdev->mode_info.atom_context, index, &frev, &crev))
return -EINVAL;
switch (crev) {
case 1:
return -EINVAL;
case 2:
args.v2.ucVoltageType = SET_VOLTAGE_GET_MAX_VOLTAGE;
args.v2.ucVoltageMode = 0;
args.v2.usVoltageLevel = 0;
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
*voltage = le16_to_cpu(args.v2.usVoltageLevel);
break;
case 3:
args.v3.ucVoltageType = voltage_type;
args.v3.ucVoltageMode = ATOM_GET_VOLTAGE_LEVEL;
args.v3.usVoltageLevel = cpu_to_le16(voltage_id);
atom_execute_table(rdev->mode_info.atom_context, index, (uint32_t *)&args);
*voltage = le16_to_cpu(args.v3.usVoltageLevel);
break;
default:
DRM_ERROR("Unknown table version %d, %d\n", frev, crev);
return -EINVAL;
}
return 0;
}
void radeon_atom_initialize_bios_scratch_regs(struct drm_device *dev)
{
struct radeon_device *rdev = dev->dev_private;
uint32_t bios_2_scratch, bios_6_scratch;
if (rdev->family >= CHIP_R600) {
bios_2_scratch = RREG32(R600_BIOS_2_SCRATCH);
bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH);
} else {
bios_2_scratch = RREG32(RADEON_BIOS_2_SCRATCH);
bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH);
}
/* let the bios control the backlight */
bios_2_scratch &= ~ATOM_S2_VRI_BRIGHT_ENABLE;
/* tell the bios not to handle mode switching */
bios_6_scratch |= ATOM_S6_ACC_BLOCK_DISPLAY_SWITCH;
if (rdev->family >= CHIP_R600) {
WREG32(R600_BIOS_2_SCRATCH, bios_2_scratch);
WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch);
} else {
WREG32(RADEON_BIOS_2_SCRATCH, bios_2_scratch);
WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch);
}
}
void radeon_save_bios_scratch_regs(struct radeon_device *rdev)
{
uint32_t scratch_reg;
int i;
if (rdev->family >= CHIP_R600)
scratch_reg = R600_BIOS_0_SCRATCH;
else
scratch_reg = RADEON_BIOS_0_SCRATCH;
for (i = 0; i < RADEON_BIOS_NUM_SCRATCH; i++)
rdev->bios_scratch[i] = RREG32(scratch_reg + (i * 4));
}
void radeon_restore_bios_scratch_regs(struct radeon_device *rdev)
{
uint32_t scratch_reg;
int i;
if (rdev->family >= CHIP_R600)
scratch_reg = R600_BIOS_0_SCRATCH;
else
scratch_reg = RADEON_BIOS_0_SCRATCH;
for (i = 0; i < RADEON_BIOS_NUM_SCRATCH; i++)
WREG32(scratch_reg + (i * 4), rdev->bios_scratch[i]);
}
void radeon_atom_output_lock(struct drm_encoder *encoder, bool lock)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t bios_6_scratch;
if (rdev->family >= CHIP_R600)
bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH);
else
bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH);
if (lock) {
bios_6_scratch |= ATOM_S6_CRITICAL_STATE;
bios_6_scratch &= ~ATOM_S6_ACC_MODE;
} else {
bios_6_scratch &= ~ATOM_S6_CRITICAL_STATE;
bios_6_scratch |= ATOM_S6_ACC_MODE;
}
if (rdev->family >= CHIP_R600)
WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch);
else
WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch);
}
/* at some point we may want to break this out into individual functions */
void
radeon_atombios_connected_scratch_regs(struct drm_connector *connector,
struct drm_encoder *encoder,
bool connected)
{
struct drm_device *dev = connector->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_connector *radeon_connector =
to_radeon_connector(connector);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t bios_0_scratch, bios_3_scratch, bios_6_scratch;
if (rdev->family >= CHIP_R600) {
bios_0_scratch = RREG32(R600_BIOS_0_SCRATCH);
bios_3_scratch = RREG32(R600_BIOS_3_SCRATCH);
bios_6_scratch = RREG32(R600_BIOS_6_SCRATCH);
} else {
bios_0_scratch = RREG32(RADEON_BIOS_0_SCRATCH);
bios_3_scratch = RREG32(RADEON_BIOS_3_SCRATCH);
bios_6_scratch = RREG32(RADEON_BIOS_6_SCRATCH);
}
if ((radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_TV1_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("TV1 connected\n");
bios_3_scratch |= ATOM_S3_TV1_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_TV1;
} else {
DRM_DEBUG_KMS("TV1 disconnected\n");
bios_0_scratch &= ~ATOM_S0_TV1_MASK;
bios_3_scratch &= ~ATOM_S3_TV1_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_TV1;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_CV_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("CV connected\n");
bios_3_scratch |= ATOM_S3_CV_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_CV;
} else {
DRM_DEBUG_KMS("CV disconnected\n");
bios_0_scratch &= ~ATOM_S0_CV_MASK;
bios_3_scratch &= ~ATOM_S3_CV_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_CV;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_LCD1_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("LCD1 connected\n");
bios_0_scratch |= ATOM_S0_LCD1;
bios_3_scratch |= ATOM_S3_LCD1_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_LCD1;
} else {
DRM_DEBUG_KMS("LCD1 disconnected\n");
bios_0_scratch &= ~ATOM_S0_LCD1;
bios_3_scratch &= ~ATOM_S3_LCD1_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_LCD1;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_CRT1_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("CRT1 connected\n");
bios_0_scratch |= ATOM_S0_CRT1_COLOR;
bios_3_scratch |= ATOM_S3_CRT1_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_CRT1;
} else {
DRM_DEBUG_KMS("CRT1 disconnected\n");
bios_0_scratch &= ~ATOM_S0_CRT1_MASK;
bios_3_scratch &= ~ATOM_S3_CRT1_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_CRT1;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_CRT2_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("CRT2 connected\n");
bios_0_scratch |= ATOM_S0_CRT2_COLOR;
bios_3_scratch |= ATOM_S3_CRT2_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_CRT2;
} else {
DRM_DEBUG_KMS("CRT2 disconnected\n");
bios_0_scratch &= ~ATOM_S0_CRT2_MASK;
bios_3_scratch &= ~ATOM_S3_CRT2_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_CRT2;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_DFP1_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("DFP1 connected\n");
bios_0_scratch |= ATOM_S0_DFP1;
bios_3_scratch |= ATOM_S3_DFP1_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_DFP1;
} else {
DRM_DEBUG_KMS("DFP1 disconnected\n");
bios_0_scratch &= ~ATOM_S0_DFP1;
bios_3_scratch &= ~ATOM_S3_DFP1_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP1;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_DFP2_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("DFP2 connected\n");
bios_0_scratch |= ATOM_S0_DFP2;
bios_3_scratch |= ATOM_S3_DFP2_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_DFP2;
} else {
DRM_DEBUG_KMS("DFP2 disconnected\n");
bios_0_scratch &= ~ATOM_S0_DFP2;
bios_3_scratch &= ~ATOM_S3_DFP2_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP2;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_DFP3_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("DFP3 connected\n");
bios_0_scratch |= ATOM_S0_DFP3;
bios_3_scratch |= ATOM_S3_DFP3_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_DFP3;
} else {
DRM_DEBUG_KMS("DFP3 disconnected\n");
bios_0_scratch &= ~ATOM_S0_DFP3;
bios_3_scratch &= ~ATOM_S3_DFP3_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP3;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_DFP4_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_DFP4_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("DFP4 connected\n");
bios_0_scratch |= ATOM_S0_DFP4;
bios_3_scratch |= ATOM_S3_DFP4_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_DFP4;
} else {
DRM_DEBUG_KMS("DFP4 disconnected\n");
bios_0_scratch &= ~ATOM_S0_DFP4;
bios_3_scratch &= ~ATOM_S3_DFP4_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP4;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_DFP5_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_DFP5_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("DFP5 connected\n");
bios_0_scratch |= ATOM_S0_DFP5;
bios_3_scratch |= ATOM_S3_DFP5_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_DFP5;
} else {
DRM_DEBUG_KMS("DFP5 disconnected\n");
bios_0_scratch &= ~ATOM_S0_DFP5;
bios_3_scratch &= ~ATOM_S3_DFP5_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP5;
}
}
if ((radeon_encoder->devices & ATOM_DEVICE_DFP6_SUPPORT) &&
(radeon_connector->devices & ATOM_DEVICE_DFP6_SUPPORT)) {
if (connected) {
DRM_DEBUG_KMS("DFP6 connected\n");
bios_0_scratch |= ATOM_S0_DFP6;
bios_3_scratch |= ATOM_S3_DFP6_ACTIVE;
bios_6_scratch |= ATOM_S6_ACC_REQ_DFP6;
} else {
DRM_DEBUG_KMS("DFP6 disconnected\n");
bios_0_scratch &= ~ATOM_S0_DFP6;
bios_3_scratch &= ~ATOM_S3_DFP6_ACTIVE;
bios_6_scratch &= ~ATOM_S6_ACC_REQ_DFP6;
}
}
if (rdev->family >= CHIP_R600) {
WREG32(R600_BIOS_0_SCRATCH, bios_0_scratch);
WREG32(R600_BIOS_3_SCRATCH, bios_3_scratch);
WREG32(R600_BIOS_6_SCRATCH, bios_6_scratch);
} else {
WREG32(RADEON_BIOS_0_SCRATCH, bios_0_scratch);
WREG32(RADEON_BIOS_3_SCRATCH, bios_3_scratch);
WREG32(RADEON_BIOS_6_SCRATCH, bios_6_scratch);
}
}
void
radeon_atombios_encoder_crtc_scratch_regs(struct drm_encoder *encoder, int crtc)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t bios_3_scratch;
if (ASIC_IS_DCE4(rdev))
return;
if (rdev->family >= CHIP_R600)
bios_3_scratch = RREG32(R600_BIOS_3_SCRATCH);
else
bios_3_scratch = RREG32(RADEON_BIOS_3_SCRATCH);
if (radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_TV1_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 18);
}
if (radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_CV_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 24);
}
if (radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_CRT1_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 16);
}
if (radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_CRT2_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 20);
}
if (radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_LCD1_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 17);
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_DFP1_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 19);
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_DFP2_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 23);
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) {
bios_3_scratch &= ~ATOM_S3_DFP3_CRTC_ACTIVE;
bios_3_scratch |= (crtc << 25);
}
if (rdev->family >= CHIP_R600)
WREG32(R600_BIOS_3_SCRATCH, bios_3_scratch);
else
WREG32(RADEON_BIOS_3_SCRATCH, bios_3_scratch);
}
void
radeon_atombios_encoder_dpms_scratch_regs(struct drm_encoder *encoder, bool on)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t bios_2_scratch;
if (ASIC_IS_DCE4(rdev))
return;
if (rdev->family >= CHIP_R600)
bios_2_scratch = RREG32(R600_BIOS_2_SCRATCH);
else
bios_2_scratch = RREG32(RADEON_BIOS_2_SCRATCH);
if (radeon_encoder->devices & ATOM_DEVICE_TV1_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_TV1_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_TV1_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_CV_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_CV_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_CV_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_CRT1_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_CRT1_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_CRT1_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_CRT2_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_CRT2_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_CRT2_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_LCD1_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_LCD1_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_LCD1_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP1_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_DFP1_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_DFP1_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP2_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_DFP2_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_DFP2_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP3_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_DFP3_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_DFP3_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP4_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_DFP4_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_DFP4_DPMS_STATE;
}
if (radeon_encoder->devices & ATOM_DEVICE_DFP5_SUPPORT) {
if (on)
bios_2_scratch &= ~ATOM_S2_DFP5_DPMS_STATE;
else
bios_2_scratch |= ATOM_S2_DFP5_DPMS_STATE;
}
if (rdev->family >= CHIP_R600)
WREG32(R600_BIOS_2_SCRATCH, bios_2_scratch);
else
WREG32(RADEON_BIOS_2_SCRATCH, bios_2_scratch);
}
| gpl-2.0 |
knych/linux-sunxi | kernel/sched/fair.c | 524 | 143312 | /*
* Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
*
* Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
*
* Interactivity improvements by Mike Galbraith
* (C) 2007 Mike Galbraith <efault@gmx.de>
*
* Various enhancements by Dmitry Adamushko.
* (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
*
* Group scheduling enhancements by Srivatsa Vaddagiri
* Copyright IBM Corporation, 2007
* Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
*
* Scaled math optimizations by Thomas Gleixner
* Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
*
* Adaptive scheduling granularity, math enhancements by Peter Zijlstra
* Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
*/
#include <linux/latencytop.h>
#include <linux/sched.h>
#include <linux/cpumask.h>
#include <linux/slab.h>
#include <linux/profile.h>
#include <linux/interrupt.h>
#include <trace/events/sched.h>
#include "sched.h"
/*
* Targeted preemption latency for CPU-bound tasks:
* (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
*
* NOTE: this latency value is not the same as the concept of
* 'timeslice length' - timeslices in CFS are of variable length
* and have no persistent notion like in traditional, time-slice
* based scheduling concepts.
*
* (to see the precise effective timeslice length of your workload,
* run vmstat and monitor the context-switches (cs) field)
*/
unsigned int sysctl_sched_latency = 6000000ULL;
unsigned int normalized_sysctl_sched_latency = 6000000ULL;
/*
* The initial- and re-scaling of tunables is configurable
* (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
*
* Options are:
* SCHED_TUNABLESCALING_NONE - unscaled, always *1
* SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
* SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
*/
enum sched_tunable_scaling sysctl_sched_tunable_scaling
= SCHED_TUNABLESCALING_LOG;
/*
* Minimal preemption granularity for CPU-bound tasks:
* (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
*/
unsigned int sysctl_sched_min_granularity = 750000ULL;
unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
/*
* is kept at sysctl_sched_latency / sysctl_sched_min_granularity
*/
static unsigned int sched_nr_latency = 8;
/*
* After fork, child runs first. If set to 0 (default) then
* parent will (try to) run first.
*/
unsigned int sysctl_sched_child_runs_first __read_mostly;
/*
* SCHED_OTHER wake-up granularity.
* (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
*
* This option delays the preemption effects of decoupled workloads
* and reduces their over-scheduling. Synchronous workloads will still
* have immediate wakeup/sleep latencies.
*/
unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
/*
* The exponential sliding window over which load is averaged for shares
* distribution.
* (default: 10msec)
*/
unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
#ifdef CONFIG_CFS_BANDWIDTH
/*
* Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
* each time a cfs_rq requests quota.
*
* Note: in the case that the slice exceeds the runtime remaining (either due
* to consumption or the quota being specified to be smaller than the slice)
* we will always only issue the remaining available time.
*
* default: 5 msec, units: microseconds
*/
unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
#endif
/*
* Increase the granularity value when there are more CPUs,
* because with more CPUs the 'effective latency' as visible
* to users decreases. But the relationship is not linear,
* so pick a second-best guess by going with the log2 of the
* number of CPUs.
*
* This idea comes from the SD scheduler of Con Kolivas:
*/
static int get_update_sysctl_factor(void)
{
unsigned int cpus = min_t(int, num_online_cpus(), 8);
unsigned int factor;
switch (sysctl_sched_tunable_scaling) {
case SCHED_TUNABLESCALING_NONE:
factor = 1;
break;
case SCHED_TUNABLESCALING_LINEAR:
factor = cpus;
break;
case SCHED_TUNABLESCALING_LOG:
default:
factor = 1 + ilog2(cpus);
break;
}
return factor;
}
static void update_sysctl(void)
{
unsigned int factor = get_update_sysctl_factor();
#define SET_SYSCTL(name) \
(sysctl_##name = (factor) * normalized_sysctl_##name)
SET_SYSCTL(sched_min_granularity);
SET_SYSCTL(sched_latency);
SET_SYSCTL(sched_wakeup_granularity);
#undef SET_SYSCTL
}
void sched_init_granularity(void)
{
update_sysctl();
}
#if BITS_PER_LONG == 32
# define WMULT_CONST (~0UL)
#else
# define WMULT_CONST (1UL << 32)
#endif
#define WMULT_SHIFT 32
/*
* Shift right and round:
*/
#define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
/*
* delta *= weight / lw
*/
static unsigned long
calc_delta_mine(unsigned long delta_exec, unsigned long weight,
struct load_weight *lw)
{
u64 tmp;
/*
* weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
* entities since MIN_SHARES = 2. Treat weight as 1 if less than
* 2^SCHED_LOAD_RESOLUTION.
*/
if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
tmp = (u64)delta_exec * scale_load_down(weight);
else
tmp = (u64)delta_exec;
if (!lw->inv_weight) {
unsigned long w = scale_load_down(lw->weight);
if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
lw->inv_weight = 1;
else if (unlikely(!w))
lw->inv_weight = WMULT_CONST;
else
lw->inv_weight = WMULT_CONST / w;
}
/*
* Check whether we'd overflow the 64-bit multiplication:
*/
if (unlikely(tmp > WMULT_CONST))
tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
WMULT_SHIFT/2);
else
tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
}
const struct sched_class fair_sched_class;
/**************************************************************
* CFS operations on generic schedulable entities:
*/
#ifdef CONFIG_FAIR_GROUP_SCHED
/* cpu runqueue to which this cfs_rq is attached */
static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
{
return cfs_rq->rq;
}
/* An entity is a task if it doesn't "own" a runqueue */
#define entity_is_task(se) (!se->my_q)
static inline struct task_struct *task_of(struct sched_entity *se)
{
#ifdef CONFIG_SCHED_DEBUG
WARN_ON_ONCE(!entity_is_task(se));
#endif
return container_of(se, struct task_struct, se);
}
/* Walk up scheduling entities hierarchy */
#define for_each_sched_entity(se) \
for (; se; se = se->parent)
static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
{
return p->se.cfs_rq;
}
/* runqueue on which this entity is (to be) queued */
static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
{
return se->cfs_rq;
}
/* runqueue "owned" by this group */
static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
{
return grp->my_q;
}
static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
{
if (!cfs_rq->on_list) {
/*
* Ensure we either appear before our parent (if already
* enqueued) or force our parent to appear after us when it is
* enqueued. The fact that we always enqueue bottom-up
* reduces this to two cases.
*/
if (cfs_rq->tg->parent &&
cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
&rq_of(cfs_rq)->leaf_cfs_rq_list);
} else {
list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
&rq_of(cfs_rq)->leaf_cfs_rq_list);
}
cfs_rq->on_list = 1;
}
}
static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
{
if (cfs_rq->on_list) {
list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
cfs_rq->on_list = 0;
}
}
/* Iterate thr' all leaf cfs_rq's on a runqueue */
#define for_each_leaf_cfs_rq(rq, cfs_rq) \
list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
/* Do the two (enqueued) entities belong to the same group ? */
static inline int
is_same_group(struct sched_entity *se, struct sched_entity *pse)
{
if (se->cfs_rq == pse->cfs_rq)
return 1;
return 0;
}
static inline struct sched_entity *parent_entity(struct sched_entity *se)
{
return se->parent;
}
/* return depth at which a sched entity is present in the hierarchy */
static inline int depth_se(struct sched_entity *se)
{
int depth = 0;
for_each_sched_entity(se)
depth++;
return depth;
}
static void
find_matching_se(struct sched_entity **se, struct sched_entity **pse)
{
int se_depth, pse_depth;
/*
* preemption test can be made between sibling entities who are in the
* same cfs_rq i.e who have a common parent. Walk up the hierarchy of
* both tasks until we find their ancestors who are siblings of common
* parent.
*/
/* First walk up until both entities are at same depth */
se_depth = depth_se(*se);
pse_depth = depth_se(*pse);
while (se_depth > pse_depth) {
se_depth--;
*se = parent_entity(*se);
}
while (pse_depth > se_depth) {
pse_depth--;
*pse = parent_entity(*pse);
}
while (!is_same_group(*se, *pse)) {
*se = parent_entity(*se);
*pse = parent_entity(*pse);
}
}
#else /* !CONFIG_FAIR_GROUP_SCHED */
static inline struct task_struct *task_of(struct sched_entity *se)
{
return container_of(se, struct task_struct, se);
}
static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
{
return container_of(cfs_rq, struct rq, cfs);
}
#define entity_is_task(se) 1
#define for_each_sched_entity(se) \
for (; se; se = NULL)
static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
{
return &task_rq(p)->cfs;
}
static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
{
struct task_struct *p = task_of(se);
struct rq *rq = task_rq(p);
return &rq->cfs;
}
/* runqueue "owned" by this group */
static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
{
return NULL;
}
static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
{
}
static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
{
}
#define for_each_leaf_cfs_rq(rq, cfs_rq) \
for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
static inline int
is_same_group(struct sched_entity *se, struct sched_entity *pse)
{
return 1;
}
static inline struct sched_entity *parent_entity(struct sched_entity *se)
{
return NULL;
}
static inline void
find_matching_se(struct sched_entity **se, struct sched_entity **pse)
{
}
#endif /* CONFIG_FAIR_GROUP_SCHED */
static __always_inline
void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec);
/**************************************************************
* Scheduling class tree data structure manipulation methods:
*/
static inline u64 max_vruntime(u64 min_vruntime, u64 vruntime)
{
s64 delta = (s64)(vruntime - min_vruntime);
if (delta > 0)
min_vruntime = vruntime;
return min_vruntime;
}
static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
{
s64 delta = (s64)(vruntime - min_vruntime);
if (delta < 0)
min_vruntime = vruntime;
return min_vruntime;
}
static inline int entity_before(struct sched_entity *a,
struct sched_entity *b)
{
return (s64)(a->vruntime - b->vruntime) < 0;
}
static void update_min_vruntime(struct cfs_rq *cfs_rq)
{
u64 vruntime = cfs_rq->min_vruntime;
if (cfs_rq->curr)
vruntime = cfs_rq->curr->vruntime;
if (cfs_rq->rb_leftmost) {
struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
struct sched_entity,
run_node);
if (!cfs_rq->curr)
vruntime = se->vruntime;
else
vruntime = min_vruntime(vruntime, se->vruntime);
}
cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
#ifndef CONFIG_64BIT
smp_wmb();
cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
#endif
}
/*
* Enqueue an entity into the rb-tree:
*/
static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
struct rb_node *parent = NULL;
struct sched_entity *entry;
int leftmost = 1;
/*
* Find the right place in the rbtree:
*/
while (*link) {
parent = *link;
entry = rb_entry(parent, struct sched_entity, run_node);
/*
* We dont care about collisions. Nodes with
* the same key stay together.
*/
if (entity_before(se, entry)) {
link = &parent->rb_left;
} else {
link = &parent->rb_right;
leftmost = 0;
}
}
/*
* Maintain a cache of leftmost tree entries (it is frequently
* used):
*/
if (leftmost)
cfs_rq->rb_leftmost = &se->run_node;
rb_link_node(&se->run_node, parent, link);
rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
}
static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
if (cfs_rq->rb_leftmost == &se->run_node) {
struct rb_node *next_node;
next_node = rb_next(&se->run_node);
cfs_rq->rb_leftmost = next_node;
}
rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
}
struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
{
struct rb_node *left = cfs_rq->rb_leftmost;
if (!left)
return NULL;
return rb_entry(left, struct sched_entity, run_node);
}
static struct sched_entity *__pick_next_entity(struct sched_entity *se)
{
struct rb_node *next = rb_next(&se->run_node);
if (!next)
return NULL;
return rb_entry(next, struct sched_entity, run_node);
}
#ifdef CONFIG_SCHED_DEBUG
struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
{
struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
if (!last)
return NULL;
return rb_entry(last, struct sched_entity, run_node);
}
/**************************************************************
* Scheduling class statistics methods:
*/
int sched_proc_update_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
int factor = get_update_sysctl_factor();
if (ret || !write)
return ret;
sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
sysctl_sched_min_granularity);
#define WRT_SYSCTL(name) \
(normalized_sysctl_##name = sysctl_##name / (factor))
WRT_SYSCTL(sched_min_granularity);
WRT_SYSCTL(sched_latency);
WRT_SYSCTL(sched_wakeup_granularity);
#undef WRT_SYSCTL
return 0;
}
#endif
/*
* delta /= w
*/
static inline unsigned long
calc_delta_fair(unsigned long delta, struct sched_entity *se)
{
if (unlikely(se->load.weight != NICE_0_LOAD))
delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
return delta;
}
/*
* The idea is to set a period in which each task runs once.
*
* When there are too many tasks (sysctl_sched_nr_latency) we have to stretch
* this period because otherwise the slices get too small.
*
* p = (nr <= nl) ? l : l*nr/nl
*/
static u64 __sched_period(unsigned long nr_running)
{
u64 period = sysctl_sched_latency;
unsigned long nr_latency = sched_nr_latency;
if (unlikely(nr_running > nr_latency)) {
period = sysctl_sched_min_granularity;
period *= nr_running;
}
return period;
}
/*
* We calculate the wall-time slice from the period by taking a part
* proportional to the weight.
*
* s = p*P[w/rw]
*/
static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
for_each_sched_entity(se) {
struct load_weight *load;
struct load_weight lw;
cfs_rq = cfs_rq_of(se);
load = &cfs_rq->load;
if (unlikely(!se->on_rq)) {
lw = cfs_rq->load;
update_load_add(&lw, se->load.weight);
load = &lw;
}
slice = calc_delta_mine(slice, se->load.weight, load);
}
return slice;
}
/*
* We calculate the vruntime slice of a to be inserted task
*
* vs = s/w
*/
static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
return calc_delta_fair(sched_slice(cfs_rq, se), se);
}
static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update);
static void update_cfs_shares(struct cfs_rq *cfs_rq);
/*
* Update the current task's runtime statistics. Skip current tasks that
* are not in our scheduling class.
*/
static inline void
__update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
unsigned long delta_exec)
{
unsigned long delta_exec_weighted;
schedstat_set(curr->statistics.exec_max,
max((u64)delta_exec, curr->statistics.exec_max));
curr->sum_exec_runtime += delta_exec;
schedstat_add(cfs_rq, exec_clock, delta_exec);
delta_exec_weighted = calc_delta_fair(delta_exec, curr);
curr->vruntime += delta_exec_weighted;
update_min_vruntime(cfs_rq);
#if defined CONFIG_SMP && defined CONFIG_FAIR_GROUP_SCHED
cfs_rq->load_unacc_exec_time += delta_exec;
#endif
}
static void update_curr(struct cfs_rq *cfs_rq)
{
struct sched_entity *curr = cfs_rq->curr;
u64 now = rq_of(cfs_rq)->clock_task;
unsigned long delta_exec;
if (unlikely(!curr))
return;
/*
* Get the amount of time the current task was running
* since the last time we changed load (this cannot
* overflow on 32 bits):
*/
delta_exec = (unsigned long)(now - curr->exec_start);
if (!delta_exec)
return;
__update_curr(cfs_rq, curr, delta_exec);
curr->exec_start = now;
if (entity_is_task(curr)) {
struct task_struct *curtask = task_of(curr);
trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
cpuacct_charge(curtask, delta_exec);
account_group_exec_runtime(curtask, delta_exec);
}
account_cfs_rq_runtime(cfs_rq, delta_exec);
}
static inline void
update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
}
/*
* Task is being enqueued - update stats:
*/
static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
/*
* Are we enqueueing a waiting task? (for current tasks
* a dequeue/enqueue event is a NOP)
*/
if (se != cfs_rq->curr)
update_stats_wait_start(cfs_rq, se);
}
static void
update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
rq_of(cfs_rq)->clock - se->statistics.wait_start));
schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
rq_of(cfs_rq)->clock - se->statistics.wait_start);
#ifdef CONFIG_SCHEDSTATS
if (entity_is_task(se)) {
trace_sched_stat_wait(task_of(se),
rq_of(cfs_rq)->clock - se->statistics.wait_start);
}
#endif
schedstat_set(se->statistics.wait_start, 0);
}
static inline void
update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
/*
* Mark the end of the wait period if dequeueing a
* waiting task:
*/
if (se != cfs_rq->curr)
update_stats_wait_end(cfs_rq, se);
}
/*
* We are picking a new current task - update its stats:
*/
static inline void
update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
/*
* We are starting a new run period:
*/
se->exec_start = rq_of(cfs_rq)->clock_task;
}
/**************************************************
* Scheduling class queueing methods:
*/
static void
account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
update_load_add(&cfs_rq->load, se->load.weight);
if (!parent_entity(se))
update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
#ifdef CONFIG_SMP
if (entity_is_task(se))
list_add(&se->group_node, &rq_of(cfs_rq)->cfs_tasks);
#endif
cfs_rq->nr_running++;
}
static void
account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
update_load_sub(&cfs_rq->load, se->load.weight);
if (!parent_entity(se))
update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
if (entity_is_task(se))
list_del_init(&se->group_node);
cfs_rq->nr_running--;
}
#ifdef CONFIG_FAIR_GROUP_SCHED
/* we need this in update_cfs_load and load-balance functions below */
static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
# ifdef CONFIG_SMP
static void update_cfs_rq_load_contribution(struct cfs_rq *cfs_rq,
int global_update)
{
struct task_group *tg = cfs_rq->tg;
long load_avg;
load_avg = div64_u64(cfs_rq->load_avg, cfs_rq->load_period+1);
load_avg -= cfs_rq->load_contribution;
if (global_update || abs(load_avg) > cfs_rq->load_contribution / 8) {
atomic_add(load_avg, &tg->load_weight);
cfs_rq->load_contribution += load_avg;
}
}
static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
{
u64 period = sysctl_sched_shares_window;
u64 now, delta;
unsigned long load = cfs_rq->load.weight;
if (cfs_rq->tg == &root_task_group || throttled_hierarchy(cfs_rq))
return;
now = rq_of(cfs_rq)->clock_task;
delta = now - cfs_rq->load_stamp;
/* truncate load history at 4 idle periods */
if (cfs_rq->load_stamp > cfs_rq->load_last &&
now - cfs_rq->load_last > 4 * period) {
cfs_rq->load_period = 0;
cfs_rq->load_avg = 0;
delta = period - 1;
}
cfs_rq->load_stamp = now;
cfs_rq->load_unacc_exec_time = 0;
cfs_rq->load_period += delta;
if (load) {
cfs_rq->load_last = now;
cfs_rq->load_avg += delta * load;
}
/* consider updating load contribution on each fold or truncate */
if (global_update || cfs_rq->load_period > period
|| !cfs_rq->load_period)
update_cfs_rq_load_contribution(cfs_rq, global_update);
while (cfs_rq->load_period > period) {
/*
* Inline assembly required to prevent the compiler
* optimising this loop into a divmod call.
* See __iter_div_u64_rem() for another example of this.
*/
asm("" : "+rm" (cfs_rq->load_period));
cfs_rq->load_period /= 2;
cfs_rq->load_avg /= 2;
}
if (!cfs_rq->curr && !cfs_rq->nr_running && !cfs_rq->load_avg)
list_del_leaf_cfs_rq(cfs_rq);
}
static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
{
long tg_weight;
/*
* Use this CPU's actual weight instead of the last load_contribution
* to gain a more accurate current total weight. See
* update_cfs_rq_load_contribution().
*/
tg_weight = atomic_read(&tg->load_weight);
tg_weight -= cfs_rq->load_contribution;
tg_weight += cfs_rq->load.weight;
return tg_weight;
}
static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
{
long tg_weight, load, shares;
tg_weight = calc_tg_weight(tg, cfs_rq);
load = cfs_rq->load.weight;
shares = (tg->shares * load);
if (tg_weight)
shares /= tg_weight;
if (shares < MIN_SHARES)
shares = MIN_SHARES;
if (shares > tg->shares)
shares = tg->shares;
return shares;
}
static void update_entity_shares_tick(struct cfs_rq *cfs_rq)
{
if (cfs_rq->load_unacc_exec_time > sysctl_sched_shares_window) {
update_cfs_load(cfs_rq, 0);
update_cfs_shares(cfs_rq);
}
}
# else /* CONFIG_SMP */
static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
{
}
static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
{
return tg->shares;
}
static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
{
}
# endif /* CONFIG_SMP */
static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
unsigned long weight)
{
if (se->on_rq) {
/* commit outstanding execution time */
if (cfs_rq->curr == se)
update_curr(cfs_rq);
account_entity_dequeue(cfs_rq, se);
}
update_load_set(&se->load, weight);
if (se->on_rq)
account_entity_enqueue(cfs_rq, se);
}
static void update_cfs_shares(struct cfs_rq *cfs_rq)
{
struct task_group *tg;
struct sched_entity *se;
long shares;
tg = cfs_rq->tg;
se = tg->se[cpu_of(rq_of(cfs_rq))];
if (!se || throttled_hierarchy(cfs_rq))
return;
#ifndef CONFIG_SMP
if (likely(se->load.weight == tg->shares))
return;
#endif
shares = calc_cfs_shares(cfs_rq, tg);
reweight_entity(cfs_rq_of(se), se, shares);
}
#else /* CONFIG_FAIR_GROUP_SCHED */
static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
{
}
static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
{
}
static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
{
}
#endif /* CONFIG_FAIR_GROUP_SCHED */
static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
#ifdef CONFIG_SCHEDSTATS
struct task_struct *tsk = NULL;
if (entity_is_task(se))
tsk = task_of(se);
if (se->statistics.sleep_start) {
u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
if ((s64)delta < 0)
delta = 0;
if (unlikely(delta > se->statistics.sleep_max))
se->statistics.sleep_max = delta;
se->statistics.sleep_start = 0;
se->statistics.sum_sleep_runtime += delta;
if (tsk) {
account_scheduler_latency(tsk, delta >> 10, 1);
trace_sched_stat_sleep(tsk, delta);
}
}
if (se->statistics.block_start) {
u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
if ((s64)delta < 0)
delta = 0;
if (unlikely(delta > se->statistics.block_max))
se->statistics.block_max = delta;
se->statistics.block_start = 0;
se->statistics.sum_sleep_runtime += delta;
if (tsk) {
if (tsk->in_iowait) {
se->statistics.iowait_sum += delta;
se->statistics.iowait_count++;
trace_sched_stat_iowait(tsk, delta);
}
trace_sched_stat_blocked(tsk, delta);
/*
* Blocking time is in units of nanosecs, so shift by
* 20 to get a milliseconds-range estimation of the
* amount of time that the task spent sleeping:
*/
if (unlikely(prof_on == SLEEP_PROFILING)) {
profile_hits(SLEEP_PROFILING,
(void *)get_wchan(tsk),
delta >> 20);
}
account_scheduler_latency(tsk, delta >> 10, 0);
}
}
#endif
}
static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
#ifdef CONFIG_SCHED_DEBUG
s64 d = se->vruntime - cfs_rq->min_vruntime;
if (d < 0)
d = -d;
if (d > 3*sysctl_sched_latency)
schedstat_inc(cfs_rq, nr_spread_over);
#endif
}
static void
place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
{
u64 vruntime = cfs_rq->min_vruntime;
/*
* The 'current' period is already promised to the current tasks,
* however the extra weight of the new task will slow them down a
* little, place the new task so that it fits in the slot that
* stays open at the end.
*/
if (initial && sched_feat(START_DEBIT))
vruntime += sched_vslice(cfs_rq, se);
/* sleeps up to a single latency don't count. */
if (!initial) {
unsigned long thresh = sysctl_sched_latency;
/*
* Halve their sleep time's effect, to allow
* for a gentler effect of sleepers:
*/
if (sched_feat(GENTLE_FAIR_SLEEPERS))
thresh >>= 1;
vruntime -= thresh;
}
/* ensure we never gain time by being placed backwards. */
vruntime = max_vruntime(se->vruntime, vruntime);
se->vruntime = vruntime;
}
static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
static void
enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
{
/*
* Update the normalized vruntime before updating min_vruntime
* through callig update_curr().
*/
if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
se->vruntime += cfs_rq->min_vruntime;
/*
* Update run-time statistics of the 'current'.
*/
update_curr(cfs_rq);
update_cfs_load(cfs_rq, 0);
account_entity_enqueue(cfs_rq, se);
update_cfs_shares(cfs_rq);
if (flags & ENQUEUE_WAKEUP) {
place_entity(cfs_rq, se, 0);
enqueue_sleeper(cfs_rq, se);
}
update_stats_enqueue(cfs_rq, se);
check_spread(cfs_rq, se);
if (se != cfs_rq->curr)
__enqueue_entity(cfs_rq, se);
se->on_rq = 1;
if (cfs_rq->nr_running == 1) {
list_add_leaf_cfs_rq(cfs_rq);
check_enqueue_throttle(cfs_rq);
}
}
static void __clear_buddies_last(struct sched_entity *se)
{
for_each_sched_entity(se) {
struct cfs_rq *cfs_rq = cfs_rq_of(se);
if (cfs_rq->last == se)
cfs_rq->last = NULL;
else
break;
}
}
static void __clear_buddies_next(struct sched_entity *se)
{
for_each_sched_entity(se) {
struct cfs_rq *cfs_rq = cfs_rq_of(se);
if (cfs_rq->next == se)
cfs_rq->next = NULL;
else
break;
}
}
static void __clear_buddies_skip(struct sched_entity *se)
{
for_each_sched_entity(se) {
struct cfs_rq *cfs_rq = cfs_rq_of(se);
if (cfs_rq->skip == se)
cfs_rq->skip = NULL;
else
break;
}
}
static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
if (cfs_rq->last == se)
__clear_buddies_last(se);
if (cfs_rq->next == se)
__clear_buddies_next(se);
if (cfs_rq->skip == se)
__clear_buddies_skip(se);
}
static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
static void
dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
{
/*
* Update run-time statistics of the 'current'.
*/
update_curr(cfs_rq);
update_stats_dequeue(cfs_rq, se);
if (flags & DEQUEUE_SLEEP) {
#ifdef CONFIG_SCHEDSTATS
if (entity_is_task(se)) {
struct task_struct *tsk = task_of(se);
if (tsk->state & TASK_INTERRUPTIBLE)
se->statistics.sleep_start = rq_of(cfs_rq)->clock;
if (tsk->state & TASK_UNINTERRUPTIBLE)
se->statistics.block_start = rq_of(cfs_rq)->clock;
}
#endif
}
clear_buddies(cfs_rq, se);
if (se != cfs_rq->curr)
__dequeue_entity(cfs_rq, se);
se->on_rq = 0;
update_cfs_load(cfs_rq, 0);
account_entity_dequeue(cfs_rq, se);
/*
* Normalize the entity after updating the min_vruntime because the
* update can refer to the ->curr item and we need to reflect this
* movement in our normalized position.
*/
if (!(flags & DEQUEUE_SLEEP))
se->vruntime -= cfs_rq->min_vruntime;
/* return excess runtime on last dequeue */
return_cfs_rq_runtime(cfs_rq);
update_min_vruntime(cfs_rq);
update_cfs_shares(cfs_rq);
}
/*
* Preempt the current task with a newly woken task if needed:
*/
static void
check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
{
unsigned long ideal_runtime, delta_exec;
struct sched_entity *se;
s64 delta;
ideal_runtime = sched_slice(cfs_rq, curr);
delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
if (delta_exec > ideal_runtime) {
resched_task(rq_of(cfs_rq)->curr);
/*
* The current task ran long enough, ensure it doesn't get
* re-elected due to buddy favours.
*/
clear_buddies(cfs_rq, curr);
return;
}
/*
* Ensure that a task that missed wakeup preemption by a
* narrow margin doesn't have to wait for a full slice.
* This also mitigates buddy induced latencies under load.
*/
if (delta_exec < sysctl_sched_min_granularity)
return;
se = __pick_first_entity(cfs_rq);
delta = curr->vruntime - se->vruntime;
if (delta < 0)
return;
if (delta > ideal_runtime)
resched_task(rq_of(cfs_rq)->curr);
}
static void
set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
/* 'current' is not kept within the tree. */
if (se->on_rq) {
/*
* Any task has to be enqueued before it get to execute on
* a CPU. So account for the time it spent waiting on the
* runqueue.
*/
update_stats_wait_end(cfs_rq, se);
__dequeue_entity(cfs_rq, se);
}
update_stats_curr_start(cfs_rq, se);
cfs_rq->curr = se;
#ifdef CONFIG_SCHEDSTATS
/*
* Track our maximum slice length, if the CPU's load is at
* least twice that of our own weight (i.e. dont track it
* when there are only lesser-weight tasks around):
*/
if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
se->statistics.slice_max = max(se->statistics.slice_max,
se->sum_exec_runtime - se->prev_sum_exec_runtime);
}
#endif
se->prev_sum_exec_runtime = se->sum_exec_runtime;
}
static int
wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
/*
* Pick the next process, keeping these things in mind, in this order:
* 1) keep things fair between processes/task groups
* 2) pick the "next" process, since someone really wants that to run
* 3) pick the "last" process, for cache locality
* 4) do not run the "skip" process, if something else is available
*/
static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
{
struct sched_entity *se = __pick_first_entity(cfs_rq);
struct sched_entity *left = se;
/*
* Avoid running the skip buddy, if running something else can
* be done without getting too unfair.
*/
if (cfs_rq->skip == se) {
struct sched_entity *second = __pick_next_entity(se);
if (second && wakeup_preempt_entity(second, left) < 1)
se = second;
}
/*
* Prefer last buddy, try to return the CPU to a preempted task.
*/
if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
se = cfs_rq->last;
/*
* Someone really wants this to run. If it's not unfair, run it.
*/
if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
se = cfs_rq->next;
clear_buddies(cfs_rq, se);
return se;
}
static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
{
/*
* If still on the runqueue then deactivate_task()
* was not called and update_curr() has to be done:
*/
if (prev->on_rq)
update_curr(cfs_rq);
/* throttle cfs_rqs exceeding runtime */
check_cfs_rq_runtime(cfs_rq);
check_spread(cfs_rq, prev);
if (prev->on_rq) {
update_stats_wait_start(cfs_rq, prev);
/* Put 'current' back into the tree. */
__enqueue_entity(cfs_rq, prev);
}
cfs_rq->curr = NULL;
}
static void
entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
{
/*
* Update run-time statistics of the 'current'.
*/
update_curr(cfs_rq);
/*
* Update share accounting for long-running entities.
*/
update_entity_shares_tick(cfs_rq);
#ifdef CONFIG_SCHED_HRTICK
/*
* queued ticks are scheduled to match the slice, so don't bother
* validating it and just reschedule.
*/
if (queued) {
resched_task(rq_of(cfs_rq)->curr);
return;
}
/*
* don't let the period tick interfere with the hrtick preemption
*/
if (!sched_feat(DOUBLE_TICK) &&
hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
return;
#endif
if (cfs_rq->nr_running > 1)
check_preempt_tick(cfs_rq, curr);
}
/**************************************************
* CFS bandwidth control machinery
*/
#ifdef CONFIG_CFS_BANDWIDTH
#ifdef HAVE_JUMP_LABEL
static struct static_key __cfs_bandwidth_used;
static inline bool cfs_bandwidth_used(void)
{
return static_key_false(&__cfs_bandwidth_used);
}
void account_cfs_bandwidth_used(int enabled, int was_enabled)
{
/* only need to count groups transitioning between enabled/!enabled */
if (enabled && !was_enabled)
static_key_slow_inc(&__cfs_bandwidth_used);
else if (!enabled && was_enabled)
static_key_slow_dec(&__cfs_bandwidth_used);
}
#else /* HAVE_JUMP_LABEL */
static bool cfs_bandwidth_used(void)
{
return true;
}
void account_cfs_bandwidth_used(int enabled, int was_enabled) {}
#endif /* HAVE_JUMP_LABEL */
/*
* default period for cfs group bandwidth.
* default: 0.1s, units: nanoseconds
*/
static inline u64 default_cfs_period(void)
{
return 100000000ULL;
}
static inline u64 sched_cfs_bandwidth_slice(void)
{
return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
}
/*
* Replenish runtime according to assigned quota and update expiration time.
* We use sched_clock_cpu directly instead of rq->clock to avoid adding
* additional synchronization around rq->lock.
*
* requires cfs_b->lock
*/
void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
{
u64 now;
if (cfs_b->quota == RUNTIME_INF)
return;
now = sched_clock_cpu(smp_processor_id());
cfs_b->runtime = cfs_b->quota;
cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
}
static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
{
return &tg->cfs_bandwidth;
}
/* returns 0 on failure to allocate runtime */
static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
{
struct task_group *tg = cfs_rq->tg;
struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
u64 amount = 0, min_amount, expires;
/* note: this is a positive sum as runtime_remaining <= 0 */
min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
raw_spin_lock(&cfs_b->lock);
if (cfs_b->quota == RUNTIME_INF)
amount = min_amount;
else {
/*
* If the bandwidth pool has become inactive, then at least one
* period must have elapsed since the last consumption.
* Refresh the global state and ensure bandwidth timer becomes
* active.
*/
if (!cfs_b->timer_active) {
__refill_cfs_bandwidth_runtime(cfs_b);
__start_cfs_bandwidth(cfs_b);
}
if (cfs_b->runtime > 0) {
amount = min(cfs_b->runtime, min_amount);
cfs_b->runtime -= amount;
cfs_b->idle = 0;
}
}
expires = cfs_b->runtime_expires;
raw_spin_unlock(&cfs_b->lock);
cfs_rq->runtime_remaining += amount;
/*
* we may have advanced our local expiration to account for allowed
* spread between our sched_clock and the one on which runtime was
* issued.
*/
if ((s64)(expires - cfs_rq->runtime_expires) > 0)
cfs_rq->runtime_expires = expires;
return cfs_rq->runtime_remaining > 0;
}
/*
* Note: This depends on the synchronization provided by sched_clock and the
* fact that rq->clock snapshots this value.
*/
static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
{
struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
struct rq *rq = rq_of(cfs_rq);
/* if the deadline is ahead of our clock, nothing to do */
if (likely((s64)(rq->clock - cfs_rq->runtime_expires) < 0))
return;
if (cfs_rq->runtime_remaining < 0)
return;
/*
* If the local deadline has passed we have to consider the
* possibility that our sched_clock is 'fast' and the global deadline
* has not truly expired.
*
* Fortunately we can check determine whether this the case by checking
* whether the global deadline has advanced.
*/
if ((s64)(cfs_rq->runtime_expires - cfs_b->runtime_expires) >= 0) {
/* extend local deadline, drift is bounded above by 2 ticks */
cfs_rq->runtime_expires += TICK_NSEC;
} else {
/* global deadline is ahead, expiration has passed */
cfs_rq->runtime_remaining = 0;
}
}
static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq,
unsigned long delta_exec)
{
/* dock delta_exec before expiring quota (as it could span periods) */
cfs_rq->runtime_remaining -= delta_exec;
expire_cfs_rq_runtime(cfs_rq);
if (likely(cfs_rq->runtime_remaining > 0))
return;
/*
* if we're unable to extend our runtime we resched so that the active
* hierarchy can be throttled
*/
if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
resched_task(rq_of(cfs_rq)->curr);
}
static __always_inline
void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec)
{
if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
return;
__account_cfs_rq_runtime(cfs_rq, delta_exec);
}
static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
{
return cfs_bandwidth_used() && cfs_rq->throttled;
}
/* check whether cfs_rq, or any parent, is throttled */
static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
{
return cfs_bandwidth_used() && cfs_rq->throttle_count;
}
/*
* Ensure that neither of the group entities corresponding to src_cpu or
* dest_cpu are members of a throttled hierarchy when performing group
* load-balance operations.
*/
static inline int throttled_lb_pair(struct task_group *tg,
int src_cpu, int dest_cpu)
{
struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
src_cfs_rq = tg->cfs_rq[src_cpu];
dest_cfs_rq = tg->cfs_rq[dest_cpu];
return throttled_hierarchy(src_cfs_rq) ||
throttled_hierarchy(dest_cfs_rq);
}
/* updated child weight may affect parent so we have to do this bottom up */
static int tg_unthrottle_up(struct task_group *tg, void *data)
{
struct rq *rq = data;
struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
cfs_rq->throttle_count--;
#ifdef CONFIG_SMP
if (!cfs_rq->throttle_count) {
u64 delta = rq->clock_task - cfs_rq->load_stamp;
/* leaving throttled state, advance shares averaging windows */
cfs_rq->load_stamp += delta;
cfs_rq->load_last += delta;
/* update entity weight now that we are on_rq again */
update_cfs_shares(cfs_rq);
}
#endif
return 0;
}
static int tg_throttle_down(struct task_group *tg, void *data)
{
struct rq *rq = data;
struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
/* group is entering throttled state, record last load */
if (!cfs_rq->throttle_count)
update_cfs_load(cfs_rq, 0);
cfs_rq->throttle_count++;
return 0;
}
static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
{
struct rq *rq = rq_of(cfs_rq);
struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
struct sched_entity *se;
long task_delta, dequeue = 1;
se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
/* account load preceding throttle */
rcu_read_lock();
walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
rcu_read_unlock();
task_delta = cfs_rq->h_nr_running;
for_each_sched_entity(se) {
struct cfs_rq *qcfs_rq = cfs_rq_of(se);
/* throttled entity or throttle-on-deactivate */
if (!se->on_rq)
break;
if (dequeue)
dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
qcfs_rq->h_nr_running -= task_delta;
if (qcfs_rq->load.weight)
dequeue = 0;
}
if (!se)
rq->nr_running -= task_delta;
cfs_rq->throttled = 1;
cfs_rq->throttled_timestamp = rq->clock;
raw_spin_lock(&cfs_b->lock);
list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
raw_spin_unlock(&cfs_b->lock);
}
void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
{
struct rq *rq = rq_of(cfs_rq);
struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
struct sched_entity *se;
int enqueue = 1;
long task_delta;
se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
cfs_rq->throttled = 0;
raw_spin_lock(&cfs_b->lock);
cfs_b->throttled_time += rq->clock - cfs_rq->throttled_timestamp;
list_del_rcu(&cfs_rq->throttled_list);
raw_spin_unlock(&cfs_b->lock);
cfs_rq->throttled_timestamp = 0;
update_rq_clock(rq);
/* update hierarchical throttle state */
walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
if (!cfs_rq->load.weight)
return;
task_delta = cfs_rq->h_nr_running;
for_each_sched_entity(se) {
if (se->on_rq)
enqueue = 0;
cfs_rq = cfs_rq_of(se);
if (enqueue)
enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
cfs_rq->h_nr_running += task_delta;
if (cfs_rq_throttled(cfs_rq))
break;
}
if (!se)
rq->nr_running += task_delta;
/* determine whether we need to wake up potentially idle cpu */
if (rq->curr == rq->idle && rq->cfs.nr_running)
resched_task(rq->curr);
}
static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
u64 remaining, u64 expires)
{
struct cfs_rq *cfs_rq;
u64 runtime = remaining;
rcu_read_lock();
list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
throttled_list) {
struct rq *rq = rq_of(cfs_rq);
raw_spin_lock(&rq->lock);
if (!cfs_rq_throttled(cfs_rq))
goto next;
runtime = -cfs_rq->runtime_remaining + 1;
if (runtime > remaining)
runtime = remaining;
remaining -= runtime;
cfs_rq->runtime_remaining += runtime;
cfs_rq->runtime_expires = expires;
/* we check whether we're throttled above */
if (cfs_rq->runtime_remaining > 0)
unthrottle_cfs_rq(cfs_rq);
next:
raw_spin_unlock(&rq->lock);
if (!remaining)
break;
}
rcu_read_unlock();
return remaining;
}
/*
* Responsible for refilling a task_group's bandwidth and unthrottling its
* cfs_rqs as appropriate. If there has been no activity within the last
* period the timer is deactivated until scheduling resumes; cfs_b->idle is
* used to track this state.
*/
static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
{
u64 runtime, runtime_expires;
int idle = 1, throttled;
raw_spin_lock(&cfs_b->lock);
/* no need to continue the timer with no bandwidth constraint */
if (cfs_b->quota == RUNTIME_INF)
goto out_unlock;
throttled = !list_empty(&cfs_b->throttled_cfs_rq);
/* idle depends on !throttled (for the case of a large deficit) */
idle = cfs_b->idle && !throttled;
cfs_b->nr_periods += overrun;
/* if we're going inactive then everything else can be deferred */
if (idle)
goto out_unlock;
__refill_cfs_bandwidth_runtime(cfs_b);
if (!throttled) {
/* mark as potentially idle for the upcoming period */
cfs_b->idle = 1;
goto out_unlock;
}
/* account preceding periods in which throttling occurred */
cfs_b->nr_throttled += overrun;
/*
* There are throttled entities so we must first use the new bandwidth
* to unthrottle them before making it generally available. This
* ensures that all existing debts will be paid before a new cfs_rq is
* allowed to run.
*/
runtime = cfs_b->runtime;
runtime_expires = cfs_b->runtime_expires;
cfs_b->runtime = 0;
/*
* This check is repeated as we are holding onto the new bandwidth
* while we unthrottle. This can potentially race with an unthrottled
* group trying to acquire new bandwidth from the global pool.
*/
while (throttled && runtime > 0) {
raw_spin_unlock(&cfs_b->lock);
/* we can't nest cfs_b->lock while distributing bandwidth */
runtime = distribute_cfs_runtime(cfs_b, runtime,
runtime_expires);
raw_spin_lock(&cfs_b->lock);
throttled = !list_empty(&cfs_b->throttled_cfs_rq);
}
/* return (any) remaining runtime */
cfs_b->runtime = runtime;
/*
* While we are ensured activity in the period following an
* unthrottle, this also covers the case in which the new bandwidth is
* insufficient to cover the existing bandwidth deficit. (Forcing the
* timer to remain active while there are any throttled entities.)
*/
cfs_b->idle = 0;
out_unlock:
if (idle)
cfs_b->timer_active = 0;
raw_spin_unlock(&cfs_b->lock);
return idle;
}
/* a cfs_rq won't donate quota below this amount */
static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
/* minimum remaining period time to redistribute slack quota */
static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
/* how long we wait to gather additional slack before distributing */
static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
/* are we near the end of the current quota period? */
static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
{
struct hrtimer *refresh_timer = &cfs_b->period_timer;
u64 remaining;
/* if the call-back is running a quota refresh is already occurring */
if (hrtimer_callback_running(refresh_timer))
return 1;
/* is a quota refresh about to occur? */
remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
if (remaining < min_expire)
return 1;
return 0;
}
static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
{
u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
/* if there's a quota refresh soon don't bother with slack */
if (runtime_refresh_within(cfs_b, min_left))
return;
start_bandwidth_timer(&cfs_b->slack_timer,
ns_to_ktime(cfs_bandwidth_slack_period));
}
/* we know any runtime found here is valid as update_curr() precedes return */
static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
{
struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
if (slack_runtime <= 0)
return;
raw_spin_lock(&cfs_b->lock);
if (cfs_b->quota != RUNTIME_INF &&
cfs_rq->runtime_expires == cfs_b->runtime_expires) {
cfs_b->runtime += slack_runtime;
/* we are under rq->lock, defer unthrottling using a timer */
if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
!list_empty(&cfs_b->throttled_cfs_rq))
start_cfs_slack_bandwidth(cfs_b);
}
raw_spin_unlock(&cfs_b->lock);
/* even if it's not valid for return we don't want to try again */
cfs_rq->runtime_remaining -= slack_runtime;
}
static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
{
if (!cfs_bandwidth_used())
return;
if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
return;
__return_cfs_rq_runtime(cfs_rq);
}
/*
* This is done with a timer (instead of inline with bandwidth return) since
* it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
*/
static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
{
u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
u64 expires;
/* confirm we're still not at a refresh boundary */
if (runtime_refresh_within(cfs_b, min_bandwidth_expiration))
return;
raw_spin_lock(&cfs_b->lock);
if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) {
runtime = cfs_b->runtime;
cfs_b->runtime = 0;
}
expires = cfs_b->runtime_expires;
raw_spin_unlock(&cfs_b->lock);
if (!runtime)
return;
runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
raw_spin_lock(&cfs_b->lock);
if (expires == cfs_b->runtime_expires)
cfs_b->runtime = runtime;
raw_spin_unlock(&cfs_b->lock);
}
/*
* When a group wakes up we want to make sure that its quota is not already
* expired/exceeded, otherwise it may be allowed to steal additional ticks of
* runtime as update_curr() throttling can not not trigger until it's on-rq.
*/
static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
{
if (!cfs_bandwidth_used())
return;
/* an active group must be handled by the update_curr()->put() path */
if (!cfs_rq->runtime_enabled || cfs_rq->curr)
return;
/* ensure the group is not already throttled */
if (cfs_rq_throttled(cfs_rq))
return;
/* update runtime allocation */
account_cfs_rq_runtime(cfs_rq, 0);
if (cfs_rq->runtime_remaining <= 0)
throttle_cfs_rq(cfs_rq);
}
/* conditionally throttle active cfs_rq's from put_prev_entity() */
static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
{
if (!cfs_bandwidth_used())
return;
if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
return;
/*
* it's possible for a throttled entity to be forced into a running
* state (e.g. set_curr_task), in this case we're finished.
*/
if (cfs_rq_throttled(cfs_rq))
return;
throttle_cfs_rq(cfs_rq);
}
static inline u64 default_cfs_period(void);
static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun);
static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b);
static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
{
struct cfs_bandwidth *cfs_b =
container_of(timer, struct cfs_bandwidth, slack_timer);
do_sched_cfs_slack_timer(cfs_b);
return HRTIMER_NORESTART;
}
static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
{
struct cfs_bandwidth *cfs_b =
container_of(timer, struct cfs_bandwidth, period_timer);
ktime_t now;
int overrun;
int idle = 0;
for (;;) {
now = hrtimer_cb_get_time(timer);
overrun = hrtimer_forward(timer, now, cfs_b->period);
if (!overrun)
break;
idle = do_sched_cfs_period_timer(cfs_b, overrun);
}
return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
}
void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
{
raw_spin_lock_init(&cfs_b->lock);
cfs_b->runtime = 0;
cfs_b->quota = RUNTIME_INF;
cfs_b->period = ns_to_ktime(default_cfs_period());
INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
cfs_b->period_timer.function = sched_cfs_period_timer;
hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
cfs_b->slack_timer.function = sched_cfs_slack_timer;
}
static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
{
cfs_rq->runtime_enabled = 0;
INIT_LIST_HEAD(&cfs_rq->throttled_list);
}
/* requires cfs_b->lock, may release to reprogram timer */
void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
{
/*
* The timer may be active because we're trying to set a new bandwidth
* period or because we're racing with the tear-down path
* (timer_active==0 becomes visible before the hrtimer call-back
* terminates). In either case we ensure that it's re-programmed
*/
while (unlikely(hrtimer_active(&cfs_b->period_timer))) {
raw_spin_unlock(&cfs_b->lock);
/* ensure cfs_b->lock is available while we wait */
hrtimer_cancel(&cfs_b->period_timer);
raw_spin_lock(&cfs_b->lock);
/* if someone else restarted the timer then we're done */
if (cfs_b->timer_active)
return;
}
cfs_b->timer_active = 1;
start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
}
static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
{
hrtimer_cancel(&cfs_b->period_timer);
hrtimer_cancel(&cfs_b->slack_timer);
}
void unthrottle_offline_cfs_rqs(struct rq *rq)
{
struct cfs_rq *cfs_rq;
for_each_leaf_cfs_rq(rq, cfs_rq) {
struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
if (!cfs_rq->runtime_enabled)
continue;
/*
* clock_task is not advancing so we just need to make sure
* there's some valid quota amount
*/
cfs_rq->runtime_remaining = cfs_b->quota;
if (cfs_rq_throttled(cfs_rq))
unthrottle_cfs_rq(cfs_rq);
}
}
#else /* CONFIG_CFS_BANDWIDTH */
static __always_inline
void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, unsigned long delta_exec) {}
static void check_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
{
return 0;
}
static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
{
return 0;
}
static inline int throttled_lb_pair(struct task_group *tg,
int src_cpu, int dest_cpu)
{
return 0;
}
void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
#ifdef CONFIG_FAIR_GROUP_SCHED
static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
#endif
static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
{
return NULL;
}
static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
void unthrottle_offline_cfs_rqs(struct rq *rq) {}
#endif /* CONFIG_CFS_BANDWIDTH */
/**************************************************
* CFS operations on tasks:
*/
#ifdef CONFIG_SCHED_HRTICK
static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
{
struct sched_entity *se = &p->se;
struct cfs_rq *cfs_rq = cfs_rq_of(se);
WARN_ON(task_rq(p) != rq);
if (cfs_rq->nr_running > 1) {
u64 slice = sched_slice(cfs_rq, se);
u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
s64 delta = slice - ran;
if (delta < 0) {
if (rq->curr == p)
resched_task(p);
return;
}
/*
* Don't schedule slices shorter than 10000ns, that just
* doesn't make sense. Rely on vruntime for fairness.
*/
if (rq->curr != p)
delta = max_t(s64, 10000LL, delta);
hrtick_start(rq, delta);
}
}
/*
* called from enqueue/dequeue and updates the hrtick when the
* current task is from our class and nr_running is low enough
* to matter.
*/
static void hrtick_update(struct rq *rq)
{
struct task_struct *curr = rq->curr;
if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
return;
if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
hrtick_start_fair(rq, curr);
}
#else /* !CONFIG_SCHED_HRTICK */
static inline void
hrtick_start_fair(struct rq *rq, struct task_struct *p)
{
}
static inline void hrtick_update(struct rq *rq)
{
}
#endif
/*
* The enqueue_task method is called before nr_running is
* increased. Here we update the fair scheduling stats and
* then put the task into the rbtree:
*/
static void
enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
{
struct cfs_rq *cfs_rq;
struct sched_entity *se = &p->se;
for_each_sched_entity(se) {
if (se->on_rq)
break;
cfs_rq = cfs_rq_of(se);
enqueue_entity(cfs_rq, se, flags);
/*
* end evaluation on encountering a throttled cfs_rq
*
* note: in the case of encountering a throttled cfs_rq we will
* post the final h_nr_running increment below.
*/
if (cfs_rq_throttled(cfs_rq))
break;
cfs_rq->h_nr_running++;
flags = ENQUEUE_WAKEUP;
}
for_each_sched_entity(se) {
cfs_rq = cfs_rq_of(se);
cfs_rq->h_nr_running++;
if (cfs_rq_throttled(cfs_rq))
break;
update_cfs_load(cfs_rq, 0);
update_cfs_shares(cfs_rq);
}
if (!se)
inc_nr_running(rq);
hrtick_update(rq);
}
static void set_next_buddy(struct sched_entity *se);
/*
* The dequeue_task method is called before nr_running is
* decreased. We remove the task from the rbtree and
* update the fair scheduling stats:
*/
static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
{
struct cfs_rq *cfs_rq;
struct sched_entity *se = &p->se;
int task_sleep = flags & DEQUEUE_SLEEP;
for_each_sched_entity(se) {
cfs_rq = cfs_rq_of(se);
dequeue_entity(cfs_rq, se, flags);
/*
* end evaluation on encountering a throttled cfs_rq
*
* note: in the case of encountering a throttled cfs_rq we will
* post the final h_nr_running decrement below.
*/
if (cfs_rq_throttled(cfs_rq))
break;
cfs_rq->h_nr_running--;
/* Don't dequeue parent if it has other entities besides us */
if (cfs_rq->load.weight) {
/*
* Bias pick_next to pick a task from this cfs_rq, as
* p is sleeping when it is within its sched_slice.
*/
if (task_sleep && parent_entity(se))
set_next_buddy(parent_entity(se));
/* avoid re-evaluating load for this entity */
se = parent_entity(se);
break;
}
flags |= DEQUEUE_SLEEP;
}
for_each_sched_entity(se) {
cfs_rq = cfs_rq_of(se);
cfs_rq->h_nr_running--;
if (cfs_rq_throttled(cfs_rq))
break;
update_cfs_load(cfs_rq, 0);
update_cfs_shares(cfs_rq);
}
if (!se)
dec_nr_running(rq);
hrtick_update(rq);
}
#ifdef CONFIG_SMP
/* Used instead of source_load when we know the type == 0 */
static unsigned long weighted_cpuload(const int cpu)
{
return cpu_rq(cpu)->load.weight;
}
/*
* Return a low guess at the load of a migration-source cpu weighted
* according to the scheduling class and "nice" value.
*
* We want to under-estimate the load of migration sources, to
* balance conservatively.
*/
static unsigned long source_load(int cpu, int type)
{
struct rq *rq = cpu_rq(cpu);
unsigned long total = weighted_cpuload(cpu);
if (type == 0 || !sched_feat(LB_BIAS))
return total;
return min(rq->cpu_load[type-1], total);
}
/*
* Return a high guess at the load of a migration-target cpu weighted
* according to the scheduling class and "nice" value.
*/
static unsigned long target_load(int cpu, int type)
{
struct rq *rq = cpu_rq(cpu);
unsigned long total = weighted_cpuload(cpu);
if (type == 0 || !sched_feat(LB_BIAS))
return total;
return max(rq->cpu_load[type-1], total);
}
static unsigned long power_of(int cpu)
{
return cpu_rq(cpu)->cpu_power;
}
static unsigned long cpu_avg_load_per_task(int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
if (nr_running)
return rq->load.weight / nr_running;
return 0;
}
static void task_waking_fair(struct task_struct *p)
{
struct sched_entity *se = &p->se;
struct cfs_rq *cfs_rq = cfs_rq_of(se);
u64 min_vruntime;
#ifndef CONFIG_64BIT
u64 min_vruntime_copy;
do {
min_vruntime_copy = cfs_rq->min_vruntime_copy;
smp_rmb();
min_vruntime = cfs_rq->min_vruntime;
} while (min_vruntime != min_vruntime_copy);
#else
min_vruntime = cfs_rq->min_vruntime;
#endif
se->vruntime -= min_vruntime;
}
#ifdef CONFIG_FAIR_GROUP_SCHED
/*
* effective_load() calculates the load change as seen from the root_task_group
*
* Adding load to a group doesn't make a group heavier, but can cause movement
* of group shares between cpus. Assuming the shares were perfectly aligned one
* can calculate the shift in shares.
*
* Calculate the effective load difference if @wl is added (subtracted) to @tg
* on this @cpu and results in a total addition (subtraction) of @wg to the
* total group weight.
*
* Given a runqueue weight distribution (rw_i) we can compute a shares
* distribution (s_i) using:
*
* s_i = rw_i / \Sum rw_j (1)
*
* Suppose we have 4 CPUs and our @tg is a direct child of the root group and
* has 7 equal weight tasks, distributed as below (rw_i), with the resulting
* shares distribution (s_i):
*
* rw_i = { 2, 4, 1, 0 }
* s_i = { 2/7, 4/7, 1/7, 0 }
*
* As per wake_affine() we're interested in the load of two CPUs (the CPU the
* task used to run on and the CPU the waker is running on), we need to
* compute the effect of waking a task on either CPU and, in case of a sync
* wakeup, compute the effect of the current task going to sleep.
*
* So for a change of @wl to the local @cpu with an overall group weight change
* of @wl we can compute the new shares distribution (s'_i) using:
*
* s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
*
* Suppose we're interested in CPUs 0 and 1, and want to compute the load
* differences in waking a task to CPU 0. The additional task changes the
* weight and shares distributions like:
*
* rw'_i = { 3, 4, 1, 0 }
* s'_i = { 3/8, 4/8, 1/8, 0 }
*
* We can then compute the difference in effective weight by using:
*
* dw_i = S * (s'_i - s_i) (3)
*
* Where 'S' is the group weight as seen by its parent.
*
* Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
* times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
* 4/7) times the weight of the group.
*/
static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
{
struct sched_entity *se = tg->se[cpu];
if (!tg->parent) /* the trivial, non-cgroup case */
return wl;
for_each_sched_entity(se) {
long w, W;
tg = se->my_q->tg;
/*
* W = @wg + \Sum rw_j
*/
W = wg + calc_tg_weight(tg, se->my_q);
/*
* w = rw_i + @wl
*/
w = se->my_q->load.weight + wl;
/*
* wl = S * s'_i; see (2)
*/
if (W > 0 && w < W)
wl = (w * tg->shares) / W;
else
wl = tg->shares;
/*
* Per the above, wl is the new se->load.weight value; since
* those are clipped to [MIN_SHARES, ...) do so now. See
* calc_cfs_shares().
*/
if (wl < MIN_SHARES)
wl = MIN_SHARES;
/*
* wl = dw_i = S * (s'_i - s_i); see (3)
*/
wl -= se->load.weight;
/*
* Recursively apply this logic to all parent groups to compute
* the final effective load change on the root group. Since
* only the @tg group gets extra weight, all parent groups can
* only redistribute existing shares. @wl is the shift in shares
* resulting from this level per the above.
*/
wg = 0;
}
return wl;
}
#else
static inline unsigned long effective_load(struct task_group *tg, int cpu,
unsigned long wl, unsigned long wg)
{
return wl;
}
#endif
static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
{
s64 this_load, load;
int idx, this_cpu, prev_cpu;
unsigned long tl_per_task;
struct task_group *tg;
unsigned long weight;
int balanced;
idx = sd->wake_idx;
this_cpu = smp_processor_id();
prev_cpu = task_cpu(p);
load = source_load(prev_cpu, idx);
this_load = target_load(this_cpu, idx);
/*
* If sync wakeup then subtract the (maximum possible)
* effect of the currently running task from the load
* of the current CPU:
*/
if (sync) {
tg = task_group(current);
weight = current->se.load.weight;
this_load += effective_load(tg, this_cpu, -weight, -weight);
load += effective_load(tg, prev_cpu, 0, -weight);
}
tg = task_group(p);
weight = p->se.load.weight;
/*
* In low-load situations, where prev_cpu is idle and this_cpu is idle
* due to the sync cause above having dropped this_load to 0, we'll
* always have an imbalance, but there's really nothing you can do
* about that, so that's good too.
*
* Otherwise check if either cpus are near enough in load to allow this
* task to be woken on this_cpu.
*/
if (this_load > 0) {
s64 this_eff_load, prev_eff_load;
this_eff_load = 100;
this_eff_load *= power_of(prev_cpu);
this_eff_load *= this_load +
effective_load(tg, this_cpu, weight, weight);
prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
prev_eff_load *= power_of(this_cpu);
prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
balanced = this_eff_load <= prev_eff_load;
} else
balanced = true;
/*
* If the currently running task will sleep within
* a reasonable amount of time then attract this newly
* woken task:
*/
if (sync && balanced)
return 1;
schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
tl_per_task = cpu_avg_load_per_task(this_cpu);
if (balanced ||
(this_load <= load &&
this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
/*
* This domain has SD_WAKE_AFFINE and
* p is cache cold in this domain, and
* there is no bad imbalance.
*/
schedstat_inc(sd, ttwu_move_affine);
schedstat_inc(p, se.statistics.nr_wakeups_affine);
return 1;
}
return 0;
}
/*
* find_idlest_group finds and returns the least busy CPU group within the
* domain.
*/
static struct sched_group *
find_idlest_group(struct sched_domain *sd, struct task_struct *p,
int this_cpu, int load_idx)
{
struct sched_group *idlest = NULL, *group = sd->groups;
unsigned long min_load = ULONG_MAX, this_load = 0;
int imbalance = 100 + (sd->imbalance_pct-100)/2;
do {
unsigned long load, avg_load;
int local_group;
int i;
/* Skip over this group if it has no CPUs allowed */
if (!cpumask_intersects(sched_group_cpus(group),
tsk_cpus_allowed(p)))
continue;
local_group = cpumask_test_cpu(this_cpu,
sched_group_cpus(group));
/* Tally up the load of all CPUs in the group */
avg_load = 0;
for_each_cpu(i, sched_group_cpus(group)) {
/* Bias balancing toward cpus of our domain */
if (local_group)
load = source_load(i, load_idx);
else
load = target_load(i, load_idx);
avg_load += load;
}
/* Adjust by relative CPU power of the group */
avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
if (local_group) {
this_load = avg_load;
} else if (avg_load < min_load) {
min_load = avg_load;
idlest = group;
}
} while (group = group->next, group != sd->groups);
if (!idlest || 100*this_load < imbalance*min_load)
return NULL;
return idlest;
}
/*
* find_idlest_cpu - find the idlest cpu among the cpus in group.
*/
static int
find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
{
unsigned long load, min_load = ULONG_MAX;
int idlest = -1;
int i;
/* Traverse only the allowed CPUs */
for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
load = weighted_cpuload(i);
if (load < min_load || (load == min_load && i == this_cpu)) {
min_load = load;
idlest = i;
}
}
return idlest;
}
/*
* Try and locate an idle CPU in the sched_domain.
*/
static int select_idle_sibling(struct task_struct *p, int target)
{
int cpu = smp_processor_id();
int prev_cpu = task_cpu(p);
struct sched_domain *sd;
struct sched_group *sg;
int i;
/*
* If the task is going to be woken-up on this cpu and if it is
* already idle, then it is the right target.
*/
if (target == cpu && idle_cpu(cpu))
return cpu;
/*
* If the task is going to be woken-up on the cpu where it previously
* ran and if it is currently idle, then it the right target.
*/
if (target == prev_cpu && idle_cpu(prev_cpu))
return prev_cpu;
/*
* Otherwise, iterate the domains and find an elegible idle cpu.
*/
sd = rcu_dereference(per_cpu(sd_llc, target));
for_each_lower_domain(sd) {
sg = sd->groups;
do {
if (!cpumask_intersects(sched_group_cpus(sg),
tsk_cpus_allowed(p)))
goto next;
for_each_cpu(i, sched_group_cpus(sg)) {
if (!idle_cpu(i))
goto next;
}
target = cpumask_first_and(sched_group_cpus(sg),
tsk_cpus_allowed(p));
goto done;
next:
sg = sg->next;
} while (sg != sd->groups);
}
done:
return target;
}
/*
* sched_balance_self: balance the current task (running on cpu) in domains
* that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
* SD_BALANCE_EXEC.
*
* Balance, ie. select the least loaded group.
*
* Returns the target CPU number, or the same CPU if no balancing is needed.
*
* preempt must be disabled.
*/
static int
select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
{
struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
int cpu = smp_processor_id();
int prev_cpu = task_cpu(p);
int new_cpu = cpu;
int want_affine = 0;
int want_sd = 1;
int sync = wake_flags & WF_SYNC;
if (p->rt.nr_cpus_allowed == 1)
return prev_cpu;
if (sd_flag & SD_BALANCE_WAKE) {
if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
want_affine = 1;
new_cpu = prev_cpu;
}
rcu_read_lock();
for_each_domain(cpu, tmp) {
if (!(tmp->flags & SD_LOAD_BALANCE))
continue;
/*
* If power savings logic is enabled for a domain, see if we
* are not overloaded, if so, don't balance wider.
*/
if (tmp->flags & (SD_POWERSAVINGS_BALANCE|SD_PREFER_LOCAL)) {
unsigned long power = 0;
unsigned long nr_running = 0;
unsigned long capacity;
int i;
for_each_cpu(i, sched_domain_span(tmp)) {
power += power_of(i);
nr_running += cpu_rq(i)->cfs.nr_running;
}
capacity = DIV_ROUND_CLOSEST(power, SCHED_POWER_SCALE);
if (tmp->flags & SD_POWERSAVINGS_BALANCE)
nr_running /= 2;
if (nr_running < capacity)
want_sd = 0;
}
/*
* If both cpu and prev_cpu are part of this domain,
* cpu is a valid SD_WAKE_AFFINE target.
*/
if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
affine_sd = tmp;
want_affine = 0;
}
if (!want_sd && !want_affine)
break;
if (!(tmp->flags & sd_flag))
continue;
if (want_sd)
sd = tmp;
}
if (affine_sd) {
if (cpu == prev_cpu || wake_affine(affine_sd, p, sync))
prev_cpu = cpu;
new_cpu = select_idle_sibling(p, prev_cpu);
goto unlock;
}
while (sd) {
int load_idx = sd->forkexec_idx;
struct sched_group *group;
int weight;
if (!(sd->flags & sd_flag)) {
sd = sd->child;
continue;
}
if (sd_flag & SD_BALANCE_WAKE)
load_idx = sd->wake_idx;
group = find_idlest_group(sd, p, cpu, load_idx);
if (!group) {
sd = sd->child;
continue;
}
new_cpu = find_idlest_cpu(group, p, cpu);
if (new_cpu == -1 || new_cpu == cpu) {
/* Now try balancing at a lower domain level of cpu */
sd = sd->child;
continue;
}
/* Now try balancing at a lower domain level of new_cpu */
cpu = new_cpu;
weight = sd->span_weight;
sd = NULL;
for_each_domain(cpu, tmp) {
if (weight <= tmp->span_weight)
break;
if (tmp->flags & sd_flag)
sd = tmp;
}
/* while loop will break here if sd == NULL */
}
unlock:
rcu_read_unlock();
return new_cpu;
}
#endif /* CONFIG_SMP */
static unsigned long
wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
{
unsigned long gran = sysctl_sched_wakeup_granularity;
/*
* Since its curr running now, convert the gran from real-time
* to virtual-time in his units.
*
* By using 'se' instead of 'curr' we penalize light tasks, so
* they get preempted easier. That is, if 'se' < 'curr' then
* the resulting gran will be larger, therefore penalizing the
* lighter, if otoh 'se' > 'curr' then the resulting gran will
* be smaller, again penalizing the lighter task.
*
* This is especially important for buddies when the leftmost
* task is higher priority than the buddy.
*/
return calc_delta_fair(gran, se);
}
/*
* Should 'se' preempt 'curr'.
*
* |s1
* |s2
* |s3
* g
* |<--->|c
*
* w(c, s1) = -1
* w(c, s2) = 0
* w(c, s3) = 1
*
*/
static int
wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
{
s64 gran, vdiff = curr->vruntime - se->vruntime;
if (vdiff <= 0)
return -1;
gran = wakeup_gran(curr, se);
if (vdiff > gran)
return 1;
return 0;
}
static void set_last_buddy(struct sched_entity *se)
{
if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
return;
for_each_sched_entity(se)
cfs_rq_of(se)->last = se;
}
static void set_next_buddy(struct sched_entity *se)
{
if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
return;
for_each_sched_entity(se)
cfs_rq_of(se)->next = se;
}
static void set_skip_buddy(struct sched_entity *se)
{
for_each_sched_entity(se)
cfs_rq_of(se)->skip = se;
}
/*
* Preempt the current task with a newly woken task if needed:
*/
static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
{
struct task_struct *curr = rq->curr;
struct sched_entity *se = &curr->se, *pse = &p->se;
struct cfs_rq *cfs_rq = task_cfs_rq(curr);
int scale = cfs_rq->nr_running >= sched_nr_latency;
int next_buddy_marked = 0;
if (unlikely(se == pse))
return;
/*
* This is possible from callers such as move_task(), in which we
* unconditionally check_prempt_curr() after an enqueue (which may have
* lead to a throttle). This both saves work and prevents false
* next-buddy nomination below.
*/
if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
return;
if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
set_next_buddy(pse);
next_buddy_marked = 1;
}
/*
* We can come here with TIF_NEED_RESCHED already set from new task
* wake up path.
*
* Note: this also catches the edge-case of curr being in a throttled
* group (e.g. via set_curr_task), since update_curr() (in the
* enqueue of curr) will have resulted in resched being set. This
* prevents us from potentially nominating it as a false LAST_BUDDY
* below.
*/
if (test_tsk_need_resched(curr))
return;
/* Idle tasks are by definition preempted by non-idle tasks. */
if (unlikely(curr->policy == SCHED_IDLE) &&
likely(p->policy != SCHED_IDLE))
goto preempt;
/*
* Batch and idle tasks do not preempt non-idle tasks (their preemption
* is driven by the tick):
*/
if (unlikely(p->policy != SCHED_NORMAL))
return;
find_matching_se(&se, &pse);
update_curr(cfs_rq_of(se));
BUG_ON(!pse);
if (wakeup_preempt_entity(se, pse) == 1) {
/*
* Bias pick_next to pick the sched entity that is
* triggering this preemption.
*/
if (!next_buddy_marked)
set_next_buddy(pse);
goto preempt;
}
return;
preempt:
resched_task(curr);
/*
* Only set the backward buddy when the current task is still
* on the rq. This can happen when a wakeup gets interleaved
* with schedule on the ->pre_schedule() or idle_balance()
* point, either of which can * drop the rq lock.
*
* Also, during early boot the idle thread is in the fair class,
* for obvious reasons its a bad idea to schedule back to it.
*/
if (unlikely(!se->on_rq || curr == rq->idle))
return;
if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
set_last_buddy(se);
}
static struct task_struct *pick_next_task_fair(struct rq *rq)
{
struct task_struct *p;
struct cfs_rq *cfs_rq = &rq->cfs;
struct sched_entity *se;
if (!cfs_rq->nr_running)
return NULL;
do {
se = pick_next_entity(cfs_rq);
set_next_entity(cfs_rq, se);
cfs_rq = group_cfs_rq(se);
} while (cfs_rq);
p = task_of(se);
if (hrtick_enabled(rq))
hrtick_start_fair(rq, p);
return p;
}
/*
* Account for a descheduled task:
*/
static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
{
struct sched_entity *se = &prev->se;
struct cfs_rq *cfs_rq;
for_each_sched_entity(se) {
cfs_rq = cfs_rq_of(se);
put_prev_entity(cfs_rq, se);
}
}
/*
* sched_yield() is very simple
*
* The magic of dealing with the ->skip buddy is in pick_next_entity.
*/
static void yield_task_fair(struct rq *rq)
{
struct task_struct *curr = rq->curr;
struct cfs_rq *cfs_rq = task_cfs_rq(curr);
struct sched_entity *se = &curr->se;
/*
* Are we the only task in the tree?
*/
if (unlikely(rq->nr_running == 1))
return;
clear_buddies(cfs_rq, se);
if (curr->policy != SCHED_BATCH) {
update_rq_clock(rq);
/*
* Update run-time statistics of the 'current'.
*/
update_curr(cfs_rq);
/*
* Tell update_rq_clock() that we've just updated,
* so we don't do microscopic update in schedule()
* and double the fastpath cost.
*/
rq->skip_clock_update = 1;
}
set_skip_buddy(se);
}
static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
{
struct sched_entity *se = &p->se;
/* throttled hierarchies are not runnable */
if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
return false;
/* Tell the scheduler that we'd really like pse to run next. */
set_next_buddy(se);
yield_task_fair(rq);
return true;
}
#ifdef CONFIG_SMP
/**************************************************
* Fair scheduling class load-balancing methods:
*/
static unsigned long __read_mostly max_load_balance_interval = HZ/10;
#define LBF_ALL_PINNED 0x01
#define LBF_NEED_BREAK 0x02
struct lb_env {
struct sched_domain *sd;
int src_cpu;
struct rq *src_rq;
int dst_cpu;
struct rq *dst_rq;
enum cpu_idle_type idle;
long load_move;
unsigned int flags;
unsigned int loop;
unsigned int loop_break;
unsigned int loop_max;
};
/*
* move_task - move a task from one runqueue to another runqueue.
* Both runqueues must be locked.
*/
static void move_task(struct task_struct *p, struct lb_env *env)
{
deactivate_task(env->src_rq, p, 0);
set_task_cpu(p, env->dst_cpu);
activate_task(env->dst_rq, p, 0);
check_preempt_curr(env->dst_rq, p, 0);
}
/*
* Is this task likely cache-hot:
*/
static int
task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
{
s64 delta;
if (p->sched_class != &fair_sched_class)
return 0;
if (unlikely(p->policy == SCHED_IDLE))
return 0;
/*
* Buddy candidates are cache hot:
*/
if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
(&p->se == cfs_rq_of(&p->se)->next ||
&p->se == cfs_rq_of(&p->se)->last))
return 1;
if (sysctl_sched_migration_cost == -1)
return 1;
if (sysctl_sched_migration_cost == 0)
return 0;
delta = now - p->se.exec_start;
return delta < (s64)sysctl_sched_migration_cost;
}
/*
* can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
*/
static
int can_migrate_task(struct task_struct *p, struct lb_env *env)
{
int tsk_cache_hot = 0;
/*
* We do not migrate tasks that are:
* 1) running (obviously), or
* 2) cannot be migrated to this CPU due to cpus_allowed, or
* 3) are cache-hot on their current CPU.
*/
if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
return 0;
}
env->flags &= ~LBF_ALL_PINNED;
if (task_running(env->src_rq, p)) {
schedstat_inc(p, se.statistics.nr_failed_migrations_running);
return 0;
}
/*
* Aggressive migration if:
* 1) task is cache cold, or
* 2) too many balance attempts have failed.
*/
tsk_cache_hot = task_hot(p, env->src_rq->clock_task, env->sd);
if (!tsk_cache_hot ||
env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
#ifdef CONFIG_SCHEDSTATS
if (tsk_cache_hot) {
schedstat_inc(env->sd, lb_hot_gained[env->idle]);
schedstat_inc(p, se.statistics.nr_forced_migrations);
}
#endif
return 1;
}
if (tsk_cache_hot) {
schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
return 0;
}
return 1;
}
/*
* move_one_task tries to move exactly one task from busiest to this_rq, as
* part of active balancing operations within "domain".
* Returns 1 if successful and 0 otherwise.
*
* Called with both runqueues locked.
*/
static int move_one_task(struct lb_env *env)
{
struct task_struct *p, *n;
list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
if (throttled_lb_pair(task_group(p), env->src_rq->cpu, env->dst_cpu))
continue;
if (!can_migrate_task(p, env))
continue;
move_task(p, env);
/*
* Right now, this is only the second place move_task()
* is called, so we can safely collect move_task()
* stats here rather than inside move_task().
*/
schedstat_inc(env->sd, lb_gained[env->idle]);
return 1;
}
return 0;
}
static unsigned long task_h_load(struct task_struct *p);
static const unsigned int sched_nr_migrate_break = 32;
/*
* move_tasks tries to move up to load_move weighted load from busiest to
* this_rq, as part of a balancing operation within domain "sd".
* Returns 1 if successful and 0 otherwise.
*
* Called with both runqueues locked.
*/
static int move_tasks(struct lb_env *env)
{
struct list_head *tasks = &env->src_rq->cfs_tasks;
struct task_struct *p;
unsigned long load;
int pulled = 0;
if (env->load_move <= 0)
return 0;
while (!list_empty(tasks)) {
p = list_first_entry(tasks, struct task_struct, se.group_node);
env->loop++;
/* We've more or less seen every task there is, call it quits */
if (env->loop > env->loop_max)
break;
/* take a breather every nr_migrate tasks */
if (env->loop > env->loop_break) {
env->loop_break += sched_nr_migrate_break;
env->flags |= LBF_NEED_BREAK;
break;
}
if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
goto next;
load = task_h_load(p);
if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
goto next;
if ((load / 2) > env->load_move)
goto next;
if (!can_migrate_task(p, env))
goto next;
move_task(p, env);
pulled++;
env->load_move -= load;
#ifdef CONFIG_PREEMPT
/*
* NEWIDLE balancing is a source of latency, so preemptible
* kernels will stop after the first task is pulled to minimize
* the critical section.
*/
if (env->idle == CPU_NEWLY_IDLE)
break;
#endif
/*
* We only want to steal up to the prescribed amount of
* weighted load.
*/
if (env->load_move <= 0)
break;
continue;
next:
list_move_tail(&p->se.group_node, tasks);
}
/*
* Right now, this is one of only two places move_task() is called,
* so we can safely collect move_task() stats here rather than
* inside move_task().
*/
schedstat_add(env->sd, lb_gained[env->idle], pulled);
return pulled;
}
#ifdef CONFIG_FAIR_GROUP_SCHED
/*
* update tg->load_weight by folding this cpu's load_avg
*/
static int update_shares_cpu(struct task_group *tg, int cpu)
{
struct cfs_rq *cfs_rq;
unsigned long flags;
struct rq *rq;
if (!tg->se[cpu])
return 0;
rq = cpu_rq(cpu);
cfs_rq = tg->cfs_rq[cpu];
raw_spin_lock_irqsave(&rq->lock, flags);
update_rq_clock(rq);
update_cfs_load(cfs_rq, 1);
/*
* We need to update shares after updating tg->load_weight in
* order to adjust the weight of groups with long running tasks.
*/
update_cfs_shares(cfs_rq);
raw_spin_unlock_irqrestore(&rq->lock, flags);
return 0;
}
static void update_shares(int cpu)
{
struct cfs_rq *cfs_rq;
struct rq *rq = cpu_rq(cpu);
rcu_read_lock();
/*
* Iterates the task_group tree in a bottom up fashion, see
* list_add_leaf_cfs_rq() for details.
*/
for_each_leaf_cfs_rq(rq, cfs_rq) {
/* throttled entities do not contribute to load */
if (throttled_hierarchy(cfs_rq))
continue;
update_shares_cpu(cfs_rq->tg, cpu);
}
rcu_read_unlock();
}
/*
* Compute the cpu's hierarchical load factor for each task group.
* This needs to be done in a top-down fashion because the load of a child
* group is a fraction of its parents load.
*/
static int tg_load_down(struct task_group *tg, void *data)
{
unsigned long load;
long cpu = (long)data;
if (!tg->parent) {
load = cpu_rq(cpu)->load.weight;
} else {
load = tg->parent->cfs_rq[cpu]->h_load;
load *= tg->se[cpu]->load.weight;
load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
}
tg->cfs_rq[cpu]->h_load = load;
return 0;
}
static void update_h_load(long cpu)
{
rcu_read_lock();
walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
rcu_read_unlock();
}
static unsigned long task_h_load(struct task_struct *p)
{
struct cfs_rq *cfs_rq = task_cfs_rq(p);
unsigned long load;
load = p->se.load.weight;
load = div_u64(load * cfs_rq->h_load, cfs_rq->load.weight + 1);
return load;
}
#else
static inline void update_shares(int cpu)
{
}
static inline void update_h_load(long cpu)
{
}
static unsigned long task_h_load(struct task_struct *p)
{
return p->se.load.weight;
}
#endif
/********** Helpers for find_busiest_group ************************/
/*
* sd_lb_stats - Structure to store the statistics of a sched_domain
* during load balancing.
*/
struct sd_lb_stats {
struct sched_group *busiest; /* Busiest group in this sd */
struct sched_group *this; /* Local group in this sd */
unsigned long total_load; /* Total load of all groups in sd */
unsigned long total_pwr; /* Total power of all groups in sd */
unsigned long avg_load; /* Average load across all groups in sd */
/** Statistics of this group */
unsigned long this_load;
unsigned long this_load_per_task;
unsigned long this_nr_running;
unsigned long this_has_capacity;
unsigned int this_idle_cpus;
/* Statistics of the busiest group */
unsigned int busiest_idle_cpus;
unsigned long max_load;
unsigned long busiest_load_per_task;
unsigned long busiest_nr_running;
unsigned long busiest_group_capacity;
unsigned long busiest_has_capacity;
unsigned int busiest_group_weight;
int group_imb; /* Is there imbalance in this sd */
#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
int power_savings_balance; /* Is powersave balance needed for this sd */
struct sched_group *group_min; /* Least loaded group in sd */
struct sched_group *group_leader; /* Group which relieves group_min */
unsigned long min_load_per_task; /* load_per_task in group_min */
unsigned long leader_nr_running; /* Nr running of group_leader */
unsigned long min_nr_running; /* Nr running of group_min */
#endif
};
/*
* sg_lb_stats - stats of a sched_group required for load_balancing
*/
struct sg_lb_stats {
unsigned long avg_load; /*Avg load across the CPUs of the group */
unsigned long group_load; /* Total load over the CPUs of the group */
unsigned long sum_nr_running; /* Nr tasks running in the group */
unsigned long sum_weighted_load; /* Weighted load of group's tasks */
unsigned long group_capacity;
unsigned long idle_cpus;
unsigned long group_weight;
int group_imb; /* Is there an imbalance in the group ? */
int group_has_capacity; /* Is there extra capacity in the group? */
};
/**
* get_sd_load_idx - Obtain the load index for a given sched domain.
* @sd: The sched_domain whose load_idx is to be obtained.
* @idle: The Idle status of the CPU for whose sd load_icx is obtained.
*/
static inline int get_sd_load_idx(struct sched_domain *sd,
enum cpu_idle_type idle)
{
int load_idx;
switch (idle) {
case CPU_NOT_IDLE:
load_idx = sd->busy_idx;
break;
case CPU_NEWLY_IDLE:
load_idx = sd->newidle_idx;
break;
default:
load_idx = sd->idle_idx;
break;
}
return load_idx;
}
#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
/**
* init_sd_power_savings_stats - Initialize power savings statistics for
* the given sched_domain, during load balancing.
*
* @sd: Sched domain whose power-savings statistics are to be initialized.
* @sds: Variable containing the statistics for sd.
* @idle: Idle status of the CPU at which we're performing load-balancing.
*/
static inline void init_sd_power_savings_stats(struct sched_domain *sd,
struct sd_lb_stats *sds, enum cpu_idle_type idle)
{
/*
* Busy processors will not participate in power savings
* balance.
*/
if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
sds->power_savings_balance = 0;
else {
sds->power_savings_balance = 1;
sds->min_nr_running = ULONG_MAX;
sds->leader_nr_running = 0;
}
}
/**
* update_sd_power_savings_stats - Update the power saving stats for a
* sched_domain while performing load balancing.
*
* @group: sched_group belonging to the sched_domain under consideration.
* @sds: Variable containing the statistics of the sched_domain
* @local_group: Does group contain the CPU for which we're performing
* load balancing ?
* @sgs: Variable containing the statistics of the group.
*/
static inline void update_sd_power_savings_stats(struct sched_group *group,
struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
{
if (!sds->power_savings_balance)
return;
/*
* If the local group is idle or completely loaded
* no need to do power savings balance at this domain
*/
if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
!sds->this_nr_running))
sds->power_savings_balance = 0;
/*
* If a group is already running at full capacity or idle,
* don't include that group in power savings calculations
*/
if (!sds->power_savings_balance ||
sgs->sum_nr_running >= sgs->group_capacity ||
!sgs->sum_nr_running)
return;
/*
* Calculate the group which has the least non-idle load.
* This is the group from where we need to pick up the load
* for saving power
*/
if ((sgs->sum_nr_running < sds->min_nr_running) ||
(sgs->sum_nr_running == sds->min_nr_running &&
group_first_cpu(group) > group_first_cpu(sds->group_min))) {
sds->group_min = group;
sds->min_nr_running = sgs->sum_nr_running;
sds->min_load_per_task = sgs->sum_weighted_load /
sgs->sum_nr_running;
}
/*
* Calculate the group which is almost near its
* capacity but still has some space to pick up some load
* from other group and save more power
*/
if (sgs->sum_nr_running + 1 > sgs->group_capacity)
return;
if (sgs->sum_nr_running > sds->leader_nr_running ||
(sgs->sum_nr_running == sds->leader_nr_running &&
group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
sds->group_leader = group;
sds->leader_nr_running = sgs->sum_nr_running;
}
}
/**
* check_power_save_busiest_group - see if there is potential for some power-savings balance
* @sds: Variable containing the statistics of the sched_domain
* under consideration.
* @this_cpu: Cpu at which we're currently performing load-balancing.
* @imbalance: Variable to store the imbalance.
*
* Description:
* Check if we have potential to perform some power-savings balance.
* If yes, set the busiest group to be the least loaded group in the
* sched_domain, so that it's CPUs can be put to idle.
*
* Returns 1 if there is potential to perform power-savings balance.
* Else returns 0.
*/
static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
int this_cpu, unsigned long *imbalance)
{
if (!sds->power_savings_balance)
return 0;
if (sds->this != sds->group_leader ||
sds->group_leader == sds->group_min)
return 0;
*imbalance = sds->min_load_per_task;
sds->busiest = sds->group_min;
return 1;
}
#else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
static inline void init_sd_power_savings_stats(struct sched_domain *sd,
struct sd_lb_stats *sds, enum cpu_idle_type idle)
{
return;
}
static inline void update_sd_power_savings_stats(struct sched_group *group,
struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
{
return;
}
static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
int this_cpu, unsigned long *imbalance)
{
return 0;
}
#endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
{
return SCHED_POWER_SCALE;
}
unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
{
return default_scale_freq_power(sd, cpu);
}
unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
{
unsigned long weight = sd->span_weight;
unsigned long smt_gain = sd->smt_gain;
smt_gain /= weight;
return smt_gain;
}
unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
{
return default_scale_smt_power(sd, cpu);
}
unsigned long scale_rt_power(int cpu)
{
struct rq *rq = cpu_rq(cpu);
u64 total, available;
total = sched_avg_period() + (rq->clock - rq->age_stamp);
if (unlikely(total < rq->rt_avg)) {
/* Ensures that power won't end up being negative */
available = 0;
} else {
available = total - rq->rt_avg;
}
if (unlikely((s64)total < SCHED_POWER_SCALE))
total = SCHED_POWER_SCALE;
total >>= SCHED_POWER_SHIFT;
return div_u64(available, total);
}
static void update_cpu_power(struct sched_domain *sd, int cpu)
{
unsigned long weight = sd->span_weight;
unsigned long power = SCHED_POWER_SCALE;
struct sched_group *sdg = sd->groups;
if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
if (sched_feat(ARCH_POWER))
power *= arch_scale_smt_power(sd, cpu);
else
power *= default_scale_smt_power(sd, cpu);
power >>= SCHED_POWER_SHIFT;
}
sdg->sgp->power_orig = power;
if (sched_feat(ARCH_POWER))
power *= arch_scale_freq_power(sd, cpu);
else
power *= default_scale_freq_power(sd, cpu);
power >>= SCHED_POWER_SHIFT;
power *= scale_rt_power(cpu);
power >>= SCHED_POWER_SHIFT;
if (!power)
power = 1;
cpu_rq(cpu)->cpu_power = power;
sdg->sgp->power = power;
}
void update_group_power(struct sched_domain *sd, int cpu)
{
struct sched_domain *child = sd->child;
struct sched_group *group, *sdg = sd->groups;
unsigned long power;
unsigned long interval;
interval = msecs_to_jiffies(sd->balance_interval);
interval = clamp(interval, 1UL, max_load_balance_interval);
sdg->sgp->next_update = jiffies + interval;
if (!child) {
update_cpu_power(sd, cpu);
return;
}
power = 0;
group = child->groups;
do {
power += group->sgp->power;
group = group->next;
} while (group != child->groups);
sdg->sgp->power = power;
}
/*
* Try and fix up capacity for tiny siblings, this is needed when
* things like SD_ASYM_PACKING need f_b_g to select another sibling
* which on its own isn't powerful enough.
*
* See update_sd_pick_busiest() and check_asym_packing().
*/
static inline int
fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
{
/*
* Only siblings can have significantly less than SCHED_POWER_SCALE
*/
if (!(sd->flags & SD_SHARE_CPUPOWER))
return 0;
/*
* If ~90% of the cpu_power is still there, we're good.
*/
if (group->sgp->power * 32 > group->sgp->power_orig * 29)
return 1;
return 0;
}
/**
* update_sg_lb_stats - Update sched_group's statistics for load balancing.
* @sd: The sched_domain whose statistics are to be updated.
* @group: sched_group whose statistics are to be updated.
* @this_cpu: Cpu for which load balance is currently performed.
* @idle: Idle status of this_cpu
* @load_idx: Load index of sched_domain of this_cpu for load calc.
* @local_group: Does group contain this_cpu.
* @cpus: Set of cpus considered for load balancing.
* @balance: Should we balance.
* @sgs: variable to hold the statistics for this group.
*/
static inline void update_sg_lb_stats(struct sched_domain *sd,
struct sched_group *group, int this_cpu,
enum cpu_idle_type idle, int load_idx,
int local_group, const struct cpumask *cpus,
int *balance, struct sg_lb_stats *sgs)
{
unsigned long load, max_cpu_load, min_cpu_load, max_nr_running;
int i;
unsigned int balance_cpu = -1, first_idle_cpu = 0;
unsigned long avg_load_per_task = 0;
if (local_group)
balance_cpu = group_first_cpu(group);
/* Tally up the load of all CPUs in the group */
max_cpu_load = 0;
min_cpu_load = ~0UL;
max_nr_running = 0;
for_each_cpu_and(i, sched_group_cpus(group), cpus) {
struct rq *rq = cpu_rq(i);
/* Bias balancing toward cpus of our domain */
if (local_group) {
if (idle_cpu(i) && !first_idle_cpu) {
first_idle_cpu = 1;
balance_cpu = i;
}
load = target_load(i, load_idx);
} else {
load = source_load(i, load_idx);
if (load > max_cpu_load) {
max_cpu_load = load;
max_nr_running = rq->nr_running;
}
if (min_cpu_load > load)
min_cpu_load = load;
}
sgs->group_load += load;
sgs->sum_nr_running += rq->nr_running;
sgs->sum_weighted_load += weighted_cpuload(i);
if (idle_cpu(i))
sgs->idle_cpus++;
}
/*
* First idle cpu or the first cpu(busiest) in this sched group
* is eligible for doing load balancing at this and above
* domains. In the newly idle case, we will allow all the cpu's
* to do the newly idle load balance.
*/
if (local_group) {
if (idle != CPU_NEWLY_IDLE) {
if (balance_cpu != this_cpu) {
*balance = 0;
return;
}
update_group_power(sd, this_cpu);
} else if (time_after_eq(jiffies, group->sgp->next_update))
update_group_power(sd, this_cpu);
}
/* Adjust by relative CPU power of the group */
sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
/*
* Consider the group unbalanced when the imbalance is larger
* than the average weight of a task.
*
* APZ: with cgroup the avg task weight can vary wildly and
* might not be a suitable number - should we keep a
* normalized nr_running number somewhere that negates
* the hierarchy?
*/
if (sgs->sum_nr_running)
avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
if ((max_cpu_load - min_cpu_load) >= avg_load_per_task && max_nr_running > 1)
sgs->group_imb = 1;
sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
SCHED_POWER_SCALE);
if (!sgs->group_capacity)
sgs->group_capacity = fix_small_capacity(sd, group);
sgs->group_weight = group->group_weight;
if (sgs->group_capacity > sgs->sum_nr_running)
sgs->group_has_capacity = 1;
}
/**
* update_sd_pick_busiest - return 1 on busiest group
* @sd: sched_domain whose statistics are to be checked
* @sds: sched_domain statistics
* @sg: sched_group candidate to be checked for being the busiest
* @sgs: sched_group statistics
* @this_cpu: the current cpu
*
* Determine if @sg is a busier group than the previously selected
* busiest group.
*/
static bool update_sd_pick_busiest(struct sched_domain *sd,
struct sd_lb_stats *sds,
struct sched_group *sg,
struct sg_lb_stats *sgs,
int this_cpu)
{
if (sgs->avg_load <= sds->max_load)
return false;
if (sgs->sum_nr_running > sgs->group_capacity)
return true;
if (sgs->group_imb)
return true;
/*
* ASYM_PACKING needs to move all the work to the lowest
* numbered CPUs in the group, therefore mark all groups
* higher than ourself as busy.
*/
if ((sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
this_cpu < group_first_cpu(sg)) {
if (!sds->busiest)
return true;
if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
return true;
}
return false;
}
/**
* update_sd_lb_stats - Update sched_domain's statistics for load balancing.
* @sd: sched_domain whose statistics are to be updated.
* @this_cpu: Cpu for which load balance is currently performed.
* @idle: Idle status of this_cpu
* @cpus: Set of cpus considered for load balancing.
* @balance: Should we balance.
* @sds: variable to hold the statistics for this sched_domain.
*/
static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
enum cpu_idle_type idle, const struct cpumask *cpus,
int *balance, struct sd_lb_stats *sds)
{
struct sched_domain *child = sd->child;
struct sched_group *sg = sd->groups;
struct sg_lb_stats sgs;
int load_idx, prefer_sibling = 0;
if (child && child->flags & SD_PREFER_SIBLING)
prefer_sibling = 1;
init_sd_power_savings_stats(sd, sds, idle);
load_idx = get_sd_load_idx(sd, idle);
do {
int local_group;
local_group = cpumask_test_cpu(this_cpu, sched_group_cpus(sg));
memset(&sgs, 0, sizeof(sgs));
update_sg_lb_stats(sd, sg, this_cpu, idle, load_idx,
local_group, cpus, balance, &sgs);
if (local_group && !(*balance))
return;
sds->total_load += sgs.group_load;
sds->total_pwr += sg->sgp->power;
/*
* In case the child domain prefers tasks go to siblings
* first, lower the sg capacity to one so that we'll try
* and move all the excess tasks away. We lower the capacity
* of a group only if the local group has the capacity to fit
* these excess tasks, i.e. nr_running < group_capacity. The
* extra check prevents the case where you always pull from the
* heaviest group when it is already under-utilized (possible
* with a large weight task outweighs the tasks on the system).
*/
if (prefer_sibling && !local_group && sds->this_has_capacity)
sgs.group_capacity = min(sgs.group_capacity, 1UL);
if (local_group) {
sds->this_load = sgs.avg_load;
sds->this = sg;
sds->this_nr_running = sgs.sum_nr_running;
sds->this_load_per_task = sgs.sum_weighted_load;
sds->this_has_capacity = sgs.group_has_capacity;
sds->this_idle_cpus = sgs.idle_cpus;
} else if (update_sd_pick_busiest(sd, sds, sg, &sgs, this_cpu)) {
sds->max_load = sgs.avg_load;
sds->busiest = sg;
sds->busiest_nr_running = sgs.sum_nr_running;
sds->busiest_idle_cpus = sgs.idle_cpus;
sds->busiest_group_capacity = sgs.group_capacity;
sds->busiest_load_per_task = sgs.sum_weighted_load;
sds->busiest_has_capacity = sgs.group_has_capacity;
sds->busiest_group_weight = sgs.group_weight;
sds->group_imb = sgs.group_imb;
}
update_sd_power_savings_stats(sg, sds, local_group, &sgs);
sg = sg->next;
} while (sg != sd->groups);
}
/**
* check_asym_packing - Check to see if the group is packed into the
* sched doman.
*
* This is primarily intended to used at the sibling level. Some
* cores like POWER7 prefer to use lower numbered SMT threads. In the
* case of POWER7, it can move to lower SMT modes only when higher
* threads are idle. When in lower SMT modes, the threads will
* perform better since they share less core resources. Hence when we
* have idle threads, we want them to be the higher ones.
*
* This packing function is run on idle threads. It checks to see if
* the busiest CPU in this domain (core in the P7 case) has a higher
* CPU number than the packing function is being run on. Here we are
* assuming lower CPU number will be equivalent to lower a SMT thread
* number.
*
* Returns 1 when packing is required and a task should be moved to
* this CPU. The amount of the imbalance is returned in *imbalance.
*
* @sd: The sched_domain whose packing is to be checked.
* @sds: Statistics of the sched_domain which is to be packed
* @this_cpu: The cpu at whose sched_domain we're performing load-balance.
* @imbalance: returns amount of imbalanced due to packing.
*/
static int check_asym_packing(struct sched_domain *sd,
struct sd_lb_stats *sds,
int this_cpu, unsigned long *imbalance)
{
int busiest_cpu;
if (!(sd->flags & SD_ASYM_PACKING))
return 0;
if (!sds->busiest)
return 0;
busiest_cpu = group_first_cpu(sds->busiest);
if (this_cpu > busiest_cpu)
return 0;
*imbalance = DIV_ROUND_CLOSEST(sds->max_load * sds->busiest->sgp->power,
SCHED_POWER_SCALE);
return 1;
}
/**
* fix_small_imbalance - Calculate the minor imbalance that exists
* amongst the groups of a sched_domain, during
* load balancing.
* @sds: Statistics of the sched_domain whose imbalance is to be calculated.
* @this_cpu: The cpu at whose sched_domain we're performing load-balance.
* @imbalance: Variable to store the imbalance.
*/
static inline void fix_small_imbalance(struct sd_lb_stats *sds,
int this_cpu, unsigned long *imbalance)
{
unsigned long tmp, pwr_now = 0, pwr_move = 0;
unsigned int imbn = 2;
unsigned long scaled_busy_load_per_task;
if (sds->this_nr_running) {
sds->this_load_per_task /= sds->this_nr_running;
if (sds->busiest_load_per_task >
sds->this_load_per_task)
imbn = 1;
} else
sds->this_load_per_task =
cpu_avg_load_per_task(this_cpu);
scaled_busy_load_per_task = sds->busiest_load_per_task
* SCHED_POWER_SCALE;
scaled_busy_load_per_task /= sds->busiest->sgp->power;
if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
(scaled_busy_load_per_task * imbn)) {
*imbalance = sds->busiest_load_per_task;
return;
}
/*
* OK, we don't have enough imbalance to justify moving tasks,
* however we may be able to increase total CPU power used by
* moving them.
*/
pwr_now += sds->busiest->sgp->power *
min(sds->busiest_load_per_task, sds->max_load);
pwr_now += sds->this->sgp->power *
min(sds->this_load_per_task, sds->this_load);
pwr_now /= SCHED_POWER_SCALE;
/* Amount of load we'd subtract */
tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
sds->busiest->sgp->power;
if (sds->max_load > tmp)
pwr_move += sds->busiest->sgp->power *
min(sds->busiest_load_per_task, sds->max_load - tmp);
/* Amount of load we'd add */
if (sds->max_load * sds->busiest->sgp->power <
sds->busiest_load_per_task * SCHED_POWER_SCALE)
tmp = (sds->max_load * sds->busiest->sgp->power) /
sds->this->sgp->power;
else
tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
sds->this->sgp->power;
pwr_move += sds->this->sgp->power *
min(sds->this_load_per_task, sds->this_load + tmp);
pwr_move /= SCHED_POWER_SCALE;
/* Move if we gain throughput */
if (pwr_move > pwr_now)
*imbalance = sds->busiest_load_per_task;
}
/**
* calculate_imbalance - Calculate the amount of imbalance present within the
* groups of a given sched_domain during load balance.
* @sds: statistics of the sched_domain whose imbalance is to be calculated.
* @this_cpu: Cpu for which currently load balance is being performed.
* @imbalance: The variable to store the imbalance.
*/
static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
unsigned long *imbalance)
{
unsigned long max_pull, load_above_capacity = ~0UL;
sds->busiest_load_per_task /= sds->busiest_nr_running;
if (sds->group_imb) {
sds->busiest_load_per_task =
min(sds->busiest_load_per_task, sds->avg_load);
}
/*
* In the presence of smp nice balancing, certain scenarios can have
* max load less than avg load(as we skip the groups at or below
* its cpu_power, while calculating max_load..)
*/
if (sds->max_load < sds->avg_load) {
*imbalance = 0;
return fix_small_imbalance(sds, this_cpu, imbalance);
}
if (!sds->group_imb) {
/*
* Don't want to pull so many tasks that a group would go idle.
*/
load_above_capacity = (sds->busiest_nr_running -
sds->busiest_group_capacity);
load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
load_above_capacity /= sds->busiest->sgp->power;
}
/*
* We're trying to get all the cpus to the average_load, so we don't
* want to push ourselves above the average load, nor do we wish to
* reduce the max loaded cpu below the average load. At the same time,
* we also don't want to reduce the group load below the group capacity
* (so that we can implement power-savings policies etc). Thus we look
* for the minimum possible imbalance.
* Be careful of negative numbers as they'll appear as very large values
* with unsigned longs.
*/
max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
/* How much load to actually move to equalise the imbalance */
*imbalance = min(max_pull * sds->busiest->sgp->power,
(sds->avg_load - sds->this_load) * sds->this->sgp->power)
/ SCHED_POWER_SCALE;
/*
* if *imbalance is less than the average load per runnable task
* there is no guarantee that any tasks will be moved so we'll have
* a think about bumping its value to force at least one task to be
* moved
*/
if (*imbalance < sds->busiest_load_per_task)
return fix_small_imbalance(sds, this_cpu, imbalance);
}
/******* find_busiest_group() helpers end here *********************/
/**
* find_busiest_group - Returns the busiest group within the sched_domain
* if there is an imbalance. If there isn't an imbalance, and
* the user has opted for power-savings, it returns a group whose
* CPUs can be put to idle by rebalancing those tasks elsewhere, if
* such a group exists.
*
* Also calculates the amount of weighted load which should be moved
* to restore balance.
*
* @sd: The sched_domain whose busiest group is to be returned.
* @this_cpu: The cpu for which load balancing is currently being performed.
* @imbalance: Variable which stores amount of weighted load which should
* be moved to restore balance/put a group to idle.
* @idle: The idle status of this_cpu.
* @cpus: The set of CPUs under consideration for load-balancing.
* @balance: Pointer to a variable indicating if this_cpu
* is the appropriate cpu to perform load balancing at this_level.
*
* Returns: - the busiest group if imbalance exists.
* - If no imbalance and user has opted for power-savings balance,
* return the least loaded group whose CPUs can be
* put to idle by rebalancing its tasks onto our group.
*/
static struct sched_group *
find_busiest_group(struct sched_domain *sd, int this_cpu,
unsigned long *imbalance, enum cpu_idle_type idle,
const struct cpumask *cpus, int *balance)
{
struct sd_lb_stats sds;
memset(&sds, 0, sizeof(sds));
/*
* Compute the various statistics relavent for load balancing at
* this level.
*/
update_sd_lb_stats(sd, this_cpu, idle, cpus, balance, &sds);
/*
* this_cpu is not the appropriate cpu to perform load balancing at
* this level.
*/
if (!(*balance))
goto ret;
if ((idle == CPU_IDLE || idle == CPU_NEWLY_IDLE) &&
check_asym_packing(sd, &sds, this_cpu, imbalance))
return sds.busiest;
/* There is no busy sibling group to pull tasks from */
if (!sds.busiest || sds.busiest_nr_running == 0)
goto out_balanced;
sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
/*
* If the busiest group is imbalanced the below checks don't
* work because they assumes all things are equal, which typically
* isn't true due to cpus_allowed constraints and the like.
*/
if (sds.group_imb)
goto force_balance;
/* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
if (idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
!sds.busiest_has_capacity)
goto force_balance;
/*
* If the local group is more busy than the selected busiest group
* don't try and pull any tasks.
*/
if (sds.this_load >= sds.max_load)
goto out_balanced;
/*
* Don't pull any tasks if this group is already above the domain
* average load.
*/
if (sds.this_load >= sds.avg_load)
goto out_balanced;
if (idle == CPU_IDLE) {
/*
* This cpu is idle. If the busiest group load doesn't
* have more tasks than the number of available cpu's and
* there is no imbalance between this and busiest group
* wrt to idle cpu's, it is balanced.
*/
if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
sds.busiest_nr_running <= sds.busiest_group_weight)
goto out_balanced;
} else {
/*
* In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
* imbalance_pct to be conservative.
*/
if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
goto out_balanced;
}
force_balance:
/* Looks like there is an imbalance. Compute it */
calculate_imbalance(&sds, this_cpu, imbalance);
return sds.busiest;
out_balanced:
/*
* There is no obvious imbalance. But check if we can do some balancing
* to save power.
*/
if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
return sds.busiest;
ret:
*imbalance = 0;
return NULL;
}
/*
* find_busiest_queue - find the busiest runqueue among the cpus in group.
*/
static struct rq *
find_busiest_queue(struct sched_domain *sd, struct sched_group *group,
enum cpu_idle_type idle, unsigned long imbalance,
const struct cpumask *cpus)
{
struct rq *busiest = NULL, *rq;
unsigned long max_load = 0;
int i;
for_each_cpu(i, sched_group_cpus(group)) {
unsigned long power = power_of(i);
unsigned long capacity = DIV_ROUND_CLOSEST(power,
SCHED_POWER_SCALE);
unsigned long wl;
if (!capacity)
capacity = fix_small_capacity(sd, group);
if (!cpumask_test_cpu(i, cpus))
continue;
rq = cpu_rq(i);
wl = weighted_cpuload(i);
/*
* When comparing with imbalance, use weighted_cpuload()
* which is not scaled with the cpu power.
*/
if (capacity && rq->nr_running == 1 && wl > imbalance)
continue;
/*
* For the load comparisons with the other cpu's, consider
* the weighted_cpuload() scaled with the cpu power, so that
* the load can be moved away from the cpu that is potentially
* running at a lower capacity.
*/
wl = (wl * SCHED_POWER_SCALE) / power;
if (wl > max_load) {
max_load = wl;
busiest = rq;
}
}
return busiest;
}
/*
* Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
* so long as it is large enough.
*/
#define MAX_PINNED_INTERVAL 512
/* Working cpumask for load_balance and load_balance_newidle. */
DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
static int need_active_balance(struct sched_domain *sd, int idle,
int busiest_cpu, int this_cpu)
{
if (idle == CPU_NEWLY_IDLE) {
/*
* ASYM_PACKING needs to force migrate tasks from busy but
* higher numbered CPUs in order to pack all tasks in the
* lowest numbered CPUs.
*/
if ((sd->flags & SD_ASYM_PACKING) && busiest_cpu > this_cpu)
return 1;
/*
* The only task running in a non-idle cpu can be moved to this
* cpu in an attempt to completely freeup the other CPU
* package.
*
* The package power saving logic comes from
* find_busiest_group(). If there are no imbalance, then
* f_b_g() will return NULL. However when sched_mc={1,2} then
* f_b_g() will select a group from which a running task may be
* pulled to this cpu in order to make the other package idle.
* If there is no opportunity to make a package idle and if
* there are no imbalance, then f_b_g() will return NULL and no
* action will be taken in load_balance_newidle().
*
* Under normal task pull operation due to imbalance, there
* will be more than one task in the source run queue and
* move_tasks() will succeed. ld_moved will be true and this
* active balance code will not be triggered.
*/
if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
return 0;
}
return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
}
static int active_load_balance_cpu_stop(void *data);
/*
* Check this_cpu to ensure it is balanced within domain. Attempt to move
* tasks if there is an imbalance.
*/
static int load_balance(int this_cpu, struct rq *this_rq,
struct sched_domain *sd, enum cpu_idle_type idle,
int *balance)
{
int ld_moved, active_balance = 0;
struct sched_group *group;
unsigned long imbalance;
struct rq *busiest;
unsigned long flags;
struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
struct lb_env env = {
.sd = sd,
.dst_cpu = this_cpu,
.dst_rq = this_rq,
.idle = idle,
.loop_break = sched_nr_migrate_break,
};
cpumask_copy(cpus, cpu_active_mask);
schedstat_inc(sd, lb_count[idle]);
redo:
group = find_busiest_group(sd, this_cpu, &imbalance, idle,
cpus, balance);
if (*balance == 0)
goto out_balanced;
if (!group) {
schedstat_inc(sd, lb_nobusyg[idle]);
goto out_balanced;
}
busiest = find_busiest_queue(sd, group, idle, imbalance, cpus);
if (!busiest) {
schedstat_inc(sd, lb_nobusyq[idle]);
goto out_balanced;
}
BUG_ON(busiest == this_rq);
schedstat_add(sd, lb_imbalance[idle], imbalance);
ld_moved = 0;
if (busiest->nr_running > 1) {
/*
* Attempt to move tasks. If find_busiest_group has found
* an imbalance but busiest->nr_running <= 1, the group is
* still unbalanced. ld_moved simply stays zero, so it is
* correctly treated as an imbalance.
*/
env.flags |= LBF_ALL_PINNED;
env.load_move = imbalance;
env.src_cpu = busiest->cpu;
env.src_rq = busiest;
env.loop_max = min_t(unsigned long, sysctl_sched_nr_migrate, busiest->nr_running);
more_balance:
local_irq_save(flags);
double_rq_lock(this_rq, busiest);
if (!env.loop)
update_h_load(env.src_cpu);
ld_moved += move_tasks(&env);
double_rq_unlock(this_rq, busiest);
local_irq_restore(flags);
if (env.flags & LBF_NEED_BREAK) {
env.flags &= ~LBF_NEED_BREAK;
goto more_balance;
}
/*
* some other cpu did the load balance for us.
*/
if (ld_moved && this_cpu != smp_processor_id())
resched_cpu(this_cpu);
/* All tasks on this runqueue were pinned by CPU affinity */
if (unlikely(env.flags & LBF_ALL_PINNED)) {
cpumask_clear_cpu(cpu_of(busiest), cpus);
if (!cpumask_empty(cpus))
goto redo;
goto out_balanced;
}
}
if (!ld_moved) {
schedstat_inc(sd, lb_failed[idle]);
/*
* Increment the failure counter only on periodic balance.
* We do not want newidle balance, which can be very
* frequent, pollute the failure counter causing
* excessive cache_hot migrations and active balances.
*/
if (idle != CPU_NEWLY_IDLE)
sd->nr_balance_failed++;
if (need_active_balance(sd, idle, cpu_of(busiest), this_cpu)) {
raw_spin_lock_irqsave(&busiest->lock, flags);
/* don't kick the active_load_balance_cpu_stop,
* if the curr task on busiest cpu can't be
* moved to this_cpu
*/
if (!cpumask_test_cpu(this_cpu,
tsk_cpus_allowed(busiest->curr))) {
raw_spin_unlock_irqrestore(&busiest->lock,
flags);
env.flags |= LBF_ALL_PINNED;
goto out_one_pinned;
}
/*
* ->active_balance synchronizes accesses to
* ->active_balance_work. Once set, it's cleared
* only after active load balance is finished.
*/
if (!busiest->active_balance) {
busiest->active_balance = 1;
busiest->push_cpu = this_cpu;
active_balance = 1;
}
raw_spin_unlock_irqrestore(&busiest->lock, flags);
if (active_balance)
stop_one_cpu_nowait(cpu_of(busiest),
active_load_balance_cpu_stop, busiest,
&busiest->active_balance_work);
/*
* We've kicked active balancing, reset the failure
* counter.
*/
sd->nr_balance_failed = sd->cache_nice_tries+1;
}
} else
sd->nr_balance_failed = 0;
if (likely(!active_balance)) {
/* We were unbalanced, so reset the balancing interval */
sd->balance_interval = sd->min_interval;
} else {
/*
* If we've begun active balancing, start to back off. This
* case may not be covered by the all_pinned logic if there
* is only 1 task on the busy runqueue (because we don't call
* move_tasks).
*/
if (sd->balance_interval < sd->max_interval)
sd->balance_interval *= 2;
}
goto out;
out_balanced:
schedstat_inc(sd, lb_balanced[idle]);
sd->nr_balance_failed = 0;
out_one_pinned:
/* tune up the balancing interval */
if (((env.flags & LBF_ALL_PINNED) &&
sd->balance_interval < MAX_PINNED_INTERVAL) ||
(sd->balance_interval < sd->max_interval))
sd->balance_interval *= 2;
ld_moved = 0;
out:
return ld_moved;
}
/*
* idle_balance is called by schedule() if this_cpu is about to become
* idle. Attempts to pull tasks from other CPUs.
*/
void idle_balance(int this_cpu, struct rq *this_rq)
{
struct sched_domain *sd;
int pulled_task = 0;
unsigned long next_balance = jiffies + HZ;
this_rq->idle_stamp = this_rq->clock;
if (this_rq->avg_idle < sysctl_sched_migration_cost)
return;
/*
* Drop the rq->lock, but keep IRQ/preempt disabled.
*/
raw_spin_unlock(&this_rq->lock);
update_shares(this_cpu);
rcu_read_lock();
for_each_domain(this_cpu, sd) {
unsigned long interval;
int balance = 1;
if (!(sd->flags & SD_LOAD_BALANCE))
continue;
if (sd->flags & SD_BALANCE_NEWIDLE) {
/* If we've pulled tasks over stop searching: */
pulled_task = load_balance(this_cpu, this_rq,
sd, CPU_NEWLY_IDLE, &balance);
}
interval = msecs_to_jiffies(sd->balance_interval);
if (time_after(next_balance, sd->last_balance + interval))
next_balance = sd->last_balance + interval;
if (pulled_task) {
this_rq->idle_stamp = 0;
break;
}
}
rcu_read_unlock();
raw_spin_lock(&this_rq->lock);
if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
/*
* We are going idle. next_balance may be set based on
* a busy processor. So reset next_balance.
*/
this_rq->next_balance = next_balance;
}
}
/*
* active_load_balance_cpu_stop is run by cpu stopper. It pushes
* running tasks off the busiest CPU onto idle CPUs. It requires at
* least 1 task to be running on each physical CPU where possible, and
* avoids physical / logical imbalances.
*/
static int active_load_balance_cpu_stop(void *data)
{
struct rq *busiest_rq = data;
int busiest_cpu = cpu_of(busiest_rq);
int target_cpu = busiest_rq->push_cpu;
struct rq *target_rq = cpu_rq(target_cpu);
struct sched_domain *sd;
raw_spin_lock_irq(&busiest_rq->lock);
/* make sure the requested cpu hasn't gone down in the meantime */
if (unlikely(busiest_cpu != smp_processor_id() ||
!busiest_rq->active_balance))
goto out_unlock;
/* Is there any task to move? */
if (busiest_rq->nr_running <= 1)
goto out_unlock;
/*
* This condition is "impossible", if it occurs
* we need to fix it. Originally reported by
* Bjorn Helgaas on a 128-cpu setup.
*/
BUG_ON(busiest_rq == target_rq);
/* move a task from busiest_rq to target_rq */
double_lock_balance(busiest_rq, target_rq);
/* Search for an sd spanning us and the target CPU. */
rcu_read_lock();
for_each_domain(target_cpu, sd) {
if ((sd->flags & SD_LOAD_BALANCE) &&
cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
break;
}
if (likely(sd)) {
struct lb_env env = {
.sd = sd,
.dst_cpu = target_cpu,
.dst_rq = target_rq,
.src_cpu = busiest_rq->cpu,
.src_rq = busiest_rq,
.idle = CPU_IDLE,
};
schedstat_inc(sd, alb_count);
if (move_one_task(&env))
schedstat_inc(sd, alb_pushed);
else
schedstat_inc(sd, alb_failed);
}
rcu_read_unlock();
double_unlock_balance(busiest_rq, target_rq);
out_unlock:
busiest_rq->active_balance = 0;
raw_spin_unlock_irq(&busiest_rq->lock);
return 0;
}
#ifdef CONFIG_NO_HZ
/*
* idle load balancing details
* - When one of the busy CPUs notice that there may be an idle rebalancing
* needed, they will kick the idle load balancer, which then does idle
* load balancing for all the idle CPUs.
*/
static struct {
cpumask_var_t idle_cpus_mask;
atomic_t nr_cpus;
unsigned long next_balance; /* in jiffy units */
} nohz ____cacheline_aligned;
#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
/**
* lowest_flag_domain - Return lowest sched_domain containing flag.
* @cpu: The cpu whose lowest level of sched domain is to
* be returned.
* @flag: The flag to check for the lowest sched_domain
* for the given cpu.
*
* Returns the lowest sched_domain of a cpu which contains the given flag.
*/
static inline struct sched_domain *lowest_flag_domain(int cpu, int flag)
{
struct sched_domain *sd;
for_each_domain(cpu, sd)
if (sd->flags & flag)
break;
return sd;
}
/**
* for_each_flag_domain - Iterates over sched_domains containing the flag.
* @cpu: The cpu whose domains we're iterating over.
* @sd: variable holding the value of the power_savings_sd
* for cpu.
* @flag: The flag to filter the sched_domains to be iterated.
*
* Iterates over all the scheduler domains for a given cpu that has the 'flag'
* set, starting from the lowest sched_domain to the highest.
*/
#define for_each_flag_domain(cpu, sd, flag) \
for (sd = lowest_flag_domain(cpu, flag); \
(sd && (sd->flags & flag)); sd = sd->parent)
/**
* find_new_ilb - Finds the optimum idle load balancer for nomination.
* @cpu: The cpu which is nominating a new idle_load_balancer.
*
* Returns: Returns the id of the idle load balancer if it exists,
* Else, returns >= nr_cpu_ids.
*
* This algorithm picks the idle load balancer such that it belongs to a
* semi-idle powersavings sched_domain. The idea is to try and avoid
* completely idle packages/cores just for the purpose of idle load balancing
* when there are other idle cpu's which are better suited for that job.
*/
static int find_new_ilb(int cpu)
{
int ilb = cpumask_first(nohz.idle_cpus_mask);
struct sched_group *ilbg;
struct sched_domain *sd;
/*
* Have idle load balancer selection from semi-idle packages only
* when power-aware load balancing is enabled
*/
if (!(sched_smt_power_savings || sched_mc_power_savings))
goto out_done;
/*
* Optimize for the case when we have no idle CPUs or only one
* idle CPU. Don't walk the sched_domain hierarchy in such cases
*/
if (cpumask_weight(nohz.idle_cpus_mask) < 2)
goto out_done;
rcu_read_lock();
for_each_flag_domain(cpu, sd, SD_POWERSAVINGS_BALANCE) {
ilbg = sd->groups;
do {
if (ilbg->group_weight !=
atomic_read(&ilbg->sgp->nr_busy_cpus)) {
ilb = cpumask_first_and(nohz.idle_cpus_mask,
sched_group_cpus(ilbg));
goto unlock;
}
ilbg = ilbg->next;
} while (ilbg != sd->groups);
}
unlock:
rcu_read_unlock();
out_done:
if (ilb < nr_cpu_ids && idle_cpu(ilb))
return ilb;
return nr_cpu_ids;
}
#else /* (CONFIG_SCHED_MC || CONFIG_SCHED_SMT) */
static inline int find_new_ilb(int call_cpu)
{
return nr_cpu_ids;
}
#endif
/*
* Kick a CPU to do the nohz balancing, if it is time for it. We pick the
* nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
* CPU (if there is one).
*/
static void nohz_balancer_kick(int cpu)
{
int ilb_cpu;
nohz.next_balance++;
ilb_cpu = find_new_ilb(cpu);
if (ilb_cpu >= nr_cpu_ids)
return;
if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
return;
/*
* Use smp_send_reschedule() instead of resched_cpu().
* This way we generate a sched IPI on the target cpu which
* is idle. And the softirq performing nohz idle load balance
* will be run before returning from the IPI.
*/
smp_send_reschedule(ilb_cpu);
return;
}
static inline void clear_nohz_tick_stopped(int cpu)
{
if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
atomic_dec(&nohz.nr_cpus);
clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
}
}
static inline void set_cpu_sd_state_busy(void)
{
struct sched_domain *sd;
int cpu = smp_processor_id();
if (!test_bit(NOHZ_IDLE, nohz_flags(cpu)))
return;
clear_bit(NOHZ_IDLE, nohz_flags(cpu));
rcu_read_lock();
for_each_domain(cpu, sd)
atomic_inc(&sd->groups->sgp->nr_busy_cpus);
rcu_read_unlock();
}
void set_cpu_sd_state_idle(void)
{
struct sched_domain *sd;
int cpu = smp_processor_id();
if (test_bit(NOHZ_IDLE, nohz_flags(cpu)))
return;
set_bit(NOHZ_IDLE, nohz_flags(cpu));
rcu_read_lock();
for_each_domain(cpu, sd)
atomic_dec(&sd->groups->sgp->nr_busy_cpus);
rcu_read_unlock();
}
/*
* This routine will record that this cpu is going idle with tick stopped.
* This info will be used in performing idle load balancing in the future.
*/
void select_nohz_load_balancer(int stop_tick)
{
int cpu = smp_processor_id();
/*
* If this cpu is going down, then nothing needs to be done.
*/
if (!cpu_active(cpu))
return;
if (stop_tick) {
if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
return;
cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
atomic_inc(&nohz.nr_cpus);
set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
}
return;
}
static int __cpuinit sched_ilb_notifier(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DYING:
clear_nohz_tick_stopped(smp_processor_id());
return NOTIFY_OK;
default:
return NOTIFY_DONE;
}
}
#endif
static DEFINE_SPINLOCK(balancing);
/*
* Scale the max load_balance interval with the number of CPUs in the system.
* This trades load-balance latency on larger machines for less cross talk.
*/
void update_max_interval(void)
{
max_load_balance_interval = HZ*num_online_cpus()/10;
}
/*
* It checks each scheduling domain to see if it is due to be balanced,
* and initiates a balancing operation if so.
*
* Balancing parameters are set up in arch_init_sched_domains.
*/
static void rebalance_domains(int cpu, enum cpu_idle_type idle)
{
int balance = 1;
struct rq *rq = cpu_rq(cpu);
unsigned long interval;
struct sched_domain *sd;
/* Earliest time when we have to do rebalance again */
unsigned long next_balance = jiffies + 60*HZ;
int update_next_balance = 0;
int need_serialize;
update_shares(cpu);
rcu_read_lock();
for_each_domain(cpu, sd) {
if (!(sd->flags & SD_LOAD_BALANCE))
continue;
interval = sd->balance_interval;
if (idle != CPU_IDLE)
interval *= sd->busy_factor;
/* scale ms to jiffies */
interval = msecs_to_jiffies(interval);
interval = clamp(interval, 1UL, max_load_balance_interval);
need_serialize = sd->flags & SD_SERIALIZE;
if (need_serialize) {
if (!spin_trylock(&balancing))
goto out;
}
if (time_after_eq(jiffies, sd->last_balance + interval)) {
if (load_balance(cpu, rq, sd, idle, &balance)) {
/*
* We've pulled tasks over so either we're no
* longer idle.
*/
idle = CPU_NOT_IDLE;
}
sd->last_balance = jiffies;
}
if (need_serialize)
spin_unlock(&balancing);
out:
if (time_after(next_balance, sd->last_balance + interval)) {
next_balance = sd->last_balance + interval;
update_next_balance = 1;
}
/*
* Stop the load balance at this level. There is another
* CPU in our sched group which is doing load balancing more
* actively.
*/
if (!balance)
break;
}
rcu_read_unlock();
/*
* next_balance will be updated only when there is a need.
* When the cpu is attached to null domain for ex, it will not be
* updated.
*/
if (likely(update_next_balance))
rq->next_balance = next_balance;
}
#ifdef CONFIG_NO_HZ
/*
* In CONFIG_NO_HZ case, the idle balance kickee will do the
* rebalancing for all the cpus for whom scheduler ticks are stopped.
*/
static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
{
struct rq *this_rq = cpu_rq(this_cpu);
struct rq *rq;
int balance_cpu;
if (idle != CPU_IDLE ||
!test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
goto end;
for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
continue;
/*
* If this cpu gets work to do, stop the load balancing
* work being done for other cpus. Next load
* balancing owner will pick it up.
*/
if (need_resched())
break;
raw_spin_lock_irq(&this_rq->lock);
update_rq_clock(this_rq);
update_cpu_load(this_rq);
raw_spin_unlock_irq(&this_rq->lock);
rebalance_domains(balance_cpu, CPU_IDLE);
rq = cpu_rq(balance_cpu);
if (time_after(this_rq->next_balance, rq->next_balance))
this_rq->next_balance = rq->next_balance;
}
nohz.next_balance = this_rq->next_balance;
end:
clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
}
/*
* Current heuristic for kicking the idle load balancer in the presence
* of an idle cpu is the system.
* - This rq has more than one task.
* - At any scheduler domain level, this cpu's scheduler group has multiple
* busy cpu's exceeding the group's power.
* - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
* domain span are idle.
*/
static inline int nohz_kick_needed(struct rq *rq, int cpu)
{
unsigned long now = jiffies;
struct sched_domain *sd;
if (unlikely(idle_cpu(cpu)))
return 0;
/*
* We may be recently in ticked or tickless idle mode. At the first
* busy tick after returning from idle, we will update the busy stats.
*/
set_cpu_sd_state_busy();
clear_nohz_tick_stopped(cpu);
/*
* None are in tickless mode and hence no need for NOHZ idle load
* balancing.
*/
if (likely(!atomic_read(&nohz.nr_cpus)))
return 0;
if (time_before(now, nohz.next_balance))
return 0;
if (rq->nr_running >= 2)
goto need_kick;
rcu_read_lock();
for_each_domain(cpu, sd) {
struct sched_group *sg = sd->groups;
struct sched_group_power *sgp = sg->sgp;
int nr_busy = atomic_read(&sgp->nr_busy_cpus);
if (sd->flags & SD_SHARE_PKG_RESOURCES && nr_busy > 1)
goto need_kick_unlock;
if (sd->flags & SD_ASYM_PACKING && nr_busy != sg->group_weight
&& (cpumask_first_and(nohz.idle_cpus_mask,
sched_domain_span(sd)) < cpu))
goto need_kick_unlock;
if (!(sd->flags & (SD_SHARE_PKG_RESOURCES | SD_ASYM_PACKING)))
break;
}
rcu_read_unlock();
return 0;
need_kick_unlock:
rcu_read_unlock();
need_kick:
return 1;
}
#else
static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
#endif
/*
* run_rebalance_domains is triggered when needed from the scheduler tick.
* Also triggered for nohz idle balancing (with nohz_balancing_kick set).
*/
static void run_rebalance_domains(struct softirq_action *h)
{
int this_cpu = smp_processor_id();
struct rq *this_rq = cpu_rq(this_cpu);
enum cpu_idle_type idle = this_rq->idle_balance ?
CPU_IDLE : CPU_NOT_IDLE;
rebalance_domains(this_cpu, idle);
/*
* If this cpu has a pending nohz_balance_kick, then do the
* balancing on behalf of the other idle cpus whose ticks are
* stopped.
*/
nohz_idle_balance(this_cpu, idle);
}
static inline int on_null_domain(int cpu)
{
return !rcu_dereference_sched(cpu_rq(cpu)->sd);
}
/*
* Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
*/
void trigger_load_balance(struct rq *rq, int cpu)
{
/* Don't need to rebalance while attached to NULL domain */
if (time_after_eq(jiffies, rq->next_balance) &&
likely(!on_null_domain(cpu)))
raise_softirq(SCHED_SOFTIRQ);
#ifdef CONFIG_NO_HZ
if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
nohz_balancer_kick(cpu);
#endif
}
static void rq_online_fair(struct rq *rq)
{
update_sysctl();
}
static void rq_offline_fair(struct rq *rq)
{
update_sysctl();
}
#endif /* CONFIG_SMP */
/*
* scheduler tick hitting a task of our scheduling class:
*/
static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
{
struct cfs_rq *cfs_rq;
struct sched_entity *se = &curr->se;
for_each_sched_entity(se) {
cfs_rq = cfs_rq_of(se);
entity_tick(cfs_rq, se, queued);
}
}
/*
* called on fork with the child task as argument from the parent's context
* - child not yet on the tasklist
* - preemption disabled
*/
static void task_fork_fair(struct task_struct *p)
{
struct cfs_rq *cfs_rq;
struct sched_entity *se = &p->se, *curr;
int this_cpu = smp_processor_id();
struct rq *rq = this_rq();
unsigned long flags;
raw_spin_lock_irqsave(&rq->lock, flags);
update_rq_clock(rq);
cfs_rq = task_cfs_rq(current);
curr = cfs_rq->curr;
if (unlikely(task_cpu(p) != this_cpu)) {
rcu_read_lock();
__set_task_cpu(p, this_cpu);
rcu_read_unlock();
}
update_curr(cfs_rq);
if (curr)
se->vruntime = curr->vruntime;
place_entity(cfs_rq, se, 1);
if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
/*
* Upon rescheduling, sched_class::put_prev_task() will place
* 'current' within the tree based on its new key value.
*/
swap(curr->vruntime, se->vruntime);
resched_task(rq->curr);
}
se->vruntime -= cfs_rq->min_vruntime;
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
/*
* Priority of the task has changed. Check to see if we preempt
* the current task.
*/
static void
prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
{
if (!p->se.on_rq)
return;
/*
* Reschedule if we are currently running on this runqueue and
* our priority decreased, or if we are not currently running on
* this runqueue and our priority is higher than the current's
*/
if (rq->curr == p) {
if (p->prio > oldprio)
resched_task(rq->curr);
} else
check_preempt_curr(rq, p, 0);
}
static void switched_from_fair(struct rq *rq, struct task_struct *p)
{
struct sched_entity *se = &p->se;
struct cfs_rq *cfs_rq = cfs_rq_of(se);
/*
* Ensure the task's vruntime is normalized, so that when its
* switched back to the fair class the enqueue_entity(.flags=0) will
* do the right thing.
*
* If it was on_rq, then the dequeue_entity(.flags=0) will already
* have normalized the vruntime, if it was !on_rq, then only when
* the task is sleeping will it still have non-normalized vruntime.
*/
if (!se->on_rq && p->state != TASK_RUNNING) {
/*
* Fix up our vruntime so that the current sleep doesn't
* cause 'unlimited' sleep bonus.
*/
place_entity(cfs_rq, se, 0);
se->vruntime -= cfs_rq->min_vruntime;
}
}
/*
* We switched to the sched_fair class.
*/
static void switched_to_fair(struct rq *rq, struct task_struct *p)
{
if (!p->se.on_rq)
return;
/*
* We were most likely switched from sched_rt, so
* kick off the schedule if running, otherwise just see
* if we can still preempt the current task.
*/
if (rq->curr == p)
resched_task(rq->curr);
else
check_preempt_curr(rq, p, 0);
}
/* Account for a task changing its policy or group.
*
* This routine is mostly called to set cfs_rq->curr field when a task
* migrates between groups/classes.
*/
static void set_curr_task_fair(struct rq *rq)
{
struct sched_entity *se = &rq->curr->se;
for_each_sched_entity(se) {
struct cfs_rq *cfs_rq = cfs_rq_of(se);
set_next_entity(cfs_rq, se);
/* ensure bandwidth has been allocated on our new cfs_rq */
account_cfs_rq_runtime(cfs_rq, 0);
}
}
void init_cfs_rq(struct cfs_rq *cfs_rq)
{
cfs_rq->tasks_timeline = RB_ROOT;
cfs_rq->min_vruntime = (u64)(-(1LL << 20));
#ifndef CONFIG_64BIT
cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
#endif
}
#ifdef CONFIG_FAIR_GROUP_SCHED
static void task_move_group_fair(struct task_struct *p, int on_rq)
{
/*
* If the task was not on the rq at the time of this cgroup movement
* it must have been asleep, sleeping tasks keep their ->vruntime
* absolute on their old rq until wakeup (needed for the fair sleeper
* bonus in place_entity()).
*
* If it was on the rq, we've just 'preempted' it, which does convert
* ->vruntime to a relative base.
*
* Make sure both cases convert their relative position when migrating
* to another cgroup's rq. This does somewhat interfere with the
* fair sleeper stuff for the first placement, but who cares.
*/
/*
* When !on_rq, vruntime of the task has usually NOT been normalized.
* But there are some cases where it has already been normalized:
*
* - Moving a forked child which is waiting for being woken up by
* wake_up_new_task().
* - Moving a task which has been woken up by try_to_wake_up() and
* waiting for actually being woken up by sched_ttwu_pending().
*
* To prevent boost or penalty in the new cfs_rq caused by delta
* min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
*/
if (!on_rq && (!p->se.sum_exec_runtime || p->state == TASK_WAKING))
on_rq = 1;
if (!on_rq)
p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
set_task_rq(p, task_cpu(p));
if (!on_rq)
p->se.vruntime += cfs_rq_of(&p->se)->min_vruntime;
}
void free_fair_sched_group(struct task_group *tg)
{
int i;
destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
for_each_possible_cpu(i) {
if (tg->cfs_rq)
kfree(tg->cfs_rq[i]);
if (tg->se)
kfree(tg->se[i]);
}
kfree(tg->cfs_rq);
kfree(tg->se);
}
int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
{
struct cfs_rq *cfs_rq;
struct sched_entity *se;
int i;
tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
if (!tg->cfs_rq)
goto err;
tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
if (!tg->se)
goto err;
tg->shares = NICE_0_LOAD;
init_cfs_bandwidth(tg_cfs_bandwidth(tg));
for_each_possible_cpu(i) {
cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
GFP_KERNEL, cpu_to_node(i));
if (!cfs_rq)
goto err;
se = kzalloc_node(sizeof(struct sched_entity),
GFP_KERNEL, cpu_to_node(i));
if (!se)
goto err_free_rq;
init_cfs_rq(cfs_rq);
init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
}
return 1;
err_free_rq:
kfree(cfs_rq);
err:
return 0;
}
void unregister_fair_sched_group(struct task_group *tg, int cpu)
{
struct rq *rq = cpu_rq(cpu);
unsigned long flags;
/*
* Only empty task groups can be destroyed; so we can speculatively
* check on_list without danger of it being re-added.
*/
if (!tg->cfs_rq[cpu]->on_list)
return;
raw_spin_lock_irqsave(&rq->lock, flags);
list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
struct sched_entity *se, int cpu,
struct sched_entity *parent)
{
struct rq *rq = cpu_rq(cpu);
cfs_rq->tg = tg;
cfs_rq->rq = rq;
#ifdef CONFIG_SMP
/* allow initial update_cfs_load() to truncate */
cfs_rq->load_stamp = 1;
#endif
init_cfs_rq_runtime(cfs_rq);
tg->cfs_rq[cpu] = cfs_rq;
tg->se[cpu] = se;
/* se could be NULL for root_task_group */
if (!se)
return;
if (!parent)
se->cfs_rq = &rq->cfs;
else
se->cfs_rq = parent->my_q;
se->my_q = cfs_rq;
update_load_set(&se->load, 0);
se->parent = parent;
}
static DEFINE_MUTEX(shares_mutex);
int sched_group_set_shares(struct task_group *tg, unsigned long shares)
{
int i;
unsigned long flags;
/*
* We can't change the weight of the root cgroup.
*/
if (!tg->se[0])
return -EINVAL;
shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
mutex_lock(&shares_mutex);
if (tg->shares == shares)
goto done;
tg->shares = shares;
for_each_possible_cpu(i) {
struct rq *rq = cpu_rq(i);
struct sched_entity *se;
se = tg->se[i];
/* Propagate contribution to hierarchy */
raw_spin_lock_irqsave(&rq->lock, flags);
for_each_sched_entity(se)
update_cfs_shares(group_cfs_rq(se));
raw_spin_unlock_irqrestore(&rq->lock, flags);
}
done:
mutex_unlock(&shares_mutex);
return 0;
}
#else /* CONFIG_FAIR_GROUP_SCHED */
void free_fair_sched_group(struct task_group *tg) { }
int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
{
return 1;
}
void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
#endif /* CONFIG_FAIR_GROUP_SCHED */
static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
{
struct sched_entity *se = &task->se;
unsigned int rr_interval = 0;
/*
* Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
* idle runqueue:
*/
if (rq->cfs.load.weight)
rr_interval = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
return rr_interval;
}
/*
* All the scheduling class methods:
*/
const struct sched_class fair_sched_class = {
.next = &idle_sched_class,
.enqueue_task = enqueue_task_fair,
.dequeue_task = dequeue_task_fair,
.yield_task = yield_task_fair,
.yield_to_task = yield_to_task_fair,
.check_preempt_curr = check_preempt_wakeup,
.pick_next_task = pick_next_task_fair,
.put_prev_task = put_prev_task_fair,
#ifdef CONFIG_SMP
.select_task_rq = select_task_rq_fair,
.rq_online = rq_online_fair,
.rq_offline = rq_offline_fair,
.task_waking = task_waking_fair,
#endif
.set_curr_task = set_curr_task_fair,
.task_tick = task_tick_fair,
.task_fork = task_fork_fair,
.prio_changed = prio_changed_fair,
.switched_from = switched_from_fair,
.switched_to = switched_to_fair,
.get_rr_interval = get_rr_interval_fair,
#ifdef CONFIG_FAIR_GROUP_SCHED
.task_move_group = task_move_group_fair,
#endif
};
#ifdef CONFIG_SCHED_DEBUG
void print_cfs_stats(struct seq_file *m, int cpu)
{
struct cfs_rq *cfs_rq;
rcu_read_lock();
for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
print_cfs_rq(m, cpu, cfs_rq);
rcu_read_unlock();
}
#endif
__init void init_sched_fair_class(void)
{
#ifdef CONFIG_SMP
open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
#ifdef CONFIG_NO_HZ
nohz.next_balance = jiffies;
zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
cpu_notifier(sched_ilb_notifier, 0);
#endif
#endif /* SMP */
}
| gpl-2.0 |
CyanogenMod/htc-kernel-msm7227 | arch/powerpc/mm/mmu_context_hash32.c | 780 | 3147 | /*
* This file contains the routines for handling the MMU on those
* PowerPC implementations where the MMU substantially follows the
* architecture specification. This includes the 6xx, 7xx, 7xxx,
* 8260, and POWER3 implementations but excludes the 8xx and 4xx.
* -- paulus
*
* Derived from arch/ppc/mm/init.c:
* Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org)
*
* Modifications by Paul Mackerras (PowerMac) (paulus@cs.anu.edu.au)
* and Cort Dougan (PReP) (cort@cs.nmt.edu)
* Copyright (C) 1996 Paul Mackerras
*
* Derived from "arch/i386/mm/init.c"
* Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
*
* 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/mm.h>
#include <linux/init.h>
#include <asm/mmu_context.h>
#include <asm/tlbflush.h>
/*
* On 32-bit PowerPC 6xx/7xx/7xxx CPUs, we use a set of 16 VSIDs
* (virtual segment identifiers) for each context. Although the
* hardware supports 24-bit VSIDs, and thus >1 million contexts,
* we only use 32,768 of them. That is ample, since there can be
* at most around 30,000 tasks in the system anyway, and it means
* that we can use a bitmap to indicate which contexts are in use.
* Using a bitmap means that we entirely avoid all of the problems
* that we used to have when the context number overflowed,
* particularly on SMP systems.
* -- paulus.
*/
#define NO_CONTEXT ((unsigned long) -1)
#define LAST_CONTEXT 32767
#define FIRST_CONTEXT 1
/*
* This function defines the mapping from contexts to VSIDs (virtual
* segment IDs). We use a skew on both the context and the high 4 bits
* of the 32-bit virtual address (the "effective segment ID") in order
* to spread out the entries in the MMU hash table. Note, if this
* function is changed then arch/ppc/mm/hashtable.S will have to be
* changed to correspond.
*
*
* CTX_TO_VSID(ctx, va) (((ctx) * (897 * 16) + ((va) >> 28) * 0x111) \
* & 0xffffff)
*/
static unsigned long next_mmu_context;
static unsigned long context_map[LAST_CONTEXT / BITS_PER_LONG + 1];
/*
* Set up the context for a new address space.
*/
int init_new_context(struct task_struct *t, struct mm_struct *mm)
{
unsigned long ctx = next_mmu_context;
while (test_and_set_bit(ctx, context_map)) {
ctx = find_next_zero_bit(context_map, LAST_CONTEXT+1, ctx);
if (ctx > LAST_CONTEXT)
ctx = 0;
}
next_mmu_context = (ctx + 1) & LAST_CONTEXT;
mm->context.id = ctx;
return 0;
}
/*
* We're finished using the context for an address space.
*/
void destroy_context(struct mm_struct *mm)
{
preempt_disable();
if (mm->context.id != NO_CONTEXT) {
clear_bit(mm->context.id, context_map);
mm->context.id = NO_CONTEXT;
}
preempt_enable();
}
/*
* Initialize the context management stuff.
*/
void __init mmu_context_init(void)
{
/* Reserve context 0 for kernel use */
context_map[0] = (1 << FIRST_CONTEXT) - 1;
next_mmu_context = FIRST_CONTEXT;
}
| gpl-2.0 |
craneboard/craneboard-kernel | arch/ia64/kernel/traps.c | 780 | 17742 | /*
* Architecture-specific trap handling.
*
* Copyright (C) 1998-2003 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
*
* 05/12/00 grao <goutham.rao@intel.com> : added isr in siginfo for SIGFPE
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/tty.h>
#include <linux/vt_kern.h> /* For unblank_screen() */
#include <linux/module.h> /* for EXPORT_SYMBOL */
#include <linux/hardirq.h>
#include <linux/kprobes.h>
#include <linux/delay.h> /* for ssleep() */
#include <linux/kdebug.h>
#include <asm/fpswa.h>
#include <asm/ia32.h>
#include <asm/intrinsics.h>
#include <asm/processor.h>
#include <asm/uaccess.h>
fpswa_interface_t *fpswa_interface;
EXPORT_SYMBOL(fpswa_interface);
void __init
trap_init (void)
{
if (ia64_boot_param->fpswa)
/* FPSWA fixup: make the interface pointer a kernel virtual address: */
fpswa_interface = __va(ia64_boot_param->fpswa);
}
int
die (const char *str, struct pt_regs *regs, long err)
{
static struct {
spinlock_t lock;
u32 lock_owner;
int lock_owner_depth;
} die = {
.lock = __SPIN_LOCK_UNLOCKED(die.lock),
.lock_owner = -1,
.lock_owner_depth = 0
};
static int die_counter;
int cpu = get_cpu();
if (die.lock_owner != cpu) {
console_verbose();
spin_lock_irq(&die.lock);
die.lock_owner = cpu;
die.lock_owner_depth = 0;
bust_spinlocks(1);
}
put_cpu();
if (++die.lock_owner_depth < 3) {
printk("%s[%d]: %s %ld [%d]\n",
current->comm, task_pid_nr(current), str, err, ++die_counter);
if (notify_die(DIE_OOPS, str, regs, err, 255, SIGSEGV)
!= NOTIFY_STOP)
show_regs(regs);
else
regs = NULL;
} else
printk(KERN_ERR "Recursive die() failure, output suppressed\n");
bust_spinlocks(0);
die.lock_owner = -1;
add_taint(TAINT_DIE);
spin_unlock_irq(&die.lock);
if (!regs)
return 1;
if (panic_on_oops)
panic("Fatal exception");
do_exit(SIGSEGV);
return 0;
}
int
die_if_kernel (char *str, struct pt_regs *regs, long err)
{
if (!user_mode(regs))
return die(str, regs, err);
return 0;
}
void
__kprobes ia64_bad_break (unsigned long break_num, struct pt_regs *regs)
{
siginfo_t siginfo;
int sig, code;
/* SIGILL, SIGFPE, SIGSEGV, and SIGBUS want these field initialized: */
siginfo.si_addr = (void __user *) (regs->cr_iip + ia64_psr(regs)->ri);
siginfo.si_imm = break_num;
siginfo.si_flags = 0; /* clear __ISR_VALID */
siginfo.si_isr = 0;
switch (break_num) {
case 0: /* unknown error (used by GCC for __builtin_abort()) */
if (notify_die(DIE_BREAK, "break 0", regs, break_num, TRAP_BRKPT, SIGTRAP)
== NOTIFY_STOP)
return;
if (die_if_kernel("bugcheck!", regs, break_num))
return;
sig = SIGILL; code = ILL_ILLOPC;
break;
case 1: /* integer divide by zero */
sig = SIGFPE; code = FPE_INTDIV;
break;
case 2: /* integer overflow */
sig = SIGFPE; code = FPE_INTOVF;
break;
case 3: /* range check/bounds check */
sig = SIGFPE; code = FPE_FLTSUB;
break;
case 4: /* null pointer dereference */
sig = SIGSEGV; code = SEGV_MAPERR;
break;
case 5: /* misaligned data */
sig = SIGSEGV; code = BUS_ADRALN;
break;
case 6: /* decimal overflow */
sig = SIGFPE; code = __FPE_DECOVF;
break;
case 7: /* decimal divide by zero */
sig = SIGFPE; code = __FPE_DECDIV;
break;
case 8: /* packed decimal error */
sig = SIGFPE; code = __FPE_DECERR;
break;
case 9: /* invalid ASCII digit */
sig = SIGFPE; code = __FPE_INVASC;
break;
case 10: /* invalid decimal digit */
sig = SIGFPE; code = __FPE_INVDEC;
break;
case 11: /* paragraph stack overflow */
sig = SIGSEGV; code = __SEGV_PSTKOVF;
break;
case 0x3f000 ... 0x3ffff: /* bundle-update in progress */
sig = SIGILL; code = __ILL_BNDMOD;
break;
default:
if ((break_num < 0x40000 || break_num > 0x100000)
&& die_if_kernel("Bad break", regs, break_num))
return;
if (break_num < 0x80000) {
sig = SIGILL; code = __ILL_BREAK;
} else {
if (notify_die(DIE_BREAK, "bad break", regs, break_num, TRAP_BRKPT, SIGTRAP)
== NOTIFY_STOP)
return;
sig = SIGTRAP; code = TRAP_BRKPT;
}
}
siginfo.si_signo = sig;
siginfo.si_errno = 0;
siginfo.si_code = code;
force_sig_info(sig, &siginfo, current);
}
/*
* disabled_fph_fault() is called when a user-level process attempts to access f32..f127
* and it doesn't own the fp-high register partition. When this happens, we save the
* current fph partition in the task_struct of the fpu-owner (if necessary) and then load
* the fp-high partition of the current task (if necessary). Note that the kernel has
* access to fph by the time we get here, as the IVT's "Disabled FP-Register" handler takes
* care of clearing psr.dfh.
*/
static inline void
disabled_fph_fault (struct pt_regs *regs)
{
struct ia64_psr *psr = ia64_psr(regs);
/* first, grant user-level access to fph partition: */
psr->dfh = 0;
/*
* Make sure that no other task gets in on this processor
* while we're claiming the FPU
*/
preempt_disable();
#ifndef CONFIG_SMP
{
struct task_struct *fpu_owner
= (struct task_struct *)ia64_get_kr(IA64_KR_FPU_OWNER);
if (ia64_is_local_fpu_owner(current)) {
preempt_enable_no_resched();
return;
}
if (fpu_owner)
ia64_flush_fph(fpu_owner);
}
#endif /* !CONFIG_SMP */
ia64_set_local_fpu_owner(current);
if ((current->thread.flags & IA64_THREAD_FPH_VALID) != 0) {
__ia64_load_fpu(current->thread.fph);
psr->mfh = 0;
} else {
__ia64_init_fpu();
/*
* Set mfh because the state in thread.fph does not match the state in
* the fph partition.
*/
psr->mfh = 1;
}
preempt_enable_no_resched();
}
static inline int
fp_emulate (int fp_fault, void *bundle, long *ipsr, long *fpsr, long *isr, long *pr, long *ifs,
struct pt_regs *regs)
{
fp_state_t fp_state;
fpswa_ret_t ret;
if (!fpswa_interface)
return -1;
memset(&fp_state, 0, sizeof(fp_state_t));
/*
* compute fp_state. only FP registers f6 - f11 are used by the
* kernel, so set those bits in the mask and set the low volatile
* pointer to point to these registers.
*/
fp_state.bitmask_low64 = 0xfc0; /* bit6..bit11 */
fp_state.fp_state_low_volatile = (fp_state_low_volatile_t *) ®s->f6;
/*
* unsigned long (*EFI_FPSWA) (
* unsigned long trap_type,
* void *Bundle,
* unsigned long *pipsr,
* unsigned long *pfsr,
* unsigned long *pisr,
* unsigned long *ppreds,
* unsigned long *pifs,
* void *fp_state);
*/
ret = (*fpswa_interface->fpswa)((unsigned long) fp_fault, bundle,
(unsigned long *) ipsr, (unsigned long *) fpsr,
(unsigned long *) isr, (unsigned long *) pr,
(unsigned long *) ifs, &fp_state);
return ret.status;
}
struct fpu_swa_msg {
unsigned long count;
unsigned long time;
};
static DEFINE_PER_CPU(struct fpu_swa_msg, cpulast);
DECLARE_PER_CPU(struct fpu_swa_msg, cpulast);
static struct fpu_swa_msg last __cacheline_aligned;
/*
* Handle floating-point assist faults and traps.
*/
static int
handle_fpu_swa (int fp_fault, struct pt_regs *regs, unsigned long isr)
{
long exception, bundle[2];
unsigned long fault_ip;
struct siginfo siginfo;
fault_ip = regs->cr_iip;
if (!fp_fault && (ia64_psr(regs)->ri == 0))
fault_ip -= 16;
if (copy_from_user(bundle, (void __user *) fault_ip, sizeof(bundle)))
return -1;
if (!(current->thread.flags & IA64_THREAD_FPEMU_NOPRINT)) {
unsigned long count, current_jiffies = jiffies;
struct fpu_swa_msg *cp = &__get_cpu_var(cpulast);
if (unlikely(current_jiffies > cp->time))
cp->count = 0;
if (unlikely(cp->count < 5)) {
cp->count++;
cp->time = current_jiffies + 5 * HZ;
/* minimize races by grabbing a copy of count BEFORE checking last.time. */
count = last.count;
barrier();
/*
* Lower 4 bits are used as a count. Upper bits are a sequence
* number that is updated when count is reset. The cmpxchg will
* fail is seqno has changed. This minimizes mutiple cpus
* resetting the count.
*/
if (current_jiffies > last.time)
(void) cmpxchg_acq(&last.count, count, 16 + (count & ~15));
/* used fetchadd to atomically update the count */
if ((last.count & 15) < 5 && (ia64_fetchadd(1, &last.count, acq) & 15) < 5) {
last.time = current_jiffies + 5 * HZ;
printk(KERN_WARNING
"%s(%d): floating-point assist fault at ip %016lx, isr %016lx\n",
current->comm, task_pid_nr(current), regs->cr_iip + ia64_psr(regs)->ri, isr);
}
}
}
exception = fp_emulate(fp_fault, bundle, ®s->cr_ipsr, ®s->ar_fpsr, &isr, ®s->pr,
®s->cr_ifs, regs);
if (fp_fault) {
if (exception == 0) {
/* emulation was successful */
ia64_increment_ip(regs);
} else if (exception == -1) {
printk(KERN_ERR "handle_fpu_swa: fp_emulate() returned -1\n");
return -1;
} else {
/* is next instruction a trap? */
if (exception & 2) {
ia64_increment_ip(regs);
}
siginfo.si_signo = SIGFPE;
siginfo.si_errno = 0;
siginfo.si_code = __SI_FAULT; /* default code */
siginfo.si_addr = (void __user *) (regs->cr_iip + ia64_psr(regs)->ri);
if (isr & 0x11) {
siginfo.si_code = FPE_FLTINV;
} else if (isr & 0x22) {
/* denormal operand gets the same si_code as underflow
* see arch/i386/kernel/traps.c:math_error() */
siginfo.si_code = FPE_FLTUND;
} else if (isr & 0x44) {
siginfo.si_code = FPE_FLTDIV;
}
siginfo.si_isr = isr;
siginfo.si_flags = __ISR_VALID;
siginfo.si_imm = 0;
force_sig_info(SIGFPE, &siginfo, current);
}
} else {
if (exception == -1) {
printk(KERN_ERR "handle_fpu_swa: fp_emulate() returned -1\n");
return -1;
} else if (exception != 0) {
/* raise exception */
siginfo.si_signo = SIGFPE;
siginfo.si_errno = 0;
siginfo.si_code = __SI_FAULT; /* default code */
siginfo.si_addr = (void __user *) (regs->cr_iip + ia64_psr(regs)->ri);
if (isr & 0x880) {
siginfo.si_code = FPE_FLTOVF;
} else if (isr & 0x1100) {
siginfo.si_code = FPE_FLTUND;
} else if (isr & 0x2200) {
siginfo.si_code = FPE_FLTRES;
}
siginfo.si_isr = isr;
siginfo.si_flags = __ISR_VALID;
siginfo.si_imm = 0;
force_sig_info(SIGFPE, &siginfo, current);
}
}
return 0;
}
struct illegal_op_return {
unsigned long fkt, arg1, arg2, arg3;
};
struct illegal_op_return
ia64_illegal_op_fault (unsigned long ec, long arg1, long arg2, long arg3,
long arg4, long arg5, long arg6, long arg7,
struct pt_regs regs)
{
struct illegal_op_return rv;
struct siginfo si;
char buf[128];
#ifdef CONFIG_IA64_BRL_EMU
{
extern struct illegal_op_return ia64_emulate_brl (struct pt_regs *, unsigned long);
rv = ia64_emulate_brl(®s, ec);
if (rv.fkt != (unsigned long) -1)
return rv;
}
#endif
sprintf(buf, "IA-64 Illegal operation fault");
rv.fkt = 0;
if (die_if_kernel(buf, ®s, 0))
return rv;
memset(&si, 0, sizeof(si));
si.si_signo = SIGILL;
si.si_code = ILL_ILLOPC;
si.si_addr = (void __user *) (regs.cr_iip + ia64_psr(®s)->ri);
force_sig_info(SIGILL, &si, current);
return rv;
}
void __kprobes
ia64_fault (unsigned long vector, unsigned long isr, unsigned long ifa,
unsigned long iim, unsigned long itir, long arg5, long arg6,
long arg7, struct pt_regs regs)
{
unsigned long code, error = isr, iip;
struct siginfo siginfo;
char buf[128];
int result, sig;
static const char *reason[] = {
"IA-64 Illegal Operation fault",
"IA-64 Privileged Operation fault",
"IA-64 Privileged Register fault",
"IA-64 Reserved Register/Field fault",
"Disabled Instruction Set Transition fault",
"Unknown fault 5", "Unknown fault 6", "Unknown fault 7", "Illegal Hazard fault",
"Unknown fault 9", "Unknown fault 10", "Unknown fault 11", "Unknown fault 12",
"Unknown fault 13", "Unknown fault 14", "Unknown fault 15"
};
if ((isr & IA64_ISR_NA) && ((isr & IA64_ISR_CODE_MASK) == IA64_ISR_CODE_LFETCH)) {
/*
* This fault was due to lfetch.fault, set "ed" bit in the psr to cancel
* the lfetch.
*/
ia64_psr(®s)->ed = 1;
return;
}
iip = regs.cr_iip + ia64_psr(®s)->ri;
switch (vector) {
case 24: /* General Exception */
code = (isr >> 4) & 0xf;
sprintf(buf, "General Exception: %s%s", reason[code],
(code == 3) ? ((isr & (1UL << 37))
? " (RSE access)" : " (data access)") : "");
if (code == 8) {
# ifdef CONFIG_IA64_PRINT_HAZARDS
printk("%s[%d]: possible hazard @ ip=%016lx (pr = %016lx)\n",
current->comm, task_pid_nr(current),
regs.cr_iip + ia64_psr(®s)->ri, regs.pr);
# endif
return;
}
break;
case 25: /* Disabled FP-Register */
if (isr & 2) {
disabled_fph_fault(®s);
return;
}
sprintf(buf, "Disabled FPL fault---not supposed to happen!");
break;
case 26: /* NaT Consumption */
if (user_mode(®s)) {
void __user *addr;
if (((isr >> 4) & 0xf) == 2) {
/* NaT page consumption */
sig = SIGSEGV;
code = SEGV_ACCERR;
addr = (void __user *) ifa;
} else {
/* register NaT consumption */
sig = SIGILL;
code = ILL_ILLOPN;
addr = (void __user *) (regs.cr_iip
+ ia64_psr(®s)->ri);
}
siginfo.si_signo = sig;
siginfo.si_code = code;
siginfo.si_errno = 0;
siginfo.si_addr = addr;
siginfo.si_imm = vector;
siginfo.si_flags = __ISR_VALID;
siginfo.si_isr = isr;
force_sig_info(sig, &siginfo, current);
return;
} else if (ia64_done_with_exception(®s))
return;
sprintf(buf, "NaT consumption");
break;
case 31: /* Unsupported Data Reference */
if (user_mode(®s)) {
siginfo.si_signo = SIGILL;
siginfo.si_code = ILL_ILLOPN;
siginfo.si_errno = 0;
siginfo.si_addr = (void __user *) iip;
siginfo.si_imm = vector;
siginfo.si_flags = __ISR_VALID;
siginfo.si_isr = isr;
force_sig_info(SIGILL, &siginfo, current);
return;
}
sprintf(buf, "Unsupported data reference");
break;
case 29: /* Debug */
case 35: /* Taken Branch Trap */
case 36: /* Single Step Trap */
if (fsys_mode(current, ®s)) {
extern char __kernel_syscall_via_break[];
/*
* Got a trap in fsys-mode: Taken Branch Trap
* and Single Step trap need special handling;
* Debug trap is ignored (we disable it here
* and re-enable it in the lower-privilege trap).
*/
if (unlikely(vector == 29)) {
set_thread_flag(TIF_DB_DISABLED);
ia64_psr(®s)->db = 0;
ia64_psr(®s)->lp = 1;
return;
}
/* re-do the system call via break 0x100000: */
regs.cr_iip = (unsigned long) __kernel_syscall_via_break;
ia64_psr(®s)->ri = 0;
ia64_psr(®s)->cpl = 3;
return;
}
switch (vector) {
case 29:
siginfo.si_code = TRAP_HWBKPT;
#ifdef CONFIG_ITANIUM
/*
* Erratum 10 (IFA may contain incorrect address) now has
* "NoFix" status. There are no plans for fixing this.
*/
if (ia64_psr(®s)->is == 0)
ifa = regs.cr_iip;
#endif
break;
case 35: siginfo.si_code = TRAP_BRANCH; ifa = 0; break;
case 36: siginfo.si_code = TRAP_TRACE; ifa = 0; break;
}
if (notify_die(DIE_FAULT, "ia64_fault", ®s, vector, siginfo.si_code, SIGTRAP)
== NOTIFY_STOP)
return;
siginfo.si_signo = SIGTRAP;
siginfo.si_errno = 0;
siginfo.si_addr = (void __user *) ifa;
siginfo.si_imm = 0;
siginfo.si_flags = __ISR_VALID;
siginfo.si_isr = isr;
force_sig_info(SIGTRAP, &siginfo, current);
return;
case 32: /* fp fault */
case 33: /* fp trap */
result = handle_fpu_swa((vector == 32) ? 1 : 0, ®s, isr);
if ((result < 0) || (current->thread.flags & IA64_THREAD_FPEMU_SIGFPE)) {
siginfo.si_signo = SIGFPE;
siginfo.si_errno = 0;
siginfo.si_code = FPE_FLTINV;
siginfo.si_addr = (void __user *) iip;
siginfo.si_flags = __ISR_VALID;
siginfo.si_isr = isr;
siginfo.si_imm = 0;
force_sig_info(SIGFPE, &siginfo, current);
}
return;
case 34:
if (isr & 0x2) {
/* Lower-Privilege Transfer Trap */
/* If we disabled debug traps during an fsyscall,
* re-enable them here.
*/
if (test_thread_flag(TIF_DB_DISABLED)) {
clear_thread_flag(TIF_DB_DISABLED);
ia64_psr(®s)->db = 1;
}
/*
* Just clear PSR.lp and then return immediately:
* all the interesting work (e.g., signal delivery)
* is done in the kernel exit path.
*/
ia64_psr(®s)->lp = 0;
return;
} else {
/* Unimplemented Instr. Address Trap */
if (user_mode(®s)) {
siginfo.si_signo = SIGILL;
siginfo.si_code = ILL_BADIADDR;
siginfo.si_errno = 0;
siginfo.si_flags = 0;
siginfo.si_isr = 0;
siginfo.si_imm = 0;
siginfo.si_addr = (void __user *) iip;
force_sig_info(SIGILL, &siginfo, current);
return;
}
sprintf(buf, "Unimplemented Instruction Address fault");
}
break;
case 45:
#ifdef CONFIG_IA32_SUPPORT
if (ia32_exception(®s, isr) == 0)
return;
#endif
printk(KERN_ERR "Unexpected IA-32 exception (Trap 45)\n");
printk(KERN_ERR " iip - 0x%lx, ifa - 0x%lx, isr - 0x%lx\n",
iip, ifa, isr);
force_sig(SIGSEGV, current);
break;
case 46:
#ifdef CONFIG_IA32_SUPPORT
if (ia32_intercept(®s, isr) == 0)
return;
#endif
printk(KERN_ERR "Unexpected IA-32 intercept trap (Trap 46)\n");
printk(KERN_ERR " iip - 0x%lx, ifa - 0x%lx, isr - 0x%lx, iim - 0x%lx\n",
iip, ifa, isr, iim);
force_sig(SIGSEGV, current);
return;
case 47:
sprintf(buf, "IA-32 Interruption Fault (int 0x%lx)", isr >> 16);
break;
default:
sprintf(buf, "Fault %lu", vector);
break;
}
if (!die_if_kernel(buf, ®s, error))
force_sig(SIGILL, current);
}
| gpl-2.0 |
jrior001/android_kernel_samsung_d2 | fs/ecryptfs/mmap.c | 1292 | 16190 | /**
* eCryptfs: Linux filesystem encryption layer
* This is where eCryptfs coordinates the symmetric encryption and
* decryption of the file data as it passes between the lower
* encrypted file and the upper decrypted file.
*
* Copyright (C) 1997-2003 Erez Zadok
* Copyright (C) 2001-2003 Stony Brook University
* Copyright (C) 2004-2007 International Business Machines Corp.
* Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; 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/pagemap.h>
#include <linux/writeback.h>
#include <linux/page-flags.h>
#include <linux/mount.h>
#include <linux/file.h>
#include <linux/crypto.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include "ecryptfs_kernel.h"
/**
* ecryptfs_get_locked_page
*
* Get one page from cache or lower f/s, return error otherwise.
*
* Returns locked and up-to-date page (if ok), with increased
* refcnt.
*/
struct page *ecryptfs_get_locked_page(struct inode *inode, loff_t index)
{
struct page *page = read_mapping_page(inode->i_mapping, index, NULL);
if (!IS_ERR(page))
lock_page(page);
return page;
}
/**
* ecryptfs_writepage
* @page: Page that is locked before this call is made
*
* Returns zero on success; non-zero otherwise
*
* This is where we encrypt the data and pass the encrypted data to
* the lower filesystem. In OpenPGP-compatible mode, we operate on
* entire underlying packets.
*/
static int ecryptfs_writepage(struct page *page, struct writeback_control *wbc)
{
int rc;
rc = ecryptfs_encrypt_page(page);
if (rc) {
ecryptfs_printk(KERN_WARNING, "Error encrypting "
"page (upper index [0x%.16lx])\n", page->index);
ClearPageUptodate(page);
goto out;
}
SetPageUptodate(page);
out:
unlock_page(page);
return rc;
}
static void strip_xattr_flag(char *page_virt,
struct ecryptfs_crypt_stat *crypt_stat)
{
if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR) {
size_t written;
crypt_stat->flags &= ~ECRYPTFS_METADATA_IN_XATTR;
ecryptfs_write_crypt_stat_flags(page_virt, crypt_stat,
&written);
crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
}
}
/**
* Header Extent:
* Octets 0-7: Unencrypted file size (big-endian)
* Octets 8-15: eCryptfs special marker
* Octets 16-19: Flags
* Octet 16: File format version number (between 0 and 255)
* Octets 17-18: Reserved
* Octet 19: Bit 1 (lsb): Reserved
* Bit 2: Encrypted?
* Bits 3-8: Reserved
* Octets 20-23: Header extent size (big-endian)
* Octets 24-25: Number of header extents at front of file
* (big-endian)
* Octet 26: Begin RFC 2440 authentication token packet set
*/
/**
* ecryptfs_copy_up_encrypted_with_header
* @page: Sort of a ``virtual'' representation of the encrypted lower
* file. The actual lower file does not have the metadata in
* the header. This is locked.
* @crypt_stat: The eCryptfs inode's cryptographic context
*
* The ``view'' is the version of the file that userspace winds up
* seeing, with the header information inserted.
*/
static int
ecryptfs_copy_up_encrypted_with_header(struct page *page,
struct ecryptfs_crypt_stat *crypt_stat)
{
loff_t extent_num_in_page = 0;
loff_t num_extents_per_page = (PAGE_CACHE_SIZE
/ crypt_stat->extent_size);
int rc = 0;
while (extent_num_in_page < num_extents_per_page) {
loff_t view_extent_num = ((((loff_t)page->index)
* num_extents_per_page)
+ extent_num_in_page);
size_t num_header_extents_at_front =
(crypt_stat->metadata_size / crypt_stat->extent_size);
if (view_extent_num < num_header_extents_at_front) {
/* This is a header extent */
char *page_virt;
page_virt = kmap_atomic(page);
memset(page_virt, 0, PAGE_CACHE_SIZE);
/* TODO: Support more than one header extent */
if (view_extent_num == 0) {
size_t written;
rc = ecryptfs_read_xattr_region(
page_virt, page->mapping->host);
strip_xattr_flag(page_virt + 16, crypt_stat);
ecryptfs_write_header_metadata(page_virt + 20,
crypt_stat,
&written);
}
kunmap_atomic(page_virt);
flush_dcache_page(page);
if (rc) {
printk(KERN_ERR "%s: Error reading xattr "
"region; rc = [%d]\n", __func__, rc);
goto out;
}
} else {
/* This is an encrypted data extent */
loff_t lower_offset =
((view_extent_num * crypt_stat->extent_size)
- crypt_stat->metadata_size);
rc = ecryptfs_read_lower_page_segment(
page, (lower_offset >> PAGE_CACHE_SHIFT),
(lower_offset & ~PAGE_CACHE_MASK),
crypt_stat->extent_size, page->mapping->host);
if (rc) {
printk(KERN_ERR "%s: Error attempting to read "
"extent at offset [%lld] in the lower "
"file; rc = [%d]\n", __func__,
lower_offset, rc);
goto out;
}
}
extent_num_in_page++;
}
out:
return rc;
}
/**
* ecryptfs_readpage
* @file: An eCryptfs file
* @page: Page from eCryptfs inode mapping into which to stick the read data
*
* Read in a page, decrypting if necessary.
*
* Returns zero on success; non-zero on error.
*/
static int ecryptfs_readpage(struct file *file, struct page *page)
{
struct ecryptfs_crypt_stat *crypt_stat =
&ecryptfs_inode_to_private(page->mapping->host)->crypt_stat;
int rc = 0;
if (!crypt_stat || !(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
rc = ecryptfs_read_lower_page_segment(page, page->index, 0,
PAGE_CACHE_SIZE,
page->mapping->host);
} else if (crypt_stat->flags & ECRYPTFS_VIEW_AS_ENCRYPTED) {
if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR) {
rc = ecryptfs_copy_up_encrypted_with_header(page,
crypt_stat);
if (rc) {
printk(KERN_ERR "%s: Error attempting to copy "
"the encrypted content from the lower "
"file whilst inserting the metadata "
"from the xattr into the header; rc = "
"[%d]\n", __func__, rc);
goto out;
}
} else {
rc = ecryptfs_read_lower_page_segment(
page, page->index, 0, PAGE_CACHE_SIZE,
page->mapping->host);
if (rc) {
printk(KERN_ERR "Error reading page; rc = "
"[%d]\n", rc);
goto out;
}
}
} else {
rc = ecryptfs_decrypt_page(page);
if (rc) {
ecryptfs_printk(KERN_ERR, "Error decrypting page; "
"rc = [%d]\n", rc);
goto out;
}
}
out:
if (rc)
ClearPageUptodate(page);
else
SetPageUptodate(page);
ecryptfs_printk(KERN_DEBUG, "Unlocking page with index = [0x%.16lx]\n",
page->index);
unlock_page(page);
return rc;
}
/**
* Called with lower inode mutex held.
*/
static int fill_zeros_to_end_of_page(struct page *page, unsigned int to)
{
struct inode *inode = page->mapping->host;
int end_byte_in_page;
if ((i_size_read(inode) / PAGE_CACHE_SIZE) != page->index)
goto out;
end_byte_in_page = i_size_read(inode) % PAGE_CACHE_SIZE;
if (to > end_byte_in_page)
end_byte_in_page = to;
zero_user_segment(page, end_byte_in_page, PAGE_CACHE_SIZE);
out:
return 0;
}
/**
* ecryptfs_write_begin
* @file: The eCryptfs file
* @mapping: The eCryptfs object
* @pos: The file offset at which to start writing
* @len: Length of the write
* @flags: Various flags
* @pagep: Pointer to return the page
* @fsdata: Pointer to return fs data (unused)
*
* This function must zero any hole we create
*
* Returns zero on success; non-zero otherwise
*/
static int ecryptfs_write_begin(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
struct page *page;
loff_t prev_page_end_size;
int rc = 0;
page = grab_cache_page_write_begin(mapping, index, flags);
if (!page)
return -ENOMEM;
*pagep = page;
prev_page_end_size = ((loff_t)index << PAGE_CACHE_SHIFT);
if (!PageUptodate(page)) {
struct ecryptfs_crypt_stat *crypt_stat =
&ecryptfs_inode_to_private(mapping->host)->crypt_stat;
if (!(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
rc = ecryptfs_read_lower_page_segment(
page, index, 0, PAGE_CACHE_SIZE, mapping->host);
if (rc) {
printk(KERN_ERR "%s: Error attemping to read "
"lower page segment; rc = [%d]\n",
__func__, rc);
ClearPageUptodate(page);
goto out;
} else
SetPageUptodate(page);
} else if (crypt_stat->flags & ECRYPTFS_VIEW_AS_ENCRYPTED) {
if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR) {
rc = ecryptfs_copy_up_encrypted_with_header(
page, crypt_stat);
if (rc) {
printk(KERN_ERR "%s: Error attempting "
"to copy the encrypted content "
"from the lower file whilst "
"inserting the metadata from "
"the xattr into the header; rc "
"= [%d]\n", __func__, rc);
ClearPageUptodate(page);
goto out;
}
SetPageUptodate(page);
} else {
rc = ecryptfs_read_lower_page_segment(
page, index, 0, PAGE_CACHE_SIZE,
mapping->host);
if (rc) {
printk(KERN_ERR "%s: Error reading "
"page; rc = [%d]\n",
__func__, rc);
ClearPageUptodate(page);
goto out;
}
SetPageUptodate(page);
}
} else {
if (prev_page_end_size
>= i_size_read(page->mapping->host)) {
zero_user(page, 0, PAGE_CACHE_SIZE);
} else {
rc = ecryptfs_decrypt_page(page);
if (rc) {
printk(KERN_ERR "%s: Error decrypting "
"page at index [%ld]; "
"rc = [%d]\n",
__func__, page->index, rc);
ClearPageUptodate(page);
goto out;
}
}
SetPageUptodate(page);
}
}
/* If creating a page or more of holes, zero them out via truncate.
* Note, this will increase i_size. */
if (index != 0) {
if (prev_page_end_size > i_size_read(page->mapping->host)) {
rc = ecryptfs_truncate(file->f_path.dentry,
prev_page_end_size);
if (rc) {
printk(KERN_ERR "%s: Error on attempt to "
"truncate to (higher) offset [%lld];"
" rc = [%d]\n", __func__,
prev_page_end_size, rc);
goto out;
}
}
}
/* Writing to a new page, and creating a small hole from start
* of page? Zero it out. */
if ((i_size_read(mapping->host) == prev_page_end_size)
&& (pos != 0))
zero_user(page, 0, PAGE_CACHE_SIZE);
out:
if (unlikely(rc)) {
unlock_page(page);
page_cache_release(page);
*pagep = NULL;
}
return rc;
}
/**
* ecryptfs_write_inode_size_to_header
*
* Writes the lower file size to the first 8 bytes of the header.
*
* Returns zero on success; non-zero on error.
*/
static int ecryptfs_write_inode_size_to_header(struct inode *ecryptfs_inode)
{
char *file_size_virt;
int rc;
file_size_virt = kmalloc(sizeof(u64), GFP_KERNEL);
if (!file_size_virt) {
rc = -ENOMEM;
goto out;
}
put_unaligned_be64(i_size_read(ecryptfs_inode), file_size_virt);
rc = ecryptfs_write_lower(ecryptfs_inode, file_size_virt, 0,
sizeof(u64));
kfree(file_size_virt);
if (rc < 0)
printk(KERN_ERR "%s: Error writing file size to header; "
"rc = [%d]\n", __func__, rc);
else
rc = 0;
out:
return rc;
}
struct kmem_cache *ecryptfs_xattr_cache;
static int ecryptfs_write_inode_size_to_xattr(struct inode *ecryptfs_inode)
{
ssize_t size;
void *xattr_virt;
struct dentry *lower_dentry =
ecryptfs_inode_to_private(ecryptfs_inode)->lower_file->f_dentry;
struct inode *lower_inode = lower_dentry->d_inode;
int rc;
if (!lower_inode->i_op->getxattr || !lower_inode->i_op->setxattr) {
printk(KERN_WARNING
"No support for setting xattr in lower filesystem\n");
rc = -ENOSYS;
goto out;
}
xattr_virt = kmem_cache_alloc(ecryptfs_xattr_cache, GFP_KERNEL);
if (!xattr_virt) {
printk(KERN_ERR "Out of memory whilst attempting to write "
"inode size to xattr\n");
rc = -ENOMEM;
goto out;
}
mutex_lock(&lower_inode->i_mutex);
size = lower_inode->i_op->getxattr(lower_dentry, ECRYPTFS_XATTR_NAME,
xattr_virt, PAGE_CACHE_SIZE);
if (size < 0)
size = 8;
put_unaligned_be64(i_size_read(ecryptfs_inode), xattr_virt);
rc = lower_inode->i_op->setxattr(lower_dentry, ECRYPTFS_XATTR_NAME,
xattr_virt, size, 0);
mutex_unlock(&lower_inode->i_mutex);
if (rc)
printk(KERN_ERR "Error whilst attempting to write inode size "
"to lower file xattr; rc = [%d]\n", rc);
kmem_cache_free(ecryptfs_xattr_cache, xattr_virt);
out:
return rc;
}
int ecryptfs_write_inode_size_to_metadata(struct inode *ecryptfs_inode)
{
struct ecryptfs_crypt_stat *crypt_stat;
crypt_stat = &ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
BUG_ON(!(crypt_stat->flags & ECRYPTFS_ENCRYPTED));
if (crypt_stat->flags & ECRYPTFS_METADATA_IN_XATTR)
return ecryptfs_write_inode_size_to_xattr(ecryptfs_inode);
else
return ecryptfs_write_inode_size_to_header(ecryptfs_inode);
}
/**
* ecryptfs_write_end
* @file: The eCryptfs file object
* @mapping: The eCryptfs object
* @pos: The file position
* @len: The length of the data (unused)
* @copied: The amount of data copied
* @page: The eCryptfs page
* @fsdata: The fsdata (unused)
*/
static int ecryptfs_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
unsigned from = pos & (PAGE_CACHE_SIZE - 1);
unsigned to = from + copied;
struct inode *ecryptfs_inode = mapping->host;
struct ecryptfs_crypt_stat *crypt_stat =
&ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
int rc;
ecryptfs_printk(KERN_DEBUG, "Calling fill_zeros_to_end_of_page"
"(page w/ index = [0x%.16lx], to = [%d])\n", index, to);
if (!(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
rc = ecryptfs_write_lower_page_segment(ecryptfs_inode, page, 0,
to);
if (!rc) {
rc = copied;
fsstack_copy_inode_size(ecryptfs_inode,
ecryptfs_inode_to_lower(ecryptfs_inode));
}
goto out;
}
/* Fills in zeros if 'to' goes beyond inode size */
rc = fill_zeros_to_end_of_page(page, to);
if (rc) {
ecryptfs_printk(KERN_WARNING, "Error attempting to fill "
"zeros in page with index = [0x%.16lx]\n", index);
goto out;
}
rc = ecryptfs_encrypt_page(page);
if (rc) {
ecryptfs_printk(KERN_WARNING, "Error encrypting page (upper "
"index [0x%.16lx])\n", index);
goto out;
}
if (pos + copied > i_size_read(ecryptfs_inode)) {
i_size_write(ecryptfs_inode, pos + copied);
ecryptfs_printk(KERN_DEBUG, "Expanded file size to "
"[0x%.16llx]\n",
(unsigned long long)i_size_read(ecryptfs_inode));
}
rc = ecryptfs_write_inode_size_to_metadata(ecryptfs_inode);
if (rc)
printk(KERN_ERR "Error writing inode size to metadata; "
"rc = [%d]\n", rc);
else
rc = copied;
out:
unlock_page(page);
page_cache_release(page);
return rc;
}
static sector_t ecryptfs_bmap(struct address_space *mapping, sector_t block)
{
int rc = 0;
struct inode *inode;
struct inode *lower_inode;
inode = (struct inode *)mapping->host;
lower_inode = ecryptfs_inode_to_lower(inode);
if (lower_inode->i_mapping->a_ops->bmap)
rc = lower_inode->i_mapping->a_ops->bmap(lower_inode->i_mapping,
block);
return rc;
}
const struct address_space_operations ecryptfs_aops = {
.writepage = ecryptfs_writepage,
.readpage = ecryptfs_readpage,
.write_begin = ecryptfs_write_begin,
.write_end = ecryptfs_write_end,
.bmap = ecryptfs_bmap,
};
| gpl-2.0 |
anderco/linux | drivers/hwmon/wm8350-hwmon.c | 1548 | 3134 | /*
* drivers/hwmon/wm8350-hwmon.c - Wolfson Microelectronics WM8350 PMIC
* hardware monitoring features.
*
* Copyright (C) 2009 Wolfson Microelectronics plc
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/mfd/wm8350/core.h>
#include <linux/mfd/wm8350/comparator.h>
static const char * const input_names[] = {
[WM8350_AUXADC_USB] = "USB",
[WM8350_AUXADC_LINE] = "Line",
[WM8350_AUXADC_BATT] = "Battery",
};
static ssize_t show_voltage(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct wm8350 *wm8350 = dev_get_drvdata(dev);
int channel = to_sensor_dev_attr(attr)->index;
int val;
val = wm8350_read_auxadc(wm8350, channel, 0, 0) * WM8350_AUX_COEFF;
val = DIV_ROUND_CLOSEST(val, 1000);
return sprintf(buf, "%d\n", val);
}
static ssize_t show_label(struct device *dev,
struct device_attribute *attr, char *buf)
{
int channel = to_sensor_dev_attr(attr)->index;
return sprintf(buf, "%s\n", input_names[channel]);
}
#define WM8350_NAMED_VOLTAGE(id, name) \
static SENSOR_DEVICE_ATTR(in##id##_input, S_IRUGO, show_voltage,\
NULL, name); \
static SENSOR_DEVICE_ATTR(in##id##_label, S_IRUGO, show_label, \
NULL, name)
WM8350_NAMED_VOLTAGE(0, WM8350_AUXADC_USB);
WM8350_NAMED_VOLTAGE(1, WM8350_AUXADC_BATT);
WM8350_NAMED_VOLTAGE(2, WM8350_AUXADC_LINE);
static struct attribute *wm8350_attrs[] = {
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in0_label.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in1_label.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in2_label.dev_attr.attr,
NULL,
};
ATTRIBUTE_GROUPS(wm8350);
static int wm8350_hwmon_probe(struct platform_device *pdev)
{
struct wm8350 *wm8350 = platform_get_drvdata(pdev);
struct device *hwmon_dev;
hwmon_dev = devm_hwmon_device_register_with_groups(&pdev->dev, "wm8350",
wm8350,
wm8350_groups);
return PTR_ERR_OR_ZERO(hwmon_dev);
}
static struct platform_driver wm8350_hwmon_driver = {
.probe = wm8350_hwmon_probe,
.driver = {
.name = "wm8350-hwmon",
},
};
module_platform_driver(wm8350_hwmon_driver);
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("WM8350 Hardware Monitoring");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm8350-hwmon");
| gpl-2.0 |
Rockman18/kernel-lgnas | drivers/ieee1394/config_roms.c | 1804 | 4579 | /*
* IEEE 1394 for Linux
*
* ConfigROM entries
*
* Copyright (C) 2004 Ben Collins
*
* This code is licensed under the GPL. See the file COPYING in the root
* directory of the kernel sources for details.
*/
#include <linux/types.h>
#include "csr1212.h"
#include "ieee1394.h"
#include "ieee1394_types.h"
#include "hosts.h"
#include "ieee1394_core.h"
#include "highlevel.h"
#include "csr.h"
#include "config_roms.h"
struct hpsb_config_rom_entry {
const char *name;
/* Base initialization, called at module load */
int (*init)(void);
/* Cleanup called at module exit */
void (*cleanup)(void);
/* The flag added to host->config_roms */
unsigned int flag;
};
/* The default host entry. This must succeed. */
int hpsb_default_host_entry(struct hpsb_host *host)
{
struct csr1212_keyval *root;
struct csr1212_keyval *vend_id = NULL;
struct csr1212_keyval *text = NULL;
char csr_name[128];
int ret;
sprintf(csr_name, "Linux - %s", host->driver->name);
root = host->csr.rom->root_kv;
vend_id = csr1212_new_immediate(CSR1212_KV_ID_VENDOR, host->csr.guid_hi >> 8);
text = csr1212_new_string_descriptor_leaf(csr_name);
if (!vend_id || !text) {
if (vend_id)
csr1212_release_keyval(vend_id);
if (text)
csr1212_release_keyval(text);
csr1212_destroy_csr(host->csr.rom);
return -ENOMEM;
}
csr1212_associate_keyval(vend_id, text);
csr1212_release_keyval(text);
ret = csr1212_attach_keyval_to_directory(root, vend_id);
csr1212_release_keyval(vend_id);
if (ret != CSR1212_SUCCESS) {
csr1212_destroy_csr(host->csr.rom);
return -ENOMEM;
}
host->update_config_rom = 1;
return 0;
}
#ifdef CONFIG_IEEE1394_ETH1394_ROM_ENTRY
#include "eth1394.h"
static struct csr1212_keyval *ip1394_ud;
static int config_rom_ip1394_init(void)
{
struct csr1212_keyval *spec_id = NULL;
struct csr1212_keyval *spec_desc = NULL;
struct csr1212_keyval *ver = NULL;
struct csr1212_keyval *ver_desc = NULL;
int ret = -ENOMEM;
ip1394_ud = csr1212_new_directory(CSR1212_KV_ID_UNIT);
spec_id = csr1212_new_immediate(CSR1212_KV_ID_SPECIFIER_ID,
ETHER1394_GASP_SPECIFIER_ID);
spec_desc = csr1212_new_string_descriptor_leaf("IANA");
ver = csr1212_new_immediate(CSR1212_KV_ID_VERSION,
ETHER1394_GASP_VERSION);
ver_desc = csr1212_new_string_descriptor_leaf("IPv4");
if (!ip1394_ud || !spec_id || !spec_desc || !ver || !ver_desc)
goto ip1394_fail;
csr1212_associate_keyval(spec_id, spec_desc);
csr1212_associate_keyval(ver, ver_desc);
if (csr1212_attach_keyval_to_directory(ip1394_ud, spec_id)
== CSR1212_SUCCESS &&
csr1212_attach_keyval_to_directory(ip1394_ud, ver)
== CSR1212_SUCCESS)
ret = 0;
ip1394_fail:
if (ret && ip1394_ud) {
csr1212_release_keyval(ip1394_ud);
ip1394_ud = NULL;
}
if (spec_id)
csr1212_release_keyval(spec_id);
if (spec_desc)
csr1212_release_keyval(spec_desc);
if (ver)
csr1212_release_keyval(ver);
if (ver_desc)
csr1212_release_keyval(ver_desc);
return ret;
}
static void config_rom_ip1394_cleanup(void)
{
if (ip1394_ud) {
csr1212_release_keyval(ip1394_ud);
ip1394_ud = NULL;
}
}
int hpsb_config_rom_ip1394_add(struct hpsb_host *host)
{
if (!ip1394_ud)
return -ENODEV;
if (csr1212_attach_keyval_to_directory(host->csr.rom->root_kv,
ip1394_ud) != CSR1212_SUCCESS)
return -ENOMEM;
host->config_roms |= HPSB_CONFIG_ROM_ENTRY_IP1394;
host->update_config_rom = 1;
return 0;
}
EXPORT_SYMBOL_GPL(hpsb_config_rom_ip1394_add);
void hpsb_config_rom_ip1394_remove(struct hpsb_host *host)
{
csr1212_detach_keyval_from_directory(host->csr.rom->root_kv, ip1394_ud);
host->config_roms &= ~HPSB_CONFIG_ROM_ENTRY_IP1394;
host->update_config_rom = 1;
}
EXPORT_SYMBOL_GPL(hpsb_config_rom_ip1394_remove);
static struct hpsb_config_rom_entry ip1394_entry = {
.name = "ip1394",
.init = config_rom_ip1394_init,
.cleanup = config_rom_ip1394_cleanup,
.flag = HPSB_CONFIG_ROM_ENTRY_IP1394,
};
#endif /* CONFIG_IEEE1394_ETH1394_ROM_ENTRY */
static struct hpsb_config_rom_entry *const config_rom_entries[] = {
#ifdef CONFIG_IEEE1394_ETH1394_ROM_ENTRY
&ip1394_entry,
#endif
};
/* Initialize all config roms */
int hpsb_init_config_roms(void)
{
int i, error = 0;
for (i = 0; i < ARRAY_SIZE(config_rom_entries); i++)
if (config_rom_entries[i]->init()) {
HPSB_ERR("Failed to initialize config rom entry `%s'",
config_rom_entries[i]->name);
error = -1;
}
return error;
}
/* Cleanup all config roms */
void hpsb_cleanup_config_roms(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(config_rom_entries); i++)
config_rom_entries[i]->cleanup();
}
| gpl-2.0 |
aloksinha2001/Linux3188 | arch/arm/mach-at91/at91sam9260.c | 1804 | 11091 | /*
* arch/arm/mach-at91/at91sam9260.c
*
* Copyright (C) 2006 SAN People
*
* 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/pm.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/cpu.h>
#include <mach/at91sam9260.h>
#include <mach/at91_pmc.h>
#include <mach/at91_rstc.h>
#include <mach/at91_shdwc.h>
#include "generic.h"
#include "clock.h"
static struct map_desc at91sam9260_io_desc[] __initdata = {
{
.virtual = AT91_VA_BASE_SYS,
.pfn = __phys_to_pfn(AT91_BASE_SYS),
.length = SZ_16K,
.type = MT_DEVICE,
}
};
static struct map_desc at91sam9260_sram_desc[] __initdata = {
{
.virtual = AT91_IO_VIRT_BASE - AT91SAM9260_SRAM0_SIZE,
.pfn = __phys_to_pfn(AT91SAM9260_SRAM0_BASE),
.length = AT91SAM9260_SRAM0_SIZE,
.type = MT_DEVICE,
}, {
.virtual = AT91_IO_VIRT_BASE - AT91SAM9260_SRAM0_SIZE - AT91SAM9260_SRAM1_SIZE,
.pfn = __phys_to_pfn(AT91SAM9260_SRAM1_BASE),
.length = AT91SAM9260_SRAM1_SIZE,
.type = MT_DEVICE,
}
};
static struct map_desc at91sam9g20_sram_desc[] __initdata = {
{
.virtual = AT91_IO_VIRT_BASE - AT91SAM9G20_SRAM0_SIZE,
.pfn = __phys_to_pfn(AT91SAM9G20_SRAM0_BASE),
.length = AT91SAM9G20_SRAM0_SIZE,
.type = MT_DEVICE,
}, {
.virtual = AT91_IO_VIRT_BASE - AT91SAM9G20_SRAM0_SIZE - AT91SAM9G20_SRAM1_SIZE,
.pfn = __phys_to_pfn(AT91SAM9G20_SRAM1_BASE),
.length = AT91SAM9G20_SRAM1_SIZE,
.type = MT_DEVICE,
}
};
static struct map_desc at91sam9xe_sram_desc[] __initdata = {
{
.pfn = __phys_to_pfn(AT91SAM9XE_SRAM_BASE),
.type = MT_DEVICE,
}
};
/* --------------------------------------------------------------------
* Clocks
* -------------------------------------------------------------------- */
/*
* The peripheral clocks.
*/
static struct clk pioA_clk = {
.name = "pioA_clk",
.pmc_mask = 1 << AT91SAM9260_ID_PIOA,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioB_clk = {
.name = "pioB_clk",
.pmc_mask = 1 << AT91SAM9260_ID_PIOB,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioC_clk = {
.name = "pioC_clk",
.pmc_mask = 1 << AT91SAM9260_ID_PIOC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk adc_clk = {
.name = "adc_clk",
.pmc_mask = 1 << AT91SAM9260_ID_ADC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart0_clk = {
.name = "usart0_clk",
.pmc_mask = 1 << AT91SAM9260_ID_US0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart1_clk = {
.name = "usart1_clk",
.pmc_mask = 1 << AT91SAM9260_ID_US1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart2_clk = {
.name = "usart2_clk",
.pmc_mask = 1 << AT91SAM9260_ID_US2,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk mmc_clk = {
.name = "mci_clk",
.pmc_mask = 1 << AT91SAM9260_ID_MCI,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk udc_clk = {
.name = "udc_clk",
.pmc_mask = 1 << AT91SAM9260_ID_UDP,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk twi_clk = {
.name = "twi_clk",
.pmc_mask = 1 << AT91SAM9260_ID_TWI,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk spi0_clk = {
.name = "spi0_clk",
.pmc_mask = 1 << AT91SAM9260_ID_SPI0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk spi1_clk = {
.name = "spi1_clk",
.pmc_mask = 1 << AT91SAM9260_ID_SPI1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ssc_clk = {
.name = "ssc_clk",
.pmc_mask = 1 << AT91SAM9260_ID_SSC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc0_clk = {
.name = "tc0_clk",
.pmc_mask = 1 << AT91SAM9260_ID_TC0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc1_clk = {
.name = "tc1_clk",
.pmc_mask = 1 << AT91SAM9260_ID_TC1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc2_clk = {
.name = "tc2_clk",
.pmc_mask = 1 << AT91SAM9260_ID_TC2,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ohci_clk = {
.name = "ohci_clk",
.pmc_mask = 1 << AT91SAM9260_ID_UHP,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk macb_clk = {
.name = "macb_clk",
.pmc_mask = 1 << AT91SAM9260_ID_EMAC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk isi_clk = {
.name = "isi_clk",
.pmc_mask = 1 << AT91SAM9260_ID_ISI,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart3_clk = {
.name = "usart3_clk",
.pmc_mask = 1 << AT91SAM9260_ID_US3,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart4_clk = {
.name = "usart4_clk",
.pmc_mask = 1 << AT91SAM9260_ID_US4,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart5_clk = {
.name = "usart5_clk",
.pmc_mask = 1 << AT91SAM9260_ID_US5,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc3_clk = {
.name = "tc3_clk",
.pmc_mask = 1 << AT91SAM9260_ID_TC3,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc4_clk = {
.name = "tc4_clk",
.pmc_mask = 1 << AT91SAM9260_ID_TC4,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc5_clk = {
.name = "tc5_clk",
.pmc_mask = 1 << AT91SAM9260_ID_TC5,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk *periph_clocks[] __initdata = {
&pioA_clk,
&pioB_clk,
&pioC_clk,
&adc_clk,
&usart0_clk,
&usart1_clk,
&usart2_clk,
&mmc_clk,
&udc_clk,
&twi_clk,
&spi0_clk,
&spi1_clk,
&ssc_clk,
&tc0_clk,
&tc1_clk,
&tc2_clk,
&ohci_clk,
&macb_clk,
&isi_clk,
&usart3_clk,
&usart4_clk,
&usart5_clk,
&tc3_clk,
&tc4_clk,
&tc5_clk,
// irq0 .. irq2
};
static struct clk_lookup periph_clocks_lookups[] = {
CLKDEV_CON_DEV_ID("spi_clk", "atmel_spi.0", &spi0_clk),
CLKDEV_CON_DEV_ID("spi_clk", "atmel_spi.1", &spi1_clk),
CLKDEV_CON_DEV_ID("t0_clk", "atmel_tcb.0", &tc0_clk),
CLKDEV_CON_DEV_ID("t1_clk", "atmel_tcb.0", &tc1_clk),
CLKDEV_CON_DEV_ID("t2_clk", "atmel_tcb.0", &tc2_clk),
CLKDEV_CON_DEV_ID("t0_clk", "atmel_tcb.1", &tc3_clk),
CLKDEV_CON_DEV_ID("t1_clk", "atmel_tcb.1", &tc4_clk),
CLKDEV_CON_DEV_ID("t2_clk", "atmel_tcb.1", &tc5_clk),
CLKDEV_CON_DEV_ID("pclk", "ssc.0", &ssc_clk),
};
static struct clk_lookup usart_clocks_lookups[] = {
CLKDEV_CON_DEV_ID("usart", "atmel_usart.0", &mck),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.1", &usart0_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.2", &usart1_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.3", &usart2_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.4", &usart3_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.5", &usart4_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.6", &usart5_clk),
};
/*
* The two programmable clocks.
* You must configure pin multiplexing to bring these signals out.
*/
static struct clk pck0 = {
.name = "pck0",
.pmc_mask = AT91_PMC_PCK0,
.type = CLK_TYPE_PROGRAMMABLE,
.id = 0,
};
static struct clk pck1 = {
.name = "pck1",
.pmc_mask = AT91_PMC_PCK1,
.type = CLK_TYPE_PROGRAMMABLE,
.id = 1,
};
static void __init at91sam9260_register_clocks(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(periph_clocks); i++)
clk_register(periph_clocks[i]);
clkdev_add_table(periph_clocks_lookups,
ARRAY_SIZE(periph_clocks_lookups));
clkdev_add_table(usart_clocks_lookups,
ARRAY_SIZE(usart_clocks_lookups));
clk_register(&pck0);
clk_register(&pck1);
}
static struct clk_lookup console_clock_lookup;
void __init at91sam9260_set_console_clock(int id)
{
if (id >= ARRAY_SIZE(usart_clocks_lookups))
return;
console_clock_lookup.con_id = "usart";
console_clock_lookup.clk = usart_clocks_lookups[id].clk;
clkdev_add(&console_clock_lookup);
}
/* --------------------------------------------------------------------
* GPIO
* -------------------------------------------------------------------- */
static struct at91_gpio_bank at91sam9260_gpio[] = {
{
.id = AT91SAM9260_ID_PIOA,
.offset = AT91_PIOA,
.clock = &pioA_clk,
}, {
.id = AT91SAM9260_ID_PIOB,
.offset = AT91_PIOB,
.clock = &pioB_clk,
}, {
.id = AT91SAM9260_ID_PIOC,
.offset = AT91_PIOC,
.clock = &pioC_clk,
}
};
static void at91sam9260_poweroff(void)
{
at91_sys_write(AT91_SHDW_CR, AT91_SHDW_KEY | AT91_SHDW_SHDW);
}
/* --------------------------------------------------------------------
* AT91SAM9260 processor initialization
* -------------------------------------------------------------------- */
static void __init at91sam9xe_map_io(void)
{
unsigned long cidr, sram_size;
cidr = at91_sys_read(AT91_DBGU_CIDR);
switch (cidr & AT91_CIDR_SRAMSIZ) {
case AT91_CIDR_SRAMSIZ_32K:
sram_size = 2 * SZ_16K;
break;
case AT91_CIDR_SRAMSIZ_16K:
default:
sram_size = SZ_16K;
}
at91sam9xe_sram_desc->virtual = AT91_IO_VIRT_BASE - sram_size;
at91sam9xe_sram_desc->length = sram_size;
iotable_init(at91sam9xe_sram_desc, ARRAY_SIZE(at91sam9xe_sram_desc));
}
void __init at91sam9260_map_io(void)
{
/* Map peripherals */
iotable_init(at91sam9260_io_desc, ARRAY_SIZE(at91sam9260_io_desc));
if (cpu_is_at91sam9xe())
at91sam9xe_map_io();
else if (cpu_is_at91sam9g20())
iotable_init(at91sam9g20_sram_desc, ARRAY_SIZE(at91sam9g20_sram_desc));
else
iotable_init(at91sam9260_sram_desc, ARRAY_SIZE(at91sam9260_sram_desc));
}
void __init at91sam9260_initialize(unsigned long main_clock)
{
at91_arch_reset = at91sam9_alt_reset;
pm_power_off = at91sam9260_poweroff;
at91_extern_irq = (1 << AT91SAM9260_ID_IRQ0) | (1 << AT91SAM9260_ID_IRQ1)
| (1 << AT91SAM9260_ID_IRQ2);
/* Init clock subsystem */
at91_clock_init(main_clock);
/* Register the processor-specific clocks */
at91sam9260_register_clocks();
/* Register GPIO subsystem */
at91_gpio_init(at91sam9260_gpio, 3);
}
/* --------------------------------------------------------------------
* Interrupt initialization
* -------------------------------------------------------------------- */
/*
* The default interrupt priority levels (0 = lowest, 7 = highest).
*/
static unsigned int at91sam9260_default_irq_priority[NR_AIC_IRQS] __initdata = {
7, /* Advanced Interrupt Controller */
7, /* System Peripherals */
1, /* Parallel IO Controller A */
1, /* Parallel IO Controller B */
1, /* Parallel IO Controller C */
0, /* Analog-to-Digital Converter */
5, /* USART 0 */
5, /* USART 1 */
5, /* USART 2 */
0, /* Multimedia Card Interface */
2, /* USB Device Port */
6, /* Two-Wire Interface */
5, /* Serial Peripheral Interface 0 */
5, /* Serial Peripheral Interface 1 */
5, /* Serial Synchronous Controller */
0,
0,
0, /* Timer Counter 0 */
0, /* Timer Counter 1 */
0, /* Timer Counter 2 */
2, /* USB Host port */
3, /* Ethernet */
0, /* Image Sensor Interface */
5, /* USART 3 */
5, /* USART 4 */
5, /* USART 5 */
0, /* Timer Counter 3 */
0, /* Timer Counter 4 */
0, /* Timer Counter 5 */
0, /* Advanced Interrupt Controller */
0, /* Advanced Interrupt Controller */
0, /* Advanced Interrupt Controller */
};
void __init at91sam9260_init_interrupts(unsigned int priority[NR_AIC_IRQS])
{
if (!priority)
priority = at91sam9260_default_irq_priority;
/* Initialize the AIC interrupt controller */
at91_aic_init(priority);
/* Enable GPIO interrupts */
at91_gpio_irq_setup();
}
| gpl-2.0 |
javilonas/Enki-SM-G901F_OLD-5.X | drivers/mfd/tps65090.c | 2060 | 7229 | /*
* Core driver for TI TPS65090 PMIC family
*
* Copyright (c) 2012, NVIDIA CORPORATION. All rights reserved.
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/mfd/core.h>
#include <linux/mfd/tps65090.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/err.h>
#define NUM_INT_REG 2
#define TOTAL_NUM_REG 0x18
/* interrupt status registers */
#define TPS65090_INT_STS 0x0
#define TPS65090_INT_STS2 0x1
/* interrupt mask registers */
#define TPS65090_INT_MSK 0x2
#define TPS65090_INT_MSK2 0x3
#define TPS65090_INT1_MASK_VAC_STATUS_CHANGE 1
#define TPS65090_INT1_MASK_VSYS_STATUS_CHANGE 2
#define TPS65090_INT1_MASK_BAT_STATUS_CHANGE 3
#define TPS65090_INT1_MASK_CHARGING_STATUS_CHANGE 4
#define TPS65090_INT1_MASK_CHARGING_COMPLETE 5
#define TPS65090_INT1_MASK_OVERLOAD_DCDC1 6
#define TPS65090_INT1_MASK_OVERLOAD_DCDC2 7
#define TPS65090_INT2_MASK_OVERLOAD_DCDC3 0
#define TPS65090_INT2_MASK_OVERLOAD_FET1 1
#define TPS65090_INT2_MASK_OVERLOAD_FET2 2
#define TPS65090_INT2_MASK_OVERLOAD_FET3 3
#define TPS65090_INT2_MASK_OVERLOAD_FET4 4
#define TPS65090_INT2_MASK_OVERLOAD_FET5 5
#define TPS65090_INT2_MASK_OVERLOAD_FET6 6
#define TPS65090_INT2_MASK_OVERLOAD_FET7 7
static struct resource charger_resources[] = {
{
.start = TPS65090_IRQ_VAC_STATUS_CHANGE,
.end = TPS65090_IRQ_VAC_STATUS_CHANGE,
.flags = IORESOURCE_IRQ,
}
};
static struct mfd_cell tps65090s[] = {
{
.name = "tps65090-pmic",
},
{
.name = "tps65090-charger",
.num_resources = ARRAY_SIZE(charger_resources),
.resources = &charger_resources[0],
.of_compatible = "ti,tps65090-charger",
},
};
static const struct regmap_irq tps65090_irqs[] = {
/* INT1 IRQs*/
[TPS65090_IRQ_VAC_STATUS_CHANGE] = {
.mask = TPS65090_INT1_MASK_VAC_STATUS_CHANGE,
},
[TPS65090_IRQ_VSYS_STATUS_CHANGE] = {
.mask = TPS65090_INT1_MASK_VSYS_STATUS_CHANGE,
},
[TPS65090_IRQ_BAT_STATUS_CHANGE] = {
.mask = TPS65090_INT1_MASK_BAT_STATUS_CHANGE,
},
[TPS65090_IRQ_CHARGING_STATUS_CHANGE] = {
.mask = TPS65090_INT1_MASK_CHARGING_STATUS_CHANGE,
},
[TPS65090_IRQ_CHARGING_COMPLETE] = {
.mask = TPS65090_INT1_MASK_CHARGING_COMPLETE,
},
[TPS65090_IRQ_OVERLOAD_DCDC1] = {
.mask = TPS65090_INT1_MASK_OVERLOAD_DCDC1,
},
[TPS65090_IRQ_OVERLOAD_DCDC2] = {
.mask = TPS65090_INT1_MASK_OVERLOAD_DCDC2,
},
/* INT2 IRQs*/
[TPS65090_IRQ_OVERLOAD_DCDC3] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_DCDC3,
},
[TPS65090_IRQ_OVERLOAD_FET1] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_FET1,
},
[TPS65090_IRQ_OVERLOAD_FET2] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_FET2,
},
[TPS65090_IRQ_OVERLOAD_FET3] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_FET3,
},
[TPS65090_IRQ_OVERLOAD_FET4] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_FET4,
},
[TPS65090_IRQ_OVERLOAD_FET5] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_FET5,
},
[TPS65090_IRQ_OVERLOAD_FET6] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_FET6,
},
[TPS65090_IRQ_OVERLOAD_FET7] = {
.reg_offset = 1,
.mask = TPS65090_INT2_MASK_OVERLOAD_FET7,
},
};
static struct regmap_irq_chip tps65090_irq_chip = {
.name = "tps65090",
.irqs = tps65090_irqs,
.num_irqs = ARRAY_SIZE(tps65090_irqs),
.num_regs = NUM_INT_REG,
.status_base = TPS65090_INT_STS,
.mask_base = TPS65090_INT_MSK,
.mask_invert = true,
};
static bool is_volatile_reg(struct device *dev, unsigned int reg)
{
if ((reg == TPS65090_INT_STS) || (reg == TPS65090_INT_STS2))
return true;
else
return false;
}
static const struct regmap_config tps65090_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = TOTAL_NUM_REG,
.num_reg_defaults_raw = TOTAL_NUM_REG,
.cache_type = REGCACHE_RBTREE,
.volatile_reg = is_volatile_reg,
};
#ifdef CONFIG_OF
static const struct of_device_id tps65090_of_match[] = {
{ .compatible = "ti,tps65090",},
{},
};
MODULE_DEVICE_TABLE(of, tps65090_of_match);
#endif
static int tps65090_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tps65090_platform_data *pdata = client->dev.platform_data;
int irq_base = 0;
struct tps65090 *tps65090;
int ret;
if (!pdata && !client->dev.of_node) {
dev_err(&client->dev,
"tps65090 requires platform data or of_node\n");
return -EINVAL;
}
if (pdata)
irq_base = pdata->irq_base;
tps65090 = devm_kzalloc(&client->dev, sizeof(*tps65090), GFP_KERNEL);
if (!tps65090) {
dev_err(&client->dev, "mem alloc for tps65090 failed\n");
return -ENOMEM;
}
tps65090->dev = &client->dev;
i2c_set_clientdata(client, tps65090);
tps65090->rmap = devm_regmap_init_i2c(client, &tps65090_regmap_config);
if (IS_ERR(tps65090->rmap)) {
ret = PTR_ERR(tps65090->rmap);
dev_err(&client->dev, "regmap_init failed with err: %d\n", ret);
return ret;
}
if (client->irq) {
ret = regmap_add_irq_chip(tps65090->rmap, client->irq,
IRQF_ONESHOT | IRQF_TRIGGER_LOW, irq_base,
&tps65090_irq_chip, &tps65090->irq_data);
if (ret) {
dev_err(&client->dev,
"IRQ init failed with err: %d\n", ret);
return ret;
}
}
ret = mfd_add_devices(tps65090->dev, -1, tps65090s,
ARRAY_SIZE(tps65090s), NULL,
0, regmap_irq_get_domain(tps65090->irq_data));
if (ret) {
dev_err(&client->dev, "add mfd devices failed with err: %d\n",
ret);
goto err_irq_exit;
}
return 0;
err_irq_exit:
if (client->irq)
regmap_del_irq_chip(client->irq, tps65090->irq_data);
return ret;
}
static int tps65090_i2c_remove(struct i2c_client *client)
{
struct tps65090 *tps65090 = i2c_get_clientdata(client);
mfd_remove_devices(tps65090->dev);
if (client->irq)
regmap_del_irq_chip(client->irq, tps65090->irq_data);
return 0;
}
static const struct i2c_device_id tps65090_id_table[] = {
{ "tps65090", 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, tps65090_id_table);
static struct i2c_driver tps65090_driver = {
.driver = {
.name = "tps65090",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(tps65090_of_match),
},
.probe = tps65090_i2c_probe,
.remove = tps65090_i2c_remove,
.id_table = tps65090_id_table,
};
static int __init tps65090_init(void)
{
return i2c_add_driver(&tps65090_driver);
}
subsys_initcall(tps65090_init);
static void __exit tps65090_exit(void)
{
i2c_del_driver(&tps65090_driver);
}
module_exit(tps65090_exit);
MODULE_DESCRIPTION("TPS65090 core driver");
MODULE_AUTHOR("Venu Byravarasu <vbyravarasu@nvidia.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
k2wl/evolution_i9082 | drivers/infiniband/hw/qib/qib_sysfs.c | 2828 | 18053 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
* Copyright (c) 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/ctype.h>
#include "qib.h"
/**
* qib_parse_ushort - parse an unsigned short value in an arbitrary base
* @str: the string containing the number
* @valp: where to put the result
*
* Returns the number of bytes consumed, or negative value on error.
*/
static int qib_parse_ushort(const char *str, unsigned short *valp)
{
unsigned long val;
char *end;
int ret;
if (!isdigit(str[0])) {
ret = -EINVAL;
goto bail;
}
val = simple_strtoul(str, &end, 0);
if (val > 0xffff) {
ret = -EINVAL;
goto bail;
}
*valp = val;
ret = end + 1 - str;
if (ret == 0)
ret = -EINVAL;
bail:
return ret;
}
/* start of per-port functions */
/*
* Get/Set heartbeat enable. OR of 1=enabled, 2=auto
*/
static ssize_t show_hrtbt_enb(struct qib_pportdata *ppd, char *buf)
{
struct qib_devdata *dd = ppd->dd;
int ret;
ret = dd->f_get_ib_cfg(ppd, QIB_IB_CFG_HRTBT);
ret = scnprintf(buf, PAGE_SIZE, "%d\n", ret);
return ret;
}
static ssize_t store_hrtbt_enb(struct qib_pportdata *ppd, const char *buf,
size_t count)
{
struct qib_devdata *dd = ppd->dd;
int ret;
u16 val;
ret = qib_parse_ushort(buf, &val);
/*
* Set the "intentional" heartbeat enable per either of
* "Enable" and "Auto", as these are normally set together.
* This bit is consulted when leaving loopback mode,
* because entering loopback mode overrides it and automatically
* disables heartbeat.
*/
if (ret >= 0)
ret = dd->f_set_ib_cfg(ppd, QIB_IB_CFG_HRTBT, val);
if (ret < 0)
qib_dev_err(dd, "attempt to set invalid Heartbeat enable\n");
return ret < 0 ? ret : count;
}
static ssize_t store_loopback(struct qib_pportdata *ppd, const char *buf,
size_t count)
{
struct qib_devdata *dd = ppd->dd;
int ret = count, r;
r = dd->f_set_ib_loopback(ppd, buf);
if (r < 0)
ret = r;
return ret;
}
static ssize_t store_led_override(struct qib_pportdata *ppd, const char *buf,
size_t count)
{
struct qib_devdata *dd = ppd->dd;
int ret;
u16 val;
ret = qib_parse_ushort(buf, &val);
if (ret > 0)
qib_set_led_override(ppd, val);
else
qib_dev_err(dd, "attempt to set invalid LED override\n");
return ret < 0 ? ret : count;
}
static ssize_t show_status(struct qib_pportdata *ppd, char *buf)
{
ssize_t ret;
if (!ppd->statusp)
ret = -EINVAL;
else
ret = scnprintf(buf, PAGE_SIZE, "0x%llx\n",
(unsigned long long) *(ppd->statusp));
return ret;
}
/*
* For userland compatibility, these offsets must remain fixed.
* They are strings for QIB_STATUS_*
*/
static const char *qib_status_str[] = {
"Initted",
"",
"",
"",
"",
"Present",
"IB_link_up",
"IB_configured",
"",
"Fatal_Hardware_Error",
NULL,
};
static ssize_t show_status_str(struct qib_pportdata *ppd, char *buf)
{
int i, any;
u64 s;
ssize_t ret;
if (!ppd->statusp) {
ret = -EINVAL;
goto bail;
}
s = *(ppd->statusp);
*buf = '\0';
for (any = i = 0; s && qib_status_str[i]; i++) {
if (s & 1) {
/* if overflow */
if (any && strlcat(buf, " ", PAGE_SIZE) >= PAGE_SIZE)
break;
if (strlcat(buf, qib_status_str[i], PAGE_SIZE) >=
PAGE_SIZE)
break;
any = 1;
}
s >>= 1;
}
if (any)
strlcat(buf, "\n", PAGE_SIZE);
ret = strlen(buf);
bail:
return ret;
}
/* end of per-port functions */
/*
* Start of per-port file structures and support code
* Because we are fitting into other infrastructure, we have to supply the
* full set of kobject/sysfs_ops structures and routines.
*/
#define QIB_PORT_ATTR(name, mode, show, store) \
static struct qib_port_attr qib_port_attr_##name = \
__ATTR(name, mode, show, store)
struct qib_port_attr {
struct attribute attr;
ssize_t (*show)(struct qib_pportdata *, char *);
ssize_t (*store)(struct qib_pportdata *, const char *, size_t);
};
QIB_PORT_ATTR(loopback, S_IWUSR, NULL, store_loopback);
QIB_PORT_ATTR(led_override, S_IWUSR, NULL, store_led_override);
QIB_PORT_ATTR(hrtbt_enable, S_IWUSR | S_IRUGO, show_hrtbt_enb,
store_hrtbt_enb);
QIB_PORT_ATTR(status, S_IRUGO, show_status, NULL);
QIB_PORT_ATTR(status_str, S_IRUGO, show_status_str, NULL);
static struct attribute *port_default_attributes[] = {
&qib_port_attr_loopback.attr,
&qib_port_attr_led_override.attr,
&qib_port_attr_hrtbt_enable.attr,
&qib_port_attr_status.attr,
&qib_port_attr_status_str.attr,
NULL
};
static ssize_t qib_portattr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct qib_port_attr *pattr =
container_of(attr, struct qib_port_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, pport_kobj);
return pattr->show(ppd, buf);
}
static ssize_t qib_portattr_store(struct kobject *kobj,
struct attribute *attr, const char *buf, size_t len)
{
struct qib_port_attr *pattr =
container_of(attr, struct qib_port_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, pport_kobj);
return pattr->store(ppd, buf, len);
}
static void qib_port_release(struct kobject *kobj)
{
/* nothing to do since memory is freed by qib_free_devdata() */
}
static const struct sysfs_ops qib_port_ops = {
.show = qib_portattr_show,
.store = qib_portattr_store,
};
static struct kobj_type qib_port_ktype = {
.release = qib_port_release,
.sysfs_ops = &qib_port_ops,
.default_attrs = port_default_attributes
};
/* Start sl2vl */
#define QIB_SL2VL_ATTR(N) \
static struct qib_sl2vl_attr qib_sl2vl_attr_##N = { \
.attr = { .name = __stringify(N), .mode = 0444 }, \
.sl = N \
}
struct qib_sl2vl_attr {
struct attribute attr;
int sl;
};
QIB_SL2VL_ATTR(0);
QIB_SL2VL_ATTR(1);
QIB_SL2VL_ATTR(2);
QIB_SL2VL_ATTR(3);
QIB_SL2VL_ATTR(4);
QIB_SL2VL_ATTR(5);
QIB_SL2VL_ATTR(6);
QIB_SL2VL_ATTR(7);
QIB_SL2VL_ATTR(8);
QIB_SL2VL_ATTR(9);
QIB_SL2VL_ATTR(10);
QIB_SL2VL_ATTR(11);
QIB_SL2VL_ATTR(12);
QIB_SL2VL_ATTR(13);
QIB_SL2VL_ATTR(14);
QIB_SL2VL_ATTR(15);
static struct attribute *sl2vl_default_attributes[] = {
&qib_sl2vl_attr_0.attr,
&qib_sl2vl_attr_1.attr,
&qib_sl2vl_attr_2.attr,
&qib_sl2vl_attr_3.attr,
&qib_sl2vl_attr_4.attr,
&qib_sl2vl_attr_5.attr,
&qib_sl2vl_attr_6.attr,
&qib_sl2vl_attr_7.attr,
&qib_sl2vl_attr_8.attr,
&qib_sl2vl_attr_9.attr,
&qib_sl2vl_attr_10.attr,
&qib_sl2vl_attr_11.attr,
&qib_sl2vl_attr_12.attr,
&qib_sl2vl_attr_13.attr,
&qib_sl2vl_attr_14.attr,
&qib_sl2vl_attr_15.attr,
NULL
};
static ssize_t sl2vl_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct qib_sl2vl_attr *sattr =
container_of(attr, struct qib_sl2vl_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, sl2vl_kobj);
struct qib_ibport *qibp = &ppd->ibport_data;
return sprintf(buf, "%u\n", qibp->sl_to_vl[sattr->sl]);
}
static const struct sysfs_ops qib_sl2vl_ops = {
.show = sl2vl_attr_show,
};
static struct kobj_type qib_sl2vl_ktype = {
.release = qib_port_release,
.sysfs_ops = &qib_sl2vl_ops,
.default_attrs = sl2vl_default_attributes
};
/* End sl2vl */
/* Start diag_counters */
#define QIB_DIAGC_ATTR(N) \
static struct qib_diagc_attr qib_diagc_attr_##N = { \
.attr = { .name = __stringify(N), .mode = 0664 }, \
.counter = offsetof(struct qib_ibport, n_##N) \
}
struct qib_diagc_attr {
struct attribute attr;
size_t counter;
};
QIB_DIAGC_ATTR(rc_resends);
QIB_DIAGC_ATTR(rc_acks);
QIB_DIAGC_ATTR(rc_qacks);
QIB_DIAGC_ATTR(rc_delayed_comp);
QIB_DIAGC_ATTR(seq_naks);
QIB_DIAGC_ATTR(rdma_seq);
QIB_DIAGC_ATTR(rnr_naks);
QIB_DIAGC_ATTR(other_naks);
QIB_DIAGC_ATTR(rc_timeouts);
QIB_DIAGC_ATTR(loop_pkts);
QIB_DIAGC_ATTR(pkt_drops);
QIB_DIAGC_ATTR(dmawait);
QIB_DIAGC_ATTR(unaligned);
QIB_DIAGC_ATTR(rc_dupreq);
QIB_DIAGC_ATTR(rc_seqnak);
static struct attribute *diagc_default_attributes[] = {
&qib_diagc_attr_rc_resends.attr,
&qib_diagc_attr_rc_acks.attr,
&qib_diagc_attr_rc_qacks.attr,
&qib_diagc_attr_rc_delayed_comp.attr,
&qib_diagc_attr_seq_naks.attr,
&qib_diagc_attr_rdma_seq.attr,
&qib_diagc_attr_rnr_naks.attr,
&qib_diagc_attr_other_naks.attr,
&qib_diagc_attr_rc_timeouts.attr,
&qib_diagc_attr_loop_pkts.attr,
&qib_diagc_attr_pkt_drops.attr,
&qib_diagc_attr_dmawait.attr,
&qib_diagc_attr_unaligned.attr,
&qib_diagc_attr_rc_dupreq.attr,
&qib_diagc_attr_rc_seqnak.attr,
NULL
};
static ssize_t diagc_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct qib_diagc_attr *dattr =
container_of(attr, struct qib_diagc_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, diagc_kobj);
struct qib_ibport *qibp = &ppd->ibport_data;
return sprintf(buf, "%u\n", *(u32 *)((char *)qibp + dattr->counter));
}
static ssize_t diagc_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t size)
{
struct qib_diagc_attr *dattr =
container_of(attr, struct qib_diagc_attr, attr);
struct qib_pportdata *ppd =
container_of(kobj, struct qib_pportdata, diagc_kobj);
struct qib_ibport *qibp = &ppd->ibport_data;
char *endp;
long val = simple_strtol(buf, &endp, 0);
if (val < 0 || endp == buf)
return -EINVAL;
*(u32 *)((char *) qibp + dattr->counter) = val;
return size;
}
static const struct sysfs_ops qib_diagc_ops = {
.show = diagc_attr_show,
.store = diagc_attr_store,
};
static struct kobj_type qib_diagc_ktype = {
.release = qib_port_release,
.sysfs_ops = &qib_diagc_ops,
.default_attrs = diagc_default_attributes
};
/* End diag_counters */
/* end of per-port file structures and support code */
/*
* Start of per-unit (or driver, in some cases, but replicated
* per unit) functions (these get a device *)
*/
static ssize_t show_rev(struct device *device, struct device_attribute *attr,
char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
return sprintf(buf, "%x\n", dd_from_dev(dev)->minrev);
}
static ssize_t show_hca(struct device *device, struct device_attribute *attr,
char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int ret;
if (!dd->boardname)
ret = -EINVAL;
else
ret = scnprintf(buf, PAGE_SIZE, "%s\n", dd->boardname);
return ret;
}
static ssize_t show_version(struct device *device,
struct device_attribute *attr, char *buf)
{
/* The string printed here is already newline-terminated. */
return scnprintf(buf, PAGE_SIZE, "%s", (char *)ib_qib_version);
}
static ssize_t show_boardversion(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
/* The string printed here is already newline-terminated. */
return scnprintf(buf, PAGE_SIZE, "%s", dd->boardversion);
}
static ssize_t show_localbus_info(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
/* The string printed here is already newline-terminated. */
return scnprintf(buf, PAGE_SIZE, "%s", dd->lbus_info);
}
static ssize_t show_nctxts(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
/* Return the number of user ports (contexts) available. */
return scnprintf(buf, PAGE_SIZE, "%u\n", dd->cfgctxts -
dd->first_user_ctxt);
}
static ssize_t show_serial(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
buf[sizeof dd->serial] = '\0';
memcpy(buf, dd->serial, sizeof dd->serial);
strcat(buf, "\n");
return strlen(buf);
}
static ssize_t store_chip_reset(struct device *device,
struct device_attribute *attr, const char *buf,
size_t count)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int ret;
if (count < 5 || memcmp(buf, "reset", 5) || !dd->diag_client) {
ret = -EINVAL;
goto bail;
}
ret = qib_reset_device(dd->unit);
bail:
return ret < 0 ? ret : count;
}
static ssize_t show_logged_errs(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int idx, count;
/* force consistency with actual EEPROM */
if (qib_update_eeprom_log(dd) != 0)
return -ENXIO;
count = 0;
for (idx = 0; idx < QIB_EEP_LOG_CNT; ++idx) {
count += scnprintf(buf + count, PAGE_SIZE - count, "%d%c",
dd->eep_st_errs[idx],
idx == (QIB_EEP_LOG_CNT - 1) ? '\n' : ' ');
}
return count;
}
/*
* Dump tempsense regs. in decimal, to ease shell-scripts.
*/
static ssize_t show_tempsense(struct device *device,
struct device_attribute *attr, char *buf)
{
struct qib_ibdev *dev =
container_of(device, struct qib_ibdev, ibdev.dev);
struct qib_devdata *dd = dd_from_dev(dev);
int ret;
int idx;
u8 regvals[8];
ret = -ENXIO;
for (idx = 0; idx < 8; ++idx) {
if (idx == 6)
continue;
ret = dd->f_tempsense_rd(dd, idx);
if (ret < 0)
break;
regvals[idx] = ret;
}
if (idx == 8)
ret = scnprintf(buf, PAGE_SIZE, "%d %d %02X %02X %d %d\n",
*(signed char *)(regvals),
*(signed char *)(regvals + 1),
regvals[2], regvals[3],
*(signed char *)(regvals + 5),
*(signed char *)(regvals + 7));
return ret;
}
/*
* end of per-unit (or driver, in some cases, but replicated
* per unit) functions
*/
/* start of per-unit file structures and support code */
static DEVICE_ATTR(hw_rev, S_IRUGO, show_rev, NULL);
static DEVICE_ATTR(hca_type, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(board_id, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(version, S_IRUGO, show_version, NULL);
static DEVICE_ATTR(nctxts, S_IRUGO, show_nctxts, NULL);
static DEVICE_ATTR(serial, S_IRUGO, show_serial, NULL);
static DEVICE_ATTR(boardversion, S_IRUGO, show_boardversion, NULL);
static DEVICE_ATTR(logged_errors, S_IRUGO, show_logged_errs, NULL);
static DEVICE_ATTR(tempsense, S_IRUGO, show_tempsense, NULL);
static DEVICE_ATTR(localbus_info, S_IRUGO, show_localbus_info, NULL);
static DEVICE_ATTR(chip_reset, S_IWUSR, NULL, store_chip_reset);
static struct device_attribute *qib_attributes[] = {
&dev_attr_hw_rev,
&dev_attr_hca_type,
&dev_attr_board_id,
&dev_attr_version,
&dev_attr_nctxts,
&dev_attr_serial,
&dev_attr_boardversion,
&dev_attr_logged_errors,
&dev_attr_tempsense,
&dev_attr_localbus_info,
&dev_attr_chip_reset,
};
int qib_create_port_files(struct ib_device *ibdev, u8 port_num,
struct kobject *kobj)
{
struct qib_pportdata *ppd;
struct qib_devdata *dd = dd_from_ibdev(ibdev);
int ret;
if (!port_num || port_num > dd->num_pports) {
qib_dev_err(dd, "Skipping infiniband class with "
"invalid port %u\n", port_num);
ret = -ENODEV;
goto bail;
}
ppd = &dd->pport[port_num - 1];
ret = kobject_init_and_add(&ppd->pport_kobj, &qib_port_ktype, kobj,
"linkcontrol");
if (ret) {
qib_dev_err(dd, "Skipping linkcontrol sysfs info, "
"(err %d) port %u\n", ret, port_num);
goto bail;
}
kobject_uevent(&ppd->pport_kobj, KOBJ_ADD);
ret = kobject_init_and_add(&ppd->sl2vl_kobj, &qib_sl2vl_ktype, kobj,
"sl2vl");
if (ret) {
qib_dev_err(dd, "Skipping sl2vl sysfs info, "
"(err %d) port %u\n", ret, port_num);
goto bail_sl;
}
kobject_uevent(&ppd->sl2vl_kobj, KOBJ_ADD);
ret = kobject_init_and_add(&ppd->diagc_kobj, &qib_diagc_ktype, kobj,
"diag_counters");
if (ret) {
qib_dev_err(dd, "Skipping diag_counters sysfs info, "
"(err %d) port %u\n", ret, port_num);
goto bail_diagc;
}
kobject_uevent(&ppd->diagc_kobj, KOBJ_ADD);
return 0;
bail_diagc:
kobject_put(&ppd->sl2vl_kobj);
bail_sl:
kobject_put(&ppd->pport_kobj);
bail:
return ret;
}
/*
* Register and create our files in /sys/class/infiniband.
*/
int qib_verbs_register_sysfs(struct qib_devdata *dd)
{
struct ib_device *dev = &dd->verbs_dev.ibdev;
int i, ret;
for (i = 0; i < ARRAY_SIZE(qib_attributes); ++i) {
ret = device_create_file(&dev->dev, qib_attributes[i]);
if (ret)
return ret;
}
return 0;
}
/*
* Unregister and remove our files in /sys/class/infiniband.
*/
void qib_verbs_unregister_sysfs(struct qib_devdata *dd)
{
struct qib_pportdata *ppd;
int i;
for (i = 0; i < dd->num_pports; i++) {
ppd = &dd->pport[i];
kobject_put(&ppd->pport_kobj);
kobject_put(&ppd->sl2vl_kobj);
}
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.