repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
kjjjnob/android_kernel_lge_g3 | drivers/platform/x86/panasonic-laptop.c | 4891 | 18556 | /*
* Panasonic HotKey and LCD brightness control driver
* (C) 2004 Hiroshi Miura <miura@da-cha.org>
* (C) 2004 NTT DATA Intellilink Co. http://www.intellilink.co.jp/
* (C) YOKOTA Hiroshi <yokota (at) netlab. is. tsukuba. ac. jp>
* (C) 2004 David Bronaugh <dbronaugh>
* (C) 2006-2008 Harald Welte <laforge@gnumonks.org>
*
* derived from toshiba_acpi.c, Copyright (C) 2002-2004 John Belmonte
*
* 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
* publicshed 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
*
*---------------------------------------------------------------------------
*
* ChangeLog:
* Sep.23, 2008 Harald Welte <laforge@gnumonks.org>
* -v0.95 rename driver from drivers/acpi/pcc_acpi.c to
* drivers/misc/panasonic-laptop.c
*
* Jul.04, 2008 Harald Welte <laforge@gnumonks.org>
* -v0.94 replace /proc interface with device attributes
* support {set,get}keycode on th input device
*
* Jun.27, 2008 Harald Welte <laforge@gnumonks.org>
* -v0.92 merge with 2.6.26-rc6 input API changes
* remove broken <= 2.6.15 kernel support
* resolve all compiler warnings
* various coding style fixes (checkpatch.pl)
* add support for backlight api
* major code restructuring
*
* Dac.28, 2007 Harald Welte <laforge@gnumonks.org>
* -v0.91 merge with 2.6.24-rc6 ACPI changes
*
* Nov.04, 2006 Hiroshi Miura <miura@da-cha.org>
* -v0.9 remove warning about section reference.
* remove acpi_os_free
* add /proc/acpi/pcc/brightness interface for HAL access
* merge dbronaugh's enhancement
* Aug.17, 2004 David Bronaugh (dbronaugh)
* - Added screen brightness setting interface
* Thanks to FreeBSD crew (acpi_panasonic.c)
* for the ideas I needed to accomplish it
*
* May.29, 2006 Hiroshi Miura <miura@da-cha.org>
* -v0.8.4 follow to change keyinput structure
* thanks Fabian Yamaguchi <fabs@cs.tu-berlin.de>,
* Jacob Bower <jacob.bower@ic.ac.uk> and
* Hiroshi Yokota for providing solutions.
*
* Oct.02, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.8.2 merge code of YOKOTA Hiroshi
* <yokota@netlab.is.tsukuba.ac.jp>.
* Add sticky key mode interface.
* Refactoring acpi_pcc_generate_keyinput().
*
* Sep.15, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.8 Generate key input event on input subsystem.
* This is based on yet another driver written by
* Ryuta Nakanishi.
*
* Sep.10, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.7 Change proc interface functions using seq_file
* facility as same as other ACPI drivers.
*
* Aug.28, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.6.4 Fix a silly error with status checking
*
* Aug.25, 2004 Hiroshi Miura <miura@da-cha.org>
* -v0.6.3 replace read_acpi_int by standard function
* acpi_evaluate_integer
* some clean up and make smart copyright notice.
* fix return value of pcc_acpi_get_key()
* fix checking return value of acpi_bus_register_driver()
*
* Aug.22, 2004 David Bronaugh <dbronaugh@linuxboxen.org>
* -v0.6.2 Add check on ACPI data (num_sifr)
* Coding style cleanups, better error messages/handling
* Fixed an off-by-one error in memory allocation
*
* Aug.21, 2004 David Bronaugh <dbronaugh@linuxboxen.org>
* -v0.6.1 Fix a silly error with status checking
*
* Aug.20, 2004 David Bronaugh <dbronaugh@linuxboxen.org>
* - v0.6 Correct brightness controls to reflect reality
* based on information gleaned by Hiroshi Miura
* and discussions with Hiroshi Miura
*
* Aug.10, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.5 support LCD brightness control
* based on the disclosed information by MEI.
*
* Jul.25, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.4 first post version
* add function to retrive SIFR
*
* Jul.24, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.3 get proper status of hotkey
*
* Jul.22, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.2 add HotKey handler
*
* Jul.17, 2004 Hiroshi Miura <miura@da-cha.org>
* - v0.1 start from toshiba_acpi driver written by John Belmonte
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/backlight.h>
#include <linux/ctype.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#ifndef ACPI_HOTKEY_COMPONENT
#define ACPI_HOTKEY_COMPONENT 0x10000000
#endif
#define _COMPONENT ACPI_HOTKEY_COMPONENT
MODULE_AUTHOR("Hiroshi Miura, David Bronaugh and Harald Welte");
MODULE_DESCRIPTION("ACPI HotKey driver for Panasonic Let's Note laptops");
MODULE_LICENSE("GPL");
#define LOGPREFIX "pcc_acpi: "
/* Define ACPI PATHs */
/* Lets note hotkeys */
#define METHOD_HKEY_QUERY "HINF"
#define METHOD_HKEY_SQTY "SQTY"
#define METHOD_HKEY_SINF "SINF"
#define METHOD_HKEY_SSET "SSET"
#define HKEY_NOTIFY 0x80
#define ACPI_PCC_DRIVER_NAME "Panasonic Laptop Support"
#define ACPI_PCC_DEVICE_NAME "Hotkey"
#define ACPI_PCC_CLASS "pcc"
#define ACPI_PCC_INPUT_PHYS "panasonic/hkey0"
/* LCD_TYPEs: 0 = Normal, 1 = Semi-transparent
ENV_STATEs: Normal temp=0x01, High temp=0x81, N/A=0x00
*/
enum SINF_BITS { SINF_NUM_BATTERIES = 0,
SINF_LCD_TYPE,
SINF_AC_MAX_BRIGHT,
SINF_AC_MIN_BRIGHT,
SINF_AC_CUR_BRIGHT,
SINF_DC_MAX_BRIGHT,
SINF_DC_MIN_BRIGHT,
SINF_DC_CUR_BRIGHT,
SINF_MUTE,
SINF_RESERVED,
SINF_ENV_STATE,
SINF_STICKY_KEY = 0x80,
};
/* R1 handles SINF_AC_CUR_BRIGHT as SINF_CUR_BRIGHT, doesn't know AC state */
static int acpi_pcc_hotkey_add(struct acpi_device *device);
static int acpi_pcc_hotkey_remove(struct acpi_device *device, int type);
static int acpi_pcc_hotkey_resume(struct acpi_device *device);
static void acpi_pcc_hotkey_notify(struct acpi_device *device, u32 event);
static const struct acpi_device_id pcc_device_ids[] = {
{ "MAT0012", 0},
{ "MAT0013", 0},
{ "MAT0018", 0},
{ "MAT0019", 0},
{ "", 0},
};
MODULE_DEVICE_TABLE(acpi, pcc_device_ids);
static struct acpi_driver acpi_pcc_driver = {
.name = ACPI_PCC_DRIVER_NAME,
.class = ACPI_PCC_CLASS,
.ids = pcc_device_ids,
.ops = {
.add = acpi_pcc_hotkey_add,
.remove = acpi_pcc_hotkey_remove,
.resume = acpi_pcc_hotkey_resume,
.notify = acpi_pcc_hotkey_notify,
},
};
static const struct key_entry panasonic_keymap[] = {
{ KE_KEY, 0, { KEY_RESERVED } },
{ KE_KEY, 1, { KEY_BRIGHTNESSDOWN } },
{ KE_KEY, 2, { KEY_BRIGHTNESSUP } },
{ KE_KEY, 3, { KEY_DISPLAYTOGGLE } },
{ KE_KEY, 4, { KEY_MUTE } },
{ KE_KEY, 5, { KEY_VOLUMEDOWN } },
{ KE_KEY, 6, { KEY_VOLUMEUP } },
{ KE_KEY, 7, { KEY_SLEEP } },
{ KE_KEY, 8, { KEY_PROG1 } }, /* Change CPU boost */
{ KE_KEY, 9, { KEY_BATTERY } },
{ KE_KEY, 10, { KEY_SUSPEND } },
{ KE_END, 0 }
};
struct pcc_acpi {
acpi_handle handle;
unsigned long num_sifr;
int sticky_mode;
u32 *sinf;
struct acpi_device *device;
struct input_dev *input_dev;
struct backlight_device *backlight;
};
struct pcc_keyinput {
struct acpi_hotkey *hotkey;
};
/* method access functions */
static int acpi_pcc_write_sset(struct pcc_acpi *pcc, int func, int val)
{
union acpi_object in_objs[] = {
{ .integer.type = ACPI_TYPE_INTEGER,
.integer.value = func, },
{ .integer.type = ACPI_TYPE_INTEGER,
.integer.value = val, },
};
struct acpi_object_list params = {
.count = ARRAY_SIZE(in_objs),
.pointer = in_objs,
};
acpi_status status = AE_OK;
status = acpi_evaluate_object(pcc->handle, METHOD_HKEY_SSET,
¶ms, NULL);
return (status == AE_OK) ? 0 : -EIO;
}
static inline int acpi_pcc_get_sqty(struct acpi_device *device)
{
unsigned long long s;
acpi_status status;
status = acpi_evaluate_integer(device->handle, METHOD_HKEY_SQTY,
NULL, &s);
if (ACPI_SUCCESS(status))
return s;
else {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"evaluation error HKEY.SQTY\n"));
return -EINVAL;
}
}
static int acpi_pcc_retrieve_biosdata(struct pcc_acpi *pcc)
{
acpi_status status;
struct acpi_buffer buffer = {ACPI_ALLOCATE_BUFFER, NULL};
union acpi_object *hkey = NULL;
int i;
status = acpi_evaluate_object(pcc->handle, METHOD_HKEY_SINF, NULL,
&buffer);
if (ACPI_FAILURE(status)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"evaluation error HKEY.SINF\n"));
return 0;
}
hkey = buffer.pointer;
if (!hkey || (hkey->type != ACPI_TYPE_PACKAGE)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR, "Invalid HKEY.SINF\n"));
status = AE_ERROR;
goto end;
}
if (pcc->num_sifr < hkey->package.count) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"SQTY reports bad SINF length\n"));
status = AE_ERROR;
goto end;
}
for (i = 0; i < hkey->package.count; i++) {
union acpi_object *element = &(hkey->package.elements[i]);
if (likely(element->type == ACPI_TYPE_INTEGER)) {
pcc->sinf[i] = element->integer.value;
} else
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Invalid HKEY.SINF data\n"));
}
pcc->sinf[hkey->package.count] = -1;
end:
kfree(buffer.pointer);
return status == AE_OK;
}
/* backlight API interface functions */
/* This driver currently treats AC and DC brightness identical,
* since we don't need to invent an interface to the core ACPI
* logic to receive events in case a power supply is plugged in
* or removed */
static int bl_get(struct backlight_device *bd)
{
struct pcc_acpi *pcc = bl_get_data(bd);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return pcc->sinf[SINF_AC_CUR_BRIGHT];
}
static int bl_set_status(struct backlight_device *bd)
{
struct pcc_acpi *pcc = bl_get_data(bd);
int bright = bd->props.brightness;
int rc;
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
if (bright < pcc->sinf[SINF_AC_MIN_BRIGHT])
bright = pcc->sinf[SINF_AC_MIN_BRIGHT];
if (bright < pcc->sinf[SINF_DC_MIN_BRIGHT])
bright = pcc->sinf[SINF_DC_MIN_BRIGHT];
if (bright < pcc->sinf[SINF_AC_MIN_BRIGHT] ||
bright > pcc->sinf[SINF_AC_MAX_BRIGHT])
return -EINVAL;
rc = acpi_pcc_write_sset(pcc, SINF_AC_CUR_BRIGHT, bright);
if (rc < 0)
return rc;
return acpi_pcc_write_sset(pcc, SINF_DC_CUR_BRIGHT, bright);
}
static const struct backlight_ops pcc_backlight_ops = {
.get_brightness = bl_get,
.update_status = bl_set_status,
};
/* sysfs user interface functions */
static ssize_t show_numbatt(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_NUM_BATTERIES]);
}
static ssize_t show_lcdtype(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_LCD_TYPE]);
}
static ssize_t show_mute(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_MUTE]);
}
static ssize_t show_sticky(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
if (!acpi_pcc_retrieve_biosdata(pcc))
return -EIO;
return snprintf(buf, PAGE_SIZE, "%u\n", pcc->sinf[SINF_STICKY_KEY]);
}
static ssize_t set_sticky(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct acpi_device *acpi = to_acpi_device(dev);
struct pcc_acpi *pcc = acpi_driver_data(acpi);
int val;
if (count && sscanf(buf, "%i", &val) == 1 &&
(val == 0 || val == 1)) {
acpi_pcc_write_sset(pcc, SINF_STICKY_KEY, val);
pcc->sticky_mode = val;
}
return count;
}
static DEVICE_ATTR(numbatt, S_IRUGO, show_numbatt, NULL);
static DEVICE_ATTR(lcdtype, S_IRUGO, show_lcdtype, NULL);
static DEVICE_ATTR(mute, S_IRUGO, show_mute, NULL);
static DEVICE_ATTR(sticky_key, S_IRUGO | S_IWUSR, show_sticky, set_sticky);
static struct attribute *pcc_sysfs_entries[] = {
&dev_attr_numbatt.attr,
&dev_attr_lcdtype.attr,
&dev_attr_mute.attr,
&dev_attr_sticky_key.attr,
NULL,
};
static struct attribute_group pcc_attr_group = {
.name = NULL, /* put in device directory */
.attrs = pcc_sysfs_entries,
};
/* hotkey input device driver */
static void acpi_pcc_generate_keyinput(struct pcc_acpi *pcc)
{
struct input_dev *hotk_input_dev = pcc->input_dev;
int rc;
unsigned long long result;
rc = acpi_evaluate_integer(pcc->handle, METHOD_HKEY_QUERY,
NULL, &result);
if (!ACPI_SUCCESS(rc)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"error getting hotkey status\n"));
return;
}
acpi_bus_generate_proc_event(pcc->device, HKEY_NOTIFY, result);
if (!sparse_keymap_report_event(hotk_input_dev,
result & 0xf, result & 0x80, false))
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Unknown hotkey event: %d\n", result));
}
static void acpi_pcc_hotkey_notify(struct acpi_device *device, u32 event)
{
struct pcc_acpi *pcc = acpi_driver_data(device);
switch (event) {
case HKEY_NOTIFY:
acpi_pcc_generate_keyinput(pcc);
break;
default:
/* nothing to do */
break;
}
}
static int acpi_pcc_init_input(struct pcc_acpi *pcc)
{
struct input_dev *input_dev;
int error;
input_dev = input_allocate_device();
if (!input_dev) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Couldn't allocate input device for hotkey"));
return -ENOMEM;
}
input_dev->name = ACPI_PCC_DRIVER_NAME;
input_dev->phys = ACPI_PCC_INPUT_PHYS;
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
error = sparse_keymap_setup(input_dev, panasonic_keymap, NULL);
if (error) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Unable to setup input device keymap\n"));
goto err_free_dev;
}
error = input_register_device(input_dev);
if (error) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Unable to register input device\n"));
goto err_free_keymap;
}
pcc->input_dev = input_dev;
return 0;
err_free_keymap:
sparse_keymap_free(input_dev);
err_free_dev:
input_free_device(input_dev);
return error;
}
static void acpi_pcc_destroy_input(struct pcc_acpi *pcc)
{
sparse_keymap_free(pcc->input_dev);
input_unregister_device(pcc->input_dev);
/*
* No need to input_free_device() since core input API refcounts
* and free()s the device.
*/
}
/* kernel module interface */
static int acpi_pcc_hotkey_resume(struct acpi_device *device)
{
struct pcc_acpi *pcc = acpi_driver_data(device);
if (device == NULL || pcc == NULL)
return -EINVAL;
ACPI_DEBUG_PRINT((ACPI_DB_ERROR, "Sticky mode restore: %d\n",
pcc->sticky_mode));
return acpi_pcc_write_sset(pcc, SINF_STICKY_KEY, pcc->sticky_mode);
}
static int acpi_pcc_hotkey_add(struct acpi_device *device)
{
struct backlight_properties props;
struct pcc_acpi *pcc;
int num_sifr, result;
if (!device)
return -EINVAL;
num_sifr = acpi_pcc_get_sqty(device);
if (num_sifr < 0 || num_sifr > 255) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR, "num_sifr out of range"));
return -ENODEV;
}
pcc = kzalloc(sizeof(struct pcc_acpi), GFP_KERNEL);
if (!pcc) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Couldn't allocate mem for pcc"));
return -ENOMEM;
}
pcc->sinf = kzalloc(sizeof(u32) * (num_sifr + 1), GFP_KERNEL);
if (!pcc->sinf) {
result = -ENOMEM;
goto out_hotkey;
}
pcc->device = device;
pcc->handle = device->handle;
pcc->num_sifr = num_sifr;
device->driver_data = pcc;
strcpy(acpi_device_name(device), ACPI_PCC_DEVICE_NAME);
strcpy(acpi_device_class(device), ACPI_PCC_CLASS);
result = acpi_pcc_init_input(pcc);
if (result) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Error installing keyinput handler\n"));
goto out_sinf;
}
if (!acpi_pcc_retrieve_biosdata(pcc)) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Couldn't retrieve BIOS data\n"));
result = -EIO;
goto out_input;
}
/* initialize backlight */
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = pcc->sinf[SINF_AC_MAX_BRIGHT];
pcc->backlight = backlight_device_register("panasonic", NULL, pcc,
&pcc_backlight_ops, &props);
if (IS_ERR(pcc->backlight)) {
result = PTR_ERR(pcc->backlight);
goto out_input;
}
/* read the initial brightness setting from the hardware */
pcc->backlight->props.brightness = pcc->sinf[SINF_AC_CUR_BRIGHT];
/* read the initial sticky key mode from the hardware */
pcc->sticky_mode = pcc->sinf[SINF_STICKY_KEY];
/* add sysfs attributes */
result = sysfs_create_group(&device->dev.kobj, &pcc_attr_group);
if (result)
goto out_backlight;
return 0;
out_backlight:
backlight_device_unregister(pcc->backlight);
out_input:
acpi_pcc_destroy_input(pcc);
out_sinf:
kfree(pcc->sinf);
out_hotkey:
kfree(pcc);
return result;
}
static int __init acpi_pcc_init(void)
{
int result = 0;
if (acpi_disabled)
return -ENODEV;
result = acpi_bus_register_driver(&acpi_pcc_driver);
if (result < 0) {
ACPI_DEBUG_PRINT((ACPI_DB_ERROR,
"Error registering hotkey driver\n"));
return -ENODEV;
}
return 0;
}
static int acpi_pcc_hotkey_remove(struct acpi_device *device, int type)
{
struct pcc_acpi *pcc = acpi_driver_data(device);
if (!device || !pcc)
return -EINVAL;
sysfs_remove_group(&device->dev.kobj, &pcc_attr_group);
backlight_device_unregister(pcc->backlight);
acpi_pcc_destroy_input(pcc);
kfree(pcc->sinf);
kfree(pcc);
return 0;
}
static void __exit acpi_pcc_exit(void)
{
acpi_bus_unregister_driver(&acpi_pcc_driver);
}
module_init(acpi_pcc_init);
module_exit(acpi_pcc_exit);
| gpl-2.0 |
ausdim/TW-jb-Edition-I9505-jfltexx | drivers/mtd/nand/au1550nd.c | 4891 | 13614 | /*
* drivers/mtd/nand/au1550nd.c
*
* Copyright (C) 2004 Embedded Edge, LLC
*
* 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/slab.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/platform_device.h>
#include <asm/io.h>
#include <asm/mach-au1x00/au1000.h>
#include <asm/mach-au1x00/au1550nd.h>
struct au1550nd_ctx {
struct mtd_info info;
struct nand_chip chip;
int cs;
void __iomem *base;
void (*write_byte)(struct mtd_info *, u_char);
};
/**
* au_read_byte - read one byte from the chip
* @mtd: MTD device structure
*
* read function for 8bit buswidth
*/
static u_char au_read_byte(struct mtd_info *mtd)
{
struct nand_chip *this = mtd->priv;
u_char ret = readb(this->IO_ADDR_R);
au_sync();
return ret;
}
/**
* au_write_byte - write one byte to the chip
* @mtd: MTD device structure
* @byte: pointer to data byte to write
*
* write function for 8it buswidth
*/
static void au_write_byte(struct mtd_info *mtd, u_char byte)
{
struct nand_chip *this = mtd->priv;
writeb(byte, this->IO_ADDR_W);
au_sync();
}
/**
* au_read_byte16 - read one byte endianness aware from the chip
* @mtd: MTD device structure
*
* read function for 16bit buswidth with endianness conversion
*/
static u_char au_read_byte16(struct mtd_info *mtd)
{
struct nand_chip *this = mtd->priv;
u_char ret = (u_char) cpu_to_le16(readw(this->IO_ADDR_R));
au_sync();
return ret;
}
/**
* au_write_byte16 - write one byte endianness aware to the chip
* @mtd: MTD device structure
* @byte: pointer to data byte to write
*
* write function for 16bit buswidth with endianness conversion
*/
static void au_write_byte16(struct mtd_info *mtd, u_char byte)
{
struct nand_chip *this = mtd->priv;
writew(le16_to_cpu((u16) byte), this->IO_ADDR_W);
au_sync();
}
/**
* au_read_word - read one word from the chip
* @mtd: MTD device structure
*
* read function for 16bit buswidth without endianness conversion
*/
static u16 au_read_word(struct mtd_info *mtd)
{
struct nand_chip *this = mtd->priv;
u16 ret = readw(this->IO_ADDR_R);
au_sync();
return ret;
}
/**
* au_write_buf - write buffer to chip
* @mtd: MTD device structure
* @buf: data buffer
* @len: number of bytes to write
*
* write function for 8bit buswidth
*/
static void au_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
for (i = 0; i < len; i++) {
writeb(buf[i], this->IO_ADDR_W);
au_sync();
}
}
/**
* au_read_buf - read chip data into buffer
* @mtd: MTD device structure
* @buf: buffer to store date
* @len: number of bytes to read
*
* read function for 8bit buswidth
*/
static void au_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
for (i = 0; i < len; i++) {
buf[i] = readb(this->IO_ADDR_R);
au_sync();
}
}
/**
* au_verify_buf - Verify chip data against buffer
* @mtd: MTD device structure
* @buf: buffer containing the data to compare
* @len: number of bytes to compare
*
* verify function for 8bit buswidth
*/
static int au_verify_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
for (i = 0; i < len; i++) {
if (buf[i] != readb(this->IO_ADDR_R))
return -EFAULT;
au_sync();
}
return 0;
}
/**
* au_write_buf16 - write buffer to chip
* @mtd: MTD device structure
* @buf: data buffer
* @len: number of bytes to write
*
* write function for 16bit buswidth
*/
static void au_write_buf16(struct mtd_info *mtd, const u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
u16 *p = (u16 *) buf;
len >>= 1;
for (i = 0; i < len; i++) {
writew(p[i], this->IO_ADDR_W);
au_sync();
}
}
/**
* au_read_buf16 - read chip data into buffer
* @mtd: MTD device structure
* @buf: buffer to store date
* @len: number of bytes to read
*
* read function for 16bit buswidth
*/
static void au_read_buf16(struct mtd_info *mtd, u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
u16 *p = (u16 *) buf;
len >>= 1;
for (i = 0; i < len; i++) {
p[i] = readw(this->IO_ADDR_R);
au_sync();
}
}
/**
* au_verify_buf16 - Verify chip data against buffer
* @mtd: MTD device structure
* @buf: buffer containing the data to compare
* @len: number of bytes to compare
*
* verify function for 16bit buswidth
*/
static int au_verify_buf16(struct mtd_info *mtd, const u_char *buf, int len)
{
int i;
struct nand_chip *this = mtd->priv;
u16 *p = (u16 *) buf;
len >>= 1;
for (i = 0; i < len; i++) {
if (p[i] != readw(this->IO_ADDR_R))
return -EFAULT;
au_sync();
}
return 0;
}
/* Select the chip by setting nCE to low */
#define NAND_CTL_SETNCE 1
/* Deselect the chip by setting nCE to high */
#define NAND_CTL_CLRNCE 2
/* Select the command latch by setting CLE to high */
#define NAND_CTL_SETCLE 3
/* Deselect the command latch by setting CLE to low */
#define NAND_CTL_CLRCLE 4
/* Select the address latch by setting ALE to high */
#define NAND_CTL_SETALE 5
/* Deselect the address latch by setting ALE to low */
#define NAND_CTL_CLRALE 6
static void au1550_hwcontrol(struct mtd_info *mtd, int cmd)
{
struct au1550nd_ctx *ctx = container_of(mtd, struct au1550nd_ctx, info);
struct nand_chip *this = mtd->priv;
switch (cmd) {
case NAND_CTL_SETCLE:
this->IO_ADDR_W = ctx->base + MEM_STNAND_CMD;
break;
case NAND_CTL_CLRCLE:
this->IO_ADDR_W = ctx->base + MEM_STNAND_DATA;
break;
case NAND_CTL_SETALE:
this->IO_ADDR_W = ctx->base + MEM_STNAND_ADDR;
break;
case NAND_CTL_CLRALE:
this->IO_ADDR_W = ctx->base + MEM_STNAND_DATA;
/* FIXME: Nobody knows why this is necessary,
* but it works only that way */
udelay(1);
break;
case NAND_CTL_SETNCE:
/* assert (force assert) chip enable */
au_writel((1 << (4 + ctx->cs)), MEM_STNDCTL);
break;
case NAND_CTL_CLRNCE:
/* deassert chip enable */
au_writel(0, MEM_STNDCTL);
break;
}
this->IO_ADDR_R = this->IO_ADDR_W;
/* Drain the writebuffer */
au_sync();
}
int au1550_device_ready(struct mtd_info *mtd)
{
int ret = (au_readl(MEM_STSTAT) & 0x1) ? 1 : 0;
au_sync();
return ret;
}
/**
* au1550_select_chip - control -CE line
* Forbid driving -CE manually permitting the NAND controller to do this.
* Keeping -CE asserted during the whole sector reads interferes with the
* NOR flash and PCMCIA drivers as it causes contention on the static bus.
* We only have to hold -CE low for the NAND read commands since the flash
* chip needs it to be asserted during chip not ready time but the NAND
* controller keeps it released.
*
* @mtd: MTD device structure
* @chip: chipnumber to select, -1 for deselect
*/
static void au1550_select_chip(struct mtd_info *mtd, int chip)
{
}
/**
* au1550_command - Send command to NAND device
* @mtd: MTD device structure
* @command: the command to be sent
* @column: the column address for this command, -1 if none
* @page_addr: the page address for this command, -1 if none
*/
static void au1550_command(struct mtd_info *mtd, unsigned command, int column, int page_addr)
{
struct au1550nd_ctx *ctx = container_of(mtd, struct au1550nd_ctx, info);
struct nand_chip *this = mtd->priv;
int ce_override = 0, i;
unsigned long flags = 0;
/* Begin command latch cycle */
au1550_hwcontrol(mtd, NAND_CTL_SETCLE);
/*
* Write out the command to the device.
*/
if (command == NAND_CMD_SEQIN) {
int readcmd;
if (column >= mtd->writesize) {
/* OOB area */
column -= mtd->writesize;
readcmd = NAND_CMD_READOOB;
} else if (column < 256) {
/* First 256 bytes --> READ0 */
readcmd = NAND_CMD_READ0;
} else {
column -= 256;
readcmd = NAND_CMD_READ1;
}
ctx->write_byte(mtd, readcmd);
}
ctx->write_byte(mtd, command);
/* Set ALE and clear CLE to start address cycle */
au1550_hwcontrol(mtd, NAND_CTL_CLRCLE);
if (column != -1 || page_addr != -1) {
au1550_hwcontrol(mtd, NAND_CTL_SETALE);
/* Serially input address */
if (column != -1) {
/* Adjust columns for 16 bit buswidth */
if (this->options & NAND_BUSWIDTH_16)
column >>= 1;
ctx->write_byte(mtd, column);
}
if (page_addr != -1) {
ctx->write_byte(mtd, (u8)(page_addr & 0xff));
if (command == NAND_CMD_READ0 ||
command == NAND_CMD_READ1 ||
command == NAND_CMD_READOOB) {
/*
* NAND controller will release -CE after
* the last address byte is written, so we'll
* have to forcibly assert it. No interrupts
* are allowed while we do this as we don't
* want the NOR flash or PCMCIA drivers to
* steal our precious bytes of data...
*/
ce_override = 1;
local_irq_save(flags);
au1550_hwcontrol(mtd, NAND_CTL_SETNCE);
}
ctx->write_byte(mtd, (u8)(page_addr >> 8));
/* One more address cycle for devices > 32MiB */
if (this->chipsize > (32 << 20))
ctx->write_byte(mtd,
((page_addr >> 16) & 0x0f));
}
/* Latch in address */
au1550_hwcontrol(mtd, NAND_CTL_CLRALE);
}
/*
* Program and erase have their own busy handlers.
* Status and sequential in need no delay.
*/
switch (command) {
case NAND_CMD_PAGEPROG:
case NAND_CMD_ERASE1:
case NAND_CMD_ERASE2:
case NAND_CMD_SEQIN:
case NAND_CMD_STATUS:
return;
case NAND_CMD_RESET:
break;
case NAND_CMD_READ0:
case NAND_CMD_READ1:
case NAND_CMD_READOOB:
/* Check if we're really driving -CE low (just in case) */
if (unlikely(!ce_override))
break;
/* Apply a short delay always to ensure that we do wait tWB. */
ndelay(100);
/* Wait for a chip to become ready... */
for (i = this->chip_delay; !this->dev_ready(mtd) && i > 0; --i)
udelay(1);
/* Release -CE and re-enable interrupts. */
au1550_hwcontrol(mtd, NAND_CTL_CLRNCE);
local_irq_restore(flags);
return;
}
/* Apply this short delay always to ensure that we do wait tWB. */
ndelay(100);
while(!this->dev_ready(mtd));
}
static int __devinit find_nand_cs(unsigned long nand_base)
{
void __iomem *base =
(void __iomem *)KSEG1ADDR(AU1000_STATIC_MEM_PHYS_ADDR);
unsigned long addr, staddr, start, mask, end;
int i;
for (i = 0; i < 4; i++) {
addr = 0x1000 + (i * 0x10); /* CSx */
staddr = __raw_readl(base + addr + 0x08); /* STADDRx */
/* figure out the decoded range of this CS */
start = (staddr << 4) & 0xfffc0000;
mask = (staddr << 18) & 0xfffc0000;
end = (start | (start - 1)) & ~(start ^ mask);
if ((nand_base >= start) && (nand_base < end))
return i;
}
return -ENODEV;
}
static int __devinit au1550nd_probe(struct platform_device *pdev)
{
struct au1550nd_platdata *pd;
struct au1550nd_ctx *ctx;
struct nand_chip *this;
struct resource *r;
int ret, cs;
pd = pdev->dev.platform_data;
if (!pd) {
dev_err(&pdev->dev, "missing platform data\n");
return -ENODEV;
}
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx) {
dev_err(&pdev->dev, "no memory for NAND context\n");
return -ENOMEM;
}
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
dev_err(&pdev->dev, "no NAND memory resource\n");
ret = -ENODEV;
goto out1;
}
if (request_mem_region(r->start, resource_size(r), "au1550-nand")) {
dev_err(&pdev->dev, "cannot claim NAND memory area\n");
ret = -ENOMEM;
goto out1;
}
ctx->base = ioremap_nocache(r->start, 0x1000);
if (!ctx->base) {
dev_err(&pdev->dev, "cannot remap NAND memory area\n");
ret = -ENODEV;
goto out2;
}
this = &ctx->chip;
ctx->info.priv = this;
ctx->info.owner = THIS_MODULE;
/* figure out which CS# r->start belongs to */
cs = find_nand_cs(r->start);
if (cs < 0) {
dev_err(&pdev->dev, "cannot detect NAND chipselect\n");
ret = -ENODEV;
goto out3;
}
ctx->cs = cs;
this->dev_ready = au1550_device_ready;
this->select_chip = au1550_select_chip;
this->cmdfunc = au1550_command;
/* 30 us command delay time */
this->chip_delay = 30;
this->ecc.mode = NAND_ECC_SOFT;
this->options = NAND_NO_AUTOINCR;
if (pd->devwidth)
this->options |= NAND_BUSWIDTH_16;
this->read_byte = (pd->devwidth) ? au_read_byte16 : au_read_byte;
ctx->write_byte = (pd->devwidth) ? au_write_byte16 : au_write_byte;
this->read_word = au_read_word;
this->write_buf = (pd->devwidth) ? au_write_buf16 : au_write_buf;
this->read_buf = (pd->devwidth) ? au_read_buf16 : au_read_buf;
this->verify_buf = (pd->devwidth) ? au_verify_buf16 : au_verify_buf;
ret = nand_scan(&ctx->info, 1);
if (ret) {
dev_err(&pdev->dev, "NAND scan failed with %d\n", ret);
goto out3;
}
mtd_device_register(&ctx->info, pd->parts, pd->num_parts);
return 0;
out3:
iounmap(ctx->base);
out2:
release_mem_region(r->start, resource_size(r));
out1:
kfree(ctx);
return ret;
}
static int __devexit au1550nd_remove(struct platform_device *pdev)
{
struct au1550nd_ctx *ctx = platform_get_drvdata(pdev);
struct resource *r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
nand_release(&ctx->info);
iounmap(ctx->base);
release_mem_region(r->start, 0x1000);
kfree(ctx);
return 0;
}
static struct platform_driver au1550nd_driver = {
.driver = {
.name = "au1550-nand",
.owner = THIS_MODULE,
},
.probe = au1550nd_probe,
.remove = __devexit_p(au1550nd_remove),
};
module_platform_driver(au1550nd_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Embedded Edge, LLC");
MODULE_DESCRIPTION("Board-specific glue layer for NAND flash on Pb1550 board");
| gpl-2.0 |
Sinsoftomorrow/android_kernel_lge_g3 | drivers/gpu/drm/vmwgfx/vmwgfx_gmrid_manager.c | 5659 | 4398 | /**************************************************************************
*
* Copyright (c) 2007-2010 VMware, Inc., Palo Alto, CA., USA
* All Rights Reserved.
*
* 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, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
*/
#include "vmwgfx_drv.h"
#include "ttm/ttm_module.h"
#include "ttm/ttm_bo_driver.h"
#include "ttm/ttm_placement.h"
#include <linux/idr.h>
#include <linux/spinlock.h>
#include <linux/kernel.h>
struct vmwgfx_gmrid_man {
spinlock_t lock;
struct ida gmr_ida;
uint32_t max_gmr_ids;
uint32_t max_gmr_pages;
uint32_t used_gmr_pages;
};
static int vmw_gmrid_man_get_node(struct ttm_mem_type_manager *man,
struct ttm_buffer_object *bo,
struct ttm_placement *placement,
struct ttm_mem_reg *mem)
{
struct vmwgfx_gmrid_man *gman =
(struct vmwgfx_gmrid_man *)man->priv;
int ret = 0;
int id;
mem->mm_node = NULL;
spin_lock(&gman->lock);
if (gman->max_gmr_pages > 0) {
gman->used_gmr_pages += bo->num_pages;
if (unlikely(gman->used_gmr_pages > gman->max_gmr_pages))
goto out_err_locked;
}
do {
spin_unlock(&gman->lock);
if (unlikely(ida_pre_get(&gman->gmr_ida, GFP_KERNEL) == 0)) {
ret = -ENOMEM;
goto out_err;
}
spin_lock(&gman->lock);
ret = ida_get_new(&gman->gmr_ida, &id);
if (unlikely(ret == 0 && id >= gman->max_gmr_ids)) {
ida_remove(&gman->gmr_ida, id);
ret = 0;
goto out_err_locked;
}
} while (ret == -EAGAIN);
if (likely(ret == 0)) {
mem->mm_node = gman;
mem->start = id;
mem->num_pages = bo->num_pages;
} else
goto out_err_locked;
spin_unlock(&gman->lock);
return 0;
out_err:
spin_lock(&gman->lock);
out_err_locked:
gman->used_gmr_pages -= bo->num_pages;
spin_unlock(&gman->lock);
return ret;
}
static void vmw_gmrid_man_put_node(struct ttm_mem_type_manager *man,
struct ttm_mem_reg *mem)
{
struct vmwgfx_gmrid_man *gman =
(struct vmwgfx_gmrid_man *)man->priv;
if (mem->mm_node) {
spin_lock(&gman->lock);
ida_remove(&gman->gmr_ida, mem->start);
gman->used_gmr_pages -= mem->num_pages;
spin_unlock(&gman->lock);
mem->mm_node = NULL;
}
}
static int vmw_gmrid_man_init(struct ttm_mem_type_manager *man,
unsigned long p_size)
{
struct vmw_private *dev_priv =
container_of(man->bdev, struct vmw_private, bdev);
struct vmwgfx_gmrid_man *gman =
kzalloc(sizeof(*gman), GFP_KERNEL);
if (unlikely(gman == NULL))
return -ENOMEM;
spin_lock_init(&gman->lock);
gman->max_gmr_pages = dev_priv->max_gmr_pages;
gman->used_gmr_pages = 0;
ida_init(&gman->gmr_ida);
gman->max_gmr_ids = p_size;
man->priv = (void *) gman;
return 0;
}
static int vmw_gmrid_man_takedown(struct ttm_mem_type_manager *man)
{
struct vmwgfx_gmrid_man *gman =
(struct vmwgfx_gmrid_man *)man->priv;
if (gman) {
ida_destroy(&gman->gmr_ida);
kfree(gman);
}
return 0;
}
static void vmw_gmrid_man_debug(struct ttm_mem_type_manager *man,
const char *prefix)
{
printk(KERN_INFO "%s: No debug info available for the GMR "
"id manager.\n", prefix);
}
const struct ttm_mem_type_manager_func vmw_gmrid_manager_func = {
vmw_gmrid_man_init,
vmw_gmrid_man_takedown,
vmw_gmrid_man_get_node,
vmw_gmrid_man_put_node,
vmw_gmrid_man_debug
};
| gpl-2.0 |
blitzmohit/dragonboard-rtlinux-3.4 | drivers/isdn/pcbit/drv.c | 7707 | 22246 | /*
* PCBIT-D interface with isdn4linux
*
* Copyright (C) 1996 Universidade de Lisboa
*
* Written by Pedro Roque Marques (roque@di.fc.ul.pt)
*
* This software may be used and distributed according to the terms of
* the GNU General Public License, incorporated herein by reference.
*/
/*
* Fixes:
*
* Nuno Grilo <l38486@alfa.ist.utl.pt>
* fixed msn_list NULL pointer dereference.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <linux/skbuff.h>
#include <linux/isdnif.h>
#include <asm/string.h>
#include <asm/io.h>
#include <linux/ioport.h>
#include "pcbit.h"
#include "edss1.h"
#include "layer2.h"
#include "capi.h"
extern ushort last_ref_num;
static int pcbit_ioctl(isdn_ctrl *ctl);
static char *pcbit_devname[MAX_PCBIT_CARDS] = {
"pcbit0",
"pcbit1",
"pcbit2",
"pcbit3"
};
/*
* prototypes
*/
static int pcbit_command(isdn_ctrl *ctl);
static int pcbit_stat(u_char __user *buf, int len, int, int);
static int pcbit_xmit(int driver, int chan, int ack, struct sk_buff *skb);
static int pcbit_writecmd(const u_char __user *, int, int, int);
static int set_protocol_running(struct pcbit_dev *dev);
static void pcbit_clear_msn(struct pcbit_dev *dev);
static void pcbit_set_msn(struct pcbit_dev *dev, char *list);
static int pcbit_check_msn(struct pcbit_dev *dev, char *msn);
int pcbit_init_dev(int board, int mem_base, int irq)
{
struct pcbit_dev *dev;
isdn_if *dev_if;
if ((dev = kzalloc(sizeof(struct pcbit_dev), GFP_KERNEL)) == NULL)
{
printk("pcbit_init: couldn't malloc pcbit_dev struct\n");
return -ENOMEM;
}
dev_pcbit[board] = dev;
init_waitqueue_head(&dev->set_running_wq);
spin_lock_init(&dev->lock);
if (mem_base >= 0xA0000 && mem_base <= 0xFFFFF) {
dev->ph_mem = mem_base;
if (!request_mem_region(dev->ph_mem, 4096, "PCBIT mem")) {
printk(KERN_WARNING
"PCBIT: memory region %lx-%lx already in use\n",
dev->ph_mem, dev->ph_mem + 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EACCES;
}
dev->sh_mem = ioremap(dev->ph_mem, 4096);
}
else
{
printk("memory address invalid");
kfree(dev);
dev_pcbit[board] = NULL;
return -EACCES;
}
dev->b1 = kzalloc(sizeof(struct pcbit_chan), GFP_KERNEL);
if (!dev->b1) {
printk("pcbit_init: couldn't malloc pcbit_chan struct\n");
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
return -ENOMEM;
}
dev->b2 = kzalloc(sizeof(struct pcbit_chan), GFP_KERNEL);
if (!dev->b2) {
printk("pcbit_init: couldn't malloc pcbit_chan struct\n");
kfree(dev->b1);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
return -ENOMEM;
}
dev->b2->id = 1;
INIT_WORK(&dev->qdelivery, pcbit_deliver);
/*
* interrupts
*/
if (request_irq(irq, &pcbit_irq_handler, 0, pcbit_devname[board], dev) != 0)
{
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EIO;
}
dev->irq = irq;
/* next frame to be received */
dev->rcv_seq = 0;
dev->send_seq = 0;
dev->unack_seq = 0;
dev->hl_hdrlen = 16;
dev_if = kmalloc(sizeof(isdn_if), GFP_KERNEL);
if (!dev_if) {
free_irq(irq, dev);
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EIO;
}
dev->dev_if = dev_if;
dev_if->owner = THIS_MODULE;
dev_if->channels = 2;
dev_if->features = (ISDN_FEATURE_P_EURO | ISDN_FEATURE_L3_TRANS |
ISDN_FEATURE_L2_HDLC | ISDN_FEATURE_L2_TRANS);
dev_if->writebuf_skb = pcbit_xmit;
dev_if->hl_hdrlen = 16;
dev_if->maxbufsize = MAXBUFSIZE;
dev_if->command = pcbit_command;
dev_if->writecmd = pcbit_writecmd;
dev_if->readstat = pcbit_stat;
strcpy(dev_if->id, pcbit_devname[board]);
if (!register_isdn(dev_if)) {
free_irq(irq, dev);
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
dev_pcbit[board] = NULL;
return -EIO;
}
dev->id = dev_if->channels;
dev->l2_state = L2_DOWN;
dev->free = 511;
/*
* set_protocol_running(dev);
*/
return 0;
}
#ifdef MODULE
void pcbit_terminate(int board)
{
struct pcbit_dev *dev;
dev = dev_pcbit[board];
if (dev) {
/* unregister_isdn(dev->dev_if); */
free_irq(dev->irq, dev);
pcbit_clear_msn(dev);
kfree(dev->dev_if);
if (dev->b1->fsm_timer.function)
del_timer(&dev->b1->fsm_timer);
if (dev->b2->fsm_timer.function)
del_timer(&dev->b2->fsm_timer);
kfree(dev->b1);
kfree(dev->b2);
iounmap(dev->sh_mem);
release_mem_region(dev->ph_mem, 4096);
kfree(dev);
}
}
#endif
static int pcbit_command(isdn_ctrl *ctl)
{
struct pcbit_dev *dev;
struct pcbit_chan *chan;
struct callb_data info;
dev = finddev(ctl->driver);
if (!dev)
{
printk("pcbit_command: unknown device\n");
return -1;
}
chan = (ctl->arg & 0x0F) ? dev->b2 : dev->b1;
switch (ctl->command) {
case ISDN_CMD_IOCTL:
return pcbit_ioctl(ctl);
break;
case ISDN_CMD_DIAL:
info.type = EV_USR_SETUP_REQ;
info.data.setup.CalledPN = (char *) &ctl->parm.setup.phone;
pcbit_fsm_event(dev, chan, EV_USR_SETUP_REQ, &info);
break;
case ISDN_CMD_ACCEPTD:
pcbit_fsm_event(dev, chan, EV_USR_SETUP_RESP, NULL);
break;
case ISDN_CMD_ACCEPTB:
printk("ISDN_CMD_ACCEPTB - not really needed\n");
break;
case ISDN_CMD_HANGUP:
pcbit_fsm_event(dev, chan, EV_USR_RELEASE_REQ, NULL);
break;
case ISDN_CMD_SETL2:
chan->proto = (ctl->arg >> 8);
break;
case ISDN_CMD_CLREAZ:
pcbit_clear_msn(dev);
break;
case ISDN_CMD_SETEAZ:
pcbit_set_msn(dev, ctl->parm.num);
break;
case ISDN_CMD_SETL3:
if ((ctl->arg >> 8) != ISDN_PROTO_L3_TRANS)
printk(KERN_DEBUG "L3 protocol unknown\n");
break;
default:
printk(KERN_DEBUG "pcbit_command: unknown command\n");
break;
};
return 0;
}
/*
* Another Hack :-(
* on some conditions the board stops sending TDATA_CONFs
* let's see if we can turn around the problem
*/
#ifdef BLOCK_TIMER
static void pcbit_block_timer(unsigned long data)
{
struct pcbit_chan *chan;
struct pcbit_dev *dev;
isdn_ctrl ictl;
chan = (struct pcbit_chan *)data;
dev = chan2dev(chan);
if (dev == NULL) {
printk(KERN_DEBUG "pcbit: chan2dev failed\n");
return;
}
del_timer(&chan->block_timer);
chan->block_timer.function = NULL;
#ifdef DEBUG
printk(KERN_DEBUG "pcbit_block_timer\n");
#endif
chan->queued = 0;
ictl.driver = dev->id;
ictl.command = ISDN_STAT_BSENT;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
}
#endif
static int pcbit_xmit(int driver, int chnum, int ack, struct sk_buff *skb)
{
ushort hdrlen;
int refnum, len;
struct pcbit_chan *chan;
struct pcbit_dev *dev;
dev = finddev(driver);
if (dev == NULL)
{
printk("finddev returned NULL");
return -1;
}
chan = chnum ? dev->b2 : dev->b1;
if (chan->fsm_state != ST_ACTIVE)
return -1;
if (chan->queued >= MAX_QUEUED)
{
#ifdef DEBUG_QUEUE
printk(KERN_DEBUG
"pcbit: %d packets already in queue - write fails\n",
chan->queued);
#endif
/*
* packet stays on the head of the device queue
* since dev_start_xmit will fail
* see net/core/dev.c
*/
#ifdef BLOCK_TIMER
if (chan->block_timer.function == NULL) {
init_timer(&chan->block_timer);
chan->block_timer.function = &pcbit_block_timer;
chan->block_timer.data = (long) chan;
chan->block_timer.expires = jiffies + 1 * HZ;
add_timer(&chan->block_timer);
}
#endif
return 0;
}
chan->queued++;
len = skb->len;
hdrlen = capi_tdata_req(chan, skb);
refnum = last_ref_num++ & 0x7fffU;
chan->s_refnum = refnum;
pcbit_l2_write(dev, MSG_TDATA_REQ, refnum, skb, hdrlen);
return len;
}
static int pcbit_writecmd(const u_char __user *buf, int len, int driver, int channel)
{
struct pcbit_dev *dev;
int i, j;
const u_char *loadbuf;
u_char *ptr = NULL;
u_char *cbuf;
int errstat;
dev = finddev(driver);
if (!dev)
{
printk("pcbit_writecmd: couldn't find device");
return -ENODEV;
}
switch (dev->l2_state) {
case L2_LWMODE:
/* check (size <= rdp_size); write buf into board */
if (len < 0 || len > BANK4 + 1 || len > 1024)
{
printk("pcbit_writecmd: invalid length %d\n", len);
return -EINVAL;
}
cbuf = memdup_user(buf, len);
if (IS_ERR(cbuf))
return PTR_ERR(cbuf);
memcpy_toio(dev->sh_mem, cbuf, len);
kfree(cbuf);
return len;
case L2_FWMODE:
/* this is the hard part */
/* dumb board */
/* get it into kernel space */
if ((ptr = kmalloc(len, GFP_KERNEL)) == NULL)
return -ENOMEM;
if (copy_from_user(ptr, buf, len)) {
kfree(ptr);
return -EFAULT;
}
loadbuf = ptr;
errstat = 0;
for (i = 0; i < len; i++)
{
for (j = 0; j < LOAD_RETRY; j++)
if (!(readb(dev->sh_mem + dev->loadptr)))
break;
if (j == LOAD_RETRY)
{
errstat = -ETIME;
printk("TIMEOUT i=%d\n", i);
break;
}
writeb(loadbuf[i], dev->sh_mem + dev->loadptr + 1);
writeb(0x01, dev->sh_mem + dev->loadptr);
dev->loadptr += 2;
if (dev->loadptr > LOAD_ZONE_END)
dev->loadptr = LOAD_ZONE_START;
}
kfree(ptr);
return errstat ? errstat : len;
default:
return -EBUSY;
}
}
/*
* demultiplexing of messages
*
*/
void pcbit_l3_receive(struct pcbit_dev *dev, ulong msg,
struct sk_buff *skb,
ushort hdr_len, ushort refnum)
{
struct pcbit_chan *chan;
struct sk_buff *skb2;
unsigned short len;
struct callb_data cbdata;
int complete, err;
isdn_ctrl ictl;
switch (msg) {
case MSG_TDATA_IND:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
chan->r_refnum = skb->data[7];
skb_pull(skb, 8);
dev->dev_if->rcvcallb_skb(dev->id, chan->id, skb);
if (capi_tdata_resp(chan, &skb2) > 0)
pcbit_l2_write(dev, MSG_TDATA_RESP, refnum,
skb2, skb2->len);
return;
break;
case MSG_TDATA_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
#ifdef DEBUG
if ((*((ushort *)(skb->data + 2))) != 0) {
printk(KERN_DEBUG "TDATA_CONF error\n");
}
#endif
#ifdef BLOCK_TIMER
if (chan->queued == MAX_QUEUED) {
del_timer(&chan->block_timer);
chan->block_timer.function = NULL;
}
#endif
chan->queued--;
ictl.driver = dev->id;
ictl.command = ISDN_STAT_BSENT;
ictl.arg = chan->id;
dev->dev_if->statcallb(&ictl);
break;
case MSG_CONN_IND:
/*
* channel: 1st not used will do
* if both are used we're in trouble
*/
if (!dev->b1->fsm_state)
chan = dev->b1;
else if (!dev->b2->fsm_state)
chan = dev->b2;
else {
printk(KERN_INFO
"Incoming connection: no channels available");
if ((len = capi_disc_req(*(ushort *)(skb->data), &skb2, CAUSE_NOCHAN)) > 0)
pcbit_l2_write(dev, MSG_DISC_REQ, refnum, skb2, len);
break;
}
cbdata.data.setup.CalledPN = NULL;
cbdata.data.setup.CallingPN = NULL;
capi_decode_conn_ind(chan, skb, &cbdata);
cbdata.type = EV_NET_SETUP;
pcbit_fsm_event(dev, chan, EV_NET_SETUP, NULL);
if (pcbit_check_msn(dev, cbdata.data.setup.CallingPN))
pcbit_fsm_event(dev, chan, EV_USR_PROCED_REQ, &cbdata);
else
pcbit_fsm_event(dev, chan, EV_USR_RELEASE_REQ, NULL);
kfree(cbdata.data.setup.CalledPN);
kfree(cbdata.data.setup.CallingPN);
break;
case MSG_CONN_CONF:
/*
* We should be able to find the channel by the message
* reference number. The current version of the firmware
* doesn't sent the ref number correctly.
*/
#ifdef DEBUG
printk(KERN_DEBUG "refnum=%04x b1=%04x b2=%04x\n", refnum,
dev->b1->s_refnum,
dev->b2->s_refnum);
#endif
/* We just try to find a channel in the right state */
if (dev->b1->fsm_state == ST_CALL_INIT)
chan = dev->b1;
else {
if (dev->b2->s_refnum == ST_CALL_INIT)
chan = dev->b2;
else {
chan = NULL;
printk(KERN_WARNING "Connection Confirm - no channel in Call Init state\n");
break;
}
}
if (capi_decode_conn_conf(chan, skb, &complete)) {
printk(KERN_DEBUG "conn_conf indicates error\n");
pcbit_fsm_event(dev, chan, EV_ERROR, NULL);
}
else
if (complete)
pcbit_fsm_event(dev, chan, EV_NET_CALL_PROC, NULL);
else
pcbit_fsm_event(dev, chan, EV_NET_SETUP_ACK, NULL);
break;
case MSG_CONN_ACTV_IND:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (capi_decode_conn_actv_ind(chan, skb)) {
printk("error in capi_decode_conn_actv_ind\n");
/* pcbit_fsm_event(dev, chan, EV_ERROR, NULL); */
break;
}
chan->r_refnum = refnum;
pcbit_fsm_event(dev, chan, EV_NET_CONN, NULL);
break;
case MSG_CONN_ACTV_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (capi_decode_conn_actv_conf(chan, skb) == 0)
pcbit_fsm_event(dev, chan, EV_NET_CONN_ACK, NULL);
else
printk(KERN_DEBUG "decode_conn_actv_conf failed\n");
break;
case MSG_SELP_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!(err = capi_decode_sel_proto_conf(chan, skb)))
pcbit_fsm_event(dev, chan, EV_NET_SELP_RESP, NULL);
else {
/* Error */
printk("error %d - capi_decode_sel_proto_conf\n", err);
}
break;
case MSG_ACT_TRANSP_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!capi_decode_actv_trans_conf(chan, skb))
pcbit_fsm_event(dev, chan, EV_NET_ACTV_RESP, NULL);
break;
case MSG_DISC_IND:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!capi_decode_disc_ind(chan, skb))
pcbit_fsm_event(dev, chan, EV_NET_DISC, NULL);
else
printk(KERN_WARNING "capi_decode_disc_ind - error\n");
break;
case MSG_DISC_CONF:
if (!(chan = capi_channel(dev, skb))) {
printk(KERN_WARNING
"CAPI header: unknown channel id\n");
break;
}
if (!capi_decode_disc_ind(chan, skb))
pcbit_fsm_event(dev, chan, EV_NET_RELEASE, NULL);
else
printk(KERN_WARNING "capi_decode_disc_conf - error\n");
break;
case MSG_INFO_IND:
#ifdef DEBUG
printk(KERN_DEBUG "received Info Indication - discarded\n");
#endif
break;
#ifdef DEBUG
case MSG_DEBUG_188:
capi_decode_debug_188(skb->data, skb->len);
break;
default:
printk(KERN_DEBUG "pcbit_l3_receive: unknown message %08lx\n",
msg);
break;
#endif
}
kfree_skb(skb);
}
/*
* Single statbuf
* should be a statbuf per device
*/
static char statbuf[STATBUF_LEN];
static int stat_st = 0;
static int stat_end = 0;
static int pcbit_stat(u_char __user *buf, int len, int driver, int channel)
{
int stat_count;
stat_count = stat_end - stat_st;
if (stat_count < 0)
stat_count = STATBUF_LEN - stat_st + stat_end;
/* FIXME: should we sleep and wait for more cookies ? */
if (len > stat_count)
len = stat_count;
if (stat_st < stat_end)
{
if (copy_to_user(buf, statbuf + stat_st, len))
return -EFAULT;
stat_st += len;
}
else
{
if (len > STATBUF_LEN - stat_st)
{
if (copy_to_user(buf, statbuf + stat_st,
STATBUF_LEN - stat_st))
return -EFAULT;
if (copy_to_user(buf, statbuf,
len - (STATBUF_LEN - stat_st)))
return -EFAULT;
stat_st = len - (STATBUF_LEN - stat_st);
}
else
{
if (copy_to_user(buf, statbuf + stat_st, len))
return -EFAULT;
stat_st += len;
if (stat_st == STATBUF_LEN)
stat_st = 0;
}
}
if (stat_st == stat_end)
stat_st = stat_end = 0;
return len;
}
static void pcbit_logstat(struct pcbit_dev *dev, char *str)
{
int i;
isdn_ctrl ictl;
for (i = stat_end; i < strlen(str); i++)
{
statbuf[i] = str[i];
stat_end = (stat_end + 1) % STATBUF_LEN;
if (stat_end == stat_st)
stat_st = (stat_st + 1) % STATBUF_LEN;
}
ictl.command = ISDN_STAT_STAVAIL;
ictl.driver = dev->id;
ictl.arg = strlen(str);
dev->dev_if->statcallb(&ictl);
}
void pcbit_state_change(struct pcbit_dev *dev, struct pcbit_chan *chan,
unsigned short i, unsigned short ev, unsigned short f)
{
char buf[256];
sprintf(buf, "change on device: %d channel:%d\n%s -> %s -> %s\n",
dev->id, chan->id,
isdn_state_table[i], strisdnevent(ev), isdn_state_table[f]
);
#ifdef DEBUG
printk("%s", buf);
#endif
pcbit_logstat(dev, buf);
}
static void set_running_timeout(unsigned long ptr)
{
struct pcbit_dev *dev;
#ifdef DEBUG
printk(KERN_DEBUG "set_running_timeout\n");
#endif
dev = (struct pcbit_dev *) ptr;
wake_up_interruptible(&dev->set_running_wq);
}
static int set_protocol_running(struct pcbit_dev *dev)
{
isdn_ctrl ctl;
init_timer(&dev->set_running_timer);
dev->set_running_timer.function = &set_running_timeout;
dev->set_running_timer.data = (ulong) dev;
dev->set_running_timer.expires = jiffies + SET_RUN_TIMEOUT;
/* kick it */
dev->l2_state = L2_STARTING;
writeb((0x80U | ((dev->rcv_seq & 0x07) << 3) | (dev->send_seq & 0x07)),
dev->sh_mem + BANK4);
add_timer(&dev->set_running_timer);
interruptible_sleep_on(&dev->set_running_wq);
del_timer(&dev->set_running_timer);
if (dev->l2_state == L2_RUNNING)
{
printk(KERN_DEBUG "pcbit: running\n");
dev->unack_seq = dev->send_seq;
dev->writeptr = dev->sh_mem;
dev->readptr = dev->sh_mem + BANK2;
/* tell the good news to the upper layer */
ctl.driver = dev->id;
ctl.command = ISDN_STAT_RUN;
dev->dev_if->statcallb(&ctl);
}
else
{
printk(KERN_DEBUG "pcbit: initialization failed\n");
printk(KERN_DEBUG "pcbit: firmware not loaded\n");
dev->l2_state = L2_DOWN;
#ifdef DEBUG
printk(KERN_DEBUG "Bank3 = %02x\n",
readb(dev->sh_mem + BANK3));
#endif
writeb(0x40, dev->sh_mem + BANK4);
/* warn the upper layer */
ctl.driver = dev->id;
ctl.command = ISDN_STAT_STOP;
dev->dev_if->statcallb(&ctl);
return -EL2HLT; /* Level 2 halted */
}
return 0;
}
static int pcbit_ioctl(isdn_ctrl *ctl)
{
struct pcbit_dev *dev;
struct pcbit_ioctl *cmd;
dev = finddev(ctl->driver);
if (!dev)
{
printk(KERN_DEBUG "pcbit_ioctl: unknown device\n");
return -ENODEV;
}
cmd = (struct pcbit_ioctl *) ctl->parm.num;
switch (ctl->arg) {
case PCBIT_IOCTL_GETSTAT:
cmd->info.l2_status = dev->l2_state;
break;
case PCBIT_IOCTL_STRLOAD:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
dev->unack_seq = dev->send_seq = dev->rcv_seq = 0;
dev->writeptr = dev->sh_mem;
dev->readptr = dev->sh_mem + BANK2;
dev->l2_state = L2_LOADING;
break;
case PCBIT_IOCTL_LWMODE:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
dev->l2_state = L2_LWMODE;
break;
case PCBIT_IOCTL_FWMODE:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
dev->loadptr = LOAD_ZONE_START;
dev->l2_state = L2_FWMODE;
break;
case PCBIT_IOCTL_ENDLOAD:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
dev->l2_state = L2_DOWN;
break;
case PCBIT_IOCTL_SETBYTE:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
/* check addr */
if (cmd->info.rdp_byte.addr > BANK4)
return -EFAULT;
writeb(cmd->info.rdp_byte.value, dev->sh_mem + cmd->info.rdp_byte.addr);
break;
case PCBIT_IOCTL_GETBYTE:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
/* check addr */
if (cmd->info.rdp_byte.addr > BANK4)
{
printk("getbyte: invalid addr %04x\n", cmd->info.rdp_byte.addr);
return -EFAULT;
}
cmd->info.rdp_byte.value = readb(dev->sh_mem + cmd->info.rdp_byte.addr);
break;
case PCBIT_IOCTL_RUNNING:
if (dev->l2_state == L2_RUNNING)
return -EBUSY;
return set_protocol_running(dev);
break;
case PCBIT_IOCTL_WATCH188:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
pcbit_l2_write(dev, MSG_WATCH188, 0x0001, NULL, 0);
break;
case PCBIT_IOCTL_PING188:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
pcbit_l2_write(dev, MSG_PING188_REQ, 0x0001, NULL, 0);
break;
case PCBIT_IOCTL_APION:
if (dev->l2_state != L2_LOADING)
return -EINVAL;
pcbit_l2_write(dev, MSG_API_ON, 0x0001, NULL, 0);
break;
case PCBIT_IOCTL_STOP:
dev->l2_state = L2_DOWN;
writeb(0x40, dev->sh_mem + BANK4);
dev->rcv_seq = 0;
dev->send_seq = 0;
dev->unack_seq = 0;
break;
default:
printk("error: unknown ioctl\n");
break;
};
return 0;
}
/*
* MSN list handling
*
* if null reject all calls
* if first entry has null MSN accept all calls
*/
static void pcbit_clear_msn(struct pcbit_dev *dev)
{
struct msn_entry *ptr, *back;
for (ptr = dev->msn_list; ptr;)
{
back = ptr->next;
kfree(ptr);
ptr = back;
}
dev->msn_list = NULL;
}
static void pcbit_set_msn(struct pcbit_dev *dev, char *list)
{
struct msn_entry *ptr;
struct msn_entry *back = NULL;
char *cp, *sp;
int len;
if (strlen(list) == 0) {
ptr = kmalloc(sizeof(struct msn_entry), GFP_ATOMIC);
if (!ptr) {
printk(KERN_WARNING "kmalloc failed\n");
return;
}
ptr->msn = NULL;
ptr->next = dev->msn_list;
dev->msn_list = ptr;
return;
}
if (dev->msn_list)
for (back = dev->msn_list; back->next; back = back->next);
sp = list;
do {
cp = strchr(sp, ',');
if (cp)
len = cp - sp;
else
len = strlen(sp);
ptr = kmalloc(sizeof(struct msn_entry), GFP_ATOMIC);
if (!ptr) {
printk(KERN_WARNING "kmalloc failed\n");
return;
}
ptr->next = NULL;
ptr->msn = kmalloc(len, GFP_ATOMIC);
if (!ptr->msn) {
printk(KERN_WARNING "kmalloc failed\n");
kfree(ptr);
return;
}
memcpy(ptr->msn, sp, len - 1);
ptr->msn[len] = 0;
#ifdef DEBUG
printk(KERN_DEBUG "msn: %s\n", ptr->msn);
#endif
if (dev->msn_list == NULL)
dev->msn_list = ptr;
else
back->next = ptr;
back = ptr;
sp += len;
} while (cp);
}
/*
* check if we do signal or reject an incoming call
*/
static int pcbit_check_msn(struct pcbit_dev *dev, char *msn)
{
struct msn_entry *ptr;
for (ptr = dev->msn_list; ptr; ptr = ptr->next) {
if (ptr->msn == NULL)
return 1;
if (strcmp(ptr->msn, msn) == 0)
return 1;
}
return 0;
}
| gpl-2.0 |
HTCKernels/One-SV-boost-k2cl | drivers/ps3/ps3stor_lib.c | 10011 | 9823 | /*
* PS3 Storage Library
*
* Copyright (C) 2007 Sony Computer Entertainment Inc.
* Copyright 2007 Sony Corp.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published
* by the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/dma-mapping.h>
#include <linux/module.h>
#include <asm/lv1call.h>
#include <asm/ps3stor.h>
/*
* A workaround for flash memory I/O errors when the internal hard disk
* has not been formatted for OtherOS use. Delay disk close until flash
* memory is closed.
*/
static struct ps3_flash_workaround {
int flash_open;
int disk_open;
struct ps3_system_bus_device *disk_sbd;
} ps3_flash_workaround;
static int ps3stor_open_hv_device(struct ps3_system_bus_device *sbd)
{
int error = ps3_open_hv_device(sbd);
if (error)
return error;
if (sbd->match_id == PS3_MATCH_ID_STOR_FLASH)
ps3_flash_workaround.flash_open = 1;
if (sbd->match_id == PS3_MATCH_ID_STOR_DISK)
ps3_flash_workaround.disk_open = 1;
return 0;
}
static int ps3stor_close_hv_device(struct ps3_system_bus_device *sbd)
{
int error;
if (sbd->match_id == PS3_MATCH_ID_STOR_DISK
&& ps3_flash_workaround.disk_open
&& ps3_flash_workaround.flash_open) {
ps3_flash_workaround.disk_sbd = sbd;
return 0;
}
error = ps3_close_hv_device(sbd);
if (error)
return error;
if (sbd->match_id == PS3_MATCH_ID_STOR_DISK)
ps3_flash_workaround.disk_open = 0;
if (sbd->match_id == PS3_MATCH_ID_STOR_FLASH) {
ps3_flash_workaround.flash_open = 0;
if (ps3_flash_workaround.disk_sbd) {
ps3_close_hv_device(ps3_flash_workaround.disk_sbd);
ps3_flash_workaround.disk_open = 0;
ps3_flash_workaround.disk_sbd = NULL;
}
}
return 0;
}
static int ps3stor_probe_access(struct ps3_storage_device *dev)
{
int res, error;
unsigned int i;
unsigned long n;
if (dev->sbd.match_id == PS3_MATCH_ID_STOR_ROM) {
/* special case: CD-ROM is assumed always accessible */
dev->accessible_regions = 1;
return 0;
}
error = -EPERM;
for (i = 0; i < dev->num_regions; i++) {
dev_dbg(&dev->sbd.core,
"%s:%u: checking accessibility of region %u\n",
__func__, __LINE__, i);
dev->region_idx = i;
res = ps3stor_read_write_sectors(dev, dev->bounce_lpar, 0, 1,
0);
if (res) {
dev_dbg(&dev->sbd.core, "%s:%u: read failed, "
"region %u is not accessible\n", __func__,
__LINE__, i);
continue;
}
dev_dbg(&dev->sbd.core, "%s:%u: region %u is accessible\n",
__func__, __LINE__, i);
set_bit(i, &dev->accessible_regions);
/* We can access at least one region */
error = 0;
}
if (error)
return error;
n = hweight_long(dev->accessible_regions);
if (n > 1)
dev_info(&dev->sbd.core,
"%s:%u: %lu accessible regions found. Only the first "
"one will be used\n",
__func__, __LINE__, n);
dev->region_idx = __ffs(dev->accessible_regions);
dev_info(&dev->sbd.core,
"First accessible region has index %u start %llu size %llu\n",
dev->region_idx, dev->regions[dev->region_idx].start,
dev->regions[dev->region_idx].size);
return 0;
}
/**
* ps3stor_setup - Setup a storage device before use
* @dev: Pointer to a struct ps3_storage_device
* @handler: Pointer to an interrupt handler
*
* Returns 0 for success, or an error code
*/
int ps3stor_setup(struct ps3_storage_device *dev, irq_handler_t handler)
{
int error, res, alignment;
enum ps3_dma_page_size page_size;
error = ps3stor_open_hv_device(&dev->sbd);
if (error) {
dev_err(&dev->sbd.core,
"%s:%u: ps3_open_hv_device failed %d\n", __func__,
__LINE__, error);
goto fail;
}
error = ps3_sb_event_receive_port_setup(&dev->sbd, PS3_BINDING_CPU_ANY,
&dev->irq);
if (error) {
dev_err(&dev->sbd.core,
"%s:%u: ps3_sb_event_receive_port_setup failed %d\n",
__func__, __LINE__, error);
goto fail_close_device;
}
error = request_irq(dev->irq, handler, 0,
dev->sbd.core.driver->name, dev);
if (error) {
dev_err(&dev->sbd.core, "%s:%u: request_irq failed %d\n",
__func__, __LINE__, error);
goto fail_sb_event_receive_port_destroy;
}
alignment = min(__ffs(dev->bounce_size),
__ffs((unsigned long)dev->bounce_buf));
if (alignment < 12) {
dev_err(&dev->sbd.core,
"%s:%u: bounce buffer not aligned (%lx at 0x%p)\n",
__func__, __LINE__, dev->bounce_size, dev->bounce_buf);
error = -EINVAL;
goto fail_free_irq;
} else if (alignment < 16)
page_size = PS3_DMA_4K;
else
page_size = PS3_DMA_64K;
dev->sbd.d_region = &dev->dma_region;
ps3_dma_region_init(&dev->sbd, &dev->dma_region, page_size,
PS3_DMA_OTHER, dev->bounce_buf, dev->bounce_size);
res = ps3_dma_region_create(&dev->dma_region);
if (res) {
dev_err(&dev->sbd.core, "%s:%u: cannot create DMA region\n",
__func__, __LINE__);
error = -ENOMEM;
goto fail_free_irq;
}
dev->bounce_lpar = ps3_mm_phys_to_lpar(__pa(dev->bounce_buf));
dev->bounce_dma = dma_map_single(&dev->sbd.core, dev->bounce_buf,
dev->bounce_size, DMA_BIDIRECTIONAL);
if (!dev->bounce_dma) {
dev_err(&dev->sbd.core, "%s:%u: map DMA region failed\n",
__func__, __LINE__);
error = -ENODEV;
goto fail_free_dma;
}
error = ps3stor_probe_access(dev);
if (error) {
dev_err(&dev->sbd.core, "%s:%u: No accessible regions found\n",
__func__, __LINE__);
goto fail_unmap_dma;
}
return 0;
fail_unmap_dma:
dma_unmap_single(&dev->sbd.core, dev->bounce_dma, dev->bounce_size,
DMA_BIDIRECTIONAL);
fail_free_dma:
ps3_dma_region_free(&dev->dma_region);
fail_free_irq:
free_irq(dev->irq, dev);
fail_sb_event_receive_port_destroy:
ps3_sb_event_receive_port_destroy(&dev->sbd, dev->irq);
fail_close_device:
ps3stor_close_hv_device(&dev->sbd);
fail:
return error;
}
EXPORT_SYMBOL_GPL(ps3stor_setup);
/**
* ps3stor_teardown - Tear down a storage device after use
* @dev: Pointer to a struct ps3_storage_device
*/
void ps3stor_teardown(struct ps3_storage_device *dev)
{
int error;
dma_unmap_single(&dev->sbd.core, dev->bounce_dma, dev->bounce_size,
DMA_BIDIRECTIONAL);
ps3_dma_region_free(&dev->dma_region);
free_irq(dev->irq, dev);
error = ps3_sb_event_receive_port_destroy(&dev->sbd, dev->irq);
if (error)
dev_err(&dev->sbd.core,
"%s:%u: destroy event receive port failed %d\n",
__func__, __LINE__, error);
error = ps3stor_close_hv_device(&dev->sbd);
if (error)
dev_err(&dev->sbd.core,
"%s:%u: ps3_close_hv_device failed %d\n", __func__,
__LINE__, error);
}
EXPORT_SYMBOL_GPL(ps3stor_teardown);
/**
* ps3stor_read_write_sectors - read/write from/to a storage device
* @dev: Pointer to a struct ps3_storage_device
* @lpar: HV logical partition address
* @start_sector: First sector to read/write
* @sectors: Number of sectors to read/write
* @write: Flag indicating write (non-zero) or read (zero)
*
* Returns 0 for success, -1 in case of failure to submit the command, or
* an LV1 status value in case of other errors
*/
u64 ps3stor_read_write_sectors(struct ps3_storage_device *dev, u64 lpar,
u64 start_sector, u64 sectors, int write)
{
unsigned int region_id = dev->regions[dev->region_idx].id;
const char *op = write ? "write" : "read";
int res;
dev_dbg(&dev->sbd.core, "%s:%u: %s %llu sectors starting at %llu\n",
__func__, __LINE__, op, sectors, start_sector);
init_completion(&dev->done);
res = write ? lv1_storage_write(dev->sbd.dev_id, region_id,
start_sector, sectors, 0, lpar,
&dev->tag)
: lv1_storage_read(dev->sbd.dev_id, region_id,
start_sector, sectors, 0, lpar,
&dev->tag);
if (res) {
dev_dbg(&dev->sbd.core, "%s:%u: %s failed %d\n", __func__,
__LINE__, op, res);
return -1;
}
wait_for_completion(&dev->done);
if (dev->lv1_status) {
dev_dbg(&dev->sbd.core, "%s:%u: %s failed 0x%llx\n", __func__,
__LINE__, op, dev->lv1_status);
return dev->lv1_status;
}
dev_dbg(&dev->sbd.core, "%s:%u: %s completed\n", __func__, __LINE__,
op);
return 0;
}
EXPORT_SYMBOL_GPL(ps3stor_read_write_sectors);
/**
* ps3stor_send_command - send a device command to a storage device
* @dev: Pointer to a struct ps3_storage_device
* @cmd: Command number
* @arg1: First command argument
* @arg2: Second command argument
* @arg3: Third command argument
* @arg4: Fourth command argument
*
* Returns 0 for success, -1 in case of failure to submit the command, or
* an LV1 status value in case of other errors
*/
u64 ps3stor_send_command(struct ps3_storage_device *dev, u64 cmd, u64 arg1,
u64 arg2, u64 arg3, u64 arg4)
{
int res;
dev_dbg(&dev->sbd.core, "%s:%u: send device command 0x%llx\n", __func__,
__LINE__, cmd);
init_completion(&dev->done);
res = lv1_storage_send_device_command(dev->sbd.dev_id, cmd, arg1,
arg2, arg3, arg4, &dev->tag);
if (res) {
dev_err(&dev->sbd.core,
"%s:%u: send_device_command 0x%llx failed %d\n",
__func__, __LINE__, cmd, res);
return -1;
}
wait_for_completion(&dev->done);
if (dev->lv1_status) {
dev_dbg(&dev->sbd.core, "%s:%u: command 0x%llx failed 0x%llx\n",
__func__, __LINE__, cmd, dev->lv1_status);
return dev->lv1_status;
}
dev_dbg(&dev->sbd.core, "%s:%u: command 0x%llx completed\n", __func__,
__LINE__, cmd);
return 0;
}
EXPORT_SYMBOL_GPL(ps3stor_send_command);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("PS3 Storage Bus Library");
MODULE_AUTHOR("Sony Corporation");
| gpl-2.0 |
CyanogenMod/android_kernel_lge_msm8974 | fs/jfs/resize.c | 10267 | 15083 | /*
* Copyright (C) International Business Machines Corp., 2000-2004
*
* 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/fs.h>
#include <linux/buffer_head.h>
#include <linux/quotaops.h>
#include "jfs_incore.h"
#include "jfs_filsys.h"
#include "jfs_metapage.h"
#include "jfs_dinode.h"
#include "jfs_imap.h"
#include "jfs_dmap.h"
#include "jfs_superblock.h"
#include "jfs_txnmgr.h"
#include "jfs_debug.h"
#define BITSPERPAGE (PSIZE << 3)
#define L2MEGABYTE 20
#define MEGABYTE (1 << L2MEGABYTE)
#define MEGABYTE32 (MEGABYTE << 5)
/* convert block number to bmap file page number */
#define BLKTODMAPN(b)\
(((b) >> 13) + ((b) >> 23) + ((b) >> 33) + 3 + 1)
/*
* jfs_extendfs()
*
* function: extend file system;
*
* |-------------------------------|----------|----------|
* file system space fsck inline log
* workspace space
*
* input:
* new LVSize: in LV blocks (required)
* new LogSize: in LV blocks (optional)
* new FSSize: in LV blocks (optional)
*
* new configuration:
* 1. set new LogSize as specified or default from new LVSize;
* 2. compute new FSCKSize from new LVSize;
* 3. set new FSSize as MIN(FSSize, LVSize-(LogSize+FSCKSize)) where
* assert(new FSSize >= old FSSize),
* i.e., file system must not be shrunk;
*/
int jfs_extendfs(struct super_block *sb, s64 newLVSize, int newLogSize)
{
int rc = 0;
struct jfs_sb_info *sbi = JFS_SBI(sb);
struct inode *ipbmap = sbi->ipbmap;
struct inode *ipbmap2;
struct inode *ipimap = sbi->ipimap;
struct jfs_log *log = sbi->log;
struct bmap *bmp = sbi->bmap;
s64 newLogAddress, newFSCKAddress;
int newFSCKSize;
s64 newMapSize = 0, mapSize;
s64 XAddress, XSize, nblocks, xoff, xaddr, t64;
s64 oldLVSize;
s64 newFSSize;
s64 VolumeSize;
int newNpages = 0, nPages, newPage, xlen, t32;
int tid;
int log_formatted = 0;
struct inode *iplist[1];
struct jfs_superblock *j_sb, *j_sb2;
s64 old_agsize;
int agsizechanged = 0;
struct buffer_head *bh, *bh2;
/* If the volume hasn't grown, get out now */
if (sbi->mntflag & JFS_INLINELOG)
oldLVSize = addressPXD(&sbi->logpxd) + lengthPXD(&sbi->logpxd);
else
oldLVSize = addressPXD(&sbi->fsckpxd) +
lengthPXD(&sbi->fsckpxd);
if (oldLVSize >= newLVSize) {
printk(KERN_WARNING
"jfs_extendfs: volume hasn't grown, returning\n");
goto out;
}
VolumeSize = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (VolumeSize) {
if (newLVSize > VolumeSize) {
printk(KERN_WARNING "jfs_extendfs: invalid size\n");
rc = -EINVAL;
goto out;
}
} else {
/* check the device */
bh = sb_bread(sb, newLVSize - 1);
if (!bh) {
printk(KERN_WARNING "jfs_extendfs: invalid size\n");
rc = -EINVAL;
goto out;
}
bforget(bh);
}
/* Can't extend write-protected drive */
if (isReadOnly(ipbmap)) {
printk(KERN_WARNING "jfs_extendfs: read-only file system\n");
rc = -EROFS;
goto out;
}
/*
* reconfigure LV spaces
* ---------------------
*
* validate new size, or, if not specified, determine new size
*/
/*
* reconfigure inline log space:
*/
if ((sbi->mntflag & JFS_INLINELOG)) {
if (newLogSize == 0) {
/*
* no size specified: default to 1/256 of aggregate
* size; rounded up to a megabyte boundary;
*/
newLogSize = newLVSize >> 8;
t32 = (1 << (20 - sbi->l2bsize)) - 1;
newLogSize = (newLogSize + t32) & ~t32;
newLogSize =
min(newLogSize, MEGABYTE32 >> sbi->l2bsize);
} else {
/*
* convert the newLogSize to fs blocks.
*
* Since this is given in megabytes, it will always be
* an even number of pages.
*/
newLogSize = (newLogSize * MEGABYTE) >> sbi->l2bsize;
}
} else
newLogSize = 0;
newLogAddress = newLVSize - newLogSize;
/*
* reconfigure fsck work space:
*
* configure it to the end of the logical volume regardless of
* whether file system extends to the end of the aggregate;
* Need enough 4k pages to cover:
* - 1 bit per block in aggregate rounded up to BPERDMAP boundary
* - 1 extra page to handle control page and intermediate level pages
* - 50 extra pages for the chkdsk service log
*/
t64 = ((newLVSize - newLogSize + BPERDMAP - 1) >> L2BPERDMAP)
<< L2BPERDMAP;
t32 = DIV_ROUND_UP(t64, BITSPERPAGE) + 1 + 50;
newFSCKSize = t32 << sbi->l2nbperpage;
newFSCKAddress = newLogAddress - newFSCKSize;
/*
* compute new file system space;
*/
newFSSize = newLVSize - newLogSize - newFSCKSize;
/* file system cannot be shrunk */
if (newFSSize < bmp->db_mapsize) {
rc = -EINVAL;
goto out;
}
/*
* If we're expanding enough that the inline log does not overlap
* the old one, we can format the new log before we quiesce the
* filesystem.
*/
if ((sbi->mntflag & JFS_INLINELOG) && (newLogAddress > oldLVSize)) {
if ((rc = lmLogFormat(log, newLogAddress, newLogSize)))
goto out;
log_formatted = 1;
}
/*
* quiesce file system
*
* (prepare to move the inline log and to prevent map update)
*
* block any new transactions and wait for completion of
* all wip transactions and flush modified pages s.t.
* on-disk file system is in consistent state and
* log is not required for recovery.
*/
txQuiesce(sb);
/* Reset size of direct inode */
sbi->direct_inode->i_size = sb->s_bdev->bd_inode->i_size;
if (sbi->mntflag & JFS_INLINELOG) {
/*
* deactivate old inline log
*/
lmLogShutdown(log);
/*
* mark on-disk super block for fs in transition;
*
* update on-disk superblock for the new space configuration
* of inline log space and fsck work space descriptors:
* N.B. FS descriptor is NOT updated;
*
* crash recovery:
* logredo(): if FM_EXTENDFS, return to fsck() for cleanup;
* fsck(): if FM_EXTENDFS, reformat inline log and fsck
* workspace from superblock inline log descriptor and fsck
* workspace descriptor;
*/
/* read in superblock */
if ((rc = readSuper(sb, &bh)))
goto error_out;
j_sb = (struct jfs_superblock *)bh->b_data;
/* mark extendfs() in progress */
j_sb->s_state |= cpu_to_le32(FM_EXTENDFS);
j_sb->s_xsize = cpu_to_le64(newFSSize);
PXDaddress(&j_sb->s_xfsckpxd, newFSCKAddress);
PXDlength(&j_sb->s_xfsckpxd, newFSCKSize);
PXDaddress(&j_sb->s_xlogpxd, newLogAddress);
PXDlength(&j_sb->s_xlogpxd, newLogSize);
/* synchronously update superblock */
mark_buffer_dirty(bh);
sync_dirty_buffer(bh);
brelse(bh);
/*
* format new inline log synchronously;
*
* crash recovery: if log move in progress,
* reformat log and exit success;
*/
if (!log_formatted)
if ((rc = lmLogFormat(log, newLogAddress, newLogSize)))
goto error_out;
/*
* activate new log
*/
log->base = newLogAddress;
log->size = newLogSize >> (L2LOGPSIZE - sb->s_blocksize_bits);
if ((rc = lmLogInit(log)))
goto error_out;
}
/*
* extend block allocation map
* ---------------------------
*
* extendfs() for new extension, retry after crash recovery;
*
* note: both logredo() and fsck() rebuild map from
* the bitmap and configuration parameter from superblock
* (disregarding all other control information in the map);
*
* superblock:
* s_size: aggregate size in physical blocks;
*/
/*
* compute the new block allocation map configuration
*
* map dinode:
* di_size: map file size in byte;
* di_nblocks: number of blocks allocated for map file;
* di_mapsize: number of blocks in aggregate (covered by map);
* map control page:
* db_mapsize: number of blocks in aggregate (covered by map);
*/
newMapSize = newFSSize;
/* number of data pages of new bmap file:
* roundup new size to full dmap page boundary and
* add 1 extra dmap page for next extendfs()
*/
t64 = (newMapSize - 1) + BPERDMAP;
newNpages = BLKTODMAPN(t64) + 1;
/*
* extend map from current map (WITHOUT growing mapfile)
*
* map new extension with unmapped part of the last partial
* dmap page, if applicable, and extra page(s) allocated
* at end of bmap by mkfs() or previous extendfs();
*/
extendBmap:
/* compute number of blocks requested to extend */
mapSize = bmp->db_mapsize;
XAddress = mapSize; /* eXtension Address */
XSize = newMapSize - mapSize; /* eXtension Size */
old_agsize = bmp->db_agsize; /* We need to know if this changes */
/* compute number of blocks that can be extended by current mapfile */
t64 = dbMapFileSizeToMapSize(ipbmap);
if (mapSize > t64) {
printk(KERN_ERR "jfs_extendfs: mapSize (0x%Lx) > t64 (0x%Lx)\n",
(long long) mapSize, (long long) t64);
rc = -EIO;
goto error_out;
}
nblocks = min(t64 - mapSize, XSize);
/*
* update map pages for new extension:
*
* update/init dmap and bubble up the control hierarchy
* incrementally fold up dmaps into upper levels;
* update bmap control page;
*/
if ((rc = dbExtendFS(ipbmap, XAddress, nblocks)))
goto error_out;
agsizechanged |= (bmp->db_agsize != old_agsize);
/*
* the map now has extended to cover additional nblocks:
* dn_mapsize = oldMapsize + nblocks;
*/
/* ipbmap->i_mapsize += nblocks; */
XSize -= nblocks;
/*
* grow map file to cover remaining extension
* and/or one extra dmap page for next extendfs();
*
* allocate new map pages and its backing blocks, and
* update map file xtree
*/
/* compute number of data pages of current bmap file */
nPages = ipbmap->i_size >> L2PSIZE;
/* need to grow map file ? */
if (nPages == newNpages)
goto finalizeBmap;
/*
* grow bmap file for the new map pages required:
*
* allocate growth at the start of newly extended region;
* bmap file only grows sequentially, i.e., both data pages
* and possibly xtree index pages may grow in append mode,
* s.t. logredo() can reconstruct pre-extension state
* by washing away bmap file of pages outside s_size boundary;
*/
/*
* journal map file growth as if a regular file growth:
* (note: bmap is created with di_mode = IFJOURNAL|IFREG);
*
* journaling of bmap file growth is not required since
* logredo() do/can not use log records of bmap file growth
* but it provides careful write semantics, pmap update, etc.;
*/
/* synchronous write of data pages: bmap data pages are
* cached in meta-data cache, and not written out
* by txCommit();
*/
filemap_fdatawait(ipbmap->i_mapping);
filemap_write_and_wait(ipbmap->i_mapping);
diWriteSpecial(ipbmap, 0);
newPage = nPages; /* first new page number */
xoff = newPage << sbi->l2nbperpage;
xlen = (newNpages - nPages) << sbi->l2nbperpage;
xlen = min(xlen, (int) nblocks) & ~(sbi->nbperpage - 1);
xaddr = XAddress;
tid = txBegin(sb, COMMIT_FORCE);
if ((rc = xtAppend(tid, ipbmap, 0, xoff, nblocks, &xlen, &xaddr, 0))) {
txEnd(tid);
goto error_out;
}
/* update bmap file size */
ipbmap->i_size += xlen << sbi->l2bsize;
inode_add_bytes(ipbmap, xlen << sbi->l2bsize);
iplist[0] = ipbmap;
rc = txCommit(tid, 1, &iplist[0], COMMIT_FORCE);
txEnd(tid);
if (rc)
goto error_out;
/*
* map file has been grown now to cover extension to further out;
* di_size = new map file size;
*
* if huge extension, the previous extension based on previous
* map file size may not have been sufficient to cover whole extension
* (it could have been used up for new map pages),
* but the newly grown map file now covers lot bigger new free space
* available for further extension of map;
*/
/* any more blocks to extend ? */
if (XSize)
goto extendBmap;
finalizeBmap:
/* finalize bmap */
dbFinalizeBmap(ipbmap);
/*
* update inode allocation map
* ---------------------------
*
* move iag lists from old to new iag;
* agstart field is not updated for logredo() to reconstruct
* iag lists if system crash occurs.
* (computation of ag number from agstart based on agsize
* will correctly identify the new ag);
*/
/* if new AG size the same as old AG size, done! */
if (agsizechanged) {
if ((rc = diExtendFS(ipimap, ipbmap)))
goto error_out;
/* finalize imap */
if ((rc = diSync(ipimap)))
goto error_out;
}
/*
* finalize
* --------
*
* extension is committed when on-disk super block is
* updated with new descriptors: logredo will recover
* crash before it to pre-extension state;
*/
/* sync log to skip log replay of bmap file growth transaction; */
/* lmLogSync(log, 1); */
/*
* synchronous write bmap global control page;
* for crash before completion of write
* logredo() will recover to pre-extendfs state;
* for crash after completion of write,
* logredo() will recover post-extendfs state;
*/
if ((rc = dbSync(ipbmap)))
goto error_out;
/*
* copy primary bmap inode to secondary bmap inode
*/
ipbmap2 = diReadSpecial(sb, BMAP_I, 1);
if (ipbmap2 == NULL) {
printk(KERN_ERR "jfs_extendfs: diReadSpecial(bmap) failed\n");
goto error_out;
}
memcpy(&JFS_IP(ipbmap2)->i_xtroot, &JFS_IP(ipbmap)->i_xtroot, 288);
ipbmap2->i_size = ipbmap->i_size;
ipbmap2->i_blocks = ipbmap->i_blocks;
diWriteSpecial(ipbmap2, 1);
diFreeSpecial(ipbmap2);
/*
* update superblock
*/
if ((rc = readSuper(sb, &bh)))
goto error_out;
j_sb = (struct jfs_superblock *)bh->b_data;
/* mark extendfs() completion */
j_sb->s_state &= cpu_to_le32(~FM_EXTENDFS);
j_sb->s_size = cpu_to_le64(bmp->db_mapsize <<
le16_to_cpu(j_sb->s_l2bfactor));
j_sb->s_agsize = cpu_to_le32(bmp->db_agsize);
/* update inline log space descriptor */
if (sbi->mntflag & JFS_INLINELOG) {
PXDaddress(&(j_sb->s_logpxd), newLogAddress);
PXDlength(&(j_sb->s_logpxd), newLogSize);
}
/* record log's mount serial number */
j_sb->s_logserial = cpu_to_le32(log->serial);
/* update fsck work space descriptor */
PXDaddress(&(j_sb->s_fsckpxd), newFSCKAddress);
PXDlength(&(j_sb->s_fsckpxd), newFSCKSize);
j_sb->s_fscklog = 1;
/* sb->s_fsckloglen remains the same */
/* Update secondary superblock */
bh2 = sb_bread(sb, SUPER2_OFF >> sb->s_blocksize_bits);
if (bh2) {
j_sb2 = (struct jfs_superblock *)bh2->b_data;
memcpy(j_sb2, j_sb, sizeof (struct jfs_superblock));
mark_buffer_dirty(bh);
sync_dirty_buffer(bh2);
brelse(bh2);
}
/* write primary superblock */
mark_buffer_dirty(bh);
sync_dirty_buffer(bh);
brelse(bh);
goto resume;
error_out:
jfs_error(sb, "jfs_extendfs");
resume:
/*
* resume file system transactions
*/
txResume(sb);
out:
return rc;
}
| gpl-2.0 |
ShinySide/SM-T900_Kernel | arch/sh/kernel/stacktrace.c | 11803 | 2180 | /*
* arch/sh/kernel/stacktrace.c
*
* Stack trace management functions
*
* Copyright (C) 2006 - 2008 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/sched.h>
#include <linux/stacktrace.h>
#include <linux/thread_info.h>
#include <linux/module.h>
#include <asm/unwinder.h>
#include <asm/ptrace.h>
#include <asm/stacktrace.h>
static int save_stack_stack(void *data, char *name)
{
return 0;
}
/*
* Save stack-backtrace addresses into a stack_trace buffer.
*/
static void save_stack_address(void *data, unsigned long addr, int reliable)
{
struct stack_trace *trace = data;
if (!reliable)
return;
if (trace->skip > 0) {
trace->skip--;
return;
}
if (trace->nr_entries < trace->max_entries)
trace->entries[trace->nr_entries++] = addr;
}
static const struct stacktrace_ops save_stack_ops = {
.stack = save_stack_stack,
.address = save_stack_address,
};
void save_stack_trace(struct stack_trace *trace)
{
unsigned long *sp = (unsigned long *)current_stack_pointer;
unwind_stack(current, NULL, sp, &save_stack_ops, trace);
if (trace->nr_entries < trace->max_entries)
trace->entries[trace->nr_entries++] = ULONG_MAX;
}
EXPORT_SYMBOL_GPL(save_stack_trace);
static void
save_stack_address_nosched(void *data, unsigned long addr, int reliable)
{
struct stack_trace *trace = (struct stack_trace *)data;
if (!reliable)
return;
if (in_sched_functions(addr))
return;
if (trace->skip > 0) {
trace->skip--;
return;
}
if (trace->nr_entries < trace->max_entries)
trace->entries[trace->nr_entries++] = addr;
}
static const struct stacktrace_ops save_stack_ops_nosched = {
.stack = save_stack_stack,
.address = save_stack_address_nosched,
};
void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace)
{
unsigned long *sp = (unsigned long *)tsk->thread.sp;
unwind_stack(current, NULL, sp, &save_stack_ops_nosched, trace);
if (trace->nr_entries < trace->max_entries)
trace->entries[trace->nr_entries++] = ULONG_MAX;
}
EXPORT_SYMBOL_GPL(save_stack_trace_tsk);
| gpl-2.0 |
suzuke/pdk7105-stm-kernel | arch/sparc/prom/printf.c | 12571 | 1728 | /*
* printf.c: Internal prom library printf facility.
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1997 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (c) 2002 Pete Zaitcev (zaitcev@yahoo.com)
*
* We used to warn all over the code: DO NOT USE prom_printf(),
* and yet people do. Anton's banking code was outputting banks
* with prom_printf for most of the 2.4 lifetime. Since an effective
* stick is not available, we deployed a carrot: an early printk
* through PROM by means of -p boot option. This ought to fix it.
* USE printk; if you need, deploy -p.
*/
#include <linux/kernel.h>
#include <linux/compiler.h>
#include <linux/spinlock.h>
#include <asm/openprom.h>
#include <asm/oplib.h>
#define CONSOLE_WRITE_BUF_SIZE 1024
static char ppbuf[1024];
static char console_write_buf[CONSOLE_WRITE_BUF_SIZE];
static DEFINE_RAW_SPINLOCK(console_write_lock);
void notrace prom_write(const char *buf, unsigned int n)
{
unsigned int dest_len;
unsigned long flags;
char *dest;
dest = console_write_buf;
raw_spin_lock_irqsave(&console_write_lock, flags);
dest_len = 0;
while (n-- != 0) {
char ch = *buf++;
if (ch == '\n') {
*dest++ = '\r';
dest_len++;
}
*dest++ = ch;
dest_len++;
if (dest_len >= CONSOLE_WRITE_BUF_SIZE - 1) {
prom_console_write_buf(console_write_buf, dest_len);
dest = console_write_buf;
dest_len = 0;
}
}
if (dest_len)
prom_console_write_buf(console_write_buf, dest_len);
raw_spin_unlock_irqrestore(&console_write_lock, flags);
}
void notrace prom_printf(const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i = vscnprintf(ppbuf, sizeof(ppbuf), fmt, args);
va_end(args);
prom_write(ppbuf, i);
}
| gpl-2.0 |
rodrigues-daniel/linux | drivers/pps/generators/pps_gen_parport.c | 12827 | 7191 | /*
* pps_gen_parport.c -- kernel parallel port PPS signal generator
*
*
* Copyright (C) 2009 Alexander Gordeev <lasaine@lvk.cs.msu.su>
*
* 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.
*/
/*
* TODO:
* fix issues when realtime clock is adjusted in a leap
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/hrtimer.h>
#include <linux/parport.h>
#define DRVDESC "parallel port PPS signal generator"
#define SIGNAL 0
#define NO_SIGNAL PARPORT_CONTROL_STROBE
/* module parameters */
#define SEND_DELAY_MAX 100000
static unsigned int send_delay = 30000;
MODULE_PARM_DESC(delay,
"Delay between setting and dropping the signal (ns)");
module_param_named(delay, send_delay, uint, 0);
#define SAFETY_INTERVAL 3000 /* set the hrtimer earlier for safety (ns) */
/* internal per port structure */
struct pps_generator_pp {
struct pardevice *pardev; /* parport device */
struct hrtimer timer;
long port_write_time; /* calibrated port write time (ns) */
};
static struct pps_generator_pp device = {
.pardev = NULL,
};
static int attached;
/* calibrated time between a hrtimer event and the reaction */
static long hrtimer_error = SAFETY_INTERVAL;
/* the kernel hrtimer event */
static enum hrtimer_restart hrtimer_event(struct hrtimer *timer)
{
struct timespec expire_time, ts1, ts2, ts3, dts;
struct pps_generator_pp *dev;
struct parport *port;
long lim, delta;
unsigned long flags;
/* We have to disable interrupts here. The idea is to prevent
* other interrupts on the same processor to introduce random
* lags while polling the clock. getnstimeofday() takes <1us on
* most machines while other interrupt handlers can take much
* more potentially.
*
* NB: approx time with blocked interrupts =
* send_delay + 3 * SAFETY_INTERVAL
*/
local_irq_save(flags);
/* first of all we get the time stamp... */
getnstimeofday(&ts1);
expire_time = ktime_to_timespec(hrtimer_get_softexpires(timer));
dev = container_of(timer, struct pps_generator_pp, timer);
lim = NSEC_PER_SEC - send_delay - dev->port_write_time;
/* check if we are late */
if (expire_time.tv_sec != ts1.tv_sec || ts1.tv_nsec > lim) {
local_irq_restore(flags);
pr_err("we are late this time %ld.%09ld\n",
ts1.tv_sec, ts1.tv_nsec);
goto done;
}
/* busy loop until the time is right for an assert edge */
do {
getnstimeofday(&ts2);
} while (expire_time.tv_sec == ts2.tv_sec && ts2.tv_nsec < lim);
/* set the signal */
port = dev->pardev->port;
port->ops->write_control(port, SIGNAL);
/* busy loop until the time is right for a clear edge */
lim = NSEC_PER_SEC - dev->port_write_time;
do {
getnstimeofday(&ts2);
} while (expire_time.tv_sec == ts2.tv_sec && ts2.tv_nsec < lim);
/* unset the signal */
port->ops->write_control(port, NO_SIGNAL);
getnstimeofday(&ts3);
local_irq_restore(flags);
/* update calibrated port write time */
dts = timespec_sub(ts3, ts2);
dev->port_write_time =
(dev->port_write_time + timespec_to_ns(&dts)) >> 1;
done:
/* update calibrated hrtimer error */
dts = timespec_sub(ts1, expire_time);
delta = timespec_to_ns(&dts);
/* If the new error value is bigger then the old, use the new
* value, if not then slowly move towards the new value. This
* way it should be safe in bad conditions and efficient in
* good conditions.
*/
if (delta >= hrtimer_error)
hrtimer_error = delta;
else
hrtimer_error = (3 * hrtimer_error + delta) >> 2;
/* update the hrtimer expire time */
hrtimer_set_expires(timer,
ktime_set(expire_time.tv_sec + 1,
NSEC_PER_SEC - (send_delay +
dev->port_write_time + SAFETY_INTERVAL +
2 * hrtimer_error)));
return HRTIMER_RESTART;
}
/* calibrate port write time */
#define PORT_NTESTS_SHIFT 5
static void calibrate_port(struct pps_generator_pp *dev)
{
struct parport *port = dev->pardev->port;
int i;
long acc = 0;
for (i = 0; i < (1 << PORT_NTESTS_SHIFT); i++) {
struct timespec a, b;
unsigned long irq_flags;
local_irq_save(irq_flags);
getnstimeofday(&a);
port->ops->write_control(port, NO_SIGNAL);
getnstimeofday(&b);
local_irq_restore(irq_flags);
b = timespec_sub(b, a);
acc += timespec_to_ns(&b);
}
dev->port_write_time = acc >> PORT_NTESTS_SHIFT;
pr_info("port write takes %ldns\n", dev->port_write_time);
}
static inline ktime_t next_intr_time(struct pps_generator_pp *dev)
{
struct timespec ts;
getnstimeofday(&ts);
return ktime_set(ts.tv_sec +
((ts.tv_nsec > 990 * NSEC_PER_MSEC) ? 1 : 0),
NSEC_PER_SEC - (send_delay +
dev->port_write_time + 3 * SAFETY_INTERVAL));
}
static void parport_attach(struct parport *port)
{
if (attached) {
/* we already have a port */
return;
}
device.pardev = parport_register_device(port, KBUILD_MODNAME,
NULL, NULL, NULL, PARPORT_FLAG_EXCL, &device);
if (!device.pardev) {
pr_err("couldn't register with %s\n", port->name);
return;
}
if (parport_claim_or_block(device.pardev) < 0) {
pr_err("couldn't claim %s\n", port->name);
goto err_unregister_dev;
}
pr_info("attached to %s\n", port->name);
attached = 1;
calibrate_port(&device);
hrtimer_init(&device.timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
device.timer.function = hrtimer_event;
hrtimer_start(&device.timer, next_intr_time(&device), HRTIMER_MODE_ABS);
return;
err_unregister_dev:
parport_unregister_device(device.pardev);
}
static void parport_detach(struct parport *port)
{
if (port->cad != device.pardev)
return; /* not our port */
hrtimer_cancel(&device.timer);
parport_release(device.pardev);
parport_unregister_device(device.pardev);
}
static struct parport_driver pps_gen_parport_driver = {
.name = KBUILD_MODNAME,
.attach = parport_attach,
.detach = parport_detach,
};
/* module staff */
static int __init pps_gen_parport_init(void)
{
int ret;
pr_info(DRVDESC "\n");
if (send_delay > SEND_DELAY_MAX) {
pr_err("delay value should be not greater"
" then %d\n", SEND_DELAY_MAX);
return -EINVAL;
}
ret = parport_register_driver(&pps_gen_parport_driver);
if (ret) {
pr_err("unable to register with parport\n");
return ret;
}
return 0;
}
static void __exit pps_gen_parport_exit(void)
{
parport_unregister_driver(&pps_gen_parport_driver);
pr_info("hrtimer avg error is %ldns\n", hrtimer_error);
}
module_init(pps_gen_parport_init);
module_exit(pps_gen_parport_exit);
MODULE_AUTHOR("Alexander Gordeev <lasaine@lvk.cs.msu.su>");
MODULE_DESCRIPTION(DRVDESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
GeyerA/android_kernel_samsung_tuna | arch/powerpc/boot/cuboot-85xx.c | 13851 | 1673 | /*
* Old U-boot compatibility for 85xx
*
* Author: Scott Wood <scottwood@freescale.com>
*
* Copyright (c) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "ops.h"
#include "stdio.h"
#include "cuboot.h"
#define TARGET_85xx
#define TARGET_HAS_ETH3
#include "ppcboot.h"
static bd_t bd;
static void platform_fixups(void)
{
void *soc;
dt_fixup_memory(bd.bi_memstart, bd.bi_memsize);
dt_fixup_mac_address_by_alias("ethernet0", bd.bi_enetaddr);
dt_fixup_mac_address_by_alias("ethernet1", bd.bi_enet1addr);
dt_fixup_mac_address_by_alias("ethernet2", bd.bi_enet2addr);
dt_fixup_mac_address_by_alias("ethernet3", bd.bi_enet3addr);
dt_fixup_cpu_clocks(bd.bi_intfreq, bd.bi_busfreq / 8, bd.bi_busfreq);
/* Unfortunately, the specific model number is encoded in the
* soc node name in existing dts files -- once that is fixed,
* this can do a simple path lookup.
*/
soc = find_node_by_devtype(NULL, "soc");
if (soc) {
void *serial = NULL;
setprop(soc, "bus-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
while ((serial = find_node_by_devtype(serial, "serial"))) {
if (get_parent(serial) != soc)
continue;
setprop(serial, "clock-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
}
}
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5,
unsigned long r6, unsigned long r7)
{
CUBOOT_INIT();
fdt_init(_dtb_start);
serial_console_init();
platform_ops.fixups = platform_fixups;
}
| gpl-2.0 |
Vegaviet-DevTeam/kernel-stock-4.4.2-ef63slk | arch/powerpc/boot/cuboot-85xx.c | 13851 | 1673 | /*
* Old U-boot compatibility for 85xx
*
* Author: Scott Wood <scottwood@freescale.com>
*
* Copyright (c) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "ops.h"
#include "stdio.h"
#include "cuboot.h"
#define TARGET_85xx
#define TARGET_HAS_ETH3
#include "ppcboot.h"
static bd_t bd;
static void platform_fixups(void)
{
void *soc;
dt_fixup_memory(bd.bi_memstart, bd.bi_memsize);
dt_fixup_mac_address_by_alias("ethernet0", bd.bi_enetaddr);
dt_fixup_mac_address_by_alias("ethernet1", bd.bi_enet1addr);
dt_fixup_mac_address_by_alias("ethernet2", bd.bi_enet2addr);
dt_fixup_mac_address_by_alias("ethernet3", bd.bi_enet3addr);
dt_fixup_cpu_clocks(bd.bi_intfreq, bd.bi_busfreq / 8, bd.bi_busfreq);
/* Unfortunately, the specific model number is encoded in the
* soc node name in existing dts files -- once that is fixed,
* this can do a simple path lookup.
*/
soc = find_node_by_devtype(NULL, "soc");
if (soc) {
void *serial = NULL;
setprop(soc, "bus-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
while ((serial = find_node_by_devtype(serial, "serial"))) {
if (get_parent(serial) != soc)
continue;
setprop(serial, "clock-frequency", &bd.bi_busfreq,
sizeof(bd.bi_busfreq));
}
}
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5,
unsigned long r6, unsigned long r7)
{
CUBOOT_INIT();
fdt_init(_dtb_start);
serial_console_init();
platform_ops.fixups = platform_fixups;
}
| gpl-2.0 |
android-on-pre/kernel_common | fs/dlm/util.c | 14875 | 4610 | /******************************************************************************
*******************************************************************************
**
** Copyright (C) 2005-2008 Red Hat, Inc. All rights reserved.
**
** This copyrighted material is made available to anyone wishing to use,
** modify, copy, or redistribute it subject to the terms and conditions
** of the GNU General Public License v.2.
**
*******************************************************************************
******************************************************************************/
#include "dlm_internal.h"
#include "rcom.h"
#include "util.h"
#define DLM_ERRNO_EDEADLK 35
#define DLM_ERRNO_EBADR 53
#define DLM_ERRNO_EBADSLT 57
#define DLM_ERRNO_EPROTO 71
#define DLM_ERRNO_EOPNOTSUPP 95
#define DLM_ERRNO_ETIMEDOUT 110
#define DLM_ERRNO_EINPROGRESS 115
static void header_out(struct dlm_header *hd)
{
hd->h_version = cpu_to_le32(hd->h_version);
hd->h_lockspace = cpu_to_le32(hd->h_lockspace);
hd->h_nodeid = cpu_to_le32(hd->h_nodeid);
hd->h_length = cpu_to_le16(hd->h_length);
}
static void header_in(struct dlm_header *hd)
{
hd->h_version = le32_to_cpu(hd->h_version);
hd->h_lockspace = le32_to_cpu(hd->h_lockspace);
hd->h_nodeid = le32_to_cpu(hd->h_nodeid);
hd->h_length = le16_to_cpu(hd->h_length);
}
/* higher errno values are inconsistent across architectures, so select
one set of values for on the wire */
static int to_dlm_errno(int err)
{
switch (err) {
case -EDEADLK:
return -DLM_ERRNO_EDEADLK;
case -EBADR:
return -DLM_ERRNO_EBADR;
case -EBADSLT:
return -DLM_ERRNO_EBADSLT;
case -EPROTO:
return -DLM_ERRNO_EPROTO;
case -EOPNOTSUPP:
return -DLM_ERRNO_EOPNOTSUPP;
case -ETIMEDOUT:
return -DLM_ERRNO_ETIMEDOUT;
case -EINPROGRESS:
return -DLM_ERRNO_EINPROGRESS;
}
return err;
}
static int from_dlm_errno(int err)
{
switch (err) {
case -DLM_ERRNO_EDEADLK:
return -EDEADLK;
case -DLM_ERRNO_EBADR:
return -EBADR;
case -DLM_ERRNO_EBADSLT:
return -EBADSLT;
case -DLM_ERRNO_EPROTO:
return -EPROTO;
case -DLM_ERRNO_EOPNOTSUPP:
return -EOPNOTSUPP;
case -DLM_ERRNO_ETIMEDOUT:
return -ETIMEDOUT;
case -DLM_ERRNO_EINPROGRESS:
return -EINPROGRESS;
}
return err;
}
void dlm_message_out(struct dlm_message *ms)
{
header_out(&ms->m_header);
ms->m_type = cpu_to_le32(ms->m_type);
ms->m_nodeid = cpu_to_le32(ms->m_nodeid);
ms->m_pid = cpu_to_le32(ms->m_pid);
ms->m_lkid = cpu_to_le32(ms->m_lkid);
ms->m_remid = cpu_to_le32(ms->m_remid);
ms->m_parent_lkid = cpu_to_le32(ms->m_parent_lkid);
ms->m_parent_remid = cpu_to_le32(ms->m_parent_remid);
ms->m_exflags = cpu_to_le32(ms->m_exflags);
ms->m_sbflags = cpu_to_le32(ms->m_sbflags);
ms->m_flags = cpu_to_le32(ms->m_flags);
ms->m_lvbseq = cpu_to_le32(ms->m_lvbseq);
ms->m_hash = cpu_to_le32(ms->m_hash);
ms->m_status = cpu_to_le32(ms->m_status);
ms->m_grmode = cpu_to_le32(ms->m_grmode);
ms->m_rqmode = cpu_to_le32(ms->m_rqmode);
ms->m_bastmode = cpu_to_le32(ms->m_bastmode);
ms->m_asts = cpu_to_le32(ms->m_asts);
ms->m_result = cpu_to_le32(to_dlm_errno(ms->m_result));
}
void dlm_message_in(struct dlm_message *ms)
{
header_in(&ms->m_header);
ms->m_type = le32_to_cpu(ms->m_type);
ms->m_nodeid = le32_to_cpu(ms->m_nodeid);
ms->m_pid = le32_to_cpu(ms->m_pid);
ms->m_lkid = le32_to_cpu(ms->m_lkid);
ms->m_remid = le32_to_cpu(ms->m_remid);
ms->m_parent_lkid = le32_to_cpu(ms->m_parent_lkid);
ms->m_parent_remid = le32_to_cpu(ms->m_parent_remid);
ms->m_exflags = le32_to_cpu(ms->m_exflags);
ms->m_sbflags = le32_to_cpu(ms->m_sbflags);
ms->m_flags = le32_to_cpu(ms->m_flags);
ms->m_lvbseq = le32_to_cpu(ms->m_lvbseq);
ms->m_hash = le32_to_cpu(ms->m_hash);
ms->m_status = le32_to_cpu(ms->m_status);
ms->m_grmode = le32_to_cpu(ms->m_grmode);
ms->m_rqmode = le32_to_cpu(ms->m_rqmode);
ms->m_bastmode = le32_to_cpu(ms->m_bastmode);
ms->m_asts = le32_to_cpu(ms->m_asts);
ms->m_result = from_dlm_errno(le32_to_cpu(ms->m_result));
}
void dlm_rcom_out(struct dlm_rcom *rc)
{
header_out(&rc->rc_header);
rc->rc_type = cpu_to_le32(rc->rc_type);
rc->rc_result = cpu_to_le32(rc->rc_result);
rc->rc_id = cpu_to_le64(rc->rc_id);
rc->rc_seq = cpu_to_le64(rc->rc_seq);
rc->rc_seq_reply = cpu_to_le64(rc->rc_seq_reply);
}
void dlm_rcom_in(struct dlm_rcom *rc)
{
header_in(&rc->rc_header);
rc->rc_type = le32_to_cpu(rc->rc_type);
rc->rc_result = le32_to_cpu(rc->rc_result);
rc->rc_id = le64_to_cpu(rc->rc_id);
rc->rc_seq = le64_to_cpu(rc->rc_seq);
rc->rc_seq_reply = le64_to_cpu(rc->rc_seq_reply);
}
| gpl-2.0 |
Dm47021/android_kernel_afyonlte | drivers/video/msm/mdss/mdss_io_util.c | 28 | 12705 | /* 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/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/delay.h>
#include "mdss_io_util.h"
#define MAX_I2C_CMDS 16
void dss_reg_w(struct dss_io_data *io, u32 offset, u32 value, u32 debug)
{
u32 in_val;
if (!io || !io->base) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return;
}
if (offset > io->len) {
DEV_ERR("%pS->%s: offset out of range\n",
__builtin_return_address(0), __func__);
return;
}
writel_relaxed(value, io->base + offset);
if (debug) {
in_val = readl_relaxed(io->base + offset);
DEV_DBG("[%08x] => %08x [%08x]\n", (u32)(io->base + offset),
value, in_val);
}
} /* dss_reg_w */
u32 dss_reg_r(struct dss_io_data *io, u32 offset, u32 debug)
{
u32 value;
if (!io || !io->base) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return -EINVAL;
}
if (offset > io->len) {
DEV_ERR("%pS->%s: offset out of range\n",
__builtin_return_address(0), __func__);
return -EINVAL;
}
value = readl_relaxed(io->base + offset);
if (debug)
DEV_DBG("[%08x] <= %08x\n", (u32)(io->base + offset), value);
return value;
} /* dss_reg_r */
void dss_reg_dump(void __iomem *base, u32 length, const char *prefix,
u32 debug)
{
if (debug)
print_hex_dump(KERN_INFO, prefix, DUMP_PREFIX_OFFSET, 32, 4,
(void *)base, length, false);
} /* dss_reg_dump */
static struct resource *msm_dss_get_res_byname(struct platform_device *pdev,
unsigned int type, const char *name)
{
struct resource *res = NULL;
res = platform_get_resource_byname(pdev, type, name);
if (!res)
DEV_ERR("%s: '%s' resource not found\n", __func__, name);
return res;
} /* msm_dss_get_res_byname */
int msm_dss_ioremap_byname(struct platform_device *pdev,
struct dss_io_data *io_data, const char *name)
{
struct resource *res = NULL;
if (!pdev || !io_data) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return -EINVAL;
}
res = msm_dss_get_res_byname(pdev, IORESOURCE_MEM, name);
if (!res) {
DEV_ERR("%pS->%s: '%s' msm_dss_get_res_byname failed\n",
__builtin_return_address(0), __func__, name);
return -ENODEV;
}
io_data->len = resource_size(res);
io_data->base = ioremap(res->start, io_data->len);
if (!io_data->base) {
DEV_ERR("%pS->%s: '%s' ioremap failed\n",
__builtin_return_address(0), __func__, name);
return -EIO;
}
return 0;
} /* msm_dss_ioremap_byname */
void msm_dss_iounmap(struct dss_io_data *io_data)
{
if (!io_data) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return;
}
if (io_data->base) {
iounmap(io_data->base);
io_data->base = NULL;
}
io_data->len = 0;
} /* msm_dss_iounmap */
int msm_dss_config_vreg(struct device *dev, struct dss_vreg *in_vreg,
int num_vreg, int config)
{
int i = 0, rc = 0;
struct dss_vreg *curr_vreg = NULL;
enum dss_vreg_type type;
if (config) {
for (i = 0; i < num_vreg; i++) {
curr_vreg = &in_vreg[i];
curr_vreg->vreg = regulator_get(dev,
curr_vreg->vreg_name);
rc = PTR_RET(curr_vreg->vreg);
if (rc) {
DEV_ERR("%pS->%s: %s get failed. rc=%d\n",
__builtin_return_address(0), __func__,
curr_vreg->vreg_name, rc);
curr_vreg->vreg = NULL;
goto vreg_get_fail;
}
type = (regulator_count_voltages(curr_vreg->vreg) > 0)
? DSS_REG_LDO : DSS_REG_VS;
if (type == DSS_REG_LDO) {
rc = regulator_set_voltage(
curr_vreg->vreg,
curr_vreg->min_voltage,
curr_vreg->max_voltage);
if (rc < 0) {
DEV_ERR("%pS->%s: %s set vltg fail\n",
__builtin_return_address(0),
__func__,
curr_vreg->vreg_name);
goto vreg_set_voltage_fail;
}
}
}
} else {
for (i = num_vreg-1; i >= 0; i--) {
curr_vreg = &in_vreg[i];
if (curr_vreg->vreg) {
type = (regulator_count_voltages(
curr_vreg->vreg) > 0)
? DSS_REG_LDO : DSS_REG_VS;
if (type == DSS_REG_LDO) {
regulator_set_voltage(curr_vreg->vreg,
0, curr_vreg->max_voltage);
}
regulator_put(curr_vreg->vreg);
curr_vreg->vreg = NULL;
}
}
}
return 0;
vreg_unconfig:
if (type == DSS_REG_LDO)
regulator_set_optimum_mode(curr_vreg->vreg, 0);
vreg_set_voltage_fail:
regulator_put(curr_vreg->vreg);
curr_vreg->vreg = NULL;
vreg_get_fail:
for (i--; i >= 0; i--) {
curr_vreg = &in_vreg[i];
type = (regulator_count_voltages(curr_vreg->vreg) > 0)
? DSS_REG_LDO : DSS_REG_VS;
goto vreg_unconfig;
}
return rc;
} /* msm_dss_config_vreg */
#ifdef CONFIG_MACH_KSPORTSLTE_SPR
extern unsigned int system_rev;
#endif
int msm_dss_enable_vreg(struct dss_vreg *in_vreg, int num_vreg, int enable)
{
int i = 0, rc = 0;
if (enable) {
for (i = 0; i < num_vreg; i++) {
#if defined(CONFIG_MACH_MONDRIAN) || defined(CONFIG_MACH_CHAGALL)
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4)) {
pr_info("%s : VDD enable skip!!\n", __func__);
continue;
}
#endif
#ifdef CONFIG_MACH_KSPORTSLTE_SPR
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4) && (system_rev == 2)) {
pr_info("%s : VDD enable skip!! rev(%d)\n",in_vreg[i].vreg_name, system_rev);
continue;
}
#endif
#ifdef CONFIG_FB_MSM_MIPI_MAGNA_OCTA_VIDEO_WXGA_PT_DUAL_PANEL
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4)) {
continue;
}
#endif
rc = PTR_RET(in_vreg[i].vreg);
if (rc) {
DEV_ERR("%pS->%s: %s regulator error. rc=%d\n",
__builtin_return_address(0), __func__,
in_vreg[i].vreg_name, rc);
goto vreg_set_opt_mode_fail;
}
if (in_vreg[i].pre_on_sleep)
msleep(in_vreg[i].pre_on_sleep);
rc = regulator_set_optimum_mode(in_vreg[i].vreg,
in_vreg[i].enable_load);
if (rc < 0) {
DEV_ERR("%pS->%s: %s set opt m fail\n",
__builtin_return_address(0), __func__,
in_vreg[i].vreg_name);
goto vreg_set_opt_mode_fail;
}
rc = regulator_enable(in_vreg[i].vreg);
if (in_vreg[i].post_on_sleep)
msleep(in_vreg[i].post_on_sleep);
if (rc < 0) {
DEV_ERR("%pS->%s: %s enable failed\n",
__builtin_return_address(0), __func__,
in_vreg[i].vreg_name);
goto disable_vreg;
}
}
} else {
for (i = num_vreg-1; i >= 0; i--)
if (regulator_is_enabled(in_vreg[i].vreg)) {
#if defined(CONFIG_MACH_MONDRIAN) || defined(CONFIG_MACH_CHAGALL)
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4)) {
pr_info("%s : VDD disable skip!!\n", __func__);
continue;
}
#endif
#ifdef CONFIG_MACH_KANAS3G_CTC
if(!strncmp(in_vreg[i].vreg_name, "vdd", 3)) {
continue;
}
#endif
#ifdef CONFIG_MACH_KSPORTSLTE_SPR
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4) && (system_rev == 2)) {
pr_info("%s : VDD disable skip!! rev(%d)\n",in_vreg[i].vreg_name, system_rev);
continue;
}
#endif
if (in_vreg[i].pre_off_sleep)
msleep(in_vreg[i].pre_off_sleep);
regulator_set_optimum_mode(in_vreg[i].vreg,
in_vreg[i].disable_load);
regulator_disable(in_vreg[i].vreg);
if (in_vreg[i].post_off_sleep)
msleep(in_vreg[i].post_off_sleep);
}
}
return rc;
disable_vreg:
regulator_set_optimum_mode(in_vreg[i].vreg, in_vreg[i].disable_load);
vreg_set_opt_mode_fail:
for (i--; i >= 0; i--) {
if (in_vreg[i].pre_off_sleep)
msleep(in_vreg[i].pre_off_sleep);
regulator_set_optimum_mode(in_vreg[i].vreg,
in_vreg[i].disable_load);
regulator_disable(in_vreg[i].vreg);
if (in_vreg[i].post_off_sleep)
msleep(in_vreg[i].post_off_sleep);
}
return rc;
} /* msm_dss_enable_vreg */
int msm_dss_enable_gpio(struct dss_gpio *in_gpio, int num_gpio, int enable)
{
int i = 0, rc = 0;
if (enable) {
for (i = 0; i < num_gpio; i++) {
DEV_DBG("%pS->%s: %s enable\n",
__builtin_return_address(0), __func__,
in_gpio[i].gpio_name);
rc = gpio_request(in_gpio[i].gpio,
in_gpio[i].gpio_name);
if (rc < 0) {
DEV_ERR("%pS->%s: %s enable failed\n",
__builtin_return_address(0), __func__,
in_gpio[i].gpio_name);
goto disable_gpio;
}
gpio_set_value(in_gpio[i].gpio, in_gpio[i].value);
}
} else {
for (i = num_gpio-1; i >= 0; i--) {
DEV_DBG("%pS->%s: %s disable\n",
__builtin_return_address(0), __func__,
in_gpio[i].gpio_name);
if (in_gpio[i].gpio)
gpio_free(in_gpio[i].gpio);
}
}
return rc;
disable_gpio:
for (i--; i >= 0; i--)
if (in_gpio[i].gpio)
gpio_free(in_gpio[i].gpio);
return rc;
} /* msm_dss_enable_gpio */
void msm_dss_put_clk(struct dss_clk *clk_arry, int num_clk)
{
int i;
for (i = num_clk - 1; i >= 0; i--) {
if (clk_arry[i].clk)
clk_put(clk_arry[i].clk);
clk_arry[i].clk = NULL;
}
} /* msm_dss_put_clk */
int msm_dss_get_clk(struct device *dev, struct dss_clk *clk_arry, int num_clk)
{
int i, rc = 0;
for (i = 0; i < num_clk; i++) {
clk_arry[i].clk = clk_get(dev, clk_arry[i].clk_name);
rc = PTR_RET(clk_arry[i].clk);
if (rc) {
DEV_ERR("%pS->%s: '%s' get failed. rc=%d\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name, rc);
goto error;
}
}
return rc;
error:
msm_dss_put_clk(clk_arry, num_clk);
return rc;
} /* msm_dss_get_clk */
int msm_dss_clk_set_rate(struct dss_clk *clk_arry, int num_clk)
{
int i, rc = 0;
for (i = 0; i < num_clk; i++) {
if (clk_arry[i].clk) {
if (DSS_CLK_AHB != clk_arry[i].type) {
DEV_DBG("%pS->%s: '%s' rate %ld\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name,
clk_arry[i].rate);
rc = clk_set_rate(clk_arry[i].clk,
clk_arry[i].rate);
if (rc) {
DEV_ERR("%pS->%s: %s failed. rc=%d\n",
__builtin_return_address(0),
__func__,
clk_arry[i].clk_name, rc);
break;
}
}
} else {
DEV_ERR("%pS->%s: '%s' is not available\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
rc = -EPERM;
break;
}
}
return rc;
} /* msm_dss_clk_set_rate */
int msm_dss_enable_clk(struct dss_clk *clk_arry, int num_clk, int enable)
{
int i, rc = 0;
if (enable) {
for (i = 0; i < num_clk; i++) {
DEV_DBG("%pS->%s: enable '%s'\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
if (clk_arry[i].clk) {
rc = clk_prepare_enable(clk_arry[i].clk);
if (rc)
DEV_ERR("%pS->%s: %s en fail. rc=%d\n",
__builtin_return_address(0),
__func__,
clk_arry[i].clk_name, rc);
} else {
DEV_ERR("%pS->%s: '%s' is not available\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
rc = -EPERM;
}
if (rc) {
msm_dss_enable_clk(&clk_arry[i],
i, false);
break;
}
}
} else {
for (i = num_clk - 1; i >= 0; i--) {
DEV_DBG("%pS->%s: disable '%s'\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
if (clk_arry[i].clk)
clk_disable_unprepare(clk_arry[i].clk);
else
DEV_ERR("%pS->%s: '%s' is not available\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
}
}
return rc;
} /* msm_dss_enable_clk */
int mdss_i2c_byte_read(struct i2c_client *client, uint8_t slave_addr,
uint8_t reg_offset, uint8_t *read_buf)
{
struct i2c_msg msgs[2];
int ret = -1;
pr_debug("%s: reading from slave_addr=[%x] and offset=[%x]\n",
__func__, slave_addr, reg_offset);
msgs[0].addr = slave_addr >> 1;
msgs[0].flags = 0;
msgs[0].buf = ®_offset;
msgs[0].len = 1;
msgs[1].addr = slave_addr >> 1;
msgs[1].flags = I2C_M_RD;
msgs[1].buf = read_buf;
msgs[1].len = 1;
ret = i2c_transfer(client->adapter, msgs, 2);
if (ret < 1) {
pr_err("%s: I2C READ FAILED=[%d]\n", __func__, ret);
return -EACCES;
}
pr_debug("%s: i2c buf is [%x]\n", __func__, *read_buf);
return 0;
}
int mdss_i2c_byte_write(struct i2c_client *client, uint8_t slave_addr,
uint8_t reg_offset, uint8_t *value)
{
struct i2c_msg msgs[1];
uint8_t data[2];
int status = -EACCES;
pr_debug("%s: writing from slave_addr=[%x] and offset=[%x]\n",
__func__, slave_addr, reg_offset);
data[0] = reg_offset;
data[1] = *value;
msgs[0].addr = slave_addr >> 1;
msgs[0].flags = 0;
msgs[0].len = 2;
msgs[0].buf = data;
status = i2c_transfer(client->adapter, msgs, 1);
if (status < 1) {
pr_err("I2C WRITE FAILED=[%d]\n", status);
return -EACCES;
}
pr_debug("%s: I2C write status=%x\n", __func__, status);
return status;
}
| gpl-2.0 |
aginor/wesnoth | src/lua/lobject.cpp | 28 | 7842 | /*
** Some generic functions over Lua objects
** See Copyright Notice in lua.h
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lobject_c
#define LUA_CORE
#include "lua.h"
#include "lctype.h"
#include "ldebug.h"
#include "ldo.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "lvm.h"
LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
/*
** converts an integer to a "floating point byte", represented as
** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
** eeeee != 0 and (xxx) otherwise.
*/
int luaO_int2fb (unsigned int x) {
int e = 0; /* exponent */
if (x < 8) return x;
while (x >= 0x10) {
x = (x+1) >> 1;
e++;
}
return ((e+1) << 3) | (cast_int(x) - 8);
}
/* converts back */
int luaO_fb2int (int x) {
int e = (x >> 3) & 0x1f;
if (e == 0) return x;
else return ((x & 7) + 8) << (e - 1);
}
int luaO_ceillog2 (unsigned int x) {
static const lu_byte log_2[256] = {
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
};
int l = 0;
x--;
while (x >= 256) { l += 8; x >>= 8; }
return l + log_2[x];
}
lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {
switch (op) {
case LUA_OPADD: return luai_numadd(NULL, v1, v2);
case LUA_OPSUB: return luai_numsub(NULL, v1, v2);
case LUA_OPMUL: return luai_nummul(NULL, v1, v2);
case LUA_OPDIV: return luai_numdiv(NULL, v1, v2);
case LUA_OPMOD: return luai_nummod(NULL, v1, v2);
case LUA_OPPOW: return luai_numpow(NULL, v1, v2);
case LUA_OPUNM: return luai_numunm(NULL, v1);
default: lua_assert(0); return 0;
}
}
int luaO_hexavalue (int c) {
if (lisdigit(c)) return c - '0';
else return ltolower(c) - 'a' + 10;
}
#if !defined(lua_strx2number)
#include <math.h>
static int isneg (const char **s) {
if (**s == '-') { (*s)++; return 1; }
else if (**s == '+') (*s)++;
return 0;
}
static lua_Number readhexa (const char **s, lua_Number r, int *count) {
for (; lisxdigit(cast_uchar(**s)); (*s)++) { /* read integer part */
r = (r * cast_num(16.0)) + cast_num(luaO_hexavalue(cast_uchar(**s)));
(*count)++;
}
return r;
}
/*
** convert an hexadecimal numeric string to a number, following
** C99 specification for 'strtod'
*/
static lua_Number lua_strx2number (const char *s, char **endptr) {
lua_Number r = 0.0;
int e = 0, i = 0;
int neg = 0; /* 1 if number is negative */
*endptr = cast(char *, s); /* nothing is valid yet */
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
neg = isneg(&s); /* check signal */
if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
return 0.0; /* invalid format (no '0x') */
s += 2; /* skip '0x' */
r = readhexa(&s, r, &i); /* read integer part */
if (*s == '.') {
s++; /* skip dot */
r = readhexa(&s, r, &e); /* read fractional part */
}
if (i == 0 && e == 0)
return 0.0; /* invalid format (no digit) */
e *= -4; /* each fractional digit divides value by 2^-4 */
*endptr = cast(char *, s); /* valid up to here */
if (*s == 'p' || *s == 'P') { /* exponent part? */
int exp1 = 0;
int neg1;
s++; /* skip 'p' */
neg1 = isneg(&s); /* signal */
if (!lisdigit(cast_uchar(*s)))
goto ret; /* must have at least one digit */
while (lisdigit(cast_uchar(*s))) /* read exponent */
exp1 = exp1 * 10 + *(s++) - '0';
if (neg1) exp1 = -exp1;
e += exp1;
}
*endptr = cast(char *, s); /* valid up to here */
ret:
if (neg) r = -r;
return l_mathop(ldexp)(r, e);
}
#endif
int luaO_str2d (const char *s, size_t len, lua_Number *result) {
char *endptr;
if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */
return 0;
else if (strpbrk(s, "xX")) /* hexa? */
*result = lua_strx2number(s, &endptr);
else
*result = lua_str2number(s, &endptr);
if (endptr == s) return 0; /* nothing recognized */
while (lisspace(cast_uchar(*endptr))) endptr++;
return (endptr == s + len); /* OK if no trailing characters */
}
static void pushstr (lua_State *L, const char *str, size_t l) {
setsvalue2s(L, L->top++, luaS_newlstr(L, str, l));
}
/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
int n = 0;
for (;;) {
const char *e = strchr(fmt, '%');
if (e == NULL) break;
luaD_checkstack(L, 2); /* fmt + item */
pushstr(L, fmt, e - fmt);
switch (*(e+1)) {
case 's': {
const char *s = va_arg(argp, char *);
if (s == NULL) s = "(null)";
pushstr(L, s, strlen(s));
break;
}
case 'c': {
char buff;
buff = cast(char, va_arg(argp, int));
pushstr(L, &buff, 1);
break;
}
case 'd': {
setnvalue(L->top++, cast_num(va_arg(argp, int)));
break;
}
case 'f': {
setnvalue(L->top++, cast_num(va_arg(argp, l_uacNumber)));
break;
}
case 'p': {
char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
int l = sprintf(buff, "%p", va_arg(argp, void *));
pushstr(L, buff, l);
break;
}
case '%': {
pushstr(L, "%", 1);
break;
}
default: {
luaG_runerror(L,
"invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"),
*(e + 1));
}
}
n += 2;
fmt = e+2;
}
luaD_checkstack(L, 1);
pushstr(L, fmt, strlen(fmt));
if (n > 0) luaV_concat(L, n + 1);
return svalue(L->top - 1);
}
const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
const char *msg;
va_list argp;
va_start(argp, fmt);
msg = luaO_pushvfstring(L, fmt, argp);
va_end(argp);
return msg;
}
/* number of chars of a literal string without the ending \0 */
#define LL(x) (sizeof(x)/sizeof(char) - 1)
#define RETS "..."
#define PRE "[string \""
#define POS "\"]"
#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
void luaO_chunkid (char *out, const char *source, size_t bufflen) {
size_t l = strlen(source);
if (*source == '=') { /* 'literal' source */
if (l <= bufflen) /* small enough? */
memcpy(out, source + 1, l * sizeof(char));
else { /* truncate it */
addstr(out, source + 1, bufflen - 1);
*out = '\0';
}
}
else if (*source == '@') { /* file name */
if (l <= bufflen) /* small enough? */
memcpy(out, source + 1, l * sizeof(char));
else { /* add '...' before rest of name */
addstr(out, RETS, LL(RETS));
bufflen -= LL(RETS);
memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
}
}
else { /* string; format as [string "source"] */
const char *nl = strchr(source, '\n'); /* find first new line (if any) */
addstr(out, PRE, LL(PRE)); /* add prefix */
bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
if (l < bufflen && nl == NULL) { /* small one-line source? */
addstr(out, source, l); /* keep it */
}
else {
if (nl != NULL) l = nl - source; /* stop at first newline */
if (l > bufflen) l = bufflen;
addstr(out, source, l);
addstr(out, RETS, LL(RETS));
}
memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
}
}
| gpl-2.0 |
Hellybean/android_kernel_samsung_jf | drivers/input/keyboard/cypress_touchkey_236/cypress-touchkey-236.c | 28 | 50946 | /*
* cypress_touchkey.c - Platform data for cypress touchkey driver
*
* Copyright (C) 2011 Samsung Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#define SEC_TOUCHKEY_DEBUG
#include <linux/module.h>
#include <linux/input.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/miscdevice.h>
#include <linux/earlysuspend.h>
#include <linux/i2c/cypress_touchkey.h>
#include "cypress_tkey_fw.h"
#include <linux/regulator/consumer.h>
#include <linux/mutex.h>
#include <linux/workqueue.h>
#include <linux/leds.h>
#include <asm/mach-types.h>
#include "issp_extern.h"
#include <linux/mfd/pm8xxx/pm8921.h>
#include "../../../../arch/arm/mach-msm/board-8064.h"
#define CYPRESS_GEN 0X00
#define CYPRESS_FW_VER 0X01
#define CYPRESS_MODULE_VER 0X02
#define CYPRESS_2ND_HOST 0X03
#define CYPRESS_THRESHOLD 0X04
#define CYPRESS_AUTO_CAL_FLG 0X05
#define CYPRESS_IDAC_MENU 0X07
#define CYPRESS_IDAC_BACK 0X06
#define CYPRESS_IDAC_HOME 0X08
#define CYPRESS_DIFF_MENU 0x0C
#define CYPRESS_DIFF_BACK 0x0A
#define CYPRESS_DIFF_HOME 0x0E
#define CYPRESS_RAW_DATA_MENU 0x10
#define CYPRESS_RAW_DATA_BACK 0x0E
#define CYPRESS_RAW_DATA_HOME 0x12
#define CYPRESS_RAW_DATA_BACK_GOGH 0x14
#define CYPRESS_LED_ON 0X10
#define CYPRESS_LED_OFF 0X20
#define CYPRESS_DATA_UPDATE 0X40
#define CYPRESS_AUTO_CAL 0X50
#define CYPRESS_LED_CONTROL_ON 0X60
#define CYPRESS_LED_CONTROL_OFF 0X70
#define CYPRESS_SLEEP 0X80
#define CYPRESS_FW_ID_REG 0X05
/*
#define CYPRESS_55_IC_MASK 0x20
#define CYPRESS_65_IC_MASK 0x04
*/
u32 ic_fw_id;
EXPORT_SYMBOL(ic_fw_id);
#if defined(CONFIG_GLOVE_TOUCH)
static int glove_value;
#endif
static int vol_mv_level = 33;
#define KEYCODE_REG 0x00
#define TOUCHKEY_BACKLIGHT "button-backlight"
/* bit masks*/
#define PRESS_BIT_MASK 0X08
#define KEYCODE_BIT_MASK 0X07
#define TOUCHKEY_LOG(k, v) dev_notice(&info->client->dev, "key[%d] %d\n", k, v);
#define FUNC_CALLED dev_notice(&info->client->dev, "%s: called.\n", __func__);
#define NUM_OF_RETRY_UPDATE 3
#define NUM_OF_KEY 4
struct cypress_touchkey_info {
struct i2c_client *client;
struct cypress_touchkey_platform_data *pdata;
struct input_dev *input_dev;
struct early_suspend early_suspend;
char phys[32];
unsigned char keycode[NUM_OF_KEY];
u8 sensitivity[NUM_OF_KEY];
int irq;
u8 fw_ver;
void (*power_onoff)(int);
int touchkey_update_status;
struct led_classdev leds;
enum led_brightness brightness;
struct mutex touchkey_led_mutex;
struct workqueue_struct *led_wq;
struct work_struct led_work;
#if defined(CONFIG_GLOVE_TOUCH)
struct workqueue_struct *glove_wq;
struct work_struct glove_work;
#endif
bool is_powering_on;
bool enabled;
bool done_ta_setting;
#ifdef TKEY_FLIP_MODE
bool enabled_flip;
#endif
#ifdef TSP_BOOSTER
struct delayed_work work_dvfs_off;
struct delayed_work work_dvfs_chg;
bool dvfs_lock_status;
struct mutex dvfs_lock;
#endif
#ifdef TK_INFORM_CHARGER
struct touchkey_callbacks callbacks;
bool charging_mode;
#endif
};
#ifdef CONFIG_HAS_EARLYSUSPEND
static void cypress_touchkey_early_suspend(struct early_suspend *h);
static void cypress_touchkey_late_resume(struct early_suspend *h);
#endif
static int touchkey_led_status;
static int touchled_cmd_reversed;
static struct pm_gpio tkey_int = {
.direction = PM_GPIO_DIR_IN,
.pull = PM_GPIO_PULL_NO,
.vin_sel = 2,
.function = PM_GPIO_FUNC_NORMAL,
.inv_int_pol = 0,
};
static struct pm_gpio tkey_sleep_int = {
.direction = PM_GPIO_DIR_IN,
.pull = PM_GPIO_PULL_UP_30,
.vin_sel = 2,
.function = PM_GPIO_FUNC_NORMAL,
.inv_int_pol = 0,
};
static void cypress_int_gpio_setting(bool value)
{
int ret;
if (value) {
ret = pm8xxx_gpio_config(PM8921_GPIO_PM_TO_SYS(PMIC_GPIO_TKEY_INT),
&tkey_int);
if (ret)
printk(KERN_ERR "%s PMIC_GPIO_TKEY_INT config failed\n", __func__);
printk(KERN_DEBUG "%s in resume \n", __func__);
}
else {
ret = pm8xxx_gpio_config(PM8921_GPIO_PM_TO_SYS(PMIC_GPIO_TKEY_INT),
&tkey_sleep_int);
if (ret)
printk(KERN_ERR "%s PMIC_GPIO_TKEY_INT_SLEEP config failed\n", __func__);
printk(KERN_DEBUG "%s in suspend \n", __func__);
}
}
static void cypress_gpio_setting(bool value)
{
int ret;
#if defined(CONFIG_MACH_JF_ATT) || defined(CONFIG_MACH_JF_TMO) || defined(CONFIG_MACH_JF_EUR)
if(value) {
if (system_rev < 9) {
ret = gpio_request(GPIO_TOUCHKEY_SCL, "TKEY_SCL");
if (ret)
printk(KERN_ERR "%s: request GPIO %s err %d.",\
__func__, "TKEY_SCL", ret);
}
else {
ret = gpio_request(GPIO_TOUCHKEY_SCL_2, "TKEY_SCL");
if (ret)
printk(KERN_ERR "%s: request GPIO %s err %d.",\
__func__, "TKEY_SCL_2", ret);
}
ret = gpio_request(GPIO_TOUCHKEY_SDA, "TKEY_SDA");
if (ret)
printk(KERN_ERR "%s: request GPIO %s err %d.",\
__func__, "TKEY_SDA", ret);
printk(KERN_DEBUG "%s in resume \n",__func__);
}
else {
if (system_rev < 9) {
gpio_free(GPIO_TOUCHKEY_SCL);
}
else {
gpio_free(GPIO_TOUCHKEY_SCL_2);
}
gpio_free(GPIO_TOUCHKEY_SDA);
printk(KERN_DEBUG "%s in suspend \n",__func__);
}
#else /*VZW, SPR, USC, CRI*/
if(value) {
if (system_rev < 10) {
ret = gpio_request(GPIO_TOUCHKEY_SCL, "TKEY_SCL");
if (ret)
printk(KERN_ERR "%s: request GPIO %s err %d.",\
__func__, "TKEY_SCL", ret);
}
else {
ret = gpio_request(GPIO_TOUCHKEY_SCL_2, "TKEY_SCL");
if (ret)
printk(KERN_ERR "%s: request GPIO %s err %d.",\
__func__, "TKEY_SCL_2", ret);
}
ret = gpio_request(GPIO_TOUCHKEY_SDA, "TKEY_SDA");
if (ret)
printk(KERN_ERR "%s: request GPIO %s err %d.",\
__func__, "TKEY_SDA", ret);
printk(KERN_DEBUG "%s in resume \n",__func__);
}
else {
if (system_rev < 10) {
gpio_free(GPIO_TOUCHKEY_SCL);
}
else {
gpio_free(GPIO_TOUCHKEY_SCL_2);
}
gpio_free(GPIO_TOUCHKEY_SDA);
printk(KERN_DEBUG "%s in suspend \n",__func__);
}
#endif
}
#ifdef TSP_BOOSTER
static void cypress_change_dvfs_lock(struct work_struct *work)
{
struct cypress_touchkey_info *info =
container_of(work,
struct cypress_touchkey_info, work_dvfs_chg.work);
int retval;
mutex_lock(&info->dvfs_lock);
retval = set_freq_limit(DVFS_TOUCH_ID,
MIN_TOUCH_LIMIT_SECOND);
if (retval < 0)
dev_err(&info->client->dev,
"%s: booster change failed(%d).\n",
__func__, retval);
mutex_unlock(&info->dvfs_lock);
}
static void cypress_set_dvfs_off(struct work_struct *work)
{
struct cypress_touchkey_info *info =
container_of(work,
struct cypress_touchkey_info, work_dvfs_off.work);
int retval;
mutex_lock(&info->dvfs_lock);
retval = set_freq_limit(DVFS_TOUCH_ID, -1);
if (retval < 0)
dev_err(&info->client->dev,
"%s: booster stop failed(%d).\n",
__func__, retval);
info->dvfs_lock_status = false;
mutex_unlock(&info->dvfs_lock);
}
static void cypress_set_dvfs_lock(struct cypress_touchkey_info *info,
uint32_t on)
{
int ret = 0;
mutex_lock(&info->dvfs_lock);
if (on == 0) {
if (info->dvfs_lock_status) {
schedule_delayed_work(&info->work_dvfs_off,
msecs_to_jiffies(TOUCH_BOOSTER_OFF_TIME));
}
} else if (on == 1) {
cancel_delayed_work(&info->work_dvfs_off);
if (!info->dvfs_lock_status) {
ret = set_freq_limit(DVFS_TOUCH_ID,
MIN_TOUCH_LIMIT);
if (ret < 0)
dev_err(&info->client->dev,
"%s: cpu first lock failed(%d)\n",
__func__, ret);
schedule_delayed_work(&info->work_dvfs_chg,
msecs_to_jiffies(TOUCH_BOOSTER_CHG_TIME));
info->dvfs_lock_status = true;
}
} else if (on == 2) {
if (info->dvfs_lock_status) {
cancel_delayed_work(&info->work_dvfs_off);
cancel_delayed_work(&info->work_dvfs_chg);
schedule_work(&info->work_dvfs_off.work);
}
}
mutex_unlock(&info->dvfs_lock);
}
static void cypress_init_dvfs(struct cypress_touchkey_info *info)
{
mutex_init(&info->dvfs_lock);
INIT_DELAYED_WORK(&info->work_dvfs_off, cypress_set_dvfs_off);
INIT_DELAYED_WORK(&info->work_dvfs_chg, cypress_change_dvfs_lock);
info->dvfs_lock_status = false;
}
#endif
static int i2c_touchkey_read(struct i2c_client *client,
u8 reg, u8 *val, unsigned int len)
{
int err = 0;
int retry = 3;
while (retry--) {
err = i2c_smbus_read_i2c_block_data(client,
KEYCODE_REG, len, val);
if (err >= 0)
return 0;
printk(KERN_ERR "[TouchKey] %s %d i2c transfer error\n",
__func__, __LINE__);
msleep(20);
}
return err;
}
static int i2c_touchkey_write(struct i2c_client *client,
u8 *val, unsigned int len)
{
int err = 0;
int retry = 3;
while (retry--) {
err = i2c_smbus_write_i2c_block_data(client,
KEYCODE_REG, len, val);
if (err >= 0)
return 0;
printk(KERN_DEBUG "[TouchKey] %s %d i2c transfer error\n",
__func__, __LINE__);
msleep(20);
}
return err;
}
static void cypress_touchkey_led_work(struct work_struct *work)
{
struct cypress_touchkey_info *info =
container_of(work, struct cypress_touchkey_info, led_work);
u8 buf;
int ret;
if(info->is_powering_on == true)
touchled_cmd_reversed = 1;
msleep(30);
if (info->brightness == LED_OFF)
buf = CYPRESS_LED_OFF;
else
buf = CYPRESS_LED_ON;
printk(KERN_DEBUG "[TouchKey] %s:0x%2X \n",__func__,buf);
if ((!info->enabled)) {
touchled_cmd_reversed = 1;
touchkey_led_status = buf;
printk(KERN_ERR "[TouchKey] %s %d Touchkey is not enabled.\n",
__func__, __LINE__);
return;
}
mutex_lock(&info->touchkey_led_mutex);
ret = i2c_smbus_write_byte_data(info->client, CYPRESS_GEN, buf);
if (ret < 0)
touchled_cmd_reversed = 1;
touchkey_led_status = buf;
mutex_unlock(&info->touchkey_led_mutex);
}
static void cypress_touchkey_brightness_set(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
/* Must not sleep, use a workqueue if needed */
struct cypress_touchkey_info *info =
container_of(led_cdev, struct cypress_touchkey_info, leds);
info->brightness = brightness;
queue_work(info->led_wq, &info->led_work);
}
static void change_touch_key_led_voltage(int vol_mv)
{
struct regulator *tled_regulator;
int ret;
vol_mv_level = vol_mv;
tled_regulator = regulator_get(NULL, "8921_l10");
if (IS_ERR(tled_regulator)) {
pr_err("%s: failed to get resource %s\n", __func__,
"touch_led");
return;
}
ret = regulator_set_voltage(tled_regulator,
vol_mv * 100000, vol_mv * 100000);
if (ret)
printk(KERN_ERR"error setting voltage\n");
regulator_put(tled_regulator);
}
static ssize_t brightness_control(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int data;
if (sscanf(buf, "%d\n", &data) == 1) {
printk(KERN_ERR "[TouchKey] touch_led_brightness: %d\n", data);
change_touch_key_led_voltage(data);
} else {
printk(KERN_ERR "[TouchKey] touch_led_brightness Error\n");
}
return size;
}
static ssize_t brightness_level_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int count;
count = snprintf(buf, sizeof(buf), "%d\n", vol_mv_level);
printk(KERN_DEBUG "[TouchKey] Touch LED voltage = %d\n", vol_mv_level);
return count;
}
#if defined(TK_INFORM_CHARGER)
static int touchkey_ta_setting(struct cypress_touchkey_info *info)
{
u8 data[6] = { 0, };
int count = 0;
int ret = 0;
unsigned short retry = 0;
dev_info(&info->client->dev, "%s\n", __func__);
while (retry < 3) {
ret = i2c_touchkey_read(info->client, KEYCODE_REG, data, 4);
if (ret < 0) {
dev_err(&info->client->dev, "Failed to read Keycode_reg.\n");
return ret;
}
/* Send autocal Command */
if (info->charging_mode) {
dev_info(&info->client->dev, "TA connect!!!\n");
data[0] = 0x90;
data[3] = 0x10;
} else {
dev_info(&info->client->dev, "TA disconnect!!!\n");
data[0] = 0x90;
data[3] = 0x20;
}
count = i2c_touchkey_write(info->client, data, 4);
msleep(100);
/* Check autocal status */
ret = i2c_touchkey_read(info->client, KEYCODE_REG, data, 6);
if (info->charging_mode) {
if (data[5] & TK_BIT_TA_ON) {
dev_info(&info->client->dev, "TA Enabled\n");
break;
} else {
dev_dbg(&info->client->dev, "TA Enabled error, retry %d\n",
retry);
}
} else {
if (!(data[5] & TK_BIT_TA_ON)) {
dev_info(&info->client->dev, "TA Disabled\n");
break;
} else {
dev_dbg(&info->client->dev, "TA Disabled error, retry %d\n",
retry);
}
}
retry = retry + 1;
}
if (retry == 3)
dev_info(&info->client->dev, "TA mode setting failed\n");
return count;
}
static void touchkey_ta_cb(struct touchkey_callbacks *cb, bool ta_status)
{
struct cypress_touchkey_info *info =
container_of(cb, struct cypress_touchkey_info, callbacks);
struct i2c_client *client = info->client;
dev_info(&client->dev, "%s : 0x%02x\n", __func__, ic_fw_id);
info->charging_mode = ta_status;
if (!(info->enabled)) {
printk(KERN_ERR "[TouchKey] %s %d Touchkey is not enabled.\n",
__func__, __LINE__);
info->done_ta_setting = false;
return;
}
if (ic_fw_id & CYPRESS_55_IC_MASK) {
printk(KERN_INFO "[Touchkey] IC id 20055\n");
touchkey_ta_setting(info);
}
else if (ic_fw_id & CYPRESS_65_IC_MASK) {
printk(KERN_INFO "[Touchkey] IC id 20065\n");
touchkey_ta_setting(info);
}
else {
printk(KERN_INFO "[Touchkey] IC id 20045\n");
printk(KERN_INFO "[TouchKey] TA mode does not support!\n");
}
}
#endif
#if defined(CONFIG_GLOVE_TOUCH)
static void cypress_touchkey_glove_work(struct work_struct *work)
{
struct cypress_touchkey_info *info =
container_of(work, struct cypress_touchkey_info, glove_work);
u8 data[6] = { 0, };
int count = 0;
int ret = 0;
unsigned short retry = 0;
#ifdef TKEY_FLIP_MODE
if (info->enabled_flip) {
dev_info(&info->client->dev,"[Touchkey] Enabled flip cover mode.\n");
return;
}
#endif
if(ic_fw_id & CYPRESS_55_IC_MASK)
printk(KERN_INFO "[Touchkey] IC id 20055\n");
else if (ic_fw_id & CYPRESS_65_IC_MASK)
printk(KERN_INFO "[Touchkey] IC id 20065\n");
else {
printk(KERN_INFO "[Touchkey] IC id 20045\n");
printk(KERN_INFO "[TouchKey] Glovemode does not support!\n");
return;
}
while (retry < 3) {
ret = i2c_touchkey_read(info->client, CYPRESS_GEN, data, 4);
if (ret < 0) {
dev_err(&info->client->dev, "[TouchKey] Failed to read Keycode_reg.\n");
return;
}
if (glove_value == 1) {
/* Send glove Command */
data[0] = 0xA0;
data[3] = 0x30;
} else {
data[0] = 0xA0;
data[3] = 0x40;
}
count = i2c_touchkey_write(info->client, data, 4);
msleep(50);
/* Check autocal status */
ret = i2c_touchkey_read(info->client, CYPRESS_GEN, data, 6);
if (glove_value == 1) {
if (data[5] & TK_BIT_GLOVE) {
printk(KERN_DEBUG "[TouchKey] glove_mode Enabled\n");
break;
} else {
printk(KERN_DEBUG "[TouchKey] glove_mode Error, retry %d\n",
retry);
}
} else {
if (!(data[5] & TK_BIT_GLOVE)) {
printk(KERN_DEBUG "[TouchKey] normal_mode Enabled\n");
break;
} else {
printk(KERN_DEBUG "[TouchKey] normal_mode Error, retry %d\n",
retry);
}
}
retry = retry + 1;
}
if (retry == 3)
printk(KERN_ERR "[TouchKey] glove_mode failed\n");
return;
}
struct cypress_touchkey_info *tkey_info;
int touchkey_glovemode(int value)
{
struct cypress_touchkey_info *info = tkey_info;
if (!(info->enabled)) {
printk(KERN_ERR "[TouchKey] %s %d Touchkey is not enabled.\n",
__func__, __LINE__);
return 0;
}
glove_value = value;
queue_work(info->glove_wq, &info->glove_work);
return 0;
}
EXPORT_SYMBOL(touchkey_glovemode);
#endif
#ifdef TKEY_FLIP_MODE
void touchkey_flip_cover(int value)
{
struct cypress_touchkey_info *info = tkey_info;
u8 data[6] = { 0, };
int count = 0;
int ret = 0;
unsigned short retry = 0;
if (!(info->enabled)) {
printk(KERN_ERR "[TouchKey] %s %d Touchkey is not enabled.\n",
__func__, __LINE__);
return ;
}
if(ic_fw_id & CYPRESS_65_IC_MASK)
printk(KERN_INFO "[Touchkey] IC id 20065\n");
else if (ic_fw_id & CYPRESS_55_IC_MASK) {
printk(KERN_INFO "[Touchkey] IC id 20055\n");
printk(KERN_INFO "[TouchKey] flipmode does not support!\n");
return;
}
else {
printk(KERN_INFO "[Touchkey] IC id 20045\n");
printk(KERN_INFO "[TouchKey] flipmode does not support!\n");
return;
}
while (retry < 3) {
ret = i2c_touchkey_read(info->client, KEYCODE_REG, data, 4);
if (ret < 0) {
dev_err(&info->client->dev, "[Touchkey] Failed to read Keycode_reg %d times.\n",
retry);
return;
}
if (value == 1) {
/* Send filp mode Command */
data[0] = 0xA0;
data[3] = 0x50;
} else {
data[0] = 0xA0;
data[3] = 0x40;
}
count = i2c_touchkey_write(info->client, data, 4);
msleep(100);
/* Check autocal status */
ret = i2c_touchkey_read(info->client, KEYCODE_REG, data, 6);
if (value == 1){
if (data[5] & TK_BIT_FLIP) {
dev_info(&info->client->dev, "[Touchkey] flip_mode Enabled\n");
info->enabled_flip = true;
break;
} else {
dev_info(&info->client->dev, "[Touchkey] flip_mode Enabled, retry %d \n",
retry);
}
} else {
if (!(data[5] & TK_BIT_FLIP)) {
dev_info(&info->client->dev, "[Touchkey] normal_mode Enabled from flipmode\n");
info->enabled_flip = false;
break;
} else {
dev_info(&info->client->dev, "[Touchkey] normal_mode Enabled from flipmode, retry %d \n",
retry);
}
}
retry = retry + 1;
}
if (retry == 3)
dev_info(&info->client->dev, "[Touchkey] flip cover failed\n");
return;
}
#endif
static irqreturn_t cypress_touchkey_interrupt(int irq, void *dev_id)
{
struct cypress_touchkey_info *info = dev_id;
s8 buf[10] = {0,};
int code;
int press;
int ret;
ret = gpio_get_value(info->pdata->gpio_int);
if (ret) {
printk(KERN_ERR "not real interrupt (%d).\n", ret);
goto out;
}
if (info->is_powering_on) {
printk(KERN_ERR "%s: ignoring spurious boot "\
"interrupt\n", __func__);
return IRQ_HANDLED;
}
buf[0] = i2c_smbus_read_byte_data(info->client, CYPRESS_GEN);
if (buf[0] < 0) {
printk(KERN_ERR "interrupt failed with %d.\n", ret);
goto out;
}
press = !(buf[0] & PRESS_BIT_MASK);
code = (int)(buf[0] & KEYCODE_BIT_MASK) - 1;
printk(KERN_ERR
"[TouchKey]press=%d, code=%d\n", press, code);
if (code < 0) {
dev_err(&info->client->dev,
"not profer interrupt 0x%2X.\n", buf[0]);
goto out;
}
#if defined(SEC_TOUCHKEY_DEBUG)
TOUCHKEY_LOG(info->keycode[code], press);
#endif
input_report_key(info->input_dev, info->keycode[code], press);
input_sync(info->input_dev);
#ifdef TSP_BOOSTER
cypress_set_dvfs_lock(info, !!press);
#endif
out:
return IRQ_HANDLED;
}
static void cypress_touchkey_con_hw(struct cypress_touchkey_info *dev_info,
bool flag)
{
struct cypress_touchkey_info *info = dev_info;
gpio_set_value(info->pdata->gpio_led_en, flag ? 1 : 0);
#if defined(SEC_TOUCHKEY_DEBUG)
dev_info(&info->client->dev,
"%s : called with flag %d.\n", __func__, flag);
#endif
}
static int cypress_touchkey_auto_cal(struct cypress_touchkey_info *dev_info)
{
struct cypress_touchkey_info *info = dev_info;
u8 data[6] = { 0, };
int count = 0;
int ret = 0;
unsigned short retry = 0;
while (retry < 3) {
ret = i2c_touchkey_read(info->client, CYPRESS_GEN, data, 4);
if (ret < 0) {
printk(KERN_ERR "[TouchKey]i2c read fail.\n");
return ret;
}
data[0] = 0x50;
data[3] = 0x01;
count = i2c_touchkey_write(info->client, data, 4);
printk(KERN_DEBUG
"[TouchKey] data[0]=%x data[1]=%x data[2]=%x data[3]=%x\n",
data[0], data[1], data[2], data[3]);
msleep(130);
ret = i2c_touchkey_read(info->client, CYPRESS_GEN, data, 6);
if ((data[5] & 0x80)) {
printk(KERN_DEBUG "[Touchkey] autocal Enabled\n");
break;
} else {
printk(KERN_DEBUG "[Touchkey] autocal disabled, retry %d\n",
retry);
}
retry = retry + 1;
}
if (retry == 3)
printk(KERN_DEBUG "[Touchkey] autocal failed\n");
return count;
}
static int cypress_touchkey_led_on(struct cypress_touchkey_info *dev_info)
{
struct cypress_touchkey_info *info = dev_info;
u8 buf = CYPRESS_LED_ON;
int ret;
ret = i2c_smbus_write_byte_data(info->client, CYPRESS_GEN, buf);
if (ret < 0) {
dev_err(&info->client->dev,
"[Touchkey] i2c write error [%d]\n", ret);
}
return ret;
}
static int cypress_touchkey_led_off(struct cypress_touchkey_info *dev_info)
{
struct cypress_touchkey_info *info = dev_info;
u8 buf = CYPRESS_LED_OFF;
int ret;
ret = i2c_smbus_write_byte_data(info->client, CYPRESS_GEN, buf);
if (ret < 0) {
dev_err(&info->client->dev,
"[Touchkey] i2c write error [%d]\n", ret);
}
return ret;
}
static ssize_t touch_version_read(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
u8 data;
int count;
data = i2c_smbus_read_byte_data(info->client, CYPRESS_FW_VER);
count = snprintf(buf, 20, "0x%02x\n", data);
dev_info(&info->client->dev,
"[TouchKey] %s : FW Ver 0x%02x\n", __func__, data);
return count;
}
static ssize_t touch_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int count;
count = snprintf(buf, 20, "0x%02x\n", BIN_FW_VERSION);
return count;
}
static ssize_t touchkey_firm_status_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int count = 0;
char buff[16] = {0};
dev_info(&info->client->dev, "[TouchKey] touchkey_update_status: %d\n",
info->touchkey_update_status);
if (info->touchkey_update_status == 0)
count = snprintf(buff, sizeof(buff), "PASS\n");
else if (info->touchkey_update_status == 1)
count = snprintf(buff, sizeof(buff), "Downloading\n");
else if (info->touchkey_update_status == -1)
count = snprintf(buff, sizeof(buff), "Fail\n");
return count;
}
static ssize_t touch_update_read(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int count = 0;
char buff[16] = {0};
dev_info(&info->client->dev, "[TouchKey] touchkey_update_read: %d\n",
info->touchkey_update_status);
if (info->touchkey_update_status == 0)
count = snprintf(buff, sizeof(buff), "PASS\n");
else if (info->touchkey_update_status == 1)
count = snprintf(buff, sizeof(buff), "Downloading\n");
else if (info->touchkey_update_status == -1)
count = snprintf(buff, sizeof(buff), "Fail\n");
return count;
}
static ssize_t touch_update_write(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int count = 0;
int retry = NUM_OF_RETRY_UPDATE;
char buff[16] = {0};
u8 data;
info->touchkey_update_status = 1;
dev_info(dev, "[TouchKey] touch_update_write!\n");
disable_irq(info->irq);
if (ic_fw_id & CYPRESS_55_IC_MASK) {
printk(KERN_INFO "[Touchkey] IC id 20055\n");
return 1;
}
else if (ic_fw_id & CYPRESS_65_IC_MASK)
printk(KERN_INFO "[Touchkey] IC id 20065\n");
else {
printk(KERN_INFO "[Touchkey] IC id 20045\n");
printk(KERN_INFO "[TouchKey] FW update does not support!\n");
enable_irq(info->irq);
return 1;
}
while (retry--) {
if (ISSP_main() == 0) {
dev_info(&info->client->dev,
"[TouchKey] Update success!\n");
msleep(50);
cypress_touchkey_auto_cal(info);
info->touchkey_update_status = 0;
count = 1;
enable_irq(info->irq);
break;
}
dev_err(&info->client->dev,
"[TouchKey] Touchkey_update failed... retry...\n");
}
if (retry <= 0) {
if (info->pdata->gpio_led_en)
cypress_touchkey_con_hw(info, false);
msleep(300);
count = 0;
dev_err(&info->client->dev, "[TouchKey]Touchkey_update fail\n");
info->touchkey_update_status = -1;
return count;
}
msleep(500);
data = i2c_smbus_read_byte_data(info->client, CYPRESS_FW_VER);
count = snprintf(buff, sizeof(buff), "0x%02x\n", data);
dev_info(&info->client->dev,
"[TouchKey] %s : FW Ver 0x%02x\n", __func__, data);
return count;
}
static ssize_t touch_led_control(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t size)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
dev_info(&info->client->dev, "called %s\n", __func__);
if (buf != NULL) {
if (buf[0] == '1')
cypress_touchkey_led_on(info);
else
cypress_touchkey_led_off(info);
#if defined(SEC_TOUCHKEY_DEBUG)
dev_info(&info->client->dev,
"[TouchKey] touch_led_control : %d\n", buf[0]);
#endif
} else
dev_info(&info->client->dev, "[TouchKey] touch_led_control Error\n");
return size;
}
static ssize_t touch_sensitivity_control(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t size)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int ret;
ret = i2c_smbus_write_byte_data(info->client,
CYPRESS_GEN, CYPRESS_DATA_UPDATE);
if (ret < 0) {
dev_err(&info->client->dev,
"[Touchkey] fail to CYPRESS_DATA_UPDATE.\n");
return ret;
}
msleep(150);
return size;
}
static ssize_t touchkey_menu_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u16 menu_sensitivity;
u8 data[14] = { 0, };
int ret;
unsigned char sensitivity_control = 0x40;
i2c_touchkey_write(info->client, &sensitivity_control, 1);
ret = i2c_touchkey_read(info->client, KEYCODE_REG, data, 14);
printk(KERN_DEBUG "called %s data[10] = %d, data[11] =%d\n", __func__,
data[10], data[11]);
menu_sensitivity = ((0x00FF & data[10]) << 8) | data[11];
return snprintf(buf, 20, "%d\n", menu_sensitivity);
}
static ssize_t touchkey_back_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u16 back_sensitivity;
u8 data[14] = { 0, };
int ret;
unsigned char sensitivity_control = 0x40;
i2c_touchkey_write(info->client, &sensitivity_control, 1);
ret = i2c_touchkey_read(info->client, KEYCODE_REG, data, 14);
printk(KERN_DEBUG "called %s data[12] = %d, data[13] =%d\n", __func__,
data[12], data[13]);
back_sensitivity = ((0x00FF & data[12]) << 8) | data[13];
return snprintf(buf, 20, "%d\n", back_sensitivity);
}
static ssize_t touchkey_raw_data0_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u16 raw_data0;
u8 data[2] = {0,};
int ret;
bool touchkey;
touchkey = info->pdata->touchkey_order;
if (0) {
ret = i2c_smbus_read_i2c_block_data(info->client,
CYPRESS_RAW_DATA_MENU, ARRAY_SIZE(data), data);
} else {
ret = i2c_smbus_read_i2c_block_data(info->client,
touchkey ? CYPRESS_RAW_DATA_MENU : CYPRESS_RAW_DATA_BACK,
ARRAY_SIZE(data), data);
}
if (ret != ARRAY_SIZE(data)) {
dev_err(&info->client->dev,
"[TouchKey] fail to read MENU raw data.\n");
return ret;
}
raw_data0 = ((0x00FF & data[0])<<8) | data[1];
dev_info(&info->client->dev, "called %s , data : %d %d\n",
__func__, data[0], data[1]);
return snprintf(buf, 20, "%d\n", raw_data0);
}
static ssize_t touchkey_raw_data1_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u16 raw_data1;
u8 data[2] = {0,};
int ret;
bool touchkey;
touchkey = info->pdata->touchkey_order;
if (0) {
ret = i2c_smbus_read_i2c_block_data(info->client,
CYPRESS_RAW_DATA_BACK_GOGH, ARRAY_SIZE(data), data);
} else {
ret = i2c_smbus_read_i2c_block_data(info->client,
touchkey ? CYPRESS_RAW_DATA_BACK : CYPRESS_RAW_DATA_MENU,
ARRAY_SIZE(data), data);
}
if (ret != ARRAY_SIZE(data)) {
dev_err(&info->client->dev,
"[TouchKey] fail to read HOME raw data.\n");
return ret;
}
raw_data1 = ((0x00FF & data[0])<<8) | data[1];
dev_info(&info->client->dev, "called %s , data : %d %d\n",
__func__, data[0], data[1]);
return snprintf(buf, 20, "%d\n", raw_data1);
}
static ssize_t touchkey_idac0_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u8 idac0;
u8 data = 0;
bool touchkey;
touchkey = info->pdata->touchkey_order;
if (0) {
data = i2c_smbus_read_byte_data(info->client,
CYPRESS_IDAC_MENU);
} else {
data = i2c_smbus_read_byte_data(info->client,
touchkey ? CYPRESS_IDAC_MENU : CYPRESS_IDAC_BACK);
}
dev_info(&info->client->dev, "called %s , data : %d\n", __func__, data);
idac0 = data;
return snprintf(buf, 20, "%d\n", idac0);
}
static ssize_t touchkey_idac1_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u8 idac1;
u8 data = 0;
bool touchkey;
touchkey = info->pdata->touchkey_order;
if (0) {
data = i2c_smbus_read_byte_data(info->client,
CYPRESS_IDAC_BACK);
} else {
data = i2c_smbus_read_byte_data(info->client,
touchkey ? CYPRESS_IDAC_BACK : CYPRESS_IDAC_MENU);
}
dev_info(&info->client->dev, "called %s , data : %d\n", __func__, data);
idac1 = data;
return snprintf(buf, 20, "%d\n", idac1);
}
#if defined(TK_HOME_ENABLE)
static ssize_t touchkey_home_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u8 home_sensitivity;
u8 data[2] = {0,};
int ret;
ret = i2c_smbus_read_i2c_block_data(info->client,
CYPRESS_DIFF_MENU, ARRAY_SIZE(data), data);
if (ret != ARRAY_SIZE(data)) {
dev_err(&info->client->dev,
"[TouchKey] fail to read home sensitivity.\n");
return ret;
}
home_sensitivity = ((0x00FF & data[0])<<8) | data[1];
dev_info(&info->client->dev, "called %s , data : %d %d\n",
__func__, data[0], data[1]);
return snprintf(buf, 20, "%d\n", home_sensitivity);
}
static ssize_t touchkey_raw_data2_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u16 raw_data1;
u8 data[2] = {0,};
int ret;
ret = i2c_smbus_read_i2c_block_data(info->client,
CYPRESS_RAW_DATA_HOME, ARRAY_SIZE(data), data);
if (ret != ARRAY_SIZE(data)) {
dev_err(&info->client->dev,
"[TouchKey] fail to read HOME raw data.\n");
return ret;
}
raw_data1 = ((0x00FF & data[0])<<8) | data[1];
dev_info(&info->client->dev, "called %s , data : %d %d\n",
__func__, data[0], data[1]);
return snprintf(buf, 20, "%d\n", raw_data1);
}
static ssize_t touchkey_idac2_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u8 idac1;
u8 data = 0;
data = i2c_smbus_read_byte_data(info->client, CYPRESS_IDAC_HOME);
dev_info(&info->client->dev, "called %s , data : %d\n", __func__, data);
idac1 = data;
return snprintf(buf, 20, "%d\n", idac1);
}
#endif
static ssize_t touchkey_threshold_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
static u8 touchkey_threshold;
u8 data = 0;
data = i2c_smbus_read_byte_data(info->client, CYPRESS_THRESHOLD);
dev_info(&info->client->dev, "called %s , data : %d\n", __func__, data);
touchkey_threshold = data;
return snprintf(buf, 20, "%d\n", touchkey_threshold);
}
static ssize_t touch_autocal_testmode(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t size)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int count = 0;
int on_off;
if (sscanf(buf, "%d\n", &on_off) == 1) {
printk(KERN_ERR "[TouchKey] Test Mode : %d\n", on_off);
if (on_off == 1) {
count = i2c_smbus_write_byte_data(info->client,
CYPRESS_GEN, CYPRESS_DATA_UPDATE);
}
} else {
if (info->pdata->gpio_led_en) {
cypress_touchkey_con_hw(info, false);
msleep(50);
cypress_touchkey_con_hw(info, true);
msleep(50);
}
cypress_touchkey_auto_cal(info);
}
return count;
}
static ssize_t autocalibration_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int data;
sscanf(buf, "%d\n", &data);
if (data == 1)
cypress_touchkey_auto_cal(info);
return 0;
}
static ssize_t autocalibration_status(struct device *dev,
struct device_attribute *attr, char *buf)
{
u8 data[6];
int ret;
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
printk(KERN_DEBUG "[Touchkey] %s\n", __func__);
ret = i2c_smbus_read_i2c_block_data(info->client,
CYPRESS_GEN, 6, data);
if ((data[5] & 0x80))
return snprintf(buf, 20, "Enabled\n");
else
return snprintf(buf, 20, "Disabled\n");
}
#if defined(CONFIG_GLOVE_TOUCH)
static ssize_t glove_mode_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int data;
sscanf(buf, "%d\n", &data);
dev_info(&info->client->dev, "%s %d\n", __func__, data);
touchkey_glovemode(data);
return size;
}
#endif
#ifdef TKEY_FLIP_MODE
static ssize_t flip_cover_mode_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct cypress_touchkey_info *info = dev_get_drvdata(dev);
int data;
sscanf(buf, "%d\n", &data);
dev_info(&info->client->dev, "%s %d\n", __func__, data);
touchkey_flip_cover(data);
return size;
}
#endif
static DEVICE_ATTR(touchkey_firm_update_status,
S_IRUGO | S_IWUSR | S_IWGRP, touchkey_firm_status_show, NULL);
static DEVICE_ATTR(touchkey_firm_version_panel, S_IRUGO,
touch_version_read, NULL);
static DEVICE_ATTR(touchkey_firm_version_phone, S_IRUGO,
touch_version_show, NULL);
static DEVICE_ATTR(touchkey_firm_update, S_IRUGO | S_IWUSR | S_IWGRP,
touch_update_read, touch_update_write);
static DEVICE_ATTR(brightness, S_IRUGO | S_IWUSR | S_IWGRP,
NULL, touch_led_control);
static DEVICE_ATTR(touch_sensitivity, S_IRUGO | S_IWUSR | S_IWGRP,
NULL, touch_sensitivity_control);
static DEVICE_ATTR(touchkey_menu, S_IRUGO, touchkey_menu_show, NULL);
static DEVICE_ATTR(touchkey_raw_data0, S_IRUGO, touchkey_raw_data0_show, NULL);
static DEVICE_ATTR(touchkey_idac0, S_IRUGO, touchkey_idac0_show, NULL);
static DEVICE_ATTR(touchkey_back, S_IRUGO, touchkey_back_show, NULL);
static DEVICE_ATTR(touchkey_raw_data1, S_IRUGO, touchkey_raw_data1_show, NULL);
static DEVICE_ATTR(touchkey_idac1, S_IRUGO, touchkey_idac1_show, NULL);
#if defined(TK_HOME_ENABLE)
static DEVICE_ATTR(touchkey_home, S_IRUGO, touchkey_home_show, NULL);
static DEVICE_ATTR(touchkey_raw_data2, S_IRUGO, touchkey_raw_data2_show, NULL);
static DEVICE_ATTR(touchkey_idac2, S_IRUGO, touchkey_idac2_show, NULL);
#endif
static DEVICE_ATTR(touchkey_threshold, S_IRUGO, touchkey_threshold_show, NULL);
static DEVICE_ATTR(touchkey_autocal_start, S_IRUGO | S_IWUSR | S_IWGRP,
NULL, touch_autocal_testmode);
static DEVICE_ATTR(autocal_enable, S_IRUGO | S_IWUSR | S_IWGRP, NULL,
autocalibration_enable);
static DEVICE_ATTR(autocal_stat, S_IRUGO | S_IWUSR | S_IWGRP,
autocalibration_status, NULL);
static DEVICE_ATTR(touchkey_brightness_level, S_IRUGO | S_IWUSR | S_IWGRP,
brightness_level_show, brightness_control);
#if defined(CONFIG_GLOVE_TOUCH)
static DEVICE_ATTR(glove_mode, S_IRUGO | S_IWUSR | S_IWGRP, NULL,
glove_mode_enable);
#endif
#ifdef TKEY_FLIP_MODE
static DEVICE_ATTR(flip_mode, S_IRUGO | S_IWUSR | S_IWGRP, NULL,
flip_cover_mode_enable);
#endif
static int __devinit cypress_touchkey_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct cypress_touchkey_platform_data *pdata =
client->dev.platform_data;
struct cypress_touchkey_info *info;
struct input_dev *input_dev;
int ret = 0;
int i;
int retry = NUM_OF_RETRY_UPDATE;
u32 ic_fw_ver;
u8 data[6] = { 0, };
struct device *sec_touchkey;
printk(KERN_INFO "[TouchKey] START(%s)!\n", __func__);
if (!i2c_check_functionality(adapter, I2C_FUNC_I2C))
return -EIO;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info) {
dev_err(&client->dev, "fail to memory allocation.\n");
goto err_mem_alloc;
}
input_dev = input_allocate_device();
if (!input_dev) {
dev_err(&client->dev, "fail to allocate input device.\n");
goto err_input_dev_alloc;
}
info->client = client;
info->input_dev = input_dev;
info->pdata = client->dev.platform_data;
info->irq = client->irq;
info->power_onoff = pdata->power_onoff;
info->touchkey_update_status = 0;
memcpy(info->keycode, pdata->touchkey_keycode,
sizeof(pdata->touchkey_keycode));
snprintf(info->phys, sizeof(info->phys),
"%s/input0", dev_name(&client->dev));
input_dev->name = "sec_touchkey";
input_dev->phys = info->phys;
input_dev->id.bustype = BUS_I2C;
input_dev->dev.parent = &client->dev;
info->is_powering_on = true;
info->power_onoff(1);
msleep(50);
info->enabled = true;
set_bit(EV_SYN, input_dev->evbit);
set_bit(EV_KEY, input_dev->evbit);
set_bit(EV_LED, input_dev->evbit);
set_bit(LED_MISC, input_dev->ledbit);
for (i = 0; i < ARRAY_SIZE(info->keycode); i++)
set_bit(info->keycode[i], input_dev->keybit);
input_set_drvdata(input_dev, info);
mutex_init(&info->touchkey_led_mutex);
ret = input_register_device(input_dev);
if (ret) {
dev_err(&client->dev, "[TouchKey] failed to register input dev (%d).\n",
ret);
goto err_reg_input_dev;
}
i2c_set_clientdata(client, info);
if (info->pdata->gpio_led_en) {
ret = gpio_request(info->pdata->gpio_led_en,
"gpio_touchkey_led");
if (ret < 0) {
dev_err(&client->dev,
"gpio_touchkey_led gpio_request is failed\n");
goto err_gpio_request;
}
gpio_tlmm_config(GPIO_CFG(info->pdata->gpio_led_en, 0,
GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), 1);
cypress_touchkey_con_hw(info, true);
}
#if defined(CONFIG_MACH_JF_DCM)
msleep(50);
#endif
ret = i2c_touchkey_read(info->client, KEYCODE_REG, data, 6);
#ifdef CONFIG_TOUCHSCREEN_FACTORY_PLATFORM
if (ret < 0) {
printk(KERN_ERR "[TouchKey] %s %d i2c transfer error\n",
__func__, __LINE__);
goto err_i2c_check;
}
#else
if (ret < 0) {
disable_irq(client->irq);
if (ISSP_main() == 0) {
dev_info(&client->dev, "[TouchKey] Update success!\n");
enable_irq(client->irq);
}
else {
printk(KERN_ERR "[TouchKey] %s %d i2c transfer error\n",
__func__, __LINE__);
goto err_i2c_check;
}
}
#endif
#ifdef TSP_BOOSTER
cypress_init_dvfs(info);
#endif
ret = request_threaded_irq(client->irq, NULL,
cypress_touchkey_interrupt,
IRQF_TRIGGER_FALLING, client->dev.driver->name, info);
if (ret < 0) {
dev_err(&client->dev, "Failed to request IRQ %d (err: %d).\n",
client->irq, ret);
goto err_req_irq;
}
#ifdef CONFIG_HAS_EARLYSUSPEND
info->early_suspend.suspend = cypress_touchkey_early_suspend;
info->early_suspend.resume = cypress_touchkey_late_resume;
register_early_suspend(&info->early_suspend);
#endif /* CONFIG_HAS_EARLYSUSPEND */
#if defined(CONFIG_GLOVE_TOUCH)
info->glove_wq = create_singlethread_workqueue("cypress_touchkey");
if (!info->glove_wq)
dev_err(&client->dev, "fail to create glove workquewe.\n");
else
INIT_WORK(&info->glove_work, cypress_touchkey_glove_work);
#endif
info->led_wq = create_singlethread_workqueue("cypress_touchkey");
if (!info->led_wq)
dev_err(&client->dev, "fail to create led workquewe.\n");
else
INIT_WORK(&info->led_work, cypress_touchkey_led_work);
info->leds.name = TOUCHKEY_BACKLIGHT;
info->leds.brightness = LED_FULL;
info->leds.max_brightness = LED_FULL;
info->leds.brightness_set = cypress_touchkey_brightness_set;
ret = led_classdev_register(&client->dev, &info->leds);
if (ret)
goto err_led_class_dev;
ic_fw_ver = data[1];
printk(KERN_INFO "[Touchkey] IC FW Version: 0x%02x\n", ic_fw_ver);
ic_fw_id = data[5];
printk(KERN_INFO "[Touchkey] IC ID Version: 0x%02x\n", ic_fw_id);
if ((ic_fw_id & CYPRESS_65_IC_MASK) && (ic_fw_ver >= BASE_FW_VERSION) && (ic_fw_ver < BIN_FW_VERSION)){
printk(KERN_INFO "[Touchkey] IC id 20065\n");
printk(KERN_INFO "[TouchKey] touchkey_update Start!!\n");
disable_irq(client->irq);
while (retry--) {
if (ISSP_main() == 0) {
dev_info(&client->dev, "[TouchKey] Update success!\n");
enable_irq(client->irq);
break;
}
dev_err(&client->dev,
"[TouchKey] Touchkey_update failed... retry...\n");
}
if (retry <= 0) {
if (info->pdata->gpio_led_en)
cypress_touchkey_con_hw(info, false);
msleep(300);
dev_err(&client->dev, "[TouchKey]Touchkey_update fail\n");
}
msleep(500);
ic_fw_ver = i2c_smbus_read_byte_data(info->client,
CYPRESS_FW_VER);
dev_info(&client->dev,
"[TouchKey] %s : FW Ver 0x%02x\n", __func__, ic_fw_ver);
}
else if ((ic_fw_id & CYPRESS_55_IC_MASK) && (ic_fw_ver < BIN_FW_VERSION_20055)){
printk(KERN_INFO "[Touchkey] IC id 20055\n");
printk(KERN_INFO "[TouchKey] touchkey_update Start!!\n");
disable_irq(client->irq);
while (retry--) {
if (ISSP_main() == 0) {
dev_info(&client->dev, "[TouchKey] Update success!\n");
enable_irq(client->irq);
break;
}
dev_err(&client->dev,
"[TouchKey] Touchkey_update failed... retry...\n");
}
if (retry <= 0) {
if (info->pdata->gpio_led_en)
cypress_touchkey_con_hw(info, false);
msleep(300);
dev_err(&client->dev, "[TouchKey]Touchkey_update fail\n");
}
msleep(500);
ic_fw_ver = i2c_smbus_read_byte_data(info->client,
CYPRESS_FW_VER);
dev_info(&client->dev,
"[TouchKey] %s : FW Ver 0x%02x\n", __func__, ic_fw_ver);
} else {
dev_info(&client->dev, "[TouchKey] FW update does not need!\n");
}
cypress_touchkey_auto_cal(info);
sec_touchkey = device_create(sec_class, NULL, 0, NULL, "sec_touchkey");
if (IS_ERR(sec_touchkey)) {
pr_err("Failed to create device(sec_touchkey)!\n");
goto err_sysfs;
}
dev_set_drvdata(sec_touchkey, info);
#if defined(TK_INFORM_CHARGER)
info->callbacks.inform_charger = touchkey_ta_cb;
if (info->pdata->register_cb) {
dev_info(&client->dev, "[Touchkey] Register TA Callback\n");
info->pdata->register_cb(&info->callbacks);
}
#endif
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_firm_update_status) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_firm_update.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_firm_update) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_firm_update.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_firm_version_panel) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_firm_version_panel.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_firm_version_phone) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_firm_version_phone.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_brightness) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_brightness.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touch_sensitivity) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touch_sensitivity.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_menu) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_menu.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_back) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_back.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_raw_data0) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_raw_data0.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_raw_data1) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_raw_data1.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey, &dev_attr_touchkey_idac0) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_idac0.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey, &dev_attr_touchkey_idac1) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_idac1.attr.name);
goto err_sysfs;
}
#if defined(TK_HOME_ENABLE)
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_home) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_home.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_raw_data2) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_raw_data2.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey, &dev_attr_touchkey_idac2) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_idac2.attr.name);
goto err_sysfs;
}
#endif
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_threshold) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_threshold.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_autocal_start) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_touchkey_autocal_start.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_autocal_enable) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_autocal_enable.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_autocal_stat) < 0) {
pr_err("Failed to create device file(%s)!\n",
dev_attr_autocal_stat.attr.name);
goto err_sysfs;
}
if (device_create_file(sec_touchkey,
&dev_attr_touchkey_brightness_level) < 0) {
printk(KERN_ERR "Failed to create device file(%s)!\n",
dev_attr_touchkey_brightness_level.attr.name);
goto err_sysfs;
}
#if defined(CONFIG_GLOVE_TOUCH)
if (device_create_file(sec_touchkey,
&dev_attr_glove_mode) < 0) {
printk(KERN_ERR "Failed to create device file(%s)!\n",
dev_attr_glove_mode.attr.name);
goto err_sysfs;
}
#endif
#ifdef TKEY_FLIP_MODE
if (device_create_file(sec_touchkey,
&dev_attr_flip_mode) < 0) {
printk(KERN_ERR "Failed to create device file(%s)!\n",
dev_attr_flip_mode.attr.name);
goto err_sysfs;
}
#endif
info->is_powering_on = false;
#if defined(CONFIG_GLOVE_TOUCH)
tkey_info = info;
#endif
printk(KERN_INFO "[Touchkey] DONE(%s)!\n", __func__);
return 0;
err_sysfs:
err_led_class_dev:
if (info->led_wq)
destroy_workqueue(info->led_wq);
err_req_irq:
err_i2c_check:
err_gpio_request:
input_unregister_device(input_dev);
err_reg_input_dev:
input_free_device(input_dev);
input_dev = NULL;
mutex_destroy(&info->touchkey_led_mutex);
err_input_dev_alloc:
kfree(info);
return -ENXIO;
err_mem_alloc:
return -ENOMEM;
}
static int __devexit cypress_touchkey_remove(struct i2c_client *client)
{
struct cypress_touchkey_info *info = i2c_get_clientdata(client);
if (info->irq >= 0)
free_irq(info->irq, info);
mutex_destroy(&info->touchkey_led_mutex);
led_classdev_unregister(&info->leds);
input_unregister_device(info->input_dev);
input_free_device(info->input_dev);
kfree(info);
return 0;
}
#if defined(CONFIG_PM) || defined(CONFIG_HAS_EARLYSUSPEND)
static int cypress_touchkey_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct cypress_touchkey_info *info = i2c_get_clientdata(client);
int ret = 0;
info->is_powering_on = true;
disable_irq(info->irq);
if (info->pdata->gpio_led_en)
cypress_touchkey_con_hw(info, false);
info->power_onoff(0);
cypress_int_gpio_setting(false);
cypress_gpio_setting(false);
info->enabled = false;
info->done_ta_setting = true;
#ifdef TSP_BOOSTER
cypress_set_dvfs_lock(info, 2);
dev_info(&info->client->dev,
"%s: dvfs_lock free.\n", __func__);
#endif
return ret;
}
static int cypress_touchkey_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct cypress_touchkey_info *info = i2c_get_clientdata(client);
int ret = 0;
info->power_onoff(1);
cypress_int_gpio_setting(true);
cypress_gpio_setting(true);
if (info->pdata->gpio_led_en)
cypress_touchkey_con_hw(info, true);
msleep(100);
if (touchled_cmd_reversed) {
touchled_cmd_reversed = 0;
i2c_smbus_write_byte_data(info->client,
CYPRESS_GEN, touchkey_led_status);
printk(KERN_INFO "%s: LED returned on, %d\n", __func__, ret);
msleep(30);
i2c_smbus_write_byte_data(info->client,
CYPRESS_GEN, touchkey_led_status);
printk(KERN_INFO "%s: LED returned on, %d\n", __func__, ret);
}
info->enabled = true;
if(!(info->done_ta_setting)) {
printk(KERN_DEBUG "[Touchkey] Enter the TA setting\n");
touchkey_ta_setting(info);
}
cypress_touchkey_auto_cal(info);
/*
if (touchled_cmd_reversed) {
msleep(30);
touchled_cmd_reversed = 0;
i2c_smbus_write_byte_data(info->client,
CYPRESS_GEN, touchkey_led_status);
printk(KERN_DEBUG "LED returned on\n");
}
*/
enable_irq(info->irq);
info->is_powering_on = false;
return ret;
}
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
static void cypress_touchkey_early_suspend(struct early_suspend *h)
{
struct cypress_touchkey_info *info;
info = container_of(h, struct cypress_touchkey_info, early_suspend);
cypress_touchkey_suspend(&info->client->dev);
}
static void cypress_touchkey_late_resume(struct early_suspend *h)
{
struct cypress_touchkey_info *info;
info = container_of(h, struct cypress_touchkey_info, early_suspend);
cypress_touchkey_resume(&info->client->dev);
}
#endif
static const struct i2c_device_id cypress_touchkey_id[] = {
{"cypress_touchkey", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, cypress_touchkey_id);
#if defined(CONFIG_PM) && !defined(CONFIG_HAS_EARLYSUSPEND)
static const struct dev_pm_ops cypress_touchkey_pm_ops = {
.suspend = cypress_touchkey_suspend,
.resume = cypress_touchkey_resume,
};
#endif
struct i2c_driver cypress_touchkey_driver = {
.probe = cypress_touchkey_probe,
.remove = cypress_touchkey_remove,
.driver = {
.name = "cypress_touchkey",
#if defined(CONFIG_PM) && !defined(CONFIG_HAS_EARLYSUSPEND)
.pm = &cypress_touchkey_pm_ops,
#endif
},
.id_table = cypress_touchkey_id,
};
static int __init cypress_touchkey_init(void)
{
int ret = 0;
ret = i2c_add_driver(&cypress_touchkey_driver);
if (ret) {
printk(KERN_ERR"[TouchKey] cypress touch keypad registration failed. ret= %d\n",
ret);
}
return ret;
}
static void __exit cypress_touchkey_exit(void)
{
i2c_del_driver(&cypress_touchkey_driver);
}
late_initcall(cypress_touchkey_init);
module_exit(cypress_touchkey_exit);
MODULE_DESCRIPTION("Touchkey driver for Cypress touchkey controller ");
MODULE_LICENSE("GPL");
| gpl-2.0 |
rutvik95/android_kernel_samsung_kmini3g | drivers/video/msm/mdss/mdss_io_util.c | 28 | 12705 | /* 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/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/delay.h>
#include "mdss_io_util.h"
#define MAX_I2C_CMDS 16
void dss_reg_w(struct dss_io_data *io, u32 offset, u32 value, u32 debug)
{
u32 in_val;
if (!io || !io->base) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return;
}
if (offset > io->len) {
DEV_ERR("%pS->%s: offset out of range\n",
__builtin_return_address(0), __func__);
return;
}
writel_relaxed(value, io->base + offset);
if (debug) {
in_val = readl_relaxed(io->base + offset);
DEV_DBG("[%08x] => %08x [%08x]\n", (u32)(io->base + offset),
value, in_val);
}
} /* dss_reg_w */
u32 dss_reg_r(struct dss_io_data *io, u32 offset, u32 debug)
{
u32 value;
if (!io || !io->base) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return -EINVAL;
}
if (offset > io->len) {
DEV_ERR("%pS->%s: offset out of range\n",
__builtin_return_address(0), __func__);
return -EINVAL;
}
value = readl_relaxed(io->base + offset);
if (debug)
DEV_DBG("[%08x] <= %08x\n", (u32)(io->base + offset), value);
return value;
} /* dss_reg_r */
void dss_reg_dump(void __iomem *base, u32 length, const char *prefix,
u32 debug)
{
if (debug)
print_hex_dump(KERN_INFO, prefix, DUMP_PREFIX_OFFSET, 32, 4,
(void *)base, length, false);
} /* dss_reg_dump */
static struct resource *msm_dss_get_res_byname(struct platform_device *pdev,
unsigned int type, const char *name)
{
struct resource *res = NULL;
res = platform_get_resource_byname(pdev, type, name);
if (!res)
DEV_ERR("%s: '%s' resource not found\n", __func__, name);
return res;
} /* msm_dss_get_res_byname */
int msm_dss_ioremap_byname(struct platform_device *pdev,
struct dss_io_data *io_data, const char *name)
{
struct resource *res = NULL;
if (!pdev || !io_data) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return -EINVAL;
}
res = msm_dss_get_res_byname(pdev, IORESOURCE_MEM, name);
if (!res) {
DEV_ERR("%pS->%s: '%s' msm_dss_get_res_byname failed\n",
__builtin_return_address(0), __func__, name);
return -ENODEV;
}
io_data->len = resource_size(res);
io_data->base = ioremap(res->start, io_data->len);
if (!io_data->base) {
DEV_ERR("%pS->%s: '%s' ioremap failed\n",
__builtin_return_address(0), __func__, name);
return -EIO;
}
return 0;
} /* msm_dss_ioremap_byname */
void msm_dss_iounmap(struct dss_io_data *io_data)
{
if (!io_data) {
DEV_ERR("%pS->%s: invalid input\n",
__builtin_return_address(0), __func__);
return;
}
if (io_data->base) {
iounmap(io_data->base);
io_data->base = NULL;
}
io_data->len = 0;
} /* msm_dss_iounmap */
int msm_dss_config_vreg(struct device *dev, struct dss_vreg *in_vreg,
int num_vreg, int config)
{
int i = 0, rc = 0;
struct dss_vreg *curr_vreg = NULL;
enum dss_vreg_type type;
if (config) {
for (i = 0; i < num_vreg; i++) {
curr_vreg = &in_vreg[i];
curr_vreg->vreg = regulator_get(dev,
curr_vreg->vreg_name);
rc = PTR_RET(curr_vreg->vreg);
if (rc) {
DEV_ERR("%pS->%s: %s get failed. rc=%d\n",
__builtin_return_address(0), __func__,
curr_vreg->vreg_name, rc);
curr_vreg->vreg = NULL;
goto vreg_get_fail;
}
type = (regulator_count_voltages(curr_vreg->vreg) > 0)
? DSS_REG_LDO : DSS_REG_VS;
if (type == DSS_REG_LDO) {
rc = regulator_set_voltage(
curr_vreg->vreg,
curr_vreg->min_voltage,
curr_vreg->max_voltage);
if (rc < 0) {
DEV_ERR("%pS->%s: %s set vltg fail\n",
__builtin_return_address(0),
__func__,
curr_vreg->vreg_name);
goto vreg_set_voltage_fail;
}
}
}
} else {
for (i = num_vreg-1; i >= 0; i--) {
curr_vreg = &in_vreg[i];
if (curr_vreg->vreg) {
type = (regulator_count_voltages(
curr_vreg->vreg) > 0)
? DSS_REG_LDO : DSS_REG_VS;
if (type == DSS_REG_LDO) {
regulator_set_voltage(curr_vreg->vreg,
0, curr_vreg->max_voltage);
}
regulator_put(curr_vreg->vreg);
curr_vreg->vreg = NULL;
}
}
}
return 0;
vreg_unconfig:
if (type == DSS_REG_LDO)
regulator_set_optimum_mode(curr_vreg->vreg, 0);
vreg_set_voltage_fail:
regulator_put(curr_vreg->vreg);
curr_vreg->vreg = NULL;
vreg_get_fail:
for (i--; i >= 0; i--) {
curr_vreg = &in_vreg[i];
type = (regulator_count_voltages(curr_vreg->vreg) > 0)
? DSS_REG_LDO : DSS_REG_VS;
goto vreg_unconfig;
}
return rc;
} /* msm_dss_config_vreg */
#ifdef CONFIG_MACH_KSPORTSLTE_SPR
extern unsigned int system_rev;
#endif
int msm_dss_enable_vreg(struct dss_vreg *in_vreg, int num_vreg, int enable)
{
int i = 0, rc = 0;
if (enable) {
for (i = 0; i < num_vreg; i++) {
#if defined(CONFIG_MACH_MONDRIAN) || defined(CONFIG_MACH_CHAGALL)
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4)) {
pr_info("%s : VDD enable skip!!\n", __func__);
continue;
}
#endif
#ifdef CONFIG_MACH_KSPORTSLTE_SPR
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4) && (system_rev == 2)) {
pr_info("%s : VDD enable skip!! rev(%d)\n",in_vreg[i].vreg_name, system_rev);
continue;
}
#endif
#ifdef CONFIG_FB_MSM_MIPI_MAGNA_OCTA_VIDEO_WXGA_PT_DUAL_PANEL
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4)) {
continue;
}
#endif
rc = PTR_RET(in_vreg[i].vreg);
if (rc) {
DEV_ERR("%pS->%s: %s regulator error. rc=%d\n",
__builtin_return_address(0), __func__,
in_vreg[i].vreg_name, rc);
goto vreg_set_opt_mode_fail;
}
if (in_vreg[i].pre_on_sleep)
msleep(in_vreg[i].pre_on_sleep);
rc = regulator_set_optimum_mode(in_vreg[i].vreg,
in_vreg[i].enable_load);
if (rc < 0) {
DEV_ERR("%pS->%s: %s set opt m fail\n",
__builtin_return_address(0), __func__,
in_vreg[i].vreg_name);
goto vreg_set_opt_mode_fail;
}
rc = regulator_enable(in_vreg[i].vreg);
if (in_vreg[i].post_on_sleep)
msleep(in_vreg[i].post_on_sleep);
if (rc < 0) {
DEV_ERR("%pS->%s: %s enable failed\n",
__builtin_return_address(0), __func__,
in_vreg[i].vreg_name);
goto disable_vreg;
}
}
} else {
for (i = num_vreg-1; i >= 0; i--)
if (regulator_is_enabled(in_vreg[i].vreg)) {
#if defined(CONFIG_MACH_MONDRIAN) || defined(CONFIG_MACH_CHAGALL)
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4)) {
pr_info("%s : VDD disable skip!!\n", __func__);
continue;
}
#endif
#ifdef CONFIG_MACH_KANAS3G_CTC
if(!strncmp(in_vreg[i].vreg_name, "vdd", 3)) {
continue;
}
#endif
#ifdef CONFIG_MACH_KSPORTSLTE_SPR
if(!strncmp(in_vreg[i].vreg_name, "vdd", 4) && (system_rev == 2)) {
pr_info("%s : VDD disable skip!! rev(%d)\n",in_vreg[i].vreg_name, system_rev);
continue;
}
#endif
if (in_vreg[i].pre_off_sleep)
msleep(in_vreg[i].pre_off_sleep);
regulator_set_optimum_mode(in_vreg[i].vreg,
in_vreg[i].disable_load);
regulator_disable(in_vreg[i].vreg);
if (in_vreg[i].post_off_sleep)
msleep(in_vreg[i].post_off_sleep);
}
}
return rc;
disable_vreg:
regulator_set_optimum_mode(in_vreg[i].vreg, in_vreg[i].disable_load);
vreg_set_opt_mode_fail:
for (i--; i >= 0; i--) {
if (in_vreg[i].pre_off_sleep)
msleep(in_vreg[i].pre_off_sleep);
regulator_set_optimum_mode(in_vreg[i].vreg,
in_vreg[i].disable_load);
regulator_disable(in_vreg[i].vreg);
if (in_vreg[i].post_off_sleep)
msleep(in_vreg[i].post_off_sleep);
}
return rc;
} /* msm_dss_enable_vreg */
int msm_dss_enable_gpio(struct dss_gpio *in_gpio, int num_gpio, int enable)
{
int i = 0, rc = 0;
if (enable) {
for (i = 0; i < num_gpio; i++) {
DEV_DBG("%pS->%s: %s enable\n",
__builtin_return_address(0), __func__,
in_gpio[i].gpio_name);
rc = gpio_request(in_gpio[i].gpio,
in_gpio[i].gpio_name);
if (rc < 0) {
DEV_ERR("%pS->%s: %s enable failed\n",
__builtin_return_address(0), __func__,
in_gpio[i].gpio_name);
goto disable_gpio;
}
gpio_set_value(in_gpio[i].gpio, in_gpio[i].value);
}
} else {
for (i = num_gpio-1; i >= 0; i--) {
DEV_DBG("%pS->%s: %s disable\n",
__builtin_return_address(0), __func__,
in_gpio[i].gpio_name);
if (in_gpio[i].gpio)
gpio_free(in_gpio[i].gpio);
}
}
return rc;
disable_gpio:
for (i--; i >= 0; i--)
if (in_gpio[i].gpio)
gpio_free(in_gpio[i].gpio);
return rc;
} /* msm_dss_enable_gpio */
void msm_dss_put_clk(struct dss_clk *clk_arry, int num_clk)
{
int i;
for (i = num_clk - 1; i >= 0; i--) {
if (clk_arry[i].clk)
clk_put(clk_arry[i].clk);
clk_arry[i].clk = NULL;
}
} /* msm_dss_put_clk */
int msm_dss_get_clk(struct device *dev, struct dss_clk *clk_arry, int num_clk)
{
int i, rc = 0;
for (i = 0; i < num_clk; i++) {
clk_arry[i].clk = clk_get(dev, clk_arry[i].clk_name);
rc = PTR_RET(clk_arry[i].clk);
if (rc) {
DEV_ERR("%pS->%s: '%s' get failed. rc=%d\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name, rc);
goto error;
}
}
return rc;
error:
msm_dss_put_clk(clk_arry, num_clk);
return rc;
} /* msm_dss_get_clk */
int msm_dss_clk_set_rate(struct dss_clk *clk_arry, int num_clk)
{
int i, rc = 0;
for (i = 0; i < num_clk; i++) {
if (clk_arry[i].clk) {
if (DSS_CLK_AHB != clk_arry[i].type) {
DEV_DBG("%pS->%s: '%s' rate %ld\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name,
clk_arry[i].rate);
rc = clk_set_rate(clk_arry[i].clk,
clk_arry[i].rate);
if (rc) {
DEV_ERR("%pS->%s: %s failed. rc=%d\n",
__builtin_return_address(0),
__func__,
clk_arry[i].clk_name, rc);
break;
}
}
} else {
DEV_ERR("%pS->%s: '%s' is not available\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
rc = -EPERM;
break;
}
}
return rc;
} /* msm_dss_clk_set_rate */
int msm_dss_enable_clk(struct dss_clk *clk_arry, int num_clk, int enable)
{
int i, rc = 0;
if (enable) {
for (i = 0; i < num_clk; i++) {
DEV_DBG("%pS->%s: enable '%s'\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
if (clk_arry[i].clk) {
rc = clk_prepare_enable(clk_arry[i].clk);
if (rc)
DEV_ERR("%pS->%s: %s en fail. rc=%d\n",
__builtin_return_address(0),
__func__,
clk_arry[i].clk_name, rc);
} else {
DEV_ERR("%pS->%s: '%s' is not available\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
rc = -EPERM;
}
if (rc) {
msm_dss_enable_clk(&clk_arry[i],
i, false);
break;
}
}
} else {
for (i = num_clk - 1; i >= 0; i--) {
DEV_DBG("%pS->%s: disable '%s'\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
if (clk_arry[i].clk)
clk_disable_unprepare(clk_arry[i].clk);
else
DEV_ERR("%pS->%s: '%s' is not available\n",
__builtin_return_address(0), __func__,
clk_arry[i].clk_name);
}
}
return rc;
} /* msm_dss_enable_clk */
int mdss_i2c_byte_read(struct i2c_client *client, uint8_t slave_addr,
uint8_t reg_offset, uint8_t *read_buf)
{
struct i2c_msg msgs[2];
int ret = -1;
pr_debug("%s: reading from slave_addr=[%x] and offset=[%x]\n",
__func__, slave_addr, reg_offset);
msgs[0].addr = slave_addr >> 1;
msgs[0].flags = 0;
msgs[0].buf = ®_offset;
msgs[0].len = 1;
msgs[1].addr = slave_addr >> 1;
msgs[1].flags = I2C_M_RD;
msgs[1].buf = read_buf;
msgs[1].len = 1;
ret = i2c_transfer(client->adapter, msgs, 2);
if (ret < 1) {
pr_err("%s: I2C READ FAILED=[%d]\n", __func__, ret);
return -EACCES;
}
pr_debug("%s: i2c buf is [%x]\n", __func__, *read_buf);
return 0;
}
int mdss_i2c_byte_write(struct i2c_client *client, uint8_t slave_addr,
uint8_t reg_offset, uint8_t *value)
{
struct i2c_msg msgs[1];
uint8_t data[2];
int status = -EACCES;
pr_debug("%s: writing from slave_addr=[%x] and offset=[%x]\n",
__func__, slave_addr, reg_offset);
data[0] = reg_offset;
data[1] = *value;
msgs[0].addr = slave_addr >> 1;
msgs[0].flags = 0;
msgs[0].len = 2;
msgs[0].buf = data;
status = i2c_transfer(client->adapter, msgs, 1);
if (status < 1) {
pr_err("I2C WRITE FAILED=[%d]\n", status);
return -EACCES;
}
pr_debug("%s: I2C write status=%x\n", __func__, status);
return status;
}
| gpl-2.0 |
liaoqingwei/ltp | testcases/open_posix_testsuite/conformance/interfaces/pthread_cond_timedwait/4-3.c | 28 | 7811 | /*
* Copyright (c) 2004, Bull S.A.. All rights reserved.
* Created by: Sebastien Decugis
* 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.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* This sample test aims to check the following assertion:
*
* This sample test aims to check the following assertion:
* The function does not return an error code of EINTR
* The steps are:
*
* -> Create a thread which wait in a condition for a small time.
* -> Another thread will signal this condition from time to time.
* -> Another thread which loops on sending a signal to the first thread.
*
*/
/* We are testing conformance to IEEE Std 1003.1, 2003 Edition */
#define _POSIX_C_SOURCE 200112L
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include "../testfrmw/testfrmw.h"
#include "../testfrmw/testfrmw.c"
#define WITH_SYNCHRO
#ifndef VERBOSE
#define VERBOSE 2
#endif
#define TIMEOUT (1000) /* ns, timeout parameter for pthread_cond_timedwait */
#define INTERVAL (700) /* ns, frequency (actually, period) for the condition signaling */
char do_it = 1;
unsigned long count_cnd_sig = 0, count_cnd_wup = 0;
#ifdef WITH_SYNCHRO
sem_t semsig1;
sem_t semsig2;
unsigned long count_sig = 0;
#endif
sigset_t usersigs;
typedef struct {
int sig;
#ifdef WITH_SYNCHRO
sem_t *sem;
#endif
} thestruct;
struct {
pthread_mutex_t mtx;
pthread_cond_t cnd;
} data;
/* the following function keeps on sending the signal to the process */
void *sendsig(void *arg)
{
thestruct *thearg = (thestruct *) arg;
int ret;
pid_t process;
process = getpid();
/* We block the signals SIGUSR1 and SIGUSR2 for this THREAD */
ret = pthread_sigmask(SIG_BLOCK, &usersigs, NULL);
if (ret != 0) {
UNRESOLVED(ret,
"Unable to block SIGUSR1 and SIGUSR2 in signal thread");
}
while (do_it) {
#ifdef WITH_SYNCHRO
if ((ret = sem_wait(thearg->sem))) {
UNRESOLVED(errno, "Sem_wait in sendsig");
}
count_sig++;
#endif
ret = kill(process, thearg->sig);
if (ret != 0) {
UNRESOLVED(errno, "Kill in sendsig");
}
}
return NULL;
}
/* Next are the signal handlers. */
/* This one is registered for signal SIGUSR1 */
void sighdl1(int sig)
{
(void) sig;
#ifdef WITH_SYNCHRO
if (sem_post(&semsig1)) {
UNRESOLVED(errno, "Sem_post in signal handler 1");
}
#endif
}
/* This one is registered for signal SIGUSR2 */
void sighdl2(int sig)
{
(void) sig;
#ifdef WITH_SYNCHRO
if (sem_post(&semsig2)) {
UNRESOLVED(errno, "Sem_post in signal handler 2");
}
#endif
}
/* The following function will timedwait on the cond
* it does check that no error code of EINTR is returned */
void *waiter(void *arg)
{
int ret;
struct timespec ts;
(void) arg;
/* We don't block the signals SIGUSR1 and SIGUSR2 for this THREAD */
ret = pthread_sigmask(SIG_UNBLOCK, &usersigs, NULL);
if (ret != 0) {
UNRESOLVED(ret,
"Unable to unblock SIGUSR1 and SIGUSR2 in worker thread");
}
ret = pthread_mutex_lock(&(data.mtx));
if (ret != 0) {
UNRESOLVED(ret, "Unable to lock mutex in waiter thread");
}
while (do_it) {
ret = clock_gettime(CLOCK_REALTIME, &ts);
if (ret != 0) {
UNRESOLVED(ret, "Unable to get system time");
}
ts.tv_nsec += TIMEOUT;
while (ts.tv_nsec >= 1000000000) {
ts.tv_nsec -= 1000000000;
ts.tv_sec += 1;
}
do {
ret =
pthread_cond_timedwait(&(data.cnd), &(data.mtx),
&ts);
count_cnd_wup++;
} while (ret == 0);
if (ret == EINTR) {
FAILED("pthread_cond_timedwait returned EINTR");
}
if (ret != ETIMEDOUT) {
UNRESOLVED(ret,
"pthread_cond_timedwait returned an unexpected error");
}
}
ret = pthread_mutex_unlock(&(data.mtx));
if (ret != 0) {
UNRESOLVED(ret, "Unable to unlock mutex in waiter thread");
}
return NULL;
}
/* The next function will signal the condition at periodic interval */
void *worker(void *arg)
{
int ret = 0;
struct timespec ts, tsrem;
(void) arg;
/* We block the signals SIGUSR1 and SIGUSR2 for this THREAD */
ret = pthread_sigmask(SIG_BLOCK, &usersigs, NULL);
if (ret != 0) {
UNRESOLVED(ret,
"Unable to block SIGUSR1 and SIGUSR2 in signal thread");
}
ts.tv_sec = 0;
ts.tv_nsec = INTERVAL;
while (ts.tv_nsec >= 1000000000) {
ts.tv_nsec -= 1000000000;
ts.tv_sec += 1;
}
while (do_it) {
tsrem.tv_sec = ts.tv_sec;
tsrem.tv_nsec = ts.tv_nsec;
do {
ret = nanosleep(&tsrem, &tsrem);
}
while ((ret != 0) && (errno == EINTR));
ret = pthread_cond_signal(&(data.cnd));
if (ret != 0) {
UNRESOLVED(ret, "Failed to signal the condition");
}
count_cnd_sig++;
}
return NULL;
}
/* Main function */
int main(void)
{
int ret;
pthread_t th_waiter, th_worker, th_sig1, th_sig2;
thestruct arg1, arg2;
struct sigaction sa;
output_init();
/* We need to register the signal handlers for the PROCESS */
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = sighdl1;
if ((ret = sigaction(SIGUSR1, &sa, NULL))) {
UNRESOLVED(ret, "Unable to register signal handler1");
}
sa.sa_handler = sighdl2;
if ((ret = sigaction(SIGUSR2, &sa, NULL))) {
UNRESOLVED(ret, "Unable to register signal handler2");
}
/* We prepare a signal set which includes SIGUSR1 and SIGUSR2 */
sigemptyset(&usersigs);
ret = sigaddset(&usersigs, SIGUSR1);
ret |= sigaddset(&usersigs, SIGUSR2);
if (ret != 0) {
UNRESOLVED(ret, "Unable to add SIGUSR1 or 2 to a signal set");
}
/* We now block the signals SIGUSR1 and SIGUSR2 for this THREAD */
ret = pthread_sigmask(SIG_BLOCK, &usersigs, NULL);
if (ret != 0) {
UNRESOLVED(ret,
"Unable to block SIGUSR1 and SIGUSR2 in main thread");
}
#ifdef WITH_SYNCHRO
if (sem_init(&semsig1, 0, 1)) {
UNRESOLVED(errno, "Semsig1 init");
}
if (sem_init(&semsig2, 0, 1)) {
UNRESOLVED(errno, "Semsig2 init");
}
#endif
if ((ret = pthread_create(&th_waiter, NULL, waiter, NULL))) {
UNRESOLVED(ret, "Waiter thread creation failed");
}
if ((ret = pthread_create(&th_worker, NULL, worker, NULL))) {
UNRESOLVED(ret, "Worker thread creation failed");
}
arg1.sig = SIGUSR1;
arg2.sig = SIGUSR2;
#ifdef WITH_SYNCHRO
arg1.sem = &semsig1;
arg2.sem = &semsig2;
#endif
if ((ret = pthread_create(&th_sig1, NULL, sendsig, (void *)&arg1))) {
UNRESOLVED(ret, "Signal 1 sender thread creation failed");
}
if ((ret = pthread_create(&th_sig2, NULL, sendsig, (void *)&arg2))) {
UNRESOLVED(ret, "Signal 2 sender thread creation failed");
}
/* Let's wait for a while now */
sleep(1);
/* Now stop the threads and join them */
do {
do_it = 0;
}
while (do_it);
if ((ret = pthread_join(th_sig1, NULL))) {
UNRESOLVED(ret, "Signal 1 sender thread join failed");
}
if ((ret = pthread_join(th_sig2, NULL))) {
UNRESOLVED(ret, "Signal 2 sender thread join failed");
}
if ((ret = pthread_join(th_worker, NULL))) {
UNRESOLVED(ret, "Worker thread join failed");
}
if ((ret = pthread_join(th_waiter, NULL))) {
UNRESOLVED(ret, "Waiter thread join failed");
}
#if VERBOSE > 0
output("Test executed successfully.\n");
output(" Condition was signaled %d times.\n", count_cnd_sig);
output(" pthread_timed_wait exited %d times.\n", count_cnd_wup);
#ifdef WITH_SYNCHRO
output(" %d signals were sent meanwhile.\n", count_sig);
#endif
#endif
PASSED;
}
| gpl-2.0 |
vyatta/linux-vyatta | drivers/rtc/rtc-mc13xxx.c | 284 | 9542 | /*
* Real Time Clock driver for Freescale MC13XXX PMIC
*
* (C) 2009 Sascha Hauer, Pengutronix
* (C) 2009 Uwe Kleine-Koenig, Pengutronix
*
* 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/mfd/mc13xxx.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/rtc.h>
#define DRIVER_NAME "mc13xxx-rtc"
#define MC13XXX_RTCTOD 20
#define MC13XXX_RTCTODA 21
#define MC13XXX_RTCDAY 22
#define MC13XXX_RTCDAYA 23
struct mc13xxx_rtc {
struct rtc_device *rtc;
struct mc13xxx *mc13xxx;
int valid;
};
static int mc13xxx_rtc_irq_enable_unlocked(struct device *dev,
unsigned int enabled, int irq)
{
struct mc13xxx_rtc *priv = dev_get_drvdata(dev);
int (*func)(struct mc13xxx *mc13xxx, int irq);
if (!priv->valid)
return -ENODATA;
func = enabled ? mc13xxx_irq_unmask : mc13xxx_irq_mask;
return func(priv->mc13xxx, irq);
}
static int mc13xxx_rtc_irq_enable(struct device *dev,
unsigned int enabled, int irq)
{
struct mc13xxx_rtc *priv = dev_get_drvdata(dev);
int ret;
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_rtc_irq_enable_unlocked(dev, enabled, irq);
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct mc13xxx_rtc *priv = dev_get_drvdata(dev);
unsigned int seconds, days1, days2;
unsigned long s1970;
int ret;
mc13xxx_lock(priv->mc13xxx);
if (!priv->valid) {
ret = -ENODATA;
goto out;
}
ret = mc13xxx_reg_read(priv->mc13xxx, MC13XXX_RTCDAY, &days1);
if (unlikely(ret))
goto out;
ret = mc13xxx_reg_read(priv->mc13xxx, MC13XXX_RTCTOD, &seconds);
if (unlikely(ret))
goto out;
ret = mc13xxx_reg_read(priv->mc13xxx, MC13XXX_RTCDAY, &days2);
out:
mc13xxx_unlock(priv->mc13xxx);
if (ret)
return ret;
if (days2 == days1 + 1) {
if (seconds >= 86400 / 2)
days2 = days1;
else
days1 = days2;
}
if (days1 != days2)
return -EIO;
s1970 = days1 * 86400 + seconds;
rtc_time_to_tm(s1970, tm);
return rtc_valid_tm(tm);
}
static int mc13xxx_rtc_set_mmss(struct device *dev, unsigned long secs)
{
struct mc13xxx_rtc *priv = dev_get_drvdata(dev);
unsigned int seconds, days;
unsigned int alarmseconds;
int ret;
seconds = secs % 86400;
days = secs / 86400;
mc13xxx_lock(priv->mc13xxx);
/*
* temporarily invalidate alarm to prevent triggering it when the day is
* already updated while the time isn't yet.
*/
ret = mc13xxx_reg_read(priv->mc13xxx, MC13XXX_RTCTODA, &alarmseconds);
if (unlikely(ret))
goto out;
if (alarmseconds < 86400) {
ret = mc13xxx_reg_write(priv->mc13xxx,
MC13XXX_RTCTODA, 0x1ffff);
if (unlikely(ret))
goto out;
}
/*
* write seconds=0 to prevent a day switch between writing days
* and seconds below
*/
ret = mc13xxx_reg_write(priv->mc13xxx, MC13XXX_RTCTOD, 0);
if (unlikely(ret))
goto out;
ret = mc13xxx_reg_write(priv->mc13xxx, MC13XXX_RTCDAY, days);
if (unlikely(ret))
goto out;
ret = mc13xxx_reg_write(priv->mc13xxx, MC13XXX_RTCTOD, seconds);
if (unlikely(ret))
goto out;
/* restore alarm */
if (alarmseconds < 86400) {
ret = mc13xxx_reg_write(priv->mc13xxx,
MC13XXX_RTCTODA, alarmseconds);
if (unlikely(ret))
goto out;
}
ret = mc13xxx_irq_ack(priv->mc13xxx, MC13XXX_IRQ_RTCRST);
if (unlikely(ret))
goto out;
ret = mc13xxx_irq_unmask(priv->mc13xxx, MC13XXX_IRQ_RTCRST);
out:
priv->valid = !ret;
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static int mc13xxx_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alarm)
{
struct mc13xxx_rtc *priv = dev_get_drvdata(dev);
unsigned seconds, days;
unsigned long s1970;
int enabled, pending;
int ret;
mc13xxx_lock(priv->mc13xxx);
ret = mc13xxx_reg_read(priv->mc13xxx, MC13XXX_RTCTODA, &seconds);
if (unlikely(ret))
goto out;
if (seconds >= 86400) {
ret = -ENODATA;
goto out;
}
ret = mc13xxx_reg_read(priv->mc13xxx, MC13XXX_RTCDAY, &days);
if (unlikely(ret))
goto out;
ret = mc13xxx_irq_status(priv->mc13xxx, MC13XXX_IRQ_TODA,
&enabled, &pending);
out:
mc13xxx_unlock(priv->mc13xxx);
if (ret)
return ret;
alarm->enabled = enabled;
alarm->pending = pending;
s1970 = days * 86400 + seconds;
rtc_time_to_tm(s1970, &alarm->time);
dev_dbg(dev, "%s: %lu\n", __func__, s1970);
return 0;
}
static int mc13xxx_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alarm)
{
struct mc13xxx_rtc *priv = dev_get_drvdata(dev);
unsigned long s1970;
unsigned seconds, days;
int ret;
mc13xxx_lock(priv->mc13xxx);
/* disable alarm to prevent false triggering */
ret = mc13xxx_reg_write(priv->mc13xxx, MC13XXX_RTCTODA, 0x1ffff);
if (unlikely(ret))
goto out;
ret = mc13xxx_irq_ack(priv->mc13xxx, MC13XXX_IRQ_TODA);
if (unlikely(ret))
goto out;
ret = rtc_tm_to_time(&alarm->time, &s1970);
if (unlikely(ret))
goto out;
dev_dbg(dev, "%s: o%2.s %lu\n", __func__, alarm->enabled ? "n" : "ff",
s1970);
ret = mc13xxx_rtc_irq_enable_unlocked(dev, alarm->enabled,
MC13XXX_IRQ_TODA);
if (unlikely(ret))
goto out;
seconds = s1970 % 86400;
days = s1970 / 86400;
ret = mc13xxx_reg_write(priv->mc13xxx, MC13XXX_RTCDAYA, days);
if (unlikely(ret))
goto out;
ret = mc13xxx_reg_write(priv->mc13xxx, MC13XXX_RTCTODA, seconds);
out:
mc13xxx_unlock(priv->mc13xxx);
return ret;
}
static irqreturn_t mc13xxx_rtc_alarm_handler(int irq, void *dev)
{
struct mc13xxx_rtc *priv = dev;
struct mc13xxx *mc13xxx = priv->mc13xxx;
dev_dbg(&priv->rtc->dev, "Alarm\n");
rtc_update_irq(priv->rtc, 1, RTC_IRQF | RTC_AF);
mc13xxx_irq_ack(mc13xxx, irq);
return IRQ_HANDLED;
}
static irqreturn_t mc13xxx_rtc_update_handler(int irq, void *dev)
{
struct mc13xxx_rtc *priv = dev;
struct mc13xxx *mc13xxx = priv->mc13xxx;
dev_dbg(&priv->rtc->dev, "1HZ\n");
rtc_update_irq(priv->rtc, 1, RTC_IRQF | RTC_UF);
mc13xxx_irq_ack(mc13xxx, irq);
return IRQ_HANDLED;
}
static int mc13xxx_rtc_alarm_irq_enable(struct device *dev,
unsigned int enabled)
{
return mc13xxx_rtc_irq_enable(dev, enabled, MC13XXX_IRQ_TODA);
}
static const struct rtc_class_ops mc13xxx_rtc_ops = {
.read_time = mc13xxx_rtc_read_time,
.set_mmss = mc13xxx_rtc_set_mmss,
.read_alarm = mc13xxx_rtc_read_alarm,
.set_alarm = mc13xxx_rtc_set_alarm,
.alarm_irq_enable = mc13xxx_rtc_alarm_irq_enable,
};
static irqreturn_t mc13xxx_rtc_reset_handler(int irq, void *dev)
{
struct mc13xxx_rtc *priv = dev;
struct mc13xxx *mc13xxx = priv->mc13xxx;
dev_dbg(&priv->rtc->dev, "RTCRST\n");
priv->valid = 0;
mc13xxx_irq_mask(mc13xxx, irq);
return IRQ_HANDLED;
}
static int __init mc13xxx_rtc_probe(struct platform_device *pdev)
{
int ret;
struct mc13xxx_rtc *priv;
struct mc13xxx *mc13xxx;
int rtcrst_pending;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
mc13xxx = dev_get_drvdata(pdev->dev.parent);
priv->mc13xxx = mc13xxx;
platform_set_drvdata(pdev, priv);
mc13xxx_lock(mc13xxx);
ret = mc13xxx_irq_request(mc13xxx, MC13XXX_IRQ_RTCRST,
mc13xxx_rtc_reset_handler, DRIVER_NAME, priv);
if (ret)
goto err_reset_irq_request;
ret = mc13xxx_irq_status(mc13xxx, MC13XXX_IRQ_RTCRST,
NULL, &rtcrst_pending);
if (ret)
goto err_reset_irq_status;
priv->valid = !rtcrst_pending;
ret = mc13xxx_irq_request_nounmask(mc13xxx, MC13XXX_IRQ_1HZ,
mc13xxx_rtc_update_handler, DRIVER_NAME, priv);
if (ret)
goto err_update_irq_request;
ret = mc13xxx_irq_request_nounmask(mc13xxx, MC13XXX_IRQ_TODA,
mc13xxx_rtc_alarm_handler, DRIVER_NAME, priv);
if (ret)
goto err_alarm_irq_request;
mc13xxx_unlock(mc13xxx);
priv->rtc = rtc_device_register(pdev->name,
&pdev->dev, &mc13xxx_rtc_ops, THIS_MODULE);
if (IS_ERR(priv->rtc)) {
ret = PTR_ERR(priv->rtc);
mc13xxx_lock(mc13xxx);
mc13xxx_irq_free(mc13xxx, MC13XXX_IRQ_TODA, priv);
err_alarm_irq_request:
mc13xxx_irq_free(mc13xxx, MC13XXX_IRQ_1HZ, priv);
err_update_irq_request:
err_reset_irq_status:
mc13xxx_irq_free(mc13xxx, MC13XXX_IRQ_RTCRST, priv);
err_reset_irq_request:
mc13xxx_unlock(mc13xxx);
platform_set_drvdata(pdev, NULL);
kfree(priv);
}
return ret;
}
static int __exit mc13xxx_rtc_remove(struct platform_device *pdev)
{
struct mc13xxx_rtc *priv = platform_get_drvdata(pdev);
mc13xxx_lock(priv->mc13xxx);
rtc_device_unregister(priv->rtc);
mc13xxx_irq_free(priv->mc13xxx, MC13XXX_IRQ_TODA, priv);
mc13xxx_irq_free(priv->mc13xxx, MC13XXX_IRQ_1HZ, priv);
mc13xxx_irq_free(priv->mc13xxx, MC13XXX_IRQ_RTCRST, priv);
mc13xxx_unlock(priv->mc13xxx);
platform_set_drvdata(pdev, NULL);
kfree(priv);
return 0;
}
static const struct platform_device_id mc13xxx_rtc_idtable[] = {
{
.name = "mc13783-rtc",
}, {
.name = "mc13892-rtc",
}, {
.name = "mc34708-rtc",
},
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(platform, mc13xxx_rtc_idtable);
static struct platform_driver mc13xxx_rtc_driver = {
.id_table = mc13xxx_rtc_idtable,
.remove = __exit_p(mc13xxx_rtc_remove),
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static int __init mc13xxx_rtc_init(void)
{
return platform_driver_probe(&mc13xxx_rtc_driver, &mc13xxx_rtc_probe);
}
module_init(mc13xxx_rtc_init);
static void __exit mc13xxx_rtc_exit(void)
{
platform_driver_unregister(&mc13xxx_rtc_driver);
}
module_exit(mc13xxx_rtc_exit);
MODULE_AUTHOR("Sascha Hauer <s.hauer@pengutronix.de>");
MODULE_DESCRIPTION("RTC driver for Freescale MC13XXX PMIC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
WOWalmanserver/Pandaren5.3.0 | dep/acelite/ace/SOCK_CODgram.cpp | 540 | 4826 | // $Id: SOCK_CODgram.cpp 91287 2010-08-05 10:30:49Z johnnyw $
#include "ace/SOCK_CODgram.h"
#include "ace/Log_Msg.h"
#include "ace/OS_NS_sys_socket.h"
#if !defined (__ACE_INLINE__)
#include "ace/SOCK_CODgram.inl"
#endif /* __ACE_INLINE__ */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_ALLOC_HOOK_DEFINE(ACE_SOCK_CODgram)
void
ACE_SOCK_CODgram::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_SOCK_CODgram::dump");
#endif /* ACE_HAS_DUMP */
}
// Here's the general-purpose constructor.
ACE_SOCK_CODgram::ACE_SOCK_CODgram (const ACE_Addr &remote,
const ACE_Addr &local,
int protocol_family,
int protocol,
int reuse_addr)
{
ACE_TRACE ("ACE_SOCK_CODgram::ACE_SOCK_CODgram");
if (this->open (remote,
local,
protocol_family,
protocol,
reuse_addr) == -1)
ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("ACE_SOCK_CODgram")));
}
/* This is the general-purpose open routine. Note that it performs
a different set of functions depending on the LOCAL and REMOTE
addresses passed to it. Here's the basic logic:
1. remote == ACE_Addr::sap_any && local == ACE_Addr::sap_any
if protocol_family == PF_INET || PF_INET6 then
bind the local address to a randomly generated port number...
2. remote == ACE_Addr::sap_any && local != ACE_Addr::sap_any
we are just binding the local address
(used primarily by servers)
3. remote != ACE_Addr::sap_any && local == ACE_Addr::sap_any
we are connecting to the remote address
(used primarily by clients)
4. remote != ACE_Addr::sap_any && local != ACE_Addr::sap_any
we are binding to the local address
and connecting to the remote address
*/
int
ACE_SOCK_CODgram::open (const ACE_Addr &remote, const ACE_Addr &local,
int protocol_family, int protocol,
int reuse_addr)
{
ACE_TRACE ("ACE_SOCK_CODgram::open");
// Depending on the addresses passed as described above, figure out what
// address family to specify for the new socket. If either address is
// !ACE_Addr::sap_any, use that family. If they don't match, it's an error.
if (remote != ACE_Addr::sap_any)
{
if (local == ACE_Addr::sap_any)
protocol_family = remote.get_type ();
else
{ // Both specified; family must match
if (local.get_type () != remote.get_type ())
{
errno = EAFNOSUPPORT;
return -1;
}
protocol_family = remote.get_type ();
}
}
else
{
if (local != ACE_Addr::sap_any)
{
protocol_family = local.get_type ();
}
}
if (ACE_SOCK::open (SOCK_DGRAM,
protocol_family,
protocol,
reuse_addr) == -1)
{
return -1;
}
else
{
bool error = false;
if (local == ACE_Addr::sap_any && remote == ACE_Addr::sap_any)
{
// Assign an arbitrary port number from the transient range!!
if ((protocol_family == PF_INET
#if defined (ACE_HAS_IPV6)
|| protocol_family == PF_INET6
#endif /* ACE_HAS_IPV6 */
) && ACE::bind_port (this->get_handle ()) == -1)
error = true;
}
// We are binding just the local address.
else if (local != ACE_Addr::sap_any && remote == ACE_Addr::sap_any)
{
if (ACE_OS::bind (this->get_handle (),
(sockaddr *) local.get_addr (),
local.get_size ()) == -1)
error = true;
}
// We are connecting to the remote address.
else if (local == ACE_Addr::sap_any && remote != ACE_Addr::sap_any)
{
if (ACE_OS::connect (this->get_handle (),
(sockaddr *) remote.get_addr (),
remote.get_size ()) == -1)
error = true;
}
// We are binding to the local address and connecting to the
// remote addresses.
else
{
if (ACE_OS::bind (this->get_handle (),
(sockaddr *) local.get_addr (),
local.get_size ()) == -1
|| ACE_OS::connect (this->get_handle (),
(sockaddr *) remote.get_addr (),
remote.get_size ()) == -1)
error = true;
}
if (error)
{
this->close ();
this->set_handle (ACE_INVALID_HANDLE);
}
return error ? -1 : 0;
}
}
ACE_END_VERSIONED_NAMESPACE_DECL
| gpl-2.0 |
DJSteve/StreakKernel | drivers/atm/adummy.c | 796 | 3035 | /*
* adummy.c: a dummy ATM driver
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>
#include <linux/atmdev.h>
#include <linux/atm.h>
#include <linux/sonet.h>
/* version definition */
#define DRV_VERSION "1.0"
#define DEV_LABEL "adummy"
#define ADUMMY_DEV(dev) ((struct adummy_dev *) (dev)->dev_data)
struct adummy_dev {
struct atm_dev *atm_dev;
struct list_head entry;
};
/* globals */
static LIST_HEAD(adummy_devs);
static int __init
adummy_start(struct atm_dev *dev)
{
dev->ci_range.vpi_bits = 4;
dev->ci_range.vci_bits = 12;
return 0;
}
static int
adummy_open(struct atm_vcc *vcc)
{
short vpi = vcc->vpi;
int vci = vcc->vci;
if (vci == ATM_VCI_UNSPEC || vpi == ATM_VPI_UNSPEC)
return 0;
set_bit(ATM_VF_ADDR, &vcc->flags);
set_bit(ATM_VF_READY, &vcc->flags);
return 0;
}
static void
adummy_close(struct atm_vcc *vcc)
{
clear_bit(ATM_VF_READY, &vcc->flags);
clear_bit(ATM_VF_ADDR, &vcc->flags);
}
static int
adummy_send(struct atm_vcc *vcc, struct sk_buff *skb)
{
if (vcc->pop)
vcc->pop(vcc, skb);
else
dev_kfree_skb_any(skb);
atomic_inc(&vcc->stats->tx);
return 0;
}
static int
adummy_proc_read(struct atm_dev *dev, loff_t *pos, char *page)
{
int left = *pos;
if (!left--)
return sprintf(page, "version %s\n", DRV_VERSION);
return 0;
}
static struct atmdev_ops adummy_ops =
{
.open = adummy_open,
.close = adummy_close,
.send = adummy_send,
.proc_read = adummy_proc_read,
.owner = THIS_MODULE
};
static int __init adummy_init(void)
{
struct atm_dev *atm_dev;
struct adummy_dev *adummy_dev;
int err = 0;
printk(KERN_ERR "adummy: version %s\n", DRV_VERSION);
adummy_dev = kzalloc(sizeof(struct adummy_dev),
GFP_KERNEL);
if (!adummy_dev) {
printk(KERN_ERR DEV_LABEL ": kzalloc() failed\n");
err = -ENOMEM;
goto out;
}
atm_dev = atm_dev_register(DEV_LABEL, &adummy_ops, -1, NULL);
if (!atm_dev) {
printk(KERN_ERR DEV_LABEL ": atm_dev_register() failed\n");
err = -ENODEV;
goto out_kfree;
}
adummy_dev->atm_dev = atm_dev;
atm_dev->dev_data = adummy_dev;
if (adummy_start(atm_dev)) {
printk(KERN_ERR DEV_LABEL ": adummy_start() failed\n");
err = -ENODEV;
goto out_unregister;
}
list_add(&adummy_dev->entry, &adummy_devs);
out:
return err;
out_unregister:
atm_dev_deregister(atm_dev);
out_kfree:
kfree(adummy_dev);
goto out;
}
static void __exit adummy_cleanup(void)
{
struct adummy_dev *adummy_dev, *next;
list_for_each_entry_safe(adummy_dev, next, &adummy_devs, entry) {
atm_dev_deregister(adummy_dev->atm_dev);
kfree(adummy_dev);
}
}
module_init(adummy_init);
module_exit(adummy_cleanup);
MODULE_AUTHOR("chas williams <chas@cmf.nrl.navy.mil>");
MODULE_DESCRIPTION("dummy ATM driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
crpalmer/android_kernel_sony_tetra | arch/xtensa/mm/init.c | 1052 | 5225 | /*
* arch/xtensa/mm/init.c
*
* Derived from MIPS, PPC.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2001 - 2005 Tensilica Inc.
*
* Chris Zankel <chris@zankel.net>
* Joe Taylor <joe@tensilica.com, joetylr@yahoo.com>
* Marc Gauthier
* Kevin Chea
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/bootmem.h>
#include <linux/gfp.h>
#include <linux/swap.h>
#include <linux/mman.h>
#include <linux/nodemask.h>
#include <linux/mm.h>
#include <asm/bootparam.h>
#include <asm/page.h>
#include <asm/sections.h>
/*
* mem_reserve(start, end, must_exist)
*
* Reserve some memory from the memory pool.
*
* Parameters:
* start Start of region,
* end End of region,
* must_exist Must exist in memory pool.
*
* Returns:
* 0 (memory area couldn't be mapped)
* -1 (success)
*/
int __init mem_reserve(unsigned long start, unsigned long end, int must_exist)
{
int i;
if (start == end)
return 0;
start = start & PAGE_MASK;
end = PAGE_ALIGN(end);
for (i = 0; i < sysmem.nr_banks; i++)
if (start < sysmem.bank[i].end
&& end >= sysmem.bank[i].start)
break;
if (i == sysmem.nr_banks) {
if (must_exist)
printk (KERN_WARNING "mem_reserve: [0x%0lx, 0x%0lx) "
"not in any region!\n", start, end);
return 0;
}
if (start > sysmem.bank[i].start) {
if (end < sysmem.bank[i].end) {
/* split entry */
if (sysmem.nr_banks >= SYSMEM_BANKS_MAX)
panic("meminfo overflow\n");
sysmem.bank[sysmem.nr_banks].start = end;
sysmem.bank[sysmem.nr_banks].end = sysmem.bank[i].end;
sysmem.nr_banks++;
}
sysmem.bank[i].end = start;
} else if (end < sysmem.bank[i].end) {
sysmem.bank[i].start = end;
} else {
/* remove entry */
sysmem.nr_banks--;
sysmem.bank[i].start = sysmem.bank[sysmem.nr_banks].start;
sysmem.bank[i].end = sysmem.bank[sysmem.nr_banks].end;
}
return -1;
}
/*
* Initialize the bootmem system and give it all the memory we have available.
*/
void __init bootmem_init(void)
{
unsigned long pfn;
unsigned long bootmap_start, bootmap_size;
int i;
max_low_pfn = max_pfn = 0;
min_low_pfn = ~0;
for (i=0; i < sysmem.nr_banks; i++) {
pfn = PAGE_ALIGN(sysmem.bank[i].start) >> PAGE_SHIFT;
if (pfn < min_low_pfn)
min_low_pfn = pfn;
pfn = PAGE_ALIGN(sysmem.bank[i].end - 1) >> PAGE_SHIFT;
if (pfn > max_pfn)
max_pfn = pfn;
}
if (min_low_pfn > max_pfn)
panic("No memory found!\n");
max_low_pfn = max_pfn < MAX_MEM_PFN >> PAGE_SHIFT ?
max_pfn : MAX_MEM_PFN >> PAGE_SHIFT;
/* Find an area to use for the bootmem bitmap. */
bootmap_size = bootmem_bootmap_pages(max_low_pfn - min_low_pfn);
bootmap_size <<= PAGE_SHIFT;
bootmap_start = ~0;
for (i=0; i<sysmem.nr_banks; i++)
if (sysmem.bank[i].end - sysmem.bank[i].start >= bootmap_size) {
bootmap_start = sysmem.bank[i].start;
break;
}
if (bootmap_start == ~0UL)
panic("Cannot find %ld bytes for bootmap\n", bootmap_size);
/* Reserve the bootmem bitmap area */
mem_reserve(bootmap_start, bootmap_start + bootmap_size, 1);
bootmap_size = init_bootmem_node(NODE_DATA(0),
bootmap_start >> PAGE_SHIFT,
min_low_pfn,
max_low_pfn);
/* Add all remaining memory pieces into the bootmem map */
for (i=0; i<sysmem.nr_banks; i++)
free_bootmem(sysmem.bank[i].start,
sysmem.bank[i].end - sysmem.bank[i].start);
}
void __init zones_init(void)
{
unsigned long zones_size[MAX_NR_ZONES];
int i;
/* All pages are DMA-able, so we put them all in the DMA zone. */
zones_size[ZONE_DMA] = max_low_pfn - ARCH_PFN_OFFSET;
for (i = 1; i < MAX_NR_ZONES; i++)
zones_size[i] = 0;
#ifdef CONFIG_HIGHMEM
zones_size[ZONE_HIGHMEM] = max_pfn - max_low_pfn;
#endif
free_area_init_node(0, zones_size, ARCH_PFN_OFFSET, NULL);
}
/*
* Initialize memory pages.
*/
void __init mem_init(void)
{
unsigned long codesize, reservedpages, datasize, initsize;
unsigned long highmemsize, tmp, ram;
max_mapnr = num_physpages = max_low_pfn - ARCH_PFN_OFFSET;
high_memory = (void *) __va(max_low_pfn << PAGE_SHIFT);
highmemsize = 0;
#ifdef CONFIG_HIGHMEM
#error HIGHGMEM not implemented in init.c
#endif
totalram_pages += free_all_bootmem();
reservedpages = ram = 0;
for (tmp = 0; tmp < max_mapnr; tmp++) {
ram++;
if (PageReserved(mem_map+tmp))
reservedpages++;
}
codesize = (unsigned long) _etext - (unsigned long) _stext;
datasize = (unsigned long) _edata - (unsigned long) _sdata;
initsize = (unsigned long) __init_end - (unsigned long) __init_begin;
printk("Memory: %luk/%luk available (%ldk kernel code, %ldk reserved, "
"%ldk data, %ldk init %ldk highmem)\n",
nr_free_pages() << (PAGE_SHIFT-10),
ram << (PAGE_SHIFT-10),
codesize >> 10,
reservedpages << (PAGE_SHIFT-10),
datasize >> 10,
initsize >> 10,
highmemsize >> 10);
}
#ifdef CONFIG_BLK_DEV_INITRD
extern int initrd_is_mapped;
void free_initrd_mem(unsigned long start, unsigned long end)
{
if (initrd_is_mapped)
free_reserved_area(start, end, 0, "initrd");
}
#endif
void free_initmem(void)
{
free_initmem_default(0);
}
| gpl-2.0 |
visi0nary/android_kernel_elephone_p8000 | drivers/pwm/pwm-atmel-tcb.c | 2076 | 11737 | /*
* Copyright (C) Overkiz SAS 2012
*
* Author: Boris BREZILLON <b.brezillon@overkiz.com>
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/atmel_tc.h>
#include <linux/pwm.h>
#include <linux/of_device.h>
#include <linux/slab.h>
#define NPWM 6
#define ATMEL_TC_ACMR_MASK (ATMEL_TC_ACPA | ATMEL_TC_ACPC | \
ATMEL_TC_AEEVT | ATMEL_TC_ASWTRG)
#define ATMEL_TC_BCMR_MASK (ATMEL_TC_BCPB | ATMEL_TC_BCPC | \
ATMEL_TC_BEEVT | ATMEL_TC_BSWTRG)
struct atmel_tcb_pwm_device {
enum pwm_polarity polarity; /* PWM polarity */
unsigned div; /* PWM clock divider */
unsigned duty; /* PWM duty expressed in clk cycles */
unsigned period; /* PWM period expressed in clk cycles */
};
struct atmel_tcb_pwm_chip {
struct pwm_chip chip;
spinlock_t lock;
struct atmel_tc *tc;
struct atmel_tcb_pwm_device *pwms[NPWM];
};
static inline struct atmel_tcb_pwm_chip *to_tcb_chip(struct pwm_chip *chip)
{
return container_of(chip, struct atmel_tcb_pwm_chip, chip);
}
static int atmel_tcb_pwm_set_polarity(struct pwm_chip *chip,
struct pwm_device *pwm,
enum pwm_polarity polarity)
{
struct atmel_tcb_pwm_device *tcbpwm = pwm_get_chip_data(pwm);
tcbpwm->polarity = polarity;
return 0;
}
static int atmel_tcb_pwm_request(struct pwm_chip *chip,
struct pwm_device *pwm)
{
struct atmel_tcb_pwm_chip *tcbpwmc = to_tcb_chip(chip);
struct atmel_tcb_pwm_device *tcbpwm;
struct atmel_tc *tc = tcbpwmc->tc;
void __iomem *regs = tc->regs;
unsigned group = pwm->hwpwm / 2;
unsigned index = pwm->hwpwm % 2;
unsigned cmr;
int ret;
tcbpwm = devm_kzalloc(chip->dev, sizeof(*tcbpwm), GFP_KERNEL);
if (!tcbpwm)
return -ENOMEM;
ret = clk_enable(tc->clk[group]);
if (ret) {
devm_kfree(chip->dev, tcbpwm);
return ret;
}
pwm_set_chip_data(pwm, tcbpwm);
tcbpwm->polarity = PWM_POLARITY_NORMAL;
tcbpwm->duty = 0;
tcbpwm->period = 0;
tcbpwm->div = 0;
spin_lock(&tcbpwmc->lock);
cmr = __raw_readl(regs + ATMEL_TC_REG(group, CMR));
/*
* Get init config from Timer Counter registers if
* Timer Counter is already configured as a PWM generator.
*/
if (cmr & ATMEL_TC_WAVE) {
if (index == 0)
tcbpwm->duty =
__raw_readl(regs + ATMEL_TC_REG(group, RA));
else
tcbpwm->duty =
__raw_readl(regs + ATMEL_TC_REG(group, RB));
tcbpwm->div = cmr & ATMEL_TC_TCCLKS;
tcbpwm->period = __raw_readl(regs + ATMEL_TC_REG(group, RC));
cmr &= (ATMEL_TC_TCCLKS | ATMEL_TC_ACMR_MASK |
ATMEL_TC_BCMR_MASK);
} else
cmr = 0;
cmr |= ATMEL_TC_WAVE | ATMEL_TC_WAVESEL_UP_AUTO | ATMEL_TC_EEVT_XC0;
__raw_writel(cmr, regs + ATMEL_TC_REG(group, CMR));
spin_unlock(&tcbpwmc->lock);
tcbpwmc->pwms[pwm->hwpwm] = tcbpwm;
return 0;
}
static void atmel_tcb_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct atmel_tcb_pwm_chip *tcbpwmc = to_tcb_chip(chip);
struct atmel_tcb_pwm_device *tcbpwm = pwm_get_chip_data(pwm);
struct atmel_tc *tc = tcbpwmc->tc;
clk_disable(tc->clk[pwm->hwpwm / 2]);
tcbpwmc->pwms[pwm->hwpwm] = NULL;
devm_kfree(chip->dev, tcbpwm);
}
static void atmel_tcb_pwm_disable(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct atmel_tcb_pwm_chip *tcbpwmc = to_tcb_chip(chip);
struct atmel_tcb_pwm_device *tcbpwm = pwm_get_chip_data(pwm);
struct atmel_tc *tc = tcbpwmc->tc;
void __iomem *regs = tc->regs;
unsigned group = pwm->hwpwm / 2;
unsigned index = pwm->hwpwm % 2;
unsigned cmr;
enum pwm_polarity polarity = tcbpwm->polarity;
/*
* If duty is 0 the timer will be stopped and we have to
* configure the output correctly on software trigger:
* - set output to high if PWM_POLARITY_INVERSED
* - set output to low if PWM_POLARITY_NORMAL
*
* This is why we're reverting polarity in this case.
*/
if (tcbpwm->duty == 0)
polarity = !polarity;
spin_lock(&tcbpwmc->lock);
cmr = __raw_readl(regs + ATMEL_TC_REG(group, CMR));
/* flush old setting and set the new one */
if (index == 0) {
cmr &= ~ATMEL_TC_ACMR_MASK;
if (polarity == PWM_POLARITY_INVERSED)
cmr |= ATMEL_TC_ASWTRG_CLEAR;
else
cmr |= ATMEL_TC_ASWTRG_SET;
} else {
cmr &= ~ATMEL_TC_BCMR_MASK;
if (polarity == PWM_POLARITY_INVERSED)
cmr |= ATMEL_TC_BSWTRG_CLEAR;
else
cmr |= ATMEL_TC_BSWTRG_SET;
}
__raw_writel(cmr, regs + ATMEL_TC_REG(group, CMR));
/*
* Use software trigger to apply the new setting.
* If both PWM devices in this group are disabled we stop the clock.
*/
if (!(cmr & (ATMEL_TC_ACPC | ATMEL_TC_BCPC)))
__raw_writel(ATMEL_TC_SWTRG | ATMEL_TC_CLKDIS,
regs + ATMEL_TC_REG(group, CCR));
else
__raw_writel(ATMEL_TC_SWTRG, regs +
ATMEL_TC_REG(group, CCR));
spin_unlock(&tcbpwmc->lock);
}
static int atmel_tcb_pwm_enable(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct atmel_tcb_pwm_chip *tcbpwmc = to_tcb_chip(chip);
struct atmel_tcb_pwm_device *tcbpwm = pwm_get_chip_data(pwm);
struct atmel_tc *tc = tcbpwmc->tc;
void __iomem *regs = tc->regs;
unsigned group = pwm->hwpwm / 2;
unsigned index = pwm->hwpwm % 2;
u32 cmr;
enum pwm_polarity polarity = tcbpwm->polarity;
/*
* If duty is 0 the timer will be stopped and we have to
* configure the output correctly on software trigger:
* - set output to high if PWM_POLARITY_INVERSED
* - set output to low if PWM_POLARITY_NORMAL
*
* This is why we're reverting polarity in this case.
*/
if (tcbpwm->duty == 0)
polarity = !polarity;
spin_lock(&tcbpwmc->lock);
cmr = __raw_readl(regs + ATMEL_TC_REG(group, CMR));
/* flush old setting and set the new one */
cmr &= ~ATMEL_TC_TCCLKS;
if (index == 0) {
cmr &= ~ATMEL_TC_ACMR_MASK;
/* Set CMR flags according to given polarity */
if (polarity == PWM_POLARITY_INVERSED)
cmr |= ATMEL_TC_ASWTRG_CLEAR;
else
cmr |= ATMEL_TC_ASWTRG_SET;
} else {
cmr &= ~ATMEL_TC_BCMR_MASK;
if (polarity == PWM_POLARITY_INVERSED)
cmr |= ATMEL_TC_BSWTRG_CLEAR;
else
cmr |= ATMEL_TC_BSWTRG_SET;
}
/*
* If duty is 0 or equal to period there's no need to register
* a specific action on RA/RB and RC compare.
* The output will be configured on software trigger and keep
* this config till next config call.
*/
if (tcbpwm->duty != tcbpwm->period && tcbpwm->duty > 0) {
if (index == 0) {
if (polarity == PWM_POLARITY_INVERSED)
cmr |= ATMEL_TC_ACPA_SET | ATMEL_TC_ACPC_CLEAR;
else
cmr |= ATMEL_TC_ACPA_CLEAR | ATMEL_TC_ACPC_SET;
} else {
if (polarity == PWM_POLARITY_INVERSED)
cmr |= ATMEL_TC_BCPB_SET | ATMEL_TC_BCPC_CLEAR;
else
cmr |= ATMEL_TC_BCPB_CLEAR | ATMEL_TC_BCPC_SET;
}
}
__raw_writel(cmr, regs + ATMEL_TC_REG(group, CMR));
if (index == 0)
__raw_writel(tcbpwm->duty, regs + ATMEL_TC_REG(group, RA));
else
__raw_writel(tcbpwm->duty, regs + ATMEL_TC_REG(group, RB));
__raw_writel(tcbpwm->period, regs + ATMEL_TC_REG(group, RC));
/* Use software trigger to apply the new setting */
__raw_writel(ATMEL_TC_CLKEN | ATMEL_TC_SWTRG,
regs + ATMEL_TC_REG(group, CCR));
spin_unlock(&tcbpwmc->lock);
return 0;
}
static int atmel_tcb_pwm_config(struct pwm_chip *chip, struct pwm_device *pwm,
int duty_ns, int period_ns)
{
struct atmel_tcb_pwm_chip *tcbpwmc = to_tcb_chip(chip);
struct atmel_tcb_pwm_device *tcbpwm = pwm_get_chip_data(pwm);
unsigned group = pwm->hwpwm / 2;
unsigned index = pwm->hwpwm % 2;
struct atmel_tcb_pwm_device *atcbpwm = NULL;
struct atmel_tc *tc = tcbpwmc->tc;
int i;
int slowclk = 0;
unsigned period;
unsigned duty;
unsigned rate = clk_get_rate(tc->clk[group]);
unsigned long long min;
unsigned long long max;
/*
* Find best clk divisor:
* the smallest divisor which can fulfill the period_ns requirements.
*/
for (i = 0; i < 5; ++i) {
if (atmel_tc_divisors[i] == 0) {
slowclk = i;
continue;
}
min = div_u64((u64)NSEC_PER_SEC * atmel_tc_divisors[i], rate);
max = min << tc->tcb_config->counter_width;
if (max >= period_ns)
break;
}
/*
* If none of the divisor are small enough to represent period_ns
* take slow clock (32KHz).
*/
if (i == 5) {
i = slowclk;
rate = 32768;
min = div_u64(NSEC_PER_SEC, rate);
max = min << 16;
/* If period is too big return ERANGE error */
if (max < period_ns)
return -ERANGE;
}
duty = div_u64(duty_ns, min);
period = div_u64(period_ns, min);
if (index == 0)
atcbpwm = tcbpwmc->pwms[pwm->hwpwm + 1];
else
atcbpwm = tcbpwmc->pwms[pwm->hwpwm - 1];
/*
* PWM devices provided by TCB driver are grouped by 2:
* - group 0: PWM 0 & 1
* - group 1: PWM 2 & 3
* - group 2: PWM 4 & 5
*
* PWM devices in a given group must be configured with the
* same period_ns.
*
* We're checking the period value of the second PWM device
* in this group before applying the new config.
*/
if ((atcbpwm && atcbpwm->duty > 0 &&
atcbpwm->duty != atcbpwm->period) &&
(atcbpwm->div != i || atcbpwm->period != period)) {
dev_err(chip->dev,
"failed to configure period_ns: PWM group already configured with a different value\n");
return -EINVAL;
}
tcbpwm->period = period;
tcbpwm->div = i;
tcbpwm->duty = duty;
/* If the PWM is enabled, call enable to apply the new conf */
if (test_bit(PWMF_ENABLED, &pwm->flags))
atmel_tcb_pwm_enable(chip, pwm);
return 0;
}
static const struct pwm_ops atmel_tcb_pwm_ops = {
.request = atmel_tcb_pwm_request,
.free = atmel_tcb_pwm_free,
.config = atmel_tcb_pwm_config,
.set_polarity = atmel_tcb_pwm_set_polarity,
.enable = atmel_tcb_pwm_enable,
.disable = atmel_tcb_pwm_disable,
.owner = THIS_MODULE,
};
static int atmel_tcb_pwm_probe(struct platform_device *pdev)
{
struct atmel_tcb_pwm_chip *tcbpwm;
struct device_node *np = pdev->dev.of_node;
struct atmel_tc *tc;
int err;
int tcblock;
err = of_property_read_u32(np, "tc-block", &tcblock);
if (err < 0) {
dev_err(&pdev->dev,
"failed to get Timer Counter Block number from device tree (error: %d)\n",
err);
return err;
}
tc = atmel_tc_alloc(tcblock, "tcb-pwm");
if (tc == NULL) {
dev_err(&pdev->dev, "failed to allocate Timer Counter Block\n");
return -ENOMEM;
}
tcbpwm = devm_kzalloc(&pdev->dev, sizeof(*tcbpwm), GFP_KERNEL);
if (tcbpwm == NULL) {
atmel_tc_free(tc);
dev_err(&pdev->dev, "failed to allocate memory\n");
return -ENOMEM;
}
tcbpwm->chip.dev = &pdev->dev;
tcbpwm->chip.ops = &atmel_tcb_pwm_ops;
tcbpwm->chip.of_xlate = of_pwm_xlate_with_flags;
tcbpwm->chip.of_pwm_n_cells = 3;
tcbpwm->chip.base = -1;
tcbpwm->chip.npwm = NPWM;
tcbpwm->tc = tc;
spin_lock_init(&tcbpwm->lock);
err = pwmchip_add(&tcbpwm->chip);
if (err < 0) {
atmel_tc_free(tc);
return err;
}
platform_set_drvdata(pdev, tcbpwm);
return 0;
}
static int atmel_tcb_pwm_remove(struct platform_device *pdev)
{
struct atmel_tcb_pwm_chip *tcbpwm = platform_get_drvdata(pdev);
int err;
err = pwmchip_remove(&tcbpwm->chip);
if (err < 0)
return err;
atmel_tc_free(tcbpwm->tc);
return 0;
}
static const struct of_device_id atmel_tcb_pwm_dt_ids[] = {
{ .compatible = "atmel,tcb-pwm", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, atmel_tcb_pwm_dt_ids);
static struct platform_driver atmel_tcb_pwm_driver = {
.driver = {
.name = "atmel-tcb-pwm",
.of_match_table = atmel_tcb_pwm_dt_ids,
},
.probe = atmel_tcb_pwm_probe,
.remove = atmel_tcb_pwm_remove,
};
module_platform_driver(atmel_tcb_pwm_driver);
MODULE_AUTHOR("Boris BREZILLON <b.brezillon@overkiz.com>");
MODULE_DESCRIPTION("Atmel Timer Counter Pulse Width Modulation Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Stane1983/odroidc-linux | drivers/irqchip/irq-sun4i.c | 2076 | 4191 | /*
* Allwinner A1X SoCs IRQ chip driver.
*
* Copyright (C) 2012 Maxime Ripard
*
* Maxime Ripard <maxime.ripard@free-electrons.com>
*
* Based on code from
* Allwinner Technology Co., Ltd. <www.allwinnertech.com>
* Benn Huang <benn@allwinnertech.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <asm/exception.h>
#include <asm/mach/irq.h>
#include "irqchip.h"
#define SUN4I_IRQ_VECTOR_REG 0x00
#define SUN4I_IRQ_PROTECTION_REG 0x08
#define SUN4I_IRQ_NMI_CTRL_REG 0x0c
#define SUN4I_IRQ_PENDING_REG(x) (0x10 + 0x4 * x)
#define SUN4I_IRQ_FIQ_PENDING_REG(x) (0x20 + 0x4 * x)
#define SUN4I_IRQ_ENABLE_REG(x) (0x40 + 0x4 * x)
#define SUN4I_IRQ_MASK_REG(x) (0x50 + 0x4 * x)
static void __iomem *sun4i_irq_base;
static struct irq_domain *sun4i_irq_domain;
static asmlinkage void __exception_irq_entry sun4i_handle_irq(struct pt_regs *regs);
void sun4i_irq_ack(struct irq_data *irqd)
{
unsigned int irq = irqd_to_hwirq(irqd);
unsigned int irq_off = irq % 32;
int reg = irq / 32;
u32 val;
val = readl(sun4i_irq_base + SUN4I_IRQ_PENDING_REG(reg));
writel(val | (1 << irq_off),
sun4i_irq_base + SUN4I_IRQ_PENDING_REG(reg));
}
static void sun4i_irq_mask(struct irq_data *irqd)
{
unsigned int irq = irqd_to_hwirq(irqd);
unsigned int irq_off = irq % 32;
int reg = irq / 32;
u32 val;
val = readl(sun4i_irq_base + SUN4I_IRQ_ENABLE_REG(reg));
writel(val & ~(1 << irq_off),
sun4i_irq_base + SUN4I_IRQ_ENABLE_REG(reg));
}
static void sun4i_irq_unmask(struct irq_data *irqd)
{
unsigned int irq = irqd_to_hwirq(irqd);
unsigned int irq_off = irq % 32;
int reg = irq / 32;
u32 val;
val = readl(sun4i_irq_base + SUN4I_IRQ_ENABLE_REG(reg));
writel(val | (1 << irq_off),
sun4i_irq_base + SUN4I_IRQ_ENABLE_REG(reg));
}
static struct irq_chip sun4i_irq_chip = {
.name = "sun4i_irq",
.irq_ack = sun4i_irq_ack,
.irq_mask = sun4i_irq_mask,
.irq_unmask = sun4i_irq_unmask,
};
static int sun4i_irq_map(struct irq_domain *d, unsigned int virq,
irq_hw_number_t hw)
{
irq_set_chip_and_handler(virq, &sun4i_irq_chip,
handle_level_irq);
set_irq_flags(virq, IRQF_VALID | IRQF_PROBE);
return 0;
}
static struct irq_domain_ops sun4i_irq_ops = {
.map = sun4i_irq_map,
.xlate = irq_domain_xlate_onecell,
};
static int __init sun4i_of_init(struct device_node *node,
struct device_node *parent)
{
sun4i_irq_base = of_iomap(node, 0);
if (!sun4i_irq_base)
panic("%s: unable to map IC registers\n",
node->full_name);
/* Disable all interrupts */
writel(0, sun4i_irq_base + SUN4I_IRQ_ENABLE_REG(0));
writel(0, sun4i_irq_base + SUN4I_IRQ_ENABLE_REG(1));
writel(0, sun4i_irq_base + SUN4I_IRQ_ENABLE_REG(2));
/* Mask all the interrupts */
writel(0, sun4i_irq_base + SUN4I_IRQ_MASK_REG(0));
writel(0, sun4i_irq_base + SUN4I_IRQ_MASK_REG(1));
writel(0, sun4i_irq_base + SUN4I_IRQ_MASK_REG(2));
/* Clear all the pending interrupts */
writel(0xffffffff, sun4i_irq_base + SUN4I_IRQ_PENDING_REG(0));
writel(0xffffffff, sun4i_irq_base + SUN4I_IRQ_PENDING_REG(1));
writel(0xffffffff, sun4i_irq_base + SUN4I_IRQ_PENDING_REG(2));
/* Enable protection mode */
writel(0x01, sun4i_irq_base + SUN4I_IRQ_PROTECTION_REG);
/* Configure the external interrupt source type */
writel(0x00, sun4i_irq_base + SUN4I_IRQ_NMI_CTRL_REG);
sun4i_irq_domain = irq_domain_add_linear(node, 3 * 32,
&sun4i_irq_ops, NULL);
if (!sun4i_irq_domain)
panic("%s: unable to create IRQ domain\n", node->full_name);
set_handle_irq(sun4i_handle_irq);
return 0;
}
IRQCHIP_DECLARE(allwinner_sun4i_ic, "allwinner,sun4i-ic", sun4i_of_init);
static asmlinkage void __exception_irq_entry sun4i_handle_irq(struct pt_regs *regs)
{
u32 irq, hwirq;
hwirq = readl(sun4i_irq_base + SUN4I_IRQ_VECTOR_REG) >> 2;
while (hwirq != 0) {
irq = irq_find_mapping(sun4i_irq_domain, hwirq);
handle_IRQ(irq, regs);
hwirq = readl(sun4i_irq_base + SUN4I_IRQ_VECTOR_REG) >> 2;
}
}
| gpl-2.0 |
javelinanddart/android_kernel_3.10_ville | drivers/net/ethernet/intel/igb/e1000_82575.c | 2076 | 72725 | /*******************************************************************************
Intel(R) Gigabit Ethernet Linux driver
Copyright(c) 2007-2013 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
/* e1000_82575
* e1000_82576
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/if_ether.h>
#include <linux/i2c.h>
#include "e1000_mac.h"
#include "e1000_82575.h"
#include "e1000_i210.h"
static s32 igb_get_invariants_82575(struct e1000_hw *);
static s32 igb_acquire_phy_82575(struct e1000_hw *);
static void igb_release_phy_82575(struct e1000_hw *);
static s32 igb_acquire_nvm_82575(struct e1000_hw *);
static void igb_release_nvm_82575(struct e1000_hw *);
static s32 igb_check_for_link_82575(struct e1000_hw *);
static s32 igb_get_cfg_done_82575(struct e1000_hw *);
static s32 igb_init_hw_82575(struct e1000_hw *);
static s32 igb_phy_hw_reset_sgmii_82575(struct e1000_hw *);
static s32 igb_read_phy_reg_sgmii_82575(struct e1000_hw *, u32, u16 *);
static s32 igb_read_phy_reg_82580(struct e1000_hw *, u32, u16 *);
static s32 igb_write_phy_reg_82580(struct e1000_hw *, u32, u16);
static s32 igb_reset_hw_82575(struct e1000_hw *);
static s32 igb_reset_hw_82580(struct e1000_hw *);
static s32 igb_set_d0_lplu_state_82575(struct e1000_hw *, bool);
static s32 igb_set_d0_lplu_state_82580(struct e1000_hw *, bool);
static s32 igb_set_d3_lplu_state_82580(struct e1000_hw *, bool);
static s32 igb_setup_copper_link_82575(struct e1000_hw *);
static s32 igb_setup_serdes_link_82575(struct e1000_hw *);
static s32 igb_write_phy_reg_sgmii_82575(struct e1000_hw *, u32, u16);
static void igb_clear_hw_cntrs_82575(struct e1000_hw *);
static s32 igb_acquire_swfw_sync_82575(struct e1000_hw *, u16);
static s32 igb_get_pcs_speed_and_duplex_82575(struct e1000_hw *, u16 *,
u16 *);
static s32 igb_get_phy_id_82575(struct e1000_hw *);
static void igb_release_swfw_sync_82575(struct e1000_hw *, u16);
static bool igb_sgmii_active_82575(struct e1000_hw *);
static s32 igb_reset_init_script_82575(struct e1000_hw *);
static s32 igb_read_mac_addr_82575(struct e1000_hw *);
static s32 igb_set_pcie_completion_timeout(struct e1000_hw *hw);
static s32 igb_reset_mdicnfg_82580(struct e1000_hw *hw);
static s32 igb_validate_nvm_checksum_82580(struct e1000_hw *hw);
static s32 igb_update_nvm_checksum_82580(struct e1000_hw *hw);
static s32 igb_validate_nvm_checksum_i350(struct e1000_hw *hw);
static s32 igb_update_nvm_checksum_i350(struct e1000_hw *hw);
static const u16 e1000_82580_rxpbs_table[] =
{ 36, 72, 144, 1, 2, 4, 8, 16,
35, 70, 140 };
#define E1000_82580_RXPBS_TABLE_SIZE \
(sizeof(e1000_82580_rxpbs_table)/sizeof(u16))
/**
* igb_sgmii_uses_mdio_82575 - Determine if I2C pins are for external MDIO
* @hw: pointer to the HW structure
*
* Called to determine if the I2C pins are being used for I2C or as an
* external MDIO interface since the two options are mutually exclusive.
**/
static bool igb_sgmii_uses_mdio_82575(struct e1000_hw *hw)
{
u32 reg = 0;
bool ext_mdio = false;
switch (hw->mac.type) {
case e1000_82575:
case e1000_82576:
reg = rd32(E1000_MDIC);
ext_mdio = !!(reg & E1000_MDIC_DEST);
break;
case e1000_82580:
case e1000_i350:
case e1000_i354:
case e1000_i210:
case e1000_i211:
reg = rd32(E1000_MDICNFG);
ext_mdio = !!(reg & E1000_MDICNFG_EXT_MDIO);
break;
default:
break;
}
return ext_mdio;
}
/**
* igb_init_phy_params_82575 - Init PHY func ptrs.
* @hw: pointer to the HW structure
**/
static s32 igb_init_phy_params_82575(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val = 0;
u32 ctrl_ext;
if (hw->phy.media_type != e1000_media_type_copper) {
phy->type = e1000_phy_none;
goto out;
}
phy->autoneg_mask = AUTONEG_ADVERTISE_SPEED_DEFAULT;
phy->reset_delay_us = 100;
ctrl_ext = rd32(E1000_CTRL_EXT);
if (igb_sgmii_active_82575(hw)) {
phy->ops.reset = igb_phy_hw_reset_sgmii_82575;
ctrl_ext |= E1000_CTRL_I2C_ENA;
} else {
phy->ops.reset = igb_phy_hw_reset;
ctrl_ext &= ~E1000_CTRL_I2C_ENA;
}
wr32(E1000_CTRL_EXT, ctrl_ext);
igb_reset_mdicnfg_82580(hw);
if (igb_sgmii_active_82575(hw) && !igb_sgmii_uses_mdio_82575(hw)) {
phy->ops.read_reg = igb_read_phy_reg_sgmii_82575;
phy->ops.write_reg = igb_write_phy_reg_sgmii_82575;
} else {
switch (hw->mac.type) {
case e1000_82580:
case e1000_i350:
case e1000_i354:
phy->ops.read_reg = igb_read_phy_reg_82580;
phy->ops.write_reg = igb_write_phy_reg_82580;
break;
case e1000_i210:
case e1000_i211:
phy->ops.read_reg = igb_read_phy_reg_gs40g;
phy->ops.write_reg = igb_write_phy_reg_gs40g;
break;
default:
phy->ops.read_reg = igb_read_phy_reg_igp;
phy->ops.write_reg = igb_write_phy_reg_igp;
}
}
/* set lan id */
hw->bus.func = (rd32(E1000_STATUS) & E1000_STATUS_FUNC_MASK) >>
E1000_STATUS_FUNC_SHIFT;
/* Set phy->phy_addr and phy->id. */
ret_val = igb_get_phy_id_82575(hw);
if (ret_val)
return ret_val;
/* Verify phy id and set remaining function pointers */
switch (phy->id) {
case M88E1545_E_PHY_ID:
case I347AT4_E_PHY_ID:
case M88E1112_E_PHY_ID:
case M88E1111_I_PHY_ID:
phy->type = e1000_phy_m88;
phy->ops.check_polarity = igb_check_polarity_m88;
phy->ops.get_phy_info = igb_get_phy_info_m88;
if (phy->id != M88E1111_I_PHY_ID)
phy->ops.get_cable_length =
igb_get_cable_length_m88_gen2;
else
phy->ops.get_cable_length = igb_get_cable_length_m88;
phy->ops.force_speed_duplex = igb_phy_force_speed_duplex_m88;
break;
case IGP03E1000_E_PHY_ID:
phy->type = e1000_phy_igp_3;
phy->ops.get_phy_info = igb_get_phy_info_igp;
phy->ops.get_cable_length = igb_get_cable_length_igp_2;
phy->ops.force_speed_duplex = igb_phy_force_speed_duplex_igp;
phy->ops.set_d0_lplu_state = igb_set_d0_lplu_state_82575;
phy->ops.set_d3_lplu_state = igb_set_d3_lplu_state;
break;
case I82580_I_PHY_ID:
case I350_I_PHY_ID:
phy->type = e1000_phy_82580;
phy->ops.force_speed_duplex =
igb_phy_force_speed_duplex_82580;
phy->ops.get_cable_length = igb_get_cable_length_82580;
phy->ops.get_phy_info = igb_get_phy_info_82580;
phy->ops.set_d0_lplu_state = igb_set_d0_lplu_state_82580;
phy->ops.set_d3_lplu_state = igb_set_d3_lplu_state_82580;
break;
case I210_I_PHY_ID:
phy->type = e1000_phy_i210;
phy->ops.check_polarity = igb_check_polarity_m88;
phy->ops.get_phy_info = igb_get_phy_info_m88;
phy->ops.get_cable_length = igb_get_cable_length_m88_gen2;
phy->ops.set_d0_lplu_state = igb_set_d0_lplu_state_82580;
phy->ops.set_d3_lplu_state = igb_set_d3_lplu_state_82580;
phy->ops.force_speed_duplex = igb_phy_force_speed_duplex_m88;
break;
default:
ret_val = -E1000_ERR_PHY;
goto out;
}
out:
return ret_val;
}
/**
* igb_init_nvm_params_82575 - Init NVM func ptrs.
* @hw: pointer to the HW structure
**/
static s32 igb_init_nvm_params_82575(struct e1000_hw *hw)
{
struct e1000_nvm_info *nvm = &hw->nvm;
u32 eecd = rd32(E1000_EECD);
u16 size;
size = (u16)((eecd & E1000_EECD_SIZE_EX_MASK) >>
E1000_EECD_SIZE_EX_SHIFT);
/* Added to a constant, "size" becomes the left-shift value
* for setting word_size.
*/
size += NVM_WORD_SIZE_BASE_SHIFT;
/* Just in case size is out of range, cap it to the largest
* EEPROM size supported
*/
if (size > 15)
size = 15;
nvm->word_size = 1 << size;
if (hw->mac.type < e1000_i210) {
nvm->opcode_bits = 8;
nvm->delay_usec = 1;
switch (nvm->override) {
case e1000_nvm_override_spi_large:
nvm->page_size = 32;
nvm->address_bits = 16;
break;
case e1000_nvm_override_spi_small:
nvm->page_size = 8;
nvm->address_bits = 8;
break;
default:
nvm->page_size = eecd & E1000_EECD_ADDR_BITS ? 32 : 8;
nvm->address_bits = eecd & E1000_EECD_ADDR_BITS ?
16 : 8;
break;
}
if (nvm->word_size == (1 << 15))
nvm->page_size = 128;
nvm->type = e1000_nvm_eeprom_spi;
} else {
nvm->type = e1000_nvm_flash_hw;
}
/* NVM Function Pointers */
switch (hw->mac.type) {
case e1000_82580:
nvm->ops.validate = igb_validate_nvm_checksum_82580;
nvm->ops.update = igb_update_nvm_checksum_82580;
nvm->ops.acquire = igb_acquire_nvm_82575;
nvm->ops.release = igb_release_nvm_82575;
if (nvm->word_size < (1 << 15))
nvm->ops.read = igb_read_nvm_eerd;
else
nvm->ops.read = igb_read_nvm_spi;
nvm->ops.write = igb_write_nvm_spi;
break;
case e1000_i354:
case e1000_i350:
nvm->ops.validate = igb_validate_nvm_checksum_i350;
nvm->ops.update = igb_update_nvm_checksum_i350;
nvm->ops.acquire = igb_acquire_nvm_82575;
nvm->ops.release = igb_release_nvm_82575;
if (nvm->word_size < (1 << 15))
nvm->ops.read = igb_read_nvm_eerd;
else
nvm->ops.read = igb_read_nvm_spi;
nvm->ops.write = igb_write_nvm_spi;
break;
case e1000_i210:
nvm->ops.validate = igb_validate_nvm_checksum_i210;
nvm->ops.update = igb_update_nvm_checksum_i210;
nvm->ops.acquire = igb_acquire_nvm_i210;
nvm->ops.release = igb_release_nvm_i210;
nvm->ops.read = igb_read_nvm_srrd_i210;
nvm->ops.write = igb_write_nvm_srwr_i210;
nvm->ops.valid_led_default = igb_valid_led_default_i210;
break;
case e1000_i211:
nvm->ops.acquire = igb_acquire_nvm_i210;
nvm->ops.release = igb_release_nvm_i210;
nvm->ops.read = igb_read_nvm_i211;
nvm->ops.valid_led_default = igb_valid_led_default_i210;
nvm->ops.validate = NULL;
nvm->ops.update = NULL;
nvm->ops.write = NULL;
break;
default:
nvm->ops.validate = igb_validate_nvm_checksum;
nvm->ops.update = igb_update_nvm_checksum;
nvm->ops.acquire = igb_acquire_nvm_82575;
nvm->ops.release = igb_release_nvm_82575;
if (nvm->word_size < (1 << 15))
nvm->ops.read = igb_read_nvm_eerd;
else
nvm->ops.read = igb_read_nvm_spi;
nvm->ops.write = igb_write_nvm_spi;
break;
}
return 0;
}
/**
* igb_init_mac_params_82575 - Init MAC func ptrs.
* @hw: pointer to the HW structure
**/
static s32 igb_init_mac_params_82575(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
struct e1000_dev_spec_82575 *dev_spec = &hw->dev_spec._82575;
/* Set mta register count */
mac->mta_reg_count = 128;
/* Set rar entry count */
switch (mac->type) {
case e1000_82576:
mac->rar_entry_count = E1000_RAR_ENTRIES_82576;
break;
case e1000_82580:
mac->rar_entry_count = E1000_RAR_ENTRIES_82580;
break;
case e1000_i350:
case e1000_i354:
mac->rar_entry_count = E1000_RAR_ENTRIES_I350;
break;
default:
mac->rar_entry_count = E1000_RAR_ENTRIES_82575;
break;
}
/* reset */
if (mac->type >= e1000_82580)
mac->ops.reset_hw = igb_reset_hw_82580;
else
mac->ops.reset_hw = igb_reset_hw_82575;
if (mac->type >= e1000_i210) {
mac->ops.acquire_swfw_sync = igb_acquire_swfw_sync_i210;
mac->ops.release_swfw_sync = igb_release_swfw_sync_i210;
} else {
mac->ops.acquire_swfw_sync = igb_acquire_swfw_sync_82575;
mac->ops.release_swfw_sync = igb_release_swfw_sync_82575;
}
/* Set if part includes ASF firmware */
mac->asf_firmware_present = true;
/* Set if manageability features are enabled. */
mac->arc_subsystem_valid =
(rd32(E1000_FWSM) & E1000_FWSM_MODE_MASK)
? true : false;
/* enable EEE on i350 parts and later parts */
if (mac->type >= e1000_i350)
dev_spec->eee_disable = false;
else
dev_spec->eee_disable = true;
/* Allow a single clear of the SW semaphore on I210 and newer */
if (mac->type >= e1000_i210)
dev_spec->clear_semaphore_once = true;
/* physical interface link setup */
mac->ops.setup_physical_interface =
(hw->phy.media_type == e1000_media_type_copper)
? igb_setup_copper_link_82575
: igb_setup_serdes_link_82575;
return 0;
}
static s32 igb_get_invariants_82575(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
struct e1000_dev_spec_82575 * dev_spec = &hw->dev_spec._82575;
s32 ret_val;
u32 ctrl_ext = 0;
switch (hw->device_id) {
case E1000_DEV_ID_82575EB_COPPER:
case E1000_DEV_ID_82575EB_FIBER_SERDES:
case E1000_DEV_ID_82575GB_QUAD_COPPER:
mac->type = e1000_82575;
break;
case E1000_DEV_ID_82576:
case E1000_DEV_ID_82576_NS:
case E1000_DEV_ID_82576_NS_SERDES:
case E1000_DEV_ID_82576_FIBER:
case E1000_DEV_ID_82576_SERDES:
case E1000_DEV_ID_82576_QUAD_COPPER:
case E1000_DEV_ID_82576_QUAD_COPPER_ET2:
case E1000_DEV_ID_82576_SERDES_QUAD:
mac->type = e1000_82576;
break;
case E1000_DEV_ID_82580_COPPER:
case E1000_DEV_ID_82580_FIBER:
case E1000_DEV_ID_82580_QUAD_FIBER:
case E1000_DEV_ID_82580_SERDES:
case E1000_DEV_ID_82580_SGMII:
case E1000_DEV_ID_82580_COPPER_DUAL:
case E1000_DEV_ID_DH89XXCC_SGMII:
case E1000_DEV_ID_DH89XXCC_SERDES:
case E1000_DEV_ID_DH89XXCC_BACKPLANE:
case E1000_DEV_ID_DH89XXCC_SFP:
mac->type = e1000_82580;
break;
case E1000_DEV_ID_I350_COPPER:
case E1000_DEV_ID_I350_FIBER:
case E1000_DEV_ID_I350_SERDES:
case E1000_DEV_ID_I350_SGMII:
mac->type = e1000_i350;
break;
case E1000_DEV_ID_I210_COPPER:
case E1000_DEV_ID_I210_FIBER:
case E1000_DEV_ID_I210_SERDES:
case E1000_DEV_ID_I210_SGMII:
mac->type = e1000_i210;
break;
case E1000_DEV_ID_I211_COPPER:
mac->type = e1000_i211;
break;
case E1000_DEV_ID_I354_BACKPLANE_1GBPS:
case E1000_DEV_ID_I354_SGMII:
case E1000_DEV_ID_I354_BACKPLANE_2_5GBPS:
mac->type = e1000_i354;
break;
default:
return -E1000_ERR_MAC_INIT;
break;
}
/* Set media type */
/* The 82575 uses bits 22:23 for link mode. The mode can be changed
* based on the EEPROM. We cannot rely upon device ID. There
* is no distinguishable difference between fiber and internal
* SerDes mode on the 82575. There can be an external PHY attached
* on the SGMII interface. For this, we'll set sgmii_active to true.
*/
hw->phy.media_type = e1000_media_type_copper;
dev_spec->sgmii_active = false;
ctrl_ext = rd32(E1000_CTRL_EXT);
switch (ctrl_ext & E1000_CTRL_EXT_LINK_MODE_MASK) {
case E1000_CTRL_EXT_LINK_MODE_SGMII:
dev_spec->sgmii_active = true;
break;
case E1000_CTRL_EXT_LINK_MODE_1000BASE_KX:
case E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES:
hw->phy.media_type = e1000_media_type_internal_serdes;
break;
default:
break;
}
/* mac initialization and operations */
ret_val = igb_init_mac_params_82575(hw);
if (ret_val)
goto out;
/* NVM initialization */
ret_val = igb_init_nvm_params_82575(hw);
if (ret_val)
goto out;
/* if part supports SR-IOV then initialize mailbox parameters */
switch (mac->type) {
case e1000_82576:
case e1000_i350:
igb_init_mbx_params_pf(hw);
break;
default:
break;
}
/* setup PHY parameters */
ret_val = igb_init_phy_params_82575(hw);
out:
return ret_val;
}
/**
* igb_acquire_phy_82575 - Acquire rights to access PHY
* @hw: pointer to the HW structure
*
* Acquire access rights to the correct PHY. This is a
* function pointer entry point called by the api module.
**/
static s32 igb_acquire_phy_82575(struct e1000_hw *hw)
{
u16 mask = E1000_SWFW_PHY0_SM;
if (hw->bus.func == E1000_FUNC_1)
mask = E1000_SWFW_PHY1_SM;
else if (hw->bus.func == E1000_FUNC_2)
mask = E1000_SWFW_PHY2_SM;
else if (hw->bus.func == E1000_FUNC_3)
mask = E1000_SWFW_PHY3_SM;
return hw->mac.ops.acquire_swfw_sync(hw, mask);
}
/**
* igb_release_phy_82575 - Release rights to access PHY
* @hw: pointer to the HW structure
*
* A wrapper to release access rights to the correct PHY. This is a
* function pointer entry point called by the api module.
**/
static void igb_release_phy_82575(struct e1000_hw *hw)
{
u16 mask = E1000_SWFW_PHY0_SM;
if (hw->bus.func == E1000_FUNC_1)
mask = E1000_SWFW_PHY1_SM;
else if (hw->bus.func == E1000_FUNC_2)
mask = E1000_SWFW_PHY2_SM;
else if (hw->bus.func == E1000_FUNC_3)
mask = E1000_SWFW_PHY3_SM;
hw->mac.ops.release_swfw_sync(hw, mask);
}
/**
* igb_read_phy_reg_sgmii_82575 - Read PHY register using sgmii
* @hw: pointer to the HW structure
* @offset: register offset to be read
* @data: pointer to the read data
*
* Reads the PHY register at offset using the serial gigabit media independent
* interface and stores the retrieved information in data.
**/
static s32 igb_read_phy_reg_sgmii_82575(struct e1000_hw *hw, u32 offset,
u16 *data)
{
s32 ret_val = -E1000_ERR_PARAM;
if (offset > E1000_MAX_SGMII_PHY_REG_ADDR) {
hw_dbg("PHY Address %u is out of range\n", offset);
goto out;
}
ret_val = hw->phy.ops.acquire(hw);
if (ret_val)
goto out;
ret_val = igb_read_phy_reg_i2c(hw, offset, data);
hw->phy.ops.release(hw);
out:
return ret_val;
}
/**
* igb_write_phy_reg_sgmii_82575 - Write PHY register using sgmii
* @hw: pointer to the HW structure
* @offset: register offset to write to
* @data: data to write at register offset
*
* Writes the data to PHY register at the offset using the serial gigabit
* media independent interface.
**/
static s32 igb_write_phy_reg_sgmii_82575(struct e1000_hw *hw, u32 offset,
u16 data)
{
s32 ret_val = -E1000_ERR_PARAM;
if (offset > E1000_MAX_SGMII_PHY_REG_ADDR) {
hw_dbg("PHY Address %d is out of range\n", offset);
goto out;
}
ret_val = hw->phy.ops.acquire(hw);
if (ret_val)
goto out;
ret_val = igb_write_phy_reg_i2c(hw, offset, data);
hw->phy.ops.release(hw);
out:
return ret_val;
}
/**
* igb_get_phy_id_82575 - Retrieve PHY addr and id
* @hw: pointer to the HW structure
*
* Retrieves the PHY address and ID for both PHY's which do and do not use
* sgmi interface.
**/
static s32 igb_get_phy_id_82575(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val = 0;
u16 phy_id;
u32 ctrl_ext;
u32 mdic;
/* For SGMII PHYs, we try the list of possible addresses until
* we find one that works. For non-SGMII PHYs
* (e.g. integrated copper PHYs), an address of 1 should
* work. The result of this function should mean phy->phy_addr
* and phy->id are set correctly.
*/
if (!(igb_sgmii_active_82575(hw))) {
phy->addr = 1;
ret_val = igb_get_phy_id(hw);
goto out;
}
if (igb_sgmii_uses_mdio_82575(hw)) {
switch (hw->mac.type) {
case e1000_82575:
case e1000_82576:
mdic = rd32(E1000_MDIC);
mdic &= E1000_MDIC_PHY_MASK;
phy->addr = mdic >> E1000_MDIC_PHY_SHIFT;
break;
case e1000_82580:
case e1000_i350:
case e1000_i354:
case e1000_i210:
case e1000_i211:
mdic = rd32(E1000_MDICNFG);
mdic &= E1000_MDICNFG_PHY_MASK;
phy->addr = mdic >> E1000_MDICNFG_PHY_SHIFT;
break;
default:
ret_val = -E1000_ERR_PHY;
goto out;
break;
}
ret_val = igb_get_phy_id(hw);
goto out;
}
/* Power on sgmii phy if it is disabled */
ctrl_ext = rd32(E1000_CTRL_EXT);
wr32(E1000_CTRL_EXT, ctrl_ext & ~E1000_CTRL_EXT_SDP3_DATA);
wrfl();
msleep(300);
/* The address field in the I2CCMD register is 3 bits and 0 is invalid.
* Therefore, we need to test 1-7
*/
for (phy->addr = 1; phy->addr < 8; phy->addr++) {
ret_val = igb_read_phy_reg_sgmii_82575(hw, PHY_ID1, &phy_id);
if (ret_val == 0) {
hw_dbg("Vendor ID 0x%08X read at address %u\n",
phy_id, phy->addr);
/* At the time of this writing, The M88 part is
* the only supported SGMII PHY product.
*/
if (phy_id == M88_VENDOR)
break;
} else {
hw_dbg("PHY address %u was unreadable\n", phy->addr);
}
}
/* A valid PHY type couldn't be found. */
if (phy->addr == 8) {
phy->addr = 0;
ret_val = -E1000_ERR_PHY;
goto out;
} else {
ret_val = igb_get_phy_id(hw);
}
/* restore previous sfp cage power state */
wr32(E1000_CTRL_EXT, ctrl_ext);
out:
return ret_val;
}
/**
* igb_phy_hw_reset_sgmii_82575 - Performs a PHY reset
* @hw: pointer to the HW structure
*
* Resets the PHY using the serial gigabit media independent interface.
**/
static s32 igb_phy_hw_reset_sgmii_82575(struct e1000_hw *hw)
{
s32 ret_val;
/* This isn't a true "hard" reset, but is the only reset
* available to us at this time.
*/
hw_dbg("Soft resetting SGMII attached PHY...\n");
/* SFP documentation requires the following to configure the SPF module
* to work on SGMII. No further documentation is given.
*/
ret_val = hw->phy.ops.write_reg(hw, 0x1B, 0x8084);
if (ret_val)
goto out;
ret_val = igb_phy_sw_reset(hw);
out:
return ret_val;
}
/**
* igb_set_d0_lplu_state_82575 - Set Low Power Linkup D0 state
* @hw: pointer to the HW structure
* @active: true to enable LPLU, false to disable
*
* Sets the LPLU D0 state according to the active flag. When
* activating LPLU this function also disables smart speed
* and vice versa. LPLU will not be activated unless the
* device autonegotiation advertisement meets standards of
* either 10 or 10/100 or 10/100/1000 at all duplexes.
* This is a function pointer entry point only called by
* PHY setup routines.
**/
static s32 igb_set_d0_lplu_state_82575(struct e1000_hw *hw, bool active)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val;
u16 data;
ret_val = phy->ops.read_reg(hw, IGP02E1000_PHY_POWER_MGMT, &data);
if (ret_val)
goto out;
if (active) {
data |= IGP02E1000_PM_D0_LPLU;
ret_val = phy->ops.write_reg(hw, IGP02E1000_PHY_POWER_MGMT,
data);
if (ret_val)
goto out;
/* When LPLU is enabled, we should disable SmartSpeed */
ret_val = phy->ops.read_reg(hw, IGP01E1000_PHY_PORT_CONFIG,
&data);
data &= ~IGP01E1000_PSCFR_SMART_SPEED;
ret_val = phy->ops.write_reg(hw, IGP01E1000_PHY_PORT_CONFIG,
data);
if (ret_val)
goto out;
} else {
data &= ~IGP02E1000_PM_D0_LPLU;
ret_val = phy->ops.write_reg(hw, IGP02E1000_PHY_POWER_MGMT,
data);
/* LPLU and SmartSpeed are mutually exclusive. LPLU is used
* during Dx states where the power conservation is most
* important. During driver activity we should enable
* SmartSpeed, so performance is maintained.
*/
if (phy->smart_speed == e1000_smart_speed_on) {
ret_val = phy->ops.read_reg(hw,
IGP01E1000_PHY_PORT_CONFIG, &data);
if (ret_val)
goto out;
data |= IGP01E1000_PSCFR_SMART_SPEED;
ret_val = phy->ops.write_reg(hw,
IGP01E1000_PHY_PORT_CONFIG, data);
if (ret_val)
goto out;
} else if (phy->smart_speed == e1000_smart_speed_off) {
ret_val = phy->ops.read_reg(hw,
IGP01E1000_PHY_PORT_CONFIG, &data);
if (ret_val)
goto out;
data &= ~IGP01E1000_PSCFR_SMART_SPEED;
ret_val = phy->ops.write_reg(hw,
IGP01E1000_PHY_PORT_CONFIG, data);
if (ret_val)
goto out;
}
}
out:
return ret_val;
}
/**
* igb_set_d0_lplu_state_82580 - Set Low Power Linkup D0 state
* @hw: pointer to the HW structure
* @active: true to enable LPLU, false to disable
*
* Sets the LPLU D0 state according to the active flag. When
* activating LPLU this function also disables smart speed
* and vice versa. LPLU will not be activated unless the
* device autonegotiation advertisement meets standards of
* either 10 or 10/100 or 10/100/1000 at all duplexes.
* This is a function pointer entry point only called by
* PHY setup routines.
**/
static s32 igb_set_d0_lplu_state_82580(struct e1000_hw *hw, bool active)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val = 0;
u16 data;
data = rd32(E1000_82580_PHY_POWER_MGMT);
if (active) {
data |= E1000_82580_PM_D0_LPLU;
/* When LPLU is enabled, we should disable SmartSpeed */
data &= ~E1000_82580_PM_SPD;
} else {
data &= ~E1000_82580_PM_D0_LPLU;
/* LPLU and SmartSpeed are mutually exclusive. LPLU is used
* during Dx states where the power conservation is most
* important. During driver activity we should enable
* SmartSpeed, so performance is maintained.
*/
if (phy->smart_speed == e1000_smart_speed_on)
data |= E1000_82580_PM_SPD;
else if (phy->smart_speed == e1000_smart_speed_off)
data &= ~E1000_82580_PM_SPD; }
wr32(E1000_82580_PHY_POWER_MGMT, data);
return ret_val;
}
/**
* igb_set_d3_lplu_state_82580 - Sets low power link up state for D3
* @hw: pointer to the HW structure
* @active: boolean used to enable/disable lplu
*
* Success returns 0, Failure returns 1
*
* The low power link up (lplu) state is set to the power management level D3
* and SmartSpeed is disabled when active is true, else clear lplu for D3
* and enable Smartspeed. LPLU and Smartspeed are mutually exclusive. LPLU
* is used during Dx states where the power conservation is most important.
* During driver activity, SmartSpeed should be enabled so performance is
* maintained.
**/
static s32 igb_set_d3_lplu_state_82580(struct e1000_hw *hw, bool active)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val = 0;
u16 data;
data = rd32(E1000_82580_PHY_POWER_MGMT);
if (!active) {
data &= ~E1000_82580_PM_D3_LPLU;
/* LPLU and SmartSpeed are mutually exclusive. LPLU is used
* during Dx states where the power conservation is most
* important. During driver activity we should enable
* SmartSpeed, so performance is maintained.
*/
if (phy->smart_speed == e1000_smart_speed_on)
data |= E1000_82580_PM_SPD;
else if (phy->smart_speed == e1000_smart_speed_off)
data &= ~E1000_82580_PM_SPD;
} else if ((phy->autoneg_advertised == E1000_ALL_SPEED_DUPLEX) ||
(phy->autoneg_advertised == E1000_ALL_NOT_GIG) ||
(phy->autoneg_advertised == E1000_ALL_10_SPEED)) {
data |= E1000_82580_PM_D3_LPLU;
/* When LPLU is enabled, we should disable SmartSpeed */
data &= ~E1000_82580_PM_SPD;
}
wr32(E1000_82580_PHY_POWER_MGMT, data);
return ret_val;
}
/**
* igb_acquire_nvm_82575 - Request for access to EEPROM
* @hw: pointer to the HW structure
*
* Acquire the necessary semaphores for exclusive access to the EEPROM.
* Set the EEPROM access request bit and wait for EEPROM access grant bit.
* Return successful if access grant bit set, else clear the request for
* EEPROM access and return -E1000_ERR_NVM (-1).
**/
static s32 igb_acquire_nvm_82575(struct e1000_hw *hw)
{
s32 ret_val;
ret_val = hw->mac.ops.acquire_swfw_sync(hw, E1000_SWFW_EEP_SM);
if (ret_val)
goto out;
ret_val = igb_acquire_nvm(hw);
if (ret_val)
hw->mac.ops.release_swfw_sync(hw, E1000_SWFW_EEP_SM);
out:
return ret_val;
}
/**
* igb_release_nvm_82575 - Release exclusive access to EEPROM
* @hw: pointer to the HW structure
*
* Stop any current commands to the EEPROM and clear the EEPROM request bit,
* then release the semaphores acquired.
**/
static void igb_release_nvm_82575(struct e1000_hw *hw)
{
igb_release_nvm(hw);
hw->mac.ops.release_swfw_sync(hw, E1000_SWFW_EEP_SM);
}
/**
* igb_acquire_swfw_sync_82575 - Acquire SW/FW semaphore
* @hw: pointer to the HW structure
* @mask: specifies which semaphore to acquire
*
* Acquire the SW/FW semaphore to access the PHY or NVM. The mask
* will also specify which port we're acquiring the lock for.
**/
static s32 igb_acquire_swfw_sync_82575(struct e1000_hw *hw, u16 mask)
{
u32 swfw_sync;
u32 swmask = mask;
u32 fwmask = mask << 16;
s32 ret_val = 0;
s32 i = 0, timeout = 200; /* FIXME: find real value to use here */
while (i < timeout) {
if (igb_get_hw_semaphore(hw)) {
ret_val = -E1000_ERR_SWFW_SYNC;
goto out;
}
swfw_sync = rd32(E1000_SW_FW_SYNC);
if (!(swfw_sync & (fwmask | swmask)))
break;
/* Firmware currently using resource (fwmask)
* or other software thread using resource (swmask)
*/
igb_put_hw_semaphore(hw);
mdelay(5);
i++;
}
if (i == timeout) {
hw_dbg("Driver can't access resource, SW_FW_SYNC timeout.\n");
ret_val = -E1000_ERR_SWFW_SYNC;
goto out;
}
swfw_sync |= swmask;
wr32(E1000_SW_FW_SYNC, swfw_sync);
igb_put_hw_semaphore(hw);
out:
return ret_val;
}
/**
* igb_release_swfw_sync_82575 - Release SW/FW semaphore
* @hw: pointer to the HW structure
* @mask: specifies which semaphore to acquire
*
* Release the SW/FW semaphore used to access the PHY or NVM. The mask
* will also specify which port we're releasing the lock for.
**/
static void igb_release_swfw_sync_82575(struct e1000_hw *hw, u16 mask)
{
u32 swfw_sync;
while (igb_get_hw_semaphore(hw) != 0);
/* Empty */
swfw_sync = rd32(E1000_SW_FW_SYNC);
swfw_sync &= ~mask;
wr32(E1000_SW_FW_SYNC, swfw_sync);
igb_put_hw_semaphore(hw);
}
/**
* igb_get_cfg_done_82575 - Read config done bit
* @hw: pointer to the HW structure
*
* Read the management control register for the config done bit for
* completion status. NOTE: silicon which is EEPROM-less will fail trying
* to read the config done bit, so an error is *ONLY* logged and returns
* 0. If we were to return with error, EEPROM-less silicon
* would not be able to be reset or change link.
**/
static s32 igb_get_cfg_done_82575(struct e1000_hw *hw)
{
s32 timeout = PHY_CFG_TIMEOUT;
s32 ret_val = 0;
u32 mask = E1000_NVM_CFG_DONE_PORT_0;
if (hw->bus.func == 1)
mask = E1000_NVM_CFG_DONE_PORT_1;
else if (hw->bus.func == E1000_FUNC_2)
mask = E1000_NVM_CFG_DONE_PORT_2;
else if (hw->bus.func == E1000_FUNC_3)
mask = E1000_NVM_CFG_DONE_PORT_3;
while (timeout) {
if (rd32(E1000_EEMNGCTL) & mask)
break;
msleep(1);
timeout--;
}
if (!timeout)
hw_dbg("MNG configuration cycle has not completed.\n");
/* If EEPROM is not marked present, init the PHY manually */
if (((rd32(E1000_EECD) & E1000_EECD_PRES) == 0) &&
(hw->phy.type == e1000_phy_igp_3))
igb_phy_init_script_igp3(hw);
return ret_val;
}
/**
* igb_check_for_link_82575 - Check for link
* @hw: pointer to the HW structure
*
* If sgmii is enabled, then use the pcs register to determine link, otherwise
* use the generic interface for determining link.
**/
static s32 igb_check_for_link_82575(struct e1000_hw *hw)
{
s32 ret_val;
u16 speed, duplex;
if (hw->phy.media_type != e1000_media_type_copper) {
ret_val = igb_get_pcs_speed_and_duplex_82575(hw, &speed,
&duplex);
/* Use this flag to determine if link needs to be checked or
* not. If we have link clear the flag so that we do not
* continue to check for link.
*/
hw->mac.get_link_status = !hw->mac.serdes_has_link;
/* Configure Flow Control now that Auto-Neg has completed.
* First, we need to restore the desired flow control
* settings because we may have had to re-autoneg with a
* different link partner.
*/
ret_val = igb_config_fc_after_link_up(hw);
if (ret_val)
hw_dbg("Error configuring flow control\n");
} else {
ret_val = igb_check_for_copper_link(hw);
}
return ret_val;
}
/**
* igb_power_up_serdes_link_82575 - Power up the serdes link after shutdown
* @hw: pointer to the HW structure
**/
void igb_power_up_serdes_link_82575(struct e1000_hw *hw)
{
u32 reg;
if ((hw->phy.media_type != e1000_media_type_internal_serdes) &&
!igb_sgmii_active_82575(hw))
return;
/* Enable PCS to turn on link */
reg = rd32(E1000_PCS_CFG0);
reg |= E1000_PCS_CFG_PCS_EN;
wr32(E1000_PCS_CFG0, reg);
/* Power up the laser */
reg = rd32(E1000_CTRL_EXT);
reg &= ~E1000_CTRL_EXT_SDP3_DATA;
wr32(E1000_CTRL_EXT, reg);
/* flush the write to verify completion */
wrfl();
msleep(1);
}
/**
* igb_get_pcs_speed_and_duplex_82575 - Retrieve current speed/duplex
* @hw: pointer to the HW structure
* @speed: stores the current speed
* @duplex: stores the current duplex
*
* Using the physical coding sub-layer (PCS), retrieve the current speed and
* duplex, then store the values in the pointers provided.
**/
static s32 igb_get_pcs_speed_and_duplex_82575(struct e1000_hw *hw, u16 *speed,
u16 *duplex)
{
struct e1000_mac_info *mac = &hw->mac;
u32 pcs;
/* Set up defaults for the return values of this function */
mac->serdes_has_link = false;
*speed = 0;
*duplex = 0;
/* Read the PCS Status register for link state. For non-copper mode,
* the status register is not accurate. The PCS status register is
* used instead.
*/
pcs = rd32(E1000_PCS_LSTAT);
/* The link up bit determines when link is up on autoneg. The sync ok
* gets set once both sides sync up and agree upon link. Stable link
* can be determined by checking for both link up and link sync ok
*/
if ((pcs & E1000_PCS_LSTS_LINK_OK) && (pcs & E1000_PCS_LSTS_SYNK_OK)) {
mac->serdes_has_link = true;
/* Detect and store PCS speed */
if (pcs & E1000_PCS_LSTS_SPEED_1000) {
*speed = SPEED_1000;
} else if (pcs & E1000_PCS_LSTS_SPEED_100) {
*speed = SPEED_100;
} else {
*speed = SPEED_10;
}
/* Detect and store PCS duplex */
if (pcs & E1000_PCS_LSTS_DUPLEX_FULL) {
*duplex = FULL_DUPLEX;
} else {
*duplex = HALF_DUPLEX;
}
}
return 0;
}
/**
* igb_shutdown_serdes_link_82575 - Remove link during power down
* @hw: pointer to the HW structure
*
* In the case of fiber serdes, shut down optics and PCS on driver unload
* when management pass thru is not enabled.
**/
void igb_shutdown_serdes_link_82575(struct e1000_hw *hw)
{
u32 reg;
if (hw->phy.media_type != e1000_media_type_internal_serdes &&
igb_sgmii_active_82575(hw))
return;
if (!igb_enable_mng_pass_thru(hw)) {
/* Disable PCS to turn off link */
reg = rd32(E1000_PCS_CFG0);
reg &= ~E1000_PCS_CFG_PCS_EN;
wr32(E1000_PCS_CFG0, reg);
/* shutdown the laser */
reg = rd32(E1000_CTRL_EXT);
reg |= E1000_CTRL_EXT_SDP3_DATA;
wr32(E1000_CTRL_EXT, reg);
/* flush the write to verify completion */
wrfl();
msleep(1);
}
}
/**
* igb_reset_hw_82575 - Reset hardware
* @hw: pointer to the HW structure
*
* This resets the hardware into a known state. This is a
* function pointer entry point called by the api module.
**/
static s32 igb_reset_hw_82575(struct e1000_hw *hw)
{
u32 ctrl, icr;
s32 ret_val;
/* Prevent the PCI-E bus from sticking if there is no TLP connection
* on the last TLP read/write transaction when MAC is reset.
*/
ret_val = igb_disable_pcie_master(hw);
if (ret_val)
hw_dbg("PCI-E Master disable polling has failed.\n");
/* set the completion timeout for interface */
ret_val = igb_set_pcie_completion_timeout(hw);
if (ret_val) {
hw_dbg("PCI-E Set completion timeout has failed.\n");
}
hw_dbg("Masking off all interrupts\n");
wr32(E1000_IMC, 0xffffffff);
wr32(E1000_RCTL, 0);
wr32(E1000_TCTL, E1000_TCTL_PSP);
wrfl();
msleep(10);
ctrl = rd32(E1000_CTRL);
hw_dbg("Issuing a global reset to MAC\n");
wr32(E1000_CTRL, ctrl | E1000_CTRL_RST);
ret_val = igb_get_auto_rd_done(hw);
if (ret_val) {
/* When auto config read does not complete, do not
* return with an error. This can happen in situations
* where there is no eeprom and prevents getting link.
*/
hw_dbg("Auto Read Done did not complete\n");
}
/* If EEPROM is not present, run manual init scripts */
if ((rd32(E1000_EECD) & E1000_EECD_PRES) == 0)
igb_reset_init_script_82575(hw);
/* Clear any pending interrupt events. */
wr32(E1000_IMC, 0xffffffff);
icr = rd32(E1000_ICR);
/* Install any alternate MAC address into RAR0 */
ret_val = igb_check_alt_mac_addr(hw);
return ret_val;
}
/**
* igb_init_hw_82575 - Initialize hardware
* @hw: pointer to the HW structure
*
* This inits the hardware readying it for operation.
**/
static s32 igb_init_hw_82575(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
s32 ret_val;
u16 i, rar_count = mac->rar_entry_count;
/* Initialize identification LED */
ret_val = igb_id_led_init(hw);
if (ret_val) {
hw_dbg("Error initializing identification LED\n");
/* This is not fatal and we should not stop init due to this */
}
/* Disabling VLAN filtering */
hw_dbg("Initializing the IEEE VLAN\n");
if ((hw->mac.type == e1000_i350) || (hw->mac.type == e1000_i354))
igb_clear_vfta_i350(hw);
else
igb_clear_vfta(hw);
/* Setup the receive address */
igb_init_rx_addrs(hw, rar_count);
/* Zero out the Multicast HASH table */
hw_dbg("Zeroing the MTA\n");
for (i = 0; i < mac->mta_reg_count; i++)
array_wr32(E1000_MTA, i, 0);
/* Zero out the Unicast HASH table */
hw_dbg("Zeroing the UTA\n");
for (i = 0; i < mac->uta_reg_count; i++)
array_wr32(E1000_UTA, i, 0);
/* Setup link and flow control */
ret_val = igb_setup_link(hw);
/* Clear all of the statistics registers (clear on read). It is
* important that we do this after we have tried to establish link
* because the symbol error count will increment wildly if there
* is no link.
*/
igb_clear_hw_cntrs_82575(hw);
return ret_val;
}
/**
* igb_setup_copper_link_82575 - Configure copper link settings
* @hw: pointer to the HW structure
*
* Configures the link for auto-neg or forced speed and duplex. Then we check
* for link, once link is established calls to configure collision distance
* and flow control are called.
**/
static s32 igb_setup_copper_link_82575(struct e1000_hw *hw)
{
u32 ctrl;
s32 ret_val;
u32 phpm_reg;
ctrl = rd32(E1000_CTRL);
ctrl |= E1000_CTRL_SLU;
ctrl &= ~(E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX);
wr32(E1000_CTRL, ctrl);
/* Clear Go Link Disconnect bit */
if (hw->mac.type >= e1000_82580) {
phpm_reg = rd32(E1000_82580_PHY_POWER_MGMT);
phpm_reg &= ~E1000_82580_PM_GO_LINKD;
wr32(E1000_82580_PHY_POWER_MGMT, phpm_reg);
}
ret_val = igb_setup_serdes_link_82575(hw);
if (ret_val)
goto out;
if (igb_sgmii_active_82575(hw) && !hw->phy.reset_disable) {
/* allow time for SFP cage time to power up phy */
msleep(300);
ret_val = hw->phy.ops.reset(hw);
if (ret_val) {
hw_dbg("Error resetting the PHY.\n");
goto out;
}
}
switch (hw->phy.type) {
case e1000_phy_i210:
case e1000_phy_m88:
switch (hw->phy.id) {
case I347AT4_E_PHY_ID:
case M88E1112_E_PHY_ID:
case M88E1545_E_PHY_ID:
case I210_I_PHY_ID:
ret_val = igb_copper_link_setup_m88_gen2(hw);
break;
default:
ret_val = igb_copper_link_setup_m88(hw);
break;
}
break;
case e1000_phy_igp_3:
ret_val = igb_copper_link_setup_igp(hw);
break;
case e1000_phy_82580:
ret_val = igb_copper_link_setup_82580(hw);
break;
default:
ret_val = -E1000_ERR_PHY;
break;
}
if (ret_val)
goto out;
ret_val = igb_setup_copper_link(hw);
out:
return ret_val;
}
/**
* igb_setup_serdes_link_82575 - Setup link for serdes
* @hw: pointer to the HW structure
*
* Configure the physical coding sub-layer (PCS) link. The PCS link is
* used on copper connections where the serialized gigabit media independent
* interface (sgmii), or serdes fiber is being used. Configures the link
* for auto-negotiation or forces speed/duplex.
**/
static s32 igb_setup_serdes_link_82575(struct e1000_hw *hw)
{
u32 ctrl_ext, ctrl_reg, reg, anadv_reg;
bool pcs_autoneg;
s32 ret_val = E1000_SUCCESS;
u16 data;
if ((hw->phy.media_type != e1000_media_type_internal_serdes) &&
!igb_sgmii_active_82575(hw))
return ret_val;
/* On the 82575, SerDes loopback mode persists until it is
* explicitly turned off or a power cycle is performed. A read to
* the register does not indicate its status. Therefore, we ensure
* loopback mode is disabled during initialization.
*/
wr32(E1000_SCTL, E1000_SCTL_DISABLE_SERDES_LOOPBACK);
/* power on the sfp cage if present and turn on I2C */
ctrl_ext = rd32(E1000_CTRL_EXT);
ctrl_ext &= ~E1000_CTRL_EXT_SDP3_DATA;
ctrl_ext |= E1000_CTRL_I2C_ENA;
wr32(E1000_CTRL_EXT, ctrl_ext);
ctrl_reg = rd32(E1000_CTRL);
ctrl_reg |= E1000_CTRL_SLU;
if (hw->mac.type == e1000_82575 || hw->mac.type == e1000_82576) {
/* set both sw defined pins */
ctrl_reg |= E1000_CTRL_SWDPIN0 | E1000_CTRL_SWDPIN1;
/* Set switch control to serdes energy detect */
reg = rd32(E1000_CONNSW);
reg |= E1000_CONNSW_ENRGSRC;
wr32(E1000_CONNSW, reg);
}
reg = rd32(E1000_PCS_LCTL);
/* default pcs_autoneg to the same setting as mac autoneg */
pcs_autoneg = hw->mac.autoneg;
switch (ctrl_ext & E1000_CTRL_EXT_LINK_MODE_MASK) {
case E1000_CTRL_EXT_LINK_MODE_SGMII:
/* sgmii mode lets the phy handle forcing speed/duplex */
pcs_autoneg = true;
/* autoneg time out should be disabled for SGMII mode */
reg &= ~(E1000_PCS_LCTL_AN_TIMEOUT);
break;
case E1000_CTRL_EXT_LINK_MODE_1000BASE_KX:
/* disable PCS autoneg and support parallel detect only */
pcs_autoneg = false;
default:
if (hw->mac.type == e1000_82575 ||
hw->mac.type == e1000_82576) {
ret_val = hw->nvm.ops.read(hw, NVM_COMPAT, 1, &data);
if (ret_val) {
printk(KERN_DEBUG "NVM Read Error\n\n");
return ret_val;
}
if (data & E1000_EEPROM_PCS_AUTONEG_DISABLE_BIT)
pcs_autoneg = false;
}
/* non-SGMII modes only supports a speed of 1000/Full for the
* link so it is best to just force the MAC and let the pcs
* link either autoneg or be forced to 1000/Full
*/
ctrl_reg |= E1000_CTRL_SPD_1000 | E1000_CTRL_FRCSPD |
E1000_CTRL_FD | E1000_CTRL_FRCDPX;
/* set speed of 1000/Full if speed/duplex is forced */
reg |= E1000_PCS_LCTL_FSV_1000 | E1000_PCS_LCTL_FDV_FULL;
break;
}
wr32(E1000_CTRL, ctrl_reg);
/* New SerDes mode allows for forcing speed or autonegotiating speed
* at 1gb. Autoneg should be default set by most drivers. This is the
* mode that will be compatible with older link partners and switches.
* However, both are supported by the hardware and some drivers/tools.
*/
reg &= ~(E1000_PCS_LCTL_AN_ENABLE | E1000_PCS_LCTL_FLV_LINK_UP |
E1000_PCS_LCTL_FSD | E1000_PCS_LCTL_FORCE_LINK);
if (pcs_autoneg) {
/* Set PCS register for autoneg */
reg |= E1000_PCS_LCTL_AN_ENABLE | /* Enable Autoneg */
E1000_PCS_LCTL_AN_RESTART; /* Restart autoneg */
/* Disable force flow control for autoneg */
reg &= ~E1000_PCS_LCTL_FORCE_FCTRL;
/* Configure flow control advertisement for autoneg */
anadv_reg = rd32(E1000_PCS_ANADV);
anadv_reg &= ~(E1000_TXCW_ASM_DIR | E1000_TXCW_PAUSE);
switch (hw->fc.requested_mode) {
case e1000_fc_full:
case e1000_fc_rx_pause:
anadv_reg |= E1000_TXCW_ASM_DIR;
anadv_reg |= E1000_TXCW_PAUSE;
break;
case e1000_fc_tx_pause:
anadv_reg |= E1000_TXCW_ASM_DIR;
break;
default:
break;
}
wr32(E1000_PCS_ANADV, anadv_reg);
hw_dbg("Configuring Autoneg:PCS_LCTL=0x%08X\n", reg);
} else {
/* Set PCS register for forced link */
reg |= E1000_PCS_LCTL_FSD; /* Force Speed */
/* Force flow control for forced link */
reg |= E1000_PCS_LCTL_FORCE_FCTRL;
hw_dbg("Configuring Forced Link:PCS_LCTL=0x%08X\n", reg);
}
wr32(E1000_PCS_LCTL, reg);
if (!pcs_autoneg && !igb_sgmii_active_82575(hw))
igb_force_mac_fc(hw);
return ret_val;
}
/**
* igb_sgmii_active_82575 - Return sgmii state
* @hw: pointer to the HW structure
*
* 82575 silicon has a serialized gigabit media independent interface (sgmii)
* which can be enabled for use in the embedded applications. Simply
* return the current state of the sgmii interface.
**/
static bool igb_sgmii_active_82575(struct e1000_hw *hw)
{
struct e1000_dev_spec_82575 *dev_spec = &hw->dev_spec._82575;
return dev_spec->sgmii_active;
}
/**
* igb_reset_init_script_82575 - Inits HW defaults after reset
* @hw: pointer to the HW structure
*
* Inits recommended HW defaults after a reset when there is no EEPROM
* detected. This is only for the 82575.
**/
static s32 igb_reset_init_script_82575(struct e1000_hw *hw)
{
if (hw->mac.type == e1000_82575) {
hw_dbg("Running reset init script for 82575\n");
/* SerDes configuration via SERDESCTRL */
igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x00, 0x0C);
igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x01, 0x78);
igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x1B, 0x23);
igb_write_8bit_ctrl_reg(hw, E1000_SCTL, 0x23, 0x15);
/* CCM configuration via CCMCTL register */
igb_write_8bit_ctrl_reg(hw, E1000_CCMCTL, 0x14, 0x00);
igb_write_8bit_ctrl_reg(hw, E1000_CCMCTL, 0x10, 0x00);
/* PCIe lanes configuration */
igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x00, 0xEC);
igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x61, 0xDF);
igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x34, 0x05);
igb_write_8bit_ctrl_reg(hw, E1000_GIOCTL, 0x2F, 0x81);
/* PCIe PLL Configuration */
igb_write_8bit_ctrl_reg(hw, E1000_SCCTL, 0x02, 0x47);
igb_write_8bit_ctrl_reg(hw, E1000_SCCTL, 0x14, 0x00);
igb_write_8bit_ctrl_reg(hw, E1000_SCCTL, 0x10, 0x00);
}
return 0;
}
/**
* igb_read_mac_addr_82575 - Read device MAC address
* @hw: pointer to the HW structure
**/
static s32 igb_read_mac_addr_82575(struct e1000_hw *hw)
{
s32 ret_val = 0;
/* If there's an alternate MAC address place it in RAR0
* so that it will override the Si installed default perm
* address.
*/
ret_val = igb_check_alt_mac_addr(hw);
if (ret_val)
goto out;
ret_val = igb_read_mac_addr(hw);
out:
return ret_val;
}
/**
* igb_power_down_phy_copper_82575 - Remove link during PHY power down
* @hw: pointer to the HW structure
*
* In the case of a PHY power down to save power, or to turn off link during a
* driver unload, or wake on lan is not enabled, remove the link.
**/
void igb_power_down_phy_copper_82575(struct e1000_hw *hw)
{
/* If the management interface is not enabled, then power down */
if (!(igb_enable_mng_pass_thru(hw) || igb_check_reset_block(hw)))
igb_power_down_phy_copper(hw);
}
/**
* igb_clear_hw_cntrs_82575 - Clear device specific hardware counters
* @hw: pointer to the HW structure
*
* Clears the hardware counters by reading the counter registers.
**/
static void igb_clear_hw_cntrs_82575(struct e1000_hw *hw)
{
igb_clear_hw_cntrs_base(hw);
rd32(E1000_PRC64);
rd32(E1000_PRC127);
rd32(E1000_PRC255);
rd32(E1000_PRC511);
rd32(E1000_PRC1023);
rd32(E1000_PRC1522);
rd32(E1000_PTC64);
rd32(E1000_PTC127);
rd32(E1000_PTC255);
rd32(E1000_PTC511);
rd32(E1000_PTC1023);
rd32(E1000_PTC1522);
rd32(E1000_ALGNERRC);
rd32(E1000_RXERRC);
rd32(E1000_TNCRS);
rd32(E1000_CEXTERR);
rd32(E1000_TSCTC);
rd32(E1000_TSCTFC);
rd32(E1000_MGTPRC);
rd32(E1000_MGTPDC);
rd32(E1000_MGTPTC);
rd32(E1000_IAC);
rd32(E1000_ICRXOC);
rd32(E1000_ICRXPTC);
rd32(E1000_ICRXATC);
rd32(E1000_ICTXPTC);
rd32(E1000_ICTXATC);
rd32(E1000_ICTXQEC);
rd32(E1000_ICTXQMTC);
rd32(E1000_ICRXDMTC);
rd32(E1000_CBTMPC);
rd32(E1000_HTDPMC);
rd32(E1000_CBRMPC);
rd32(E1000_RPTHC);
rd32(E1000_HGPTC);
rd32(E1000_HTCBDPC);
rd32(E1000_HGORCL);
rd32(E1000_HGORCH);
rd32(E1000_HGOTCL);
rd32(E1000_HGOTCH);
rd32(E1000_LENERRS);
/* This register should not be read in copper configurations */
if (hw->phy.media_type == e1000_media_type_internal_serdes ||
igb_sgmii_active_82575(hw))
rd32(E1000_SCVPC);
}
/**
* igb_rx_fifo_flush_82575 - Clean rx fifo after RX enable
* @hw: pointer to the HW structure
*
* After rx enable if managability is enabled then there is likely some
* bad data at the start of the fifo and possibly in the DMA fifo. This
* function clears the fifos and flushes any packets that came in as rx was
* being enabled.
**/
void igb_rx_fifo_flush_82575(struct e1000_hw *hw)
{
u32 rctl, rlpml, rxdctl[4], rfctl, temp_rctl, rx_enabled;
int i, ms_wait;
if (hw->mac.type != e1000_82575 ||
!(rd32(E1000_MANC) & E1000_MANC_RCV_TCO_EN))
return;
/* Disable all RX queues */
for (i = 0; i < 4; i++) {
rxdctl[i] = rd32(E1000_RXDCTL(i));
wr32(E1000_RXDCTL(i),
rxdctl[i] & ~E1000_RXDCTL_QUEUE_ENABLE);
}
/* Poll all queues to verify they have shut down */
for (ms_wait = 0; ms_wait < 10; ms_wait++) {
msleep(1);
rx_enabled = 0;
for (i = 0; i < 4; i++)
rx_enabled |= rd32(E1000_RXDCTL(i));
if (!(rx_enabled & E1000_RXDCTL_QUEUE_ENABLE))
break;
}
if (ms_wait == 10)
hw_dbg("Queue disable timed out after 10ms\n");
/* Clear RLPML, RCTL.SBP, RFCTL.LEF, and set RCTL.LPE so that all
* incoming packets are rejected. Set enable and wait 2ms so that
* any packet that was coming in as RCTL.EN was set is flushed
*/
rfctl = rd32(E1000_RFCTL);
wr32(E1000_RFCTL, rfctl & ~E1000_RFCTL_LEF);
rlpml = rd32(E1000_RLPML);
wr32(E1000_RLPML, 0);
rctl = rd32(E1000_RCTL);
temp_rctl = rctl & ~(E1000_RCTL_EN | E1000_RCTL_SBP);
temp_rctl |= E1000_RCTL_LPE;
wr32(E1000_RCTL, temp_rctl);
wr32(E1000_RCTL, temp_rctl | E1000_RCTL_EN);
wrfl();
msleep(2);
/* Enable RX queues that were previously enabled and restore our
* previous state
*/
for (i = 0; i < 4; i++)
wr32(E1000_RXDCTL(i), rxdctl[i]);
wr32(E1000_RCTL, rctl);
wrfl();
wr32(E1000_RLPML, rlpml);
wr32(E1000_RFCTL, rfctl);
/* Flush receive errors generated by workaround */
rd32(E1000_ROC);
rd32(E1000_RNBC);
rd32(E1000_MPC);
}
/**
* igb_set_pcie_completion_timeout - set pci-e completion timeout
* @hw: pointer to the HW structure
*
* The defaults for 82575 and 82576 should be in the range of 50us to 50ms,
* however the hardware default for these parts is 500us to 1ms which is less
* than the 10ms recommended by the pci-e spec. To address this we need to
* increase the value to either 10ms to 200ms for capability version 1 config,
* or 16ms to 55ms for version 2.
**/
static s32 igb_set_pcie_completion_timeout(struct e1000_hw *hw)
{
u32 gcr = rd32(E1000_GCR);
s32 ret_val = 0;
u16 pcie_devctl2;
/* only take action if timeout value is defaulted to 0 */
if (gcr & E1000_GCR_CMPL_TMOUT_MASK)
goto out;
/* if capabilities version is type 1 we can write the
* timeout of 10ms to 200ms through the GCR register
*/
if (!(gcr & E1000_GCR_CAP_VER2)) {
gcr |= E1000_GCR_CMPL_TMOUT_10ms;
goto out;
}
/* for version 2 capabilities we need to write the config space
* directly in order to set the completion timeout value for
* 16ms to 55ms
*/
ret_val = igb_read_pcie_cap_reg(hw, PCIE_DEVICE_CONTROL2,
&pcie_devctl2);
if (ret_val)
goto out;
pcie_devctl2 |= PCIE_DEVICE_CONTROL2_16ms;
ret_val = igb_write_pcie_cap_reg(hw, PCIE_DEVICE_CONTROL2,
&pcie_devctl2);
out:
/* disable completion timeout resend */
gcr &= ~E1000_GCR_CMPL_TMOUT_RESEND;
wr32(E1000_GCR, gcr);
return ret_val;
}
/**
* igb_vmdq_set_anti_spoofing_pf - enable or disable anti-spoofing
* @hw: pointer to the hardware struct
* @enable: state to enter, either enabled or disabled
* @pf: Physical Function pool - do not set anti-spoofing for the PF
*
* enables/disables L2 switch anti-spoofing functionality.
**/
void igb_vmdq_set_anti_spoofing_pf(struct e1000_hw *hw, bool enable, int pf)
{
u32 reg_val, reg_offset;
switch (hw->mac.type) {
case e1000_82576:
reg_offset = E1000_DTXSWC;
break;
case e1000_i350:
case e1000_i354:
reg_offset = E1000_TXSWC;
break;
default:
return;
}
reg_val = rd32(reg_offset);
if (enable) {
reg_val |= (E1000_DTXSWC_MAC_SPOOF_MASK |
E1000_DTXSWC_VLAN_SPOOF_MASK);
/* The PF can spoof - it has to in order to
* support emulation mode NICs
*/
reg_val ^= (1 << pf | 1 << (pf + MAX_NUM_VFS));
} else {
reg_val &= ~(E1000_DTXSWC_MAC_SPOOF_MASK |
E1000_DTXSWC_VLAN_SPOOF_MASK);
}
wr32(reg_offset, reg_val);
}
/**
* igb_vmdq_set_loopback_pf - enable or disable vmdq loopback
* @hw: pointer to the hardware struct
* @enable: state to enter, either enabled or disabled
*
* enables/disables L2 switch loopback functionality.
**/
void igb_vmdq_set_loopback_pf(struct e1000_hw *hw, bool enable)
{
u32 dtxswc;
switch (hw->mac.type) {
case e1000_82576:
dtxswc = rd32(E1000_DTXSWC);
if (enable)
dtxswc |= E1000_DTXSWC_VMDQ_LOOPBACK_EN;
else
dtxswc &= ~E1000_DTXSWC_VMDQ_LOOPBACK_EN;
wr32(E1000_DTXSWC, dtxswc);
break;
case e1000_i354:
case e1000_i350:
dtxswc = rd32(E1000_TXSWC);
if (enable)
dtxswc |= E1000_DTXSWC_VMDQ_LOOPBACK_EN;
else
dtxswc &= ~E1000_DTXSWC_VMDQ_LOOPBACK_EN;
wr32(E1000_TXSWC, dtxswc);
break;
default:
/* Currently no other hardware supports loopback */
break;
}
}
/**
* igb_vmdq_set_replication_pf - enable or disable vmdq replication
* @hw: pointer to the hardware struct
* @enable: state to enter, either enabled or disabled
*
* enables/disables replication of packets across multiple pools.
**/
void igb_vmdq_set_replication_pf(struct e1000_hw *hw, bool enable)
{
u32 vt_ctl = rd32(E1000_VT_CTL);
if (enable)
vt_ctl |= E1000_VT_CTL_VM_REPL_EN;
else
vt_ctl &= ~E1000_VT_CTL_VM_REPL_EN;
wr32(E1000_VT_CTL, vt_ctl);
}
/**
* igb_read_phy_reg_82580 - Read 82580 MDI control register
* @hw: pointer to the HW structure
* @offset: register offset to be read
* @data: pointer to the read data
*
* Reads the MDI control register in the PHY at offset and stores the
* information read to data.
**/
static s32 igb_read_phy_reg_82580(struct e1000_hw *hw, u32 offset, u16 *data)
{
s32 ret_val;
ret_val = hw->phy.ops.acquire(hw);
if (ret_val)
goto out;
ret_val = igb_read_phy_reg_mdic(hw, offset, data);
hw->phy.ops.release(hw);
out:
return ret_val;
}
/**
* igb_write_phy_reg_82580 - Write 82580 MDI control register
* @hw: pointer to the HW structure
* @offset: register offset to write to
* @data: data to write to register at offset
*
* Writes data to MDI control register in the PHY at offset.
**/
static s32 igb_write_phy_reg_82580(struct e1000_hw *hw, u32 offset, u16 data)
{
s32 ret_val;
ret_val = hw->phy.ops.acquire(hw);
if (ret_val)
goto out;
ret_val = igb_write_phy_reg_mdic(hw, offset, data);
hw->phy.ops.release(hw);
out:
return ret_val;
}
/**
* igb_reset_mdicnfg_82580 - Reset MDICNFG destination and com_mdio bits
* @hw: pointer to the HW structure
*
* This resets the the MDICNFG.Destination and MDICNFG.Com_MDIO bits based on
* the values found in the EEPROM. This addresses an issue in which these
* bits are not restored from EEPROM after reset.
**/
static s32 igb_reset_mdicnfg_82580(struct e1000_hw *hw)
{
s32 ret_val = 0;
u32 mdicnfg;
u16 nvm_data = 0;
if (hw->mac.type != e1000_82580)
goto out;
if (!igb_sgmii_active_82575(hw))
goto out;
ret_val = hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_A +
NVM_82580_LAN_FUNC_OFFSET(hw->bus.func), 1,
&nvm_data);
if (ret_val) {
hw_dbg("NVM Read Error\n");
goto out;
}
mdicnfg = rd32(E1000_MDICNFG);
if (nvm_data & NVM_WORD24_EXT_MDIO)
mdicnfg |= E1000_MDICNFG_EXT_MDIO;
if (nvm_data & NVM_WORD24_COM_MDIO)
mdicnfg |= E1000_MDICNFG_COM_MDIO;
wr32(E1000_MDICNFG, mdicnfg);
out:
return ret_val;
}
/**
* igb_reset_hw_82580 - Reset hardware
* @hw: pointer to the HW structure
*
* This resets function or entire device (all ports, etc.)
* to a known state.
**/
static s32 igb_reset_hw_82580(struct e1000_hw *hw)
{
s32 ret_val = 0;
/* BH SW mailbox bit in SW_FW_SYNC */
u16 swmbsw_mask = E1000_SW_SYNCH_MB;
u32 ctrl, icr;
bool global_device_reset = hw->dev_spec._82575.global_device_reset;
hw->dev_spec._82575.global_device_reset = false;
/* due to hw errata, global device reset doesn't always
* work on 82580
*/
if (hw->mac.type == e1000_82580)
global_device_reset = false;
/* Get current control state. */
ctrl = rd32(E1000_CTRL);
/* Prevent the PCI-E bus from sticking if there is no TLP connection
* on the last TLP read/write transaction when MAC is reset.
*/
ret_val = igb_disable_pcie_master(hw);
if (ret_val)
hw_dbg("PCI-E Master disable polling has failed.\n");
hw_dbg("Masking off all interrupts\n");
wr32(E1000_IMC, 0xffffffff);
wr32(E1000_RCTL, 0);
wr32(E1000_TCTL, E1000_TCTL_PSP);
wrfl();
msleep(10);
/* Determine whether or not a global dev reset is requested */
if (global_device_reset &&
hw->mac.ops.acquire_swfw_sync(hw, swmbsw_mask))
global_device_reset = false;
if (global_device_reset &&
!(rd32(E1000_STATUS) & E1000_STAT_DEV_RST_SET))
ctrl |= E1000_CTRL_DEV_RST;
else
ctrl |= E1000_CTRL_RST;
wr32(E1000_CTRL, ctrl);
wrfl();
/* Add delay to insure DEV_RST has time to complete */
if (global_device_reset)
msleep(5);
ret_val = igb_get_auto_rd_done(hw);
if (ret_val) {
/* When auto config read does not complete, do not
* return with an error. This can happen in situations
* where there is no eeprom and prevents getting link.
*/
hw_dbg("Auto Read Done did not complete\n");
}
/* clear global device reset status bit */
wr32(E1000_STATUS, E1000_STAT_DEV_RST_SET);
/* Clear any pending interrupt events. */
wr32(E1000_IMC, 0xffffffff);
icr = rd32(E1000_ICR);
ret_val = igb_reset_mdicnfg_82580(hw);
if (ret_val)
hw_dbg("Could not reset MDICNFG based on EEPROM\n");
/* Install any alternate MAC address into RAR0 */
ret_val = igb_check_alt_mac_addr(hw);
/* Release semaphore */
if (global_device_reset)
hw->mac.ops.release_swfw_sync(hw, swmbsw_mask);
return ret_val;
}
/**
* igb_rxpbs_adjust_82580 - adjust RXPBS value to reflect actual RX PBA size
* @data: data received by reading RXPBS register
*
* The 82580 uses a table based approach for packet buffer allocation sizes.
* This function converts the retrieved value into the correct table value
* 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7
* 0x0 36 72 144 1 2 4 8 16
* 0x8 35 70 140 rsv rsv rsv rsv rsv
*/
u16 igb_rxpbs_adjust_82580(u32 data)
{
u16 ret_val = 0;
if (data < E1000_82580_RXPBS_TABLE_SIZE)
ret_val = e1000_82580_rxpbs_table[data];
return ret_val;
}
/**
* igb_validate_nvm_checksum_with_offset - Validate EEPROM
* checksum
* @hw: pointer to the HW structure
* @offset: offset in words of the checksum protected region
*
* Calculates the EEPROM checksum by reading/adding each word of the EEPROM
* and then verifies that the sum of the EEPROM is equal to 0xBABA.
**/
static s32 igb_validate_nvm_checksum_with_offset(struct e1000_hw *hw,
u16 offset)
{
s32 ret_val = 0;
u16 checksum = 0;
u16 i, nvm_data;
for (i = offset; i < ((NVM_CHECKSUM_REG + offset) + 1); i++) {
ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data);
if (ret_val) {
hw_dbg("NVM Read Error\n");
goto out;
}
checksum += nvm_data;
}
if (checksum != (u16) NVM_SUM) {
hw_dbg("NVM Checksum Invalid\n");
ret_val = -E1000_ERR_NVM;
goto out;
}
out:
return ret_val;
}
/**
* igb_update_nvm_checksum_with_offset - Update EEPROM
* checksum
* @hw: pointer to the HW structure
* @offset: offset in words of the checksum protected region
*
* Updates the EEPROM checksum by reading/adding each word of the EEPROM
* up to the checksum. Then calculates the EEPROM checksum and writes the
* value to the EEPROM.
**/
static s32 igb_update_nvm_checksum_with_offset(struct e1000_hw *hw, u16 offset)
{
s32 ret_val;
u16 checksum = 0;
u16 i, nvm_data;
for (i = offset; i < (NVM_CHECKSUM_REG + offset); i++) {
ret_val = hw->nvm.ops.read(hw, i, 1, &nvm_data);
if (ret_val) {
hw_dbg("NVM Read Error while updating checksum.\n");
goto out;
}
checksum += nvm_data;
}
checksum = (u16) NVM_SUM - checksum;
ret_val = hw->nvm.ops.write(hw, (NVM_CHECKSUM_REG + offset), 1,
&checksum);
if (ret_val)
hw_dbg("NVM Write Error while updating checksum.\n");
out:
return ret_val;
}
/**
* igb_validate_nvm_checksum_82580 - Validate EEPROM checksum
* @hw: pointer to the HW structure
*
* Calculates the EEPROM section checksum by reading/adding each word of
* the EEPROM and then verifies that the sum of the EEPROM is
* equal to 0xBABA.
**/
static s32 igb_validate_nvm_checksum_82580(struct e1000_hw *hw)
{
s32 ret_val = 0;
u16 eeprom_regions_count = 1;
u16 j, nvm_data;
u16 nvm_offset;
ret_val = hw->nvm.ops.read(hw, NVM_COMPATIBILITY_REG_3, 1, &nvm_data);
if (ret_val) {
hw_dbg("NVM Read Error\n");
goto out;
}
if (nvm_data & NVM_COMPATIBILITY_BIT_MASK) {
/* if checksums compatibility bit is set validate checksums
* for all 4 ports.
*/
eeprom_regions_count = 4;
}
for (j = 0; j < eeprom_regions_count; j++) {
nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j);
ret_val = igb_validate_nvm_checksum_with_offset(hw,
nvm_offset);
if (ret_val != 0)
goto out;
}
out:
return ret_val;
}
/**
* igb_update_nvm_checksum_82580 - Update EEPROM checksum
* @hw: pointer to the HW structure
*
* Updates the EEPROM section checksums for all 4 ports by reading/adding
* each word of the EEPROM up to the checksum. Then calculates the EEPROM
* checksum and writes the value to the EEPROM.
**/
static s32 igb_update_nvm_checksum_82580(struct e1000_hw *hw)
{
s32 ret_val;
u16 j, nvm_data;
u16 nvm_offset;
ret_val = hw->nvm.ops.read(hw, NVM_COMPATIBILITY_REG_3, 1, &nvm_data);
if (ret_val) {
hw_dbg("NVM Read Error while updating checksum"
" compatibility bit.\n");
goto out;
}
if ((nvm_data & NVM_COMPATIBILITY_BIT_MASK) == 0) {
/* set compatibility bit to validate checksums appropriately */
nvm_data = nvm_data | NVM_COMPATIBILITY_BIT_MASK;
ret_val = hw->nvm.ops.write(hw, NVM_COMPATIBILITY_REG_3, 1,
&nvm_data);
if (ret_val) {
hw_dbg("NVM Write Error while updating checksum"
" compatibility bit.\n");
goto out;
}
}
for (j = 0; j < 4; j++) {
nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j);
ret_val = igb_update_nvm_checksum_with_offset(hw, nvm_offset);
if (ret_val)
goto out;
}
out:
return ret_val;
}
/**
* igb_validate_nvm_checksum_i350 - Validate EEPROM checksum
* @hw: pointer to the HW structure
*
* Calculates the EEPROM section checksum by reading/adding each word of
* the EEPROM and then verifies that the sum of the EEPROM is
* equal to 0xBABA.
**/
static s32 igb_validate_nvm_checksum_i350(struct e1000_hw *hw)
{
s32 ret_val = 0;
u16 j;
u16 nvm_offset;
for (j = 0; j < 4; j++) {
nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j);
ret_val = igb_validate_nvm_checksum_with_offset(hw,
nvm_offset);
if (ret_val != 0)
goto out;
}
out:
return ret_val;
}
/**
* igb_update_nvm_checksum_i350 - Update EEPROM checksum
* @hw: pointer to the HW structure
*
* Updates the EEPROM section checksums for all 4 ports by reading/adding
* each word of the EEPROM up to the checksum. Then calculates the EEPROM
* checksum and writes the value to the EEPROM.
**/
static s32 igb_update_nvm_checksum_i350(struct e1000_hw *hw)
{
s32 ret_val = 0;
u16 j;
u16 nvm_offset;
for (j = 0; j < 4; j++) {
nvm_offset = NVM_82580_LAN_FUNC_OFFSET(j);
ret_val = igb_update_nvm_checksum_with_offset(hw, nvm_offset);
if (ret_val != 0)
goto out;
}
out:
return ret_val;
}
/**
* __igb_access_emi_reg - Read/write EMI register
* @hw: pointer to the HW structure
* @addr: EMI address to program
* @data: pointer to value to read/write from/to the EMI address
* @read: boolean flag to indicate read or write
**/
static s32 __igb_access_emi_reg(struct e1000_hw *hw, u16 address,
u16 *data, bool read)
{
s32 ret_val = E1000_SUCCESS;
ret_val = hw->phy.ops.write_reg(hw, E1000_EMIADD, address);
if (ret_val)
return ret_val;
if (read)
ret_val = hw->phy.ops.read_reg(hw, E1000_EMIDATA, data);
else
ret_val = hw->phy.ops.write_reg(hw, E1000_EMIDATA, *data);
return ret_val;
}
/**
* igb_read_emi_reg - Read Extended Management Interface register
* @hw: pointer to the HW structure
* @addr: EMI address to program
* @data: value to be read from the EMI address
**/
s32 igb_read_emi_reg(struct e1000_hw *hw, u16 addr, u16 *data)
{
return __igb_access_emi_reg(hw, addr, data, true);
}
/**
* igb_set_eee_i350 - Enable/disable EEE support
* @hw: pointer to the HW structure
*
* Enable/disable EEE based on setting in dev_spec structure.
*
**/
s32 igb_set_eee_i350(struct e1000_hw *hw)
{
s32 ret_val = 0;
u32 ipcnfg, eeer;
if ((hw->mac.type < e1000_i350) ||
(hw->phy.media_type != e1000_media_type_copper))
goto out;
ipcnfg = rd32(E1000_IPCNFG);
eeer = rd32(E1000_EEER);
/* enable or disable per user setting */
if (!(hw->dev_spec._82575.eee_disable)) {
u32 eee_su = rd32(E1000_EEE_SU);
ipcnfg |= (E1000_IPCNFG_EEE_1G_AN | E1000_IPCNFG_EEE_100M_AN);
eeer |= (E1000_EEER_TX_LPI_EN | E1000_EEER_RX_LPI_EN |
E1000_EEER_LPI_FC);
/* This bit should not be set in normal operation. */
if (eee_su & E1000_EEE_SU_LPI_CLK_STP)
hw_dbg("LPI Clock Stop Bit should not be set!\n");
} else {
ipcnfg &= ~(E1000_IPCNFG_EEE_1G_AN |
E1000_IPCNFG_EEE_100M_AN);
eeer &= ~(E1000_EEER_TX_LPI_EN |
E1000_EEER_RX_LPI_EN |
E1000_EEER_LPI_FC);
}
wr32(E1000_IPCNFG, ipcnfg);
wr32(E1000_EEER, eeer);
rd32(E1000_IPCNFG);
rd32(E1000_EEER);
out:
return ret_val;
}
/**
* igb_set_eee_i354 - Enable/disable EEE support
* @hw: pointer to the HW structure
*
* Enable/disable EEE legacy mode based on setting in dev_spec structure.
*
**/
s32 igb_set_eee_i354(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val = 0;
u16 phy_data;
if ((hw->phy.media_type != e1000_media_type_copper) ||
(phy->id != M88E1545_E_PHY_ID))
goto out;
if (!hw->dev_spec._82575.eee_disable) {
/* Switch to PHY page 18. */
ret_val = phy->ops.write_reg(hw, E1000_M88E1545_PAGE_ADDR, 18);
if (ret_val)
goto out;
ret_val = phy->ops.read_reg(hw, E1000_M88E1545_EEE_CTRL_1,
&phy_data);
if (ret_val)
goto out;
phy_data |= E1000_M88E1545_EEE_CTRL_1_MS;
ret_val = phy->ops.write_reg(hw, E1000_M88E1545_EEE_CTRL_1,
phy_data);
if (ret_val)
goto out;
/* Return the PHY to page 0. */
ret_val = phy->ops.write_reg(hw, E1000_M88E1545_PAGE_ADDR, 0);
if (ret_val)
goto out;
/* Turn on EEE advertisement. */
ret_val = igb_read_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354,
E1000_EEE_ADV_DEV_I354,
&phy_data);
if (ret_val)
goto out;
phy_data |= E1000_EEE_ADV_100_SUPPORTED |
E1000_EEE_ADV_1000_SUPPORTED;
ret_val = igb_write_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354,
E1000_EEE_ADV_DEV_I354,
phy_data);
} else {
/* Turn off EEE advertisement. */
ret_val = igb_read_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354,
E1000_EEE_ADV_DEV_I354,
&phy_data);
if (ret_val)
goto out;
phy_data &= ~(E1000_EEE_ADV_100_SUPPORTED |
E1000_EEE_ADV_1000_SUPPORTED);
ret_val = igb_write_xmdio_reg(hw, E1000_EEE_ADV_ADDR_I354,
E1000_EEE_ADV_DEV_I354,
phy_data);
}
out:
return ret_val;
}
/**
* igb_get_eee_status_i354 - Get EEE status
* @hw: pointer to the HW structure
* @status: EEE status
*
* Get EEE status by guessing based on whether Tx or Rx LPI indications have
* been received.
**/
s32 igb_get_eee_status_i354(struct e1000_hw *hw, bool *status)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val = 0;
u16 phy_data;
/* Check if EEE is supported on this device. */
if ((hw->phy.media_type != e1000_media_type_copper) ||
(phy->id != M88E1545_E_PHY_ID))
goto out;
ret_val = igb_read_xmdio_reg(hw, E1000_PCS_STATUS_ADDR_I354,
E1000_PCS_STATUS_DEV_I354,
&phy_data);
if (ret_val)
goto out;
*status = phy_data & (E1000_PCS_STATUS_TX_LPI_RCVD |
E1000_PCS_STATUS_RX_LPI_RCVD) ? true : false;
out:
return ret_val;
}
static const u8 e1000_emc_temp_data[4] = {
E1000_EMC_INTERNAL_DATA,
E1000_EMC_DIODE1_DATA,
E1000_EMC_DIODE2_DATA,
E1000_EMC_DIODE3_DATA
};
static const u8 e1000_emc_therm_limit[4] = {
E1000_EMC_INTERNAL_THERM_LIMIT,
E1000_EMC_DIODE1_THERM_LIMIT,
E1000_EMC_DIODE2_THERM_LIMIT,
E1000_EMC_DIODE3_THERM_LIMIT
};
/**
* igb_get_thermal_sensor_data_generic - Gathers thermal sensor data
* @hw: pointer to hardware structure
*
* Updates the temperatures in mac.thermal_sensor_data
**/
s32 igb_get_thermal_sensor_data_generic(struct e1000_hw *hw)
{
s32 status = E1000_SUCCESS;
u16 ets_offset;
u16 ets_cfg;
u16 ets_sensor;
u8 num_sensors;
u8 sensor_index;
u8 sensor_location;
u8 i;
struct e1000_thermal_sensor_data *data = &hw->mac.thermal_sensor_data;
if ((hw->mac.type != e1000_i350) || (hw->bus.func != 0))
return E1000_NOT_IMPLEMENTED;
data->sensor[0].temp = (rd32(E1000_THMJT) & 0xFF);
/* Return the internal sensor only if ETS is unsupported */
hw->nvm.ops.read(hw, NVM_ETS_CFG, 1, &ets_offset);
if ((ets_offset == 0x0000) || (ets_offset == 0xFFFF))
return status;
hw->nvm.ops.read(hw, ets_offset, 1, &ets_cfg);
if (((ets_cfg & NVM_ETS_TYPE_MASK) >> NVM_ETS_TYPE_SHIFT)
!= NVM_ETS_TYPE_EMC)
return E1000_NOT_IMPLEMENTED;
num_sensors = (ets_cfg & NVM_ETS_NUM_SENSORS_MASK);
if (num_sensors > E1000_MAX_SENSORS)
num_sensors = E1000_MAX_SENSORS;
for (i = 1; i < num_sensors; i++) {
hw->nvm.ops.read(hw, (ets_offset + i), 1, &ets_sensor);
sensor_index = ((ets_sensor & NVM_ETS_DATA_INDEX_MASK) >>
NVM_ETS_DATA_INDEX_SHIFT);
sensor_location = ((ets_sensor & NVM_ETS_DATA_LOC_MASK) >>
NVM_ETS_DATA_LOC_SHIFT);
if (sensor_location != 0)
hw->phy.ops.read_i2c_byte(hw,
e1000_emc_temp_data[sensor_index],
E1000_I2C_THERMAL_SENSOR_ADDR,
&data->sensor[i].temp);
}
return status;
}
/**
* igb_init_thermal_sensor_thresh_generic - Sets thermal sensor thresholds
* @hw: pointer to hardware structure
*
* Sets the thermal sensor thresholds according to the NVM map
* and save off the threshold and location values into mac.thermal_sensor_data
**/
s32 igb_init_thermal_sensor_thresh_generic(struct e1000_hw *hw)
{
s32 status = E1000_SUCCESS;
u16 ets_offset;
u16 ets_cfg;
u16 ets_sensor;
u8 low_thresh_delta;
u8 num_sensors;
u8 sensor_index;
u8 sensor_location;
u8 therm_limit;
u8 i;
struct e1000_thermal_sensor_data *data = &hw->mac.thermal_sensor_data;
if ((hw->mac.type != e1000_i350) || (hw->bus.func != 0))
return E1000_NOT_IMPLEMENTED;
memset(data, 0, sizeof(struct e1000_thermal_sensor_data));
data->sensor[0].location = 0x1;
data->sensor[0].caution_thresh =
(rd32(E1000_THHIGHTC) & 0xFF);
data->sensor[0].max_op_thresh =
(rd32(E1000_THLOWTC) & 0xFF);
/* Return the internal sensor only if ETS is unsupported */
hw->nvm.ops.read(hw, NVM_ETS_CFG, 1, &ets_offset);
if ((ets_offset == 0x0000) || (ets_offset == 0xFFFF))
return status;
hw->nvm.ops.read(hw, ets_offset, 1, &ets_cfg);
if (((ets_cfg & NVM_ETS_TYPE_MASK) >> NVM_ETS_TYPE_SHIFT)
!= NVM_ETS_TYPE_EMC)
return E1000_NOT_IMPLEMENTED;
low_thresh_delta = ((ets_cfg & NVM_ETS_LTHRES_DELTA_MASK) >>
NVM_ETS_LTHRES_DELTA_SHIFT);
num_sensors = (ets_cfg & NVM_ETS_NUM_SENSORS_MASK);
for (i = 1; i <= num_sensors; i++) {
hw->nvm.ops.read(hw, (ets_offset + i), 1, &ets_sensor);
sensor_index = ((ets_sensor & NVM_ETS_DATA_INDEX_MASK) >>
NVM_ETS_DATA_INDEX_SHIFT);
sensor_location = ((ets_sensor & NVM_ETS_DATA_LOC_MASK) >>
NVM_ETS_DATA_LOC_SHIFT);
therm_limit = ets_sensor & NVM_ETS_DATA_HTHRESH_MASK;
hw->phy.ops.write_i2c_byte(hw,
e1000_emc_therm_limit[sensor_index],
E1000_I2C_THERMAL_SENSOR_ADDR,
therm_limit);
if ((i < E1000_MAX_SENSORS) && (sensor_location != 0)) {
data->sensor[i].location = sensor_location;
data->sensor[i].caution_thresh = therm_limit;
data->sensor[i].max_op_thresh = therm_limit -
low_thresh_delta;
}
}
return status;
}
static struct e1000_mac_operations e1000_mac_ops_82575 = {
.init_hw = igb_init_hw_82575,
.check_for_link = igb_check_for_link_82575,
.rar_set = igb_rar_set,
.read_mac_addr = igb_read_mac_addr_82575,
.get_speed_and_duplex = igb_get_speed_and_duplex_copper,
#ifdef CONFIG_IGB_HWMON
.get_thermal_sensor_data = igb_get_thermal_sensor_data_generic,
.init_thermal_sensor_thresh = igb_init_thermal_sensor_thresh_generic,
#endif
};
static struct e1000_phy_operations e1000_phy_ops_82575 = {
.acquire = igb_acquire_phy_82575,
.get_cfg_done = igb_get_cfg_done_82575,
.release = igb_release_phy_82575,
.write_i2c_byte = igb_write_i2c_byte,
.read_i2c_byte = igb_read_i2c_byte,
};
static struct e1000_nvm_operations e1000_nvm_ops_82575 = {
.acquire = igb_acquire_nvm_82575,
.read = igb_read_nvm_eerd,
.release = igb_release_nvm_82575,
.write = igb_write_nvm_spi,
};
const struct e1000_info e1000_82575_info = {
.get_invariants = igb_get_invariants_82575,
.mac_ops = &e1000_mac_ops_82575,
.phy_ops = &e1000_phy_ops_82575,
.nvm_ops = &e1000_nvm_ops_82575,
};
| gpl-2.0 |
LeeDroid-/LeeDrOiD-Hima-M9 | tools/perf/util/hist.c | 2076 | 23671 | #include "annotate.h"
#include "util.h"
#include "build-id.h"
#include "hist.h"
#include "session.h"
#include "sort.h"
#include "evsel.h"
#include <math.h>
static bool hists__filter_entry_by_dso(struct hists *hists,
struct hist_entry *he);
static bool hists__filter_entry_by_thread(struct hists *hists,
struct hist_entry *he);
static bool hists__filter_entry_by_symbol(struct hists *hists,
struct hist_entry *he);
enum hist_filter {
HIST_FILTER__DSO,
HIST_FILTER__THREAD,
HIST_FILTER__PARENT,
HIST_FILTER__SYMBOL,
};
struct callchain_param callchain_param = {
.mode = CHAIN_GRAPH_REL,
.min_percent = 0.5,
.order = ORDER_CALLEE
};
u16 hists__col_len(struct hists *hists, enum hist_column col)
{
return hists->col_len[col];
}
void hists__set_col_len(struct hists *hists, enum hist_column col, u16 len)
{
hists->col_len[col] = len;
}
bool hists__new_col_len(struct hists *hists, enum hist_column col, u16 len)
{
if (len > hists__col_len(hists, col)) {
hists__set_col_len(hists, col, len);
return true;
}
return false;
}
void hists__reset_col_len(struct hists *hists)
{
enum hist_column col;
for (col = 0; col < HISTC_NR_COLS; ++col)
hists__set_col_len(hists, col, 0);
}
static void hists__set_unres_dso_col_len(struct hists *hists, int dso)
{
const unsigned int unresolved_col_width = BITS_PER_LONG / 4;
if (hists__col_len(hists, dso) < unresolved_col_width &&
!symbol_conf.col_width_list_str && !symbol_conf.field_sep &&
!symbol_conf.dso_list)
hists__set_col_len(hists, dso, unresolved_col_width);
}
void hists__calc_col_len(struct hists *hists, struct hist_entry *h)
{
const unsigned int unresolved_col_width = BITS_PER_LONG / 4;
int symlen;
u16 len;
if (h->ms.sym)
hists__new_col_len(hists, HISTC_SYMBOL, h->ms.sym->namelen + 4);
else {
symlen = unresolved_col_width + 4 + 2;
hists__new_col_len(hists, HISTC_SYMBOL, symlen);
hists__set_unres_dso_col_len(hists, HISTC_DSO);
}
len = thread__comm_len(h->thread);
if (hists__new_col_len(hists, HISTC_COMM, len))
hists__set_col_len(hists, HISTC_THREAD, len + 6);
if (h->ms.map) {
len = dso__name_len(h->ms.map->dso);
hists__new_col_len(hists, HISTC_DSO, len);
}
if (h->parent)
hists__new_col_len(hists, HISTC_PARENT, h->parent->namelen);
if (h->branch_info) {
/*
* +4 accounts for '[x] ' priv level info
* +2 account of 0x prefix on raw addresses
*/
if (h->branch_info->from.sym) {
symlen = (int)h->branch_info->from.sym->namelen + 4;
hists__new_col_len(hists, HISTC_SYMBOL_FROM, symlen);
symlen = dso__name_len(h->branch_info->from.map->dso);
hists__new_col_len(hists, HISTC_DSO_FROM, symlen);
} else {
symlen = unresolved_col_width + 4 + 2;
hists__new_col_len(hists, HISTC_SYMBOL_FROM, symlen);
hists__set_unres_dso_col_len(hists, HISTC_DSO_FROM);
}
if (h->branch_info->to.sym) {
symlen = (int)h->branch_info->to.sym->namelen + 4;
hists__new_col_len(hists, HISTC_SYMBOL_TO, symlen);
symlen = dso__name_len(h->branch_info->to.map->dso);
hists__new_col_len(hists, HISTC_DSO_TO, symlen);
} else {
symlen = unresolved_col_width + 4 + 2;
hists__new_col_len(hists, HISTC_SYMBOL_TO, symlen);
hists__set_unres_dso_col_len(hists, HISTC_DSO_TO);
}
}
if (h->mem_info) {
/*
* +4 accounts for '[x] ' priv level info
* +2 account of 0x prefix on raw addresses
*/
if (h->mem_info->daddr.sym) {
symlen = (int)h->mem_info->daddr.sym->namelen + 4
+ unresolved_col_width + 2;
hists__new_col_len(hists, HISTC_MEM_DADDR_SYMBOL,
symlen);
} else {
symlen = unresolved_col_width + 4 + 2;
hists__new_col_len(hists, HISTC_MEM_DADDR_SYMBOL,
symlen);
}
if (h->mem_info->daddr.map) {
symlen = dso__name_len(h->mem_info->daddr.map->dso);
hists__new_col_len(hists, HISTC_MEM_DADDR_DSO,
symlen);
} else {
symlen = unresolved_col_width + 4 + 2;
hists__set_unres_dso_col_len(hists, HISTC_MEM_DADDR_DSO);
}
} else {
symlen = unresolved_col_width + 4 + 2;
hists__new_col_len(hists, HISTC_MEM_DADDR_SYMBOL, symlen);
hists__set_unres_dso_col_len(hists, HISTC_MEM_DADDR_DSO);
}
hists__new_col_len(hists, HISTC_MEM_LOCKED, 6);
hists__new_col_len(hists, HISTC_MEM_TLB, 22);
hists__new_col_len(hists, HISTC_MEM_SNOOP, 12);
hists__new_col_len(hists, HISTC_MEM_LVL, 21 + 3);
hists__new_col_len(hists, HISTC_LOCAL_WEIGHT, 12);
hists__new_col_len(hists, HISTC_GLOBAL_WEIGHT, 12);
}
void hists__output_recalc_col_len(struct hists *hists, int max_rows)
{
struct rb_node *next = rb_first(&hists->entries);
struct hist_entry *n;
int row = 0;
hists__reset_col_len(hists);
while (next && row++ < max_rows) {
n = rb_entry(next, struct hist_entry, rb_node);
if (!n->filtered)
hists__calc_col_len(hists, n);
next = rb_next(&n->rb_node);
}
}
static void hist_entry__add_cpumode_period(struct hist_entry *he,
unsigned int cpumode, u64 period)
{
switch (cpumode) {
case PERF_RECORD_MISC_KERNEL:
he->stat.period_sys += period;
break;
case PERF_RECORD_MISC_USER:
he->stat.period_us += period;
break;
case PERF_RECORD_MISC_GUEST_KERNEL:
he->stat.period_guest_sys += period;
break;
case PERF_RECORD_MISC_GUEST_USER:
he->stat.period_guest_us += period;
break;
default:
break;
}
}
static void he_stat__add_period(struct he_stat *he_stat, u64 period,
u64 weight)
{
he_stat->period += period;
he_stat->weight += weight;
he_stat->nr_events += 1;
}
static void he_stat__add_stat(struct he_stat *dest, struct he_stat *src)
{
dest->period += src->period;
dest->period_sys += src->period_sys;
dest->period_us += src->period_us;
dest->period_guest_sys += src->period_guest_sys;
dest->period_guest_us += src->period_guest_us;
dest->nr_events += src->nr_events;
dest->weight += src->weight;
}
static void hist_entry__decay(struct hist_entry *he)
{
he->stat.period = (he->stat.period * 7) / 8;
he->stat.nr_events = (he->stat.nr_events * 7) / 8;
/* XXX need decay for weight too? */
}
static bool hists__decay_entry(struct hists *hists, struct hist_entry *he)
{
u64 prev_period = he->stat.period;
if (prev_period == 0)
return true;
hist_entry__decay(he);
if (!he->filtered)
hists->stats.total_period -= prev_period - he->stat.period;
return he->stat.period == 0;
}
static void __hists__decay_entries(struct hists *hists, bool zap_user,
bool zap_kernel, bool threaded)
{
struct rb_node *next = rb_first(&hists->entries);
struct hist_entry *n;
while (next) {
n = rb_entry(next, struct hist_entry, rb_node);
next = rb_next(&n->rb_node);
/*
* We may be annotating this, for instance, so keep it here in
* case some it gets new samples, we'll eventually free it when
* the user stops browsing and it agains gets fully decayed.
*/
if (((zap_user && n->level == '.') ||
(zap_kernel && n->level != '.') ||
hists__decay_entry(hists, n)) &&
!n->used) {
rb_erase(&n->rb_node, &hists->entries);
if (sort__need_collapse || threaded)
rb_erase(&n->rb_node_in, &hists->entries_collapsed);
hist_entry__free(n);
--hists->nr_entries;
}
}
}
void hists__decay_entries(struct hists *hists, bool zap_user, bool zap_kernel)
{
return __hists__decay_entries(hists, zap_user, zap_kernel, false);
}
void hists__decay_entries_threaded(struct hists *hists,
bool zap_user, bool zap_kernel)
{
return __hists__decay_entries(hists, zap_user, zap_kernel, true);
}
/*
* histogram, sorted on item, collects periods
*/
static struct hist_entry *hist_entry__new(struct hist_entry *template)
{
size_t callchain_size = symbol_conf.use_callchain ? sizeof(struct callchain_root) : 0;
struct hist_entry *he = zalloc(sizeof(*he) + callchain_size);
if (he != NULL) {
*he = *template;
if (he->ms.map)
he->ms.map->referenced = true;
if (he->branch_info) {
if (he->branch_info->from.map)
he->branch_info->from.map->referenced = true;
if (he->branch_info->to.map)
he->branch_info->to.map->referenced = true;
}
if (he->mem_info) {
if (he->mem_info->iaddr.map)
he->mem_info->iaddr.map->referenced = true;
if (he->mem_info->daddr.map)
he->mem_info->daddr.map->referenced = true;
}
if (symbol_conf.use_callchain)
callchain_init(he->callchain);
INIT_LIST_HEAD(&he->pairs.node);
}
return he;
}
void hists__inc_nr_entries(struct hists *hists, struct hist_entry *h)
{
if (!h->filtered) {
hists__calc_col_len(hists, h);
++hists->nr_entries;
hists->stats.total_period += h->stat.period;
}
}
static u8 symbol__parent_filter(const struct symbol *parent)
{
if (symbol_conf.exclude_other && parent == NULL)
return 1 << HIST_FILTER__PARENT;
return 0;
}
static struct hist_entry *add_hist_entry(struct hists *hists,
struct hist_entry *entry,
struct addr_location *al,
u64 period,
u64 weight)
{
struct rb_node **p;
struct rb_node *parent = NULL;
struct hist_entry *he;
int cmp;
pthread_mutex_lock(&hists->lock);
p = &hists->entries_in->rb_node;
while (*p != NULL) {
parent = *p;
he = rb_entry(parent, struct hist_entry, rb_node_in);
/*
* Make sure that it receives arguments in a same order as
* hist_entry__collapse() so that we can use an appropriate
* function when searching an entry regardless which sort
* keys were used.
*/
cmp = hist_entry__cmp(he, entry);
if (!cmp) {
he_stat__add_period(&he->stat, period, weight);
/* If the map of an existing hist_entry has
* become out-of-date due to an exec() or
* similar, update it. Otherwise we will
* mis-adjust symbol addresses when computing
* the history counter to increment.
*/
if (he->ms.map != entry->ms.map) {
he->ms.map = entry->ms.map;
if (he->ms.map)
he->ms.map->referenced = true;
}
goto out;
}
if (cmp < 0)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
he = hist_entry__new(entry);
if (!he)
goto out_unlock;
rb_link_node(&he->rb_node_in, parent, p);
rb_insert_color(&he->rb_node_in, hists->entries_in);
out:
hist_entry__add_cpumode_period(he, al->cpumode, period);
out_unlock:
pthread_mutex_unlock(&hists->lock);
return he;
}
struct hist_entry *__hists__add_mem_entry(struct hists *self,
struct addr_location *al,
struct symbol *sym_parent,
struct mem_info *mi,
u64 period,
u64 weight)
{
struct hist_entry entry = {
.thread = al->thread,
.ms = {
.map = al->map,
.sym = al->sym,
},
.stat = {
.period = period,
.weight = weight,
.nr_events = 1,
},
.cpu = al->cpu,
.ip = al->addr,
.level = al->level,
.parent = sym_parent,
.filtered = symbol__parent_filter(sym_parent),
.hists = self,
.mem_info = mi,
.branch_info = NULL,
};
return add_hist_entry(self, &entry, al, period, weight);
}
struct hist_entry *__hists__add_branch_entry(struct hists *self,
struct addr_location *al,
struct symbol *sym_parent,
struct branch_info *bi,
u64 period,
u64 weight)
{
struct hist_entry entry = {
.thread = al->thread,
.ms = {
.map = bi->to.map,
.sym = bi->to.sym,
},
.cpu = al->cpu,
.ip = bi->to.addr,
.level = al->level,
.stat = {
.period = period,
.nr_events = 1,
.weight = weight,
},
.parent = sym_parent,
.filtered = symbol__parent_filter(sym_parent),
.branch_info = bi,
.hists = self,
.mem_info = NULL,
};
return add_hist_entry(self, &entry, al, period, weight);
}
struct hist_entry *__hists__add_entry(struct hists *self,
struct addr_location *al,
struct symbol *sym_parent, u64 period,
u64 weight)
{
struct hist_entry entry = {
.thread = al->thread,
.ms = {
.map = al->map,
.sym = al->sym,
},
.cpu = al->cpu,
.ip = al->addr,
.level = al->level,
.stat = {
.period = period,
.nr_events = 1,
.weight = weight,
},
.parent = sym_parent,
.filtered = symbol__parent_filter(sym_parent),
.hists = self,
.branch_info = NULL,
.mem_info = NULL,
};
return add_hist_entry(self, &entry, al, period, weight);
}
int64_t
hist_entry__cmp(struct hist_entry *left, struct hist_entry *right)
{
struct sort_entry *se;
int64_t cmp = 0;
list_for_each_entry(se, &hist_entry__sort_list, list) {
cmp = se->se_cmp(left, right);
if (cmp)
break;
}
return cmp;
}
int64_t
hist_entry__collapse(struct hist_entry *left, struct hist_entry *right)
{
struct sort_entry *se;
int64_t cmp = 0;
list_for_each_entry(se, &hist_entry__sort_list, list) {
int64_t (*f)(struct hist_entry *, struct hist_entry *);
f = se->se_collapse ?: se->se_cmp;
cmp = f(left, right);
if (cmp)
break;
}
return cmp;
}
void hist_entry__free(struct hist_entry *he)
{
free(he->branch_info);
free(he->mem_info);
free(he);
}
/*
* collapse the histogram
*/
static bool hists__collapse_insert_entry(struct hists *hists __maybe_unused,
struct rb_root *root,
struct hist_entry *he)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent = NULL;
struct hist_entry *iter;
int64_t cmp;
while (*p != NULL) {
parent = *p;
iter = rb_entry(parent, struct hist_entry, rb_node_in);
cmp = hist_entry__collapse(iter, he);
if (!cmp) {
he_stat__add_stat(&iter->stat, &he->stat);
if (symbol_conf.use_callchain) {
callchain_cursor_reset(&callchain_cursor);
callchain_merge(&callchain_cursor,
iter->callchain,
he->callchain);
}
hist_entry__free(he);
return false;
}
if (cmp < 0)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&he->rb_node_in, parent, p);
rb_insert_color(&he->rb_node_in, root);
return true;
}
static struct rb_root *hists__get_rotate_entries_in(struct hists *hists)
{
struct rb_root *root;
pthread_mutex_lock(&hists->lock);
root = hists->entries_in;
if (++hists->entries_in > &hists->entries_in_array[1])
hists->entries_in = &hists->entries_in_array[0];
pthread_mutex_unlock(&hists->lock);
return root;
}
static void hists__apply_filters(struct hists *hists, struct hist_entry *he)
{
hists__filter_entry_by_dso(hists, he);
hists__filter_entry_by_thread(hists, he);
hists__filter_entry_by_symbol(hists, he);
}
static void __hists__collapse_resort(struct hists *hists, bool threaded)
{
struct rb_root *root;
struct rb_node *next;
struct hist_entry *n;
if (!sort__need_collapse && !threaded)
return;
root = hists__get_rotate_entries_in(hists);
next = rb_first(root);
while (next) {
n = rb_entry(next, struct hist_entry, rb_node_in);
next = rb_next(&n->rb_node_in);
rb_erase(&n->rb_node_in, root);
if (hists__collapse_insert_entry(hists, &hists->entries_collapsed, n)) {
/*
* If it wasn't combined with one of the entries already
* collapsed, we need to apply the filters that may have
* been set by, say, the hist_browser.
*/
hists__apply_filters(hists, n);
}
}
}
void hists__collapse_resort(struct hists *hists)
{
return __hists__collapse_resort(hists, false);
}
void hists__collapse_resort_threaded(struct hists *hists)
{
return __hists__collapse_resort(hists, true);
}
/*
* reverse the map, sort on period.
*/
static int period_cmp(u64 period_a, u64 period_b)
{
if (period_a > period_b)
return 1;
if (period_a < period_b)
return -1;
return 0;
}
static int hist_entry__sort_on_period(struct hist_entry *a,
struct hist_entry *b)
{
int ret;
int i, nr_members;
struct perf_evsel *evsel;
struct hist_entry *pair;
u64 *periods_a, *periods_b;
ret = period_cmp(a->stat.period, b->stat.period);
if (ret || !symbol_conf.event_group)
return ret;
evsel = hists_to_evsel(a->hists);
nr_members = evsel->nr_members;
if (nr_members <= 1)
return ret;
periods_a = zalloc(sizeof(periods_a) * nr_members);
periods_b = zalloc(sizeof(periods_b) * nr_members);
if (!periods_a || !periods_b)
goto out;
list_for_each_entry(pair, &a->pairs.head, pairs.node) {
evsel = hists_to_evsel(pair->hists);
periods_a[perf_evsel__group_idx(evsel)] = pair->stat.period;
}
list_for_each_entry(pair, &b->pairs.head, pairs.node) {
evsel = hists_to_evsel(pair->hists);
periods_b[perf_evsel__group_idx(evsel)] = pair->stat.period;
}
for (i = 1; i < nr_members; i++) {
ret = period_cmp(periods_a[i], periods_b[i]);
if (ret)
break;
}
out:
free(periods_a);
free(periods_b);
return ret;
}
static void __hists__insert_output_entry(struct rb_root *entries,
struct hist_entry *he,
u64 min_callchain_hits)
{
struct rb_node **p = &entries->rb_node;
struct rb_node *parent = NULL;
struct hist_entry *iter;
if (symbol_conf.use_callchain)
callchain_param.sort(&he->sorted_chain, he->callchain,
min_callchain_hits, &callchain_param);
while (*p != NULL) {
parent = *p;
iter = rb_entry(parent, struct hist_entry, rb_node);
if (hist_entry__sort_on_period(he, iter) > 0)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&he->rb_node, parent, p);
rb_insert_color(&he->rb_node, entries);
}
static void __hists__output_resort(struct hists *hists, bool threaded)
{
struct rb_root *root;
struct rb_node *next;
struct hist_entry *n;
u64 min_callchain_hits;
min_callchain_hits = hists->stats.total_period * (callchain_param.min_percent / 100);
if (sort__need_collapse || threaded)
root = &hists->entries_collapsed;
else
root = hists->entries_in;
next = rb_first(root);
hists->entries = RB_ROOT;
hists->nr_entries = 0;
hists->stats.total_period = 0;
hists__reset_col_len(hists);
while (next) {
n = rb_entry(next, struct hist_entry, rb_node_in);
next = rb_next(&n->rb_node_in);
__hists__insert_output_entry(&hists->entries, n, min_callchain_hits);
hists__inc_nr_entries(hists, n);
}
}
void hists__output_resort(struct hists *hists)
{
return __hists__output_resort(hists, false);
}
void hists__output_resort_threaded(struct hists *hists)
{
return __hists__output_resort(hists, true);
}
static void hists__remove_entry_filter(struct hists *hists, struct hist_entry *h,
enum hist_filter filter)
{
h->filtered &= ~(1 << filter);
if (h->filtered)
return;
++hists->nr_entries;
if (h->ms.unfolded)
hists->nr_entries += h->nr_rows;
h->row_offset = 0;
hists->stats.total_period += h->stat.period;
hists->stats.nr_events[PERF_RECORD_SAMPLE] += h->stat.nr_events;
hists__calc_col_len(hists, h);
}
static bool hists__filter_entry_by_dso(struct hists *hists,
struct hist_entry *he)
{
if (hists->dso_filter != NULL &&
(he->ms.map == NULL || he->ms.map->dso != hists->dso_filter)) {
he->filtered |= (1 << HIST_FILTER__DSO);
return true;
}
return false;
}
void hists__filter_by_dso(struct hists *hists)
{
struct rb_node *nd;
hists->nr_entries = hists->stats.total_period = 0;
hists->stats.nr_events[PERF_RECORD_SAMPLE] = 0;
hists__reset_col_len(hists);
for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
if (symbol_conf.exclude_other && !h->parent)
continue;
if (hists__filter_entry_by_dso(hists, h))
continue;
hists__remove_entry_filter(hists, h, HIST_FILTER__DSO);
}
}
static bool hists__filter_entry_by_thread(struct hists *hists,
struct hist_entry *he)
{
if (hists->thread_filter != NULL &&
he->thread != hists->thread_filter) {
he->filtered |= (1 << HIST_FILTER__THREAD);
return true;
}
return false;
}
void hists__filter_by_thread(struct hists *hists)
{
struct rb_node *nd;
hists->nr_entries = hists->stats.total_period = 0;
hists->stats.nr_events[PERF_RECORD_SAMPLE] = 0;
hists__reset_col_len(hists);
for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
if (hists__filter_entry_by_thread(hists, h))
continue;
hists__remove_entry_filter(hists, h, HIST_FILTER__THREAD);
}
}
static bool hists__filter_entry_by_symbol(struct hists *hists,
struct hist_entry *he)
{
if (hists->symbol_filter_str != NULL &&
(!he->ms.sym || strstr(he->ms.sym->name,
hists->symbol_filter_str) == NULL)) {
he->filtered |= (1 << HIST_FILTER__SYMBOL);
return true;
}
return false;
}
void hists__filter_by_symbol(struct hists *hists)
{
struct rb_node *nd;
hists->nr_entries = hists->stats.total_period = 0;
hists->stats.nr_events[PERF_RECORD_SAMPLE] = 0;
hists__reset_col_len(hists);
for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
if (hists__filter_entry_by_symbol(hists, h))
continue;
hists__remove_entry_filter(hists, h, HIST_FILTER__SYMBOL);
}
}
int hist_entry__inc_addr_samples(struct hist_entry *he, int evidx, u64 ip)
{
return symbol__inc_addr_samples(he->ms.sym, he->ms.map, evidx, ip);
}
int hist_entry__annotate(struct hist_entry *he, size_t privsize)
{
return symbol__annotate(he->ms.sym, he->ms.map, privsize);
}
void events_stats__inc(struct events_stats *stats, u32 type)
{
++stats->nr_events[0];
++stats->nr_events[type];
}
void hists__inc_nr_events(struct hists *hists, u32 type)
{
events_stats__inc(&hists->stats, type);
}
static struct hist_entry *hists__add_dummy_entry(struct hists *hists,
struct hist_entry *pair)
{
struct rb_root *root;
struct rb_node **p;
struct rb_node *parent = NULL;
struct hist_entry *he;
int cmp;
if (sort__need_collapse)
root = &hists->entries_collapsed;
else
root = hists->entries_in;
p = &root->rb_node;
while (*p != NULL) {
parent = *p;
he = rb_entry(parent, struct hist_entry, rb_node_in);
cmp = hist_entry__collapse(he, pair);
if (!cmp)
goto out;
if (cmp < 0)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
he = hist_entry__new(pair);
if (he) {
memset(&he->stat, 0, sizeof(he->stat));
he->hists = hists;
rb_link_node(&he->rb_node_in, parent, p);
rb_insert_color(&he->rb_node_in, root);
hists__inc_nr_entries(hists, he);
}
out:
return he;
}
static struct hist_entry *hists__find_entry(struct hists *hists,
struct hist_entry *he)
{
struct rb_node *n;
if (sort__need_collapse)
n = hists->entries_collapsed.rb_node;
else
n = hists->entries_in->rb_node;
while (n) {
struct hist_entry *iter = rb_entry(n, struct hist_entry, rb_node_in);
int64_t cmp = hist_entry__collapse(iter, he);
if (cmp < 0)
n = n->rb_left;
else if (cmp > 0)
n = n->rb_right;
else
return iter;
}
return NULL;
}
/*
* Look for pairs to link to the leader buckets (hist_entries):
*/
void hists__match(struct hists *leader, struct hists *other)
{
struct rb_root *root;
struct rb_node *nd;
struct hist_entry *pos, *pair;
if (sort__need_collapse)
root = &leader->entries_collapsed;
else
root = leader->entries_in;
for (nd = rb_first(root); nd; nd = rb_next(nd)) {
pos = rb_entry(nd, struct hist_entry, rb_node_in);
pair = hists__find_entry(other, pos);
if (pair)
hist_entry__add_pair(pair, pos);
}
}
/*
* Look for entries in the other hists that are not present in the leader, if
* we find them, just add a dummy entry on the leader hists, with period=0,
* nr_events=0, to serve as the list header.
*/
int hists__link(struct hists *leader, struct hists *other)
{
struct rb_root *root;
struct rb_node *nd;
struct hist_entry *pos, *pair;
if (sort__need_collapse)
root = &other->entries_collapsed;
else
root = other->entries_in;
for (nd = rb_first(root); nd; nd = rb_next(nd)) {
pos = rb_entry(nd, struct hist_entry, rb_node_in);
if (!hist_entry__has_pairs(pos)) {
pair = hists__add_dummy_entry(leader, pos);
if (pair == NULL)
return -1;
hist_entry__add_pair(pos, pair);
}
}
return 0;
}
| gpl-2.0 |
olegfusion/IM-A830S_kernel | arch/s390/mm/init.c | 2588 | 6046 | /*
* arch/s390/mm/init.c
*
* S390 version
* Copyright (C) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Hartmut Penner (hp@de.ibm.com)
*
* Derived from "arch/i386/mm/init.c"
* Copyright (C) 1995 Linus Torvalds
*/
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/bootmem.h>
#include <linux/pfn.h>
#include <linux/poison.h>
#include <linux/initrd.h>
#include <linux/gfp.h>
#include <asm/processor.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/dma.h>
#include <asm/lowcore.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/sections.h>
pgd_t swapper_pg_dir[PTRS_PER_PGD] __attribute__((__aligned__(PAGE_SIZE)));
unsigned long empty_zero_page, zero_page_mask;
EXPORT_SYMBOL(empty_zero_page);
static unsigned long setup_zero_pages(void)
{
struct cpuid cpu_id;
unsigned int order;
unsigned long size;
struct page *page;
int i;
get_cpu_id(&cpu_id);
switch (cpu_id.machine) {
case 0x9672: /* g5 */
case 0x2064: /* z900 */
case 0x2066: /* z900 */
case 0x2084: /* z990 */
case 0x2086: /* z990 */
case 0x2094: /* z9-109 */
case 0x2096: /* z9-109 */
order = 0;
break;
case 0x2097: /* z10 */
case 0x2098: /* z10 */
default:
order = 2;
break;
}
empty_zero_page = __get_free_pages(GFP_KERNEL | __GFP_ZERO, order);
if (!empty_zero_page)
panic("Out of memory in setup_zero_pages");
page = virt_to_page((void *) empty_zero_page);
split_page(page, order);
for (i = 1 << order; i > 0; i--) {
SetPageReserved(page);
page++;
}
size = PAGE_SIZE << order;
zero_page_mask = (size - 1) & PAGE_MASK;
return 1UL << order;
}
/*
* paging_init() sets up the page tables
*/
void __init paging_init(void)
{
unsigned long max_zone_pfns[MAX_NR_ZONES];
unsigned long pgd_type;
init_mm.pgd = swapper_pg_dir;
S390_lowcore.kernel_asce = __pa(init_mm.pgd) & PAGE_MASK;
#ifdef CONFIG_64BIT
/* A three level page table (4TB) is enough for the kernel space. */
S390_lowcore.kernel_asce |= _ASCE_TYPE_REGION3 | _ASCE_TABLE_LENGTH;
pgd_type = _REGION3_ENTRY_EMPTY;
#else
S390_lowcore.kernel_asce |= _ASCE_TABLE_LENGTH;
pgd_type = _SEGMENT_ENTRY_EMPTY;
#endif
clear_table((unsigned long *) init_mm.pgd, pgd_type,
sizeof(unsigned long)*2048);
vmem_map_init();
/* enable virtual mapping in kernel mode */
__ctl_load(S390_lowcore.kernel_asce, 1, 1);
__ctl_load(S390_lowcore.kernel_asce, 7, 7);
__ctl_load(S390_lowcore.kernel_asce, 13, 13);
arch_local_irq_restore(4UL << (BITS_PER_LONG - 8));
atomic_set(&init_mm.context.attach_count, 1);
sparse_memory_present_with_active_regions(MAX_NUMNODES);
sparse_init();
memset(max_zone_pfns, 0, sizeof(max_zone_pfns));
max_zone_pfns[ZONE_DMA] = PFN_DOWN(MAX_DMA_ADDRESS);
max_zone_pfns[ZONE_NORMAL] = max_low_pfn;
free_area_init_nodes(max_zone_pfns);
fault_init();
}
void __init mem_init(void)
{
unsigned long codesize, reservedpages, datasize, initsize;
max_mapnr = num_physpages = max_low_pfn;
high_memory = (void *) __va(max_low_pfn * PAGE_SIZE);
/* Setup guest page hinting */
cmma_init();
/* this will put all low memory onto the freelists */
totalram_pages += free_all_bootmem();
totalram_pages -= setup_zero_pages(); /* Setup zeroed pages. */
reservedpages = 0;
codesize = (unsigned long) &_etext - (unsigned long) &_text;
datasize = (unsigned long) &_edata - (unsigned long) &_etext;
initsize = (unsigned long) &__init_end - (unsigned long) &__init_begin;
printk("Memory: %luk/%luk available (%ldk kernel code, %ldk reserved, %ldk data, %ldk init)\n",
nr_free_pages() << (PAGE_SHIFT-10),
max_mapnr << (PAGE_SHIFT-10),
codesize >> 10,
reservedpages << (PAGE_SHIFT-10),
datasize >>10,
initsize >> 10);
printk("Write protected kernel read-only data: %#lx - %#lx\n",
(unsigned long)&_stext,
PFN_ALIGN((unsigned long)&_eshared) - 1);
}
#ifdef CONFIG_DEBUG_PAGEALLOC
void kernel_map_pages(struct page *page, int numpages, int enable)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
unsigned long address;
int i;
for (i = 0; i < numpages; i++) {
address = page_to_phys(page + i);
pgd = pgd_offset_k(address);
pud = pud_offset(pgd, address);
pmd = pmd_offset(pud, address);
pte = pte_offset_kernel(pmd, address);
if (!enable) {
__ptep_ipte(address, pte);
pte_val(*pte) = _PAGE_TYPE_EMPTY;
continue;
}
*pte = mk_pte_phys(address, __pgprot(_PAGE_TYPE_RW));
/* Flush cpu write queue. */
mb();
}
}
#endif
void free_init_pages(char *what, unsigned long begin, unsigned long end)
{
unsigned long addr = begin;
if (begin >= end)
return;
for (; addr < end; addr += PAGE_SIZE) {
ClearPageReserved(virt_to_page(addr));
init_page_count(virt_to_page(addr));
memset((void *)(addr & PAGE_MASK), POISON_FREE_INITMEM,
PAGE_SIZE);
free_page(addr);
totalram_pages++;
}
printk(KERN_INFO "Freeing %s: %luk freed\n", what, (end - begin) >> 10);
}
void free_initmem(void)
{
free_init_pages("unused kernel memory",
(unsigned long)&__init_begin,
(unsigned long)&__init_end);
}
#ifdef CONFIG_BLK_DEV_INITRD
void free_initrd_mem(unsigned long start, unsigned long end)
{
free_init_pages("initrd memory", start, end);
}
#endif
#ifdef CONFIG_MEMORY_HOTPLUG
int arch_add_memory(int nid, u64 start, u64 size)
{
struct pglist_data *pgdat;
struct zone *zone;
int rc;
pgdat = NODE_DATA(nid);
zone = pgdat->node_zones + ZONE_MOVABLE;
rc = vmem_add_mapping(start, size);
if (rc)
return rc;
rc = __add_pages(nid, zone, PFN_DOWN(start), PFN_DOWN(size));
if (rc)
vmem_remove_mapping(start, size);
return rc;
}
#endif /* CONFIG_MEMORY_HOTPLUG */
| gpl-2.0 |
bluechiptechnology/Rx3_linux_3.0.35_4.0.0 | arch/arm/mach-ks8695/board-micrel.c | 2588 | 1377 | /*
* arch/arm/mach-ks8695/board-micrel.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/gpio.h>
#include <mach/devices.h>
#include "generic.h"
#ifdef CONFIG_PCI
static int micrel_pci_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
return KS8695_IRQ_EXTERN0;
}
static struct ks8695_pci_cfg __initdata micrel_pci = {
.mode = KS8695_MODE_MINIPCI,
.map_irq = micrel_pci_map_irq,
};
#endif
static void __init micrel_init(void)
{
printk(KERN_INFO "Micrel KS8695 Development Board initializing\n");
ks8695_register_gpios();
#ifdef CONFIG_PCI
ks8695_init_pci(&micrel_pci);
#endif
/* Add devices */
ks8695_add_device_wan(); /* eth0 = WAN */
ks8695_add_device_lan(); /* eth1 = LAN */
}
MACHINE_START(KS8695, "KS8695 Centaur Development Board")
/* Maintainer: Micrel Semiconductor Inc. */
.boot_params = KS8695_SDRAM_PA + 0x100,
.map_io = ks8695_map_io,
.init_irq = ks8695_init_irq,
.init_machine = micrel_init,
.timer = &ks8695_timer,
MACHINE_END
| gpl-2.0 |
zparallax/amplitude_kernel_aosp | drivers/staging/media/go7007/snd-go7007.c | 5148 | 8107 | /*
* Copyright (C) 2005-2006 Micronas USA Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/vmalloc.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include "go7007-priv.h"
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
module_param_array(index, int, NULL, 0444);
module_param_array(id, charp, NULL, 0444);
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the go7007 audio driver");
MODULE_PARM_DESC(id, "ID string for the go7007 audio driver");
MODULE_PARM_DESC(enable, "Enable for the go7007 audio driver");
struct go7007_snd {
struct snd_card *card;
struct snd_pcm *pcm;
struct snd_pcm_substream *substream;
spinlock_t lock;
int w_idx;
int hw_ptr;
int avail;
int capturing;
};
static struct snd_pcm_hardware go7007_snd_capture_hw = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 4096,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 32,
};
static void parse_audio_stream_data(struct go7007 *go, u8 *buf, int length)
{
struct go7007_snd *gosnd = go->snd_context;
struct snd_pcm_runtime *runtime = gosnd->substream->runtime;
int frames = bytes_to_frames(runtime, length);
spin_lock(&gosnd->lock);
gosnd->hw_ptr += frames;
if (gosnd->hw_ptr >= runtime->buffer_size)
gosnd->hw_ptr -= runtime->buffer_size;
gosnd->avail += frames;
spin_unlock(&gosnd->lock);
if (gosnd->w_idx + length > runtime->dma_bytes) {
int cpy = runtime->dma_bytes - gosnd->w_idx;
memcpy(runtime->dma_area + gosnd->w_idx, buf, cpy);
length -= cpy;
buf += cpy;
gosnd->w_idx = 0;
}
memcpy(runtime->dma_area + gosnd->w_idx, buf, length);
gosnd->w_idx += length;
spin_lock(&gosnd->lock);
if (gosnd->avail < runtime->period_size) {
spin_unlock(&gosnd->lock);
return;
}
gosnd->avail -= runtime->period_size;
spin_unlock(&gosnd->lock);
if (gosnd->capturing)
snd_pcm_period_elapsed(gosnd->substream);
}
static int go7007_snd_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct go7007 *go = snd_pcm_substream_chip(substream);
unsigned int bytes;
bytes = params_buffer_bytes(hw_params);
if (substream->runtime->dma_bytes > 0)
vfree(substream->runtime->dma_area);
substream->runtime->dma_bytes = 0;
substream->runtime->dma_area = vmalloc(bytes);
if (substream->runtime->dma_area == NULL)
return -ENOMEM;
substream->runtime->dma_bytes = bytes;
go->audio_deliver = parse_audio_stream_data;
return 0;
}
static int go7007_snd_hw_free(struct snd_pcm_substream *substream)
{
struct go7007 *go = snd_pcm_substream_chip(substream);
go->audio_deliver = NULL;
if (substream->runtime->dma_bytes > 0)
vfree(substream->runtime->dma_area);
substream->runtime->dma_bytes = 0;
return 0;
}
static int go7007_snd_capture_open(struct snd_pcm_substream *substream)
{
struct go7007 *go = snd_pcm_substream_chip(substream);
struct go7007_snd *gosnd = go->snd_context;
unsigned long flags;
int r;
spin_lock_irqsave(&gosnd->lock, flags);
if (gosnd->substream == NULL) {
gosnd->substream = substream;
substream->runtime->hw = go7007_snd_capture_hw;
r = 0;
} else
r = -EBUSY;
spin_unlock_irqrestore(&gosnd->lock, flags);
return r;
}
static int go7007_snd_capture_close(struct snd_pcm_substream *substream)
{
struct go7007 *go = snd_pcm_substream_chip(substream);
struct go7007_snd *gosnd = go->snd_context;
gosnd->substream = NULL;
return 0;
}
static int go7007_snd_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int go7007_snd_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct go7007 *go = snd_pcm_substream_chip(substream);
struct go7007_snd *gosnd = go->snd_context;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
/* Just set a flag to indicate we should signal ALSA when
* sound comes in */
gosnd->capturing = 1;
return 0;
case SNDRV_PCM_TRIGGER_STOP:
gosnd->hw_ptr = gosnd->w_idx = gosnd->avail = 0;
gosnd->capturing = 0;
return 0;
default:
return -EINVAL;
}
}
static snd_pcm_uframes_t go7007_snd_pcm_pointer(struct snd_pcm_substream *substream)
{
struct go7007 *go = snd_pcm_substream_chip(substream);
struct go7007_snd *gosnd = go->snd_context;
return gosnd->hw_ptr;
}
static struct page *go7007_snd_pcm_page(struct snd_pcm_substream *substream,
unsigned long offset)
{
return vmalloc_to_page(substream->runtime->dma_area + offset);
}
static struct snd_pcm_ops go7007_snd_capture_ops = {
.open = go7007_snd_capture_open,
.close = go7007_snd_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = go7007_snd_hw_params,
.hw_free = go7007_snd_hw_free,
.prepare = go7007_snd_pcm_prepare,
.trigger = go7007_snd_pcm_trigger,
.pointer = go7007_snd_pcm_pointer,
.page = go7007_snd_pcm_page,
};
static int go7007_snd_free(struct snd_device *device)
{
struct go7007 *go = device->device_data;
kfree(go->snd_context);
go->snd_context = NULL;
if (--go->ref_count == 0)
kfree(go);
return 0;
}
static struct snd_device_ops go7007_snd_device_ops = {
.dev_free = go7007_snd_free,
};
int go7007_snd_init(struct go7007 *go)
{
static int dev;
struct go7007_snd *gosnd;
int ret = 0;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
gosnd = kmalloc(sizeof(struct go7007_snd), GFP_KERNEL);
if (gosnd == NULL)
return -ENOMEM;
spin_lock_init(&gosnd->lock);
gosnd->hw_ptr = gosnd->w_idx = gosnd->avail = 0;
gosnd->capturing = 0;
ret = snd_card_create(index[dev], id[dev], THIS_MODULE, 0,
&gosnd->card);
if (ret < 0) {
kfree(gosnd);
return ret;
}
ret = snd_device_new(gosnd->card, SNDRV_DEV_LOWLEVEL, go,
&go7007_snd_device_ops);
if (ret < 0) {
kfree(gosnd);
return ret;
}
snd_card_set_dev(gosnd->card, go->dev);
ret = snd_pcm_new(gosnd->card, "go7007", 0, 0, 1, &gosnd->pcm);
if (ret < 0) {
snd_card_free(gosnd->card);
kfree(gosnd);
return ret;
}
strncpy(gosnd->card->driver, "go7007", sizeof(gosnd->card->driver));
strncpy(gosnd->card->shortname, go->name, sizeof(gosnd->card->driver));
strncpy(gosnd->card->longname, gosnd->card->shortname,
sizeof(gosnd->card->longname));
gosnd->pcm->private_data = go;
snd_pcm_set_ops(gosnd->pcm, SNDRV_PCM_STREAM_CAPTURE,
&go7007_snd_capture_ops);
ret = snd_card_register(gosnd->card);
if (ret < 0) {
snd_card_free(gosnd->card);
kfree(gosnd);
return ret;
}
gosnd->substream = NULL;
go->snd_context = gosnd;
++dev;
++go->ref_count;
return 0;
}
EXPORT_SYMBOL(go7007_snd_init);
int go7007_snd_remove(struct go7007 *go)
{
struct go7007_snd *gosnd = go->snd_context;
snd_card_disconnect(gosnd->card);
snd_card_free_when_closed(gosnd->card);
return 0;
}
EXPORT_SYMBOL(go7007_snd_remove);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ivkos/kernel_i9500 | drivers/isdn/mISDN/timerdev.c | 5148 | 6860 | /*
*
* general timer device for using in ISDN stacks
*
* Author Karsten Keil <kkeil@novell.com>
*
* Copyright 2008 by Karsten Keil <kkeil@novell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/poll.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mISDNif.h>
#include <linux/mutex.h>
#include "core.h"
static DEFINE_MUTEX(mISDN_mutex);
static u_int *debug;
struct mISDNtimerdev {
int next_id;
struct list_head pending;
struct list_head expired;
wait_queue_head_t wait;
u_int work;
spinlock_t lock; /* protect lists */
};
struct mISDNtimer {
struct list_head list;
struct mISDNtimerdev *dev;
struct timer_list tl;
int id;
};
static int
mISDN_open(struct inode *ino, struct file *filep)
{
struct mISDNtimerdev *dev;
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s(%p,%p)\n", __func__, ino, filep);
dev = kmalloc(sizeof(struct mISDNtimerdev) , GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->next_id = 1;
INIT_LIST_HEAD(&dev->pending);
INIT_LIST_HEAD(&dev->expired);
spin_lock_init(&dev->lock);
dev->work = 0;
init_waitqueue_head(&dev->wait);
filep->private_data = dev;
__module_get(THIS_MODULE);
return nonseekable_open(ino, filep);
}
static int
mISDN_close(struct inode *ino, struct file *filep)
{
struct mISDNtimerdev *dev = filep->private_data;
struct mISDNtimer *timer, *next;
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s(%p,%p)\n", __func__, ino, filep);
list_for_each_entry_safe(timer, next, &dev->pending, list) {
del_timer(&timer->tl);
kfree(timer);
}
list_for_each_entry_safe(timer, next, &dev->expired, list) {
kfree(timer);
}
kfree(dev);
module_put(THIS_MODULE);
return 0;
}
static ssize_t
mISDN_read(struct file *filep, char __user *buf, size_t count, loff_t *off)
{
struct mISDNtimerdev *dev = filep->private_data;
struct mISDNtimer *timer;
u_long flags;
int ret = 0;
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s(%p, %p, %d, %p)\n", __func__,
filep, buf, (int)count, off);
if (list_empty(&dev->expired) && (dev->work == 0)) {
if (filep->f_flags & O_NONBLOCK)
return -EAGAIN;
wait_event_interruptible(dev->wait, (dev->work ||
!list_empty(&dev->expired)));
if (signal_pending(current))
return -ERESTARTSYS;
}
if (count < sizeof(int))
return -ENOSPC;
if (dev->work)
dev->work = 0;
if (!list_empty(&dev->expired)) {
spin_lock_irqsave(&dev->lock, flags);
timer = (struct mISDNtimer *)dev->expired.next;
list_del(&timer->list);
spin_unlock_irqrestore(&dev->lock, flags);
if (put_user(timer->id, (int __user *)buf))
ret = -EFAULT;
else
ret = sizeof(int);
kfree(timer);
}
return ret;
}
static unsigned int
mISDN_poll(struct file *filep, poll_table *wait)
{
struct mISDNtimerdev *dev = filep->private_data;
unsigned int mask = POLLERR;
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s(%p, %p)\n", __func__, filep, wait);
if (dev) {
poll_wait(filep, &dev->wait, wait);
mask = 0;
if (dev->work || !list_empty(&dev->expired))
mask |= (POLLIN | POLLRDNORM);
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s work(%d) empty(%d)\n", __func__,
dev->work, list_empty(&dev->expired));
}
return mask;
}
static void
dev_expire_timer(unsigned long data)
{
struct mISDNtimer *timer = (void *)data;
u_long flags;
spin_lock_irqsave(&timer->dev->lock, flags);
list_move_tail(&timer->list, &timer->dev->expired);
spin_unlock_irqrestore(&timer->dev->lock, flags);
wake_up_interruptible(&timer->dev->wait);
}
static int
misdn_add_timer(struct mISDNtimerdev *dev, int timeout)
{
int id;
u_long flags;
struct mISDNtimer *timer;
if (!timeout) {
dev->work = 1;
wake_up_interruptible(&dev->wait);
id = 0;
} else {
timer = kzalloc(sizeof(struct mISDNtimer), GFP_KERNEL);
if (!timer)
return -ENOMEM;
spin_lock_irqsave(&dev->lock, flags);
timer->id = dev->next_id++;
if (dev->next_id < 0)
dev->next_id = 1;
list_add_tail(&timer->list, &dev->pending);
spin_unlock_irqrestore(&dev->lock, flags);
timer->dev = dev;
timer->tl.data = (long)timer;
timer->tl.function = dev_expire_timer;
init_timer(&timer->tl);
timer->tl.expires = jiffies + ((HZ * (u_long)timeout) / 1000);
add_timer(&timer->tl);
id = timer->id;
}
return id;
}
static int
misdn_del_timer(struct mISDNtimerdev *dev, int id)
{
u_long flags;
struct mISDNtimer *timer;
int ret = 0;
spin_lock_irqsave(&dev->lock, flags);
list_for_each_entry(timer, &dev->pending, list) {
if (timer->id == id) {
list_del_init(&timer->list);
/* RED-PEN AK: race -- timer can be still running on
* other CPU. Needs reference count I think
*/
del_timer(&timer->tl);
ret = timer->id;
kfree(timer);
goto unlock;
}
}
unlock:
spin_unlock_irqrestore(&dev->lock, flags);
return ret;
}
static long
mISDN_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
{
struct mISDNtimerdev *dev = filep->private_data;
int id, tout, ret = 0;
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s(%p, %x, %lx)\n", __func__,
filep, cmd, arg);
mutex_lock(&mISDN_mutex);
switch (cmd) {
case IMADDTIMER:
if (get_user(tout, (int __user *)arg)) {
ret = -EFAULT;
break;
}
id = misdn_add_timer(dev, tout);
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s add %d id %d\n", __func__,
tout, id);
if (id < 0) {
ret = id;
break;
}
if (put_user(id, (int __user *)arg))
ret = -EFAULT;
break;
case IMDELTIMER:
if (get_user(id, (int __user *)arg)) {
ret = -EFAULT;
break;
}
if (*debug & DEBUG_TIMER)
printk(KERN_DEBUG "%s del id %d\n", __func__, id);
id = misdn_del_timer(dev, id);
if (put_user(id, (int __user *)arg))
ret = -EFAULT;
break;
default:
ret = -EINVAL;
}
mutex_unlock(&mISDN_mutex);
return ret;
}
static const struct file_operations mISDN_fops = {
.read = mISDN_read,
.poll = mISDN_poll,
.unlocked_ioctl = mISDN_ioctl,
.open = mISDN_open,
.release = mISDN_close,
.llseek = no_llseek,
};
static struct miscdevice mISDNtimer = {
.minor = MISC_DYNAMIC_MINOR,
.name = "mISDNtimer",
.fops = &mISDN_fops,
};
int
mISDN_inittimer(u_int *deb)
{
int err;
debug = deb;
err = misc_register(&mISDNtimer);
if (err)
printk(KERN_WARNING "mISDN: Could not register timer device\n");
return err;
}
void mISDN_timer_cleanup(void)
{
misc_deregister(&mISDNtimer);
}
| gpl-2.0 |
qubir/PhoenixA20_linux_sourcecode | arch/arm/boot/compressed/misc.c | 5404 | 2954 | /*
* misc.c
*
* This is a collection of several routines from gzip-1.0.3
* adapted for Linux.
*
* malloc by Hannu Savolainen 1993 and Matthias Urlichs 1994
*
* Modified for ARM Linux by Russell King
*
* Nicolas Pitre <nico@visuaide.com> 1999/04/14 :
* For this code to run directly from Flash, all constant variables must
* be marked with 'const' and all other variables initialized at run-time
* only. This way all non constant variables will end up in the bss segment,
* which should point to addresses in RAM and cleared to 0 on start.
* This allows for a much quicker boot time.
*/
unsigned int __machine_arch_type;
#include <linux/compiler.h> /* for inline */
#include <linux/types.h>
#include <linux/linkage.h>
static void putstr(const char *ptr);
extern void error(char *x);
#include <mach/uncompress.h>
#ifdef CONFIG_DEBUG_ICEDCC
#if defined(CONFIG_CPU_V6) || defined(CONFIG_CPU_V6K) || defined(CONFIG_CPU_V7)
static void icedcc_putc(int ch)
{
int status, i = 0x4000000;
do {
if (--i < 0)
return;
asm volatile ("mrc p14, 0, %0, c0, c1, 0" : "=r" (status));
} while (status & (1 << 29));
asm("mcr p14, 0, %0, c0, c5, 0" : : "r" (ch));
}
#elif defined(CONFIG_CPU_XSCALE)
static void icedcc_putc(int ch)
{
int status, i = 0x4000000;
do {
if (--i < 0)
return;
asm volatile ("mrc p14, 0, %0, c14, c0, 0" : "=r" (status));
} while (status & (1 << 28));
asm("mcr p14, 0, %0, c8, c0, 0" : : "r" (ch));
}
#else
static void icedcc_putc(int ch)
{
int status, i = 0x4000000;
do {
if (--i < 0)
return;
asm volatile ("mrc p14, 0, %0, c0, c0, 0" : "=r" (status));
} while (status & 2);
asm("mcr p14, 0, %0, c1, c0, 0" : : "r" (ch));
}
#endif
#define putc(ch) icedcc_putc(ch)
#endif
static void putstr(const char *ptr)
{
char c;
while ((c = *ptr++) != '\0') {
if (c == '\n')
putc('\r');
putc(c);
}
flush();
}
/*
* gzip declarations
*/
extern char input_data[];
extern char input_data_end[];
unsigned char *output_data;
unsigned long free_mem_ptr;
unsigned long free_mem_end_ptr;
#ifndef arch_error
#define arch_error(x)
#endif
void error(char *x)
{
arch_error(x);
putstr("\n\n");
putstr(x);
putstr("\n\n -- System halted");
while(1); /* Halt */
}
asmlinkage void __div0(void)
{
error("Attempting division by 0!");
}
extern int do_decompress(u8 *input, int len, u8 *output, void (*error)(char *x));
void
decompress_kernel(unsigned long output_start, unsigned long free_mem_ptr_p,
unsigned long free_mem_ptr_end_p,
int arch_id)
{
int ret;
output_data = (unsigned char *)output_start;
free_mem_ptr = free_mem_ptr_p;
free_mem_end_ptr = free_mem_ptr_end_p;
__machine_arch_type = arch_id;
arch_decomp_setup();
putstr("Uncompressing Linux...");
ret = do_decompress(input_data, input_data_end - input_data,
output_data, error);
if (ret)
error("decompressor returned an error");
else
putstr(" done, booting the kernel.\n");
}
| gpl-2.0 |
StelixROM/android_kernel_htc_msm8960 | arch/unicore32/kernel/puv3-nb0916.c | 6940 | 3601 | /*
* linux/arch/unicore32/kernel/puv3-nb0916.c
*
* Code specific to PKUnity SoC and UniCore ISA
*
* Maintained by GUAN Xue-tao <gxt@mprc.pku.edu.cn>
* Copyright (C) 2001-2010 Guan Xuetao
*
* 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/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/physmap.h>
#include <linux/io.h>
#include <linux/reboot.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/pwm_backlight.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <mach/hardware.h>
static struct physmap_flash_data physmap_flash_data = {
.width = 1,
};
static struct resource physmap_flash_resource = {
.start = 0xFFF80000,
.end = 0xFFFFFFFF,
.flags = IORESOURCE_MEM,
};
static struct resource puv3_i2c_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_I2C_BASE),
.end = io_v2p(PKUNITY_I2C_BASE) + 0xff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_I2C,
.end = IRQ_I2C,
.flags = IORESOURCE_IRQ,
}
};
static struct platform_pwm_backlight_data nb0916_backlight_data = {
.pwm_id = 0,
.max_brightness = 100,
.dft_brightness = 100,
.pwm_period_ns = 70 * 1024,
};
static struct gpio_keys_button nb0916_gpio_keys[] = {
{
.type = EV_KEY,
.code = KEY_POWER,
.gpio = GPI_SOFF_REQ,
.desc = "Power Button",
.wakeup = 1,
.active_low = 1,
},
{
.type = EV_KEY,
.code = BTN_TOUCH,
.gpio = GPI_BTN_TOUCH,
.desc = "Touchpad Button",
.wakeup = 1,
.active_low = 1,
},
};
static struct gpio_keys_platform_data nb0916_gpio_button_data = {
.buttons = nb0916_gpio_keys,
.nbuttons = ARRAY_SIZE(nb0916_gpio_keys),
};
static irqreturn_t nb0916_lcdcaseoff_handler(int irq, void *dev_id)
{
if (gpio_get_value(GPI_LCD_CASE_OFF))
gpio_set_value(GPO_LCD_EN, 1);
else
gpio_set_value(GPO_LCD_EN, 0);
return IRQ_HANDLED;
}
static irqreturn_t nb0916_overheat_handler(int irq, void *dev_id)
{
machine_halt();
/* SYSTEM HALT, NO RETURN */
return IRQ_HANDLED;
}
static struct i2c_board_info __initdata puv3_i2c_devices[] = {
{ I2C_BOARD_INFO("lm75", I2C_TAR_THERMAL), },
{ I2C_BOARD_INFO("bq27200", I2C_TAR_PWIC), },
{ I2C_BOARD_INFO("24c02", I2C_TAR_EEPROM), },
};
int __init mach_nb0916_init(void)
{
i2c_register_board_info(0, puv3_i2c_devices,
ARRAY_SIZE(puv3_i2c_devices));
platform_device_register_simple("PKUnity-v3-I2C", -1,
puv3_i2c_resources, ARRAY_SIZE(puv3_i2c_resources));
platform_device_register_data(&platform_bus, "pwm-backlight", -1,
&nb0916_backlight_data, sizeof(nb0916_backlight_data));
platform_device_register_data(&platform_bus, "gpio-keys", -1,
&nb0916_gpio_button_data, sizeof(nb0916_gpio_button_data));
platform_device_register_resndata(&platform_bus, "physmap-flash", -1,
&physmap_flash_resource, 1,
&physmap_flash_data, sizeof(physmap_flash_data));
if (request_irq(gpio_to_irq(GPI_LCD_CASE_OFF),
&nb0916_lcdcaseoff_handler,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
"NB0916 lcd case off", NULL) < 0) {
printk(KERN_DEBUG "LCD-Case-OFF IRQ %d not available\n",
gpio_to_irq(GPI_LCD_CASE_OFF));
}
if (request_irq(gpio_to_irq(GPI_OTP_INT), &nb0916_overheat_handler,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
"NB0916 overheating protection", NULL) < 0) {
printk(KERN_DEBUG "Overheating Protection IRQ %d not available\n",
gpio_to_irq(GPI_OTP_INT));
}
return 0;
}
subsys_initcall_sync(mach_nb0916_init);
| gpl-2.0 |
Pafcholini/Nadia-kernel-KK-N910F-EUR-KK-OpenSource | sound/soc/fsl/wm1133-ev1.c | 7196 | 9122 | /*
* wm1133-ev1.c - Audio for WM1133-EV1 on i.MX31ADS
*
* Copyright (c) 2010 Wolfson Microelectronics plc
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* Based on an earlier driver for the same hardware by Liam Girdwood.
*
* 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/platform_device.h>
#include <linux/clk.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/jack.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include "imx-ssi.h"
#include "../codecs/wm8350.h"
#include "imx-audmux.h"
/* There is a silicon mic on the board optionally connected via a solder pad
* SP1. Define this to enable it.
*/
#undef USE_SIMIC
struct _wm8350_audio {
unsigned int channels;
snd_pcm_format_t format;
unsigned int rate;
unsigned int sysclk;
unsigned int bclkdiv;
unsigned int clkdiv;
unsigned int lr_rate;
};
/* in order of power consumption per rate (lowest first) */
static const struct _wm8350_audio wm8350_audio[] = {
/* 16bit mono modes */
{1, SNDRV_PCM_FORMAT_S16_LE, 8000, 12288000 >> 1,
WM8350_BCLK_DIV_48, WM8350_DACDIV_3, 16,},
/* 16 bit stereo modes */
{2, SNDRV_PCM_FORMAT_S16_LE, 8000, 12288000,
WM8350_BCLK_DIV_48, WM8350_DACDIV_6, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 16000, 12288000,
WM8350_BCLK_DIV_24, WM8350_DACDIV_3, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 32000, 12288000,
WM8350_BCLK_DIV_12, WM8350_DACDIV_1_5, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 48000, 12288000,
WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 96000, 24576000,
WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 11025, 11289600,
WM8350_BCLK_DIV_32, WM8350_DACDIV_4, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 22050, 11289600,
WM8350_BCLK_DIV_16, WM8350_DACDIV_2, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 44100, 11289600,
WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,},
{2, SNDRV_PCM_FORMAT_S16_LE, 88200, 22579200,
WM8350_BCLK_DIV_8, WM8350_DACDIV_1, 32,},
/* 24bit stereo modes */
{2, SNDRV_PCM_FORMAT_S24_LE, 48000, 12288000,
WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,},
{2, SNDRV_PCM_FORMAT_S24_LE, 96000, 24576000,
WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,},
{2, SNDRV_PCM_FORMAT_S24_LE, 44100, 11289600,
WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,},
{2, SNDRV_PCM_FORMAT_S24_LE, 88200, 22579200,
WM8350_BCLK_DIV_4, WM8350_DACDIV_1, 64,},
};
static int wm1133_ev1_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int i, found = 0;
snd_pcm_format_t format = params_format(params);
unsigned int rate = params_rate(params);
unsigned int channels = params_channels(params);
u32 dai_format;
/* find the correct audio parameters */
for (i = 0; i < ARRAY_SIZE(wm8350_audio); i++) {
if (rate == wm8350_audio[i].rate &&
format == wm8350_audio[i].format &&
channels == wm8350_audio[i].channels) {
found = 1;
break;
}
}
if (!found)
return -EINVAL;
/* codec FLL input is 14.75 MHz from MCLK */
snd_soc_dai_set_pll(codec_dai, 0, 0, 14750000, wm8350_audio[i].sysclk);
dai_format = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM;
/* set codec DAI configuration */
snd_soc_dai_set_fmt(codec_dai, dai_format);
/* set cpu DAI configuration */
snd_soc_dai_set_fmt(cpu_dai, dai_format);
/* TODO: The SSI driver should figure this out for us */
switch (channels) {
case 2:
snd_soc_dai_set_tdm_slot(cpu_dai, 0xffffffc, 0xffffffc, 2, 0);
break;
case 1:
snd_soc_dai_set_tdm_slot(cpu_dai, 0xffffffe, 0xffffffe, 1, 0);
break;
default:
return -EINVAL;
}
/* set MCLK as the codec system clock for DAC and ADC */
snd_soc_dai_set_sysclk(codec_dai, WM8350_MCLK_SEL_PLL_MCLK,
wm8350_audio[i].sysclk, SND_SOC_CLOCK_IN);
/* set codec BCLK division for sample rate */
snd_soc_dai_set_clkdiv(codec_dai, WM8350_BCLK_CLKDIV,
wm8350_audio[i].bclkdiv);
/* DAI is synchronous and clocked with DAC LRCLK & ADC LRC */
snd_soc_dai_set_clkdiv(codec_dai,
WM8350_DACLR_CLKDIV, wm8350_audio[i].lr_rate);
snd_soc_dai_set_clkdiv(codec_dai,
WM8350_ADCLR_CLKDIV, wm8350_audio[i].lr_rate);
/* now configure DAC and ADC clocks */
snd_soc_dai_set_clkdiv(codec_dai,
WM8350_DAC_CLKDIV, wm8350_audio[i].clkdiv);
snd_soc_dai_set_clkdiv(codec_dai,
WM8350_ADC_CLKDIV, wm8350_audio[i].clkdiv);
return 0;
}
static struct snd_soc_ops wm1133_ev1_ops = {
.hw_params = wm1133_ev1_hw_params,
};
static const struct snd_soc_dapm_widget wm1133_ev1_widgets[] = {
#ifdef USE_SIMIC
SND_SOC_DAPM_MIC("SiMIC", NULL),
#endif
SND_SOC_DAPM_MIC("Mic1 Jack", NULL),
SND_SOC_DAPM_MIC("Mic2 Jack", NULL),
SND_SOC_DAPM_LINE("Line In Jack", NULL),
SND_SOC_DAPM_LINE("Line Out Jack", NULL),
SND_SOC_DAPM_HP("Headphone Jack", NULL),
};
/* imx32ads soc_card audio map */
static const struct snd_soc_dapm_route wm1133_ev1_map[] = {
#ifdef USE_SIMIC
/* SiMIC --> IN1LN (with automatic bias) via SP1 */
{ "IN1LN", NULL, "Mic Bias" },
{ "Mic Bias", NULL, "SiMIC" },
#endif
/* Mic 1 Jack --> IN1LN and IN1LP (with automatic bias) */
{ "IN1LN", NULL, "Mic Bias" },
{ "IN1LP", NULL, "Mic1 Jack" },
{ "Mic Bias", NULL, "Mic1 Jack" },
/* Mic 2 Jack --> IN1RN and IN1RP (with automatic bias) */
{ "IN1RN", NULL, "Mic Bias" },
{ "IN1RP", NULL, "Mic2 Jack" },
{ "Mic Bias", NULL, "Mic2 Jack" },
/* Line in Jack --> AUX (L+R) */
{ "IN3R", NULL, "Line In Jack" },
{ "IN3L", NULL, "Line In Jack" },
/* Out1 --> Headphone Jack */
{ "Headphone Jack", NULL, "OUT1R" },
{ "Headphone Jack", NULL, "OUT1L" },
/* Out1 --> Line Out Jack */
{ "Line Out Jack", NULL, "OUT2R" },
{ "Line Out Jack", NULL, "OUT2L" },
};
static struct snd_soc_jack hp_jack;
static struct snd_soc_jack_pin hp_jack_pins[] = {
{ .pin = "Headphone Jack", .mask = SND_JACK_HEADPHONE },
};
static struct snd_soc_jack mic_jack;
static struct snd_soc_jack_pin mic_jack_pins[] = {
{ .pin = "Mic1 Jack", .mask = SND_JACK_MICROPHONE },
{ .pin = "Mic2 Jack", .mask = SND_JACK_MICROPHONE },
};
static int wm1133_ev1_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_new_controls(dapm, wm1133_ev1_widgets,
ARRAY_SIZE(wm1133_ev1_widgets));
snd_soc_dapm_add_routes(dapm, wm1133_ev1_map,
ARRAY_SIZE(wm1133_ev1_map));
/* Headphone jack detection */
snd_soc_jack_new(codec, "Headphone", SND_JACK_HEADPHONE, &hp_jack);
snd_soc_jack_add_pins(&hp_jack, ARRAY_SIZE(hp_jack_pins),
hp_jack_pins);
wm8350_hp_jack_detect(codec, WM8350_JDR, &hp_jack, SND_JACK_HEADPHONE);
/* Microphone jack detection */
snd_soc_jack_new(codec, "Microphone",
SND_JACK_MICROPHONE | SND_JACK_BTN_0, &mic_jack);
snd_soc_jack_add_pins(&mic_jack, ARRAY_SIZE(mic_jack_pins),
mic_jack_pins);
wm8350_mic_jack_detect(codec, &mic_jack, SND_JACK_MICROPHONE,
SND_JACK_BTN_0);
snd_soc_dapm_force_enable_pin(dapm, "Mic Bias");
return 0;
}
static struct snd_soc_dai_link wm1133_ev1_dai = {
.name = "WM1133-EV1",
.stream_name = "Audio",
.cpu_dai_name = "imx-ssi.0",
.codec_dai_name = "wm8350-hifi",
.platform_name = "imx-fiq-pcm-audio.0",
.codec_name = "wm8350-codec.0-0x1a",
.init = wm1133_ev1_init,
.ops = &wm1133_ev1_ops,
.symmetric_rates = 1,
};
static struct snd_soc_card wm1133_ev1 = {
.name = "WM1133-EV1",
.owner = THIS_MODULE,
.dai_link = &wm1133_ev1_dai,
.num_links = 1,
};
static struct platform_device *wm1133_ev1_snd_device;
static int __init wm1133_ev1_audio_init(void)
{
int ret;
unsigned int ptcr, pdcr;
/* SSI0 mastered by port 5 */
ptcr = IMX_AUDMUX_V2_PTCR_SYN |
IMX_AUDMUX_V2_PTCR_TFSDIR |
IMX_AUDMUX_V2_PTCR_TFSEL(MX31_AUDMUX_PORT5_SSI_PINS_5) |
IMX_AUDMUX_V2_PTCR_TCLKDIR |
IMX_AUDMUX_V2_PTCR_TCSEL(MX31_AUDMUX_PORT5_SSI_PINS_5);
pdcr = IMX_AUDMUX_V2_PDCR_RXDSEL(MX31_AUDMUX_PORT5_SSI_PINS_5);
imx_audmux_v2_configure_port(MX31_AUDMUX_PORT1_SSI0, ptcr, pdcr);
ptcr = IMX_AUDMUX_V2_PTCR_SYN;
pdcr = IMX_AUDMUX_V2_PDCR_RXDSEL(MX31_AUDMUX_PORT1_SSI0);
imx_audmux_v2_configure_port(MX31_AUDMUX_PORT5_SSI_PINS_5, ptcr, pdcr);
wm1133_ev1_snd_device = platform_device_alloc("soc-audio", -1);
if (!wm1133_ev1_snd_device)
return -ENOMEM;
platform_set_drvdata(wm1133_ev1_snd_device, &wm1133_ev1);
ret = platform_device_add(wm1133_ev1_snd_device);
if (ret)
platform_device_put(wm1133_ev1_snd_device);
return ret;
}
module_init(wm1133_ev1_audio_init);
static void __exit wm1133_ev1_audio_exit(void)
{
platform_device_unregister(wm1133_ev1_snd_device);
}
module_exit(wm1133_ev1_audio_exit);
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("Audio for WM1133-EV1 on i.MX31ADS");
MODULE_LICENSE("GPL");
| gpl-2.0 |
thicklizard/patch | drivers/infiniband/hw/amso1100/c2_provider.c | 7708 | 21625 | /*
* Copyright (c) 2005 Ammasso, Inc. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/inetdevice.h>
#include <linux/delay.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/if_vlan.h>
#include <linux/crc32.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <linux/if_arp.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/byteorder.h>
#include <rdma/ib_smi.h>
#include <rdma/ib_umem.h>
#include <rdma/ib_user_verbs.h>
#include "c2.h"
#include "c2_provider.h"
#include "c2_user.h"
static int c2_query_device(struct ib_device *ibdev,
struct ib_device_attr *props)
{
struct c2_dev *c2dev = to_c2dev(ibdev);
pr_debug("%s:%u\n", __func__, __LINE__);
*props = c2dev->props;
return 0;
}
static int c2_query_port(struct ib_device *ibdev,
u8 port, struct ib_port_attr *props)
{
pr_debug("%s:%u\n", __func__, __LINE__);
props->max_mtu = IB_MTU_4096;
props->lid = 0;
props->lmc = 0;
props->sm_lid = 0;
props->sm_sl = 0;
props->state = IB_PORT_ACTIVE;
props->phys_state = 0;
props->port_cap_flags =
IB_PORT_CM_SUP |
IB_PORT_REINIT_SUP |
IB_PORT_VENDOR_CLASS_SUP | IB_PORT_BOOT_MGMT_SUP;
props->gid_tbl_len = 1;
props->pkey_tbl_len = 1;
props->qkey_viol_cntr = 0;
props->active_width = 1;
props->active_speed = IB_SPEED_SDR;
return 0;
}
static int c2_query_pkey(struct ib_device *ibdev,
u8 port, u16 index, u16 * pkey)
{
pr_debug("%s:%u\n", __func__, __LINE__);
*pkey = 0;
return 0;
}
static int c2_query_gid(struct ib_device *ibdev, u8 port,
int index, union ib_gid *gid)
{
struct c2_dev *c2dev = to_c2dev(ibdev);
pr_debug("%s:%u\n", __func__, __LINE__);
memset(&(gid->raw[0]), 0, sizeof(gid->raw));
memcpy(&(gid->raw[0]), c2dev->pseudo_netdev->dev_addr, 6);
return 0;
}
/* Allocate the user context data structure. This keeps track
* of all objects associated with a particular user-mode client.
*/
static struct ib_ucontext *c2_alloc_ucontext(struct ib_device *ibdev,
struct ib_udata *udata)
{
struct c2_ucontext *context;
pr_debug("%s:%u\n", __func__, __LINE__);
context = kmalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
return &context->ibucontext;
}
static int c2_dealloc_ucontext(struct ib_ucontext *context)
{
pr_debug("%s:%u\n", __func__, __LINE__);
kfree(context);
return 0;
}
static int c2_mmap_uar(struct ib_ucontext *context, struct vm_area_struct *vma)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return -ENOSYS;
}
static struct ib_pd *c2_alloc_pd(struct ib_device *ibdev,
struct ib_ucontext *context,
struct ib_udata *udata)
{
struct c2_pd *pd;
int err;
pr_debug("%s:%u\n", __func__, __LINE__);
pd = kmalloc(sizeof(*pd), GFP_KERNEL);
if (!pd)
return ERR_PTR(-ENOMEM);
err = c2_pd_alloc(to_c2dev(ibdev), !context, pd);
if (err) {
kfree(pd);
return ERR_PTR(err);
}
if (context) {
if (ib_copy_to_udata(udata, &pd->pd_id, sizeof(__u32))) {
c2_pd_free(to_c2dev(ibdev), pd);
kfree(pd);
return ERR_PTR(-EFAULT);
}
}
return &pd->ibpd;
}
static int c2_dealloc_pd(struct ib_pd *pd)
{
pr_debug("%s:%u\n", __func__, __LINE__);
c2_pd_free(to_c2dev(pd->device), to_c2pd(pd));
kfree(pd);
return 0;
}
static struct ib_ah *c2_ah_create(struct ib_pd *pd, struct ib_ah_attr *ah_attr)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return ERR_PTR(-ENOSYS);
}
static int c2_ah_destroy(struct ib_ah *ah)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return -ENOSYS;
}
static void c2_add_ref(struct ib_qp *ibqp)
{
struct c2_qp *qp;
BUG_ON(!ibqp);
qp = to_c2qp(ibqp);
atomic_inc(&qp->refcount);
}
static void c2_rem_ref(struct ib_qp *ibqp)
{
struct c2_qp *qp;
BUG_ON(!ibqp);
qp = to_c2qp(ibqp);
if (atomic_dec_and_test(&qp->refcount))
wake_up(&qp->wait);
}
struct ib_qp *c2_get_qp(struct ib_device *device, int qpn)
{
struct c2_dev* c2dev = to_c2dev(device);
struct c2_qp *qp;
qp = c2_find_qpn(c2dev, qpn);
pr_debug("%s Returning QP=%p for QPN=%d, device=%p, refcount=%d\n",
__func__, qp, qpn, device,
(qp?atomic_read(&qp->refcount):0));
return (qp?&qp->ibqp:NULL);
}
static struct ib_qp *c2_create_qp(struct ib_pd *pd,
struct ib_qp_init_attr *init_attr,
struct ib_udata *udata)
{
struct c2_qp *qp;
int err;
pr_debug("%s:%u\n", __func__, __LINE__);
if (init_attr->create_flags)
return ERR_PTR(-EINVAL);
switch (init_attr->qp_type) {
case IB_QPT_RC:
qp = kzalloc(sizeof(*qp), GFP_KERNEL);
if (!qp) {
pr_debug("%s: Unable to allocate QP\n", __func__);
return ERR_PTR(-ENOMEM);
}
spin_lock_init(&qp->lock);
if (pd->uobject) {
/* userspace specific */
}
err = c2_alloc_qp(to_c2dev(pd->device),
to_c2pd(pd), init_attr, qp);
if (err && pd->uobject) {
/* userspace specific */
}
break;
default:
pr_debug("%s: Invalid QP type: %d\n", __func__,
init_attr->qp_type);
return ERR_PTR(-EINVAL);
}
if (err) {
kfree(qp);
return ERR_PTR(err);
}
return &qp->ibqp;
}
static int c2_destroy_qp(struct ib_qp *ib_qp)
{
struct c2_qp *qp = to_c2qp(ib_qp);
pr_debug("%s:%u qp=%p,qp->state=%d\n",
__func__, __LINE__, ib_qp, qp->state);
c2_free_qp(to_c2dev(ib_qp->device), qp);
kfree(qp);
return 0;
}
static struct ib_cq *c2_create_cq(struct ib_device *ibdev, int entries, int vector,
struct ib_ucontext *context,
struct ib_udata *udata)
{
struct c2_cq *cq;
int err;
cq = kmalloc(sizeof(*cq), GFP_KERNEL);
if (!cq) {
pr_debug("%s: Unable to allocate CQ\n", __func__);
return ERR_PTR(-ENOMEM);
}
err = c2_init_cq(to_c2dev(ibdev), entries, NULL, cq);
if (err) {
pr_debug("%s: error initializing CQ\n", __func__);
kfree(cq);
return ERR_PTR(err);
}
return &cq->ibcq;
}
static int c2_destroy_cq(struct ib_cq *ib_cq)
{
struct c2_cq *cq = to_c2cq(ib_cq);
pr_debug("%s:%u\n", __func__, __LINE__);
c2_free_cq(to_c2dev(ib_cq->device), cq);
kfree(cq);
return 0;
}
static inline u32 c2_convert_access(int acc)
{
return (acc & IB_ACCESS_REMOTE_WRITE ? C2_ACF_REMOTE_WRITE : 0) |
(acc & IB_ACCESS_REMOTE_READ ? C2_ACF_REMOTE_READ : 0) |
(acc & IB_ACCESS_LOCAL_WRITE ? C2_ACF_LOCAL_WRITE : 0) |
C2_ACF_LOCAL_READ | C2_ACF_WINDOW_BIND;
}
static struct ib_mr *c2_reg_phys_mr(struct ib_pd *ib_pd,
struct ib_phys_buf *buffer_list,
int num_phys_buf, int acc, u64 * iova_start)
{
struct c2_mr *mr;
u64 *page_list;
u32 total_len;
int err, i, j, k, page_shift, pbl_depth;
pbl_depth = 0;
total_len = 0;
page_shift = PAGE_SHIFT;
/*
* If there is only 1 buffer we assume this could
* be a map of all phy mem...use a 32k page_shift.
*/
if (num_phys_buf == 1)
page_shift += 3;
for (i = 0; i < num_phys_buf; i++) {
if (buffer_list[i].addr & ~PAGE_MASK) {
pr_debug("Unaligned Memory Buffer: 0x%x\n",
(unsigned int) buffer_list[i].addr);
return ERR_PTR(-EINVAL);
}
if (!buffer_list[i].size) {
pr_debug("Invalid Buffer Size\n");
return ERR_PTR(-EINVAL);
}
total_len += buffer_list[i].size;
pbl_depth += ALIGN(buffer_list[i].size,
(1 << page_shift)) >> page_shift;
}
page_list = vmalloc(sizeof(u64) * pbl_depth);
if (!page_list) {
pr_debug("couldn't vmalloc page_list of size %zd\n",
(sizeof(u64) * pbl_depth));
return ERR_PTR(-ENOMEM);
}
for (i = 0, j = 0; i < num_phys_buf; i++) {
int naddrs;
naddrs = ALIGN(buffer_list[i].size,
(1 << page_shift)) >> page_shift;
for (k = 0; k < naddrs; k++)
page_list[j++] = (buffer_list[i].addr +
(k << page_shift));
}
mr = kmalloc(sizeof(*mr), GFP_KERNEL);
if (!mr) {
vfree(page_list);
return ERR_PTR(-ENOMEM);
}
mr->pd = to_c2pd(ib_pd);
mr->umem = NULL;
pr_debug("%s - page shift %d, pbl_depth %d, total_len %u, "
"*iova_start %llx, first pa %llx, last pa %llx\n",
__func__, page_shift, pbl_depth, total_len,
(unsigned long long) *iova_start,
(unsigned long long) page_list[0],
(unsigned long long) page_list[pbl_depth-1]);
err = c2_nsmr_register_phys_kern(to_c2dev(ib_pd->device), page_list,
(1 << page_shift), pbl_depth,
total_len, 0, iova_start,
c2_convert_access(acc), mr);
vfree(page_list);
if (err) {
kfree(mr);
return ERR_PTR(err);
}
return &mr->ibmr;
}
static struct ib_mr *c2_get_dma_mr(struct ib_pd *pd, int acc)
{
struct ib_phys_buf bl;
u64 kva = 0;
pr_debug("%s:%u\n", __func__, __LINE__);
/* AMSO1100 limit */
bl.size = 0xffffffff;
bl.addr = 0;
return c2_reg_phys_mr(pd, &bl, 1, acc, &kva);
}
static struct ib_mr *c2_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
u64 virt, int acc, struct ib_udata *udata)
{
u64 *pages;
u64 kva = 0;
int shift, n, len;
int i, j, k;
int err = 0;
struct ib_umem_chunk *chunk;
struct c2_pd *c2pd = to_c2pd(pd);
struct c2_mr *c2mr;
pr_debug("%s:%u\n", __func__, __LINE__);
c2mr = kmalloc(sizeof(*c2mr), GFP_KERNEL);
if (!c2mr)
return ERR_PTR(-ENOMEM);
c2mr->pd = c2pd;
c2mr->umem = ib_umem_get(pd->uobject->context, start, length, acc, 0);
if (IS_ERR(c2mr->umem)) {
err = PTR_ERR(c2mr->umem);
kfree(c2mr);
return ERR_PTR(err);
}
shift = ffs(c2mr->umem->page_size) - 1;
n = 0;
list_for_each_entry(chunk, &c2mr->umem->chunk_list, list)
n += chunk->nents;
pages = kmalloc(n * sizeof(u64), GFP_KERNEL);
if (!pages) {
err = -ENOMEM;
goto err;
}
i = 0;
list_for_each_entry(chunk, &c2mr->umem->chunk_list, list) {
for (j = 0; j < chunk->nmap; ++j) {
len = sg_dma_len(&chunk->page_list[j]) >> shift;
for (k = 0; k < len; ++k) {
pages[i++] =
sg_dma_address(&chunk->page_list[j]) +
(c2mr->umem->page_size * k);
}
}
}
kva = virt;
err = c2_nsmr_register_phys_kern(to_c2dev(pd->device),
pages,
c2mr->umem->page_size,
i,
length,
c2mr->umem->offset,
&kva,
c2_convert_access(acc),
c2mr);
kfree(pages);
if (err)
goto err;
return &c2mr->ibmr;
err:
ib_umem_release(c2mr->umem);
kfree(c2mr);
return ERR_PTR(err);
}
static int c2_dereg_mr(struct ib_mr *ib_mr)
{
struct c2_mr *mr = to_c2mr(ib_mr);
int err;
pr_debug("%s:%u\n", __func__, __LINE__);
err = c2_stag_dealloc(to_c2dev(ib_mr->device), ib_mr->lkey);
if (err)
pr_debug("c2_stag_dealloc failed: %d\n", err);
else {
if (mr->umem)
ib_umem_release(mr->umem);
kfree(mr);
}
return err;
}
static ssize_t show_rev(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct c2_dev *c2dev = container_of(dev, struct c2_dev, ibdev.dev);
pr_debug("%s:%u\n", __func__, __LINE__);
return sprintf(buf, "%x\n", c2dev->props.hw_ver);
}
static ssize_t show_fw_ver(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct c2_dev *c2dev = container_of(dev, struct c2_dev, ibdev.dev);
pr_debug("%s:%u\n", __func__, __LINE__);
return sprintf(buf, "%x.%x.%x\n",
(int) (c2dev->props.fw_ver >> 32),
(int) (c2dev->props.fw_ver >> 16) & 0xffff,
(int) (c2dev->props.fw_ver & 0xffff));
}
static ssize_t show_hca(struct device *dev, struct device_attribute *attr,
char *buf)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return sprintf(buf, "AMSO1100\n");
}
static ssize_t show_board(struct device *dev, struct device_attribute *attr,
char *buf)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return sprintf(buf, "%.*s\n", 32, "AMSO1100 Board ID");
}
static DEVICE_ATTR(hw_rev, S_IRUGO, show_rev, NULL);
static DEVICE_ATTR(fw_ver, S_IRUGO, show_fw_ver, NULL);
static DEVICE_ATTR(hca_type, S_IRUGO, show_hca, NULL);
static DEVICE_ATTR(board_id, S_IRUGO, show_board, NULL);
static struct device_attribute *c2_dev_attributes[] = {
&dev_attr_hw_rev,
&dev_attr_fw_ver,
&dev_attr_hca_type,
&dev_attr_board_id
};
static int c2_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_udata *udata)
{
int err;
err =
c2_qp_modify(to_c2dev(ibqp->device), to_c2qp(ibqp), attr,
attr_mask);
return err;
}
static int c2_multicast_attach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return -ENOSYS;
}
static int c2_multicast_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return -ENOSYS;
}
static int c2_process_mad(struct ib_device *ibdev,
int mad_flags,
u8 port_num,
struct ib_wc *in_wc,
struct ib_grh *in_grh,
struct ib_mad *in_mad, struct ib_mad *out_mad)
{
pr_debug("%s:%u\n", __func__, __LINE__);
return -ENOSYS;
}
static int c2_connect(struct iw_cm_id *cm_id, struct iw_cm_conn_param *iw_param)
{
pr_debug("%s:%u\n", __func__, __LINE__);
/* Request a connection */
return c2_llp_connect(cm_id, iw_param);
}
static int c2_accept(struct iw_cm_id *cm_id, struct iw_cm_conn_param *iw_param)
{
pr_debug("%s:%u\n", __func__, __LINE__);
/* Accept the new connection */
return c2_llp_accept(cm_id, iw_param);
}
static int c2_reject(struct iw_cm_id *cm_id, const void *pdata, u8 pdata_len)
{
int err;
pr_debug("%s:%u\n", __func__, __LINE__);
err = c2_llp_reject(cm_id, pdata, pdata_len);
return err;
}
static int c2_service_create(struct iw_cm_id *cm_id, int backlog)
{
int err;
pr_debug("%s:%u\n", __func__, __LINE__);
err = c2_llp_service_create(cm_id, backlog);
pr_debug("%s:%u err=%d\n",
__func__, __LINE__,
err);
return err;
}
static int c2_service_destroy(struct iw_cm_id *cm_id)
{
int err;
pr_debug("%s:%u\n", __func__, __LINE__);
err = c2_llp_service_destroy(cm_id);
return err;
}
static int c2_pseudo_up(struct net_device *netdev)
{
struct in_device *ind;
struct c2_dev *c2dev = netdev->ml_priv;
ind = in_dev_get(netdev);
if (!ind)
return 0;
pr_debug("adding...\n");
for_ifa(ind) {
#ifdef DEBUG
u8 *ip = (u8 *) & ifa->ifa_address;
pr_debug("%s: %d.%d.%d.%d\n",
ifa->ifa_label, ip[0], ip[1], ip[2], ip[3]);
#endif
c2_add_addr(c2dev, ifa->ifa_address, ifa->ifa_mask);
}
endfor_ifa(ind);
in_dev_put(ind);
return 0;
}
static int c2_pseudo_down(struct net_device *netdev)
{
struct in_device *ind;
struct c2_dev *c2dev = netdev->ml_priv;
ind = in_dev_get(netdev);
if (!ind)
return 0;
pr_debug("deleting...\n");
for_ifa(ind) {
#ifdef DEBUG
u8 *ip = (u8 *) & ifa->ifa_address;
pr_debug("%s: %d.%d.%d.%d\n",
ifa->ifa_label, ip[0], ip[1], ip[2], ip[3]);
#endif
c2_del_addr(c2dev, ifa->ifa_address, ifa->ifa_mask);
}
endfor_ifa(ind);
in_dev_put(ind);
return 0;
}
static int c2_pseudo_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
{
kfree_skb(skb);
return NETDEV_TX_OK;
}
static int c2_pseudo_change_mtu(struct net_device *netdev, int new_mtu)
{
if (new_mtu < ETH_ZLEN || new_mtu > ETH_JUMBO_MTU)
return -EINVAL;
netdev->mtu = new_mtu;
/* TODO: Tell rnic about new rmda interface mtu */
return 0;
}
static const struct net_device_ops c2_pseudo_netdev_ops = {
.ndo_open = c2_pseudo_up,
.ndo_stop = c2_pseudo_down,
.ndo_start_xmit = c2_pseudo_xmit_frame,
.ndo_change_mtu = c2_pseudo_change_mtu,
.ndo_validate_addr = eth_validate_addr,
};
static void setup(struct net_device *netdev)
{
netdev->netdev_ops = &c2_pseudo_netdev_ops;
netdev->watchdog_timeo = 0;
netdev->type = ARPHRD_ETHER;
netdev->mtu = 1500;
netdev->hard_header_len = ETH_HLEN;
netdev->addr_len = ETH_ALEN;
netdev->tx_queue_len = 0;
netdev->flags |= IFF_NOARP;
}
static struct net_device *c2_pseudo_netdev_init(struct c2_dev *c2dev)
{
char name[IFNAMSIZ];
struct net_device *netdev;
/* change ethxxx to iwxxx */
strcpy(name, "iw");
strcat(name, &c2dev->netdev->name[3]);
netdev = alloc_netdev(0, name, setup);
if (!netdev) {
printk(KERN_ERR PFX "%s - etherdev alloc failed",
__func__);
return NULL;
}
netdev->ml_priv = c2dev;
SET_NETDEV_DEV(netdev, &c2dev->pcidev->dev);
memcpy_fromio(netdev->dev_addr, c2dev->kva + C2_REGS_RDMA_ENADDR, 6);
/* Print out the MAC address */
pr_debug("%s: MAC %pM\n", netdev->name, netdev->dev_addr);
#if 0
/* Disable network packets */
netif_stop_queue(netdev);
#endif
return netdev;
}
int c2_register_device(struct c2_dev *dev)
{
int ret = -ENOMEM;
int i;
/* Register pseudo network device */
dev->pseudo_netdev = c2_pseudo_netdev_init(dev);
if (!dev->pseudo_netdev)
goto out;
ret = register_netdev(dev->pseudo_netdev);
if (ret)
goto out_free_netdev;
pr_debug("%s:%u\n", __func__, __LINE__);
strlcpy(dev->ibdev.name, "amso%d", IB_DEVICE_NAME_MAX);
dev->ibdev.owner = THIS_MODULE;
dev->ibdev.uverbs_cmd_mask =
(1ull << IB_USER_VERBS_CMD_GET_CONTEXT) |
(1ull << IB_USER_VERBS_CMD_QUERY_DEVICE) |
(1ull << IB_USER_VERBS_CMD_QUERY_PORT) |
(1ull << IB_USER_VERBS_CMD_ALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_DEALLOC_PD) |
(1ull << IB_USER_VERBS_CMD_REG_MR) |
(1ull << IB_USER_VERBS_CMD_DEREG_MR) |
(1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) |
(1ull << IB_USER_VERBS_CMD_CREATE_CQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_CQ) |
(1ull << IB_USER_VERBS_CMD_REQ_NOTIFY_CQ) |
(1ull << IB_USER_VERBS_CMD_CREATE_QP) |
(1ull << IB_USER_VERBS_CMD_MODIFY_QP) |
(1ull << IB_USER_VERBS_CMD_POLL_CQ) |
(1ull << IB_USER_VERBS_CMD_DESTROY_QP) |
(1ull << IB_USER_VERBS_CMD_POST_SEND) |
(1ull << IB_USER_VERBS_CMD_POST_RECV);
dev->ibdev.node_type = RDMA_NODE_RNIC;
memset(&dev->ibdev.node_guid, 0, sizeof(dev->ibdev.node_guid));
memcpy(&dev->ibdev.node_guid, dev->pseudo_netdev->dev_addr, 6);
dev->ibdev.phys_port_cnt = 1;
dev->ibdev.num_comp_vectors = 1;
dev->ibdev.dma_device = &dev->pcidev->dev;
dev->ibdev.query_device = c2_query_device;
dev->ibdev.query_port = c2_query_port;
dev->ibdev.query_pkey = c2_query_pkey;
dev->ibdev.query_gid = c2_query_gid;
dev->ibdev.alloc_ucontext = c2_alloc_ucontext;
dev->ibdev.dealloc_ucontext = c2_dealloc_ucontext;
dev->ibdev.mmap = c2_mmap_uar;
dev->ibdev.alloc_pd = c2_alloc_pd;
dev->ibdev.dealloc_pd = c2_dealloc_pd;
dev->ibdev.create_ah = c2_ah_create;
dev->ibdev.destroy_ah = c2_ah_destroy;
dev->ibdev.create_qp = c2_create_qp;
dev->ibdev.modify_qp = c2_modify_qp;
dev->ibdev.destroy_qp = c2_destroy_qp;
dev->ibdev.create_cq = c2_create_cq;
dev->ibdev.destroy_cq = c2_destroy_cq;
dev->ibdev.poll_cq = c2_poll_cq;
dev->ibdev.get_dma_mr = c2_get_dma_mr;
dev->ibdev.reg_phys_mr = c2_reg_phys_mr;
dev->ibdev.reg_user_mr = c2_reg_user_mr;
dev->ibdev.dereg_mr = c2_dereg_mr;
dev->ibdev.alloc_fmr = NULL;
dev->ibdev.unmap_fmr = NULL;
dev->ibdev.dealloc_fmr = NULL;
dev->ibdev.map_phys_fmr = NULL;
dev->ibdev.attach_mcast = c2_multicast_attach;
dev->ibdev.detach_mcast = c2_multicast_detach;
dev->ibdev.process_mad = c2_process_mad;
dev->ibdev.req_notify_cq = c2_arm_cq;
dev->ibdev.post_send = c2_post_send;
dev->ibdev.post_recv = c2_post_receive;
dev->ibdev.iwcm = kmalloc(sizeof(*dev->ibdev.iwcm), GFP_KERNEL);
if (dev->ibdev.iwcm == NULL) {
ret = -ENOMEM;
goto out_unregister_netdev;
}
dev->ibdev.iwcm->add_ref = c2_add_ref;
dev->ibdev.iwcm->rem_ref = c2_rem_ref;
dev->ibdev.iwcm->get_qp = c2_get_qp;
dev->ibdev.iwcm->connect = c2_connect;
dev->ibdev.iwcm->accept = c2_accept;
dev->ibdev.iwcm->reject = c2_reject;
dev->ibdev.iwcm->create_listen = c2_service_create;
dev->ibdev.iwcm->destroy_listen = c2_service_destroy;
ret = ib_register_device(&dev->ibdev, NULL);
if (ret)
goto out_free_iwcm;
for (i = 0; i < ARRAY_SIZE(c2_dev_attributes); ++i) {
ret = device_create_file(&dev->ibdev.dev,
c2_dev_attributes[i]);
if (ret)
goto out_unregister_ibdev;
}
goto out;
out_unregister_ibdev:
ib_unregister_device(&dev->ibdev);
out_free_iwcm:
kfree(dev->ibdev.iwcm);
out_unregister_netdev:
unregister_netdev(dev->pseudo_netdev);
out_free_netdev:
free_netdev(dev->pseudo_netdev);
out:
pr_debug("%s:%u ret=%d\n", __func__, __LINE__, ret);
return ret;
}
void c2_unregister_device(struct c2_dev *dev)
{
pr_debug("%s:%u\n", __func__, __LINE__);
unregister_netdev(dev->pseudo_netdev);
free_netdev(dev->pseudo_netdev);
ib_unregister_device(&dev->ibdev);
}
| gpl-2.0 |
yellowback/ubuntu-precise-armadaxp | fs/nfsd/nfs3proc.c | 7964 | 25084 | /*
* Process version 3 NFS requests.
*
* Copyright (C) 1996, 1997, 1998 Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/fs.h>
#include <linux/ext2_fs.h>
#include <linux/magic.h>
#include "cache.h"
#include "xdr3.h"
#include "vfs.h"
#define NFSDDBG_FACILITY NFSDDBG_PROC
#define RETURN_STATUS(st) { resp->status = (st); return (st); }
static int nfs3_ftypes[] = {
0, /* NF3NON */
S_IFREG, /* NF3REG */
S_IFDIR, /* NF3DIR */
S_IFBLK, /* NF3BLK */
S_IFCHR, /* NF3CHR */
S_IFLNK, /* NF3LNK */
S_IFSOCK, /* NF3SOCK */
S_IFIFO, /* NF3FIFO */
};
/*
* NULL call.
*/
static __be32
nfsd3_proc_null(struct svc_rqst *rqstp, void *argp, void *resp)
{
return nfs_ok;
}
/*
* Get a file's attributes
*/
static __be32
nfsd3_proc_getattr(struct svc_rqst *rqstp, struct nfsd_fhandle *argp,
struct nfsd3_attrstat *resp)
{
int err;
__be32 nfserr;
dprintk("nfsd: GETATTR(3) %s\n",
SVCFH_fmt(&argp->fh));
fh_copy(&resp->fh, &argp->fh);
nfserr = fh_verify(rqstp, &resp->fh, 0,
NFSD_MAY_NOP | NFSD_MAY_BYPASS_GSS_ON_ROOT);
if (nfserr)
RETURN_STATUS(nfserr);
err = vfs_getattr(resp->fh.fh_export->ex_path.mnt,
resp->fh.fh_dentry, &resp->stat);
nfserr = nfserrno(err);
RETURN_STATUS(nfserr);
}
/*
* Set a file's attributes
*/
static __be32
nfsd3_proc_setattr(struct svc_rqst *rqstp, struct nfsd3_sattrargs *argp,
struct nfsd3_attrstat *resp)
{
__be32 nfserr;
dprintk("nfsd: SETATTR(3) %s\n",
SVCFH_fmt(&argp->fh));
fh_copy(&resp->fh, &argp->fh);
nfserr = nfsd_setattr(rqstp, &resp->fh, &argp->attrs,
argp->check_guard, argp->guardtime);
RETURN_STATUS(nfserr);
}
/*
* Look up a path name component
*/
static __be32
nfsd3_proc_lookup(struct svc_rqst *rqstp, struct nfsd3_diropargs *argp,
struct nfsd3_diropres *resp)
{
__be32 nfserr;
dprintk("nfsd: LOOKUP(3) %s %.*s\n",
SVCFH_fmt(&argp->fh),
argp->len,
argp->name);
fh_copy(&resp->dirfh, &argp->fh);
fh_init(&resp->fh, NFS3_FHSIZE);
nfserr = nfsd_lookup(rqstp, &resp->dirfh,
argp->name,
argp->len,
&resp->fh);
RETURN_STATUS(nfserr);
}
/*
* Check file access
*/
static __be32
nfsd3_proc_access(struct svc_rqst *rqstp, struct nfsd3_accessargs *argp,
struct nfsd3_accessres *resp)
{
__be32 nfserr;
dprintk("nfsd: ACCESS(3) %s 0x%x\n",
SVCFH_fmt(&argp->fh),
argp->access);
fh_copy(&resp->fh, &argp->fh);
resp->access = argp->access;
nfserr = nfsd_access(rqstp, &resp->fh, &resp->access, NULL);
RETURN_STATUS(nfserr);
}
/*
* Read a symlink.
*/
static __be32
nfsd3_proc_readlink(struct svc_rqst *rqstp, struct nfsd3_readlinkargs *argp,
struct nfsd3_readlinkres *resp)
{
__be32 nfserr;
dprintk("nfsd: READLINK(3) %s\n", SVCFH_fmt(&argp->fh));
/* Read the symlink. */
fh_copy(&resp->fh, &argp->fh);
resp->len = NFS3_MAXPATHLEN;
nfserr = nfsd_readlink(rqstp, &resp->fh, argp->buffer, &resp->len);
RETURN_STATUS(nfserr);
}
/*
* Read a portion of a file.
*/
static __be32
nfsd3_proc_read(struct svc_rqst *rqstp, struct nfsd3_readargs *argp,
struct nfsd3_readres *resp)
{
__be32 nfserr;
u32 max_blocksize = svc_max_payload(rqstp);
dprintk("nfsd: READ(3) %s %lu bytes at %Lu\n",
SVCFH_fmt(&argp->fh),
(unsigned long) argp->count,
(unsigned long long) argp->offset);
/* Obtain buffer pointer for payload.
* 1 (status) + 22 (post_op_attr) + 1 (count) + 1 (eof)
* + 1 (xdr opaque byte count) = 26
*/
resp->count = argp->count;
if (max_blocksize < resp->count)
resp->count = max_blocksize;
svc_reserve_auth(rqstp, ((1 + NFS3_POST_OP_ATTR_WORDS + 3)<<2) + resp->count +4);
fh_copy(&resp->fh, &argp->fh);
nfserr = nfsd_read(rqstp, &resp->fh,
argp->offset,
rqstp->rq_vec, argp->vlen,
&resp->count);
if (nfserr == 0) {
struct inode *inode = resp->fh.fh_dentry->d_inode;
resp->eof = (argp->offset + resp->count) >= inode->i_size;
}
RETURN_STATUS(nfserr);
}
/*
* Write data to a file
*/
static __be32
nfsd3_proc_write(struct svc_rqst *rqstp, struct nfsd3_writeargs *argp,
struct nfsd3_writeres *resp)
{
__be32 nfserr;
unsigned long cnt = argp->len;
dprintk("nfsd: WRITE(3) %s %d bytes at %Lu%s\n",
SVCFH_fmt(&argp->fh),
argp->len,
(unsigned long long) argp->offset,
argp->stable? " stable" : "");
fh_copy(&resp->fh, &argp->fh);
resp->committed = argp->stable;
nfserr = nfsd_write(rqstp, &resp->fh, NULL,
argp->offset,
rqstp->rq_vec, argp->vlen,
&cnt,
&resp->committed);
resp->count = cnt;
RETURN_STATUS(nfserr);
}
/*
* With NFSv3, CREATE processing is a lot easier than with NFSv2.
* At least in theory; we'll see how it fares in practice when the
* first reports about SunOS compatibility problems start to pour in...
*/
static __be32
nfsd3_proc_create(struct svc_rqst *rqstp, struct nfsd3_createargs *argp,
struct nfsd3_diropres *resp)
{
svc_fh *dirfhp, *newfhp = NULL;
struct iattr *attr;
__be32 nfserr;
dprintk("nfsd: CREATE(3) %s %.*s\n",
SVCFH_fmt(&argp->fh),
argp->len,
argp->name);
dirfhp = fh_copy(&resp->dirfh, &argp->fh);
newfhp = fh_init(&resp->fh, NFS3_FHSIZE);
attr = &argp->attrs;
/* Get the directory inode */
nfserr = fh_verify(rqstp, dirfhp, S_IFDIR, NFSD_MAY_CREATE);
if (nfserr)
RETURN_STATUS(nfserr);
/* Unfudge the mode bits */
attr->ia_mode &= ~S_IFMT;
if (!(attr->ia_valid & ATTR_MODE)) {
attr->ia_valid |= ATTR_MODE;
attr->ia_mode = S_IFREG;
} else {
attr->ia_mode = (attr->ia_mode & ~S_IFMT) | S_IFREG;
}
/* Now create the file and set attributes */
nfserr = do_nfsd_create(rqstp, dirfhp, argp->name, argp->len,
attr, newfhp,
argp->createmode, argp->verf, NULL, NULL);
RETURN_STATUS(nfserr);
}
/*
* Make directory. This operation is not idempotent.
*/
static __be32
nfsd3_proc_mkdir(struct svc_rqst *rqstp, struct nfsd3_createargs *argp,
struct nfsd3_diropres *resp)
{
__be32 nfserr;
dprintk("nfsd: MKDIR(3) %s %.*s\n",
SVCFH_fmt(&argp->fh),
argp->len,
argp->name);
argp->attrs.ia_valid &= ~ATTR_SIZE;
fh_copy(&resp->dirfh, &argp->fh);
fh_init(&resp->fh, NFS3_FHSIZE);
nfserr = nfsd_create(rqstp, &resp->dirfh, argp->name, argp->len,
&argp->attrs, S_IFDIR, 0, &resp->fh);
fh_unlock(&resp->dirfh);
RETURN_STATUS(nfserr);
}
static __be32
nfsd3_proc_symlink(struct svc_rqst *rqstp, struct nfsd3_symlinkargs *argp,
struct nfsd3_diropres *resp)
{
__be32 nfserr;
dprintk("nfsd: SYMLINK(3) %s %.*s -> %.*s\n",
SVCFH_fmt(&argp->ffh),
argp->flen, argp->fname,
argp->tlen, argp->tname);
fh_copy(&resp->dirfh, &argp->ffh);
fh_init(&resp->fh, NFS3_FHSIZE);
nfserr = nfsd_symlink(rqstp, &resp->dirfh, argp->fname, argp->flen,
argp->tname, argp->tlen,
&resp->fh, &argp->attrs);
RETURN_STATUS(nfserr);
}
/*
* Make socket/fifo/device.
*/
static __be32
nfsd3_proc_mknod(struct svc_rqst *rqstp, struct nfsd3_mknodargs *argp,
struct nfsd3_diropres *resp)
{
__be32 nfserr;
int type;
dev_t rdev = 0;
dprintk("nfsd: MKNOD(3) %s %.*s\n",
SVCFH_fmt(&argp->fh),
argp->len,
argp->name);
fh_copy(&resp->dirfh, &argp->fh);
fh_init(&resp->fh, NFS3_FHSIZE);
if (argp->ftype == 0 || argp->ftype >= NF3BAD)
RETURN_STATUS(nfserr_inval);
if (argp->ftype == NF3CHR || argp->ftype == NF3BLK) {
rdev = MKDEV(argp->major, argp->minor);
if (MAJOR(rdev) != argp->major ||
MINOR(rdev) != argp->minor)
RETURN_STATUS(nfserr_inval);
} else
if (argp->ftype != NF3SOCK && argp->ftype != NF3FIFO)
RETURN_STATUS(nfserr_inval);
type = nfs3_ftypes[argp->ftype];
nfserr = nfsd_create(rqstp, &resp->dirfh, argp->name, argp->len,
&argp->attrs, type, rdev, &resp->fh);
fh_unlock(&resp->dirfh);
RETURN_STATUS(nfserr);
}
/*
* Remove file/fifo/socket etc.
*/
static __be32
nfsd3_proc_remove(struct svc_rqst *rqstp, struct nfsd3_diropargs *argp,
struct nfsd3_attrstat *resp)
{
__be32 nfserr;
dprintk("nfsd: REMOVE(3) %s %.*s\n",
SVCFH_fmt(&argp->fh),
argp->len,
argp->name);
/* Unlink. -S_IFDIR means file must not be a directory */
fh_copy(&resp->fh, &argp->fh);
nfserr = nfsd_unlink(rqstp, &resp->fh, -S_IFDIR, argp->name, argp->len);
fh_unlock(&resp->fh);
RETURN_STATUS(nfserr);
}
/*
* Remove a directory
*/
static __be32
nfsd3_proc_rmdir(struct svc_rqst *rqstp, struct nfsd3_diropargs *argp,
struct nfsd3_attrstat *resp)
{
__be32 nfserr;
dprintk("nfsd: RMDIR(3) %s %.*s\n",
SVCFH_fmt(&argp->fh),
argp->len,
argp->name);
fh_copy(&resp->fh, &argp->fh);
nfserr = nfsd_unlink(rqstp, &resp->fh, S_IFDIR, argp->name, argp->len);
fh_unlock(&resp->fh);
RETURN_STATUS(nfserr);
}
static __be32
nfsd3_proc_rename(struct svc_rqst *rqstp, struct nfsd3_renameargs *argp,
struct nfsd3_renameres *resp)
{
__be32 nfserr;
dprintk("nfsd: RENAME(3) %s %.*s ->\n",
SVCFH_fmt(&argp->ffh),
argp->flen,
argp->fname);
dprintk("nfsd: -> %s %.*s\n",
SVCFH_fmt(&argp->tfh),
argp->tlen,
argp->tname);
fh_copy(&resp->ffh, &argp->ffh);
fh_copy(&resp->tfh, &argp->tfh);
nfserr = nfsd_rename(rqstp, &resp->ffh, argp->fname, argp->flen,
&resp->tfh, argp->tname, argp->tlen);
RETURN_STATUS(nfserr);
}
static __be32
nfsd3_proc_link(struct svc_rqst *rqstp, struct nfsd3_linkargs *argp,
struct nfsd3_linkres *resp)
{
__be32 nfserr;
dprintk("nfsd: LINK(3) %s ->\n",
SVCFH_fmt(&argp->ffh));
dprintk("nfsd: -> %s %.*s\n",
SVCFH_fmt(&argp->tfh),
argp->tlen,
argp->tname);
fh_copy(&resp->fh, &argp->ffh);
fh_copy(&resp->tfh, &argp->tfh);
nfserr = nfsd_link(rqstp, &resp->tfh, argp->tname, argp->tlen,
&resp->fh);
RETURN_STATUS(nfserr);
}
/*
* Read a portion of a directory.
*/
static __be32
nfsd3_proc_readdir(struct svc_rqst *rqstp, struct nfsd3_readdirargs *argp,
struct nfsd3_readdirres *resp)
{
__be32 nfserr;
int count;
dprintk("nfsd: READDIR(3) %s %d bytes at %d\n",
SVCFH_fmt(&argp->fh),
argp->count, (u32) argp->cookie);
/* Make sure we've room for the NULL ptr & eof flag, and shrink to
* client read size */
count = (argp->count >> 2) - 2;
/* Read directory and encode entries on the fly */
fh_copy(&resp->fh, &argp->fh);
resp->buflen = count;
resp->common.err = nfs_ok;
resp->buffer = argp->buffer;
resp->rqstp = rqstp;
nfserr = nfsd_readdir(rqstp, &resp->fh, (loff_t*) &argp->cookie,
&resp->common, nfs3svc_encode_entry);
memcpy(resp->verf, argp->verf, 8);
resp->count = resp->buffer - argp->buffer;
if (resp->offset)
xdr_encode_hyper(resp->offset, argp->cookie);
RETURN_STATUS(nfserr);
}
/*
* Read a portion of a directory, including file handles and attrs.
* For now, we choose to ignore the dircount parameter.
*/
static __be32
nfsd3_proc_readdirplus(struct svc_rqst *rqstp, struct nfsd3_readdirargs *argp,
struct nfsd3_readdirres *resp)
{
__be32 nfserr;
int count = 0;
loff_t offset;
int i;
caddr_t page_addr = NULL;
dprintk("nfsd: READDIR+(3) %s %d bytes at %d\n",
SVCFH_fmt(&argp->fh),
argp->count, (u32) argp->cookie);
/* Convert byte count to number of words (i.e. >> 2),
* and reserve room for the NULL ptr & eof flag (-2 words) */
resp->count = (argp->count >> 2) - 2;
/* Read directory and encode entries on the fly */
fh_copy(&resp->fh, &argp->fh);
resp->common.err = nfs_ok;
resp->buffer = argp->buffer;
resp->buflen = resp->count;
resp->rqstp = rqstp;
offset = argp->cookie;
nfserr = nfsd_readdir(rqstp, &resp->fh,
&offset,
&resp->common,
nfs3svc_encode_entry_plus);
memcpy(resp->verf, argp->verf, 8);
for (i=1; i<rqstp->rq_resused ; i++) {
page_addr = page_address(rqstp->rq_respages[i]);
if (((caddr_t)resp->buffer >= page_addr) &&
((caddr_t)resp->buffer < page_addr + PAGE_SIZE)) {
count += (caddr_t)resp->buffer - page_addr;
break;
}
count += PAGE_SIZE;
}
resp->count = count >> 2;
if (resp->offset) {
if (unlikely(resp->offset1)) {
/* we ended up with offset on a page boundary */
*resp->offset = htonl(offset >> 32);
*resp->offset1 = htonl(offset & 0xffffffff);
resp->offset1 = NULL;
} else {
xdr_encode_hyper(resp->offset, offset);
}
}
RETURN_STATUS(nfserr);
}
/*
* Get file system stats
*/
static __be32
nfsd3_proc_fsstat(struct svc_rqst * rqstp, struct nfsd_fhandle *argp,
struct nfsd3_fsstatres *resp)
{
__be32 nfserr;
dprintk("nfsd: FSSTAT(3) %s\n",
SVCFH_fmt(&argp->fh));
nfserr = nfsd_statfs(rqstp, &argp->fh, &resp->stats, 0);
fh_put(&argp->fh);
RETURN_STATUS(nfserr);
}
/*
* Get file system info
*/
static __be32
nfsd3_proc_fsinfo(struct svc_rqst * rqstp, struct nfsd_fhandle *argp,
struct nfsd3_fsinfores *resp)
{
__be32 nfserr;
u32 max_blocksize = svc_max_payload(rqstp);
dprintk("nfsd: FSINFO(3) %s\n",
SVCFH_fmt(&argp->fh));
resp->f_rtmax = max_blocksize;
resp->f_rtpref = max_blocksize;
resp->f_rtmult = PAGE_SIZE;
resp->f_wtmax = max_blocksize;
resp->f_wtpref = max_blocksize;
resp->f_wtmult = PAGE_SIZE;
resp->f_dtpref = PAGE_SIZE;
resp->f_maxfilesize = ~(u32) 0;
resp->f_properties = NFS3_FSF_DEFAULT;
nfserr = fh_verify(rqstp, &argp->fh, 0,
NFSD_MAY_NOP | NFSD_MAY_BYPASS_GSS_ON_ROOT);
/* Check special features of the file system. May request
* different read/write sizes for file systems known to have
* problems with large blocks */
if (nfserr == 0) {
struct super_block *sb = argp->fh.fh_dentry->d_inode->i_sb;
/* Note that we don't care for remote fs's here */
if (sb->s_magic == MSDOS_SUPER_MAGIC) {
resp->f_properties = NFS3_FSF_BILLYBOY;
}
resp->f_maxfilesize = sb->s_maxbytes;
}
fh_put(&argp->fh);
RETURN_STATUS(nfserr);
}
/*
* Get pathconf info for the specified file
*/
static __be32
nfsd3_proc_pathconf(struct svc_rqst * rqstp, struct nfsd_fhandle *argp,
struct nfsd3_pathconfres *resp)
{
__be32 nfserr;
dprintk("nfsd: PATHCONF(3) %s\n",
SVCFH_fmt(&argp->fh));
/* Set default pathconf */
resp->p_link_max = 255; /* at least */
resp->p_name_max = 255; /* at least */
resp->p_no_trunc = 0;
resp->p_chown_restricted = 1;
resp->p_case_insensitive = 0;
resp->p_case_preserving = 1;
nfserr = fh_verify(rqstp, &argp->fh, 0, NFSD_MAY_NOP);
if (nfserr == 0) {
struct super_block *sb = argp->fh.fh_dentry->d_inode->i_sb;
/* Note that we don't care for remote fs's here */
switch (sb->s_magic) {
case EXT2_SUPER_MAGIC:
resp->p_link_max = EXT2_LINK_MAX;
resp->p_name_max = EXT2_NAME_LEN;
break;
case MSDOS_SUPER_MAGIC:
resp->p_case_insensitive = 1;
resp->p_case_preserving = 0;
break;
}
}
fh_put(&argp->fh);
RETURN_STATUS(nfserr);
}
/*
* Commit a file (range) to stable storage.
*/
static __be32
nfsd3_proc_commit(struct svc_rqst * rqstp, struct nfsd3_commitargs *argp,
struct nfsd3_commitres *resp)
{
__be32 nfserr;
dprintk("nfsd: COMMIT(3) %s %u@%Lu\n",
SVCFH_fmt(&argp->fh),
argp->count,
(unsigned long long) argp->offset);
if (argp->offset > NFS_OFFSET_MAX)
RETURN_STATUS(nfserr_inval);
fh_copy(&resp->fh, &argp->fh);
nfserr = nfsd_commit(rqstp, &resp->fh, argp->offset, argp->count);
RETURN_STATUS(nfserr);
}
/*
* NFSv3 Server procedures.
* Only the results of non-idempotent operations are cached.
*/
#define nfs3svc_decode_fhandleargs nfs3svc_decode_fhandle
#define nfs3svc_encode_attrstatres nfs3svc_encode_attrstat
#define nfs3svc_encode_wccstatres nfs3svc_encode_wccstat
#define nfsd3_mkdirargs nfsd3_createargs
#define nfsd3_readdirplusargs nfsd3_readdirargs
#define nfsd3_fhandleargs nfsd_fhandle
#define nfsd3_fhandleres nfsd3_attrstat
#define nfsd3_attrstatres nfsd3_attrstat
#define nfsd3_wccstatres nfsd3_attrstat
#define nfsd3_createres nfsd3_diropres
#define nfsd3_voidres nfsd3_voidargs
struct nfsd3_voidargs { int dummy; };
#define PROC(name, argt, rest, relt, cache, respsize) \
{ (svc_procfunc) nfsd3_proc_##name, \
(kxdrproc_t) nfs3svc_decode_##argt##args, \
(kxdrproc_t) nfs3svc_encode_##rest##res, \
(kxdrproc_t) nfs3svc_release_##relt, \
sizeof(struct nfsd3_##argt##args), \
sizeof(struct nfsd3_##rest##res), \
0, \
cache, \
respsize, \
}
#define ST 1 /* status*/
#define FH 17 /* filehandle with length */
#define AT 21 /* attributes */
#define pAT (1+AT) /* post attributes - conditional */
#define WC (7+pAT) /* WCC attributes */
static struct svc_procedure nfsd_procedures3[22] = {
[NFS3PROC_NULL] = {
.pc_func = (svc_procfunc) nfsd3_proc_null,
.pc_encode = (kxdrproc_t) nfs3svc_encode_voidres,
.pc_argsize = sizeof(struct nfsd3_voidargs),
.pc_ressize = sizeof(struct nfsd3_voidres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST,
},
[NFS3PROC_GETATTR] = {
.pc_func = (svc_procfunc) nfsd3_proc_getattr,
.pc_decode = (kxdrproc_t) nfs3svc_decode_fhandleargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_attrstatres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_fhandleargs),
.pc_ressize = sizeof(struct nfsd3_attrstatres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+AT,
},
[NFS3PROC_SETATTR] = {
.pc_func = (svc_procfunc) nfsd3_proc_setattr,
.pc_decode = (kxdrproc_t) nfs3svc_decode_sattrargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_wccstatres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_sattrargs),
.pc_ressize = sizeof(struct nfsd3_wccstatres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+WC,
},
[NFS3PROC_LOOKUP] = {
.pc_func = (svc_procfunc) nfsd3_proc_lookup,
.pc_decode = (kxdrproc_t) nfs3svc_decode_diropargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_diropres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle2,
.pc_argsize = sizeof(struct nfsd3_diropargs),
.pc_ressize = sizeof(struct nfsd3_diropres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+FH+pAT+pAT,
},
[NFS3PROC_ACCESS] = {
.pc_func = (svc_procfunc) nfsd3_proc_access,
.pc_decode = (kxdrproc_t) nfs3svc_decode_accessargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_accessres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_accessargs),
.pc_ressize = sizeof(struct nfsd3_accessres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+pAT+1,
},
[NFS3PROC_READLINK] = {
.pc_func = (svc_procfunc) nfsd3_proc_readlink,
.pc_decode = (kxdrproc_t) nfs3svc_decode_readlinkargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_readlinkres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_readlinkargs),
.pc_ressize = sizeof(struct nfsd3_readlinkres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+pAT+1+NFS3_MAXPATHLEN/4,
},
[NFS3PROC_READ] = {
.pc_func = (svc_procfunc) nfsd3_proc_read,
.pc_decode = (kxdrproc_t) nfs3svc_decode_readargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_readres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_readargs),
.pc_ressize = sizeof(struct nfsd3_readres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+pAT+4+NFSSVC_MAXBLKSIZE/4,
},
[NFS3PROC_WRITE] = {
.pc_func = (svc_procfunc) nfsd3_proc_write,
.pc_decode = (kxdrproc_t) nfs3svc_decode_writeargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_writeres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_writeargs),
.pc_ressize = sizeof(struct nfsd3_writeres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+WC+4,
},
[NFS3PROC_CREATE] = {
.pc_func = (svc_procfunc) nfsd3_proc_create,
.pc_decode = (kxdrproc_t) nfs3svc_decode_createargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_createres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle2,
.pc_argsize = sizeof(struct nfsd3_createargs),
.pc_ressize = sizeof(struct nfsd3_createres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+(1+FH+pAT)+WC,
},
[NFS3PROC_MKDIR] = {
.pc_func = (svc_procfunc) nfsd3_proc_mkdir,
.pc_decode = (kxdrproc_t) nfs3svc_decode_mkdirargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_createres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle2,
.pc_argsize = sizeof(struct nfsd3_mkdirargs),
.pc_ressize = sizeof(struct nfsd3_createres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+(1+FH+pAT)+WC,
},
[NFS3PROC_SYMLINK] = {
.pc_func = (svc_procfunc) nfsd3_proc_symlink,
.pc_decode = (kxdrproc_t) nfs3svc_decode_symlinkargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_createres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle2,
.pc_argsize = sizeof(struct nfsd3_symlinkargs),
.pc_ressize = sizeof(struct nfsd3_createres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+(1+FH+pAT)+WC,
},
[NFS3PROC_MKNOD] = {
.pc_func = (svc_procfunc) nfsd3_proc_mknod,
.pc_decode = (kxdrproc_t) nfs3svc_decode_mknodargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_createres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle2,
.pc_argsize = sizeof(struct nfsd3_mknodargs),
.pc_ressize = sizeof(struct nfsd3_createres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+(1+FH+pAT)+WC,
},
[NFS3PROC_REMOVE] = {
.pc_func = (svc_procfunc) nfsd3_proc_remove,
.pc_decode = (kxdrproc_t) nfs3svc_decode_diropargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_wccstatres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_diropargs),
.pc_ressize = sizeof(struct nfsd3_wccstatres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+WC,
},
[NFS3PROC_RMDIR] = {
.pc_func = (svc_procfunc) nfsd3_proc_rmdir,
.pc_decode = (kxdrproc_t) nfs3svc_decode_diropargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_wccstatres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_diropargs),
.pc_ressize = sizeof(struct nfsd3_wccstatres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+WC,
},
[NFS3PROC_RENAME] = {
.pc_func = (svc_procfunc) nfsd3_proc_rename,
.pc_decode = (kxdrproc_t) nfs3svc_decode_renameargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_renameres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle2,
.pc_argsize = sizeof(struct nfsd3_renameargs),
.pc_ressize = sizeof(struct nfsd3_renameres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+WC+WC,
},
[NFS3PROC_LINK] = {
.pc_func = (svc_procfunc) nfsd3_proc_link,
.pc_decode = (kxdrproc_t) nfs3svc_decode_linkargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_linkres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle2,
.pc_argsize = sizeof(struct nfsd3_linkargs),
.pc_ressize = sizeof(struct nfsd3_linkres),
.pc_cachetype = RC_REPLBUFF,
.pc_xdrressize = ST+pAT+WC,
},
[NFS3PROC_READDIR] = {
.pc_func = (svc_procfunc) nfsd3_proc_readdir,
.pc_decode = (kxdrproc_t) nfs3svc_decode_readdirargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_readdirres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_readdirargs),
.pc_ressize = sizeof(struct nfsd3_readdirres),
.pc_cachetype = RC_NOCACHE,
},
[NFS3PROC_READDIRPLUS] = {
.pc_func = (svc_procfunc) nfsd3_proc_readdirplus,
.pc_decode = (kxdrproc_t) nfs3svc_decode_readdirplusargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_readdirres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_readdirplusargs),
.pc_ressize = sizeof(struct nfsd3_readdirres),
.pc_cachetype = RC_NOCACHE,
},
[NFS3PROC_FSSTAT] = {
.pc_func = (svc_procfunc) nfsd3_proc_fsstat,
.pc_decode = (kxdrproc_t) nfs3svc_decode_fhandleargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_fsstatres,
.pc_argsize = sizeof(struct nfsd3_fhandleargs),
.pc_ressize = sizeof(struct nfsd3_fsstatres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+pAT+2*6+1,
},
[NFS3PROC_FSINFO] = {
.pc_func = (svc_procfunc) nfsd3_proc_fsinfo,
.pc_decode = (kxdrproc_t) nfs3svc_decode_fhandleargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_fsinfores,
.pc_argsize = sizeof(struct nfsd3_fhandleargs),
.pc_ressize = sizeof(struct nfsd3_fsinfores),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+pAT+12,
},
[NFS3PROC_PATHCONF] = {
.pc_func = (svc_procfunc) nfsd3_proc_pathconf,
.pc_decode = (kxdrproc_t) nfs3svc_decode_fhandleargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_pathconfres,
.pc_argsize = sizeof(struct nfsd3_fhandleargs),
.pc_ressize = sizeof(struct nfsd3_pathconfres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+pAT+6,
},
[NFS3PROC_COMMIT] = {
.pc_func = (svc_procfunc) nfsd3_proc_commit,
.pc_decode = (kxdrproc_t) nfs3svc_decode_commitargs,
.pc_encode = (kxdrproc_t) nfs3svc_encode_commitres,
.pc_release = (kxdrproc_t) nfs3svc_release_fhandle,
.pc_argsize = sizeof(struct nfsd3_commitargs),
.pc_ressize = sizeof(struct nfsd3_commitres),
.pc_cachetype = RC_NOCACHE,
.pc_xdrressize = ST+WC+2,
},
};
struct svc_version nfsd_version3 = {
.vs_vers = 3,
.vs_nproc = 22,
.vs_proc = nfsd_procedures3,
.vs_dispatch = nfsd_dispatch,
.vs_xdrsize = NFS3_SVC_XDRSIZE,
};
| gpl-2.0 |
koying/buildroot-linux-kernel-m3-pivos | arch/um/os-Linux/execvp.c | 9756 | 4095 | /* Copyright (C) 2006 by Paolo Giarrusso - modified from glibc' execvp.c.
Original copyright notice follows:
Copyright (C) 1991,92,1995-99,2002,2004 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#ifndef TEST
#include "um_malloc.h"
#else
#include <stdio.h>
#define um_kmalloc malloc
#endif
#include "os.h"
/* Execute FILE, searching in the `PATH' environment variable if it contains
no slashes, with arguments ARGV and environment from `environ'. */
int execvp_noalloc(char *buf, const char *file, char *const argv[])
{
if (*file == '\0') {
return -ENOENT;
}
if (strchr (file, '/') != NULL) {
/* Don't search when it contains a slash. */
execv(file, argv);
} else {
int got_eacces;
size_t len, pathlen;
char *name, *p;
char *path = getenv("PATH");
if (path == NULL)
path = ":/bin:/usr/bin";
len = strlen(file) + 1;
pathlen = strlen(path);
/* Copy the file name at the top. */
name = memcpy(buf + pathlen + 1, file, len);
/* And add the slash. */
*--name = '/';
got_eacces = 0;
p = path;
do {
char *startp;
path = p;
//Let's avoid this GNU extension.
//p = strchrnul (path, ':');
p = strchr(path, ':');
if (!p)
p = strchr(path, '\0');
if (p == path)
/* Two adjacent colons, or a colon at the beginning or the end
of `PATH' means to search the current directory. */
startp = name + 1;
else
startp = memcpy(name - (p - path), path, p - path);
/* Try to execute this name. If it works, execv will not return. */
execv(startp, argv);
/*
if (errno == ENOEXEC) {
}
*/
switch (errno) {
case EACCES:
/* Record the we got a `Permission denied' error. If we end
up finding no executable we can use, we want to diagnose
that we did find one but were denied access. */
got_eacces = 1;
case ENOENT:
case ESTALE:
case ENOTDIR:
/* Those errors indicate the file is missing or not executable
by us, in which case we want to just try the next path
directory. */
case ENODEV:
case ETIMEDOUT:
/* Some strange filesystems like AFS return even
stranger error numbers. They cannot reasonably mean
anything else so ignore those, too. */
case ENOEXEC:
/* We won't go searching for the shell
* if it is not executable - the Linux
* kernel already handles this enough,
* for us. */
break;
default:
/* Some other error means we found an executable file, but
something went wrong executing it; return the error to our
caller. */
return -errno;
}
} while (*p++ != '\0');
/* We tried every element and none of them worked. */
if (got_eacces)
/* At least one failure was due to permissions, so report that
error. */
return -EACCES;
}
/* Return the error from the last attempt (probably ENOENT). */
return -errno;
}
#ifdef TEST
int main(int argc, char**argv)
{
char buf[PATH_MAX];
int ret;
argc--;
if (!argc) {
fprintf(stderr, "Not enough arguments\n");
return 1;
}
argv++;
if (ret = execvp_noalloc(buf, argv[0], argv)) {
errno = -ret;
perror("execvp_noalloc");
}
return 0;
}
#endif
| gpl-2.0 |
hominlinx/linux-bananapi | net/tipc/netlink.c | 9756 | 3475 | /*
* net/tipc/netlink.c: TIPC configuration handling
*
* Copyright (c) 2005-2006, Ericsson AB
* Copyright (c) 2005-2007, Wind River Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "core.h"
#include "config.h"
#include <net/genetlink.h>
static int handle_cmd(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *rep_buf;
struct nlmsghdr *rep_nlh;
struct nlmsghdr *req_nlh = info->nlhdr;
struct tipc_genlmsghdr *req_userhdr = info->userhdr;
int hdr_space = NLMSG_SPACE(GENL_HDRLEN + TIPC_GENL_HDRLEN);
u16 cmd;
if ((req_userhdr->cmd & 0xC000) && (!capable(CAP_NET_ADMIN)))
cmd = TIPC_CMD_NOT_NET_ADMIN;
else
cmd = req_userhdr->cmd;
rep_buf = tipc_cfg_do_cmd(req_userhdr->dest, cmd,
NLMSG_DATA(req_nlh) + GENL_HDRLEN + TIPC_GENL_HDRLEN,
NLMSG_PAYLOAD(req_nlh, GENL_HDRLEN + TIPC_GENL_HDRLEN),
hdr_space);
if (rep_buf) {
skb_push(rep_buf, hdr_space);
rep_nlh = nlmsg_hdr(rep_buf);
memcpy(rep_nlh, req_nlh, hdr_space);
rep_nlh->nlmsg_len = rep_buf->len;
genlmsg_unicast(&init_net, rep_buf, NETLINK_CB(skb).pid);
}
return 0;
}
static struct genl_family tipc_genl_family = {
.id = GENL_ID_GENERATE,
.name = TIPC_GENL_NAME,
.version = TIPC_GENL_VERSION,
.hdrsize = TIPC_GENL_HDRLEN,
.maxattr = 0,
};
static struct genl_ops tipc_genl_ops = {
.cmd = TIPC_GENL_CMD,
.doit = handle_cmd,
};
static int tipc_genl_family_registered;
int tipc_netlink_start(void)
{
int res;
res = genl_register_family_with_ops(&tipc_genl_family,
&tipc_genl_ops, 1);
if (res) {
err("Failed to register netlink interface\n");
return res;
}
tipc_genl_family_registered = 1;
return 0;
}
void tipc_netlink_stop(void)
{
if (!tipc_genl_family_registered)
return;
genl_unregister_family(&tipc_genl_family);
tipc_genl_family_registered = 0;
}
| gpl-2.0 |
jcadduono/nethunter_kernel_g5 | arch/m68k/lib/ashrdi3.c | 12828 | 1690 | /* ashrdi3.c extracted from gcc-2.7.2/libgcc2.c which is: */
/* Copyright (C) 1989, 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
This file is part of GNU CC.
GNU CC 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.
GNU CC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU CC; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#define BITS_PER_UNIT 8
typedef int SItype __attribute__ ((mode (SI)));
typedef unsigned int USItype __attribute__ ((mode (SI)));
typedef int DItype __attribute__ ((mode (DI)));
typedef int word_type __attribute__ ((mode (__word__)));
struct DIstruct {SItype high, low;};
typedef union
{
struct DIstruct s;
DItype ll;
} DIunion;
DItype
__ashrdi3 (DItype u, word_type b)
{
DIunion w;
word_type bm;
DIunion uu;
if (b == 0)
return u;
uu.ll = u;
bm = (sizeof (SItype) * BITS_PER_UNIT) - b;
if (bm <= 0)
{
/* w.s.high = 1..1 or 0..0 */
w.s.high = uu.s.high >> (sizeof (SItype) * BITS_PER_UNIT - 1);
w.s.low = uu.s.high >> -bm;
}
else
{
USItype carries = (USItype)uu.s.high << bm;
w.s.high = uu.s.high >> b;
w.s.low = ((USItype)uu.s.low >> b) | carries;
}
return w.ll;
}
| gpl-2.0 |
jeboo/kernel_JB_I9100official | drivers/ide/ide-timings.c | 13852 | 6661 | /*
* Copyright (c) 1999-2001 Vojtech Pavlik
* Copyright (c) 2007-2008 Bartlomiej Zolnierkiewicz
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/kernel.h>
#include <linux/ide.h>
#include <linux/module.h>
/*
* PIO 0-5, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
* These were taken from ATA/ATAPI-6 standard, rev 0a, except
* for PIO 5, which is a nonstandard extension and UDMA6, which
* is currently supported only by Maxtor drives.
*/
static struct ide_timing ide_timing[] = {
{ XFER_UDMA_6, 0, 0, 0, 0, 0, 0, 0, 15 },
{ XFER_UDMA_5, 0, 0, 0, 0, 0, 0, 0, 20 },
{ XFER_UDMA_4, 0, 0, 0, 0, 0, 0, 0, 30 },
{ XFER_UDMA_3, 0, 0, 0, 0, 0, 0, 0, 45 },
{ XFER_UDMA_2, 0, 0, 0, 0, 0, 0, 0, 60 },
{ XFER_UDMA_1, 0, 0, 0, 0, 0, 0, 0, 80 },
{ XFER_UDMA_0, 0, 0, 0, 0, 0, 0, 0, 120 },
{ XFER_MW_DMA_4, 25, 0, 0, 0, 55, 20, 80, 0 },
{ XFER_MW_DMA_3, 25, 0, 0, 0, 65, 25, 100, 0 },
{ XFER_MW_DMA_2, 25, 0, 0, 0, 70, 25, 120, 0 },
{ XFER_MW_DMA_1, 45, 0, 0, 0, 80, 50, 150, 0 },
{ XFER_MW_DMA_0, 60, 0, 0, 0, 215, 215, 480, 0 },
{ XFER_SW_DMA_2, 60, 0, 0, 0, 120, 120, 240, 0 },
{ XFER_SW_DMA_1, 90, 0, 0, 0, 240, 240, 480, 0 },
{ XFER_SW_DMA_0, 120, 0, 0, 0, 480, 480, 960, 0 },
{ XFER_PIO_6, 10, 55, 20, 80, 55, 20, 80, 0 },
{ XFER_PIO_5, 15, 65, 25, 100, 65, 25, 100, 0 },
{ XFER_PIO_4, 25, 70, 25, 120, 70, 25, 120, 0 },
{ XFER_PIO_3, 30, 80, 70, 180, 80, 70, 180, 0 },
{ XFER_PIO_2, 30, 290, 40, 330, 100, 90, 240, 0 },
{ XFER_PIO_1, 50, 290, 93, 383, 125, 100, 383, 0 },
{ XFER_PIO_0, 70, 290, 240, 600, 165, 150, 600, 0 },
{ XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 960, 0 },
{ 0xff }
};
struct ide_timing *ide_timing_find_mode(u8 speed)
{
struct ide_timing *t;
for (t = ide_timing; t->mode != speed; t++)
if (t->mode == 0xff)
return NULL;
return t;
}
EXPORT_SYMBOL_GPL(ide_timing_find_mode);
u16 ide_pio_cycle_time(ide_drive_t *drive, u8 pio)
{
u16 *id = drive->id;
struct ide_timing *t = ide_timing_find_mode(XFER_PIO_0 + pio);
u16 cycle = 0;
if (id[ATA_ID_FIELD_VALID] & 2) {
if (ata_id_has_iordy(drive->id))
cycle = id[ATA_ID_EIDE_PIO_IORDY];
else
cycle = id[ATA_ID_EIDE_PIO];
/* conservative "downgrade" for all pre-ATA2 drives */
if (pio < 3 && cycle < t->cycle)
cycle = 0; /* use standard timing */
/* Use the standard timing for the CF specific modes too */
if (pio > 4 && ata_id_is_cfa(id))
cycle = 0;
}
return cycle ? cycle : t->cycle;
}
EXPORT_SYMBOL_GPL(ide_pio_cycle_time);
#define ENOUGH(v, unit) (((v) - 1) / (unit) + 1)
#define EZ(v, unit) ((v) ? ENOUGH(v, unit) : 0)
static void ide_timing_quantize(struct ide_timing *t, struct ide_timing *q,
int T, int UT)
{
q->setup = EZ(t->setup * 1000, T);
q->act8b = EZ(t->act8b * 1000, T);
q->rec8b = EZ(t->rec8b * 1000, T);
q->cyc8b = EZ(t->cyc8b * 1000, T);
q->active = EZ(t->active * 1000, T);
q->recover = EZ(t->recover * 1000, T);
q->cycle = EZ(t->cycle * 1000, T);
q->udma = EZ(t->udma * 1000, UT);
}
void ide_timing_merge(struct ide_timing *a, struct ide_timing *b,
struct ide_timing *m, unsigned int what)
{
if (what & IDE_TIMING_SETUP)
m->setup = max(a->setup, b->setup);
if (what & IDE_TIMING_ACT8B)
m->act8b = max(a->act8b, b->act8b);
if (what & IDE_TIMING_REC8B)
m->rec8b = max(a->rec8b, b->rec8b);
if (what & IDE_TIMING_CYC8B)
m->cyc8b = max(a->cyc8b, b->cyc8b);
if (what & IDE_TIMING_ACTIVE)
m->active = max(a->active, b->active);
if (what & IDE_TIMING_RECOVER)
m->recover = max(a->recover, b->recover);
if (what & IDE_TIMING_CYCLE)
m->cycle = max(a->cycle, b->cycle);
if (what & IDE_TIMING_UDMA)
m->udma = max(a->udma, b->udma);
}
EXPORT_SYMBOL_GPL(ide_timing_merge);
int ide_timing_compute(ide_drive_t *drive, u8 speed,
struct ide_timing *t, int T, int UT)
{
u16 *id = drive->id;
struct ide_timing *s, p;
/*
* Find the mode.
*/
s = ide_timing_find_mode(speed);
if (s == NULL)
return -EINVAL;
/*
* Copy the timing from the table.
*/
*t = *s;
/*
* If the drive is an EIDE drive, it can tell us it needs extended
* PIO/MWDMA cycle timing.
*/
if (id[ATA_ID_FIELD_VALID] & 2) { /* EIDE drive */
memset(&p, 0, sizeof(p));
if (speed >= XFER_PIO_0 && speed < XFER_SW_DMA_0) {
if (speed <= XFER_PIO_2)
p.cycle = p.cyc8b = id[ATA_ID_EIDE_PIO];
else if ((speed <= XFER_PIO_4) ||
(speed == XFER_PIO_5 && !ata_id_is_cfa(id)))
p.cycle = p.cyc8b = id[ATA_ID_EIDE_PIO_IORDY];
} else if (speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2)
p.cycle = id[ATA_ID_EIDE_DMA_MIN];
ide_timing_merge(&p, t, t, IDE_TIMING_CYCLE | IDE_TIMING_CYC8B);
}
/*
* Convert the timing to bus clock counts.
*/
ide_timing_quantize(t, t, T, UT);
/*
* Even in DMA/UDMA modes we still use PIO access for IDENTIFY,
* S.M.A.R.T and some other commands. We have to ensure that the
* DMA cycle timing is slower/equal than the current PIO timing.
*/
if (speed >= XFER_SW_DMA_0) {
ide_timing_compute(drive, drive->pio_mode, &p, T, UT);
ide_timing_merge(&p, t, t, IDE_TIMING_ALL);
}
/*
* Lengthen active & recovery time so that cycle time is correct.
*/
if (t->act8b + t->rec8b < t->cyc8b) {
t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
t->rec8b = t->cyc8b - t->act8b;
}
if (t->active + t->recover < t->cycle) {
t->active += (t->cycle - (t->active + t->recover)) / 2;
t->recover = t->cycle - t->active;
}
return 0;
}
EXPORT_SYMBOL_GPL(ide_timing_compute);
| gpl-2.0 |
sameersethi/minorproject-asterisk | addons/ooh323c/src/rtctype.c | 29 | 7745 | /*
* Copyright (C) 1997-2005 by Objective Systems, Inc.
*
* This software is furnished under an open source license and may be
* used and copied only in accordance with the terms of this license.
* The text of the license may generally be found in the root
* directory of this installation in the COPYING file. It
* can also be viewed online at the following URL:
*
* http://www.obj-sys.com/open/license.html
*
* Any redistributions of this file including modified versions must
* maintain this copyright notice.
*
*****************************************************************************/
/* Run-time ctype substitution */
#include "asterisk.h"
#include "asterisk/lock.h"
#include "ooasn1.h"
#include "rtctype.h"
const ASN1OCTET rtCtypeTable[256] = {
OS_CTYPE_CTRL, /* 00 (NUL) */
OS_CTYPE_CTRL, /* 01 (SOH) */
OS_CTYPE_CTRL, /* 02 (STX) */
OS_CTYPE_CTRL, /* 03 (ETX) */
OS_CTYPE_CTRL, /* 04 (EOT) */
OS_CTYPE_CTRL, /* 05 (ENQ) */
OS_CTYPE_CTRL, /* 06 (ACK) */
OS_CTYPE_CTRL, /* 07 (BEL) */
OS_CTYPE_CTRL, /* 08 (BS) */
OS_CTYPE_CTRL|OS_CTYPE_SPACE, /* 09 (HT) */
OS_CTYPE_CTRL|OS_CTYPE_SPACE, /* 0A (LF) */
OS_CTYPE_CTRL|OS_CTYPE_SPACE, /* 0B (VT) */
OS_CTYPE_CTRL|OS_CTYPE_SPACE, /* 0C (FF) */
OS_CTYPE_CTRL|OS_CTYPE_SPACE, /* 0D (CR) */
OS_CTYPE_CTRL, /* 0E (SI) */
OS_CTYPE_CTRL, /* 0F (SO) */
OS_CTYPE_CTRL, /* 10 (DLE) */
OS_CTYPE_CTRL, /* 11 (DC1) */
OS_CTYPE_CTRL, /* 12 (DC2) */
OS_CTYPE_CTRL, /* 13 (DC3) */
OS_CTYPE_CTRL, /* 14 (DC4) */
OS_CTYPE_CTRL, /* 15 (NAK) */
OS_CTYPE_CTRL, /* 16 (SYN) */
OS_CTYPE_CTRL, /* 17 (ETB) */
OS_CTYPE_CTRL, /* 18 (CAN) */
OS_CTYPE_CTRL, /* 19 (EM) */
OS_CTYPE_CTRL, /* 1A (SUB) */
OS_CTYPE_CTRL, /* 1B (ESC) */
OS_CTYPE_CTRL, /* 1C (FS) */
OS_CTYPE_CTRL, /* 1D (GS) */
OS_CTYPE_CTRL, /* 1E (RS) */
OS_CTYPE_CTRL, /* 1F (US) */
OS_CTYPE_SPACE|OS_CTYPE_BLANK, /* 20 SPACE */
OS_CTYPE_PUNCT, /* 21 ! */
OS_CTYPE_PUNCT, /* 22 " */
OS_CTYPE_PUNCT, /* 23 # */
OS_CTYPE_PUNCT, /* 24 $ */
OS_CTYPE_PUNCT, /* 25 % */
OS_CTYPE_PUNCT, /* 26 & */
OS_CTYPE_PUNCT, /* 27 ' */
OS_CTYPE_PUNCT, /* 28 ( */
OS_CTYPE_PUNCT, /* 29 ) */
OS_CTYPE_PUNCT, /* 2A * */
OS_CTYPE_PUNCT, /* 2B + */
OS_CTYPE_PUNCT, /* 2C , */
OS_CTYPE_PUNCT, /* 2D - */
OS_CTYPE_PUNCT, /* 2E . */
OS_CTYPE_PUNCT, /* 2F / */
OS_CTYPE_NUMBER, /* 30 0 */
OS_CTYPE_NUMBER, /* 31 1 */
OS_CTYPE_NUMBER, /* 32 2 */
OS_CTYPE_NUMBER, /* 33 3 */
OS_CTYPE_NUMBER, /* 34 4 */
OS_CTYPE_NUMBER, /* 35 5 */
OS_CTYPE_NUMBER, /* 36 6 */
OS_CTYPE_NUMBER, /* 37 7 */
OS_CTYPE_NUMBER, /* 38 8 */
OS_CTYPE_NUMBER, /* 39 9 */
OS_CTYPE_PUNCT, /* 3A : */
OS_CTYPE_PUNCT, /* 3B ; */
OS_CTYPE_PUNCT, /* 3C < */
OS_CTYPE_PUNCT, /* 3D = */
OS_CTYPE_PUNCT, /* 3E > */
OS_CTYPE_PUNCT, /* 3F ? */
OS_CTYPE_PUNCT, /* 40 @ */
OS_CTYPE_UPPER|OS_CTYPE_HEX, /* 41 A */
OS_CTYPE_UPPER|OS_CTYPE_HEX, /* 42 B */
OS_CTYPE_UPPER|OS_CTYPE_HEX, /* 43 C */
OS_CTYPE_UPPER|OS_CTYPE_HEX, /* 44 D */
OS_CTYPE_UPPER|OS_CTYPE_HEX, /* 45 E */
OS_CTYPE_UPPER|OS_CTYPE_HEX, /* 46 F */
OS_CTYPE_UPPER, /* 47 G */
OS_CTYPE_UPPER, /* 48 H */
OS_CTYPE_UPPER, /* 49 I */
OS_CTYPE_UPPER, /* 4A J */
OS_CTYPE_UPPER, /* 4B K */
OS_CTYPE_UPPER, /* 4C L */
OS_CTYPE_UPPER, /* 4D M */
OS_CTYPE_UPPER, /* 4E N */
OS_CTYPE_UPPER, /* 4F O */
OS_CTYPE_UPPER, /* 50 P */
OS_CTYPE_UPPER, /* 51 Q */
OS_CTYPE_UPPER, /* 52 R */
OS_CTYPE_UPPER, /* 53 S */
OS_CTYPE_UPPER, /* 54 T */
OS_CTYPE_UPPER, /* 55 U */
OS_CTYPE_UPPER, /* 56 V */
OS_CTYPE_UPPER, /* 57 W */
OS_CTYPE_UPPER, /* 58 X */
OS_CTYPE_UPPER, /* 59 Y */
OS_CTYPE_UPPER, /* 5A Z */
OS_CTYPE_PUNCT, /* 5B [ */
OS_CTYPE_PUNCT, /* 5C \ */
OS_CTYPE_PUNCT, /* 5D ] */
OS_CTYPE_PUNCT, /* 5E ^ */
OS_CTYPE_PUNCT, /* 5F _ */
OS_CTYPE_PUNCT, /* 60 ` */
OS_CTYPE_LOWER|OS_CTYPE_HEX, /* 61 a */
OS_CTYPE_LOWER|OS_CTYPE_HEX, /* 62 b */
OS_CTYPE_LOWER|OS_CTYPE_HEX, /* 63 c */
OS_CTYPE_LOWER|OS_CTYPE_HEX, /* 64 d */
OS_CTYPE_LOWER|OS_CTYPE_HEX, /* 65 e */
OS_CTYPE_LOWER|OS_CTYPE_HEX, /* 66 f */
OS_CTYPE_LOWER, /* 67 g */
OS_CTYPE_LOWER, /* 68 h */
OS_CTYPE_LOWER, /* 69 i */
OS_CTYPE_LOWER, /* 6A j */
OS_CTYPE_LOWER, /* 6B k */
OS_CTYPE_LOWER, /* 6C l */
OS_CTYPE_LOWER, /* 6D m */
OS_CTYPE_LOWER, /* 6E n */
OS_CTYPE_LOWER, /* 6F o */
OS_CTYPE_LOWER, /* 70 p */
OS_CTYPE_LOWER, /* 71 q */
OS_CTYPE_LOWER, /* 72 r */
OS_CTYPE_LOWER, /* 73 s */
OS_CTYPE_LOWER, /* 74 t */
OS_CTYPE_LOWER, /* 75 u */
OS_CTYPE_LOWER, /* 76 v */
OS_CTYPE_LOWER, /* 77 w */
OS_CTYPE_LOWER, /* 78 x */
OS_CTYPE_LOWER, /* 79 y */
OS_CTYPE_LOWER, /* 7A z */
OS_CTYPE_PUNCT, /* 7B { */
OS_CTYPE_PUNCT, /* 7C | */
OS_CTYPE_PUNCT, /* 7D } */
OS_CTYPE_PUNCT, /* 7E ~ */
OS_CTYPE_CTRL, /* 7F (DEL) */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
| gpl-2.0 |
sartakov/nv-qemu | hw/puv3_intc.c | 29 | 3254 | /*
* INTC device simulation in PKUnity SoC
*
* Copyright (C) 2010-2012 Guan Xuetao
*
* 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, or any later version.
* See the COPYING file in the top-level directory.
*/
#include "sysbus.h"
#undef DEBUG_PUV3
#include "puv3.h"
typedef struct {
SysBusDevice busdev;
MemoryRegion iomem;
qemu_irq parent_irq;
uint32_t reg_ICMR;
uint32_t reg_ICPR;
} PUV3INTCState;
/* Update interrupt status after enabled or pending bits have been changed. */
static void puv3_intc_update(PUV3INTCState *s)
{
if (s->reg_ICMR & s->reg_ICPR) {
qemu_irq_raise(s->parent_irq);
} else {
qemu_irq_lower(s->parent_irq);
}
}
/* Process a change in an external INTC input. */
static void puv3_intc_handler(void *opaque, int irq, int level)
{
PUV3INTCState *s = opaque;
DPRINTF("irq 0x%x, level 0x%x\n", irq, level);
if (level) {
s->reg_ICPR |= (1 << irq);
} else {
s->reg_ICPR &= ~(1 << irq);
}
puv3_intc_update(s);
}
static uint64_t puv3_intc_read(void *opaque, hwaddr offset,
unsigned size)
{
PUV3INTCState *s = opaque;
uint32_t ret = 0;
switch (offset) {
case 0x04: /* INTC_ICMR */
ret = s->reg_ICMR;
break;
case 0x0c: /* INTC_ICIP */
ret = s->reg_ICPR; /* the same value with ICPR */
break;
default:
DPRINTF("Bad offset %x\n", (int)offset);
}
DPRINTF("offset 0x%x, value 0x%x\n", offset, ret);
return ret;
}
static void puv3_intc_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
PUV3INTCState *s = opaque;
DPRINTF("offset 0x%x, value 0x%x\n", offset, value);
switch (offset) {
case 0x00: /* INTC_ICLR */
case 0x14: /* INTC_ICCR */
break;
case 0x04: /* INTC_ICMR */
s->reg_ICMR = value;
break;
default:
DPRINTF("Bad offset 0x%x\n", (int)offset);
return;
}
puv3_intc_update(s);
}
static const MemoryRegionOps puv3_intc_ops = {
.read = puv3_intc_read,
.write = puv3_intc_write,
.impl = {
.min_access_size = 4,
.max_access_size = 4,
},
.endianness = DEVICE_NATIVE_ENDIAN,
};
static int puv3_intc_init(SysBusDevice *dev)
{
PUV3INTCState *s = FROM_SYSBUS(PUV3INTCState, dev);
qdev_init_gpio_in(&s->busdev.qdev, puv3_intc_handler, PUV3_IRQS_NR);
sysbus_init_irq(&s->busdev, &s->parent_irq);
s->reg_ICMR = 0;
s->reg_ICPR = 0;
memory_region_init_io(&s->iomem, &puv3_intc_ops, s, "puv3_intc",
PUV3_REGS_OFFSET);
sysbus_init_mmio(dev, &s->iomem);
return 0;
}
static void puv3_intc_class_init(ObjectClass *klass, void *data)
{
SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);
sdc->init = puv3_intc_init;
}
static const TypeInfo puv3_intc_info = {
.name = "puv3_intc",
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(PUV3INTCState),
.class_init = puv3_intc_class_init,
};
static void puv3_intc_register_type(void)
{
type_register_static(&puv3_intc_info);
}
type_init(puv3_intc_register_type)
| gpl-2.0 |
eriklindahl/fftw3 | mpi/rearrange.c | 29 | 2115 | /*
* Copyright (c) 2003, 2007-14 Matteo Frigo
* Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology
*
* 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 "ifftw-mpi.h"
/* common functions for rearrangements of the data for the *-rank1-bigvec
solvers */
static int div_mult(INT b, INT a) {
return (a > b && a % b == 0);
}
static int div_mult2(INT b, INT a, INT n) {
return (div_mult(b, a) && div_mult(n, b));
}
int XM(rearrange_applicable)(rearrangement rearrange,
ddim dim0, INT vn, int n_pes)
{
/* note: it is important that cases other than CONTIG be
applicable only when the resulting transpose dimension
is divisible by n_pes; otherwise, the allocation size
returned by the API will be incorrect */
return ((rearrange != DISCONTIG || div_mult(n_pes, vn))
&& (rearrange != SQUARE_BEFORE
|| div_mult2(dim0.b[IB], vn, n_pes))
&& (rearrange != SQUARE_AFTER
|| (dim0.b[IB] != dim0.b[OB]
&& div_mult2(dim0.b[OB], vn, n_pes)))
&& (rearrange != SQUARE_MIDDLE
|| div_mult(dim0.n * n_pes, vn)));
}
INT XM(rearrange_ny)(rearrangement rearrange, ddim dim0, INT vn, int n_pes)
{
switch (rearrange) {
case CONTIG:
return vn;
case DISCONTIG:
return n_pes;
case SQUARE_BEFORE:
return dim0.b[IB];
case SQUARE_AFTER:
return dim0.b[OB];
case SQUARE_MIDDLE:
return dim0.n * n_pes;
}
return 0;
}
| gpl-2.0 |
iConsole/Console-OS_external_alsa-utils | alsamixer/mainloop.c | 29 | 3248 | /*
* mainloop.c - main loop
* Copyright (c) Clemens Ladisch <clemens@ladisch.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, see <http://www.gnu.org/licenses/>.
*/
#include "aconfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <poll.h>
#include <panel.h>
#include <alsa/asoundlib.h>
#include "mem.h"
#include "die.h"
#include "colors.h"
#include "widget.h"
#include "mixer_widget.h"
#include "mixer_display.h"
#include "mainloop.h"
static WINDOW *curses_initialized;
static void black_hole_error_handler(const char *file, int line,
const char *function, int err,
const char *fmt, ...)
{
}
void initialize_curses(bool use_color)
{
curses_initialized = initscr();
cbreak();
noecho();
#ifdef HAVE_CURSES_ESCDELAY
set_escdelay(100);
#endif
window_size_changed(); /* update screen_lines/cols */
init_colors(use_color);
snd_lib_error_set_handler(black_hole_error_handler);
}
void shutdown(void)
{
if (curses_initialized) {
clear();
refresh();
curs_set(1);
endwin();
}
mixer_shutdown();
}
void mainloop(void)
{
struct pollfd *pollfds = NULL;
int nfds = 0, n;
struct widget *active_widget;
unsigned short revents;
int key;
int err;
for (;;) {
update_panels();
doupdate();
active_widget = get_active_widget();
if (!active_widget)
break;
n = 1 + snd_mixer_poll_descriptors_count(mixer);
if (n != nfds) {
free(pollfds);
nfds = n;
pollfds = ccalloc(nfds, sizeof *pollfds);
pollfds[0].fd = fileno(stdin);
pollfds[0].events = POLLIN;
}
err = snd_mixer_poll_descriptors(mixer, &pollfds[1], nfds - 1);
if (err < 0)
fatal_alsa_error("cannot get poll descriptors", err);
n = poll(pollfds, nfds, -1);
if (n < 0) {
if (errno == EINTR) {
pollfds[0].revents = 0;
doupdate(); /* handle SIGWINCH */
} else {
fatal_error("poll error");
}
}
if (pollfds[0].revents & (POLLERR | POLLHUP | POLLNVAL))
break;
if (pollfds[0].revents & POLLIN)
--n;
if (n > 0) {
err = snd_mixer_poll_descriptors_revents(mixer, &pollfds[1], nfds - 1, &revents);
if (err < 0)
fatal_alsa_error("cannot get poll events", err);
if (revents & (POLLERR | POLLNVAL))
close_mixer_device();
else if (revents & POLLIN)
snd_mixer_handle_events(mixer);
}
key = wgetch(active_widget->window);
while (key != ERR) {
#ifdef KEY_RESIZE
if (key == KEY_RESIZE)
window_size_changed();
else
#endif
active_widget->handle_key(key);
active_widget = get_active_widget();
if (!active_widget)
break;
key = wgetch(active_widget->window);
}
if (!active_widget)
break;
if (controls_changed)
display_controls();
}
free(pollfds);
}
| gpl-2.0 |
SaleJumper/android-source-browsing.platform--external--elfutils | libelf/elf_gnu_hash.c | 29 | 3341 | /* GNU-style Hash function used in ELF implementations.
Copyright (C) 2006 Red Hat, Inc.
This file is part of Red Hat elfutils.
Contributed by Ulrich Drepper <drepper@redhat.com>, 2006.
Red Hat elfutils 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.
Red Hat elfutils 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 Red Hat elfutils; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA.
In addition, as a special exception, Red Hat, Inc. gives You the
additional right to link the code of Red Hat elfutils with code licensed
under any Open Source Initiative certified open source license
(http://www.opensource.org/licenses/index.php) which requires the
distribution of source code with any binary distribution and to
distribute linked combinations of the two. Non-GPL Code permitted under
this exception must only link to the code of Red Hat elfutils through
those well defined interfaces identified in the file named EXCEPTION
found in the source code files (the "Approved Interfaces"). The files
of Non-GPL Code may instantiate templates or use macros or inline
functions from the Approved Interfaces without causing the resulting
work to be covered by the GNU General Public License. Only Red Hat,
Inc. may make changes or additions to the list of Approved Interfaces.
Red Hat's grant of this exception is conditioned upon your not adding
any new exceptions. If you wish to add a new Approved Interface or
exception, please contact Red Hat. You must obey the GNU General Public
License in all respects for all of the Red Hat elfutils code and other
code used in conjunction with Red Hat elfutils except the Non-GPL Code
covered by this exception. If you modify this file, you may extend this
exception to your version of the file, but you are not obligated to do
so. If you do not wish to provide this exception without modification,
you must delete this exception statement from your version and license
this file solely under the GPL without exception.
Red Hat elfutils is an included package of the Open Invention Network.
An included package of the Open Invention Network is a package for which
Open Invention Network licensees cross-license their patents. No patent
license is granted, either expressly or impliedly, by designation as an
included package. Should you wish to participate in the Open Invention
Network licensing program, please visit www.openinventionnetwork.com
<http://www.openinventionnetwork.com>. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <libelfP.h>
/* Get the implementation. */
#include <dl-hash.h>
unsigned long int
elf_gnu_hash (string)
const char *string;
{
uint_fast32_t h = 5381;
for (unsigned char c = *string; c != '\0'; c = *++string)
h = h * 33 + c;
return h & 0xffffffff;
}
| gpl-2.0 |
ShinySide/SM-T900_Kernel | drivers/infiniband/ulp/ipoib/ipoib_multicast.c | 1565 | 25647 | /*
* Copyright (c) 2004, 2005 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 <linux/skbuff.h>
#include <linux/rtnetlink.h>
#include <linux/moduleparam.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/igmp.h>
#include <linux/inetdevice.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/slab.h>
#include <net/dst.h>
#include "ipoib.h"
#ifdef CONFIG_INFINIBAND_IPOIB_DEBUG
static int mcast_debug_level;
module_param(mcast_debug_level, int, 0644);
MODULE_PARM_DESC(mcast_debug_level,
"Enable multicast debug tracing if > 0");
#endif
static DEFINE_MUTEX(mcast_mutex);
struct ipoib_mcast_iter {
struct net_device *dev;
union ib_gid mgid;
unsigned long created;
unsigned int queuelen;
unsigned int complete;
unsigned int send_only;
};
static void ipoib_mcast_free(struct ipoib_mcast *mcast)
{
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_neigh *neigh, *tmp;
int tx_dropped = 0;
ipoib_dbg_mcast(netdev_priv(dev), "deleting multicast group %pI6\n",
mcast->mcmember.mgid.raw);
spin_lock_irq(&priv->lock);
list_for_each_entry_safe(neigh, tmp, &mcast->neigh_list, list) {
/*
* It's safe to call ipoib_put_ah() inside priv->lock
* here, because we know that mcast->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_irq(&priv->lock);
if (mcast->ah)
ipoib_put_ah(mcast->ah);
while (!skb_queue_empty(&mcast->pkt_queue)) {
++tx_dropped;
dev_kfree_skb_any(skb_dequeue(&mcast->pkt_queue));
}
netif_tx_lock_bh(dev);
dev->stats.tx_dropped += tx_dropped;
netif_tx_unlock_bh(dev);
kfree(mcast);
}
static struct ipoib_mcast *ipoib_mcast_alloc(struct net_device *dev,
int can_sleep)
{
struct ipoib_mcast *mcast;
mcast = kzalloc(sizeof *mcast, can_sleep ? GFP_KERNEL : GFP_ATOMIC);
if (!mcast)
return NULL;
mcast->dev = dev;
mcast->created = jiffies;
mcast->backoff = 1;
INIT_LIST_HEAD(&mcast->list);
INIT_LIST_HEAD(&mcast->neigh_list);
skb_queue_head_init(&mcast->pkt_queue);
return mcast;
}
static struct ipoib_mcast *__ipoib_mcast_find(struct net_device *dev, void *mgid)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct rb_node *n = priv->multicast_tree.rb_node;
while (n) {
struct ipoib_mcast *mcast;
int ret;
mcast = rb_entry(n, struct ipoib_mcast, rb_node);
ret = memcmp(mgid, mcast->mcmember.mgid.raw,
sizeof (union ib_gid));
if (ret < 0)
n = n->rb_left;
else if (ret > 0)
n = n->rb_right;
else
return mcast;
}
return NULL;
}
static int __ipoib_mcast_add(struct net_device *dev, struct ipoib_mcast *mcast)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct rb_node **n = &priv->multicast_tree.rb_node, *pn = NULL;
while (*n) {
struct ipoib_mcast *tmcast;
int ret;
pn = *n;
tmcast = rb_entry(pn, struct ipoib_mcast, rb_node);
ret = memcmp(mcast->mcmember.mgid.raw, tmcast->mcmember.mgid.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(&mcast->rb_node, pn, n);
rb_insert_color(&mcast->rb_node, &priv->multicast_tree);
return 0;
}
static int ipoib_mcast_join_finish(struct ipoib_mcast *mcast,
struct ib_sa_mcmember_rec *mcmember)
{
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_ah *ah;
int ret;
int set_qkey = 0;
mcast->mcmember = *mcmember;
/* Set the multicast MTU and cached Q_Key before we attach if it's
* the broadcast group.
*/
if (!memcmp(mcast->mcmember.mgid.raw, priv->dev->broadcast + 4,
sizeof (union ib_gid))) {
spin_lock_irq(&priv->lock);
if (!priv->broadcast) {
spin_unlock_irq(&priv->lock);
return -EAGAIN;
}
priv->mcast_mtu = IPOIB_UD_MTU(ib_mtu_enum_to_int(priv->broadcast->mcmember.mtu));
priv->qkey = be32_to_cpu(priv->broadcast->mcmember.qkey);
spin_unlock_irq(&priv->lock);
priv->tx_wr.wr.ud.remote_qkey = priv->qkey;
set_qkey = 1;
if (!ipoib_cm_admin_enabled(dev)) {
rtnl_lock();
dev_set_mtu(dev, min(priv->mcast_mtu, priv->admin_mtu));
rtnl_unlock();
}
}
if (!test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)) {
if (test_and_set_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags)) {
ipoib_warn(priv, "multicast group %pI6 already attached\n",
mcast->mcmember.mgid.raw);
return 0;
}
ret = ipoib_mcast_attach(dev, be16_to_cpu(mcast->mcmember.mlid),
&mcast->mcmember.mgid, set_qkey);
if (ret < 0) {
ipoib_warn(priv, "couldn't attach QP to multicast group %pI6\n",
mcast->mcmember.mgid.raw);
clear_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags);
return ret;
}
}
{
struct ib_ah_attr av = {
.dlid = be16_to_cpu(mcast->mcmember.mlid),
.port_num = priv->port,
.sl = mcast->mcmember.sl,
.ah_flags = IB_AH_GRH,
.static_rate = mcast->mcmember.rate,
.grh = {
.flow_label = be32_to_cpu(mcast->mcmember.flow_label),
.hop_limit = mcast->mcmember.hop_limit,
.sgid_index = 0,
.traffic_class = mcast->mcmember.traffic_class
}
};
av.grh.dgid = mcast->mcmember.mgid;
ah = ipoib_create_ah(dev, priv->pd, &av);
if (IS_ERR(ah)) {
ipoib_warn(priv, "ib_address_create failed %ld\n",
-PTR_ERR(ah));
/* use original error */
return PTR_ERR(ah);
} else {
spin_lock_irq(&priv->lock);
mcast->ah = ah;
spin_unlock_irq(&priv->lock);
ipoib_dbg_mcast(priv, "MGID %pI6 AV %p, LID 0x%04x, SL %d\n",
mcast->mcmember.mgid.raw,
mcast->ah->ah,
be16_to_cpu(mcast->mcmember.mlid),
mcast->mcmember.sl);
}
}
/* actually send any queued packets */
netif_tx_lock_bh(dev);
while (!skb_queue_empty(&mcast->pkt_queue)) {
struct sk_buff *skb = skb_dequeue(&mcast->pkt_queue);
netif_tx_unlock_bh(dev);
skb->dev = dev;
if (dev_queue_xmit(skb))
ipoib_warn(priv, "dev_queue_xmit failed to requeue packet\n");
netif_tx_lock_bh(dev);
}
netif_tx_unlock_bh(dev);
return 0;
}
static int
ipoib_mcast_sendonly_join_complete(int status,
struct ib_sa_multicast *multicast)
{
struct ipoib_mcast *mcast = multicast->context;
struct net_device *dev = mcast->dev;
/* We trap for port events ourselves. */
if (status == -ENETRESET)
return 0;
if (!status)
status = ipoib_mcast_join_finish(mcast, &multicast->rec);
if (status) {
if (mcast->logcount++ < 20)
ipoib_dbg_mcast(netdev_priv(dev), "multicast join failed for %pI6, status %d\n",
mcast->mcmember.mgid.raw, status);
/* Flush out any queued packets */
netif_tx_lock_bh(dev);
while (!skb_queue_empty(&mcast->pkt_queue)) {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb_dequeue(&mcast->pkt_queue));
}
netif_tx_unlock_bh(dev);
/* Clear the busy flag so we try again */
status = test_and_clear_bit(IPOIB_MCAST_FLAG_BUSY,
&mcast->flags);
}
return status;
}
static int ipoib_mcast_sendonly_join(struct ipoib_mcast *mcast)
{
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ib_sa_mcmember_rec rec = {
#if 0 /* Some SMs don't support send-only yet */
.join_state = 4
#else
.join_state = 1
#endif
};
int ret = 0;
if (!test_bit(IPOIB_FLAG_OPER_UP, &priv->flags)) {
ipoib_dbg_mcast(priv, "device shutting down, no multicast joins\n");
return -ENODEV;
}
if (test_and_set_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags)) {
ipoib_dbg_mcast(priv, "multicast entry busy, skipping\n");
return -EBUSY;
}
rec.mgid = mcast->mcmember.mgid;
rec.port_gid = priv->local_gid;
rec.pkey = cpu_to_be16(priv->pkey);
mcast->mc = ib_sa_join_multicast(&ipoib_sa_client, priv->ca,
priv->port, &rec,
IB_SA_MCMEMBER_REC_MGID |
IB_SA_MCMEMBER_REC_PORT_GID |
IB_SA_MCMEMBER_REC_PKEY |
IB_SA_MCMEMBER_REC_JOIN_STATE,
GFP_ATOMIC,
ipoib_mcast_sendonly_join_complete,
mcast);
if (IS_ERR(mcast->mc)) {
ret = PTR_ERR(mcast->mc);
clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
ipoib_warn(priv, "ib_sa_join_multicast failed (ret = %d)\n",
ret);
} else {
ipoib_dbg_mcast(priv, "no multicast record for %pI6, starting join\n",
mcast->mcmember.mgid.raw);
}
return ret;
}
void ipoib_mcast_carrier_on_task(struct work_struct *work)
{
struct ipoib_dev_priv *priv = container_of(work, struct ipoib_dev_priv,
carrier_on_task);
struct ib_port_attr attr;
/*
* Take rtnl_lock to avoid racing with ipoib_stop() and
* turning the carrier back on while a device is being
* removed.
*/
if (ib_query_port(priv->ca, priv->port, &attr) ||
attr.state != IB_PORT_ACTIVE) {
ipoib_dbg(priv, "Keeping carrier off until IB port is active\n");
return;
}
rtnl_lock();
netif_carrier_on(priv->dev);
rtnl_unlock();
}
static int ipoib_mcast_join_complete(int status,
struct ib_sa_multicast *multicast)
{
struct ipoib_mcast *mcast = multicast->context;
struct net_device *dev = mcast->dev;
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg_mcast(priv, "join completion for %pI6 (status %d)\n",
mcast->mcmember.mgid.raw, status);
/* We trap for port events ourselves. */
if (status == -ENETRESET)
return 0;
if (!status)
status = ipoib_mcast_join_finish(mcast, &multicast->rec);
if (!status) {
mcast->backoff = 1;
mutex_lock(&mcast_mutex);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue,
&priv->mcast_task, 0);
mutex_unlock(&mcast_mutex);
/*
* Defer carrier on work to ipoib_workqueue to avoid a
* deadlock on rtnl_lock here.
*/
if (mcast == priv->broadcast)
queue_work(ipoib_workqueue, &priv->carrier_on_task);
return 0;
}
if (mcast->logcount++ < 20) {
if (status == -ETIMEDOUT || status == -EAGAIN) {
ipoib_dbg_mcast(priv, "multicast join failed for %pI6, status %d\n",
mcast->mcmember.mgid.raw, status);
} else {
ipoib_warn(priv, "multicast join failed for %pI6, status %d\n",
mcast->mcmember.mgid.raw, status);
}
}
mcast->backoff *= 2;
if (mcast->backoff > IPOIB_MAX_BACKOFF_SECONDS)
mcast->backoff = IPOIB_MAX_BACKOFF_SECONDS;
/* Clear the busy flag so we try again */
status = test_and_clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
mutex_lock(&mcast_mutex);
spin_lock_irq(&priv->lock);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue, &priv->mcast_task,
mcast->backoff * HZ);
spin_unlock_irq(&priv->lock);
mutex_unlock(&mcast_mutex);
return status;
}
static void ipoib_mcast_join(struct net_device *dev, struct ipoib_mcast *mcast,
int create)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ib_sa_mcmember_rec rec = {
.join_state = 1
};
ib_sa_comp_mask comp_mask;
int ret = 0;
ipoib_dbg_mcast(priv, "joining MGID %pI6\n", mcast->mcmember.mgid.raw);
rec.mgid = mcast->mcmember.mgid;
rec.port_gid = priv->local_gid;
rec.pkey = cpu_to_be16(priv->pkey);
comp_mask =
IB_SA_MCMEMBER_REC_MGID |
IB_SA_MCMEMBER_REC_PORT_GID |
IB_SA_MCMEMBER_REC_PKEY |
IB_SA_MCMEMBER_REC_JOIN_STATE;
if (create) {
comp_mask |=
IB_SA_MCMEMBER_REC_QKEY |
IB_SA_MCMEMBER_REC_MTU_SELECTOR |
IB_SA_MCMEMBER_REC_MTU |
IB_SA_MCMEMBER_REC_TRAFFIC_CLASS |
IB_SA_MCMEMBER_REC_RATE_SELECTOR |
IB_SA_MCMEMBER_REC_RATE |
IB_SA_MCMEMBER_REC_SL |
IB_SA_MCMEMBER_REC_FLOW_LABEL |
IB_SA_MCMEMBER_REC_HOP_LIMIT;
rec.qkey = priv->broadcast->mcmember.qkey;
rec.mtu_selector = IB_SA_EQ;
rec.mtu = priv->broadcast->mcmember.mtu;
rec.traffic_class = priv->broadcast->mcmember.traffic_class;
rec.rate_selector = IB_SA_EQ;
rec.rate = priv->broadcast->mcmember.rate;
rec.sl = priv->broadcast->mcmember.sl;
rec.flow_label = priv->broadcast->mcmember.flow_label;
rec.hop_limit = priv->broadcast->mcmember.hop_limit;
}
set_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
mcast->mc = ib_sa_join_multicast(&ipoib_sa_client, priv->ca, priv->port,
&rec, comp_mask, GFP_KERNEL,
ipoib_mcast_join_complete, mcast);
if (IS_ERR(mcast->mc)) {
clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags);
ret = PTR_ERR(mcast->mc);
ipoib_warn(priv, "ib_sa_join_multicast failed, status %d\n", ret);
mcast->backoff *= 2;
if (mcast->backoff > IPOIB_MAX_BACKOFF_SECONDS)
mcast->backoff = IPOIB_MAX_BACKOFF_SECONDS;
mutex_lock(&mcast_mutex);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue,
&priv->mcast_task,
mcast->backoff * HZ);
mutex_unlock(&mcast_mutex);
}
}
void ipoib_mcast_join_task(struct work_struct *work)
{
struct ipoib_dev_priv *priv =
container_of(work, struct ipoib_dev_priv, mcast_task.work);
struct net_device *dev = priv->dev;
if (!test_bit(IPOIB_MCAST_RUN, &priv->flags))
return;
if (ib_query_gid(priv->ca, priv->port, 0, &priv->local_gid))
ipoib_warn(priv, "ib_query_gid() failed\n");
else
memcpy(priv->dev->dev_addr + 4, priv->local_gid.raw, sizeof (union ib_gid));
{
struct ib_port_attr attr;
if (!ib_query_port(priv->ca, priv->port, &attr))
priv->local_lid = attr.lid;
else
ipoib_warn(priv, "ib_query_port failed\n");
}
if (!priv->broadcast) {
struct ipoib_mcast *broadcast;
if (!test_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags))
return;
broadcast = ipoib_mcast_alloc(dev, 1);
if (!broadcast) {
ipoib_warn(priv, "failed to allocate broadcast group\n");
mutex_lock(&mcast_mutex);
if (test_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue,
&priv->mcast_task, HZ);
mutex_unlock(&mcast_mutex);
return;
}
spin_lock_irq(&priv->lock);
memcpy(broadcast->mcmember.mgid.raw, priv->dev->broadcast + 4,
sizeof (union ib_gid));
priv->broadcast = broadcast;
__ipoib_mcast_add(dev, priv->broadcast);
spin_unlock_irq(&priv->lock);
}
if (!test_bit(IPOIB_MCAST_FLAG_ATTACHED, &priv->broadcast->flags)) {
if (!test_bit(IPOIB_MCAST_FLAG_BUSY, &priv->broadcast->flags))
ipoib_mcast_join(dev, priv->broadcast, 0);
return;
}
while (1) {
struct ipoib_mcast *mcast = NULL;
spin_lock_irq(&priv->lock);
list_for_each_entry(mcast, &priv->multicast_list, list) {
if (!test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)
&& !test_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags)
&& !test_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags)) {
/* Found the next unjoined group */
break;
}
}
spin_unlock_irq(&priv->lock);
if (&mcast->list == &priv->multicast_list) {
/* All done */
break;
}
ipoib_mcast_join(dev, mcast, 1);
return;
}
ipoib_dbg_mcast(priv, "successfully joined all multicast groups\n");
clear_bit(IPOIB_MCAST_RUN, &priv->flags);
}
int ipoib_mcast_start_thread(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg_mcast(priv, "starting multicast thread\n");
mutex_lock(&mcast_mutex);
if (!test_and_set_bit(IPOIB_MCAST_RUN, &priv->flags))
queue_delayed_work(ipoib_workqueue, &priv->mcast_task, 0);
mutex_unlock(&mcast_mutex);
return 0;
}
int ipoib_mcast_stop_thread(struct net_device *dev, int flush)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
ipoib_dbg_mcast(priv, "stopping multicast thread\n");
mutex_lock(&mcast_mutex);
clear_bit(IPOIB_MCAST_RUN, &priv->flags);
cancel_delayed_work(&priv->mcast_task);
mutex_unlock(&mcast_mutex);
if (flush)
flush_workqueue(ipoib_workqueue);
return 0;
}
static int ipoib_mcast_leave(struct net_device *dev, struct ipoib_mcast *mcast)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
int ret = 0;
if (test_and_clear_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags))
ib_sa_free_multicast(mcast->mc);
if (test_and_clear_bit(IPOIB_MCAST_FLAG_ATTACHED, &mcast->flags)) {
ipoib_dbg_mcast(priv, "leaving MGID %pI6\n",
mcast->mcmember.mgid.raw);
/* Remove ourselves from the multicast group */
ret = ib_detach_mcast(priv->qp, &mcast->mcmember.mgid,
be16_to_cpu(mcast->mcmember.mlid));
if (ret)
ipoib_warn(priv, "ib_detach_mcast failed (result = %d)\n", ret);
}
return 0;
}
void ipoib_mcast_send(struct net_device *dev, void *mgid, struct sk_buff *skb)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
struct ipoib_mcast *mcast;
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
if (!test_bit(IPOIB_FLAG_OPER_UP, &priv->flags) ||
!priv->broadcast ||
!test_bit(IPOIB_MCAST_FLAG_ATTACHED, &priv->broadcast->flags)) {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
goto unlock;
}
mcast = __ipoib_mcast_find(dev, mgid);
if (!mcast) {
/* Let's create a new send only group now */
ipoib_dbg_mcast(priv, "setting up send only multicast group for %pI6\n",
mgid);
mcast = ipoib_mcast_alloc(dev, 0);
if (!mcast) {
ipoib_warn(priv, "unable to allocate memory for "
"multicast structure\n");
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
goto out;
}
set_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags);
memcpy(mcast->mcmember.mgid.raw, mgid, sizeof (union ib_gid));
__ipoib_mcast_add(dev, mcast);
list_add_tail(&mcast->list, &priv->multicast_list);
}
if (!mcast->ah) {
if (skb_queue_len(&mcast->pkt_queue) < IPOIB_MAX_MCAST_QUEUE)
skb_queue_tail(&mcast->pkt_queue, skb);
else {
++dev->stats.tx_dropped;
dev_kfree_skb_any(skb);
}
if (test_bit(IPOIB_MCAST_FLAG_BUSY, &mcast->flags))
ipoib_dbg_mcast(priv, "no address vector, "
"but multicast join already started\n");
else if (test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags))
ipoib_mcast_sendonly_join(mcast);
/*
* If lookup completes between here and out:, don't
* want to send packet twice.
*/
mcast = NULL;
}
out:
if (mcast && mcast->ah) {
struct dst_entry *dst = skb_dst(skb);
struct neighbour *n = NULL;
rcu_read_lock();
if (dst)
n = dst_get_neighbour_noref(dst);
if (n && !*to_ipoib_neigh(n)) {
struct ipoib_neigh *neigh = ipoib_neigh_alloc(n,
skb->dev);
if (neigh) {
kref_get(&mcast->ah->ref);
neigh->ah = mcast->ah;
list_add_tail(&neigh->list, &mcast->neigh_list);
}
}
rcu_read_unlock();
spin_unlock_irqrestore(&priv->lock, flags);
ipoib_send(dev, skb, mcast->ah, IB_MULTICAST_QPN);
return;
}
unlock:
spin_unlock_irqrestore(&priv->lock, flags);
}
void ipoib_mcast_dev_flush(struct net_device *dev)
{
struct ipoib_dev_priv *priv = netdev_priv(dev);
LIST_HEAD(remove_list);
struct ipoib_mcast *mcast, *tmcast;
unsigned long flags;
ipoib_dbg_mcast(priv, "flushing multicast list\n");
spin_lock_irqsave(&priv->lock, flags);
list_for_each_entry_safe(mcast, tmcast, &priv->multicast_list, list) {
list_del(&mcast->list);
rb_erase(&mcast->rb_node, &priv->multicast_tree);
list_add_tail(&mcast->list, &remove_list);
}
if (priv->broadcast) {
rb_erase(&priv->broadcast->rb_node, &priv->multicast_tree);
list_add_tail(&priv->broadcast->list, &remove_list);
priv->broadcast = NULL;
}
spin_unlock_irqrestore(&priv->lock, flags);
list_for_each_entry_safe(mcast, tmcast, &remove_list, list) {
ipoib_mcast_leave(dev, mcast);
ipoib_mcast_free(mcast);
}
}
static int ipoib_mcast_addr_is_valid(const u8 *addr, const u8 *broadcast)
{
/* reserved QPN, prefix, scope */
if (memcmp(addr, broadcast, 6))
return 0;
/* signature lower, pkey */
if (memcmp(addr + 7, broadcast + 7, 3))
return 0;
return 1;
}
void ipoib_mcast_restart_task(struct work_struct *work)
{
struct ipoib_dev_priv *priv =
container_of(work, struct ipoib_dev_priv, restart_task);
struct net_device *dev = priv->dev;
struct netdev_hw_addr *ha;
struct ipoib_mcast *mcast, *tmcast;
LIST_HEAD(remove_list);
unsigned long flags;
struct ib_sa_mcmember_rec rec;
ipoib_dbg_mcast(priv, "restarting multicast task\n");
ipoib_mcast_stop_thread(dev, 0);
local_irq_save(flags);
netif_addr_lock(dev);
spin_lock(&priv->lock);
/*
* Unfortunately, the networking core only gives us a list of all of
* the multicast hardware addresses. We need to figure out which ones
* are new and which ones have been removed
*/
/* Clear out the found flag */
list_for_each_entry(mcast, &priv->multicast_list, list)
clear_bit(IPOIB_MCAST_FLAG_FOUND, &mcast->flags);
/* Mark all of the entries that are found or don't exist */
netdev_for_each_mc_addr(ha, dev) {
union ib_gid mgid;
if (!ipoib_mcast_addr_is_valid(ha->addr, dev->broadcast))
continue;
memcpy(mgid.raw, ha->addr + 4, sizeof mgid);
mcast = __ipoib_mcast_find(dev, &mgid);
if (!mcast || test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)) {
struct ipoib_mcast *nmcast;
/* ignore group which is directly joined by userspace */
if (test_bit(IPOIB_FLAG_UMCAST, &priv->flags) &&
!ib_sa_get_mcmember_rec(priv->ca, priv->port, &mgid, &rec)) {
ipoib_dbg_mcast(priv, "ignoring multicast entry for mgid %pI6\n",
mgid.raw);
continue;
}
/* Not found or send-only group, let's add a new entry */
ipoib_dbg_mcast(priv, "adding multicast entry for mgid %pI6\n",
mgid.raw);
nmcast = ipoib_mcast_alloc(dev, 0);
if (!nmcast) {
ipoib_warn(priv, "unable to allocate memory for multicast structure\n");
continue;
}
set_bit(IPOIB_MCAST_FLAG_FOUND, &nmcast->flags);
nmcast->mcmember.mgid = mgid;
if (mcast) {
/* Destroy the send only entry */
list_move_tail(&mcast->list, &remove_list);
rb_replace_node(&mcast->rb_node,
&nmcast->rb_node,
&priv->multicast_tree);
} else
__ipoib_mcast_add(dev, nmcast);
list_add_tail(&nmcast->list, &priv->multicast_list);
}
if (mcast)
set_bit(IPOIB_MCAST_FLAG_FOUND, &mcast->flags);
}
/* Remove all of the entries don't exist anymore */
list_for_each_entry_safe(mcast, tmcast, &priv->multicast_list, list) {
if (!test_bit(IPOIB_MCAST_FLAG_FOUND, &mcast->flags) &&
!test_bit(IPOIB_MCAST_FLAG_SENDONLY, &mcast->flags)) {
ipoib_dbg_mcast(priv, "deleting multicast group %pI6\n",
mcast->mcmember.mgid.raw);
rb_erase(&mcast->rb_node, &priv->multicast_tree);
/* Move to the remove list */
list_move_tail(&mcast->list, &remove_list);
}
}
spin_unlock(&priv->lock);
netif_addr_unlock(dev);
local_irq_restore(flags);
/* We have to cancel outside of the spinlock */
list_for_each_entry_safe(mcast, tmcast, &remove_list, list) {
ipoib_mcast_leave(mcast->dev, mcast);
ipoib_mcast_free(mcast);
}
if (test_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags))
ipoib_mcast_start_thread(dev);
}
#ifdef CONFIG_INFINIBAND_IPOIB_DEBUG
struct ipoib_mcast_iter *ipoib_mcast_iter_init(struct net_device *dev)
{
struct ipoib_mcast_iter *iter;
iter = kmalloc(sizeof *iter, GFP_KERNEL);
if (!iter)
return NULL;
iter->dev = dev;
memset(iter->mgid.raw, 0, 16);
if (ipoib_mcast_iter_next(iter)) {
kfree(iter);
return NULL;
}
return iter;
}
int ipoib_mcast_iter_next(struct ipoib_mcast_iter *iter)
{
struct ipoib_dev_priv *priv = netdev_priv(iter->dev);
struct rb_node *n;
struct ipoib_mcast *mcast;
int ret = 1;
spin_lock_irq(&priv->lock);
n = rb_first(&priv->multicast_tree);
while (n) {
mcast = rb_entry(n, struct ipoib_mcast, rb_node);
if (memcmp(iter->mgid.raw, mcast->mcmember.mgid.raw,
sizeof (union ib_gid)) < 0) {
iter->mgid = mcast->mcmember.mgid;
iter->created = mcast->created;
iter->queuelen = skb_queue_len(&mcast->pkt_queue);
iter->complete = !!mcast->ah;
iter->send_only = !!(mcast->flags & (1 << IPOIB_MCAST_FLAG_SENDONLY));
ret = 0;
break;
}
n = rb_next(n);
}
spin_unlock_irq(&priv->lock);
return ret;
}
void ipoib_mcast_iter_read(struct ipoib_mcast_iter *iter,
union ib_gid *mgid,
unsigned long *created,
unsigned int *queuelen,
unsigned int *complete,
unsigned int *send_only)
{
*mgid = iter->mgid;
*created = iter->created;
*queuelen = iter->queuelen;
*complete = iter->complete;
*send_only = iter->send_only;
}
#endif /* CONFIG_INFINIBAND_IPOIB_DEBUG */
| gpl-2.0 |
backup-kb/pnotify-linux-4.1.6 | arch/mips/kernel/smp-up.c | 1821 | 1559 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2006, 07 by Ralf Baechle (ralf@linux-mips.org)
*
* Symmetric Uniprocessor (TM) Support
*/
#include <linux/kernel.h>
#include <linux/sched.h>
/*
* Send inter-processor interrupt
*/
static void up_send_ipi_single(int cpu, unsigned int action)
{
panic(KERN_ERR "%s called", __func__);
}
static inline void up_send_ipi_mask(const struct cpumask *mask,
unsigned int action)
{
panic(KERN_ERR "%s called", __func__);
}
/*
* After we've done initial boot, this function is called to allow the
* board code to clean up state, if needed
*/
static void up_init_secondary(void)
{
}
static void up_smp_finish(void)
{
}
/*
* Firmware CPU startup hook
*/
static void up_boot_secondary(int cpu, struct task_struct *idle)
{
}
static void __init up_smp_setup(void)
{
}
static void __init up_prepare_cpus(unsigned int max_cpus)
{
}
#ifdef CONFIG_HOTPLUG_CPU
static int up_cpu_disable(void)
{
return -ENOSYS;
}
static void up_cpu_die(unsigned int cpu)
{
BUG();
}
#endif
struct plat_smp_ops up_smp_ops = {
.send_ipi_single = up_send_ipi_single,
.send_ipi_mask = up_send_ipi_mask,
.init_secondary = up_init_secondary,
.smp_finish = up_smp_finish,
.boot_secondary = up_boot_secondary,
.smp_setup = up_smp_setup,
.prepare_cpus = up_prepare_cpus,
#ifdef CONFIG_HOTPLUG_CPU
.cpu_disable = up_cpu_disable,
.cpu_die = up_cpu_die,
#endif
};
| gpl-2.0 |
jiangdapeng/btrfs-next | arch/x86/kernel/check.c | 2589 | 3912 | #include <linux/module.h>
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/workqueue.h>
#include <linux/memblock.h>
#include <asm/proto.h>
/*
* Some BIOSes seem to corrupt the low 64k of memory during events
* like suspend/resume and unplugging an HDMI cable. Reserve all
* remaining free memory in that area and fill it with a distinct
* pattern.
*/
#define MAX_SCAN_AREAS 8
static int __read_mostly memory_corruption_check = -1;
static unsigned __read_mostly corruption_check_size = 64*1024;
static unsigned __read_mostly corruption_check_period = 60; /* seconds */
static struct scan_area {
u64 addr;
u64 size;
} scan_areas[MAX_SCAN_AREAS];
static int num_scan_areas;
static __init int set_corruption_check(char *arg)
{
ssize_t ret;
unsigned long val;
ret = kstrtoul(arg, 10, &val);
if (ret)
return ret;
memory_corruption_check = val;
return 0;
}
early_param("memory_corruption_check", set_corruption_check);
static __init int set_corruption_check_period(char *arg)
{
ssize_t ret;
unsigned long val;
ret = kstrtoul(arg, 10, &val);
if (ret)
return ret;
corruption_check_period = val;
return 0;
}
early_param("memory_corruption_check_period", set_corruption_check_period);
static __init int set_corruption_check_size(char *arg)
{
char *end;
unsigned size;
size = memparse(arg, &end);
if (*end == '\0')
corruption_check_size = size;
return (size == corruption_check_size) ? 0 : -EINVAL;
}
early_param("memory_corruption_check_size", set_corruption_check_size);
void __init setup_bios_corruption_check(void)
{
phys_addr_t start, end;
u64 i;
if (memory_corruption_check == -1) {
memory_corruption_check =
#ifdef CONFIG_X86_BOOTPARAM_MEMORY_CORRUPTION_CHECK
1
#else
0
#endif
;
}
if (corruption_check_size == 0)
memory_corruption_check = 0;
if (!memory_corruption_check)
return;
corruption_check_size = round_up(corruption_check_size, PAGE_SIZE);
for_each_free_mem_range(i, MAX_NUMNODES, &start, &end, NULL) {
start = clamp_t(phys_addr_t, round_up(start, PAGE_SIZE),
PAGE_SIZE, corruption_check_size);
end = clamp_t(phys_addr_t, round_down(end, PAGE_SIZE),
PAGE_SIZE, corruption_check_size);
if (start >= end)
continue;
memblock_reserve(start, end - start);
scan_areas[num_scan_areas].addr = start;
scan_areas[num_scan_areas].size = end - start;
/* Assume we've already mapped this early memory */
memset(__va(start), 0, end - start);
if (++num_scan_areas >= MAX_SCAN_AREAS)
break;
}
if (num_scan_areas)
printk(KERN_INFO "Scanning %d areas for low memory corruption\n", num_scan_areas);
}
void check_for_bios_corruption(void)
{
int i;
int corruption = 0;
if (!memory_corruption_check)
return;
for (i = 0; i < num_scan_areas; i++) {
unsigned long *addr = __va(scan_areas[i].addr);
unsigned long size = scan_areas[i].size;
for (; size; addr++, size -= sizeof(unsigned long)) {
if (!*addr)
continue;
printk(KERN_ERR "Corrupted low memory at %p (%lx phys) = %08lx\n",
addr, __pa(addr), *addr);
corruption = 1;
*addr = 0;
}
}
WARN_ONCE(corruption, KERN_ERR "Memory corruption detected in low memory\n");
}
static void check_corruption(struct work_struct *dummy);
static DECLARE_DELAYED_WORK(bios_check_work, check_corruption);
static void check_corruption(struct work_struct *dummy)
{
check_for_bios_corruption();
schedule_delayed_work(&bios_check_work,
round_jiffies_relative(corruption_check_period*HZ));
}
static int start_periodic_check_for_corruption(void)
{
if (!num_scan_areas || !memory_corruption_check || corruption_check_period == 0)
return 0;
printk(KERN_INFO "Scanning for low memory corruption every %d seconds\n",
corruption_check_period);
/* First time we run the checks right away */
schedule_delayed_work(&bios_check_work, 0);
return 0;
}
module_init(start_periodic_check_for_corruption);
| gpl-2.0 |
cdesjardins/DTS-Eagle-Integration_CAF-Android-kernel | drivers/usb/gadget/audio.c | 2845 | 4669 | /*
* audio.c -- Audio gadget driver
*
* Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
* Copyright (C) 2008 Analog Devices, Inc
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
/* #define VERBOSE_DEBUG */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/usb/composite.h>
#include "gadget_chips.h"
#define DRIVER_DESC "Linux USB Audio Gadget"
#define DRIVER_VERSION "Feb 2, 2012"
USB_GADGET_COMPOSITE_OPTIONS();
/* string IDs are assigned dynamically */
static struct usb_string strings_dev[] = {
[USB_GADGET_MANUFACTURER_IDX].s = "",
[USB_GADGET_PRODUCT_IDX].s = DRIVER_DESC,
[USB_GADGET_SERIAL_IDX].s = "",
{ } /* end of list */
};
static struct usb_gadget_strings stringtab_dev = {
.language = 0x0409, /* en-us */
.strings = strings_dev,
};
static struct usb_gadget_strings *audio_strings[] = {
&stringtab_dev,
NULL,
};
#ifdef CONFIG_GADGET_UAC1
#include "u_uac1.h"
#include "u_uac1.c"
#include "f_uac1.c"
#else
#include "f_uac2.c"
#endif
/*-------------------------------------------------------------------------*/
/* DO NOT REUSE THESE IDs with a protocol-incompatible driver!! Ever!!
* Instead: allocate your own, using normal USB-IF procedures.
*/
/* Thanks to Linux Foundation for donating this product ID. */
#define AUDIO_VENDOR_NUM 0x1d6b /* Linux Foundation */
#define AUDIO_PRODUCT_NUM 0x0101 /* Linux-USB Audio Gadget */
/*-------------------------------------------------------------------------*/
static struct usb_device_descriptor device_desc = {
.bLength = sizeof device_desc,
.bDescriptorType = USB_DT_DEVICE,
.bcdUSB = __constant_cpu_to_le16(0x200),
#ifdef CONFIG_GADGET_UAC1
.bDeviceClass = USB_CLASS_PER_INTERFACE,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
#else
.bDeviceClass = USB_CLASS_MISC,
.bDeviceSubClass = 0x02,
.bDeviceProtocol = 0x01,
#endif
/* .bMaxPacketSize0 = f(hardware) */
/* Vendor and product id defaults change according to what configs
* we support. (As does bNumConfigurations.) These values can
* also be overridden by module parameters.
*/
.idVendor = __constant_cpu_to_le16(AUDIO_VENDOR_NUM),
.idProduct = __constant_cpu_to_le16(AUDIO_PRODUCT_NUM),
/* .bcdDevice = f(hardware) */
/* .iManufacturer = DYNAMIC */
/* .iProduct = DYNAMIC */
/* NO SERIAL NUMBER */
.bNumConfigurations = 1,
};
static struct usb_otg_descriptor otg_descriptor = {
.bLength = sizeof otg_descriptor,
.bDescriptorType = USB_DT_OTG,
/* REVISIT SRP-only hardware is possible, although
* it would not be called "OTG" ...
*/
.bmAttributes = USB_OTG_SRP | USB_OTG_HNP,
};
static const struct usb_descriptor_header *otg_desc[] = {
(struct usb_descriptor_header *) &otg_descriptor,
NULL,
};
/*-------------------------------------------------------------------------*/
static int __init audio_do_config(struct usb_configuration *c)
{
/* FIXME alloc iConfiguration string, set it in c->strings */
if (gadget_is_otg(c->cdev->gadget)) {
c->descriptors = otg_desc;
c->bmAttributes |= USB_CONFIG_ATT_WAKEUP;
}
audio_bind_config(c);
return 0;
}
static struct usb_configuration audio_config_driver = {
.label = DRIVER_DESC,
.bConfigurationValue = 1,
/* .iConfiguration = DYNAMIC */
.bmAttributes = USB_CONFIG_ATT_SELFPOWER,
#ifndef CONFIG_GADGET_UAC1
.unbind = uac2_unbind_config,
#endif
};
/*-------------------------------------------------------------------------*/
static int __init audio_bind(struct usb_composite_dev *cdev)
{
int status;
status = usb_string_ids_tab(cdev, strings_dev);
if (status < 0)
goto fail;
device_desc.iManufacturer = strings_dev[USB_GADGET_MANUFACTURER_IDX].id;
device_desc.iProduct = strings_dev[USB_GADGET_PRODUCT_IDX].id;
status = usb_add_config(cdev, &audio_config_driver, audio_do_config);
if (status < 0)
goto fail;
usb_composite_overwrite_options(cdev, &coverwrite);
INFO(cdev, "%s, version: %s\n", DRIVER_DESC, DRIVER_VERSION);
return 0;
fail:
return status;
}
static int __exit audio_unbind(struct usb_composite_dev *cdev)
{
#ifdef CONFIG_GADGET_UAC1
gaudio_cleanup();
#endif
return 0;
}
static __refdata struct usb_composite_driver audio_driver = {
.name = "g_audio",
.dev = &device_desc,
.strings = audio_strings,
.max_speed = USB_SPEED_HIGH,
.bind = audio_bind,
.unbind = __exit_p(audio_unbind),
};
static int __init init(void)
{
return usb_composite_probe(&audio_driver);
}
module_init(init);
static void __exit cleanup(void)
{
usb_composite_unregister(&audio_driver);
}
module_exit(cleanup);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR("Bryan Wu <cooloney@kernel.org>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
danielhk/android_kernel_samsung_smdk4210 | drivers/input/serio/altera_ps2.c | 3101 | 4838 | /*
* Altera University Program PS2 controller driver
*
* Copyright (C) 2008 Thomas Chou <thomas@wytron.com.tw>
*
* Based on sa1111ps2.c, which is:
* Copyright (C) 2002 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/of.h>
#define DRV_NAME "altera_ps2"
struct ps2if {
struct serio *io;
struct resource *iomem_res;
void __iomem *base;
unsigned irq;
};
/*
* Read all bytes waiting in the PS2 port. There should be
* at the most one, but we loop for safety.
*/
static irqreturn_t altera_ps2_rxint(int irq, void *dev_id)
{
struct ps2if *ps2if = dev_id;
unsigned int status;
int handled = IRQ_NONE;
while ((status = readl(ps2if->base)) & 0xffff0000) {
serio_interrupt(ps2if->io, status & 0xff, 0);
handled = IRQ_HANDLED;
}
return handled;
}
/*
* Write a byte to the PS2 port.
*/
static int altera_ps2_write(struct serio *io, unsigned char val)
{
struct ps2if *ps2if = io->port_data;
writel(val, ps2if->base);
return 0;
}
static int altera_ps2_open(struct serio *io)
{
struct ps2if *ps2if = io->port_data;
/* clear fifo */
while (readl(ps2if->base) & 0xffff0000)
/* empty */;
writel(1, ps2if->base + 4); /* enable rx irq */
return 0;
}
static void altera_ps2_close(struct serio *io)
{
struct ps2if *ps2if = io->port_data;
writel(0, ps2if->base); /* disable rx irq */
}
/*
* Add one device to this driver.
*/
static int __devinit altera_ps2_probe(struct platform_device *pdev)
{
struct ps2if *ps2if;
struct serio *serio;
int error, irq;
ps2if = kzalloc(sizeof(struct ps2if), GFP_KERNEL);
serio = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (!ps2if || !serio) {
error = -ENOMEM;
goto err_free_mem;
}
serio->id.type = SERIO_8042;
serio->write = altera_ps2_write;
serio->open = altera_ps2_open;
serio->close = altera_ps2_close;
strlcpy(serio->name, dev_name(&pdev->dev), sizeof(serio->name));
strlcpy(serio->phys, dev_name(&pdev->dev), sizeof(serio->phys));
serio->port_data = ps2if;
serio->dev.parent = &pdev->dev;
ps2if->io = serio;
ps2if->iomem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (ps2if->iomem_res == NULL) {
error = -ENOENT;
goto err_free_mem;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
error = -ENXIO;
goto err_free_mem;
}
ps2if->irq = irq;
if (!request_mem_region(ps2if->iomem_res->start,
resource_size(ps2if->iomem_res), pdev->name)) {
error = -EBUSY;
goto err_free_mem;
}
ps2if->base = ioremap(ps2if->iomem_res->start,
resource_size(ps2if->iomem_res));
if (!ps2if->base) {
error = -ENOMEM;
goto err_free_res;
}
error = request_irq(ps2if->irq, altera_ps2_rxint, 0, pdev->name, ps2if);
if (error) {
dev_err(&pdev->dev, "could not allocate IRQ %d: %d\n",
ps2if->irq, error);
goto err_unmap;
}
dev_info(&pdev->dev, "base %p, irq %d\n", ps2if->base, ps2if->irq);
serio_register_port(ps2if->io);
platform_set_drvdata(pdev, ps2if);
return 0;
err_unmap:
iounmap(ps2if->base);
err_free_res:
release_mem_region(ps2if->iomem_res->start,
resource_size(ps2if->iomem_res));
err_free_mem:
kfree(ps2if);
kfree(serio);
return error;
}
/*
* Remove one device from this driver.
*/
static int __devexit altera_ps2_remove(struct platform_device *pdev)
{
struct ps2if *ps2if = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
serio_unregister_port(ps2if->io);
free_irq(ps2if->irq, ps2if);
iounmap(ps2if->base);
release_mem_region(ps2if->iomem_res->start,
resource_size(ps2if->iomem_res));
kfree(ps2if);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id altera_ps2_match[] = {
{ .compatible = "ALTR,ps2-1.0", },
{},
};
MODULE_DEVICE_TABLE(of, altera_ps2_match);
#else /* CONFIG_OF */
#define altera_ps2_match NULL
#endif /* CONFIG_OF */
/*
* Our device driver structure
*/
static struct platform_driver altera_ps2_driver = {
.probe = altera_ps2_probe,
.remove = __devexit_p(altera_ps2_remove),
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = altera_ps2_match,
},
};
static int __init altera_ps2_init(void)
{
return platform_driver_register(&altera_ps2_driver);
}
module_init(altera_ps2_init);
static void __exit altera_ps2_exit(void)
{
platform_driver_unregister(&altera_ps2_driver);
}
module_exit(altera_ps2_exit);
MODULE_DESCRIPTION("Altera University Program PS2 controller driver");
MODULE_AUTHOR("Thomas Chou <thomas@wytron.com.tw>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
KDGDev/meizu-mx-kernel | sound/pci/echoaudio/indigodjx.c | 3613 | 2982 | /*
* ALSA driver for Echoaudio soundcards.
* Copyright (C) 2009 Giuliano Pochini <pochini@shiny.it>
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#define INDIGO_FAMILY
#define ECHOCARD_INDIGO_DJX
#define ECHOCARD_NAME "Indigo DJx"
#define ECHOCARD_HAS_SUPER_INTERLEAVE
#define ECHOCARD_HAS_VMIXER
#define ECHOCARD_HAS_STEREO_BIG_ENDIAN32
/* Pipe indexes */
#define PX_ANALOG_OUT 0 /* 8 */
#define PX_DIGITAL_OUT 8 /* 0 */
#define PX_ANALOG_IN 8 /* 0 */
#define PX_DIGITAL_IN 8 /* 0 */
#define PX_NUM 8
/* Bus indexes */
#define BX_ANALOG_OUT 0 /* 4 */
#define BX_DIGITAL_OUT 4 /* 0 */
#define BX_ANALOG_IN 4 /* 0 */
#define BX_DIGITAL_IN 4 /* 0 */
#define BX_NUM 4
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/moduleparam.h>
#include <linux/firmware.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/asoundef.h>
#include <sound/initval.h>
#include <asm/atomic.h>
#include "echoaudio.h"
MODULE_FIRMWARE("ea/loader_dsp.fw");
MODULE_FIRMWARE("ea/indigo_djx_dsp.fw");
#define FW_361_LOADER 0
#define FW_INDIGO_DJX_DSP 1
static const struct firmware card_fw[] = {
{0, "loader_dsp.fw"},
{0, "indigo_djx_dsp.fw"}
};
static DEFINE_PCI_DEVICE_TABLE(snd_echo_ids) = {
{0x1057, 0x3410, 0xECC0, 0x00E0, 0, 0, 0}, /* Indigo DJx*/
{0,}
};
static struct snd_pcm_hardware pcm_hardware_skel = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_SYNC_START,
.formats = SNDRV_PCM_FMTBIT_U8 |
SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S24_3LE |
SNDRV_PCM_FMTBIT_S32_LE |
SNDRV_PCM_FMTBIT_S32_BE,
.rates = SNDRV_PCM_RATE_32000 |
SNDRV_PCM_RATE_44100 |
SNDRV_PCM_RATE_48000 |
SNDRV_PCM_RATE_64000 |
SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000,
.rate_min = 32000,
.rate_max = 96000,
.channels_min = 1,
.channels_max = 4,
.buffer_bytes_max = 262144,
.period_bytes_min = 32,
.period_bytes_max = 131072,
.periods_min = 2,
.periods_max = 220,
};
#include "indigodjx_dsp.c"
#include "indigo_express_dsp.c"
#include "echoaudio_dsp.c"
#include "echoaudio.c"
| gpl-2.0 |
Vangreen/android_kernel_lge_msm8926 | drivers/usb/storage/alauda.c | 4637 | 34365 | /*
* Driver for Alauda-based card readers
*
* Current development and maintenance by:
* (c) 2005 Daniel Drake <dsd@gentoo.org>
*
* The 'Alauda' is a chip manufacturered by RATOC for OEM use.
*
* Alauda implements a vendor-specific command set to access two media reader
* ports (XD, SmartMedia). This driver converts SCSI commands to the commands
* which are accepted by these devices.
*
* The driver was developed through reverse-engineering, with the help of the
* sddr09 driver which has many similarities, and with some help from the
* (very old) vendor-supplied GPL sma03 driver.
*
* For protocol info, see http://alauda.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, 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/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include "usb.h"
#include "transport.h"
#include "protocol.h"
#include "debug.h"
MODULE_DESCRIPTION("Driver for Alauda-based card readers");
MODULE_AUTHOR("Daniel Drake <dsd@gentoo.org>");
MODULE_LICENSE("GPL");
/*
* Status bytes
*/
#define ALAUDA_STATUS_ERROR 0x01
#define ALAUDA_STATUS_READY 0x40
/*
* Control opcodes (for request field)
*/
#define ALAUDA_GET_XD_MEDIA_STATUS 0x08
#define ALAUDA_GET_SM_MEDIA_STATUS 0x98
#define ALAUDA_ACK_XD_MEDIA_CHANGE 0x0a
#define ALAUDA_ACK_SM_MEDIA_CHANGE 0x9a
#define ALAUDA_GET_XD_MEDIA_SIG 0x86
#define ALAUDA_GET_SM_MEDIA_SIG 0x96
/*
* Bulk command identity (byte 0)
*/
#define ALAUDA_BULK_CMD 0x40
/*
* Bulk opcodes (byte 1)
*/
#define ALAUDA_BULK_GET_REDU_DATA 0x85
#define ALAUDA_BULK_READ_BLOCK 0x94
#define ALAUDA_BULK_ERASE_BLOCK 0xa3
#define ALAUDA_BULK_WRITE_BLOCK 0xb4
#define ALAUDA_BULK_GET_STATUS2 0xb7
#define ALAUDA_BULK_RESET_MEDIA 0xe0
/*
* Port to operate on (byte 8)
*/
#define ALAUDA_PORT_XD 0x00
#define ALAUDA_PORT_SM 0x01
/*
* LBA and PBA are unsigned ints. Special values.
*/
#define UNDEF 0xffff
#define SPARE 0xfffe
#define UNUSABLE 0xfffd
struct alauda_media_info {
unsigned long capacity; /* total media size in bytes */
unsigned int pagesize; /* page size in bytes */
unsigned int blocksize; /* number of pages per block */
unsigned int uzonesize; /* number of usable blocks per zone */
unsigned int zonesize; /* number of blocks per zone */
unsigned int blockmask; /* mask to get page from address */
unsigned char pageshift;
unsigned char blockshift;
unsigned char zoneshift;
u16 **lba_to_pba; /* logical to physical block map */
u16 **pba_to_lba; /* physical to logical block map */
};
struct alauda_info {
struct alauda_media_info port[2];
int wr_ep; /* endpoint to write data out of */
unsigned char sense_key;
unsigned long sense_asc; /* additional sense code */
unsigned long sense_ascq; /* additional sense code qualifier */
};
#define short_pack(lsb,msb) ( ((u16)(lsb)) | ( ((u16)(msb))<<8 ) )
#define LSB_of(s) ((s)&0xFF)
#define MSB_of(s) ((s)>>8)
#define MEDIA_PORT(us) us->srb->device->lun
#define MEDIA_INFO(us) ((struct alauda_info *)us->extra)->port[MEDIA_PORT(us)]
#define PBA_LO(pba) ((pba & 0xF) << 5)
#define PBA_HI(pba) (pba >> 3)
#define PBA_ZONE(pba) (pba >> 11)
static int init_alauda(struct us_data *us);
/*
* The table of devices
*/
#define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
vendorName, productName, useProtocol, useTransport, \
initFunction, flags) \
{ USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \
.driver_info = (flags)|(USB_US_TYPE_STOR<<24) }
static struct usb_device_id alauda_usb_ids[] = {
# include "unusual_alauda.h"
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, alauda_usb_ids);
#undef UNUSUAL_DEV
/*
* The flags table
*/
#define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
vendor_name, product_name, use_protocol, use_transport, \
init_function, Flags) \
{ \
.vendorName = vendor_name, \
.productName = product_name, \
.useProtocol = use_protocol, \
.useTransport = use_transport, \
.initFunction = init_function, \
}
static struct us_unusual_dev alauda_unusual_dev_list[] = {
# include "unusual_alauda.h"
{ } /* Terminating entry */
};
#undef UNUSUAL_DEV
/*
* Media handling
*/
struct alauda_card_info {
unsigned char id; /* id byte */
unsigned char chipshift; /* 1<<cs bytes total capacity */
unsigned char pageshift; /* 1<<ps bytes in a page */
unsigned char blockshift; /* 1<<bs pages per block */
unsigned char zoneshift; /* 1<<zs blocks per zone */
};
static struct alauda_card_info alauda_card_ids[] = {
/* NAND flash */
{ 0x6e, 20, 8, 4, 8}, /* 1 MB */
{ 0xe8, 20, 8, 4, 8}, /* 1 MB */
{ 0xec, 20, 8, 4, 8}, /* 1 MB */
{ 0x64, 21, 8, 4, 9}, /* 2 MB */
{ 0xea, 21, 8, 4, 9}, /* 2 MB */
{ 0x6b, 22, 9, 4, 9}, /* 4 MB */
{ 0xe3, 22, 9, 4, 9}, /* 4 MB */
{ 0xe5, 22, 9, 4, 9}, /* 4 MB */
{ 0xe6, 23, 9, 4, 10}, /* 8 MB */
{ 0x73, 24, 9, 5, 10}, /* 16 MB */
{ 0x75, 25, 9, 5, 10}, /* 32 MB */
{ 0x76, 26, 9, 5, 10}, /* 64 MB */
{ 0x79, 27, 9, 5, 10}, /* 128 MB */
{ 0x71, 28, 9, 5, 10}, /* 256 MB */
/* MASK ROM */
{ 0x5d, 21, 9, 4, 8}, /* 2 MB */
{ 0xd5, 22, 9, 4, 9}, /* 4 MB */
{ 0xd6, 23, 9, 4, 10}, /* 8 MB */
{ 0x57, 24, 9, 4, 11}, /* 16 MB */
{ 0x58, 25, 9, 4, 12}, /* 32 MB */
{ 0,}
};
static struct alauda_card_info *alauda_card_find_id(unsigned char id) {
int i;
for (i = 0; alauda_card_ids[i].id != 0; i++)
if (alauda_card_ids[i].id == id)
return &(alauda_card_ids[i]);
return NULL;
}
/*
* ECC computation.
*/
static unsigned char parity[256];
static unsigned char ecc2[256];
static void nand_init_ecc(void) {
int i, j, a;
parity[0] = 0;
for (i = 1; i < 256; i++)
parity[i] = (parity[i&(i-1)] ^ 1);
for (i = 0; i < 256; i++) {
a = 0;
for (j = 0; j < 8; j++) {
if (i & (1<<j)) {
if ((j & 1) == 0)
a ^= 0x04;
if ((j & 2) == 0)
a ^= 0x10;
if ((j & 4) == 0)
a ^= 0x40;
}
}
ecc2[i] = ~(a ^ (a<<1) ^ (parity[i] ? 0xa8 : 0));
}
}
/* compute 3-byte ecc on 256 bytes */
static void nand_compute_ecc(unsigned char *data, unsigned char *ecc) {
int i, j, a;
unsigned char par, bit, bits[8];
par = 0;
for (j = 0; j < 8; j++)
bits[j] = 0;
/* collect 16 checksum bits */
for (i = 0; i < 256; i++) {
par ^= data[i];
bit = parity[data[i]];
for (j = 0; j < 8; j++)
if ((i & (1<<j)) == 0)
bits[j] ^= bit;
}
/* put 4+4+4 = 12 bits in the ecc */
a = (bits[3] << 6) + (bits[2] << 4) + (bits[1] << 2) + bits[0];
ecc[0] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0));
a = (bits[7] << 6) + (bits[6] << 4) + (bits[5] << 2) + bits[4];
ecc[1] = ~(a ^ (a<<1) ^ (parity[par] ? 0xaa : 0));
ecc[2] = ecc2[par];
}
static int nand_compare_ecc(unsigned char *data, unsigned char *ecc) {
return (data[0] == ecc[0] && data[1] == ecc[1] && data[2] == ecc[2]);
}
static void nand_store_ecc(unsigned char *data, unsigned char *ecc) {
memcpy(data, ecc, 3);
}
/*
* Alauda driver
*/
/*
* Forget our PBA <---> LBA mappings for a particular port
*/
static void alauda_free_maps (struct alauda_media_info *media_info)
{
unsigned int shift = media_info->zoneshift
+ media_info->blockshift + media_info->pageshift;
unsigned int num_zones = media_info->capacity >> shift;
unsigned int i;
if (media_info->lba_to_pba != NULL)
for (i = 0; i < num_zones; i++) {
kfree(media_info->lba_to_pba[i]);
media_info->lba_to_pba[i] = NULL;
}
if (media_info->pba_to_lba != NULL)
for (i = 0; i < num_zones; i++) {
kfree(media_info->pba_to_lba[i]);
media_info->pba_to_lba[i] = NULL;
}
}
/*
* Returns 2 bytes of status data
* The first byte describes media status, and second byte describes door status
*/
static int alauda_get_media_status(struct us_data *us, unsigned char *data)
{
int rc;
unsigned char command;
if (MEDIA_PORT(us) == ALAUDA_PORT_XD)
command = ALAUDA_GET_XD_MEDIA_STATUS;
else
command = ALAUDA_GET_SM_MEDIA_STATUS;
rc = usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe,
command, 0xc0, 0, 1, data, 2);
US_DEBUGP("alauda_get_media_status: Media status %02X %02X\n",
data[0], data[1]);
return rc;
}
/*
* Clears the "media was changed" bit so that we know when it changes again
* in the future.
*/
static int alauda_ack_media(struct us_data *us)
{
unsigned char command;
if (MEDIA_PORT(us) == ALAUDA_PORT_XD)
command = ALAUDA_ACK_XD_MEDIA_CHANGE;
else
command = ALAUDA_ACK_SM_MEDIA_CHANGE;
return usb_stor_ctrl_transfer(us, us->send_ctrl_pipe,
command, 0x40, 0, 1, NULL, 0);
}
/*
* Retrieves a 4-byte media signature, which indicates manufacturer, capacity,
* and some other details.
*/
static int alauda_get_media_signature(struct us_data *us, unsigned char *data)
{
unsigned char command;
if (MEDIA_PORT(us) == ALAUDA_PORT_XD)
command = ALAUDA_GET_XD_MEDIA_SIG;
else
command = ALAUDA_GET_SM_MEDIA_SIG;
return usb_stor_ctrl_transfer(us, us->recv_ctrl_pipe,
command, 0xc0, 0, 0, data, 4);
}
/*
* Resets the media status (but not the whole device?)
*/
static int alauda_reset_media(struct us_data *us)
{
unsigned char *command = us->iobuf;
memset(command, 0, 9);
command[0] = ALAUDA_BULK_CMD;
command[1] = ALAUDA_BULK_RESET_MEDIA;
command[8] = MEDIA_PORT(us);
return usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
command, 9, NULL);
}
/*
* Examines the media and deduces capacity, etc.
*/
static int alauda_init_media(struct us_data *us)
{
unsigned char *data = us->iobuf;
int ready = 0;
struct alauda_card_info *media_info;
unsigned int num_zones;
while (ready == 0) {
msleep(20);
if (alauda_get_media_status(us, data) != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
if (data[0] & 0x10)
ready = 1;
}
US_DEBUGP("alauda_init_media: We are ready for action!\n");
if (alauda_ack_media(us) != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
msleep(10);
if (alauda_get_media_status(us, data) != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
if (data[0] != 0x14) {
US_DEBUGP("alauda_init_media: Media not ready after ack\n");
return USB_STOR_TRANSPORT_ERROR;
}
if (alauda_get_media_signature(us, data) != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
US_DEBUGP("alauda_init_media: Media signature: %02X %02X %02X %02X\n",
data[0], data[1], data[2], data[3]);
media_info = alauda_card_find_id(data[1]);
if (media_info == NULL) {
printk(KERN_WARNING
"alauda_init_media: Unrecognised media signature: "
"%02X %02X %02X %02X\n",
data[0], data[1], data[2], data[3]);
return USB_STOR_TRANSPORT_ERROR;
}
MEDIA_INFO(us).capacity = 1 << media_info->chipshift;
US_DEBUGP("Found media with capacity: %ldMB\n",
MEDIA_INFO(us).capacity >> 20);
MEDIA_INFO(us).pageshift = media_info->pageshift;
MEDIA_INFO(us).blockshift = media_info->blockshift;
MEDIA_INFO(us).zoneshift = media_info->zoneshift;
MEDIA_INFO(us).pagesize = 1 << media_info->pageshift;
MEDIA_INFO(us).blocksize = 1 << media_info->blockshift;
MEDIA_INFO(us).zonesize = 1 << media_info->zoneshift;
MEDIA_INFO(us).uzonesize = ((1 << media_info->zoneshift) / 128) * 125;
MEDIA_INFO(us).blockmask = MEDIA_INFO(us).blocksize - 1;
num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift
+ MEDIA_INFO(us).blockshift + MEDIA_INFO(us).pageshift);
MEDIA_INFO(us).pba_to_lba = kcalloc(num_zones, sizeof(u16*), GFP_NOIO);
MEDIA_INFO(us).lba_to_pba = kcalloc(num_zones, sizeof(u16*), GFP_NOIO);
if (alauda_reset_media(us) != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
return USB_STOR_TRANSPORT_GOOD;
}
/*
* Examines the media status and does the right thing when the media has gone,
* appeared, or changed.
*/
static int alauda_check_media(struct us_data *us)
{
struct alauda_info *info = (struct alauda_info *) us->extra;
unsigned char status[2];
int rc;
rc = alauda_get_media_status(us, status);
/* Check for no media or door open */
if ((status[0] & 0x80) || ((status[0] & 0x1F) == 0x10)
|| ((status[1] & 0x01) == 0)) {
US_DEBUGP("alauda_check_media: No media, or door open\n");
alauda_free_maps(&MEDIA_INFO(us));
info->sense_key = 0x02;
info->sense_asc = 0x3A;
info->sense_ascq = 0x00;
return USB_STOR_TRANSPORT_FAILED;
}
/* Check for media change */
if (status[0] & 0x08) {
US_DEBUGP("alauda_check_media: Media change detected\n");
alauda_free_maps(&MEDIA_INFO(us));
alauda_init_media(us);
info->sense_key = UNIT_ATTENTION;
info->sense_asc = 0x28;
info->sense_ascq = 0x00;
return USB_STOR_TRANSPORT_FAILED;
}
return USB_STOR_TRANSPORT_GOOD;
}
/*
* Checks the status from the 2nd status register
* Returns 3 bytes of status data, only the first is known
*/
static int alauda_check_status2(struct us_data *us)
{
int rc;
unsigned char command[] = {
ALAUDA_BULK_CMD, ALAUDA_BULK_GET_STATUS2,
0, 0, 0, 0, 3, 0, MEDIA_PORT(us)
};
unsigned char data[3];
rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
command, 9, NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
rc = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
data, 3, NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
US_DEBUGP("alauda_check_status2: %02X %02X %02X\n", data[0], data[1], data[2]);
if (data[0] & ALAUDA_STATUS_ERROR)
return USB_STOR_XFER_ERROR;
return USB_STOR_XFER_GOOD;
}
/*
* Gets the redundancy data for the first page of a PBA
* Returns 16 bytes.
*/
static int alauda_get_redu_data(struct us_data *us, u16 pba, unsigned char *data)
{
int rc;
unsigned char command[] = {
ALAUDA_BULK_CMD, ALAUDA_BULK_GET_REDU_DATA,
PBA_HI(pba), PBA_ZONE(pba), 0, PBA_LO(pba), 0, 0, MEDIA_PORT(us)
};
rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
command, 9, NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
data, 16, NULL);
}
/*
* Finds the first unused PBA in a zone
* Returns the absolute PBA of an unused PBA, or 0 if none found.
*/
static u16 alauda_find_unused_pba(struct alauda_media_info *info,
unsigned int zone)
{
u16 *pba_to_lba = info->pba_to_lba[zone];
unsigned int i;
for (i = 0; i < info->zonesize; i++)
if (pba_to_lba[i] == UNDEF)
return (zone << info->zoneshift) + i;
return 0;
}
/*
* Reads the redundancy data for all PBA's in a zone
* Produces lba <--> pba mappings
*/
static int alauda_read_map(struct us_data *us, unsigned int zone)
{
unsigned char *data = us->iobuf;
int result;
int i, j;
unsigned int zonesize = MEDIA_INFO(us).zonesize;
unsigned int uzonesize = MEDIA_INFO(us).uzonesize;
unsigned int lba_offset, lba_real, blocknum;
unsigned int zone_base_lba = zone * uzonesize;
unsigned int zone_base_pba = zone * zonesize;
u16 *lba_to_pba = kcalloc(zonesize, sizeof(u16), GFP_NOIO);
u16 *pba_to_lba = kcalloc(zonesize, sizeof(u16), GFP_NOIO);
if (lba_to_pba == NULL || pba_to_lba == NULL) {
result = USB_STOR_TRANSPORT_ERROR;
goto error;
}
US_DEBUGP("alauda_read_map: Mapping blocks for zone %d\n", zone);
/* 1024 PBA's per zone */
for (i = 0; i < zonesize; i++)
lba_to_pba[i] = pba_to_lba[i] = UNDEF;
for (i = 0; i < zonesize; i++) {
blocknum = zone_base_pba + i;
result = alauda_get_redu_data(us, blocknum, data);
if (result != USB_STOR_XFER_GOOD) {
result = USB_STOR_TRANSPORT_ERROR;
goto error;
}
/* special PBAs have control field 0^16 */
for (j = 0; j < 16; j++)
if (data[j] != 0)
goto nonz;
pba_to_lba[i] = UNUSABLE;
US_DEBUGP("alauda_read_map: PBA %d has no logical mapping\n", blocknum);
continue;
nonz:
/* unwritten PBAs have control field FF^16 */
for (j = 0; j < 16; j++)
if (data[j] != 0xff)
goto nonff;
continue;
nonff:
/* normal PBAs start with six FFs */
if (j < 6) {
US_DEBUGP("alauda_read_map: PBA %d has no logical mapping: "
"reserved area = %02X%02X%02X%02X "
"data status %02X block status %02X\n",
blocknum, data[0], data[1], data[2], data[3],
data[4], data[5]);
pba_to_lba[i] = UNUSABLE;
continue;
}
if ((data[6] >> 4) != 0x01) {
US_DEBUGP("alauda_read_map: PBA %d has invalid address "
"field %02X%02X/%02X%02X\n",
blocknum, data[6], data[7], data[11], data[12]);
pba_to_lba[i] = UNUSABLE;
continue;
}
/* check even parity */
if (parity[data[6] ^ data[7]]) {
printk(KERN_WARNING
"alauda_read_map: Bad parity in LBA for block %d"
" (%02X %02X)\n", i, data[6], data[7]);
pba_to_lba[i] = UNUSABLE;
continue;
}
lba_offset = short_pack(data[7], data[6]);
lba_offset = (lba_offset & 0x07FF) >> 1;
lba_real = lba_offset + zone_base_lba;
/*
* Every 1024 physical blocks ("zone"), the LBA numbers
* go back to zero, but are within a higher block of LBA's.
* Also, there is a maximum of 1000 LBA's per zone.
* In other words, in PBA 1024-2047 you will find LBA 0-999
* which are really LBA 1000-1999. This allows for 24 bad
* or special physical blocks per zone.
*/
if (lba_offset >= uzonesize) {
printk(KERN_WARNING
"alauda_read_map: Bad low LBA %d for block %d\n",
lba_real, blocknum);
continue;
}
if (lba_to_pba[lba_offset] != UNDEF) {
printk(KERN_WARNING
"alauda_read_map: "
"LBA %d seen for PBA %d and %d\n",
lba_real, lba_to_pba[lba_offset], blocknum);
continue;
}
pba_to_lba[i] = lba_real;
lba_to_pba[lba_offset] = blocknum;
continue;
}
MEDIA_INFO(us).lba_to_pba[zone] = lba_to_pba;
MEDIA_INFO(us).pba_to_lba[zone] = pba_to_lba;
result = 0;
goto out;
error:
kfree(lba_to_pba);
kfree(pba_to_lba);
out:
return result;
}
/*
* Checks to see whether we have already mapped a certain zone
* If we haven't, the map is generated
*/
static void alauda_ensure_map_for_zone(struct us_data *us, unsigned int zone)
{
if (MEDIA_INFO(us).lba_to_pba[zone] == NULL
|| MEDIA_INFO(us).pba_to_lba[zone] == NULL)
alauda_read_map(us, zone);
}
/*
* Erases an entire block
*/
static int alauda_erase_block(struct us_data *us, u16 pba)
{
int rc;
unsigned char command[] = {
ALAUDA_BULK_CMD, ALAUDA_BULK_ERASE_BLOCK, PBA_HI(pba),
PBA_ZONE(pba), 0, PBA_LO(pba), 0x02, 0, MEDIA_PORT(us)
};
unsigned char buf[2];
US_DEBUGP("alauda_erase_block: Erasing PBA %d\n", pba);
rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
command, 9, NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
rc = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
buf, 2, NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
US_DEBUGP("alauda_erase_block: Erase result: %02X %02X\n",
buf[0], buf[1]);
return rc;
}
/*
* Reads data from a certain offset page inside a PBA, including interleaved
* redundancy data. Returns (pagesize+64)*pages bytes in data.
*/
static int alauda_read_block_raw(struct us_data *us, u16 pba,
unsigned int page, unsigned int pages, unsigned char *data)
{
int rc;
unsigned char command[] = {
ALAUDA_BULK_CMD, ALAUDA_BULK_READ_BLOCK, PBA_HI(pba),
PBA_ZONE(pba), 0, PBA_LO(pba) + page, pages, 0, MEDIA_PORT(us)
};
US_DEBUGP("alauda_read_block: pba %d page %d count %d\n",
pba, page, pages);
rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
command, 9, NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
return usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
data, (MEDIA_INFO(us).pagesize + 64) * pages, NULL);
}
/*
* Reads data from a certain offset page inside a PBA, excluding redundancy
* data. Returns pagesize*pages bytes in data. Note that data must be big enough
* to hold (pagesize+64)*pages bytes of data, but you can ignore those 'extra'
* trailing bytes outside this function.
*/
static int alauda_read_block(struct us_data *us, u16 pba,
unsigned int page, unsigned int pages, unsigned char *data)
{
int i, rc;
unsigned int pagesize = MEDIA_INFO(us).pagesize;
rc = alauda_read_block_raw(us, pba, page, pages, data);
if (rc != USB_STOR_XFER_GOOD)
return rc;
/* Cut out the redundancy data */
for (i = 0; i < pages; i++) {
int dest_offset = i * pagesize;
int src_offset = i * (pagesize + 64);
memmove(data + dest_offset, data + src_offset, pagesize);
}
return rc;
}
/*
* Writes an entire block of data and checks status after write.
* Redundancy data must be already included in data. Data should be
* (pagesize+64)*blocksize bytes in length.
*/
static int alauda_write_block(struct us_data *us, u16 pba, unsigned char *data)
{
int rc;
struct alauda_info *info = (struct alauda_info *) us->extra;
unsigned char command[] = {
ALAUDA_BULK_CMD, ALAUDA_BULK_WRITE_BLOCK, PBA_HI(pba),
PBA_ZONE(pba), 0, PBA_LO(pba), 32, 0, MEDIA_PORT(us)
};
US_DEBUGP("alauda_write_block: pba %d\n", pba);
rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
command, 9, NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
rc = usb_stor_bulk_transfer_buf(us, info->wr_ep, data,
(MEDIA_INFO(us).pagesize + 64) * MEDIA_INFO(us).blocksize,
NULL);
if (rc != USB_STOR_XFER_GOOD)
return rc;
return alauda_check_status2(us);
}
/*
* Write some data to a specific LBA.
*/
static int alauda_write_lba(struct us_data *us, u16 lba,
unsigned int page, unsigned int pages,
unsigned char *ptr, unsigned char *blockbuffer)
{
u16 pba, lbap, new_pba;
unsigned char *bptr, *cptr, *xptr;
unsigned char ecc[3];
int i, result;
unsigned int uzonesize = MEDIA_INFO(us).uzonesize;
unsigned int zonesize = MEDIA_INFO(us).zonesize;
unsigned int pagesize = MEDIA_INFO(us).pagesize;
unsigned int blocksize = MEDIA_INFO(us).blocksize;
unsigned int lba_offset = lba % uzonesize;
unsigned int new_pba_offset;
unsigned int zone = lba / uzonesize;
alauda_ensure_map_for_zone(us, zone);
pba = MEDIA_INFO(us).lba_to_pba[zone][lba_offset];
if (pba == 1) {
/* Maybe it is impossible to write to PBA 1.
Fake success, but don't do anything. */
printk(KERN_WARNING
"alauda_write_lba: avoid writing to pba 1\n");
return USB_STOR_TRANSPORT_GOOD;
}
new_pba = alauda_find_unused_pba(&MEDIA_INFO(us), zone);
if (!new_pba) {
printk(KERN_WARNING
"alauda_write_lba: Out of unused blocks\n");
return USB_STOR_TRANSPORT_ERROR;
}
/* read old contents */
if (pba != UNDEF) {
result = alauda_read_block_raw(us, pba, 0,
blocksize, blockbuffer);
if (result != USB_STOR_XFER_GOOD)
return result;
} else {
memset(blockbuffer, 0, blocksize * (pagesize + 64));
}
lbap = (lba_offset << 1) | 0x1000;
if (parity[MSB_of(lbap) ^ LSB_of(lbap)])
lbap ^= 1;
/* check old contents and fill lba */
for (i = 0; i < blocksize; i++) {
bptr = blockbuffer + (i * (pagesize + 64));
cptr = bptr + pagesize;
nand_compute_ecc(bptr, ecc);
if (!nand_compare_ecc(cptr+13, ecc)) {
US_DEBUGP("Warning: bad ecc in page %d- of pba %d\n",
i, pba);
nand_store_ecc(cptr+13, ecc);
}
nand_compute_ecc(bptr + (pagesize / 2), ecc);
if (!nand_compare_ecc(cptr+8, ecc)) {
US_DEBUGP("Warning: bad ecc in page %d+ of pba %d\n",
i, pba);
nand_store_ecc(cptr+8, ecc);
}
cptr[6] = cptr[11] = MSB_of(lbap);
cptr[7] = cptr[12] = LSB_of(lbap);
}
/* copy in new stuff and compute ECC */
xptr = ptr;
for (i = page; i < page+pages; i++) {
bptr = blockbuffer + (i * (pagesize + 64));
cptr = bptr + pagesize;
memcpy(bptr, xptr, pagesize);
xptr += pagesize;
nand_compute_ecc(bptr, ecc);
nand_store_ecc(cptr+13, ecc);
nand_compute_ecc(bptr + (pagesize / 2), ecc);
nand_store_ecc(cptr+8, ecc);
}
result = alauda_write_block(us, new_pba, blockbuffer);
if (result != USB_STOR_XFER_GOOD)
return result;
new_pba_offset = new_pba - (zone * zonesize);
MEDIA_INFO(us).pba_to_lba[zone][new_pba_offset] = lba;
MEDIA_INFO(us).lba_to_pba[zone][lba_offset] = new_pba;
US_DEBUGP("alauda_write_lba: Remapped LBA %d to PBA %d\n",
lba, new_pba);
if (pba != UNDEF) {
unsigned int pba_offset = pba - (zone * zonesize);
result = alauda_erase_block(us, pba);
if (result != USB_STOR_XFER_GOOD)
return result;
MEDIA_INFO(us).pba_to_lba[zone][pba_offset] = UNDEF;
}
return USB_STOR_TRANSPORT_GOOD;
}
/*
* Read data from a specific sector address
*/
static int alauda_read_data(struct us_data *us, unsigned long address,
unsigned int sectors)
{
unsigned char *buffer;
u16 lba, max_lba;
unsigned int page, len, offset;
unsigned int blockshift = MEDIA_INFO(us).blockshift;
unsigned int pageshift = MEDIA_INFO(us).pageshift;
unsigned int blocksize = MEDIA_INFO(us).blocksize;
unsigned int pagesize = MEDIA_INFO(us).pagesize;
unsigned int uzonesize = MEDIA_INFO(us).uzonesize;
struct scatterlist *sg;
int result;
/*
* Since we only read in one block at a time, we have to create
* a bounce buffer and move the data a piece at a time between the
* bounce buffer and the actual transfer buffer.
* We make this buffer big enough to hold temporary redundancy data,
* which we use when reading the data blocks.
*/
len = min(sectors, blocksize) * (pagesize + 64);
buffer = kmalloc(len, GFP_NOIO);
if (buffer == NULL) {
printk(KERN_WARNING "alauda_read_data: Out of memory\n");
return USB_STOR_TRANSPORT_ERROR;
}
/* Figure out the initial LBA and page */
lba = address >> blockshift;
page = (address & MEDIA_INFO(us).blockmask);
max_lba = MEDIA_INFO(us).capacity >> (blockshift + pageshift);
result = USB_STOR_TRANSPORT_GOOD;
offset = 0;
sg = NULL;
while (sectors > 0) {
unsigned int zone = lba / uzonesize; /* integer division */
unsigned int lba_offset = lba - (zone * uzonesize);
unsigned int pages;
u16 pba;
alauda_ensure_map_for_zone(us, zone);
/* Not overflowing capacity? */
if (lba >= max_lba) {
US_DEBUGP("Error: Requested lba %u exceeds "
"maximum %u\n", lba, max_lba);
result = USB_STOR_TRANSPORT_ERROR;
break;
}
/* Find number of pages we can read in this block */
pages = min(sectors, blocksize - page);
len = pages << pageshift;
/* Find where this lba lives on disk */
pba = MEDIA_INFO(us).lba_to_pba[zone][lba_offset];
if (pba == UNDEF) { /* this lba was never written */
US_DEBUGP("Read %d zero pages (LBA %d) page %d\n",
pages, lba, page);
/* This is not really an error. It just means
that the block has never been written.
Instead of returning USB_STOR_TRANSPORT_ERROR
it is better to return all zero data. */
memset(buffer, 0, len);
} else {
US_DEBUGP("Read %d pages, from PBA %d"
" (LBA %d) page %d\n",
pages, pba, lba, page);
result = alauda_read_block(us, pba, page, pages, buffer);
if (result != USB_STOR_TRANSPORT_GOOD)
break;
}
/* Store the data in the transfer buffer */
usb_stor_access_xfer_buf(buffer, len, us->srb,
&sg, &offset, TO_XFER_BUF);
page = 0;
lba++;
sectors -= pages;
}
kfree(buffer);
return result;
}
/*
* Write data to a specific sector address
*/
static int alauda_write_data(struct us_data *us, unsigned long address,
unsigned int sectors)
{
unsigned char *buffer, *blockbuffer;
unsigned int page, len, offset;
unsigned int blockshift = MEDIA_INFO(us).blockshift;
unsigned int pageshift = MEDIA_INFO(us).pageshift;
unsigned int blocksize = MEDIA_INFO(us).blocksize;
unsigned int pagesize = MEDIA_INFO(us).pagesize;
struct scatterlist *sg;
u16 lba, max_lba;
int result;
/*
* Since we don't write the user data directly to the device,
* we have to create a bounce buffer and move the data a piece
* at a time between the bounce buffer and the actual transfer buffer.
*/
len = min(sectors, blocksize) * pagesize;
buffer = kmalloc(len, GFP_NOIO);
if (buffer == NULL) {
printk(KERN_WARNING "alauda_write_data: Out of memory\n");
return USB_STOR_TRANSPORT_ERROR;
}
/*
* We also need a temporary block buffer, where we read in the old data,
* overwrite parts with the new data, and manipulate the redundancy data
*/
blockbuffer = kmalloc((pagesize + 64) * blocksize, GFP_NOIO);
if (blockbuffer == NULL) {
printk(KERN_WARNING "alauda_write_data: Out of memory\n");
kfree(buffer);
return USB_STOR_TRANSPORT_ERROR;
}
/* Figure out the initial LBA and page */
lba = address >> blockshift;
page = (address & MEDIA_INFO(us).blockmask);
max_lba = MEDIA_INFO(us).capacity >> (pageshift + blockshift);
result = USB_STOR_TRANSPORT_GOOD;
offset = 0;
sg = NULL;
while (sectors > 0) {
/* Write as many sectors as possible in this block */
unsigned int pages = min(sectors, blocksize - page);
len = pages << pageshift;
/* Not overflowing capacity? */
if (lba >= max_lba) {
US_DEBUGP("alauda_write_data: Requested lba %u exceeds "
"maximum %u\n", lba, max_lba);
result = USB_STOR_TRANSPORT_ERROR;
break;
}
/* Get the data from the transfer buffer */
usb_stor_access_xfer_buf(buffer, len, us->srb,
&sg, &offset, FROM_XFER_BUF);
result = alauda_write_lba(us, lba, page, pages, buffer,
blockbuffer);
if (result != USB_STOR_TRANSPORT_GOOD)
break;
page = 0;
lba++;
sectors -= pages;
}
kfree(buffer);
kfree(blockbuffer);
return result;
}
/*
* Our interface with the rest of the world
*/
static void alauda_info_destructor(void *extra)
{
struct alauda_info *info = (struct alauda_info *) extra;
int port;
if (!info)
return;
for (port = 0; port < 2; port++) {
struct alauda_media_info *media_info = &info->port[port];
alauda_free_maps(media_info);
kfree(media_info->lba_to_pba);
kfree(media_info->pba_to_lba);
}
}
/*
* Initialize alauda_info struct and find the data-write endpoint
*/
static int init_alauda(struct us_data *us)
{
struct alauda_info *info;
struct usb_host_interface *altsetting = us->pusb_intf->cur_altsetting;
nand_init_ecc();
us->extra = kzalloc(sizeof(struct alauda_info), GFP_NOIO);
if (!us->extra) {
US_DEBUGP("init_alauda: Gah! Can't allocate storage for"
"alauda info struct!\n");
return USB_STOR_TRANSPORT_ERROR;
}
info = (struct alauda_info *) us->extra;
us->extra_destructor = alauda_info_destructor;
info->wr_ep = usb_sndbulkpipe(us->pusb_dev,
altsetting->endpoint[0].desc.bEndpointAddress
& USB_ENDPOINT_NUMBER_MASK);
return USB_STOR_TRANSPORT_GOOD;
}
static int alauda_transport(struct scsi_cmnd *srb, struct us_data *us)
{
int rc;
struct alauda_info *info = (struct alauda_info *) us->extra;
unsigned char *ptr = us->iobuf;
static unsigned char inquiry_response[36] = {
0x00, 0x80, 0x00, 0x01, 0x1F, 0x00, 0x00, 0x00
};
if (srb->cmnd[0] == INQUIRY) {
US_DEBUGP("alauda_transport: INQUIRY. "
"Returning bogus response.\n");
memcpy(ptr, inquiry_response, sizeof(inquiry_response));
fill_inquiry_response(us, ptr, 36);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == TEST_UNIT_READY) {
US_DEBUGP("alauda_transport: TEST_UNIT_READY.\n");
return alauda_check_media(us);
}
if (srb->cmnd[0] == READ_CAPACITY) {
unsigned int num_zones;
unsigned long capacity;
rc = alauda_check_media(us);
if (rc != USB_STOR_TRANSPORT_GOOD)
return rc;
num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift
+ MEDIA_INFO(us).blockshift + MEDIA_INFO(us).pageshift);
capacity = num_zones * MEDIA_INFO(us).uzonesize
* MEDIA_INFO(us).blocksize;
/* Report capacity and page size */
((__be32 *) ptr)[0] = cpu_to_be32(capacity - 1);
((__be32 *) ptr)[1] = cpu_to_be32(512);
usb_stor_set_xfer_buf(ptr, 8, srb);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == READ_10) {
unsigned int page, pages;
rc = alauda_check_media(us);
if (rc != USB_STOR_TRANSPORT_GOOD)
return rc;
page = short_pack(srb->cmnd[3], srb->cmnd[2]);
page <<= 16;
page |= short_pack(srb->cmnd[5], srb->cmnd[4]);
pages = short_pack(srb->cmnd[8], srb->cmnd[7]);
US_DEBUGP("alauda_transport: READ_10: page %d pagect %d\n",
page, pages);
return alauda_read_data(us, page, pages);
}
if (srb->cmnd[0] == WRITE_10) {
unsigned int page, pages;
rc = alauda_check_media(us);
if (rc != USB_STOR_TRANSPORT_GOOD)
return rc;
page = short_pack(srb->cmnd[3], srb->cmnd[2]);
page <<= 16;
page |= short_pack(srb->cmnd[5], srb->cmnd[4]);
pages = short_pack(srb->cmnd[8], srb->cmnd[7]);
US_DEBUGP("alauda_transport: WRITE_10: page %d pagect %d\n",
page, pages);
return alauda_write_data(us, page, pages);
}
if (srb->cmnd[0] == REQUEST_SENSE) {
US_DEBUGP("alauda_transport: REQUEST_SENSE.\n");
memset(ptr, 0, 18);
ptr[0] = 0xF0;
ptr[2] = info->sense_key;
ptr[7] = 11;
ptr[12] = info->sense_asc;
ptr[13] = info->sense_ascq;
usb_stor_set_xfer_buf(ptr, 18, srb);
return USB_STOR_TRANSPORT_GOOD;
}
if (srb->cmnd[0] == ALLOW_MEDIUM_REMOVAL) {
/* sure. whatever. not like we can stop the user from popping
the media out of the device (no locking doors, etc) */
return USB_STOR_TRANSPORT_GOOD;
}
US_DEBUGP("alauda_transport: Gah! Unknown command: %d (0x%x)\n",
srb->cmnd[0], srb->cmnd[0]);
info->sense_key = 0x05;
info->sense_asc = 0x20;
info->sense_ascq = 0x00;
return USB_STOR_TRANSPORT_FAILED;
}
static int alauda_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct us_data *us;
int result;
result = usb_stor_probe1(&us, intf, id,
(id - alauda_usb_ids) + alauda_unusual_dev_list);
if (result)
return result;
us->transport_name = "Alauda Control/Bulk";
us->transport = alauda_transport;
us->transport_reset = usb_stor_Bulk_reset;
us->max_lun = 1;
result = usb_stor_probe2(us);
return result;
}
static struct usb_driver alauda_driver = {
.name = "ums-alauda",
.probe = alauda_probe,
.disconnect = usb_stor_disconnect,
.suspend = usb_stor_suspend,
.resume = usb_stor_resume,
.reset_resume = usb_stor_reset_resume,
.pre_reset = usb_stor_pre_reset,
.post_reset = usb_stor_post_reset,
.id_table = alauda_usb_ids,
.soft_unbind = 1,
.no_dynamic_id = 1,
};
module_usb_driver(alauda_driver);
| gpl-2.0 |
LeMaker/linux-sunxi | net/caif/cfdgml.c | 5149 | 2950 | /*
* Copyright (C) ST-Ericsson AB 2010
* Author: Sjur Brendeland/sjur.brandeland@stericsson.com
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) KBUILD_MODNAME ":%s(): " fmt, __func__
#include <linux/stddef.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <net/caif/caif_layer.h>
#include <net/caif/cfsrvl.h>
#include <net/caif/cfpkt.h>
#define container_obj(layr) ((struct cfsrvl *) layr)
#define DGM_CMD_BIT 0x80
#define DGM_FLOW_OFF 0x81
#define DGM_FLOW_ON 0x80
#define DGM_MTU 1500
static int cfdgml_receive(struct cflayer *layr, struct cfpkt *pkt);
static int cfdgml_transmit(struct cflayer *layr, struct cfpkt *pkt);
struct cflayer *cfdgml_create(u8 channel_id, struct dev_info *dev_info)
{
struct cfsrvl *dgm = kzalloc(sizeof(struct cfsrvl), GFP_ATOMIC);
if (!dgm)
return NULL;
caif_assert(offsetof(struct cfsrvl, layer) == 0);
cfsrvl_init(dgm, channel_id, dev_info, true);
dgm->layer.receive = cfdgml_receive;
dgm->layer.transmit = cfdgml_transmit;
snprintf(dgm->layer.name, CAIF_LAYER_NAME_SZ - 1, "dgm%d", channel_id);
dgm->layer.name[CAIF_LAYER_NAME_SZ - 1] = '\0';
return &dgm->layer;
}
static int cfdgml_receive(struct cflayer *layr, struct cfpkt *pkt)
{
u8 cmd = -1;
u8 dgmhdr[3];
int ret;
caif_assert(layr->up != NULL);
caif_assert(layr->receive != NULL);
caif_assert(layr->ctrlcmd != NULL);
if (cfpkt_extr_head(pkt, &cmd, 1) < 0) {
pr_err("Packet is erroneous!\n");
cfpkt_destroy(pkt);
return -EPROTO;
}
if ((cmd & DGM_CMD_BIT) == 0) {
if (cfpkt_extr_head(pkt, &dgmhdr, 3) < 0) {
pr_err("Packet is erroneous!\n");
cfpkt_destroy(pkt);
return -EPROTO;
}
ret = layr->up->receive(layr->up, pkt);
return ret;
}
switch (cmd) {
case DGM_FLOW_OFF: /* FLOW OFF */
layr->ctrlcmd(layr, CAIF_CTRLCMD_FLOW_OFF_IND, 0);
cfpkt_destroy(pkt);
return 0;
case DGM_FLOW_ON: /* FLOW ON */
layr->ctrlcmd(layr, CAIF_CTRLCMD_FLOW_ON_IND, 0);
cfpkt_destroy(pkt);
return 0;
default:
cfpkt_destroy(pkt);
pr_info("Unknown datagram control %d (0x%x)\n", cmd, cmd);
return -EPROTO;
}
}
static int cfdgml_transmit(struct cflayer *layr, struct cfpkt *pkt)
{
u8 packet_type;
u32 zero = 0;
struct caif_payload_info *info;
struct cfsrvl *service = container_obj(layr);
int ret;
if (!cfsrvl_ready(service, &ret)) {
cfpkt_destroy(pkt);
return ret;
}
/* STE Modem cannot handle more than 1500 bytes datagrams */
if (cfpkt_getlen(pkt) > DGM_MTU) {
cfpkt_destroy(pkt);
return -EMSGSIZE;
}
cfpkt_add_head(pkt, &zero, 3);
packet_type = 0x08; /* B9 set - UNCLASSIFIED */
cfpkt_add_head(pkt, &packet_type, 1);
/* Add info for MUX-layer to route the packet out. */
info = cfpkt_info(pkt);
info->channel_id = service->layer.id;
/* To optimize alignment, we add up the size of CAIF header
* before payload.
*/
info->hdr_len = 4;
info->dev_info = &service->dev_info;
return layr->dn->transmit(layr->dn, pkt);
}
| gpl-2.0 |
vantjnh1991/F160-JB | drivers/gpu/drm/nouveau/nv04_instmem.c | 5917 | 4440 | #include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_ramht.h"
/* returns the size of fifo context */
static int
nouveau_fifo_ctx_size(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
if (dev_priv->chipset >= 0x40)
return 128;
else
if (dev_priv->chipset >= 0x17)
return 64;
return 32;
}
int nv04_instmem_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_gpuobj *ramht = NULL;
u32 offset, length;
int ret;
/* RAMIN always available */
dev_priv->ramin_available = true;
/* Reserve space at end of VRAM for PRAMIN */
if (dev_priv->card_type >= NV_40) {
u32 vs = hweight8((nv_rd32(dev, 0x001540) & 0x0000ff00) >> 8);
u32 rsvd;
/* estimate grctx size, the magics come from nv40_grctx.c */
if (dev_priv->chipset == 0x40) rsvd = 0x6aa0 * vs;
else if (dev_priv->chipset < 0x43) rsvd = 0x4f00 * vs;
else if (nv44_graph_class(dev)) rsvd = 0x4980 * vs;
else rsvd = 0x4a40 * vs;
rsvd += 16 * 1024;
rsvd *= dev_priv->engine.fifo.channels;
/* pciegart table */
if (pci_is_pcie(dev->pdev))
rsvd += 512 * 1024;
/* object storage */
rsvd += 512 * 1024;
dev_priv->ramin_rsvd_vram = round_up(rsvd, 4096);
} else {
dev_priv->ramin_rsvd_vram = 512 * 1024;
}
/* Setup shared RAMHT */
ret = nouveau_gpuobj_new_fake(dev, 0x10000, ~0, 4096,
NVOBJ_FLAG_ZERO_ALLOC, &ramht);
if (ret)
return ret;
ret = nouveau_ramht_new(dev, ramht, &dev_priv->ramht);
nouveau_gpuobj_ref(NULL, &ramht);
if (ret)
return ret;
/* And RAMRO */
ret = nouveau_gpuobj_new_fake(dev, 0x11200, ~0, 512,
NVOBJ_FLAG_ZERO_ALLOC, &dev_priv->ramro);
if (ret)
return ret;
/* And RAMFC */
length = dev_priv->engine.fifo.channels * nouveau_fifo_ctx_size(dev);
switch (dev_priv->card_type) {
case NV_40:
offset = 0x20000;
break;
default:
offset = 0x11400;
break;
}
ret = nouveau_gpuobj_new_fake(dev, offset, ~0, length,
NVOBJ_FLAG_ZERO_ALLOC, &dev_priv->ramfc);
if (ret)
return ret;
/* Only allow space after RAMFC to be used for object allocation */
offset += length;
/* It appears RAMRO (or something?) is controlled by 0x2220/0x2230
* on certain NV4x chipsets as well as RAMFC. When 0x2230 == 0
* ("new style" control) the upper 16-bits of 0x2220 points at this
* other mysterious table that's clobbering important things.
*
* We're now pointing this at RAMIN+0x30000 to avoid RAMFC getting
* smashed to pieces on us, so reserve 0x30000-0x40000 too..
*/
if (dev_priv->card_type >= NV_40) {
if (offset < 0x40000)
offset = 0x40000;
}
ret = drm_mm_init(&dev_priv->ramin_heap, offset,
dev_priv->ramin_rsvd_vram - offset);
if (ret) {
NV_ERROR(dev, "Failed to init RAMIN heap: %d\n", ret);
return ret;
}
return 0;
}
void
nv04_instmem_takedown(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
nouveau_ramht_ref(NULL, &dev_priv->ramht, NULL);
nouveau_gpuobj_ref(NULL, &dev_priv->ramro);
nouveau_gpuobj_ref(NULL, &dev_priv->ramfc);
if (drm_mm_initialized(&dev_priv->ramin_heap))
drm_mm_takedown(&dev_priv->ramin_heap);
}
int
nv04_instmem_suspend(struct drm_device *dev)
{
return 0;
}
void
nv04_instmem_resume(struct drm_device *dev)
{
}
int
nv04_instmem_get(struct nouveau_gpuobj *gpuobj, struct nouveau_channel *chan,
u32 size, u32 align)
{
struct drm_nouveau_private *dev_priv = gpuobj->dev->dev_private;
struct drm_mm_node *ramin = NULL;
do {
if (drm_mm_pre_get(&dev_priv->ramin_heap))
return -ENOMEM;
spin_lock(&dev_priv->ramin_lock);
ramin = drm_mm_search_free(&dev_priv->ramin_heap, size, align, 0);
if (ramin == NULL) {
spin_unlock(&dev_priv->ramin_lock);
return -ENOMEM;
}
ramin = drm_mm_get_block_atomic(ramin, size, align);
spin_unlock(&dev_priv->ramin_lock);
} while (ramin == NULL);
gpuobj->node = ramin;
gpuobj->vinst = ramin->start;
return 0;
}
void
nv04_instmem_put(struct nouveau_gpuobj *gpuobj)
{
struct drm_nouveau_private *dev_priv = gpuobj->dev->dev_private;
spin_lock(&dev_priv->ramin_lock);
drm_mm_put_block(gpuobj->node);
gpuobj->node = NULL;
spin_unlock(&dev_priv->ramin_lock);
}
int
nv04_instmem_map(struct nouveau_gpuobj *gpuobj)
{
gpuobj->pinst = gpuobj->vinst;
return 0;
}
void
nv04_instmem_unmap(struct nouveau_gpuobj *gpuobj)
{
}
void
nv04_instmem_flush(struct drm_device *dev)
{
}
| gpl-2.0 |
jimsmith80/android_kernel_zte_warplte | drivers/staging/rtl8712/rtl871x_sta_mgt.c | 7453 | 9548 | /******************************************************************************
* rtl871x_sta_mgt.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_STA_MGT_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "recv_osdep.h"
#include "xmit_osdep.h"
#include "sta_info.h"
static void _init_stainfo(struct sta_info *psta)
{
memset((u8 *)psta, 0, sizeof(struct sta_info));
spin_lock_init(&psta->lock);
_init_listhead(&psta->list);
_init_listhead(&psta->hash_list);
_r8712_init_sta_xmit_priv(&psta->sta_xmitpriv);
_r8712_init_sta_recv_priv(&psta->sta_recvpriv);
_init_listhead(&psta->asoc_list);
_init_listhead(&psta->auth_list);
}
u32 _r8712_init_sta_priv(struct sta_priv *pstapriv)
{
struct sta_info *psta;
s32 i;
pstapriv->pallocated_stainfo_buf = _malloc(sizeof(struct sta_info) *
NUM_STA + 4);
if (pstapriv->pallocated_stainfo_buf == NULL)
return _FAIL;
pstapriv->pstainfo_buf = pstapriv->pallocated_stainfo_buf + 4 -
((addr_t)(pstapriv->pallocated_stainfo_buf) & 3);
_init_queue(&pstapriv->free_sta_queue);
spin_lock_init(&pstapriv->sta_hash_lock);
pstapriv->asoc_sta_count = 0;
_init_queue(&pstapriv->sleep_q);
_init_queue(&pstapriv->wakeup_q);
psta = (struct sta_info *)(pstapriv->pstainfo_buf);
for (i = 0; i < NUM_STA; i++) {
_init_stainfo(psta);
_init_listhead(&(pstapriv->sta_hash[i]));
list_insert_tail(&psta->list,
get_list_head(&pstapriv->free_sta_queue));
psta++;
}
_init_listhead(&pstapriv->asoc_list);
_init_listhead(&pstapriv->auth_list);
return _SUCCESS;
}
/* this function is used to free the memory of lock || sema for all stainfos */
static void mfree_all_stainfo(struct sta_priv *pstapriv)
{
unsigned long irqL;
struct list_head *plist, *phead;
struct sta_info *psta = NULL;
spin_lock_irqsave(&pstapriv->sta_hash_lock, irqL);
phead = get_list_head(&pstapriv->free_sta_queue);
plist = get_next(phead);
while ((end_of_queue_search(phead, plist)) == false) {
psta = LIST_CONTAINOR(plist, struct sta_info, list);
plist = get_next(plist);
}
spin_unlock_irqrestore(&pstapriv->sta_hash_lock, irqL);
}
static void mfree_sta_priv_lock(struct sta_priv *pstapriv)
{
mfree_all_stainfo(pstapriv); /* be done before free sta_hash_lock */
}
u32 _r8712_free_sta_priv(struct sta_priv *pstapriv)
{
if (pstapriv) {
mfree_sta_priv_lock(pstapriv);
kfree(pstapriv->pallocated_stainfo_buf);
}
return _SUCCESS;
}
struct sta_info *r8712_alloc_stainfo(struct sta_priv *pstapriv, u8 *hwaddr)
{
uint tmp_aid;
s32 index;
struct list_head *phash_list;
struct sta_info *psta;
struct __queue *pfree_sta_queue;
struct recv_reorder_ctrl *preorder_ctrl;
int i = 0;
u16 wRxSeqInitialValue = 0xffff;
unsigned long flags;
pfree_sta_queue = &pstapriv->free_sta_queue;
spin_lock_irqsave(&(pfree_sta_queue->lock), flags);
if (_queue_empty(pfree_sta_queue) == true)
psta = NULL;
else {
psta = LIST_CONTAINOR(get_next(&pfree_sta_queue->queue),
struct sta_info, list);
list_delete(&(psta->list));
tmp_aid = psta->aid;
_init_stainfo(psta);
memcpy(psta->hwaddr, hwaddr, ETH_ALEN);
index = wifi_mac_hash(hwaddr);
if (index >= NUM_STA) {
psta = NULL;
goto exit;
}
phash_list = &(pstapriv->sta_hash[index]);
list_insert_tail(&psta->hash_list, phash_list);
pstapriv->asoc_sta_count++ ;
/* For the SMC router, the sequence number of first packet of WPS handshake
* will be 0. In this case, this packet will be dropped by recv_decache function
* if we use the 0x00 as the default value for tid_rxseq variable. So, we
* initialize the tid_rxseq variable as the 0xffff.
*/
for (i = 0; i < 16; i++)
memcpy(&psta->sta_recvpriv.rxcache.tid_rxseq[i],
&wRxSeqInitialValue, 2);
/* for A-MPDU Rx reordering buffer control */
for (i = 0; i < 16 ; i++) {
preorder_ctrl = &psta->recvreorder_ctrl[i];
preorder_ctrl->padapter = pstapriv->padapter;
preorder_ctrl->indicate_seq = 0xffff;
preorder_ctrl->wend_b = 0xffff;
preorder_ctrl->wsize_b = 64;
_init_queue(&preorder_ctrl->pending_recvframe_queue);
r8712_init_recv_timer(preorder_ctrl);
}
}
exit:
spin_unlock_irqrestore(&(pfree_sta_queue->lock), flags);
return psta;
}
/* using pstapriv->sta_hash_lock to protect */
void r8712_free_stainfo(struct _adapter *padapter, struct sta_info *psta)
{
int i;
unsigned long irqL0;
struct __queue *pfree_sta_queue;
struct recv_reorder_ctrl *preorder_ctrl;
struct sta_xmit_priv *pstaxmitpriv;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
struct sta_priv *pstapriv = &padapter->stapriv;
if (psta == NULL)
return;
pfree_sta_queue = &pstapriv->free_sta_queue;
pstaxmitpriv = &psta->sta_xmitpriv;
spin_lock_irqsave(&(pxmitpriv->vo_pending.lock), irqL0);
r8712_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->vo_q.sta_pending);
list_delete(&(pstaxmitpriv->vo_q.tx_pending));
spin_unlock_irqrestore(&(pxmitpriv->vo_pending.lock), irqL0);
spin_lock_irqsave(&(pxmitpriv->vi_pending.lock), irqL0);
r8712_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->vi_q.sta_pending);
list_delete(&(pstaxmitpriv->vi_q.tx_pending));
spin_unlock_irqrestore(&(pxmitpriv->vi_pending.lock), irqL0);
spin_lock_irqsave(&(pxmitpriv->bk_pending.lock), irqL0);
r8712_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->bk_q.sta_pending);
list_delete(&(pstaxmitpriv->bk_q.tx_pending));
spin_unlock_irqrestore(&(pxmitpriv->bk_pending.lock), irqL0);
spin_lock_irqsave(&(pxmitpriv->be_pending.lock), irqL0);
r8712_free_xmitframe_queue(pxmitpriv, &pstaxmitpriv->be_q.sta_pending);
list_delete(&(pstaxmitpriv->be_q.tx_pending));
spin_unlock_irqrestore(&(pxmitpriv->be_pending.lock), irqL0);
list_delete(&psta->hash_list);
pstapriv->asoc_sta_count--;
/* re-init sta_info; 20061114 */
_r8712_init_sta_xmit_priv(&psta->sta_xmitpriv);
_r8712_init_sta_recv_priv(&psta->sta_recvpriv);
/* for A-MPDU Rx reordering buffer control,
* cancel reordering_ctrl_timer */
for (i = 0; i < 16; i++) {
preorder_ctrl = &psta->recvreorder_ctrl[i];
_cancel_timer_ex(&preorder_ctrl->reordering_ctrl_timer);
}
spin_lock(&(pfree_sta_queue->lock));
/* insert into free_sta_queue; 20061114 */
list_insert_tail(&psta->list, get_list_head(pfree_sta_queue));
spin_unlock(&(pfree_sta_queue->lock));
}
/* free all stainfo which in sta_hash[all] */
void r8712_free_all_stainfo(struct _adapter *padapter)
{
unsigned long irqL;
struct list_head *plist, *phead;
s32 index;
struct sta_info *psta = NULL;
struct sta_priv *pstapriv = &padapter->stapriv;
struct sta_info *pbcmc_stainfo = r8712_get_bcmc_stainfo(padapter);
if (pstapriv->asoc_sta_count == 1)
return;
spin_lock_irqsave(&pstapriv->sta_hash_lock, irqL);
for (index = 0; index < NUM_STA; index++) {
phead = &(pstapriv->sta_hash[index]);
plist = get_next(phead);
while ((end_of_queue_search(phead, plist)) == false) {
psta = LIST_CONTAINOR(plist,
struct sta_info, hash_list);
plist = get_next(plist);
if (pbcmc_stainfo != psta)
r8712_free_stainfo(padapter , psta);
}
}
spin_unlock_irqrestore(&pstapriv->sta_hash_lock, irqL);
}
/* any station allocated can be searched by hash list */
struct sta_info *r8712_get_stainfo(struct sta_priv *pstapriv, u8 *hwaddr)
{
unsigned long irqL;
struct list_head *plist, *phead;
struct sta_info *psta = NULL;
u32 index;
if (hwaddr == NULL)
return NULL;
index = wifi_mac_hash(hwaddr);
spin_lock_irqsave(&pstapriv->sta_hash_lock, irqL);
phead = &(pstapriv->sta_hash[index]);
plist = get_next(phead);
while ((end_of_queue_search(phead, plist)) == false) {
psta = LIST_CONTAINOR(plist, struct sta_info, hash_list);
if ((!memcmp(psta->hwaddr, hwaddr, ETH_ALEN))) {
/* if found the matched address */
break;
}
psta = NULL;
plist = get_next(plist);
}
spin_unlock_irqrestore(&pstapriv->sta_hash_lock, irqL);
return psta;
}
void r8712_init_bcmc_stainfo(struct _adapter *padapter)
{
struct sta_info *psta;
struct tx_servq *ptxservq;
unsigned char bcast_addr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
struct sta_priv *pstapriv = &padapter->stapriv;
psta = r8712_alloc_stainfo(pstapriv, bcast_addr);
if (psta == NULL)
return;
ptxservq = &(psta->sta_xmitpriv.be_q);
}
struct sta_info *r8712_get_bcmc_stainfo(struct _adapter *padapter)
{
struct sta_info *psta;
struct sta_priv *pstapriv = &padapter->stapriv;
u8 bc_addr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
psta = r8712_get_stainfo(pstapriv, bc_addr);
return psta;
}
u8 r8712_access_ctrl(struct wlan_acl_pool *pacl_list, u8 *mac_addr)
{
return true;
}
| gpl-2.0 |
dimavs/android_kernel_huawei_g510 | arch/mips/loongson/common/gpio.c | 8733 | 2863 | /*
* STLS2F GPIO Support
*
* Copyright (c) 2008 Richard Liu, STMicroelectronics <richard.liu@st.com>
* Copyright (c) 2008-2010 Arnaud Patard <apatard@mandriva.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/err.h>
#include <asm/types.h>
#include <loongson.h>
#include <linux/gpio.h>
#define STLS2F_N_GPIO 4
#define STLS2F_GPIO_IN_OFFSET 16
static DEFINE_SPINLOCK(gpio_lock);
int gpio_get_value(unsigned gpio)
{
u32 val;
u32 mask;
if (gpio >= STLS2F_N_GPIO)
return __gpio_get_value(gpio);
mask = 1 << (gpio + STLS2F_GPIO_IN_OFFSET);
spin_lock(&gpio_lock);
val = LOONGSON_GPIODATA;
spin_unlock(&gpio_lock);
return ((val & mask) != 0);
}
EXPORT_SYMBOL(gpio_get_value);
void gpio_set_value(unsigned gpio, int state)
{
u32 val;
u32 mask;
if (gpio >= STLS2F_N_GPIO) {
__gpio_set_value(gpio, state);
return ;
}
mask = 1 << gpio;
spin_lock(&gpio_lock);
val = LOONGSON_GPIODATA;
if (state)
val |= mask;
else
val &= (~mask);
LOONGSON_GPIODATA = val;
spin_unlock(&gpio_lock);
}
EXPORT_SYMBOL(gpio_set_value);
int gpio_cansleep(unsigned gpio)
{
if (gpio < STLS2F_N_GPIO)
return 0;
else
return __gpio_cansleep(gpio);
}
EXPORT_SYMBOL(gpio_cansleep);
static int ls2f_gpio_direction_input(struct gpio_chip *chip, unsigned gpio)
{
u32 temp;
u32 mask;
if (gpio >= STLS2F_N_GPIO)
return -EINVAL;
spin_lock(&gpio_lock);
mask = 1 << gpio;
temp = LOONGSON_GPIOIE;
temp |= mask;
LOONGSON_GPIOIE = temp;
spin_unlock(&gpio_lock);
return 0;
}
static int ls2f_gpio_direction_output(struct gpio_chip *chip,
unsigned gpio, int level)
{
u32 temp;
u32 mask;
if (gpio >= STLS2F_N_GPIO)
return -EINVAL;
gpio_set_value(gpio, level);
spin_lock(&gpio_lock);
mask = 1 << gpio;
temp = LOONGSON_GPIOIE;
temp &= (~mask);
LOONGSON_GPIOIE = temp;
spin_unlock(&gpio_lock);
return 0;
}
static int ls2f_gpio_get_value(struct gpio_chip *chip, unsigned gpio)
{
return gpio_get_value(gpio);
}
static void ls2f_gpio_set_value(struct gpio_chip *chip,
unsigned gpio, int value)
{
gpio_set_value(gpio, value);
}
static struct gpio_chip ls2f_chip = {
.label = "ls2f",
.direction_input = ls2f_gpio_direction_input,
.get = ls2f_gpio_get_value,
.direction_output = ls2f_gpio_direction_output,
.set = ls2f_gpio_set_value,
.base = 0,
.ngpio = STLS2F_N_GPIO,
};
static int __init ls2f_gpio_setup(void)
{
return gpiochip_add(&ls2f_chip);
}
arch_initcall(ls2f_gpio_setup);
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_klte | drivers/sbus/char/bbc_envctrl.c | 9501 | 16169 | /* bbc_envctrl.c: UltraSPARC-III environment control driver.
*
* Copyright (C) 2001, 2008 David S. Miller (davem@davemloft.net)
*/
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/kmod.h>
#include <linux/reboot.h>
#include <linux/of.h>
#include <linux/slab.h>
#include <linux/of_device.h>
#include <asm/oplib.h>
#include "bbc_i2c.h"
#include "max1617.h"
#undef ENVCTRL_TRACE
/* WARNING: Making changes to this driver is very dangerous.
* If you misprogram the sensor chips they can
* cut the power on you instantly.
*/
/* Two temperature sensors exist in the SunBLADE-1000 enclosure.
* Both are implemented using max1617 i2c devices. Each max1617
* monitors 2 temperatures, one for one of the cpu dies and the other
* for the ambient temperature.
*
* The max1617 is capable of being programmed with power-off
* temperature values, one low limit and one high limit. These
* can be controlled independently for the cpu or ambient temperature.
* If a limit is violated, the power is simply shut off. The frequency
* with which the max1617 does temperature sampling can be controlled
* as well.
*
* Three fans exist inside the machine, all three are controlled with
* an i2c digital to analog converter. There is a fan directed at the
* two processor slots, another for the rest of the enclosure, and the
* third is for the power supply. The first two fans may be speed
* controlled by changing the voltage fed to them. The third fan may
* only be completely off or on. The third fan is meant to only be
* disabled/enabled when entering/exiting the lowest power-saving
* mode of the machine.
*
* An environmental control kernel thread periodically monitors all
* temperature sensors. Based upon the samples it will adjust the
* fan speeds to try and keep the system within a certain temperature
* range (the goal being to make the fans as quiet as possible without
* allowing the system to get too hot).
*
* If the temperature begins to rise/fall outside of the acceptable
* operating range, a periodic warning will be sent to the kernel log.
* The fans will be put on full blast to attempt to deal with this
* situation. After exceeding the acceptable operating range by a
* certain threshold, the kernel thread will shut down the system.
* Here, the thread is attempting to shut the machine down cleanly
* before the hardware based power-off event is triggered.
*/
/* These settings are in Celsius. We use these defaults only
* if we cannot interrogate the cpu-fru SEEPROM.
*/
struct temp_limits {
s8 high_pwroff, high_shutdown, high_warn;
s8 low_warn, low_shutdown, low_pwroff;
};
static struct temp_limits cpu_temp_limits[2] = {
{ 100, 85, 80, 5, -5, -10 },
{ 100, 85, 80, 5, -5, -10 },
};
static struct temp_limits amb_temp_limits[2] = {
{ 65, 55, 40, 5, -5, -10 },
{ 65, 55, 40, 5, -5, -10 },
};
static LIST_HEAD(all_temps);
static LIST_HEAD(all_fans);
#define CPU_FAN_REG 0xf0
#define SYS_FAN_REG 0xf2
#define PSUPPLY_FAN_REG 0xf4
#define FAN_SPEED_MIN 0x0c
#define FAN_SPEED_MAX 0x3f
#define PSUPPLY_FAN_ON 0x1f
#define PSUPPLY_FAN_OFF 0x00
static void set_fan_speeds(struct bbc_fan_control *fp)
{
/* Put temperatures into range so we don't mis-program
* the hardware.
*/
if (fp->cpu_fan_speed < FAN_SPEED_MIN)
fp->cpu_fan_speed = FAN_SPEED_MIN;
if (fp->cpu_fan_speed > FAN_SPEED_MAX)
fp->cpu_fan_speed = FAN_SPEED_MAX;
if (fp->system_fan_speed < FAN_SPEED_MIN)
fp->system_fan_speed = FAN_SPEED_MIN;
if (fp->system_fan_speed > FAN_SPEED_MAX)
fp->system_fan_speed = FAN_SPEED_MAX;
#ifdef ENVCTRL_TRACE
printk("fan%d: Changed fan speed to cpu(%02x) sys(%02x)\n",
fp->index,
fp->cpu_fan_speed, fp->system_fan_speed);
#endif
bbc_i2c_writeb(fp->client, fp->cpu_fan_speed, CPU_FAN_REG);
bbc_i2c_writeb(fp->client, fp->system_fan_speed, SYS_FAN_REG);
bbc_i2c_writeb(fp->client,
(fp->psupply_fan_on ?
PSUPPLY_FAN_ON : PSUPPLY_FAN_OFF),
PSUPPLY_FAN_REG);
}
static void get_current_temps(struct bbc_cpu_temperature *tp)
{
tp->prev_amb_temp = tp->curr_amb_temp;
bbc_i2c_readb(tp->client,
(unsigned char *) &tp->curr_amb_temp,
MAX1617_AMB_TEMP);
tp->prev_cpu_temp = tp->curr_cpu_temp;
bbc_i2c_readb(tp->client,
(unsigned char *) &tp->curr_cpu_temp,
MAX1617_CPU_TEMP);
#ifdef ENVCTRL_TRACE
printk("temp%d: cpu(%d C) amb(%d C)\n",
tp->index,
(int) tp->curr_cpu_temp, (int) tp->curr_amb_temp);
#endif
}
static void do_envctrl_shutdown(struct bbc_cpu_temperature *tp)
{
static int shutting_down = 0;
char *type = "???";
s8 val = -1;
if (shutting_down != 0)
return;
if (tp->curr_amb_temp >= amb_temp_limits[tp->index].high_shutdown ||
tp->curr_amb_temp < amb_temp_limits[tp->index].low_shutdown) {
type = "ambient";
val = tp->curr_amb_temp;
} else if (tp->curr_cpu_temp >= cpu_temp_limits[tp->index].high_shutdown ||
tp->curr_cpu_temp < cpu_temp_limits[tp->index].low_shutdown) {
type = "CPU";
val = tp->curr_cpu_temp;
}
printk(KERN_CRIT "temp%d: Outside of safe %s "
"operating temperature, %d C.\n",
tp->index, type, val);
printk(KERN_CRIT "kenvctrld: Shutting down the system now.\n");
shutting_down = 1;
if (orderly_poweroff(true) < 0)
printk(KERN_CRIT "envctrl: shutdown execution failed\n");
}
#define WARN_INTERVAL (30 * HZ)
static void analyze_ambient_temp(struct bbc_cpu_temperature *tp, unsigned long *last_warn, int tick)
{
int ret = 0;
if (time_after(jiffies, (*last_warn + WARN_INTERVAL))) {
if (tp->curr_amb_temp >=
amb_temp_limits[tp->index].high_warn) {
printk(KERN_WARNING "temp%d: "
"Above safe ambient operating temperature, %d C.\n",
tp->index, (int) tp->curr_amb_temp);
ret = 1;
} else if (tp->curr_amb_temp <
amb_temp_limits[tp->index].low_warn) {
printk(KERN_WARNING "temp%d: "
"Below safe ambient operating temperature, %d C.\n",
tp->index, (int) tp->curr_amb_temp);
ret = 1;
}
if (ret)
*last_warn = jiffies;
} else if (tp->curr_amb_temp >= amb_temp_limits[tp->index].high_warn ||
tp->curr_amb_temp < amb_temp_limits[tp->index].low_warn)
ret = 1;
/* Now check the shutdown limits. */
if (tp->curr_amb_temp >= amb_temp_limits[tp->index].high_shutdown ||
tp->curr_amb_temp < amb_temp_limits[tp->index].low_shutdown) {
do_envctrl_shutdown(tp);
ret = 1;
}
if (ret) {
tp->fan_todo[FAN_AMBIENT] = FAN_FULLBLAST;
} else if ((tick & (8 - 1)) == 0) {
s8 amb_goal_hi = amb_temp_limits[tp->index].high_warn - 10;
s8 amb_goal_lo;
amb_goal_lo = amb_goal_hi - 3;
/* We do not try to avoid 'too cold' events. Basically we
* only try to deal with over-heating and fan noise reduction.
*/
if (tp->avg_amb_temp < amb_goal_hi) {
if (tp->avg_amb_temp >= amb_goal_lo)
tp->fan_todo[FAN_AMBIENT] = FAN_SAME;
else
tp->fan_todo[FAN_AMBIENT] = FAN_SLOWER;
} else {
tp->fan_todo[FAN_AMBIENT] = FAN_FASTER;
}
} else {
tp->fan_todo[FAN_AMBIENT] = FAN_SAME;
}
}
static void analyze_cpu_temp(struct bbc_cpu_temperature *tp, unsigned long *last_warn, int tick)
{
int ret = 0;
if (time_after(jiffies, (*last_warn + WARN_INTERVAL))) {
if (tp->curr_cpu_temp >=
cpu_temp_limits[tp->index].high_warn) {
printk(KERN_WARNING "temp%d: "
"Above safe CPU operating temperature, %d C.\n",
tp->index, (int) tp->curr_cpu_temp);
ret = 1;
} else if (tp->curr_cpu_temp <
cpu_temp_limits[tp->index].low_warn) {
printk(KERN_WARNING "temp%d: "
"Below safe CPU operating temperature, %d C.\n",
tp->index, (int) tp->curr_cpu_temp);
ret = 1;
}
if (ret)
*last_warn = jiffies;
} else if (tp->curr_cpu_temp >= cpu_temp_limits[tp->index].high_warn ||
tp->curr_cpu_temp < cpu_temp_limits[tp->index].low_warn)
ret = 1;
/* Now check the shutdown limits. */
if (tp->curr_cpu_temp >= cpu_temp_limits[tp->index].high_shutdown ||
tp->curr_cpu_temp < cpu_temp_limits[tp->index].low_shutdown) {
do_envctrl_shutdown(tp);
ret = 1;
}
if (ret) {
tp->fan_todo[FAN_CPU] = FAN_FULLBLAST;
} else if ((tick & (8 - 1)) == 0) {
s8 cpu_goal_hi = cpu_temp_limits[tp->index].high_warn - 10;
s8 cpu_goal_lo;
cpu_goal_lo = cpu_goal_hi - 3;
/* We do not try to avoid 'too cold' events. Basically we
* only try to deal with over-heating and fan noise reduction.
*/
if (tp->avg_cpu_temp < cpu_goal_hi) {
if (tp->avg_cpu_temp >= cpu_goal_lo)
tp->fan_todo[FAN_CPU] = FAN_SAME;
else
tp->fan_todo[FAN_CPU] = FAN_SLOWER;
} else {
tp->fan_todo[FAN_CPU] = FAN_FASTER;
}
} else {
tp->fan_todo[FAN_CPU] = FAN_SAME;
}
}
static void analyze_temps(struct bbc_cpu_temperature *tp, unsigned long *last_warn)
{
tp->avg_amb_temp = (s8)((int)((int)tp->avg_amb_temp + (int)tp->curr_amb_temp) / 2);
tp->avg_cpu_temp = (s8)((int)((int)tp->avg_cpu_temp + (int)tp->curr_cpu_temp) / 2);
analyze_ambient_temp(tp, last_warn, tp->sample_tick);
analyze_cpu_temp(tp, last_warn, tp->sample_tick);
tp->sample_tick++;
}
static enum fan_action prioritize_fan_action(int which_fan)
{
struct bbc_cpu_temperature *tp;
enum fan_action decision = FAN_STATE_MAX;
/* Basically, prioritize what the temperature sensors
* recommend we do, and perform that action on all the
* fans.
*/
list_for_each_entry(tp, &all_temps, glob_list) {
if (tp->fan_todo[which_fan] == FAN_FULLBLAST) {
decision = FAN_FULLBLAST;
break;
}
if (tp->fan_todo[which_fan] == FAN_SAME &&
decision != FAN_FASTER)
decision = FAN_SAME;
else if (tp->fan_todo[which_fan] == FAN_FASTER)
decision = FAN_FASTER;
else if (decision != FAN_FASTER &&
decision != FAN_SAME &&
tp->fan_todo[which_fan] == FAN_SLOWER)
decision = FAN_SLOWER;
}
if (decision == FAN_STATE_MAX)
decision = FAN_SAME;
return decision;
}
static int maybe_new_ambient_fan_speed(struct bbc_fan_control *fp)
{
enum fan_action decision = prioritize_fan_action(FAN_AMBIENT);
int ret;
if (decision == FAN_SAME)
return 0;
ret = 1;
if (decision == FAN_FULLBLAST) {
if (fp->system_fan_speed >= FAN_SPEED_MAX)
ret = 0;
else
fp->system_fan_speed = FAN_SPEED_MAX;
} else {
if (decision == FAN_FASTER) {
if (fp->system_fan_speed >= FAN_SPEED_MAX)
ret = 0;
else
fp->system_fan_speed += 2;
} else {
int orig_speed = fp->system_fan_speed;
if (orig_speed <= FAN_SPEED_MIN ||
orig_speed <= (fp->cpu_fan_speed - 3))
ret = 0;
else
fp->system_fan_speed -= 1;
}
}
return ret;
}
static int maybe_new_cpu_fan_speed(struct bbc_fan_control *fp)
{
enum fan_action decision = prioritize_fan_action(FAN_CPU);
int ret;
if (decision == FAN_SAME)
return 0;
ret = 1;
if (decision == FAN_FULLBLAST) {
if (fp->cpu_fan_speed >= FAN_SPEED_MAX)
ret = 0;
else
fp->cpu_fan_speed = FAN_SPEED_MAX;
} else {
if (decision == FAN_FASTER) {
if (fp->cpu_fan_speed >= FAN_SPEED_MAX)
ret = 0;
else {
fp->cpu_fan_speed += 2;
if (fp->system_fan_speed <
(fp->cpu_fan_speed - 3))
fp->system_fan_speed =
fp->cpu_fan_speed - 3;
}
} else {
if (fp->cpu_fan_speed <= FAN_SPEED_MIN)
ret = 0;
else
fp->cpu_fan_speed -= 1;
}
}
return ret;
}
static void maybe_new_fan_speeds(struct bbc_fan_control *fp)
{
int new;
new = maybe_new_ambient_fan_speed(fp);
new |= maybe_new_cpu_fan_speed(fp);
if (new)
set_fan_speeds(fp);
}
static void fans_full_blast(void)
{
struct bbc_fan_control *fp;
/* Since we will not be monitoring things anymore, put
* the fans on full blast.
*/
list_for_each_entry(fp, &all_fans, glob_list) {
fp->cpu_fan_speed = FAN_SPEED_MAX;
fp->system_fan_speed = FAN_SPEED_MAX;
fp->psupply_fan_on = 1;
set_fan_speeds(fp);
}
}
#define POLL_INTERVAL (5 * 1000)
static unsigned long last_warning_jiffies;
static struct task_struct *kenvctrld_task;
static int kenvctrld(void *__unused)
{
printk(KERN_INFO "bbc_envctrl: kenvctrld starting...\n");
last_warning_jiffies = jiffies - WARN_INTERVAL;
for (;;) {
struct bbc_cpu_temperature *tp;
struct bbc_fan_control *fp;
msleep_interruptible(POLL_INTERVAL);
if (kthread_should_stop())
break;
list_for_each_entry(tp, &all_temps, glob_list) {
get_current_temps(tp);
analyze_temps(tp, &last_warning_jiffies);
}
list_for_each_entry(fp, &all_fans, glob_list)
maybe_new_fan_speeds(fp);
}
printk(KERN_INFO "bbc_envctrl: kenvctrld exiting...\n");
fans_full_blast();
return 0;
}
static void attach_one_temp(struct bbc_i2c_bus *bp, struct platform_device *op,
int temp_idx)
{
struct bbc_cpu_temperature *tp;
tp = kzalloc(sizeof(*tp), GFP_KERNEL);
if (!tp)
return;
tp->client = bbc_i2c_attach(bp, op);
if (!tp->client) {
kfree(tp);
return;
}
tp->index = temp_idx;
list_add(&tp->glob_list, &all_temps);
list_add(&tp->bp_list, &bp->temps);
/* Tell it to convert once every 5 seconds, clear all cfg
* bits.
*/
bbc_i2c_writeb(tp->client, 0x00, MAX1617_WR_CFG_BYTE);
bbc_i2c_writeb(tp->client, 0x02, MAX1617_WR_CVRATE_BYTE);
/* Program the hard temperature limits into the chip. */
bbc_i2c_writeb(tp->client, amb_temp_limits[tp->index].high_pwroff,
MAX1617_WR_AMB_HIGHLIM);
bbc_i2c_writeb(tp->client, amb_temp_limits[tp->index].low_pwroff,
MAX1617_WR_AMB_LOWLIM);
bbc_i2c_writeb(tp->client, cpu_temp_limits[tp->index].high_pwroff,
MAX1617_WR_CPU_HIGHLIM);
bbc_i2c_writeb(tp->client, cpu_temp_limits[tp->index].low_pwroff,
MAX1617_WR_CPU_LOWLIM);
get_current_temps(tp);
tp->prev_cpu_temp = tp->avg_cpu_temp = tp->curr_cpu_temp;
tp->prev_amb_temp = tp->avg_amb_temp = tp->curr_amb_temp;
tp->fan_todo[FAN_AMBIENT] = FAN_SAME;
tp->fan_todo[FAN_CPU] = FAN_SAME;
}
static void attach_one_fan(struct bbc_i2c_bus *bp, struct platform_device *op,
int fan_idx)
{
struct bbc_fan_control *fp;
fp = kzalloc(sizeof(*fp), GFP_KERNEL);
if (!fp)
return;
fp->client = bbc_i2c_attach(bp, op);
if (!fp->client) {
kfree(fp);
return;
}
fp->index = fan_idx;
list_add(&fp->glob_list, &all_fans);
list_add(&fp->bp_list, &bp->fans);
/* The i2c device controlling the fans is write-only.
* So the only way to keep track of the current power
* level fed to the fans is via software. Choose half
* power for cpu/system and 'on' fo the powersupply fan
* and set it now.
*/
fp->psupply_fan_on = 1;
fp->cpu_fan_speed = (FAN_SPEED_MAX - FAN_SPEED_MIN) / 2;
fp->cpu_fan_speed += FAN_SPEED_MIN;
fp->system_fan_speed = (FAN_SPEED_MAX - FAN_SPEED_MIN) / 2;
fp->system_fan_speed += FAN_SPEED_MIN;
set_fan_speeds(fp);
}
static void destroy_one_temp(struct bbc_cpu_temperature *tp)
{
bbc_i2c_detach(tp->client);
kfree(tp);
}
static void destroy_all_temps(struct bbc_i2c_bus *bp)
{
struct bbc_cpu_temperature *tp, *tpos;
list_for_each_entry_safe(tp, tpos, &bp->temps, bp_list) {
list_del(&tp->bp_list);
list_del(&tp->glob_list);
destroy_one_temp(tp);
}
}
static void destroy_one_fan(struct bbc_fan_control *fp)
{
bbc_i2c_detach(fp->client);
kfree(fp);
}
static void destroy_all_fans(struct bbc_i2c_bus *bp)
{
struct bbc_fan_control *fp, *fpos;
list_for_each_entry_safe(fp, fpos, &bp->fans, bp_list) {
list_del(&fp->bp_list);
list_del(&fp->glob_list);
destroy_one_fan(fp);
}
}
int bbc_envctrl_init(struct bbc_i2c_bus *bp)
{
struct platform_device *op;
int temp_index = 0;
int fan_index = 0;
int devidx = 0;
while ((op = bbc_i2c_getdev(bp, devidx++)) != NULL) {
if (!strcmp(op->dev.of_node->name, "temperature"))
attach_one_temp(bp, op, temp_index++);
if (!strcmp(op->dev.of_node->name, "fan-control"))
attach_one_fan(bp, op, fan_index++);
}
if (temp_index != 0 && fan_index != 0) {
kenvctrld_task = kthread_run(kenvctrld, NULL, "kenvctrld");
if (IS_ERR(kenvctrld_task)) {
int err = PTR_ERR(kenvctrld_task);
kenvctrld_task = NULL;
destroy_all_temps(bp);
destroy_all_fans(bp);
return err;
}
}
return 0;
}
void bbc_envctrl_cleanup(struct bbc_i2c_bus *bp)
{
if (kenvctrld_task)
kthread_stop(kenvctrld_task);
destroy_all_temps(bp);
destroy_all_fans(bp);
}
| gpl-2.0 |
huz123/bricked.tenderloin | arch/avr32/boards/atstk1000/atstk1004.c | 13597 | 3756 | /*
* ATSTK1003 daughterboard-specific init code
*
* Copyright (C) 2007 Atmel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/spi/at73c213.h>
#include <linux/spi/spi.h>
#include <linux/atmel-mci.h>
#include <video/atmel_lcdc.h>
#include <asm/setup.h>
#include <mach/at32ap700x.h>
#include <mach/board.h>
#include <mach/init.h>
#include <mach/portmux.h>
#include "atstk1000.h"
/* Oscillator frequencies. These are board specific */
unsigned long at32_board_osc_rates[3] = {
[0] = 32768, /* 32.768 kHz on RTC osc */
[1] = 20000000, /* 20 MHz on osc0 */
[2] = 12000000, /* 12 MHz on osc1 */
};
#ifdef CONFIG_BOARD_ATSTK1000_EXTDAC
static struct at73c213_board_info at73c213_data = {
.ssc_id = 0,
.shortname = "AVR32 STK1000 external DAC",
};
#endif
#ifndef CONFIG_BOARD_ATSTK100X_SW1_CUSTOM
static struct spi_board_info spi0_board_info[] __initdata = {
#ifdef CONFIG_BOARD_ATSTK1000_EXTDAC
{
/* AT73C213 */
.modalias = "at73c213",
.max_speed_hz = 200000,
.chip_select = 0,
.mode = SPI_MODE_1,
.platform_data = &at73c213_data,
},
#endif
{
/* QVGA display */
.modalias = "ltv350qv",
.max_speed_hz = 16000000,
.chip_select = 1,
.mode = SPI_MODE_3,
},
};
#endif
#ifdef CONFIG_BOARD_ATSTK100X_SPI1
static struct spi_board_info spi1_board_info[] __initdata = { {
/* patch in custom entries here */
} };
#endif
#ifndef CONFIG_BOARD_ATSTK100X_SW2_CUSTOM
static struct mci_platform_data __initdata mci0_data = {
.slot[0] = {
.bus_width = 4,
.detect_pin = -ENODEV,
.wp_pin = -ENODEV,
},
};
#endif
#ifdef CONFIG_BOARD_ATSTK1000_EXTDAC
static void __init atstk1004_setup_extdac(void)
{
struct clk *gclk;
struct clk *pll;
gclk = clk_get(NULL, "gclk0");
if (IS_ERR(gclk))
goto err_gclk;
pll = clk_get(NULL, "pll0");
if (IS_ERR(pll))
goto err_pll;
if (clk_set_parent(gclk, pll)) {
pr_debug("STK1000: failed to set pll0 as parent for DAC clock\n");
goto err_set_clk;
}
at32_select_periph(GPIO_PIOA_BASE, (1 << 30), GPIO_PERIPH_A, 0);
at73c213_data.dac_clk = gclk;
err_set_clk:
clk_put(pll);
err_pll:
clk_put(gclk);
err_gclk:
return;
}
#else
static void __init atstk1004_setup_extdac(void)
{
}
#endif /* CONFIG_BOARD_ATSTK1000_EXTDAC */
void __init setup_board(void)
{
#ifdef CONFIG_BOARD_ATSTK100X_SW2_CUSTOM
at32_map_usart(0, 1, 0); /* USART 0/B: /dev/ttyS1, IRDA */
#else
at32_map_usart(1, 0, 0); /* USART 1/A: /dev/ttyS0, DB9 */
#endif
/* USART 2/unused: expansion connector */
at32_map_usart(3, 2, 0); /* USART 3/C: /dev/ttyS2, DB9 */
at32_setup_serial_console(0);
}
static int __init atstk1004_init(void)
{
#ifdef CONFIG_BOARD_ATSTK100X_SW2_CUSTOM
at32_add_device_usart(1);
#else
at32_add_device_usart(0);
#endif
at32_add_device_usart(2);
#ifndef CONFIG_BOARD_ATSTK100X_SW1_CUSTOM
at32_add_device_spi(0, spi0_board_info, ARRAY_SIZE(spi0_board_info));
#endif
#ifdef CONFIG_BOARD_ATSTK100X_SPI1
at32_add_device_spi(1, spi1_board_info, ARRAY_SIZE(spi1_board_info));
#endif
#ifndef CONFIG_BOARD_ATSTK100X_SW2_CUSTOM
at32_add_device_mci(0, &mci0_data);
#endif
at32_add_device_lcdc(0, &atstk1000_lcdc_data,
fbmem_start, fbmem_size,
ATMEL_LCDC_PRI_24BIT | ATMEL_LCDC_PRI_CONTROL);
at32_add_device_usba(0, NULL);
#ifndef CONFIG_BOARD_ATSTK100X_SW3_CUSTOM
at32_add_device_ssc(0, ATMEL_SSC_TX);
#endif
atstk1000_setup_j2_leds();
atstk1004_setup_extdac();
return 0;
}
postcore_initcall(atstk1004_init);
| gpl-2.0 |
mturquette/linux-omap-android | drivers/gpu/drm/i915/intel_crt.c | 30 | 15459 | /*
* Copyright © 2006-2007 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Eric Anholt <eric@anholt.net>
*/
#include <linux/i2c.h>
#include "drmP.h"
#include "drm.h"
#include "drm_crtc.h"
#include "drm_crtc_helper.h"
#include "intel_drv.h"
#include "i915_drm.h"
#include "i915_drv.h"
static void intel_crt_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
u32 temp, reg;
if (IS_IGDNG(dev))
reg = PCH_ADPA;
else
reg = ADPA;
temp = I915_READ(reg);
temp &= ~(ADPA_HSYNC_CNTL_DISABLE | ADPA_VSYNC_CNTL_DISABLE);
temp &= ~ADPA_DAC_ENABLE;
switch(mode) {
case DRM_MODE_DPMS_ON:
temp |= ADPA_DAC_ENABLE;
break;
case DRM_MODE_DPMS_STANDBY:
temp |= ADPA_DAC_ENABLE | ADPA_HSYNC_CNTL_DISABLE;
break;
case DRM_MODE_DPMS_SUSPEND:
temp |= ADPA_DAC_ENABLE | ADPA_VSYNC_CNTL_DISABLE;
break;
case DRM_MODE_DPMS_OFF:
temp |= ADPA_HSYNC_CNTL_DISABLE | ADPA_VSYNC_CNTL_DISABLE;
break;
}
I915_WRITE(reg, temp);
if (IS_IGD(dev)) {
if (mode == DRM_MODE_DPMS_OFF) {
/* turn off DAC */
temp = I915_READ(PORT_HOTPLUG_EN);
temp &= ~CRT_EOS_INT_EN;
I915_WRITE(PORT_HOTPLUG_EN, temp);
temp = I915_READ(PORT_HOTPLUG_STAT);
if (temp & CRT_EOS_INT_STATUS)
I915_WRITE(PORT_HOTPLUG_STAT,
CRT_EOS_INT_STATUS);
} else {
/* turn on DAC. EOS interrupt must be enabled after DAC
* is enabled, so it sounds not good to enable it in
* i915_driver_irq_postinstall()
* wait 12.5ms after DAC is enabled
*/
msleep(13);
temp = I915_READ(PORT_HOTPLUG_STAT);
if (temp & CRT_EOS_INT_STATUS)
I915_WRITE(PORT_HOTPLUG_STAT,
CRT_EOS_INT_STATUS);
temp = I915_READ(PORT_HOTPLUG_EN);
temp |= CRT_EOS_INT_EN;
I915_WRITE(PORT_HOTPLUG_EN, temp);
}
}
}
static int intel_crt_mode_valid(struct drm_connector *connector,
struct drm_display_mode *mode)
{
struct drm_device *dev = connector->dev;
int max_clock = 0;
if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
return MODE_NO_DBLESCAN;
if (mode->clock < 25000)
return MODE_CLOCK_LOW;
if (!IS_I9XX(dev))
max_clock = 350000;
else
max_clock = 400000;
if (mode->clock > max_clock)
return MODE_CLOCK_HIGH;
return MODE_OK;
}
static bool intel_crt_mode_fixup(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
return true;
}
static void intel_crt_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct drm_crtc *crtc = encoder->crtc;
struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
struct drm_i915_private *dev_priv = dev->dev_private;
int dpll_md_reg;
u32 adpa, dpll_md;
u32 adpa_reg;
if (intel_crtc->pipe == 0)
dpll_md_reg = DPLL_A_MD;
else
dpll_md_reg = DPLL_B_MD;
if (IS_IGDNG(dev))
adpa_reg = PCH_ADPA;
else
adpa_reg = ADPA;
/*
* Disable separate mode multiplier used when cloning SDVO to CRT
* XXX this needs to be adjusted when we really are cloning
*/
if (IS_I965G(dev) && !IS_IGDNG(dev)) {
dpll_md = I915_READ(dpll_md_reg);
I915_WRITE(dpll_md_reg,
dpll_md & ~DPLL_MD_UDI_MULTIPLIER_MASK);
}
adpa = 0;
if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
adpa |= ADPA_HSYNC_ACTIVE_HIGH;
if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
adpa |= ADPA_VSYNC_ACTIVE_HIGH;
if (intel_crtc->pipe == 0) {
adpa |= ADPA_PIPE_A_SELECT;
if (!IS_IGDNG(dev))
I915_WRITE(BCLRPAT_A, 0);
} else {
adpa |= ADPA_PIPE_B_SELECT;
if (!IS_IGDNG(dev))
I915_WRITE(BCLRPAT_B, 0);
}
I915_WRITE(adpa_reg, adpa);
}
static bool intel_igdng_crt_detect_hotplug(struct drm_connector *connector)
{
struct drm_device *dev = connector->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
u32 adpa;
bool ret;
adpa = I915_READ(PCH_ADPA);
adpa &= ~ADPA_CRT_HOTPLUG_MASK;
adpa |= (ADPA_CRT_HOTPLUG_PERIOD_128 |
ADPA_CRT_HOTPLUG_WARMUP_10MS |
ADPA_CRT_HOTPLUG_SAMPLE_4S |
ADPA_CRT_HOTPLUG_VOLTAGE_50 | /* default */
ADPA_CRT_HOTPLUG_VOLREF_325MV |
ADPA_CRT_HOTPLUG_ENABLE |
ADPA_CRT_HOTPLUG_FORCE_TRIGGER);
DRM_DEBUG("pch crt adpa 0x%x", adpa);
I915_WRITE(PCH_ADPA, adpa);
while ((I915_READ(PCH_ADPA) & ADPA_CRT_HOTPLUG_FORCE_TRIGGER) != 0)
;
/* Check the status to see if both blue and green are on now */
adpa = I915_READ(PCH_ADPA);
adpa &= ADPA_CRT_HOTPLUG_MONITOR_MASK;
if ((adpa == ADPA_CRT_HOTPLUG_MONITOR_COLOR) ||
(adpa == ADPA_CRT_HOTPLUG_MONITOR_MONO))
ret = true;
else
ret = false;
return ret;
}
/**
* Uses CRT_HOTPLUG_EN and CRT_HOTPLUG_STAT to detect CRT presence.
*
* Not for i915G/i915GM
*
* \return true if CRT is connected.
* \return false if CRT is disconnected.
*/
static bool intel_crt_detect_hotplug(struct drm_connector *connector)
{
struct drm_device *dev = connector->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
u32 hotplug_en;
int i, tries = 0;
if (IS_IGDNG(dev))
return intel_igdng_crt_detect_hotplug(connector);
/*
* On 4 series desktop, CRT detect sequence need to be done twice
* to get a reliable result.
*/
if (IS_G4X(dev) && !IS_GM45(dev))
tries = 2;
else
tries = 1;
hotplug_en = I915_READ(PORT_HOTPLUG_EN);
hotplug_en &= CRT_FORCE_HOTPLUG_MASK;
hotplug_en |= CRT_HOTPLUG_FORCE_DETECT;
if (IS_G4X(dev))
hotplug_en |= CRT_HOTPLUG_ACTIVATION_PERIOD_64;
hotplug_en |= CRT_HOTPLUG_VOLTAGE_COMPARE_50;
for (i = 0; i < tries ; i++) {
unsigned long timeout;
/* turn on the FORCE_DETECT */
I915_WRITE(PORT_HOTPLUG_EN, hotplug_en);
timeout = jiffies + msecs_to_jiffies(1000);
/* wait for FORCE_DETECT to go off */
do {
if (!(I915_READ(PORT_HOTPLUG_EN) &
CRT_HOTPLUG_FORCE_DETECT))
break;
msleep(1);
} while (time_after(timeout, jiffies));
}
if ((I915_READ(PORT_HOTPLUG_STAT) & CRT_HOTPLUG_MONITOR_MASK) !=
CRT_HOTPLUG_MONITOR_NONE)
return true;
return false;
}
static bool intel_crt_detect_ddc(struct drm_connector *connector)
{
struct intel_output *intel_output = to_intel_output(connector);
/* CRT should always be at 0, but check anyway */
if (intel_output->type != INTEL_OUTPUT_ANALOG)
return false;
return intel_ddc_probe(intel_output);
}
static enum drm_connector_status
intel_crt_load_detect(struct drm_crtc *crtc, struct intel_output *intel_output)
{
struct drm_encoder *encoder = &intel_output->enc;
struct drm_device *dev = encoder->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
uint32_t pipe = intel_crtc->pipe;
uint32_t save_bclrpat;
uint32_t save_vtotal;
uint32_t vtotal, vactive;
uint32_t vsample;
uint32_t vblank, vblank_start, vblank_end;
uint32_t dsl;
uint32_t bclrpat_reg;
uint32_t vtotal_reg;
uint32_t vblank_reg;
uint32_t vsync_reg;
uint32_t pipeconf_reg;
uint32_t pipe_dsl_reg;
uint8_t st00;
enum drm_connector_status status;
if (pipe == 0) {
bclrpat_reg = BCLRPAT_A;
vtotal_reg = VTOTAL_A;
vblank_reg = VBLANK_A;
vsync_reg = VSYNC_A;
pipeconf_reg = PIPEACONF;
pipe_dsl_reg = PIPEADSL;
} else {
bclrpat_reg = BCLRPAT_B;
vtotal_reg = VTOTAL_B;
vblank_reg = VBLANK_B;
vsync_reg = VSYNC_B;
pipeconf_reg = PIPEBCONF;
pipe_dsl_reg = PIPEBDSL;
}
save_bclrpat = I915_READ(bclrpat_reg);
save_vtotal = I915_READ(vtotal_reg);
vblank = I915_READ(vblank_reg);
vtotal = ((save_vtotal >> 16) & 0xfff) + 1;
vactive = (save_vtotal & 0x7ff) + 1;
vblank_start = (vblank & 0xfff) + 1;
vblank_end = ((vblank >> 16) & 0xfff) + 1;
/* Set the border color to purple. */
I915_WRITE(bclrpat_reg, 0x500050);
if (IS_I9XX(dev)) {
uint32_t pipeconf = I915_READ(pipeconf_reg);
I915_WRITE(pipeconf_reg, pipeconf | PIPECONF_FORCE_BORDER);
/* Wait for next Vblank to substitue
* border color for Color info */
intel_wait_for_vblank(dev);
st00 = I915_READ8(VGA_MSR_WRITE);
status = ((st00 & (1 << 4)) != 0) ?
connector_status_connected :
connector_status_disconnected;
I915_WRITE(pipeconf_reg, pipeconf);
} else {
bool restore_vblank = false;
int count, detect;
/*
* If there isn't any border, add some.
* Yes, this will flicker
*/
if (vblank_start <= vactive && vblank_end >= vtotal) {
uint32_t vsync = I915_READ(vsync_reg);
uint32_t vsync_start = (vsync & 0xffff) + 1;
vblank_start = vsync_start;
I915_WRITE(vblank_reg,
(vblank_start - 1) |
((vblank_end - 1) << 16));
restore_vblank = true;
}
/* sample in the vertical border, selecting the larger one */
if (vblank_start - vactive >= vtotal - vblank_end)
vsample = (vblank_start + vactive) >> 1;
else
vsample = (vtotal + vblank_end) >> 1;
/*
* Wait for the border to be displayed
*/
while (I915_READ(pipe_dsl_reg) >= vactive)
;
while ((dsl = I915_READ(pipe_dsl_reg)) <= vsample)
;
/*
* Watch ST00 for an entire scanline
*/
detect = 0;
count = 0;
do {
count++;
/* Read the ST00 VGA status register */
st00 = I915_READ8(VGA_MSR_WRITE);
if (st00 & (1 << 4))
detect++;
} while ((I915_READ(pipe_dsl_reg) == dsl));
/* restore vblank if necessary */
if (restore_vblank)
I915_WRITE(vblank_reg, vblank);
/*
* If more than 3/4 of the scanline detected a monitor,
* then it is assumed to be present. This works even on i830,
* where there isn't any way to force the border color across
* the screen
*/
status = detect * 4 > count * 3 ?
connector_status_connected :
connector_status_disconnected;
}
/* Restore previous settings */
I915_WRITE(bclrpat_reg, save_bclrpat);
return status;
}
static enum drm_connector_status intel_crt_detect(struct drm_connector *connector)
{
struct drm_device *dev = connector->dev;
struct intel_output *intel_output = to_intel_output(connector);
struct drm_encoder *encoder = &intel_output->enc;
struct drm_crtc *crtc;
int dpms_mode;
enum drm_connector_status status;
if (IS_I9XX(dev) && !IS_I915G(dev) && !IS_I915GM(dev)) {
if (intel_crt_detect_hotplug(connector))
return connector_status_connected;
else
return connector_status_disconnected;
}
if (intel_crt_detect_ddc(connector))
return connector_status_connected;
/* for pre-945g platforms use load detect */
if (encoder->crtc && encoder->crtc->enabled) {
status = intel_crt_load_detect(encoder->crtc, intel_output);
} else {
crtc = intel_get_load_detect_pipe(intel_output,
NULL, &dpms_mode);
if (crtc) {
status = intel_crt_load_detect(crtc, intel_output);
intel_release_load_detect_pipe(intel_output, dpms_mode);
} else
status = connector_status_unknown;
}
return status;
}
static void intel_crt_destroy(struct drm_connector *connector)
{
struct intel_output *intel_output = to_intel_output(connector);
intel_i2c_destroy(intel_output->ddc_bus);
drm_sysfs_connector_remove(connector);
drm_connector_cleanup(connector);
kfree(connector);
}
static int intel_crt_get_modes(struct drm_connector *connector)
{
int ret;
struct intel_output *intel_output = to_intel_output(connector);
struct i2c_adapter *ddcbus;
struct drm_device *dev = connector->dev;
ret = intel_ddc_get_modes(intel_output);
if (ret || !IS_G4X(dev))
goto end;
ddcbus = intel_output->ddc_bus;
/* Try to probe digital port for output in DVI-I -> VGA mode. */
intel_output->ddc_bus =
intel_i2c_create(connector->dev, GPIOD, "CRTDDC_D");
if (!intel_output->ddc_bus) {
intel_output->ddc_bus = ddcbus;
dev_printk(KERN_ERR, &connector->dev->pdev->dev,
"DDC bus registration failed for CRTDDC_D.\n");
goto end;
}
/* Try to get modes by GPIOD port */
ret = intel_ddc_get_modes(intel_output);
intel_i2c_destroy(ddcbus);
end:
return ret;
}
static int intel_crt_set_property(struct drm_connector *connector,
struct drm_property *property,
uint64_t value)
{
return 0;
}
/*
* Routines for controlling stuff on the analog port
*/
static const struct drm_encoder_helper_funcs intel_crt_helper_funcs = {
.dpms = intel_crt_dpms,
.mode_fixup = intel_crt_mode_fixup,
.prepare = intel_encoder_prepare,
.commit = intel_encoder_commit,
.mode_set = intel_crt_mode_set,
};
static const struct drm_connector_funcs intel_crt_connector_funcs = {
.dpms = drm_helper_connector_dpms,
.detect = intel_crt_detect,
.fill_modes = drm_helper_probe_single_connector_modes,
.destroy = intel_crt_destroy,
.set_property = intel_crt_set_property,
};
static const struct drm_connector_helper_funcs intel_crt_connector_helper_funcs = {
.mode_valid = intel_crt_mode_valid,
.get_modes = intel_crt_get_modes,
.best_encoder = intel_best_encoder,
};
static void intel_crt_enc_destroy(struct drm_encoder *encoder)
{
drm_encoder_cleanup(encoder);
}
static const struct drm_encoder_funcs intel_crt_enc_funcs = {
.destroy = intel_crt_enc_destroy,
};
void intel_crt_init(struct drm_device *dev)
{
struct drm_connector *connector;
struct intel_output *intel_output;
struct drm_i915_private *dev_priv = dev->dev_private;
u32 i2c_reg;
intel_output = kzalloc(sizeof(struct intel_output), GFP_KERNEL);
if (!intel_output)
return;
connector = &intel_output->base;
drm_connector_init(dev, &intel_output->base,
&intel_crt_connector_funcs, DRM_MODE_CONNECTOR_VGA);
drm_encoder_init(dev, &intel_output->enc, &intel_crt_enc_funcs,
DRM_MODE_ENCODER_DAC);
drm_mode_connector_attach_encoder(&intel_output->base,
&intel_output->enc);
/* Set up the DDC bus. */
if (IS_IGDNG(dev))
i2c_reg = PCH_GPIOA;
else {
i2c_reg = GPIOA;
/* Use VBT information for CRT DDC if available */
if (dev_priv->crt_ddc_bus != -1)
i2c_reg = dev_priv->crt_ddc_bus;
}
intel_output->ddc_bus = intel_i2c_create(dev, i2c_reg, "CRTDDC_A");
if (!intel_output->ddc_bus) {
dev_printk(KERN_ERR, &dev->pdev->dev, "DDC bus registration "
"failed.\n");
return;
}
intel_output->type = INTEL_OUTPUT_ANALOG;
intel_output->clone_mask = (1 << INTEL_SDVO_NON_TV_CLONE_BIT) |
(1 << INTEL_ANALOG_CLONE_BIT) |
(1 << INTEL_SDVO_LVDS_CLONE_BIT);
intel_output->crtc_mask = (1 << 0) | (1 << 1);
connector->interlace_allowed = 0;
connector->doublescan_allowed = 0;
drm_encoder_helper_add(&intel_output->enc, &intel_crt_helper_funcs);
drm_connector_helper_add(connector, &intel_crt_connector_helper_funcs);
drm_sysfs_connector_add(connector);
}
| gpl-2.0 |
binkybear/AK-OnePone | drivers/base/core.c | 30 | 50008 | /*
* drivers/base/core.c - core driver model code (device registration, etc)
*
* Copyright (c) 2002-3 Patrick Mochel
* Copyright (c) 2002-3 Open Source Development Labs
* Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de>
* Copyright (c) 2006 Novell, Inc.
*
* This file is released under the GPLv2
*
*/
#include <linux/device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/kdev_t.h>
#include <linux/notifier.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/genhd.h>
#include <linux/kallsyms.h>
#include <linux/mutex.h>
#include <linux/async.h>
#include <linux/pm_runtime.h>
#include "base.h"
#include "power/power.h"
#ifdef CONFIG_SYSFS_DEPRECATED
#ifdef CONFIG_SYSFS_DEPRECATED_V2
long sysfs_deprecated = 1;
#else
long sysfs_deprecated = 0;
#endif
static __init int sysfs_deprecated_setup(char *arg)
{
return strict_strtol(arg, 10, &sysfs_deprecated);
}
early_param("sysfs.deprecated", sysfs_deprecated_setup);
#endif
int (*platform_notify)(struct device *dev) = NULL;
int (*platform_notify_remove)(struct device *dev) = NULL;
static struct kobject *dev_kobj;
struct kobject *sysfs_dev_char_kobj;
struct kobject *sysfs_dev_block_kobj;
#ifdef CONFIG_BLOCK
static inline int device_is_not_partition(struct device *dev)
{
return !(dev->type == &part_type);
}
#else
static inline int device_is_not_partition(struct device *dev)
{
return 1;
}
#endif
/**
* dev_driver_string - Return a device's driver name, if at all possible
* @dev: struct device to get the name of
*
* Will return the device's driver's name if it is bound to a device. If
* the device is not bound to a device, it will return the name of the bus
* it is attached to. If it is not attached to a bus either, an empty
* string will be returned.
*/
const char *dev_driver_string(const struct device *dev)
{
struct device_driver *drv;
/* dev->driver can change to NULL underneath us because of unbinding,
* so be careful about accessing it. dev->bus and dev->class should
* never change once they are set, so they don't need special care.
*/
drv = ACCESS_ONCE(dev->driver);
return drv ? drv->name :
(dev->bus ? dev->bus->name :
(dev->class ? dev->class->name : ""));
}
EXPORT_SYMBOL(dev_driver_string);
#define to_dev(obj) container_of(obj, struct device, kobj)
#define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct device_attribute *dev_attr = to_dev_attr(attr);
struct device *dev = to_dev(kobj);
ssize_t ret = -EIO;
if (dev_attr->show)
ret = dev_attr->show(dev, dev_attr, buf);
if (ret >= (ssize_t)PAGE_SIZE) {
print_symbol("dev_attr_show: %s returned bad count\n",
(unsigned long)dev_attr->show);
}
return ret;
}
static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct device_attribute *dev_attr = to_dev_attr(attr);
struct device *dev = to_dev(kobj);
ssize_t ret = -EIO;
if (dev_attr->store)
ret = dev_attr->store(dev, dev_attr, buf, count);
return ret;
}
static const struct sysfs_ops dev_sysfs_ops = {
.show = dev_attr_show,
.store = dev_attr_store,
};
#define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
ssize_t device_store_ulong(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct dev_ext_attribute *ea = to_ext_attr(attr);
char *end;
unsigned long new = simple_strtoul(buf, &end, 0);
if (end == buf)
return -EINVAL;
*(unsigned long *)(ea->var) = new;
/* Always return full write size even if we didn't consume all */
return size;
}
EXPORT_SYMBOL_GPL(device_store_ulong);
ssize_t device_show_ulong(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct dev_ext_attribute *ea = to_ext_attr(attr);
return snprintf(buf, PAGE_SIZE, "%lx\n", *(unsigned long *)(ea->var));
}
EXPORT_SYMBOL_GPL(device_show_ulong);
ssize_t device_store_int(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct dev_ext_attribute *ea = to_ext_attr(attr);
char *end;
long new = simple_strtol(buf, &end, 0);
if (end == buf || new > INT_MAX || new < INT_MIN)
return -EINVAL;
*(int *)(ea->var) = new;
/* Always return full write size even if we didn't consume all */
return size;
}
EXPORT_SYMBOL_GPL(device_store_int);
ssize_t device_show_int(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct dev_ext_attribute *ea = to_ext_attr(attr);
return snprintf(buf, PAGE_SIZE, "%d\n", *(int *)(ea->var));
}
EXPORT_SYMBOL_GPL(device_show_int);
/**
* device_release - free device structure.
* @kobj: device's kobject.
*
* This is called once the reference count for the object
* reaches 0. We forward the call to the device's release
* method, which should handle actually freeing the structure.
*/
static void device_release(struct kobject *kobj)
{
struct device *dev = to_dev(kobj);
struct device_private *p = dev->p;
if (dev->release)
dev->release(dev);
else if (dev->type && dev->type->release)
dev->type->release(dev);
else if (dev->class && dev->class->dev_release)
dev->class->dev_release(dev);
else
WARN(1, KERN_ERR "Device '%s' does not have a release() "
"function, it is broken and must be fixed.\n",
dev_name(dev));
kfree(p);
}
static const void *device_namespace(struct kobject *kobj)
{
struct device *dev = to_dev(kobj);
const void *ns = NULL;
if (dev->class && dev->class->ns_type)
ns = dev->class->namespace(dev);
return ns;
}
static struct kobj_type device_ktype = {
.release = device_release,
.sysfs_ops = &dev_sysfs_ops,
.namespace = device_namespace,
};
static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
{
struct kobj_type *ktype = get_ktype(kobj);
if (ktype == &device_ktype) {
struct device *dev = to_dev(kobj);
if (dev->bus)
return 1;
if (dev->class)
return 1;
}
return 0;
}
static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
{
struct device *dev = to_dev(kobj);
if (dev->bus)
return dev->bus->name;
if (dev->class)
return dev->class->name;
return NULL;
}
static int dev_uevent(struct kset *kset, struct kobject *kobj,
struct kobj_uevent_env *env)
{
struct device *dev = to_dev(kobj);
int retval = 0;
/* add device node properties if present */
if (MAJOR(dev->devt)) {
const char *tmp;
const char *name;
umode_t mode = 0;
add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
name = device_get_devnode(dev, &mode, &tmp);
if (name) {
add_uevent_var(env, "DEVNAME=%s", name);
kfree(tmp);
if (mode)
add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
}
}
if (dev->type && dev->type->name)
add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
if (dev->driver)
add_uevent_var(env, "DRIVER=%s", dev->driver->name);
/* Add common DT information about the device */
of_device_uevent(dev, env);
/* have the bus specific function add its stuff */
if (dev->bus && dev->bus->uevent) {
retval = dev->bus->uevent(dev, env);
if (retval)
pr_debug("device: '%s': %s: bus uevent() returned %d\n",
dev_name(dev), __func__, retval);
}
/* have the class specific function add its stuff */
if (dev->class && dev->class->dev_uevent) {
retval = dev->class->dev_uevent(dev, env);
if (retval)
pr_debug("device: '%s': %s: class uevent() "
"returned %d\n", dev_name(dev),
__func__, retval);
}
/* have the device type specific function add its stuff */
if (dev->type && dev->type->uevent) {
retval = dev->type->uevent(dev, env);
if (retval)
pr_debug("device: '%s': %s: dev_type uevent() "
"returned %d\n", dev_name(dev),
__func__, retval);
}
return retval;
}
static const struct kset_uevent_ops device_uevent_ops = {
.filter = dev_uevent_filter,
.name = dev_uevent_name,
.uevent = dev_uevent,
};
static ssize_t show_uevent(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct kobject *top_kobj;
struct kset *kset;
struct kobj_uevent_env *env = NULL;
int i;
size_t count = 0;
int retval;
/* search the kset, the device belongs to */
top_kobj = &dev->kobj;
while (!top_kobj->kset && top_kobj->parent)
top_kobj = top_kobj->parent;
if (!top_kobj->kset)
goto out;
kset = top_kobj->kset;
if (!kset->uevent_ops || !kset->uevent_ops->uevent)
goto out;
/* respect filter */
if (kset->uevent_ops && kset->uevent_ops->filter)
if (!kset->uevent_ops->filter(kset, &dev->kobj))
goto out;
env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
/* let the kset specific function add its keys */
retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
if (retval)
goto out;
/* copy keys to file */
for (i = 0; i < env->envp_idx; i++)
count += sprintf(&buf[count], "%s\n", env->envp[i]);
out:
kfree(env);
return count;
}
static ssize_t store_uevent(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
enum kobject_action action;
if (kobject_action_type(buf, count, &action) == 0)
kobject_uevent(&dev->kobj, action);
else
dev_err(dev, "uevent: unknown action-string\n");
return count;
}
static struct device_attribute uevent_attr =
__ATTR(uevent, S_IRUGO | S_IWUSR, show_uevent, store_uevent);
static int device_add_attributes(struct device *dev,
struct device_attribute *attrs)
{
int error = 0;
int i;
if (attrs) {
for (i = 0; attr_name(attrs[i]); i++) {
error = device_create_file(dev, &attrs[i]);
if (error)
break;
}
if (error)
while (--i >= 0)
device_remove_file(dev, &attrs[i]);
}
return error;
}
static void device_remove_attributes(struct device *dev,
struct device_attribute *attrs)
{
int i;
if (attrs)
for (i = 0; attr_name(attrs[i]); i++)
device_remove_file(dev, &attrs[i]);
}
static int device_add_bin_attributes(struct device *dev,
struct bin_attribute *attrs)
{
int error = 0;
int i;
if (attrs) {
for (i = 0; attr_name(attrs[i]); i++) {
error = device_create_bin_file(dev, &attrs[i]);
if (error)
break;
}
if (error)
while (--i >= 0)
device_remove_bin_file(dev, &attrs[i]);
}
return error;
}
static void device_remove_bin_attributes(struct device *dev,
struct bin_attribute *attrs)
{
int i;
if (attrs)
for (i = 0; attr_name(attrs[i]); i++)
device_remove_bin_file(dev, &attrs[i]);
}
static int device_add_groups(struct device *dev,
const struct attribute_group **groups)
{
int error = 0;
int i;
if (groups) {
for (i = 0; groups[i]; i++) {
error = sysfs_create_group(&dev->kobj, groups[i]);
if (error) {
while (--i >= 0)
sysfs_remove_group(&dev->kobj,
groups[i]);
break;
}
}
}
return error;
}
static void device_remove_groups(struct device *dev,
const struct attribute_group **groups)
{
int i;
if (groups)
for (i = 0; groups[i]; i++)
sysfs_remove_group(&dev->kobj, groups[i]);
}
static int device_add_attrs(struct device *dev)
{
struct class *class = dev->class;
const struct device_type *type = dev->type;
int error;
if (class) {
error = device_add_attributes(dev, class->dev_attrs);
if (error)
return error;
error = device_add_bin_attributes(dev, class->dev_bin_attrs);
if (error)
goto err_remove_class_attrs;
}
if (type) {
error = device_add_groups(dev, type->groups);
if (error)
goto err_remove_class_bin_attrs;
}
error = device_add_groups(dev, dev->groups);
if (error)
goto err_remove_type_groups;
return 0;
err_remove_type_groups:
if (type)
device_remove_groups(dev, type->groups);
err_remove_class_bin_attrs:
if (class)
device_remove_bin_attributes(dev, class->dev_bin_attrs);
err_remove_class_attrs:
if (class)
device_remove_attributes(dev, class->dev_attrs);
return error;
}
static void device_remove_attrs(struct device *dev)
{
struct class *class = dev->class;
const struct device_type *type = dev->type;
device_remove_groups(dev, dev->groups);
if (type)
device_remove_groups(dev, type->groups);
if (class) {
device_remove_attributes(dev, class->dev_attrs);
device_remove_bin_attributes(dev, class->dev_bin_attrs);
}
}
static ssize_t show_dev(struct device *dev, struct device_attribute *attr,
char *buf)
{
return print_dev_t(buf, dev->devt);
}
static struct device_attribute devt_attr =
__ATTR(dev, S_IRUGO, show_dev, NULL);
/* /sys/devices/ */
struct kset *devices_kset;
/**
* device_create_file - create sysfs attribute file for device.
* @dev: device.
* @attr: device attribute descriptor.
*/
int device_create_file(struct device *dev,
const struct device_attribute *attr)
{
int error = 0;
if (dev)
error = sysfs_create_file(&dev->kobj, &attr->attr);
return error;
}
/**
* device_remove_file - remove sysfs attribute file.
* @dev: device.
* @attr: device attribute descriptor.
*/
void device_remove_file(struct device *dev,
const struct device_attribute *attr)
{
if (dev)
sysfs_remove_file(&dev->kobj, &attr->attr);
}
/**
* device_create_bin_file - create sysfs binary attribute file for device.
* @dev: device.
* @attr: device binary attribute descriptor.
*/
int device_create_bin_file(struct device *dev,
const struct bin_attribute *attr)
{
int error = -EINVAL;
if (dev)
error = sysfs_create_bin_file(&dev->kobj, attr);
return error;
}
EXPORT_SYMBOL_GPL(device_create_bin_file);
/**
* device_remove_bin_file - remove sysfs binary attribute file
* @dev: device.
* @attr: device binary attribute descriptor.
*/
void device_remove_bin_file(struct device *dev,
const struct bin_attribute *attr)
{
if (dev)
sysfs_remove_bin_file(&dev->kobj, attr);
}
EXPORT_SYMBOL_GPL(device_remove_bin_file);
/**
* device_schedule_callback_owner - helper to schedule a callback for a device
* @dev: device.
* @func: callback function to invoke later.
* @owner: module owning the callback routine
*
* Attribute methods must not unregister themselves or their parent device
* (which would amount to the same thing). Attempts to do so will deadlock,
* since unregistration is mutually exclusive with driver callbacks.
*
* Instead methods can call this routine, which will attempt to allocate
* and schedule a workqueue request to call back @func with @dev as its
* argument in the workqueue's process context. @dev will be pinned until
* @func returns.
*
* This routine is usually called via the inline device_schedule_callback(),
* which automatically sets @owner to THIS_MODULE.
*
* Returns 0 if the request was submitted, -ENOMEM if storage could not
* be allocated, -ENODEV if a reference to @owner isn't available.
*
* NOTE: This routine won't work if CONFIG_SYSFS isn't set! It uses an
* underlying sysfs routine (since it is intended for use by attribute
* methods), and if sysfs isn't available you'll get nothing but -ENOSYS.
*/
int device_schedule_callback_owner(struct device *dev,
void (*func)(struct device *), struct module *owner)
{
return sysfs_schedule_callback(&dev->kobj,
(void (*)(void *)) func, dev, owner);
}
EXPORT_SYMBOL_GPL(device_schedule_callback_owner);
static void klist_children_get(struct klist_node *n)
{
struct device_private *p = to_device_private_parent(n);
struct device *dev = p->device;
get_device(dev);
}
static void klist_children_put(struct klist_node *n)
{
struct device_private *p = to_device_private_parent(n);
struct device *dev = p->device;
put_device(dev);
}
/**
* device_initialize - init device structure.
* @dev: device.
*
* This prepares the device for use by other layers by initializing
* its fields.
* It is the first half of device_register(), if called by
* that function, though it can also be called separately, so one
* may use @dev's fields. In particular, get_device()/put_device()
* may be used for reference counting of @dev after calling this
* function.
*
* All fields in @dev must be initialized by the caller to 0, except
* for those explicitly set to some other value. The simplest
* approach is to use kzalloc() to allocate the structure containing
* @dev.
*
* NOTE: Use put_device() to give up your reference instead of freeing
* @dev directly once you have called this function.
*/
void device_initialize(struct device *dev)
{
dev->kobj.kset = devices_kset;
kobject_init(&dev->kobj, &device_ktype);
INIT_LIST_HEAD(&dev->dma_pools);
mutex_init(&dev->mutex);
lockdep_set_novalidate_class(&dev->mutex);
spin_lock_init(&dev->devres_lock);
INIT_LIST_HEAD(&dev->devres_head);
device_pm_init(dev);
set_dev_node(dev, -1);
}
static struct kobject *virtual_device_parent(struct device *dev)
{
static struct kobject *virtual_dir = NULL;
if (!virtual_dir)
virtual_dir = kobject_create_and_add("virtual",
&devices_kset->kobj);
return virtual_dir;
}
struct class_dir {
struct kobject kobj;
struct class *class;
};
#define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
static void class_dir_release(struct kobject *kobj)
{
struct class_dir *dir = to_class_dir(kobj);
kfree(dir);
}
static const
struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
{
struct class_dir *dir = to_class_dir(kobj);
return dir->class->ns_type;
}
static struct kobj_type class_dir_ktype = {
.release = class_dir_release,
.sysfs_ops = &kobj_sysfs_ops,
.child_ns_type = class_dir_child_ns_type
};
static struct kobject *
class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
{
struct class_dir *dir;
int retval;
dir = kzalloc(sizeof(*dir), GFP_KERNEL);
if (!dir)
return NULL;
dir->class = class;
kobject_init(&dir->kobj, &class_dir_ktype);
dir->kobj.kset = &class->p->glue_dirs;
retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
if (retval < 0) {
kobject_put(&dir->kobj);
return NULL;
}
return &dir->kobj;
}
static struct kobject *get_device_parent(struct device *dev,
struct device *parent)
{
if (dev->class) {
static DEFINE_MUTEX(gdp_mutex);
struct kobject *kobj = NULL;
struct kobject *parent_kobj;
struct kobject *k;
#ifdef CONFIG_BLOCK
/* block disks show up in /sys/block */
if (sysfs_deprecated && dev->class == &block_class) {
if (parent && parent->class == &block_class)
return &parent->kobj;
return &block_class.p->subsys.kobj;
}
#endif
/*
* If we have no parent, we live in "virtual".
* Class-devices with a non class-device as parent, live
* in a "glue" directory to prevent namespace collisions.
*/
if (parent == NULL)
parent_kobj = virtual_device_parent(dev);
else if (parent->class && !dev->class->ns_type)
return &parent->kobj;
else
parent_kobj = &parent->kobj;
mutex_lock(&gdp_mutex);
/* find our class-directory at the parent and reference it */
spin_lock(&dev->class->p->glue_dirs.list_lock);
list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
if (k->parent == parent_kobj) {
kobj = kobject_get(k);
break;
}
spin_unlock(&dev->class->p->glue_dirs.list_lock);
if (kobj) {
mutex_unlock(&gdp_mutex);
return kobj;
}
/* or create a new class-directory at the parent device */
k = class_dir_create_and_add(dev->class, parent_kobj);
/* do not emit an uevent for this simple "glue" directory */
mutex_unlock(&gdp_mutex);
return k;
}
/* subsystems can specify a default root directory for their devices */
if (!parent && dev->bus && dev->bus->dev_root)
return &dev->bus->dev_root->kobj;
if (parent)
return &parent->kobj;
return NULL;
}
static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
{
/* see if we live in a "glue" directory */
if (!glue_dir || !dev->class ||
glue_dir->kset != &dev->class->p->glue_dirs)
return;
kobject_put(glue_dir);
}
static void cleanup_device_parent(struct device *dev)
{
cleanup_glue_dir(dev, dev->kobj.parent);
}
static int device_add_class_symlinks(struct device *dev)
{
int error;
if (!dev->class)
return 0;
error = sysfs_create_link(&dev->kobj,
&dev->class->p->subsys.kobj,
"subsystem");
if (error)
goto out;
if (dev->parent && device_is_not_partition(dev)) {
error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
"device");
if (error)
goto out_subsys;
}
#ifdef CONFIG_BLOCK
/* /sys/block has directories and does not need symlinks */
if (sysfs_deprecated && dev->class == &block_class)
return 0;
#endif
/* link in the class directory pointing to the device */
error = sysfs_create_link(&dev->class->p->subsys.kobj,
&dev->kobj, dev_name(dev));
if (error)
goto out_device;
return 0;
out_device:
sysfs_remove_link(&dev->kobj, "device");
out_subsys:
sysfs_remove_link(&dev->kobj, "subsystem");
out:
return error;
}
static void device_remove_class_symlinks(struct device *dev)
{
if (!dev->class)
return;
if (dev->parent && device_is_not_partition(dev))
sysfs_remove_link(&dev->kobj, "device");
sysfs_remove_link(&dev->kobj, "subsystem");
#ifdef CONFIG_BLOCK
if (sysfs_deprecated && dev->class == &block_class)
return;
#endif
sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
}
/**
* dev_set_name - set a device name
* @dev: device
* @fmt: format string for the device's name
*/
int dev_set_name(struct device *dev, const char *fmt, ...)
{
va_list vargs;
int err;
va_start(vargs, fmt);
err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
va_end(vargs);
return err;
}
EXPORT_SYMBOL_GPL(dev_set_name);
/**
* device_to_dev_kobj - select a /sys/dev/ directory for the device
* @dev: device
*
* By default we select char/ for new entries. Setting class->dev_obj
* to NULL prevents an entry from being created. class->dev_kobj must
* be set (or cleared) before any devices are registered to the class
* otherwise device_create_sys_dev_entry() and
* device_remove_sys_dev_entry() will disagree about the the presence
* of the link.
*/
static struct kobject *device_to_dev_kobj(struct device *dev)
{
struct kobject *kobj;
if (dev->class)
kobj = dev->class->dev_kobj;
else
kobj = sysfs_dev_char_kobj;
return kobj;
}
static int device_create_sys_dev_entry(struct device *dev)
{
struct kobject *kobj = device_to_dev_kobj(dev);
int error = 0;
char devt_str[15];
if (kobj) {
format_dev_t(devt_str, dev->devt);
error = sysfs_create_link(kobj, &dev->kobj, devt_str);
}
return error;
}
static void device_remove_sys_dev_entry(struct device *dev)
{
struct kobject *kobj = device_to_dev_kobj(dev);
char devt_str[15];
if (kobj) {
format_dev_t(devt_str, dev->devt);
sysfs_remove_link(kobj, devt_str);
}
}
int device_private_init(struct device *dev)
{
dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
if (!dev->p)
return -ENOMEM;
dev->p->device = dev;
klist_init(&dev->p->klist_children, klist_children_get,
klist_children_put);
INIT_LIST_HEAD(&dev->p->deferred_probe);
return 0;
}
/**
* device_add - add device to device hierarchy.
* @dev: device.
*
* This is part 2 of device_register(), though may be called
* separately _iff_ device_initialize() has been called separately.
*
* This adds @dev to the kobject hierarchy via kobject_add(), adds it
* to the global and sibling lists for the device, then
* adds it to the other relevant subsystems of the driver model.
*
* Do not call this routine or device_register() more than once for
* any device structure. The driver model core is not designed to work
* with devices that get unregistered and then spring back to life.
* (Among other things, it's very hard to guarantee that all references
* to the previous incarnation of @dev have been dropped.) Allocate
* and register a fresh new struct device instead.
*
* NOTE: _Never_ directly free @dev after calling this function, even
* if it returned an error! Always use put_device() to give up your
* reference instead.
*/
int device_add(struct device *dev)
{
struct device *parent = NULL;
struct kobject *kobj;
struct class_interface *class_intf;
int error = -EINVAL;
dev = get_device(dev);
if (!dev)
goto done;
if (!dev->p) {
error = device_private_init(dev);
if (error)
goto done;
}
/*
* for statically allocated devices, which should all be converted
* some day, we need to initialize the name. We prevent reading back
* the name, and force the use of dev_name()
*/
if (dev->init_name) {
dev_set_name(dev, "%s", dev->init_name);
dev->init_name = NULL;
}
/* subsystems can specify simple device enumeration */
if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
if (!dev_name(dev)) {
error = -EINVAL;
goto name_error;
}
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
parent = get_device(dev->parent);
kobj = get_device_parent(dev, parent);
if (kobj)
dev->kobj.parent = kobj;
/* use parent numa_node */
if (parent)
set_dev_node(dev, dev_to_node(parent));
/* first, register with generic layer. */
/* we require the name to be set before, and pass NULL */
error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
if (error)
goto Error;
/* notify platform of device entry */
if (platform_notify)
platform_notify(dev);
error = device_create_file(dev, &uevent_attr);
if (error)
goto attrError;
if (MAJOR(dev->devt)) {
error = device_create_file(dev, &devt_attr);
if (error)
goto ueventattrError;
error = device_create_sys_dev_entry(dev);
if (error)
goto devtattrError;
devtmpfs_create_node(dev);
}
error = device_add_class_symlinks(dev);
if (error)
goto SymlinkError;
error = device_add_attrs(dev);
if (error)
goto AttrsError;
error = bus_add_device(dev);
if (error)
goto BusError;
error = dpm_sysfs_add(dev);
if (error)
goto DPMError;
if ((dev->pm_domain) || (dev->type && dev->type->pm)
|| (dev->class && (dev->class->pm || dev->class->resume))
|| (dev->bus && (dev->bus->pm || dev->bus->resume)) ||
(dev->driver && dev->driver->pm)) {
device_pm_add(dev);
}
/* Notify clients of device addition. This call must come
* after dpm_sysfs_add() and before kobject_uevent().
*/
if (dev->bus)
blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
BUS_NOTIFY_ADD_DEVICE, dev);
kobject_uevent(&dev->kobj, KOBJ_ADD);
bus_probe_device(dev);
if (parent)
klist_add_tail(&dev->p->knode_parent,
&parent->p->klist_children);
if (dev->class) {
mutex_lock(&dev->class->p->mutex);
/* tie the class to the device */
klist_add_tail(&dev->knode_class,
&dev->class->p->klist_devices);
/* notify any interfaces that the device is here */
list_for_each_entry(class_intf,
&dev->class->p->interfaces, node)
if (class_intf->add_dev)
class_intf->add_dev(dev, class_intf);
mutex_unlock(&dev->class->p->mutex);
}
done:
put_device(dev);
return error;
DPMError:
bus_remove_device(dev);
BusError:
device_remove_attrs(dev);
AttrsError:
device_remove_class_symlinks(dev);
SymlinkError:
if (MAJOR(dev->devt))
devtmpfs_delete_node(dev);
if (MAJOR(dev->devt))
device_remove_sys_dev_entry(dev);
devtattrError:
if (MAJOR(dev->devt))
device_remove_file(dev, &devt_attr);
ueventattrError:
device_remove_file(dev, &uevent_attr);
attrError:
kobject_uevent(&dev->kobj, KOBJ_REMOVE);
kobject_del(&dev->kobj);
Error:
cleanup_device_parent(dev);
if (parent)
put_device(parent);
name_error:
kfree(dev->p);
dev->p = NULL;
goto done;
}
/**
* device_register - register a device with the system.
* @dev: pointer to the device structure
*
* This happens in two clean steps - initialize the device
* and add it to the system. The two steps can be called
* separately, but this is the easiest and most common.
* I.e. you should only call the two helpers separately if
* have a clearly defined need to use and refcount the device
* before it is added to the hierarchy.
*
* For more information, see the kerneldoc for device_initialize()
* and device_add().
*
* NOTE: _Never_ directly free @dev after calling this function, even
* if it returned an error! Always use put_device() to give up the
* reference initialized in this function instead.
*/
int device_register(struct device *dev)
{
device_initialize(dev);
return device_add(dev);
}
/**
* get_device - increment reference count for device.
* @dev: device.
*
* This simply forwards the call to kobject_get(), though
* we do take care to provide for the case that we get a NULL
* pointer passed in.
*/
struct device *get_device(struct device *dev)
{
return dev ? to_dev(kobject_get(&dev->kobj)) : NULL;
}
/**
* put_device - decrement reference count.
* @dev: device in question.
*/
void put_device(struct device *dev)
{
/* might_sleep(); */
if (dev)
kobject_put(&dev->kobj);
}
/**
* device_del - delete device from system.
* @dev: device.
*
* This is the first part of the device unregistration
* sequence. This removes the device from the lists we control
* from here, has it removed from the other driver model
* subsystems it was added to in device_add(), and removes it
* from the kobject hierarchy.
*
* NOTE: this should be called manually _iff_ device_add() was
* also called manually.
*/
void device_del(struct device *dev)
{
struct device *parent = dev->parent;
struct class_interface *class_intf;
/* Notify clients of device removal. This call must come
* before dpm_sysfs_remove().
*/
if (dev->bus)
blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
BUS_NOTIFY_DEL_DEVICE, dev);
device_pm_remove(dev);
dpm_sysfs_remove(dev);
if (parent)
klist_del(&dev->p->knode_parent);
if (MAJOR(dev->devt)) {
devtmpfs_delete_node(dev);
device_remove_sys_dev_entry(dev);
device_remove_file(dev, &devt_attr);
}
if (dev->class) {
device_remove_class_symlinks(dev);
mutex_lock(&dev->class->p->mutex);
/* notify any interfaces that the device is now gone */
list_for_each_entry(class_intf,
&dev->class->p->interfaces, node)
if (class_intf->remove_dev)
class_intf->remove_dev(dev, class_intf);
/* remove the device from the class list */
klist_del(&dev->knode_class);
mutex_unlock(&dev->class->p->mutex);
}
device_remove_file(dev, &uevent_attr);
device_remove_attrs(dev);
bus_remove_device(dev);
driver_deferred_probe_del(dev);
/*
* Some platform devices are driven without driver attached
* and managed resources may have been acquired. Make sure
* all resources are released.
*/
devres_release_all(dev);
/* Notify the platform of the removal, in case they
* need to do anything...
*/
if (platform_notify_remove)
platform_notify_remove(dev);
kobject_uevent(&dev->kobj, KOBJ_REMOVE);
cleanup_device_parent(dev);
kobject_del(&dev->kobj);
put_device(parent);
}
/**
* device_unregister - unregister device from system.
* @dev: device going away.
*
* We do this in two parts, like we do device_register(). First,
* we remove it from all the subsystems with device_del(), then
* we decrement the reference count via put_device(). If that
* is the final reference count, the device will be cleaned up
* via device_release() above. Otherwise, the structure will
* stick around until the final reference to the device is dropped.
*/
void device_unregister(struct device *dev)
{
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
device_del(dev);
put_device(dev);
}
static struct device *next_device(struct klist_iter *i)
{
struct klist_node *n = klist_next(i);
struct device *dev = NULL;
struct device_private *p;
if (n) {
p = to_device_private_parent(n);
dev = p->device;
}
return dev;
}
/**
* device_get_devnode - path of device node file
* @dev: device
* @mode: returned file access mode
* @tmp: possibly allocated string
*
* Return the relative path of a possible device node.
* Non-default names may need to allocate a memory to compose
* a name. This memory is returned in tmp and needs to be
* freed by the caller.
*/
const char *device_get_devnode(struct device *dev,
umode_t *mode, const char **tmp)
{
char *s;
*tmp = NULL;
/* the device type may provide a specific name */
if (dev->type && dev->type->devnode)
*tmp = dev->type->devnode(dev, mode);
if (*tmp)
return *tmp;
/* the class may provide a specific name */
if (dev->class && dev->class->devnode)
*tmp = dev->class->devnode(dev, mode);
if (*tmp)
return *tmp;
/* return name without allocation, tmp == NULL */
if (strchr(dev_name(dev), '!') == NULL)
return dev_name(dev);
/* replace '!' in the name with '/' */
*tmp = kstrdup(dev_name(dev), GFP_KERNEL);
if (!*tmp)
return NULL;
while ((s = strchr(*tmp, '!')))
s[0] = '/';
return *tmp;
}
/**
* device_for_each_child - device child iterator.
* @parent: parent struct device.
* @data: data for the callback.
* @fn: function to be called for each device.
*
* Iterate over @parent's child devices, and call @fn for each,
* passing it @data.
*
* We check the return of @fn each time. If it returns anything
* other than 0, we break out and return that value.
*/
int device_for_each_child(struct device *parent, void *data,
int (*fn)(struct device *dev, void *data))
{
struct klist_iter i;
struct device *child;
int error = 0;
if (!parent->p)
return 0;
klist_iter_init(&parent->p->klist_children, &i);
while ((child = next_device(&i)) && !error)
error = fn(child, data);
klist_iter_exit(&i);
return error;
}
/**
* device_find_child - device iterator for locating a particular device.
* @parent: parent struct device
* @data: Data to pass to match function
* @match: Callback function to check device
*
* This is similar to the device_for_each_child() 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 and a reference to the
* current device can be obtained, this function will return to the caller
* and not iterate over any more devices.
*/
struct device *device_find_child(struct device *parent, void *data,
int (*match)(struct device *dev, void *data))
{
struct klist_iter i;
struct device *child;
if (!parent)
return NULL;
klist_iter_init(&parent->p->klist_children, &i);
while ((child = next_device(&i)))
if (match(child, data) && get_device(child))
break;
klist_iter_exit(&i);
return child;
}
int __init devices_init(void)
{
devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
if (!devices_kset)
return -ENOMEM;
dev_kobj = kobject_create_and_add("dev", NULL);
if (!dev_kobj)
goto dev_kobj_err;
sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
if (!sysfs_dev_block_kobj)
goto block_kobj_err;
sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
if (!sysfs_dev_char_kobj)
goto char_kobj_err;
return 0;
char_kobj_err:
kobject_put(sysfs_dev_block_kobj);
block_kobj_err:
kobject_put(dev_kobj);
dev_kobj_err:
kset_unregister(devices_kset);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(device_for_each_child);
EXPORT_SYMBOL_GPL(device_find_child);
EXPORT_SYMBOL_GPL(device_initialize);
EXPORT_SYMBOL_GPL(device_add);
EXPORT_SYMBOL_GPL(device_register);
EXPORT_SYMBOL_GPL(device_del);
EXPORT_SYMBOL_GPL(device_unregister);
EXPORT_SYMBOL_GPL(get_device);
EXPORT_SYMBOL_GPL(put_device);
EXPORT_SYMBOL_GPL(device_create_file);
EXPORT_SYMBOL_GPL(device_remove_file);
struct root_device {
struct device dev;
struct module *owner;
};
inline struct root_device *to_root_device(struct device *d)
{
return container_of(d, struct root_device, dev);
}
static void root_device_release(struct device *dev)
{
kfree(to_root_device(dev));
}
/**
* __root_device_register - allocate and register a root device
* @name: root device name
* @owner: owner module of the root device, usually THIS_MODULE
*
* This function allocates a root device and registers it
* using device_register(). In order to free the returned
* device, use root_device_unregister().
*
* Root devices are dummy devices which allow other devices
* to be grouped under /sys/devices. Use this function to
* allocate a root device and then use it as the parent of
* any device which should appear under /sys/devices/{name}
*
* The /sys/devices/{name} directory will also contain a
* 'module' symlink which points to the @owner directory
* in sysfs.
*
* Returns &struct device pointer on success, or ERR_PTR() on error.
*
* Note: You probably want to use root_device_register().
*/
struct device *__root_device_register(const char *name, struct module *owner)
{
struct root_device *root;
int err = -ENOMEM;
root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
if (!root)
return ERR_PTR(err);
err = dev_set_name(&root->dev, "%s", name);
if (err) {
kfree(root);
return ERR_PTR(err);
}
root->dev.release = root_device_release;
err = device_register(&root->dev);
if (err) {
put_device(&root->dev);
return ERR_PTR(err);
}
#ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */
if (owner) {
struct module_kobject *mk = &owner->mkobj;
err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
if (err) {
device_unregister(&root->dev);
return ERR_PTR(err);
}
root->owner = owner;
}
#endif
return &root->dev;
}
EXPORT_SYMBOL_GPL(__root_device_register);
/**
* root_device_unregister - unregister and free a root device
* @dev: device going away
*
* This function unregisters and cleans up a device that was created by
* root_device_register().
*/
void root_device_unregister(struct device *dev)
{
struct root_device *root = to_root_device(dev);
if (root->owner)
sysfs_remove_link(&root->dev.kobj, "module");
device_unregister(dev);
}
EXPORT_SYMBOL_GPL(root_device_unregister);
static void device_create_release(struct device *dev)
{
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
kfree(dev);
}
/**
* device_create_vargs - creates a device and registers it with sysfs
* @class: pointer to the struct class that this device should be registered to
* @parent: pointer to the parent struct device of this new device, if any
* @devt: the dev_t for the char device to be added
* @drvdata: the data to be added to the device for callbacks
* @fmt: string for the device's name
* @args: va_list for the device's name
*
* This function can be used by char device classes. A struct device
* will be created in sysfs, registered to the specified class.
*
* A "dev" file will be created, showing the dev_t for the device, if
* the dev_t is not 0,0.
* If a pointer to a parent struct device is passed in, the newly created
* struct device will be a child of that device in sysfs.
* The pointer to the struct device will be returned from the call.
* Any further sysfs files that might be required can be created using this
* pointer.
*
* Returns &struct device pointer on success, or ERR_PTR() on error.
*
* Note: the struct class passed to this function must have previously
* been created with a call to class_create().
*/
struct device *device_create_vargs(struct class *class, struct device *parent,
dev_t devt, void *drvdata, const char *fmt,
va_list args)
{
struct device *dev = NULL;
int retval = -ENODEV;
if (class == NULL || IS_ERR(class))
goto error;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
retval = -ENOMEM;
goto error;
}
dev->devt = devt;
dev->class = class;
dev->parent = parent;
dev->release = device_create_release;
dev_set_drvdata(dev, drvdata);
retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
if (retval)
goto error;
retval = device_register(dev);
if (retval)
goto error;
return dev;
error:
put_device(dev);
return ERR_PTR(retval);
}
EXPORT_SYMBOL_GPL(device_create_vargs);
/**
* device_create - creates a device and registers it with sysfs
* @class: pointer to the struct class that this device should be registered to
* @parent: pointer to the parent struct device of this new device, if any
* @devt: the dev_t for the char device to be added
* @drvdata: the data to be added to the device for callbacks
* @fmt: string for the device's name
*
* This function can be used by char device classes. A struct device
* will be created in sysfs, registered to the specified class.
*
* A "dev" file will be created, showing the dev_t for the device, if
* the dev_t is not 0,0.
* If a pointer to a parent struct device is passed in, the newly created
* struct device will be a child of that device in sysfs.
* The pointer to the struct device will be returned from the call.
* Any further sysfs files that might be required can be created using this
* pointer.
*
* Returns &struct device pointer on success, or ERR_PTR() on error.
*
* Note: the struct class passed to this function must have previously
* been created with a call to class_create().
*/
struct device *device_create(struct class *class, struct device *parent,
dev_t devt, void *drvdata, const char *fmt, ...)
{
va_list vargs;
struct device *dev;
va_start(vargs, fmt);
dev = device_create_vargs(class, parent, devt, drvdata, fmt, vargs);
va_end(vargs);
return dev;
}
EXPORT_SYMBOL_GPL(device_create);
static int __match_devt(struct device *dev, void *data)
{
dev_t *devt = data;
return dev->devt == *devt;
}
/**
* device_destroy - removes a device that was created with device_create()
* @class: pointer to the struct class that this device was registered with
* @devt: the dev_t of the device that was previously registered
*
* This call unregisters and cleans up a device that was created with a
* call to device_create().
*/
void device_destroy(struct class *class, dev_t devt)
{
struct device *dev;
dev = class_find_device(class, NULL, &devt, __match_devt);
if (dev) {
put_device(dev);
device_unregister(dev);
}
}
EXPORT_SYMBOL_GPL(device_destroy);
/**
* device_rename - renames a device
* @dev: the pointer to the struct device to be renamed
* @new_name: the new name of the device
*
* It is the responsibility of the caller to provide mutual
* exclusion between two different calls of device_rename
* on the same device to ensure that new_name is valid and
* won't conflict with other devices.
*
* Note: Don't call this function. Currently, the networking layer calls this
* function, but that will change. The following text from Kay Sievers offers
* some insight:
*
* Renaming devices is racy at many levels, symlinks and other stuff are not
* replaced atomically, and you get a "move" uevent, but it's not easy to
* connect the event to the old and new device. Device nodes are not renamed at
* all, there isn't even support for that in the kernel now.
*
* In the meantime, during renaming, your target name might be taken by another
* driver, creating conflicts. Or the old name is taken directly after you
* renamed it -- then you get events for the same DEVPATH, before you even see
* the "move" event. It's just a mess, and nothing new should ever rely on
* kernel device renaming. Besides that, it's not even implemented now for
* other things than (driver-core wise very simple) network devices.
*
* We are currently about to change network renaming in udev to completely
* disallow renaming of devices in the same namespace as the kernel uses,
* because we can't solve the problems properly, that arise with swapping names
* of multiple interfaces without races. Means, renaming of eth[0-9]* will only
* be allowed to some other name than eth[0-9]*, for the aforementioned
* reasons.
*
* Make up a "real" name in the driver before you register anything, or add
* some other attributes for userspace to find the device, or use udev to add
* symlinks -- but never rename kernel devices later, it's a complete mess. We
* don't even want to get into that and try to implement the missing pieces in
* the core. We really have other pieces to fix in the driver core mess. :)
*/
int device_rename(struct device *dev, const char *new_name)
{
char *old_class_name = NULL;
char *new_class_name = NULL;
char *old_device_name = NULL;
int error;
dev = get_device(dev);
if (!dev)
return -EINVAL;
pr_debug("device: '%s': %s: renaming to '%s'\n", dev_name(dev),
__func__, new_name);
old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
if (!old_device_name) {
error = -ENOMEM;
goto out;
}
if (dev->class) {
error = sysfs_rename_link(&dev->class->p->subsys.kobj,
&dev->kobj, old_device_name, new_name);
if (error)
goto out;
}
error = kobject_rename(&dev->kobj, new_name);
if (error)
goto out;
out:
put_device(dev);
kfree(new_class_name);
kfree(old_class_name);
kfree(old_device_name);
return error;
}
EXPORT_SYMBOL_GPL(device_rename);
static int device_move_class_links(struct device *dev,
struct device *old_parent,
struct device *new_parent)
{
int error = 0;
if (old_parent)
sysfs_remove_link(&dev->kobj, "device");
if (new_parent)
error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
"device");
return error;
}
/**
* device_move - moves a device to a new parent
* @dev: the pointer to the struct device to be moved
* @new_parent: the new parent of the device (can by NULL)
* @dpm_order: how to reorder the dpm_list
*/
int device_move(struct device *dev, struct device *new_parent,
enum dpm_order dpm_order)
{
int error;
struct device *old_parent;
struct kobject *new_parent_kobj;
dev = get_device(dev);
if (!dev)
return -EINVAL;
device_pm_lock();
new_parent = get_device(new_parent);
new_parent_kobj = get_device_parent(dev, new_parent);
pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
__func__, new_parent ? dev_name(new_parent) : "<NULL>");
error = kobject_move(&dev->kobj, new_parent_kobj);
if (error) {
cleanup_glue_dir(dev, new_parent_kobj);
put_device(new_parent);
goto out;
}
old_parent = dev->parent;
dev->parent = new_parent;
if (old_parent)
klist_remove(&dev->p->knode_parent);
if (new_parent) {
klist_add_tail(&dev->p->knode_parent,
&new_parent->p->klist_children);
set_dev_node(dev, dev_to_node(new_parent));
}
if (!dev->class)
goto out_put;
error = device_move_class_links(dev, old_parent, new_parent);
if (error) {
/* We ignore errors on cleanup since we're hosed anyway... */
device_move_class_links(dev, new_parent, old_parent);
if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
if (new_parent)
klist_remove(&dev->p->knode_parent);
dev->parent = old_parent;
if (old_parent) {
klist_add_tail(&dev->p->knode_parent,
&old_parent->p->klist_children);
set_dev_node(dev, dev_to_node(old_parent));
}
}
cleanup_glue_dir(dev, new_parent_kobj);
put_device(new_parent);
goto out;
}
switch (dpm_order) {
case DPM_ORDER_NONE:
break;
case DPM_ORDER_DEV_AFTER_PARENT:
device_pm_move_after(dev, new_parent);
break;
case DPM_ORDER_PARENT_BEFORE_DEV:
device_pm_move_before(new_parent, dev);
break;
case DPM_ORDER_DEV_LAST:
device_pm_move_last(dev);
break;
}
out_put:
put_device(old_parent);
out:
device_pm_unlock();
put_device(dev);
return error;
}
EXPORT_SYMBOL_GPL(device_move);
/**
* device_shutdown - call ->shutdown() on each device to shutdown.
*/
void device_shutdown(void)
{
struct device *dev;
spin_lock(&devices_kset->list_lock);
/*
* Walk the devices list backward, shutting down each in turn.
* Beware that device unplug events may also start pulling
* devices offline, even as the system is shutting down.
*/
while (!list_empty(&devices_kset->list)) {
dev = list_entry(devices_kset->list.prev, struct device,
kobj.entry);
get_device(dev);
/*
* Make sure the device is off the kset list, in the
* event that dev->*->shutdown() doesn't remove it.
*/
list_del_init(&dev->kobj.entry);
spin_unlock(&devices_kset->list_lock);
/* Don't allow any more runtime suspends */
pm_runtime_get_noresume(dev);
pm_runtime_barrier(dev);
if (dev->bus && dev->bus->shutdown) {
dev_dbg(dev, "shutdown\n");
dev->bus->shutdown(dev);
} else if (dev->driver && dev->driver->shutdown) {
dev_dbg(dev, "shutdown\n");
dev->driver->shutdown(dev);
}
put_device(dev);
spin_lock(&devices_kset->list_lock);
}
spin_unlock(&devices_kset->list_lock);
async_synchronize_full();
}
/*
* Device logging functions
*/
#ifdef CONFIG_PRINTK
int __dev_printk(const char *level, const struct device *dev,
struct va_format *vaf)
{
if (!dev)
return printk("%s(NULL device *): %pV", level, vaf);
return printk("%s%s %s: %pV",
level, dev_driver_string(dev), dev_name(dev), vaf);
}
EXPORT_SYMBOL(__dev_printk);
int dev_printk(const char *level, const struct device *dev,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
int r;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
r = __dev_printk(level, dev, &vaf);
va_end(args);
return r;
}
EXPORT_SYMBOL(dev_printk);
#define define_dev_printk_level(func, kern_level) \
int func(const struct device *dev, const char *fmt, ...) \
{ \
struct va_format vaf; \
va_list args; \
int r; \
\
va_start(args, fmt); \
\
vaf.fmt = fmt; \
vaf.va = &args; \
\
r = __dev_printk(kern_level, dev, &vaf); \
va_end(args); \
\
return r; \
} \
EXPORT_SYMBOL(func);
define_dev_printk_level(dev_emerg, KERN_EMERG);
define_dev_printk_level(dev_alert, KERN_ALERT);
define_dev_printk_level(dev_crit, KERN_CRIT);
define_dev_printk_level(dev_err, KERN_ERR);
define_dev_printk_level(dev_warn, KERN_WARNING);
define_dev_printk_level(dev_notice, KERN_NOTICE);
define_dev_printk_level(_dev_info, KERN_INFO);
#endif
| gpl-2.0 |
JianguoWEI/Linux-EFQ | drivers/tty/serial/sh-sci.c | 30 | 57540 | /*
* SuperH on-chip serial module support. (SCI with no FIFO / with FIFO)
*
* Copyright (C) 2002 - 2011 Paul Mundt
* Modified to support SH7720 SCIF. Markus Brunner, Mark Jonas (Jul 2007).
*
* based off of the old drivers/char/sh-sci.c by:
*
* Copyright (C) 1999, 2000 Niibe Yutaka
* Copyright (C) 2000 Sugioka Toshinobu
* Modified to support multiple serial ports. Stuart Menefy (May 2000).
* Modified to support SecureEdge. David McCullough (2002)
* Modified to support SH7300 SCIF. Takashi Kusuda (Jun 2003).
* Removed SH7300 support (Jul 2007).
*
* 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.
*/
#if defined(CONFIG_SERIAL_SH_SCI_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#undef DEBUG
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/sysrq.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/console.h>
#include <linux/platform_device.h>
#include <linux/serial_sci.h>
#include <linux/notifier.h>
#include <linux/pm_runtime.h>
#include <linux/cpufreq.h>
#include <linux/clk.h>
#include <linux/ctype.h>
#include <linux/err.h>
#include <linux/dmaengine.h>
#include <linux/dma-mapping.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#ifdef CONFIG_SUPERH
#include <asm/sh_bios.h>
#endif
#include "sh-sci.h"
struct sci_port {
struct uart_port port;
/* Platform configuration */
struct plat_sci_port *cfg;
/* Break timer */
struct timer_list break_timer;
int break_flag;
/* Interface clock */
struct clk *iclk;
/* Function clock */
struct clk *fclk;
char *irqstr[SCIx_NR_IRQS];
char *gpiostr[SCIx_NR_FNS];
struct dma_chan *chan_tx;
struct dma_chan *chan_rx;
#ifdef CONFIG_SERIAL_SH_SCI_DMA
struct dma_async_tx_descriptor *desc_tx;
struct dma_async_tx_descriptor *desc_rx[2];
dma_cookie_t cookie_tx;
dma_cookie_t cookie_rx[2];
dma_cookie_t active_rx;
struct scatterlist sg_tx;
unsigned int sg_len_tx;
struct scatterlist sg_rx[2];
size_t buf_len_rx;
struct sh_dmae_slave param_tx;
struct sh_dmae_slave param_rx;
struct work_struct work_tx;
struct work_struct work_rx;
struct timer_list rx_timer;
unsigned int rx_timeout;
#endif
struct notifier_block freq_transition;
#ifdef CONFIG_SERIAL_SH_SCI_CONSOLE
unsigned short saved_smr;
unsigned short saved_fcr;
unsigned char saved_brr;
#endif
};
/* Function prototypes */
static void sci_start_tx(struct uart_port *port);
static void sci_stop_tx(struct uart_port *port);
static void sci_start_rx(struct uart_port *port);
#define SCI_NPORTS CONFIG_SERIAL_SH_SCI_NR_UARTS
static struct sci_port sci_ports[SCI_NPORTS];
static struct uart_driver sci_uart_driver;
static inline struct sci_port *
to_sci_port(struct uart_port *uart)
{
return container_of(uart, struct sci_port, port);
}
struct plat_sci_reg {
u8 offset, size;
};
/* Helper for invalidating specific entries of an inherited map. */
#define sci_reg_invalid { .offset = 0, .size = 0 }
static struct plat_sci_reg sci_regmap[SCIx_NR_REGTYPES][SCIx_NR_REGS] = {
[SCIx_PROBE_REGTYPE] = {
[0 ... SCIx_NR_REGS - 1] = sci_reg_invalid,
},
/*
* Common SCI definitions, dependent on the port's regshift
* value.
*/
[SCIx_SCI_REGTYPE] = {
[SCSMR] = { 0x00, 8 },
[SCBRR] = { 0x01, 8 },
[SCSCR] = { 0x02, 8 },
[SCxTDR] = { 0x03, 8 },
[SCxSR] = { 0x04, 8 },
[SCxRDR] = { 0x05, 8 },
[SCFCR] = sci_reg_invalid,
[SCFDR] = sci_reg_invalid,
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = sci_reg_invalid,
[SCLSR] = sci_reg_invalid,
},
/*
* Common definitions for legacy IrDA ports, dependent on
* regshift value.
*/
[SCIx_IRDA_REGTYPE] = {
[SCSMR] = { 0x00, 8 },
[SCBRR] = { 0x01, 8 },
[SCSCR] = { 0x02, 8 },
[SCxTDR] = { 0x03, 8 },
[SCxSR] = { 0x04, 8 },
[SCxRDR] = { 0x05, 8 },
[SCFCR] = { 0x06, 8 },
[SCFDR] = { 0x07, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = sci_reg_invalid,
[SCLSR] = sci_reg_invalid,
},
/*
* Common SCIFA definitions.
*/
[SCIx_SCIFA_REGTYPE] = {
[SCSMR] = { 0x00, 16 },
[SCBRR] = { 0x04, 8 },
[SCSCR] = { 0x08, 16 },
[SCxTDR] = { 0x20, 8 },
[SCxSR] = { 0x14, 16 },
[SCxRDR] = { 0x24, 8 },
[SCFCR] = { 0x18, 16 },
[SCFDR] = { 0x1c, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = sci_reg_invalid,
[SCLSR] = sci_reg_invalid,
},
/*
* Common SCIFB definitions.
*/
[SCIx_SCIFB_REGTYPE] = {
[SCSMR] = { 0x00, 16 },
[SCBRR] = { 0x04, 8 },
[SCSCR] = { 0x08, 16 },
[SCxTDR] = { 0x40, 8 },
[SCxSR] = { 0x14, 16 },
[SCxRDR] = { 0x60, 8 },
[SCFCR] = { 0x18, 16 },
[SCFDR] = { 0x1c, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = sci_reg_invalid,
[SCLSR] = sci_reg_invalid,
},
/*
* Common SH-2(A) SCIF definitions for ports with FIFO data
* count registers.
*/
[SCIx_SH2_SCIF_FIFODATA_REGTYPE] = {
[SCSMR] = { 0x00, 16 },
[SCBRR] = { 0x04, 8 },
[SCSCR] = { 0x08, 16 },
[SCxTDR] = { 0x0c, 8 },
[SCxSR] = { 0x10, 16 },
[SCxRDR] = { 0x14, 8 },
[SCFCR] = { 0x18, 16 },
[SCFDR] = { 0x1c, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = { 0x20, 16 },
[SCLSR] = { 0x24, 16 },
},
/*
* Common SH-3 SCIF definitions.
*/
[SCIx_SH3_SCIF_REGTYPE] = {
[SCSMR] = { 0x00, 8 },
[SCBRR] = { 0x02, 8 },
[SCSCR] = { 0x04, 8 },
[SCxTDR] = { 0x06, 8 },
[SCxSR] = { 0x08, 16 },
[SCxRDR] = { 0x0a, 8 },
[SCFCR] = { 0x0c, 8 },
[SCFDR] = { 0x0e, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = sci_reg_invalid,
[SCLSR] = sci_reg_invalid,
},
/*
* Common SH-4(A) SCIF(B) definitions.
*/
[SCIx_SH4_SCIF_REGTYPE] = {
[SCSMR] = { 0x00, 16 },
[SCBRR] = { 0x04, 8 },
[SCSCR] = { 0x08, 16 },
[SCxTDR] = { 0x0c, 8 },
[SCxSR] = { 0x10, 16 },
[SCxRDR] = { 0x14, 8 },
[SCFCR] = { 0x18, 16 },
[SCFDR] = { 0x1c, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = { 0x20, 16 },
[SCLSR] = { 0x24, 16 },
},
/*
* Common SH-4(A) SCIF(B) definitions for ports without an SCSPTR
* register.
*/
[SCIx_SH4_SCIF_NO_SCSPTR_REGTYPE] = {
[SCSMR] = { 0x00, 16 },
[SCBRR] = { 0x04, 8 },
[SCSCR] = { 0x08, 16 },
[SCxTDR] = { 0x0c, 8 },
[SCxSR] = { 0x10, 16 },
[SCxRDR] = { 0x14, 8 },
[SCFCR] = { 0x18, 16 },
[SCFDR] = { 0x1c, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = sci_reg_invalid,
[SCLSR] = { 0x24, 16 },
},
/*
* Common SH-4(A) SCIF(B) definitions for ports with FIFO data
* count registers.
*/
[SCIx_SH4_SCIF_FIFODATA_REGTYPE] = {
[SCSMR] = { 0x00, 16 },
[SCBRR] = { 0x04, 8 },
[SCSCR] = { 0x08, 16 },
[SCxTDR] = { 0x0c, 8 },
[SCxSR] = { 0x10, 16 },
[SCxRDR] = { 0x14, 8 },
[SCFCR] = { 0x18, 16 },
[SCFDR] = { 0x1c, 16 },
[SCTFDR] = { 0x1c, 16 }, /* aliased to SCFDR */
[SCRFDR] = { 0x20, 16 },
[SCSPTR] = { 0x24, 16 },
[SCLSR] = { 0x28, 16 },
},
/*
* SH7705-style SCIF(B) ports, lacking both SCSPTR and SCLSR
* registers.
*/
[SCIx_SH7705_SCIF_REGTYPE] = {
[SCSMR] = { 0x00, 16 },
[SCBRR] = { 0x04, 8 },
[SCSCR] = { 0x08, 16 },
[SCxTDR] = { 0x20, 8 },
[SCxSR] = { 0x14, 16 },
[SCxRDR] = { 0x24, 8 },
[SCFCR] = { 0x18, 16 },
[SCFDR] = { 0x1c, 16 },
[SCTFDR] = sci_reg_invalid,
[SCRFDR] = sci_reg_invalid,
[SCSPTR] = sci_reg_invalid,
[SCLSR] = sci_reg_invalid,
},
};
#define sci_getreg(up, offset) (sci_regmap[to_sci_port(up)->cfg->regtype] + offset)
/*
* The "offset" here is rather misleading, in that it refers to an enum
* value relative to the port mapping rather than the fixed offset
* itself, which needs to be manually retrieved from the platform's
* register map for the given port.
*/
static unsigned int sci_serial_in(struct uart_port *p, int offset)
{
struct plat_sci_reg *reg = sci_getreg(p, offset);
if (reg->size == 8)
return ioread8(p->membase + (reg->offset << p->regshift));
else if (reg->size == 16)
return ioread16(p->membase + (reg->offset << p->regshift));
else
WARN(1, "Invalid register access\n");
return 0;
}
static void sci_serial_out(struct uart_port *p, int offset, int value)
{
struct plat_sci_reg *reg = sci_getreg(p, offset);
if (reg->size == 8)
iowrite8(value, p->membase + (reg->offset << p->regshift));
else if (reg->size == 16)
iowrite16(value, p->membase + (reg->offset << p->regshift));
else
WARN(1, "Invalid register access\n");
}
#define sci_in(up, offset) (up->serial_in(up, offset))
#define sci_out(up, offset, value) (up->serial_out(up, offset, value))
static int sci_probe_regmap(struct plat_sci_port *cfg)
{
switch (cfg->type) {
case PORT_SCI:
cfg->regtype = SCIx_SCI_REGTYPE;
break;
case PORT_IRDA:
cfg->regtype = SCIx_IRDA_REGTYPE;
break;
case PORT_SCIFA:
cfg->regtype = SCIx_SCIFA_REGTYPE;
break;
case PORT_SCIFB:
cfg->regtype = SCIx_SCIFB_REGTYPE;
break;
case PORT_SCIF:
/*
* The SH-4 is a bit of a misnomer here, although that's
* where this particular port layout originated. This
* configuration (or some slight variation thereof)
* remains the dominant model for all SCIFs.
*/
cfg->regtype = SCIx_SH4_SCIF_REGTYPE;
break;
default:
printk(KERN_ERR "Can't probe register map for given port\n");
return -EINVAL;
}
return 0;
}
static void sci_port_enable(struct sci_port *sci_port)
{
if (!sci_port->port.dev)
return;
pm_runtime_get_sync(sci_port->port.dev);
clk_enable(sci_port->iclk);
sci_port->port.uartclk = clk_get_rate(sci_port->iclk);
clk_enable(sci_port->fclk);
}
static void sci_port_disable(struct sci_port *sci_port)
{
if (!sci_port->port.dev)
return;
clk_disable(sci_port->fclk);
clk_disable(sci_port->iclk);
pm_runtime_put_sync(sci_port->port.dev);
}
#if defined(CONFIG_CONSOLE_POLL) || defined(CONFIG_SERIAL_SH_SCI_CONSOLE)
#ifdef CONFIG_CONSOLE_POLL
static int sci_poll_get_char(struct uart_port *port)
{
unsigned short status;
int c;
do {
status = sci_in(port, SCxSR);
if (status & SCxSR_ERRORS(port)) {
sci_out(port, SCxSR, SCxSR_ERROR_CLEAR(port));
continue;
}
break;
} while (1);
if (!(status & SCxSR_RDxF(port)))
return NO_POLL_CHAR;
c = sci_in(port, SCxRDR);
/* Dummy read */
sci_in(port, SCxSR);
sci_out(port, SCxSR, SCxSR_RDxF_CLEAR(port));
return c;
}
#endif
static void sci_poll_put_char(struct uart_port *port, unsigned char c)
{
unsigned short status;
do {
status = sci_in(port, SCxSR);
} while (!(status & SCxSR_TDxE(port)));
sci_out(port, SCxTDR, c);
sci_out(port, SCxSR, SCxSR_TDxE_CLEAR(port) & ~SCxSR_TEND(port));
}
#endif /* CONFIG_CONSOLE_POLL || CONFIG_SERIAL_SH_SCI_CONSOLE */
static void sci_init_pins(struct uart_port *port, unsigned int cflag)
{
struct sci_port *s = to_sci_port(port);
struct plat_sci_reg *reg = sci_regmap[s->cfg->regtype] + SCSPTR;
/*
* Use port-specific handler if provided.
*/
if (s->cfg->ops && s->cfg->ops->init_pins) {
s->cfg->ops->init_pins(port, cflag);
return;
}
/*
* For the generic path SCSPTR is necessary. Bail out if that's
* unavailable, too.
*/
if (!reg->size)
return;
if ((s->cfg->capabilities & SCIx_HAVE_RTSCTS) &&
((!(cflag & CRTSCTS)))) {
unsigned short status;
status = sci_in(port, SCSPTR);
status &= ~SCSPTR_CTSIO;
status |= SCSPTR_RTSIO;
sci_out(port, SCSPTR, status); /* Set RTS = 1 */
}
}
static int sci_txfill(struct uart_port *port)
{
struct plat_sci_reg *reg;
reg = sci_getreg(port, SCTFDR);
if (reg->size)
return sci_in(port, SCTFDR) & 0xff;
reg = sci_getreg(port, SCFDR);
if (reg->size)
return sci_in(port, SCFDR) >> 8;
return !(sci_in(port, SCxSR) & SCI_TDRE);
}
static int sci_txroom(struct uart_port *port)
{
return port->fifosize - sci_txfill(port);
}
static int sci_rxfill(struct uart_port *port)
{
struct plat_sci_reg *reg;
reg = sci_getreg(port, SCRFDR);
if (reg->size)
return sci_in(port, SCRFDR) & 0xff;
reg = sci_getreg(port, SCFDR);
if (reg->size)
return sci_in(port, SCFDR) & ((port->fifosize << 1) - 1);
return (sci_in(port, SCxSR) & SCxSR_RDxF(port)) != 0;
}
/*
* SCI helper for checking the state of the muxed port/RXD pins.
*/
static inline int sci_rxd_in(struct uart_port *port)
{
struct sci_port *s = to_sci_port(port);
if (s->cfg->port_reg <= 0)
return 1;
return !!__raw_readb(s->cfg->port_reg);
}
/* ********************************************************************** *
* the interrupt related routines *
* ********************************************************************** */
static void sci_transmit_chars(struct uart_port *port)
{
struct circ_buf *xmit = &port->state->xmit;
unsigned int stopped = uart_tx_stopped(port);
unsigned short status;
unsigned short ctrl;
int count;
status = sci_in(port, SCxSR);
if (!(status & SCxSR_TDxE(port))) {
ctrl = sci_in(port, SCSCR);
if (uart_circ_empty(xmit))
ctrl &= ~SCSCR_TIE;
else
ctrl |= SCSCR_TIE;
sci_out(port, SCSCR, ctrl);
return;
}
count = sci_txroom(port);
do {
unsigned char c;
if (port->x_char) {
c = port->x_char;
port->x_char = 0;
} else if (!uart_circ_empty(xmit) && !stopped) {
c = xmit->buf[xmit->tail];
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
} else {
break;
}
sci_out(port, SCxTDR, c);
port->icount.tx++;
} while (--count > 0);
sci_out(port, SCxSR, SCxSR_TDxE_CLEAR(port));
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(port);
if (uart_circ_empty(xmit)) {
sci_stop_tx(port);
} else {
ctrl = sci_in(port, SCSCR);
if (port->type != PORT_SCI) {
sci_in(port, SCxSR); /* Dummy read */
sci_out(port, SCxSR, SCxSR_TDxE_CLEAR(port));
}
ctrl |= SCSCR_TIE;
sci_out(port, SCSCR, ctrl);
}
}
/* On SH3, SCIF may read end-of-break as a space->mark char */
#define STEPFN(c) ({int __c = (c); (((__c-1)|(__c)) == -1); })
static void sci_receive_chars(struct uart_port *port)
{
struct sci_port *sci_port = to_sci_port(port);
struct tty_struct *tty = port->state->port.tty;
int i, count, copied = 0;
unsigned short status;
unsigned char flag;
status = sci_in(port, SCxSR);
if (!(status & SCxSR_RDxF(port)))
return;
while (1) {
/* Don't copy more bytes than there is room for in the buffer */
count = tty_buffer_request_room(tty, sci_rxfill(port));
/* If for any reason we can't copy more data, we're done! */
if (count == 0)
break;
if (port->type == PORT_SCI) {
char c = sci_in(port, SCxRDR);
if (uart_handle_sysrq_char(port, c) ||
sci_port->break_flag)
count = 0;
else
tty_insert_flip_char(tty, c, TTY_NORMAL);
} else {
for (i = 0; i < count; i++) {
char c = sci_in(port, SCxRDR);
status = sci_in(port, SCxSR);
#if defined(CONFIG_CPU_SH3)
/* Skip "chars" during break */
if (sci_port->break_flag) {
if ((c == 0) &&
(status & SCxSR_FER(port))) {
count--; i--;
continue;
}
/* Nonzero => end-of-break */
dev_dbg(port->dev, "debounce<%02x>\n", c);
sci_port->break_flag = 0;
if (STEPFN(c)) {
count--; i--;
continue;
}
}
#endif /* CONFIG_CPU_SH3 */
if (uart_handle_sysrq_char(port, c)) {
count--; i--;
continue;
}
/* Store data and status */
if (status & SCxSR_FER(port)) {
flag = TTY_FRAME;
port->icount.frame++;
dev_notice(port->dev, "frame error\n");
} else if (status & SCxSR_PER(port)) {
flag = TTY_PARITY;
port->icount.parity++;
dev_notice(port->dev, "parity error\n");
} else
flag = TTY_NORMAL;
tty_insert_flip_char(tty, c, flag);
}
}
sci_in(port, SCxSR); /* dummy read */
sci_out(port, SCxSR, SCxSR_RDxF_CLEAR(port));
copied += count;
port->icount.rx += count;
}
if (copied) {
/* Tell the rest of the system the news. New characters! */
tty_flip_buffer_push(tty);
} else {
sci_in(port, SCxSR); /* dummy read */
sci_out(port, SCxSR, SCxSR_RDxF_CLEAR(port));
}
}
#define SCI_BREAK_JIFFIES (HZ/20)
/*
* The sci generates interrupts during the break,
* 1 per millisecond or so during the break period, for 9600 baud.
* So dont bother disabling interrupts.
* But dont want more than 1 break event.
* Use a kernel timer to periodically poll the rx line until
* the break is finished.
*/
static inline void sci_schedule_break_timer(struct sci_port *port)
{
mod_timer(&port->break_timer, jiffies + SCI_BREAK_JIFFIES);
}
/* Ensure that two consecutive samples find the break over. */
static void sci_break_timer(unsigned long data)
{
struct sci_port *port = (struct sci_port *)data;
sci_port_enable(port);
if (sci_rxd_in(&port->port) == 0) {
port->break_flag = 1;
sci_schedule_break_timer(port);
} else if (port->break_flag == 1) {
/* break is over. */
port->break_flag = 2;
sci_schedule_break_timer(port);
} else
port->break_flag = 0;
sci_port_disable(port);
}
static int sci_handle_errors(struct uart_port *port)
{
int copied = 0;
unsigned short status = sci_in(port, SCxSR);
struct tty_struct *tty = port->state->port.tty;
struct sci_port *s = to_sci_port(port);
/*
* Handle overruns, if supported.
*/
if (s->cfg->overrun_bit != SCIx_NOT_SUPPORTED) {
if (status & (1 << s->cfg->overrun_bit)) {
port->icount.overrun++;
/* overrun error */
if (tty_insert_flip_char(tty, 0, TTY_OVERRUN))
copied++;
dev_notice(port->dev, "overrun error");
}
}
if (status & SCxSR_FER(port)) {
if (sci_rxd_in(port) == 0) {
/* Notify of BREAK */
struct sci_port *sci_port = to_sci_port(port);
if (!sci_port->break_flag) {
port->icount.brk++;
sci_port->break_flag = 1;
sci_schedule_break_timer(sci_port);
/* Do sysrq handling. */
if (uart_handle_break(port))
return 0;
dev_dbg(port->dev, "BREAK detected\n");
if (tty_insert_flip_char(tty, 0, TTY_BREAK))
copied++;
}
} else {
/* frame error */
port->icount.frame++;
if (tty_insert_flip_char(tty, 0, TTY_FRAME))
copied++;
dev_notice(port->dev, "frame error\n");
}
}
if (status & SCxSR_PER(port)) {
/* parity error */
port->icount.parity++;
if (tty_insert_flip_char(tty, 0, TTY_PARITY))
copied++;
dev_notice(port->dev, "parity error");
}
if (copied)
tty_flip_buffer_push(tty);
return copied;
}
static int sci_handle_fifo_overrun(struct uart_port *port)
{
struct tty_struct *tty = port->state->port.tty;
struct sci_port *s = to_sci_port(port);
struct plat_sci_reg *reg;
int copied = 0;
reg = sci_getreg(port, SCLSR);
if (!reg->size)
return 0;
if ((sci_in(port, SCLSR) & (1 << s->cfg->overrun_bit))) {
sci_out(port, SCLSR, 0);
port->icount.overrun++;
tty_insert_flip_char(tty, 0, TTY_OVERRUN);
tty_flip_buffer_push(tty);
dev_notice(port->dev, "overrun error\n");
copied++;
}
return copied;
}
static int sci_handle_breaks(struct uart_port *port)
{
int copied = 0;
unsigned short status = sci_in(port, SCxSR);
struct tty_struct *tty = port->state->port.tty;
struct sci_port *s = to_sci_port(port);
if (uart_handle_break(port))
return 0;
if (!s->break_flag && status & SCxSR_BRK(port)) {
#if defined(CONFIG_CPU_SH3)
/* Debounce break */
s->break_flag = 1;
#endif
port->icount.brk++;
/* Notify of BREAK */
if (tty_insert_flip_char(tty, 0, TTY_BREAK))
copied++;
dev_dbg(port->dev, "BREAK detected\n");
}
if (copied)
tty_flip_buffer_push(tty);
copied += sci_handle_fifo_overrun(port);
return copied;
}
static irqreturn_t sci_rx_interrupt(int irq, void *ptr)
{
#ifdef CONFIG_SERIAL_SH_SCI_DMA
struct uart_port *port = ptr;
struct sci_port *s = to_sci_port(port);
if (s->chan_rx) {
u16 scr = sci_in(port, SCSCR);
u16 ssr = sci_in(port, SCxSR);
/* Disable future Rx interrupts */
if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
disable_irq_nosync(irq);
scr |= 0x4000;
} else {
scr &= ~SCSCR_RIE;
}
sci_out(port, SCSCR, scr);
/* Clear current interrupt */
sci_out(port, SCxSR, ssr & ~(1 | SCxSR_RDxF(port)));
dev_dbg(port->dev, "Rx IRQ %lu: setup t-out in %u jiffies\n",
jiffies, s->rx_timeout);
mod_timer(&s->rx_timer, jiffies + s->rx_timeout);
return IRQ_HANDLED;
}
#endif
/* I think sci_receive_chars has to be called irrespective
* of whether the I_IXOFF is set, otherwise, how is the interrupt
* to be disabled?
*/
sci_receive_chars(ptr);
return IRQ_HANDLED;
}
static irqreturn_t sci_tx_interrupt(int irq, void *ptr)
{
struct uart_port *port = ptr;
unsigned long flags;
spin_lock_irqsave(&port->lock, flags);
sci_transmit_chars(port);
spin_unlock_irqrestore(&port->lock, flags);
return IRQ_HANDLED;
}
static irqreturn_t sci_er_interrupt(int irq, void *ptr)
{
struct uart_port *port = ptr;
/* Handle errors */
if (port->type == PORT_SCI) {
if (sci_handle_errors(port)) {
/* discard character in rx buffer */
sci_in(port, SCxSR);
sci_out(port, SCxSR, SCxSR_RDxF_CLEAR(port));
}
} else {
sci_handle_fifo_overrun(port);
sci_rx_interrupt(irq, ptr);
}
sci_out(port, SCxSR, SCxSR_ERROR_CLEAR(port));
/* Kick the transmission */
sci_tx_interrupt(irq, ptr);
return IRQ_HANDLED;
}
static irqreturn_t sci_br_interrupt(int irq, void *ptr)
{
struct uart_port *port = ptr;
/* Handle BREAKs */
sci_handle_breaks(port);
sci_out(port, SCxSR, SCxSR_BREAK_CLEAR(port));
return IRQ_HANDLED;
}
static inline unsigned long port_rx_irq_mask(struct uart_port *port)
{
/*
* Not all ports (such as SCIFA) will support REIE. Rather than
* special-casing the port type, we check the port initialization
* IRQ enable mask to see whether the IRQ is desired at all. If
* it's unset, it's logically inferred that there's no point in
* testing for it.
*/
return SCSCR_RIE | (to_sci_port(port)->cfg->scscr & SCSCR_REIE);
}
static irqreturn_t sci_mpxed_interrupt(int irq, void *ptr)
{
unsigned short ssr_status, scr_status, err_enabled;
struct uart_port *port = ptr;
struct sci_port *s = to_sci_port(port);
irqreturn_t ret = IRQ_NONE;
ssr_status = sci_in(port, SCxSR);
scr_status = sci_in(port, SCSCR);
err_enabled = scr_status & port_rx_irq_mask(port);
/* Tx Interrupt */
if ((ssr_status & SCxSR_TDxE(port)) && (scr_status & SCSCR_TIE) &&
!s->chan_tx)
ret = sci_tx_interrupt(irq, ptr);
/*
* Rx Interrupt: if we're using DMA, the DMA controller clears RDF /
* DR flags
*/
if (((ssr_status & SCxSR_RDxF(port)) || s->chan_rx) &&
(scr_status & SCSCR_RIE))
ret = sci_rx_interrupt(irq, ptr);
/* Error Interrupt */
if ((ssr_status & SCxSR_ERRORS(port)) && err_enabled)
ret = sci_er_interrupt(irq, ptr);
/* Break Interrupt */
if ((ssr_status & SCxSR_BRK(port)) && err_enabled)
ret = sci_br_interrupt(irq, ptr);
return ret;
}
/*
* Here we define a transition notifier so that we can update all of our
* ports' baud rate when the peripheral clock changes.
*/
static int sci_notifier(struct notifier_block *self,
unsigned long phase, void *p)
{
struct sci_port *sci_port;
unsigned long flags;
sci_port = container_of(self, struct sci_port, freq_transition);
if ((phase == CPUFREQ_POSTCHANGE) ||
(phase == CPUFREQ_RESUMECHANGE)) {
struct uart_port *port = &sci_port->port;
spin_lock_irqsave(&port->lock, flags);
port->uartclk = clk_get_rate(sci_port->iclk);
spin_unlock_irqrestore(&port->lock, flags);
}
return NOTIFY_OK;
}
static struct sci_irq_desc {
const char *desc;
irq_handler_t handler;
} sci_irq_desc[] = {
/*
* Split out handlers, the default case.
*/
[SCIx_ERI_IRQ] = {
.desc = "rx err",
.handler = sci_er_interrupt,
},
[SCIx_RXI_IRQ] = {
.desc = "rx full",
.handler = sci_rx_interrupt,
},
[SCIx_TXI_IRQ] = {
.desc = "tx empty",
.handler = sci_tx_interrupt,
},
[SCIx_BRI_IRQ] = {
.desc = "break",
.handler = sci_br_interrupt,
},
/*
* Special muxed handler.
*/
[SCIx_MUX_IRQ] = {
.desc = "mux",
.handler = sci_mpxed_interrupt,
},
};
static int sci_request_irq(struct sci_port *port)
{
struct uart_port *up = &port->port;
int i, j, ret = 0;
for (i = j = 0; i < SCIx_NR_IRQS; i++, j++) {
struct sci_irq_desc *desc;
unsigned int irq;
if (SCIx_IRQ_IS_MUXED(port)) {
i = SCIx_MUX_IRQ;
irq = up->irq;
} else
irq = port->cfg->irqs[i];
desc = sci_irq_desc + i;
port->irqstr[j] = kasprintf(GFP_KERNEL, "%s:%s",
dev_name(up->dev), desc->desc);
if (!port->irqstr[j]) {
dev_err(up->dev, "Failed to allocate %s IRQ string\n",
desc->desc);
goto out_nomem;
}
ret = request_irq(irq, desc->handler, up->irqflags,
port->irqstr[j], port);
if (unlikely(ret)) {
dev_err(up->dev, "Can't allocate %s IRQ\n", desc->desc);
goto out_noirq;
}
}
return 0;
out_noirq:
while (--i >= 0)
free_irq(port->cfg->irqs[i], port);
out_nomem:
while (--j >= 0)
kfree(port->irqstr[j]);
return ret;
}
static void sci_free_irq(struct sci_port *port)
{
int i;
/*
* Intentionally in reverse order so we iterate over the muxed
* IRQ first.
*/
for (i = 0; i < SCIx_NR_IRQS; i++) {
free_irq(port->cfg->irqs[i], port);
kfree(port->irqstr[i]);
if (SCIx_IRQ_IS_MUXED(port)) {
/* If there's only one IRQ, we're done. */
return;
}
}
}
static const char *sci_gpio_names[SCIx_NR_FNS] = {
"sck", "rxd", "txd", "cts", "rts",
};
static const char *sci_gpio_str(unsigned int index)
{
return sci_gpio_names[index];
}
static void __devinit sci_init_gpios(struct sci_port *port)
{
struct uart_port *up = &port->port;
int i;
if (!port->cfg)
return;
for (i = 0; i < SCIx_NR_FNS; i++) {
const char *desc;
int ret;
if (!port->cfg->gpios[i])
continue;
desc = sci_gpio_str(i);
port->gpiostr[i] = kasprintf(GFP_KERNEL, "%s:%s",
dev_name(up->dev), desc);
/*
* If we've failed the allocation, we can still continue
* on with a NULL string.
*/
if (!port->gpiostr[i])
dev_notice(up->dev, "%s string allocation failure\n",
desc);
ret = gpio_request(port->cfg->gpios[i], port->gpiostr[i]);
if (unlikely(ret != 0)) {
dev_notice(up->dev, "failed %s gpio request\n", desc);
/*
* If we can't get the GPIO for whatever reason,
* no point in keeping the verbose string around.
*/
kfree(port->gpiostr[i]);
}
}
}
static void sci_free_gpios(struct sci_port *port)
{
int i;
for (i = 0; i < SCIx_NR_FNS; i++)
if (port->cfg->gpios[i]) {
gpio_free(port->cfg->gpios[i]);
kfree(port->gpiostr[i]);
}
}
static unsigned int sci_tx_empty(struct uart_port *port)
{
unsigned short status = sci_in(port, SCxSR);
unsigned short in_tx_fifo = sci_txfill(port);
return (status & SCxSR_TEND(port)) && !in_tx_fifo ? TIOCSER_TEMT : 0;
}
/*
* Modem control is a bit of a mixed bag for SCI(F) ports. Generally
* CTS/RTS is supported in hardware by at least one port and controlled
* via SCSPTR (SCxPCR for SCIFA/B parts), or external pins (presently
* handled via the ->init_pins() op, which is a bit of a one-way street,
* lacking any ability to defer pin control -- this will later be
* converted over to the GPIO framework).
*
* Other modes (such as loopback) are supported generically on certain
* port types, but not others. For these it's sufficient to test for the
* existence of the support register and simply ignore the port type.
*/
static void sci_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
if (mctrl & TIOCM_LOOP) {
struct plat_sci_reg *reg;
/*
* Standard loopback mode for SCFCR ports.
*/
reg = sci_getreg(port, SCFCR);
if (reg->size)
sci_out(port, SCFCR, sci_in(port, SCFCR) | 1);
}
}
static unsigned int sci_get_mctrl(struct uart_port *port)
{
/*
* CTS/RTS is handled in hardware when supported, while nothing
* else is wired up. Keep it simple and simply assert DSR/CAR.
*/
return TIOCM_DSR | TIOCM_CAR;
}
#ifdef CONFIG_SERIAL_SH_SCI_DMA
static void sci_dma_tx_complete(void *arg)
{
struct sci_port *s = arg;
struct uart_port *port = &s->port;
struct circ_buf *xmit = &port->state->xmit;
unsigned long flags;
dev_dbg(port->dev, "%s(%d)\n", __func__, port->line);
spin_lock_irqsave(&port->lock, flags);
xmit->tail += sg_dma_len(&s->sg_tx);
xmit->tail &= UART_XMIT_SIZE - 1;
port->icount.tx += sg_dma_len(&s->sg_tx);
async_tx_ack(s->desc_tx);
s->cookie_tx = -EINVAL;
s->desc_tx = NULL;
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(port);
if (!uart_circ_empty(xmit)) {
schedule_work(&s->work_tx);
} else if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
u16 ctrl = sci_in(port, SCSCR);
sci_out(port, SCSCR, ctrl & ~SCSCR_TIE);
}
spin_unlock_irqrestore(&port->lock, flags);
}
/* Locking: called with port lock held */
static int sci_dma_rx_push(struct sci_port *s, struct tty_struct *tty,
size_t count)
{
struct uart_port *port = &s->port;
int i, active, room;
room = tty_buffer_request_room(tty, count);
if (s->active_rx == s->cookie_rx[0]) {
active = 0;
} else if (s->active_rx == s->cookie_rx[1]) {
active = 1;
} else {
dev_err(port->dev, "cookie %d not found!\n", s->active_rx);
return 0;
}
if (room < count)
dev_warn(port->dev, "Rx overrun: dropping %u bytes\n",
count - room);
if (!room)
return room;
for (i = 0; i < room; i++)
tty_insert_flip_char(tty, ((u8 *)sg_virt(&s->sg_rx[active]))[i],
TTY_NORMAL);
port->icount.rx += room;
return room;
}
static void sci_dma_rx_complete(void *arg)
{
struct sci_port *s = arg;
struct uart_port *port = &s->port;
struct tty_struct *tty = port->state->port.tty;
unsigned long flags;
int count;
dev_dbg(port->dev, "%s(%d) active #%d\n", __func__, port->line, s->active_rx);
spin_lock_irqsave(&port->lock, flags);
count = sci_dma_rx_push(s, tty, s->buf_len_rx);
mod_timer(&s->rx_timer, jiffies + s->rx_timeout);
spin_unlock_irqrestore(&port->lock, flags);
if (count)
tty_flip_buffer_push(tty);
schedule_work(&s->work_rx);
}
static void sci_rx_dma_release(struct sci_port *s, bool enable_pio)
{
struct dma_chan *chan = s->chan_rx;
struct uart_port *port = &s->port;
s->chan_rx = NULL;
s->cookie_rx[0] = s->cookie_rx[1] = -EINVAL;
dma_release_channel(chan);
if (sg_dma_address(&s->sg_rx[0]))
dma_free_coherent(port->dev, s->buf_len_rx * 2,
sg_virt(&s->sg_rx[0]), sg_dma_address(&s->sg_rx[0]));
if (enable_pio)
sci_start_rx(port);
}
static void sci_tx_dma_release(struct sci_port *s, bool enable_pio)
{
struct dma_chan *chan = s->chan_tx;
struct uart_port *port = &s->port;
s->chan_tx = NULL;
s->cookie_tx = -EINVAL;
dma_release_channel(chan);
if (enable_pio)
sci_start_tx(port);
}
static void sci_submit_rx(struct sci_port *s)
{
struct dma_chan *chan = s->chan_rx;
int i;
for (i = 0; i < 2; i++) {
struct scatterlist *sg = &s->sg_rx[i];
struct dma_async_tx_descriptor *desc;
desc = chan->device->device_prep_slave_sg(chan,
sg, 1, DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT);
if (desc) {
s->desc_rx[i] = desc;
desc->callback = sci_dma_rx_complete;
desc->callback_param = s;
s->cookie_rx[i] = desc->tx_submit(desc);
}
if (!desc || s->cookie_rx[i] < 0) {
if (i) {
async_tx_ack(s->desc_rx[0]);
s->cookie_rx[0] = -EINVAL;
}
if (desc) {
async_tx_ack(desc);
s->cookie_rx[i] = -EINVAL;
}
dev_warn(s->port.dev,
"failed to re-start DMA, using PIO\n");
sci_rx_dma_release(s, true);
return;
}
dev_dbg(s->port.dev, "%s(): cookie %d to #%d\n", __func__,
s->cookie_rx[i], i);
}
s->active_rx = s->cookie_rx[0];
dma_async_issue_pending(chan);
}
static void work_fn_rx(struct work_struct *work)
{
struct sci_port *s = container_of(work, struct sci_port, work_rx);
struct uart_port *port = &s->port;
struct dma_async_tx_descriptor *desc;
int new;
if (s->active_rx == s->cookie_rx[0]) {
new = 0;
} else if (s->active_rx == s->cookie_rx[1]) {
new = 1;
} else {
dev_err(port->dev, "cookie %d not found!\n", s->active_rx);
return;
}
desc = s->desc_rx[new];
if (dma_async_is_tx_complete(s->chan_rx, s->active_rx, NULL, NULL) !=
DMA_SUCCESS) {
/* Handle incomplete DMA receive */
struct tty_struct *tty = port->state->port.tty;
struct dma_chan *chan = s->chan_rx;
struct sh_desc *sh_desc = container_of(desc, struct sh_desc,
async_tx);
unsigned long flags;
int count;
chan->device->device_control(chan, DMA_TERMINATE_ALL, 0);
dev_dbg(port->dev, "Read %u bytes with cookie %d\n",
sh_desc->partial, sh_desc->cookie);
spin_lock_irqsave(&port->lock, flags);
count = sci_dma_rx_push(s, tty, sh_desc->partial);
spin_unlock_irqrestore(&port->lock, flags);
if (count)
tty_flip_buffer_push(tty);
sci_submit_rx(s);
return;
}
s->cookie_rx[new] = desc->tx_submit(desc);
if (s->cookie_rx[new] < 0) {
dev_warn(port->dev, "Failed submitting Rx DMA descriptor\n");
sci_rx_dma_release(s, true);
return;
}
s->active_rx = s->cookie_rx[!new];
dev_dbg(port->dev, "%s: cookie %d #%d, new active #%d\n", __func__,
s->cookie_rx[new], new, s->active_rx);
}
static void work_fn_tx(struct work_struct *work)
{
struct sci_port *s = container_of(work, struct sci_port, work_tx);
struct dma_async_tx_descriptor *desc;
struct dma_chan *chan = s->chan_tx;
struct uart_port *port = &s->port;
struct circ_buf *xmit = &port->state->xmit;
struct scatterlist *sg = &s->sg_tx;
/*
* DMA is idle now.
* Port xmit buffer is already mapped, and it is one page... Just adjust
* offsets and lengths. Since it is a circular buffer, we have to
* transmit till the end, and then the rest. Take the port lock to get a
* consistent xmit buffer state.
*/
spin_lock_irq(&port->lock);
sg->offset = xmit->tail & (UART_XMIT_SIZE - 1);
sg_dma_address(sg) = (sg_dma_address(sg) & ~(UART_XMIT_SIZE - 1)) +
sg->offset;
sg_dma_len(sg) = min((int)CIRC_CNT(xmit->head, xmit->tail, UART_XMIT_SIZE),
CIRC_CNT_TO_END(xmit->head, xmit->tail, UART_XMIT_SIZE));
spin_unlock_irq(&port->lock);
BUG_ON(!sg_dma_len(sg));
desc = chan->device->device_prep_slave_sg(chan,
sg, s->sg_len_tx, DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc) {
/* switch to PIO */
sci_tx_dma_release(s, true);
return;
}
dma_sync_sg_for_device(port->dev, sg, 1, DMA_TO_DEVICE);
spin_lock_irq(&port->lock);
s->desc_tx = desc;
desc->callback = sci_dma_tx_complete;
desc->callback_param = s;
spin_unlock_irq(&port->lock);
s->cookie_tx = desc->tx_submit(desc);
if (s->cookie_tx < 0) {
dev_warn(port->dev, "Failed submitting Tx DMA descriptor\n");
/* switch to PIO */
sci_tx_dma_release(s, true);
return;
}
dev_dbg(port->dev, "%s: %p: %d...%d, cookie %d\n", __func__,
xmit->buf, xmit->tail, xmit->head, s->cookie_tx);
dma_async_issue_pending(chan);
}
#endif
static void sci_start_tx(struct uart_port *port)
{
struct sci_port *s = to_sci_port(port);
unsigned short ctrl;
#ifdef CONFIG_SERIAL_SH_SCI_DMA
if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
u16 new, scr = sci_in(port, SCSCR);
if (s->chan_tx)
new = scr | 0x8000;
else
new = scr & ~0x8000;
if (new != scr)
sci_out(port, SCSCR, new);
}
if (s->chan_tx && !uart_circ_empty(&s->port.state->xmit) &&
s->cookie_tx < 0)
schedule_work(&s->work_tx);
#endif
if (!s->chan_tx || port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
/* Set TIE (Transmit Interrupt Enable) bit in SCSCR */
ctrl = sci_in(port, SCSCR);
sci_out(port, SCSCR, ctrl | SCSCR_TIE);
}
}
static void sci_stop_tx(struct uart_port *port)
{
unsigned short ctrl;
/* Clear TIE (Transmit Interrupt Enable) bit in SCSCR */
ctrl = sci_in(port, SCSCR);
if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
ctrl &= ~0x8000;
ctrl &= ~SCSCR_TIE;
sci_out(port, SCSCR, ctrl);
}
static void sci_start_rx(struct uart_port *port)
{
unsigned short ctrl;
ctrl = sci_in(port, SCSCR) | port_rx_irq_mask(port);
if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
ctrl &= ~0x4000;
sci_out(port, SCSCR, ctrl);
}
static void sci_stop_rx(struct uart_port *port)
{
unsigned short ctrl;
ctrl = sci_in(port, SCSCR);
if (port->type == PORT_SCIFA || port->type == PORT_SCIFB)
ctrl &= ~0x4000;
ctrl &= ~port_rx_irq_mask(port);
sci_out(port, SCSCR, ctrl);
}
static void sci_enable_ms(struct uart_port *port)
{
/*
* Not supported by hardware, always a nop.
*/
}
static void sci_break_ctl(struct uart_port *port, int break_state)
{
/*
* Not supported by hardware. Most parts couple break and rx
* interrupts together, with break detection always enabled.
*/
}
#ifdef CONFIG_SERIAL_SH_SCI_DMA
static bool filter(struct dma_chan *chan, void *slave)
{
struct sh_dmae_slave *param = slave;
dev_dbg(chan->device->dev, "%s: slave ID %d\n", __func__,
param->slave_id);
chan->private = param;
return true;
}
static void rx_timer_fn(unsigned long arg)
{
struct sci_port *s = (struct sci_port *)arg;
struct uart_port *port = &s->port;
u16 scr = sci_in(port, SCSCR);
if (port->type == PORT_SCIFA || port->type == PORT_SCIFB) {
scr &= ~0x4000;
enable_irq(s->cfg->irqs[1]);
}
sci_out(port, SCSCR, scr | SCSCR_RIE);
dev_dbg(port->dev, "DMA Rx timed out\n");
schedule_work(&s->work_rx);
}
static void sci_request_dma(struct uart_port *port)
{
struct sci_port *s = to_sci_port(port);
struct sh_dmae_slave *param;
struct dma_chan *chan;
dma_cap_mask_t mask;
int nent;
dev_dbg(port->dev, "%s: port %d\n", __func__,
port->line);
if (s->cfg->dma_slave_tx <= 0 || s->cfg->dma_slave_rx <= 0)
return;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
param = &s->param_tx;
/* Slave ID, e.g., SHDMA_SLAVE_SCIF0_TX */
param->slave_id = s->cfg->dma_slave_tx;
s->cookie_tx = -EINVAL;
chan = dma_request_channel(mask, filter, param);
dev_dbg(port->dev, "%s: TX: got channel %p\n", __func__, chan);
if (chan) {
s->chan_tx = chan;
sg_init_table(&s->sg_tx, 1);
/* UART circular tx buffer is an aligned page. */
BUG_ON((int)port->state->xmit.buf & ~PAGE_MASK);
sg_set_page(&s->sg_tx, virt_to_page(port->state->xmit.buf),
UART_XMIT_SIZE, (int)port->state->xmit.buf & ~PAGE_MASK);
nent = dma_map_sg(port->dev, &s->sg_tx, 1, DMA_TO_DEVICE);
if (!nent)
sci_tx_dma_release(s, false);
else
dev_dbg(port->dev, "%s: mapped %d@%p to %x\n", __func__,
sg_dma_len(&s->sg_tx),
port->state->xmit.buf, sg_dma_address(&s->sg_tx));
s->sg_len_tx = nent;
INIT_WORK(&s->work_tx, work_fn_tx);
}
param = &s->param_rx;
/* Slave ID, e.g., SHDMA_SLAVE_SCIF0_RX */
param->slave_id = s->cfg->dma_slave_rx;
chan = dma_request_channel(mask, filter, param);
dev_dbg(port->dev, "%s: RX: got channel %p\n", __func__, chan);
if (chan) {
dma_addr_t dma[2];
void *buf[2];
int i;
s->chan_rx = chan;
s->buf_len_rx = 2 * max(16, (int)port->fifosize);
buf[0] = dma_alloc_coherent(port->dev, s->buf_len_rx * 2,
&dma[0], GFP_KERNEL);
if (!buf[0]) {
dev_warn(port->dev,
"failed to allocate dma buffer, using PIO\n");
sci_rx_dma_release(s, true);
return;
}
buf[1] = buf[0] + s->buf_len_rx;
dma[1] = dma[0] + s->buf_len_rx;
for (i = 0; i < 2; i++) {
struct scatterlist *sg = &s->sg_rx[i];
sg_init_table(sg, 1);
sg_set_page(sg, virt_to_page(buf[i]), s->buf_len_rx,
(int)buf[i] & ~PAGE_MASK);
sg_dma_address(sg) = dma[i];
}
INIT_WORK(&s->work_rx, work_fn_rx);
setup_timer(&s->rx_timer, rx_timer_fn, (unsigned long)s);
sci_submit_rx(s);
}
}
static void sci_free_dma(struct uart_port *port)
{
struct sci_port *s = to_sci_port(port);
if (s->chan_tx)
sci_tx_dma_release(s, false);
if (s->chan_rx)
sci_rx_dma_release(s, false);
}
#else
static inline void sci_request_dma(struct uart_port *port)
{
}
static inline void sci_free_dma(struct uart_port *port)
{
}
#endif
static int sci_startup(struct uart_port *port)
{
struct sci_port *s = to_sci_port(port);
int ret;
dev_dbg(port->dev, "%s(%d)\n", __func__, port->line);
sci_port_enable(s);
ret = sci_request_irq(s);
if (unlikely(ret < 0))
return ret;
sci_request_dma(port);
sci_start_tx(port);
sci_start_rx(port);
return 0;
}
static void sci_shutdown(struct uart_port *port)
{
struct sci_port *s = to_sci_port(port);
dev_dbg(port->dev, "%s(%d)\n", __func__, port->line);
sci_stop_rx(port);
sci_stop_tx(port);
sci_free_dma(port);
sci_free_irq(s);
sci_port_disable(s);
}
static unsigned int sci_scbrr_calc(unsigned int algo_id, unsigned int bps,
unsigned long freq)
{
switch (algo_id) {
case SCBRR_ALGO_1:
return ((freq + 16 * bps) / (16 * bps) - 1);
case SCBRR_ALGO_2:
return ((freq + 16 * bps) / (32 * bps) - 1);
case SCBRR_ALGO_3:
return (((freq * 2) + 16 * bps) / (16 * bps) - 1);
case SCBRR_ALGO_4:
return (((freq * 2) + 16 * bps) / (32 * bps) - 1);
case SCBRR_ALGO_5:
return (((freq * 1000 / 32) / bps) - 1);
}
/* Warn, but use a safe default */
WARN_ON(1);
return ((freq + 16 * bps) / (32 * bps) - 1);
}
static void sci_reset(struct uart_port *port)
{
struct plat_sci_reg *reg;
unsigned int status;
do {
status = sci_in(port, SCxSR);
} while (!(status & SCxSR_TEND(port)));
sci_out(port, SCSCR, 0x00); /* TE=0, RE=0, CKE1=0 */
reg = sci_getreg(port, SCFCR);
if (reg->size)
sci_out(port, SCFCR, SCFCR_RFRST | SCFCR_TFRST);
}
static void sci_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
struct sci_port *s = to_sci_port(port);
struct plat_sci_reg *reg;
unsigned int baud, smr_val, max_baud;
int t = -1;
/*
* earlyprintk comes here early on with port->uartclk set to zero.
* the clock framework is not up and running at this point so here
* we assume that 115200 is the maximum baud rate. please note that
* the baud rate is not programmed during earlyprintk - it is assumed
* that the previous boot loader has enabled required clocks and
* setup the baud rate generator hardware for us already.
*/
max_baud = port->uartclk ? port->uartclk / 16 : 115200;
baud = uart_get_baud_rate(port, termios, old, 0, max_baud);
if (likely(baud && port->uartclk))
t = sci_scbrr_calc(s->cfg->scbrr_algo_id, baud, port->uartclk);
sci_port_enable(s);
sci_reset(port);
smr_val = sci_in(port, SCSMR) & 3;
if ((termios->c_cflag & CSIZE) == CS7)
smr_val |= 0x40;
if (termios->c_cflag & PARENB)
smr_val |= 0x20;
if (termios->c_cflag & PARODD)
smr_val |= 0x30;
if (termios->c_cflag & CSTOPB)
smr_val |= 0x08;
uart_update_timeout(port, termios->c_cflag, baud);
sci_out(port, SCSMR, smr_val);
dev_dbg(port->dev, "%s: SMR %x, t %x, SCSCR %x\n", __func__, smr_val, t,
s->cfg->scscr);
if (t > 0) {
if (t >= 256) {
sci_out(port, SCSMR, (sci_in(port, SCSMR) & ~3) | 1);
t >>= 2;
} else
sci_out(port, SCSMR, sci_in(port, SCSMR) & ~3);
sci_out(port, SCBRR, t);
udelay((1000000+(baud-1)) / baud); /* Wait one bit interval */
}
sci_init_pins(port, termios->c_cflag);
reg = sci_getreg(port, SCFCR);
if (reg->size) {
unsigned short ctrl = sci_in(port, SCFCR);
if (s->cfg->capabilities & SCIx_HAVE_RTSCTS) {
if (termios->c_cflag & CRTSCTS)
ctrl |= SCFCR_MCE;
else
ctrl &= ~SCFCR_MCE;
}
/*
* As we've done a sci_reset() above, ensure we don't
* interfere with the FIFOs while toggling MCE. As the
* reset values could still be set, simply mask them out.
*/
ctrl &= ~(SCFCR_RFRST | SCFCR_TFRST);
sci_out(port, SCFCR, ctrl);
}
sci_out(port, SCSCR, s->cfg->scscr);
#ifdef CONFIG_SERIAL_SH_SCI_DMA
/*
* Calculate delay for 1.5 DMA buffers: see
* drivers/serial/serial_core.c::uart_update_timeout(). With 10 bits
* (CS8), 250Hz, 115200 baud and 64 bytes FIFO, the above function
* calculates 1 jiffie for the data plus 5 jiffies for the "slop(e)."
* Then below we calculate 3 jiffies (12ms) for 1.5 DMA buffers (3 FIFO
* sizes), but it has been found out experimentally, that this is not
* enough: the driver too often needlessly runs on a DMA timeout. 20ms
* as a minimum seem to work perfectly.
*/
if (s->chan_rx) {
s->rx_timeout = (port->timeout - HZ / 50) * s->buf_len_rx * 3 /
port->fifosize / 2;
dev_dbg(port->dev,
"DMA Rx t-out %ums, tty t-out %u jiffies\n",
s->rx_timeout * 1000 / HZ, port->timeout);
if (s->rx_timeout < msecs_to_jiffies(20))
s->rx_timeout = msecs_to_jiffies(20);
}
#endif
if ((termios->c_cflag & CREAD) != 0)
sci_start_rx(port);
sci_port_disable(s);
}
static const char *sci_type(struct uart_port *port)
{
switch (port->type) {
case PORT_IRDA:
return "irda";
case PORT_SCI:
return "sci";
case PORT_SCIF:
return "scif";
case PORT_SCIFA:
return "scifa";
case PORT_SCIFB:
return "scifb";
}
return NULL;
}
static inline unsigned long sci_port_size(struct uart_port *port)
{
/*
* Pick an arbitrary size that encapsulates all of the base
* registers by default. This can be optimized later, or derived
* from platform resource data at such a time that ports begin to
* behave more erratically.
*/
return 64;
}
static int sci_remap_port(struct uart_port *port)
{
unsigned long size = sci_port_size(port);
/*
* Nothing to do if there's already an established membase.
*/
if (port->membase)
return 0;
if (port->flags & UPF_IOREMAP) {
port->membase = ioremap_nocache(port->mapbase, size);
if (unlikely(!port->membase)) {
dev_err(port->dev, "can't remap port#%d\n", port->line);
return -ENXIO;
}
} else {
/*
* For the simple (and majority of) cases where we don't
* need to do any remapping, just cast the cookie
* directly.
*/
port->membase = (void __iomem *)port->mapbase;
}
return 0;
}
static void sci_release_port(struct uart_port *port)
{
if (port->flags & UPF_IOREMAP) {
iounmap(port->membase);
port->membase = NULL;
}
release_mem_region(port->mapbase, sci_port_size(port));
}
static int sci_request_port(struct uart_port *port)
{
unsigned long size = sci_port_size(port);
struct resource *res;
int ret;
res = request_mem_region(port->mapbase, size, dev_name(port->dev));
if (unlikely(res == NULL))
return -EBUSY;
ret = sci_remap_port(port);
if (unlikely(ret != 0)) {
release_resource(res);
return ret;
}
return 0;
}
static void sci_config_port(struct uart_port *port, int flags)
{
if (flags & UART_CONFIG_TYPE) {
struct sci_port *sport = to_sci_port(port);
port->type = sport->cfg->type;
sci_request_port(port);
}
}
static int sci_verify_port(struct uart_port *port, struct serial_struct *ser)
{
struct sci_port *s = to_sci_port(port);
if (ser->irq != s->cfg->irqs[SCIx_TXI_IRQ] || ser->irq > nr_irqs)
return -EINVAL;
if (ser->baud_base < 2400)
/* No paper tape reader for Mitch.. */
return -EINVAL;
return 0;
}
static struct uart_ops sci_uart_ops = {
.tx_empty = sci_tx_empty,
.set_mctrl = sci_set_mctrl,
.get_mctrl = sci_get_mctrl,
.start_tx = sci_start_tx,
.stop_tx = sci_stop_tx,
.stop_rx = sci_stop_rx,
.enable_ms = sci_enable_ms,
.break_ctl = sci_break_ctl,
.startup = sci_startup,
.shutdown = sci_shutdown,
.set_termios = sci_set_termios,
.type = sci_type,
.release_port = sci_release_port,
.request_port = sci_request_port,
.config_port = sci_config_port,
.verify_port = sci_verify_port,
#ifdef CONFIG_CONSOLE_POLL
.poll_get_char = sci_poll_get_char,
.poll_put_char = sci_poll_put_char,
#endif
};
static int __devinit sci_init_single(struct platform_device *dev,
struct sci_port *sci_port,
unsigned int index,
struct plat_sci_port *p)
{
struct uart_port *port = &sci_port->port;
int ret;
sci_port->cfg = p;
port->ops = &sci_uart_ops;
port->iotype = UPIO_MEM;
port->line = index;
switch (p->type) {
case PORT_SCIFB:
port->fifosize = 256;
break;
case PORT_SCIFA:
port->fifosize = 64;
break;
case PORT_SCIF:
port->fifosize = 16;
break;
default:
port->fifosize = 1;
break;
}
if (p->regtype == SCIx_PROBE_REGTYPE) {
ret = sci_probe_regmap(p);
if (unlikely(ret))
return ret;
}
if (dev) {
sci_port->iclk = clk_get(&dev->dev, "sci_ick");
if (IS_ERR(sci_port->iclk)) {
sci_port->iclk = clk_get(&dev->dev, "peripheral_clk");
if (IS_ERR(sci_port->iclk)) {
dev_err(&dev->dev, "can't get iclk\n");
return PTR_ERR(sci_port->iclk);
}
}
/*
* The function clock is optional, ignore it if we can't
* find it.
*/
sci_port->fclk = clk_get(&dev->dev, "sci_fck");
if (IS_ERR(sci_port->fclk))
sci_port->fclk = NULL;
port->dev = &dev->dev;
sci_init_gpios(sci_port);
pm_runtime_irq_safe(&dev->dev);
pm_runtime_enable(&dev->dev);
}
sci_port->break_timer.data = (unsigned long)sci_port;
sci_port->break_timer.function = sci_break_timer;
init_timer(&sci_port->break_timer);
/*
* Establish some sensible defaults for the error detection.
*/
if (!p->error_mask)
p->error_mask = (p->type == PORT_SCI) ?
SCI_DEFAULT_ERROR_MASK : SCIF_DEFAULT_ERROR_MASK;
/*
* Establish sensible defaults for the overrun detection, unless
* the part has explicitly disabled support for it.
*/
if (p->overrun_bit != SCIx_NOT_SUPPORTED) {
if (p->type == PORT_SCI)
p->overrun_bit = 5;
else if (p->scbrr_algo_id == SCBRR_ALGO_4)
p->overrun_bit = 9;
else
p->overrun_bit = 0;
/*
* Make the error mask inclusive of overrun detection, if
* supported.
*/
p->error_mask |= (1 << p->overrun_bit);
}
port->mapbase = p->mapbase;
port->type = p->type;
port->flags = p->flags;
port->regshift = p->regshift;
/*
* The UART port needs an IRQ value, so we peg this to the RX IRQ
* for the multi-IRQ ports, which is where we are primarily
* concerned with the shutdown path synchronization.
*
* For the muxed case there's nothing more to do.
*/
port->irq = p->irqs[SCIx_RXI_IRQ];
port->irqflags = 0;
port->serial_in = sci_serial_in;
port->serial_out = sci_serial_out;
if (p->dma_slave_tx > 0 && p->dma_slave_rx > 0)
dev_dbg(port->dev, "DMA tx %d, rx %d\n",
p->dma_slave_tx, p->dma_slave_rx);
return 0;
}
#ifdef CONFIG_SERIAL_SH_SCI_CONSOLE
static void serial_console_putchar(struct uart_port *port, int ch)
{
sci_poll_put_char(port, ch);
}
/*
* Print a string to the serial port trying not to disturb
* any possible real use of the port...
*/
static void serial_console_write(struct console *co, const char *s,
unsigned count)
{
struct sci_port *sci_port = &sci_ports[co->index];
struct uart_port *port = &sci_port->port;
unsigned short bits;
sci_port_enable(sci_port);
uart_console_write(port, s, count, serial_console_putchar);
/* wait until fifo is empty and last bit has been transmitted */
bits = SCxSR_TDxE(port) | SCxSR_TEND(port);
while ((sci_in(port, SCxSR) & bits) != bits)
cpu_relax();
sci_port_disable(sci_port);
}
static int __devinit serial_console_setup(struct console *co, char *options)
{
struct sci_port *sci_port;
struct uart_port *port;
int baud = 115200;
int bits = 8;
int parity = 'n';
int flow = 'n';
int ret;
/*
* Refuse to handle any bogus ports.
*/
if (co->index < 0 || co->index >= SCI_NPORTS)
return -ENODEV;
sci_port = &sci_ports[co->index];
port = &sci_port->port;
/*
* Refuse to handle uninitialized ports.
*/
if (!port->ops)
return -ENODEV;
ret = sci_remap_port(port);
if (unlikely(ret != 0))
return ret;
sci_port_enable(sci_port);
if (options)
uart_parse_options(options, &baud, &parity, &bits, &flow);
sci_port_disable(sci_port);
return uart_set_options(port, co, baud, parity, bits, flow);
}
static struct console serial_console = {
.name = "ttySC",
.device = uart_console_device,
.write = serial_console_write,
.setup = serial_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &sci_uart_driver,
};
static struct console early_serial_console = {
.name = "early_ttySC",
.write = serial_console_write,
.flags = CON_PRINTBUFFER,
.index = -1,
};
static char early_serial_buf[32];
static int __devinit sci_probe_earlyprintk(struct platform_device *pdev)
{
struct plat_sci_port *cfg = pdev->dev.platform_data;
if (early_serial_console.data)
return -EEXIST;
early_serial_console.index = pdev->id;
sci_init_single(NULL, &sci_ports[pdev->id], pdev->id, cfg);
serial_console_setup(&early_serial_console, early_serial_buf);
if (!strstr(early_serial_buf, "keep"))
early_serial_console.flags |= CON_BOOT;
register_console(&early_serial_console);
return 0;
}
#define uart_console(port) ((port)->cons->index == (port)->line)
static int sci_runtime_suspend(struct device *dev)
{
struct sci_port *sci_port = dev_get_drvdata(dev);
struct uart_port *port = &sci_port->port;
if (uart_console(port)) {
struct plat_sci_reg *reg;
sci_port->saved_smr = sci_in(port, SCSMR);
sci_port->saved_brr = sci_in(port, SCBRR);
reg = sci_getreg(port, SCFCR);
if (reg->size)
sci_port->saved_fcr = sci_in(port, SCFCR);
else
sci_port->saved_fcr = 0;
}
return 0;
}
static int sci_runtime_resume(struct device *dev)
{
struct sci_port *sci_port = dev_get_drvdata(dev);
struct uart_port *port = &sci_port->port;
if (uart_console(port)) {
sci_reset(port);
sci_out(port, SCSMR, sci_port->saved_smr);
sci_out(port, SCBRR, sci_port->saved_brr);
if (sci_port->saved_fcr)
sci_out(port, SCFCR, sci_port->saved_fcr);
sci_out(port, SCSCR, sci_port->cfg->scscr);
}
return 0;
}
#define SCI_CONSOLE (&serial_console)
#else
static inline int __devinit sci_probe_earlyprintk(struct platform_device *pdev)
{
return -EINVAL;
}
#define SCI_CONSOLE NULL
#define sci_runtime_suspend NULL
#define sci_runtime_resume NULL
#endif /* CONFIG_SERIAL_SH_SCI_CONSOLE */
static char banner[] __initdata =
KERN_INFO "SuperH SCI(F) driver initialized\n";
static struct uart_driver sci_uart_driver = {
.owner = THIS_MODULE,
.driver_name = "sci",
.dev_name = "ttySC",
.major = SCI_MAJOR,
.minor = SCI_MINOR_START,
.nr = SCI_NPORTS,
.cons = SCI_CONSOLE,
};
static int sci_remove(struct platform_device *dev)
{
struct sci_port *port = platform_get_drvdata(dev);
cpufreq_unregister_notifier(&port->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
sci_free_gpios(port);
uart_remove_one_port(&sci_uart_driver, &port->port);
clk_put(port->iclk);
clk_put(port->fclk);
pm_runtime_disable(&dev->dev);
return 0;
}
static int __devinit sci_probe_single(struct platform_device *dev,
unsigned int index,
struct plat_sci_port *p,
struct sci_port *sciport)
{
int ret;
/* Sanity check */
if (unlikely(index >= SCI_NPORTS)) {
dev_notice(&dev->dev, "Attempting to register port "
"%d when only %d are available.\n",
index+1, SCI_NPORTS);
dev_notice(&dev->dev, "Consider bumping "
"CONFIG_SERIAL_SH_SCI_NR_UARTS!\n");
return 0;
}
ret = sci_init_single(dev, sciport, index, p);
if (ret)
return ret;
return uart_add_one_port(&sci_uart_driver, &sciport->port);
}
static int __devinit sci_probe(struct platform_device *dev)
{
struct plat_sci_port *p = dev->dev.platform_data;
struct sci_port *sp = &sci_ports[dev->id];
int ret;
/*
* If we've come here via earlyprintk initialization, head off to
* the special early probe. We don't have sufficient device state
* to make it beyond this yet.
*/
if (is_early_platform_device(dev))
return sci_probe_earlyprintk(dev);
platform_set_drvdata(dev, sp);
ret = sci_probe_single(dev, dev->id, p, sp);
if (ret)
goto err_unreg;
sp->freq_transition.notifier_call = sci_notifier;
ret = cpufreq_register_notifier(&sp->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
if (unlikely(ret < 0))
goto err_unreg;
#ifdef CONFIG_SH_STANDARD_BIOS
sh_bios_gdb_detach();
#endif
return 0;
err_unreg:
sci_remove(dev);
return ret;
}
static int sci_suspend(struct device *dev)
{
struct sci_port *sport = dev_get_drvdata(dev);
if (sport)
uart_suspend_port(&sci_uart_driver, &sport->port);
return 0;
}
static int sci_resume(struct device *dev)
{
struct sci_port *sport = dev_get_drvdata(dev);
if (sport)
uart_resume_port(&sci_uart_driver, &sport->port);
return 0;
}
static const struct dev_pm_ops sci_dev_pm_ops = {
.runtime_suspend = sci_runtime_suspend,
.runtime_resume = sci_runtime_resume,
.suspend = sci_suspend,
.resume = sci_resume,
};
static struct platform_driver sci_driver = {
.probe = sci_probe,
.remove = sci_remove,
.driver = {
.name = "sh-sci",
.owner = THIS_MODULE,
.pm = &sci_dev_pm_ops,
},
};
static int __init sci_init(void)
{
int ret;
printk(banner);
ret = uart_register_driver(&sci_uart_driver);
if (likely(ret == 0)) {
ret = platform_driver_register(&sci_driver);
if (unlikely(ret))
uart_unregister_driver(&sci_uart_driver);
}
return ret;
}
static void __exit sci_exit(void)
{
platform_driver_unregister(&sci_driver);
uart_unregister_driver(&sci_uart_driver);
}
#ifdef CONFIG_SERIAL_SH_SCI_CONSOLE
early_platform_init_buffer("earlyprintk", &sci_driver,
early_serial_buf, ARRAY_SIZE(early_serial_buf));
#endif
module_init(sci_init);
module_exit(sci_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:sh-sci");
MODULE_AUTHOR("Paul Mundt");
MODULE_DESCRIPTION("SuperH SCI(F) serial driver");
| gpl-2.0 |
aospan/media_tree | drivers/gpu/drm/amd/amdgpu/gfx_v7_0.c | 30 | 153130 | /*
* Copyright 2014 Advanced Micro Devices, 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.
*
*/
#include <linux/firmware.h>
#include "drmP.h"
#include "amdgpu.h"
#include "amdgpu_ih.h"
#include "amdgpu_gfx.h"
#include "cikd.h"
#include "cik.h"
#include "atom.h"
#include "amdgpu_ucode.h"
#include "clearstate_ci.h"
#include "dce/dce_8_0_d.h"
#include "dce/dce_8_0_sh_mask.h"
#include "bif/bif_4_1_d.h"
#include "bif/bif_4_1_sh_mask.h"
#include "gca/gfx_7_0_d.h"
#include "gca/gfx_7_2_enum.h"
#include "gca/gfx_7_2_sh_mask.h"
#include "gmc/gmc_7_0_d.h"
#include "gmc/gmc_7_0_sh_mask.h"
#include "oss/oss_2_0_d.h"
#include "oss/oss_2_0_sh_mask.h"
#define GFX7_NUM_GFX_RINGS 1
#define GFX7_NUM_COMPUTE_RINGS 8
static void gfx_v7_0_set_ring_funcs(struct amdgpu_device *adev);
static void gfx_v7_0_set_irq_funcs(struct amdgpu_device *adev);
static void gfx_v7_0_set_gds_init(struct amdgpu_device *adev);
MODULE_FIRMWARE("radeon/bonaire_pfp.bin");
MODULE_FIRMWARE("radeon/bonaire_me.bin");
MODULE_FIRMWARE("radeon/bonaire_ce.bin");
MODULE_FIRMWARE("radeon/bonaire_rlc.bin");
MODULE_FIRMWARE("radeon/bonaire_mec.bin");
MODULE_FIRMWARE("radeon/hawaii_pfp.bin");
MODULE_FIRMWARE("radeon/hawaii_me.bin");
MODULE_FIRMWARE("radeon/hawaii_ce.bin");
MODULE_FIRMWARE("radeon/hawaii_rlc.bin");
MODULE_FIRMWARE("radeon/hawaii_mec.bin");
MODULE_FIRMWARE("radeon/kaveri_pfp.bin");
MODULE_FIRMWARE("radeon/kaveri_me.bin");
MODULE_FIRMWARE("radeon/kaveri_ce.bin");
MODULE_FIRMWARE("radeon/kaveri_rlc.bin");
MODULE_FIRMWARE("radeon/kaveri_mec.bin");
MODULE_FIRMWARE("radeon/kaveri_mec2.bin");
MODULE_FIRMWARE("radeon/kabini_pfp.bin");
MODULE_FIRMWARE("radeon/kabini_me.bin");
MODULE_FIRMWARE("radeon/kabini_ce.bin");
MODULE_FIRMWARE("radeon/kabini_rlc.bin");
MODULE_FIRMWARE("radeon/kabini_mec.bin");
MODULE_FIRMWARE("radeon/mullins_pfp.bin");
MODULE_FIRMWARE("radeon/mullins_me.bin");
MODULE_FIRMWARE("radeon/mullins_ce.bin");
MODULE_FIRMWARE("radeon/mullins_rlc.bin");
MODULE_FIRMWARE("radeon/mullins_mec.bin");
static const struct amdgpu_gds_reg_offset amdgpu_gds_reg_offset[] =
{
{mmGDS_VMID0_BASE, mmGDS_VMID0_SIZE, mmGDS_GWS_VMID0, mmGDS_OA_VMID0},
{mmGDS_VMID1_BASE, mmGDS_VMID1_SIZE, mmGDS_GWS_VMID1, mmGDS_OA_VMID1},
{mmGDS_VMID2_BASE, mmGDS_VMID2_SIZE, mmGDS_GWS_VMID2, mmGDS_OA_VMID2},
{mmGDS_VMID3_BASE, mmGDS_VMID3_SIZE, mmGDS_GWS_VMID3, mmGDS_OA_VMID3},
{mmGDS_VMID4_BASE, mmGDS_VMID4_SIZE, mmGDS_GWS_VMID4, mmGDS_OA_VMID4},
{mmGDS_VMID5_BASE, mmGDS_VMID5_SIZE, mmGDS_GWS_VMID5, mmGDS_OA_VMID5},
{mmGDS_VMID6_BASE, mmGDS_VMID6_SIZE, mmGDS_GWS_VMID6, mmGDS_OA_VMID6},
{mmGDS_VMID7_BASE, mmGDS_VMID7_SIZE, mmGDS_GWS_VMID7, mmGDS_OA_VMID7},
{mmGDS_VMID8_BASE, mmGDS_VMID8_SIZE, mmGDS_GWS_VMID8, mmGDS_OA_VMID8},
{mmGDS_VMID9_BASE, mmGDS_VMID9_SIZE, mmGDS_GWS_VMID9, mmGDS_OA_VMID9},
{mmGDS_VMID10_BASE, mmGDS_VMID10_SIZE, mmGDS_GWS_VMID10, mmGDS_OA_VMID10},
{mmGDS_VMID11_BASE, mmGDS_VMID11_SIZE, mmGDS_GWS_VMID11, mmGDS_OA_VMID11},
{mmGDS_VMID12_BASE, mmGDS_VMID12_SIZE, mmGDS_GWS_VMID12, mmGDS_OA_VMID12},
{mmGDS_VMID13_BASE, mmGDS_VMID13_SIZE, mmGDS_GWS_VMID13, mmGDS_OA_VMID13},
{mmGDS_VMID14_BASE, mmGDS_VMID14_SIZE, mmGDS_GWS_VMID14, mmGDS_OA_VMID14},
{mmGDS_VMID15_BASE, mmGDS_VMID15_SIZE, mmGDS_GWS_VMID15, mmGDS_OA_VMID15}
};
static const u32 spectre_rlc_save_restore_register_list[] =
{
(0x0e00 << 16) | (0xc12c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc140 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc150 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc15c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc168 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc170 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc178 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc204 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2b8 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2bc >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2c0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8228 >> 2),
0x00000000,
(0x0e00 << 16) | (0x829c >> 2),
0x00000000,
(0x0e00 << 16) | (0x869c >> 2),
0x00000000,
(0x0600 << 16) | (0x98f4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x98f8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x9900 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc260 >> 2),
0x00000000,
(0x0e00 << 16) | (0x90e8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c000 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c00c >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c1c >> 2),
0x00000000,
(0x0e00 << 16) | (0x9700 >> 2),
0x00000000,
(0x0e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x4e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x5e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x6e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x7e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x8e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x9e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0xae00 << 16) | (0xcd20 >> 2),
0x00000000,
(0xbe00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x0e00 << 16) | (0x89bc >> 2),
0x00000000,
(0x0e00 << 16) | (0x8900 >> 2),
0x00000000,
0x3,
(0x0e00 << 16) | (0xc130 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc134 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc1fc >> 2),
0x00000000,
(0x0e00 << 16) | (0xc208 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc264 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc268 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc26c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc270 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc274 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc278 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc27c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc280 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc284 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc288 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc28c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc290 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc294 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc298 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc29c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2a0 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2a4 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2a8 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2ac >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2b0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x301d0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30238 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30250 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30254 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30258 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3025c >> 2),
0x00000000,
(0x4e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x8e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x9e00 << 16) | (0xc900 >> 2),
0x00000000,
(0xae00 << 16) | (0xc900 >> 2),
0x00000000,
(0xbe00 << 16) | (0xc900 >> 2),
0x00000000,
(0x4e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x8e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x9e00 << 16) | (0xc904 >> 2),
0x00000000,
(0xae00 << 16) | (0xc904 >> 2),
0x00000000,
(0xbe00 << 16) | (0xc904 >> 2),
0x00000000,
(0x4e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x8e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x9e00 << 16) | (0xc908 >> 2),
0x00000000,
(0xae00 << 16) | (0xc908 >> 2),
0x00000000,
(0xbe00 << 16) | (0xc908 >> 2),
0x00000000,
(0x4e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x5e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x6e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x7e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x8e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x9e00 << 16) | (0xc90c >> 2),
0x00000000,
(0xae00 << 16) | (0xc90c >> 2),
0x00000000,
(0xbe00 << 16) | (0xc90c >> 2),
0x00000000,
(0x4e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x8e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x9e00 << 16) | (0xc910 >> 2),
0x00000000,
(0xae00 << 16) | (0xc910 >> 2),
0x00000000,
(0xbe00 << 16) | (0xc910 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc99c >> 2),
0x00000000,
(0x0e00 << 16) | (0x9834 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f00 >> 2),
0x00000000,
(0x0001 << 16) | (0x30f00 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f04 >> 2),
0x00000000,
(0x0001 << 16) | (0x30f04 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f08 >> 2),
0x00000000,
(0x0001 << 16) | (0x30f08 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f0c >> 2),
0x00000000,
(0x0001 << 16) | (0x30f0c >> 2),
0x00000000,
(0x0600 << 16) | (0x9b7c >> 2),
0x00000000,
(0x0e00 << 16) | (0x8a14 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8a18 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a00 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8bf0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8bcc >> 2),
0x00000000,
(0x0e00 << 16) | (0x8b24 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30a04 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a10 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a14 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a18 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a2c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc700 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc704 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc708 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc768 >> 2),
0x00000000,
(0x0400 << 16) | (0xc770 >> 2),
0x00000000,
(0x0400 << 16) | (0xc774 >> 2),
0x00000000,
(0x0400 << 16) | (0xc778 >> 2),
0x00000000,
(0x0400 << 16) | (0xc77c >> 2),
0x00000000,
(0x0400 << 16) | (0xc780 >> 2),
0x00000000,
(0x0400 << 16) | (0xc784 >> 2),
0x00000000,
(0x0400 << 16) | (0xc788 >> 2),
0x00000000,
(0x0400 << 16) | (0xc78c >> 2),
0x00000000,
(0x0400 << 16) | (0xc798 >> 2),
0x00000000,
(0x0400 << 16) | (0xc79c >> 2),
0x00000000,
(0x0400 << 16) | (0xc7a0 >> 2),
0x00000000,
(0x0400 << 16) | (0xc7a4 >> 2),
0x00000000,
(0x0400 << 16) | (0xc7a8 >> 2),
0x00000000,
(0x0400 << 16) | (0xc7ac >> 2),
0x00000000,
(0x0400 << 16) | (0xc7b0 >> 2),
0x00000000,
(0x0400 << 16) | (0xc7b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x9100 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c010 >> 2),
0x00000000,
(0x0e00 << 16) | (0x92a8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x92ac >> 2),
0x00000000,
(0x0e00 << 16) | (0x92b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x92b8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x92bc >> 2),
0x00000000,
(0x0e00 << 16) | (0x92c0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x92c4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x92c8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x92cc >> 2),
0x00000000,
(0x0e00 << 16) | (0x92d0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c00 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c04 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c20 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c38 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c3c >> 2),
0x00000000,
(0x0e00 << 16) | (0xae00 >> 2),
0x00000000,
(0x0e00 << 16) | (0x9604 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac08 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac0c >> 2),
0x00000000,
(0x0e00 << 16) | (0xac10 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac14 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac58 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac68 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac6c >> 2),
0x00000000,
(0x0e00 << 16) | (0xac70 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac74 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac78 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac7c >> 2),
0x00000000,
(0x0e00 << 16) | (0xac80 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac84 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac88 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac8c >> 2),
0x00000000,
(0x0e00 << 16) | (0x970c >> 2),
0x00000000,
(0x0e00 << 16) | (0x9714 >> 2),
0x00000000,
(0x0e00 << 16) | (0x9718 >> 2),
0x00000000,
(0x0e00 << 16) | (0x971c >> 2),
0x00000000,
(0x0e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x4e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x5e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x6e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x7e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x8e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x9e00 << 16) | (0x31068 >> 2),
0x00000000,
(0xae00 << 16) | (0x31068 >> 2),
0x00000000,
(0xbe00 << 16) | (0x31068 >> 2),
0x00000000,
(0x0e00 << 16) | (0xcd10 >> 2),
0x00000000,
(0x0e00 << 16) | (0xcd14 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88b0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88b8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88bc >> 2),
0x00000000,
(0x0400 << 16) | (0x89c0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88c4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88c8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88d0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88d4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88d8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8980 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30938 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3093c >> 2),
0x00000000,
(0x0e00 << 16) | (0x30940 >> 2),
0x00000000,
(0x0e00 << 16) | (0x89a0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30900 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30904 >> 2),
0x00000000,
(0x0e00 << 16) | (0x89b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c210 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c214 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c218 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8904 >> 2),
0x00000000,
0x5,
(0x0e00 << 16) | (0x8c28 >> 2),
(0x0e00 << 16) | (0x8c2c >> 2),
(0x0e00 << 16) | (0x8c30 >> 2),
(0x0e00 << 16) | (0x8c34 >> 2),
(0x0e00 << 16) | (0x9600 >> 2),
};
static const u32 kalindi_rlc_save_restore_register_list[] =
{
(0x0e00 << 16) | (0xc12c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc140 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc150 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc15c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc168 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc170 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc204 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2b8 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2bc >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2c0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8228 >> 2),
0x00000000,
(0x0e00 << 16) | (0x829c >> 2),
0x00000000,
(0x0e00 << 16) | (0x869c >> 2),
0x00000000,
(0x0600 << 16) | (0x98f4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x98f8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x9900 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc260 >> 2),
0x00000000,
(0x0e00 << 16) | (0x90e8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c000 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c00c >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c1c >> 2),
0x00000000,
(0x0e00 << 16) | (0x9700 >> 2),
0x00000000,
(0x0e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x4e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x5e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x6e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x7e00 << 16) | (0xcd20 >> 2),
0x00000000,
(0x0e00 << 16) | (0x89bc >> 2),
0x00000000,
(0x0e00 << 16) | (0x8900 >> 2),
0x00000000,
0x3,
(0x0e00 << 16) | (0xc130 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc134 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc1fc >> 2),
0x00000000,
(0x0e00 << 16) | (0xc208 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc264 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc268 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc26c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc270 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc274 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc28c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc290 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc294 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc298 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2a0 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2a4 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2a8 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc2ac >> 2),
0x00000000,
(0x0e00 << 16) | (0x301d0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30238 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30250 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30254 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30258 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3025c >> 2),
0x00000000,
(0x4e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc900 >> 2),
0x00000000,
(0x4e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc904 >> 2),
0x00000000,
(0x4e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc908 >> 2),
0x00000000,
(0x4e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x5e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x6e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x7e00 << 16) | (0xc90c >> 2),
0x00000000,
(0x4e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x5e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x6e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x7e00 << 16) | (0xc910 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc99c >> 2),
0x00000000,
(0x0e00 << 16) | (0x9834 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f00 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f04 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f08 >> 2),
0x00000000,
(0x0000 << 16) | (0x30f0c >> 2),
0x00000000,
(0x0600 << 16) | (0x9b7c >> 2),
0x00000000,
(0x0e00 << 16) | (0x8a14 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8a18 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a00 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8bf0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8bcc >> 2),
0x00000000,
(0x0e00 << 16) | (0x8b24 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30a04 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a10 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a14 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a18 >> 2),
0x00000000,
(0x0600 << 16) | (0x30a2c >> 2),
0x00000000,
(0x0e00 << 16) | (0xc700 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc704 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc708 >> 2),
0x00000000,
(0x0e00 << 16) | (0xc768 >> 2),
0x00000000,
(0x0400 << 16) | (0xc770 >> 2),
0x00000000,
(0x0400 << 16) | (0xc774 >> 2),
0x00000000,
(0x0400 << 16) | (0xc798 >> 2),
0x00000000,
(0x0400 << 16) | (0xc79c >> 2),
0x00000000,
(0x0e00 << 16) | (0x9100 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c010 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c00 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c04 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c20 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c38 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8c3c >> 2),
0x00000000,
(0x0e00 << 16) | (0xae00 >> 2),
0x00000000,
(0x0e00 << 16) | (0x9604 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac08 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac0c >> 2),
0x00000000,
(0x0e00 << 16) | (0xac10 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac14 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac58 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac68 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac6c >> 2),
0x00000000,
(0x0e00 << 16) | (0xac70 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac74 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac78 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac7c >> 2),
0x00000000,
(0x0e00 << 16) | (0xac80 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac84 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac88 >> 2),
0x00000000,
(0x0e00 << 16) | (0xac8c >> 2),
0x00000000,
(0x0e00 << 16) | (0x970c >> 2),
0x00000000,
(0x0e00 << 16) | (0x9714 >> 2),
0x00000000,
(0x0e00 << 16) | (0x9718 >> 2),
0x00000000,
(0x0e00 << 16) | (0x971c >> 2),
0x00000000,
(0x0e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x4e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x5e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x6e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x7e00 << 16) | (0x31068 >> 2),
0x00000000,
(0x0e00 << 16) | (0xcd10 >> 2),
0x00000000,
(0x0e00 << 16) | (0xcd14 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88b0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88b8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88bc >> 2),
0x00000000,
(0x0400 << 16) | (0x89c0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88c4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88c8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88d0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88d4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x88d8 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8980 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30938 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3093c >> 2),
0x00000000,
(0x0e00 << 16) | (0x30940 >> 2),
0x00000000,
(0x0e00 << 16) | (0x89a0 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30900 >> 2),
0x00000000,
(0x0e00 << 16) | (0x30904 >> 2),
0x00000000,
(0x0e00 << 16) | (0x89b4 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3e1fc >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c210 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c214 >> 2),
0x00000000,
(0x0e00 << 16) | (0x3c218 >> 2),
0x00000000,
(0x0e00 << 16) | (0x8904 >> 2),
0x00000000,
0x5,
(0x0e00 << 16) | (0x8c28 >> 2),
(0x0e00 << 16) | (0x8c2c >> 2),
(0x0e00 << 16) | (0x8c30 >> 2),
(0x0e00 << 16) | (0x8c34 >> 2),
(0x0e00 << 16) | (0x9600 >> 2),
};
static u32 gfx_v7_0_get_csb_size(struct amdgpu_device *adev);
static void gfx_v7_0_get_csb_buffer(struct amdgpu_device *adev, volatile u32 *buffer);
static void gfx_v7_0_init_cp_pg_table(struct amdgpu_device *adev);
static void gfx_v7_0_init_pg(struct amdgpu_device *adev);
static void gfx_v7_0_get_cu_info(struct amdgpu_device *adev);
/*
* Core functions
*/
/**
* gfx_v7_0_init_microcode - load ucode images from disk
*
* @adev: amdgpu_device pointer
*
* Use the firmware interface to load the ucode images into
* the driver (not loaded into hw).
* Returns 0 on success, error on failure.
*/
static int gfx_v7_0_init_microcode(struct amdgpu_device *adev)
{
const char *chip_name;
char fw_name[30];
int err;
DRM_DEBUG("\n");
switch (adev->asic_type) {
case CHIP_BONAIRE:
chip_name = "bonaire";
break;
case CHIP_HAWAII:
chip_name = "hawaii";
break;
case CHIP_KAVERI:
chip_name = "kaveri";
break;
case CHIP_KABINI:
chip_name = "kabini";
break;
case CHIP_MULLINS:
chip_name = "mullins";
break;
default: BUG();
}
snprintf(fw_name, sizeof(fw_name), "radeon/%s_pfp.bin", chip_name);
err = request_firmware(&adev->gfx.pfp_fw, fw_name, adev->dev);
if (err)
goto out;
err = amdgpu_ucode_validate(adev->gfx.pfp_fw);
if (err)
goto out;
snprintf(fw_name, sizeof(fw_name), "radeon/%s_me.bin", chip_name);
err = request_firmware(&adev->gfx.me_fw, fw_name, adev->dev);
if (err)
goto out;
err = amdgpu_ucode_validate(adev->gfx.me_fw);
if (err)
goto out;
snprintf(fw_name, sizeof(fw_name), "radeon/%s_ce.bin", chip_name);
err = request_firmware(&adev->gfx.ce_fw, fw_name, adev->dev);
if (err)
goto out;
err = amdgpu_ucode_validate(adev->gfx.ce_fw);
if (err)
goto out;
snprintf(fw_name, sizeof(fw_name), "radeon/%s_mec.bin", chip_name);
err = request_firmware(&adev->gfx.mec_fw, fw_name, adev->dev);
if (err)
goto out;
err = amdgpu_ucode_validate(adev->gfx.mec_fw);
if (err)
goto out;
if (adev->asic_type == CHIP_KAVERI) {
snprintf(fw_name, sizeof(fw_name), "radeon/%s_mec2.bin", chip_name);
err = request_firmware(&adev->gfx.mec2_fw, fw_name, adev->dev);
if (err)
goto out;
err = amdgpu_ucode_validate(adev->gfx.mec2_fw);
if (err)
goto out;
}
snprintf(fw_name, sizeof(fw_name), "radeon/%s_rlc.bin", chip_name);
err = request_firmware(&adev->gfx.rlc_fw, fw_name, adev->dev);
if (err)
goto out;
err = amdgpu_ucode_validate(adev->gfx.rlc_fw);
out:
if (err) {
printk(KERN_ERR
"gfx7: Failed to load firmware \"%s\"\n",
fw_name);
release_firmware(adev->gfx.pfp_fw);
adev->gfx.pfp_fw = NULL;
release_firmware(adev->gfx.me_fw);
adev->gfx.me_fw = NULL;
release_firmware(adev->gfx.ce_fw);
adev->gfx.ce_fw = NULL;
release_firmware(adev->gfx.mec_fw);
adev->gfx.mec_fw = NULL;
release_firmware(adev->gfx.mec2_fw);
adev->gfx.mec2_fw = NULL;
release_firmware(adev->gfx.rlc_fw);
adev->gfx.rlc_fw = NULL;
}
return err;
}
static void gfx_v7_0_free_microcode(struct amdgpu_device *adev)
{
release_firmware(adev->gfx.pfp_fw);
adev->gfx.pfp_fw = NULL;
release_firmware(adev->gfx.me_fw);
adev->gfx.me_fw = NULL;
release_firmware(adev->gfx.ce_fw);
adev->gfx.ce_fw = NULL;
release_firmware(adev->gfx.mec_fw);
adev->gfx.mec_fw = NULL;
release_firmware(adev->gfx.mec2_fw);
adev->gfx.mec2_fw = NULL;
release_firmware(adev->gfx.rlc_fw);
adev->gfx.rlc_fw = NULL;
}
/**
* gfx_v7_0_tiling_mode_table_init - init the hw tiling table
*
* @adev: amdgpu_device pointer
*
* Starting with SI, the tiling setup is done globally in a
* set of 32 tiling modes. Rather than selecting each set of
* parameters per surface as on older asics, we just select
* which index in the tiling table we want to use, and the
* surface uses those parameters (CIK).
*/
static void gfx_v7_0_tiling_mode_table_init(struct amdgpu_device *adev)
{
const u32 num_tile_mode_states =
ARRAY_SIZE(adev->gfx.config.tile_mode_array);
const u32 num_secondary_tile_mode_states =
ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);
u32 reg_offset, split_equal_to_row_size;
uint32_t *tile, *macrotile;
tile = adev->gfx.config.tile_mode_array;
macrotile = adev->gfx.config.macrotile_mode_array;
switch (adev->gfx.config.mem_row_size_in_kb) {
case 1:
split_equal_to_row_size = ADDR_SURF_TILE_SPLIT_1KB;
break;
case 2:
default:
split_equal_to_row_size = ADDR_SURF_TILE_SPLIT_2KB;
break;
case 4:
split_equal_to_row_size = ADDR_SURF_TILE_SPLIT_4KB;
break;
}
for (reg_offset = 0; reg_offset < num_tile_mode_states; reg_offset++)
tile[reg_offset] = 0;
for (reg_offset = 0; reg_offset < num_secondary_tile_mode_states; reg_offset++)
macrotile[reg_offset] = 0;
switch (adev->asic_type) {
case CHIP_BONAIRE:
tile[0] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_64B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[1] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_128B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[2] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_256B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[3] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_512B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[4] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[5] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[6] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[7] = (TILE_SPLIT(split_equal_to_row_size));
tile[8] = (ARRAY_MODE(ARRAY_LINEAR_ALIGNED) |
PIPE_CONFIG(ADDR_SURF_P4_16x16));
tile[9] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING));
tile[10] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[11] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[12] = (TILE_SPLIT(split_equal_to_row_size));
tile[13] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING));
tile[14] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[15] = (ARRAY_MODE(ARRAY_3D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[16] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[17] = (TILE_SPLIT(split_equal_to_row_size));
tile[18] = (ARRAY_MODE(ARRAY_1D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[19] = (ARRAY_MODE(ARRAY_1D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING));
tile[20] = (ARRAY_MODE(ARRAY_2D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[21] = (ARRAY_MODE(ARRAY_3D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[22] = (ARRAY_MODE(ARRAY_PRT_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[23] = (TILE_SPLIT(split_equal_to_row_size));
tile[24] = (ARRAY_MODE(ARRAY_2D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[25] = (ARRAY_MODE(ARRAY_2D_TILED_XTHICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[26] = (ARRAY_MODE(ARRAY_3D_TILED_XTHICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[27] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING));
tile[28] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[29] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[30] = (TILE_SPLIT(split_equal_to_row_size));
macrotile[0] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[1] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[2] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[3] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[4] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[5] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[6] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_4_BANK));
macrotile[8] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_2) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_8) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[9] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_2) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[10] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[11] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[12] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[13] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[14] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_4_BANK));
for (reg_offset = 0; reg_offset < num_tile_mode_states; reg_offset++)
WREG32(mmGB_TILE_MODE0 + reg_offset, tile[reg_offset]);
for (reg_offset = 0; reg_offset < num_secondary_tile_mode_states; reg_offset++)
if (reg_offset != 7)
WREG32(mmGB_MACROTILE_MODE0 + reg_offset, macrotile[reg_offset]);
break;
case CHIP_HAWAII:
tile[0] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_64B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[1] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_128B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[2] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_256B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[3] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_512B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[4] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[5] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[6] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[7] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[8] = (ARRAY_MODE(ARRAY_LINEAR_ALIGNED) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16));
tile[9] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING));
tile[10] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[11] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[12] = (ARRAY_MODE(ARRAY_PRT_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[13] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING));
tile[14] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[15] = (ARRAY_MODE(ARRAY_3D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[16] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[17] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[18] = (ARRAY_MODE(ARRAY_1D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[19] = (ARRAY_MODE(ARRAY_1D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING));
tile[20] = (ARRAY_MODE(ARRAY_2D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[21] = (ARRAY_MODE(ARRAY_3D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[22] = (ARRAY_MODE(ARRAY_PRT_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[23] = (ARRAY_MODE(ARRAY_PRT_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[24] = (ARRAY_MODE(ARRAY_2D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[25] = (ARRAY_MODE(ARRAY_2D_TILED_XTHICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[26] = (ARRAY_MODE(ARRAY_3D_TILED_XTHICK) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[27] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING));
tile[28] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[29] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P16_32x32_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[30] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P4_16x16) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
macrotile[0] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[1] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[2] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[3] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[4] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[5] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_4_BANK));
macrotile[6] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_4_BANK));
macrotile[8] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[9] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[10] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[11] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[12] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[13] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[14] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_1) |
NUM_BANKS(ADDR_SURF_4_BANK));
for (reg_offset = 0; reg_offset < num_tile_mode_states; reg_offset++)
WREG32(mmGB_TILE_MODE0 + reg_offset, tile[reg_offset]);
for (reg_offset = 0; reg_offset < num_secondary_tile_mode_states; reg_offset++)
if (reg_offset != 7)
WREG32(mmGB_MACROTILE_MODE0 + reg_offset, macrotile[reg_offset]);
break;
case CHIP_KABINI:
case CHIP_KAVERI:
case CHIP_MULLINS:
default:
tile[0] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_64B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[1] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_128B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[2] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_256B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[3] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
TILE_SPLIT(ADDR_SURF_TILE_SPLIT_512B) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[4] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[5] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING));
tile[6] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DEPTH_MICRO_TILING) |
TILE_SPLIT(split_equal_to_row_size));
tile[7] = (TILE_SPLIT(split_equal_to_row_size));
tile[8] = (ARRAY_MODE(ARRAY_LINEAR_ALIGNED) |
PIPE_CONFIG(ADDR_SURF_P2));
tile[9] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING));
tile[10] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[11] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_DISPLAY_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[12] = (TILE_SPLIT(split_equal_to_row_size));
tile[13] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING));
tile[14] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[15] = (ARRAY_MODE(ARRAY_3D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[16] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[17] = (TILE_SPLIT(split_equal_to_row_size));
tile[18] = (ARRAY_MODE(ARRAY_1D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[19] = (ARRAY_MODE(ARRAY_1D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING));
tile[20] = (ARRAY_MODE(ARRAY_2D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[21] = (ARRAY_MODE(ARRAY_3D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[22] = (ARRAY_MODE(ARRAY_PRT_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[23] = (TILE_SPLIT(split_equal_to_row_size));
tile[24] = (ARRAY_MODE(ARRAY_2D_TILED_THICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THIN_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[25] = (ARRAY_MODE(ARRAY_2D_TILED_XTHICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[26] = (ARRAY_MODE(ARRAY_3D_TILED_XTHICK) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_THICK_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_1));
tile[27] = (ARRAY_MODE(ARRAY_1D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING));
tile[28] = (ARRAY_MODE(ARRAY_2D_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_2));
tile[29] = (ARRAY_MODE(ARRAY_PRT_TILED_THIN1) |
PIPE_CONFIG(ADDR_SURF_P2) |
MICRO_TILE_MODE_NEW(ADDR_SURF_ROTATED_MICRO_TILING) |
SAMPLE_SPLIT(ADDR_SURF_SAMPLE_SPLIT_8));
tile[30] = (TILE_SPLIT(split_equal_to_row_size));
macrotile[0] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[1] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[2] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[3] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[4] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[5] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[6] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
macrotile[8] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_4) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_8) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[9] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_4) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[10] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_2) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_4) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[11] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_2) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[12] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_2) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[13] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_4) |
NUM_BANKS(ADDR_SURF_16_BANK));
macrotile[14] = (BANK_WIDTH(ADDR_SURF_BANK_WIDTH_1) |
BANK_HEIGHT(ADDR_SURF_BANK_HEIGHT_1) |
MACRO_TILE_ASPECT(ADDR_SURF_MACRO_ASPECT_2) |
NUM_BANKS(ADDR_SURF_8_BANK));
for (reg_offset = 0; reg_offset < num_tile_mode_states; reg_offset++)
WREG32(mmGB_TILE_MODE0 + reg_offset, tile[reg_offset]);
for (reg_offset = 0; reg_offset < num_secondary_tile_mode_states; reg_offset++)
if (reg_offset != 7)
WREG32(mmGB_MACROTILE_MODE0 + reg_offset, macrotile[reg_offset]);
break;
}
}
/**
* gfx_v7_0_select_se_sh - select which SE, SH to address
*
* @adev: amdgpu_device pointer
* @se_num: shader engine to address
* @sh_num: sh block to address
*
* Select which SE, SH combinations to address. Certain
* registers are instanced per SE or SH. 0xffffffff means
* broadcast to all SEs or SHs (CIK).
*/
void gfx_v7_0_select_se_sh(struct amdgpu_device *adev, u32 se_num, u32 sh_num)
{
u32 data = GRBM_GFX_INDEX__INSTANCE_BROADCAST_WRITES_MASK;
if ((se_num == 0xffffffff) && (sh_num == 0xffffffff))
data |= GRBM_GFX_INDEX__SH_BROADCAST_WRITES_MASK |
GRBM_GFX_INDEX__SE_BROADCAST_WRITES_MASK;
else if (se_num == 0xffffffff)
data |= GRBM_GFX_INDEX__SE_BROADCAST_WRITES_MASK |
(sh_num << GRBM_GFX_INDEX__SH_INDEX__SHIFT);
else if (sh_num == 0xffffffff)
data |= GRBM_GFX_INDEX__SH_BROADCAST_WRITES_MASK |
(se_num << GRBM_GFX_INDEX__SE_INDEX__SHIFT);
else
data |= (sh_num << GRBM_GFX_INDEX__SH_INDEX__SHIFT) |
(se_num << GRBM_GFX_INDEX__SE_INDEX__SHIFT);
WREG32(mmGRBM_GFX_INDEX, data);
}
/**
* gfx_v7_0_create_bitmask - create a bitmask
*
* @bit_width: length of the mask
*
* create a variable length bit mask (CIK).
* Returns the bitmask.
*/
static u32 gfx_v7_0_create_bitmask(u32 bit_width)
{
return (u32)((1ULL << bit_width) - 1);
}
/**
* gfx_v7_0_get_rb_active_bitmap - computes the mask of enabled RBs
*
* @adev: amdgpu_device pointer
*
* Calculates the bitmask of enabled RBs (CIK).
* Returns the enabled RB bitmask.
*/
static u32 gfx_v7_0_get_rb_active_bitmap(struct amdgpu_device *adev)
{
u32 data, mask;
data = RREG32(mmCC_RB_BACKEND_DISABLE);
data |= RREG32(mmGC_USER_RB_BACKEND_DISABLE);
data &= CC_RB_BACKEND_DISABLE__BACKEND_DISABLE_MASK;
data >>= GC_USER_RB_BACKEND_DISABLE__BACKEND_DISABLE__SHIFT;
mask = gfx_v7_0_create_bitmask(adev->gfx.config.max_backends_per_se /
adev->gfx.config.max_sh_per_se);
return (~data) & mask;
}
/**
* gfx_v7_0_setup_rb - setup the RBs on the asic
*
* @adev: amdgpu_device pointer
* @se_num: number of SEs (shader engines) for the asic
* @sh_per_se: number of SH blocks per SE for the asic
*
* Configures per-SE/SH RB registers (CIK).
*/
static void gfx_v7_0_setup_rb(struct amdgpu_device *adev)
{
int i, j;
u32 data;
u32 active_rbs = 0;
u32 rb_bitmap_width_per_sh = adev->gfx.config.max_backends_per_se /
adev->gfx.config.max_sh_per_se;
mutex_lock(&adev->grbm_idx_mutex);
for (i = 0; i < adev->gfx.config.max_shader_engines; i++) {
for (j = 0; j < adev->gfx.config.max_sh_per_se; j++) {
gfx_v7_0_select_se_sh(adev, i, j);
data = gfx_v7_0_get_rb_active_bitmap(adev);
active_rbs |= data << ((i * adev->gfx.config.max_sh_per_se + j) *
rb_bitmap_width_per_sh);
}
}
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
mutex_unlock(&adev->grbm_idx_mutex);
adev->gfx.config.backend_enable_mask = active_rbs;
adev->gfx.config.num_rbs = hweight32(active_rbs);
}
/**
* gmc_v7_0_init_compute_vmid - gart enable
*
* @rdev: amdgpu_device pointer
*
* Initialize compute vmid sh_mem registers
*
*/
#define DEFAULT_SH_MEM_BASES (0x6000)
#define FIRST_COMPUTE_VMID (8)
#define LAST_COMPUTE_VMID (16)
static void gmc_v7_0_init_compute_vmid(struct amdgpu_device *adev)
{
int i;
uint32_t sh_mem_config;
uint32_t sh_mem_bases;
/*
* Configure apertures:
* LDS: 0x60000000'00000000 - 0x60000001'00000000 (4GB)
* Scratch: 0x60000001'00000000 - 0x60000002'00000000 (4GB)
* GPUVM: 0x60010000'00000000 - 0x60020000'00000000 (1TB)
*/
sh_mem_bases = DEFAULT_SH_MEM_BASES | (DEFAULT_SH_MEM_BASES << 16);
sh_mem_config = SH_MEM_ALIGNMENT_MODE_UNALIGNED <<
SH_MEM_CONFIG__ALIGNMENT_MODE__SHIFT;
sh_mem_config |= MTYPE_NONCACHED << SH_MEM_CONFIG__DEFAULT_MTYPE__SHIFT;
mutex_lock(&adev->srbm_mutex);
for (i = FIRST_COMPUTE_VMID; i < LAST_COMPUTE_VMID; i++) {
cik_srbm_select(adev, 0, 0, 0, i);
/* CP and shaders */
WREG32(mmSH_MEM_CONFIG, sh_mem_config);
WREG32(mmSH_MEM_APE1_BASE, 1);
WREG32(mmSH_MEM_APE1_LIMIT, 0);
WREG32(mmSH_MEM_BASES, sh_mem_bases);
}
cik_srbm_select(adev, 0, 0, 0, 0);
mutex_unlock(&adev->srbm_mutex);
}
/**
* gfx_v7_0_gpu_init - setup the 3D engine
*
* @adev: amdgpu_device pointer
*
* Configures the 3D engine and tiling configuration
* registers so that the 3D engine is usable.
*/
static void gfx_v7_0_gpu_init(struct amdgpu_device *adev)
{
u32 tmp, sh_mem_cfg;
int i;
WREG32(mmGRBM_CNTL, (0xff << GRBM_CNTL__READ_TIMEOUT__SHIFT));
WREG32(mmGB_ADDR_CONFIG, adev->gfx.config.gb_addr_config);
WREG32(mmHDP_ADDR_CONFIG, adev->gfx.config.gb_addr_config);
WREG32(mmDMIF_ADDR_CALC, adev->gfx.config.gb_addr_config);
gfx_v7_0_tiling_mode_table_init(adev);
gfx_v7_0_setup_rb(adev);
gfx_v7_0_get_cu_info(adev);
/* set HW defaults for 3D engine */
WREG32(mmCP_MEQ_THRESHOLDS,
(0x30 << CP_MEQ_THRESHOLDS__MEQ1_START__SHIFT) |
(0x60 << CP_MEQ_THRESHOLDS__MEQ2_START__SHIFT));
mutex_lock(&adev->grbm_idx_mutex);
/*
* making sure that the following register writes will be broadcasted
* to all the shaders
*/
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
/* XXX SH_MEM regs */
/* where to put LDS, scratch, GPUVM in FSA64 space */
sh_mem_cfg = REG_SET_FIELD(0, SH_MEM_CONFIG, ALIGNMENT_MODE,
SH_MEM_ALIGNMENT_MODE_UNALIGNED);
mutex_lock(&adev->srbm_mutex);
for (i = 0; i < 16; i++) {
cik_srbm_select(adev, 0, 0, 0, i);
/* CP and shaders */
WREG32(mmSH_MEM_CONFIG, sh_mem_cfg);
WREG32(mmSH_MEM_APE1_BASE, 1);
WREG32(mmSH_MEM_APE1_LIMIT, 0);
WREG32(mmSH_MEM_BASES, 0);
}
cik_srbm_select(adev, 0, 0, 0, 0);
mutex_unlock(&adev->srbm_mutex);
gmc_v7_0_init_compute_vmid(adev);
WREG32(mmSX_DEBUG_1, 0x20);
WREG32(mmTA_CNTL_AUX, 0x00010000);
tmp = RREG32(mmSPI_CONFIG_CNTL);
tmp |= 0x03000000;
WREG32(mmSPI_CONFIG_CNTL, tmp);
WREG32(mmSQ_CONFIG, 1);
WREG32(mmDB_DEBUG, 0);
tmp = RREG32(mmDB_DEBUG2) & ~0xf00fffff;
tmp |= 0x00000400;
WREG32(mmDB_DEBUG2, tmp);
tmp = RREG32(mmDB_DEBUG3) & ~0x0002021c;
tmp |= 0x00020200;
WREG32(mmDB_DEBUG3, tmp);
tmp = RREG32(mmCB_HW_CONTROL) & ~0x00010000;
tmp |= 0x00018208;
WREG32(mmCB_HW_CONTROL, tmp);
WREG32(mmSPI_CONFIG_CNTL_1, (4 << SPI_CONFIG_CNTL_1__VTX_DONE_DELAY__SHIFT));
WREG32(mmPA_SC_FIFO_SIZE,
((adev->gfx.config.sc_prim_fifo_size_frontend << PA_SC_FIFO_SIZE__SC_FRONTEND_PRIM_FIFO_SIZE__SHIFT) |
(adev->gfx.config.sc_prim_fifo_size_backend << PA_SC_FIFO_SIZE__SC_BACKEND_PRIM_FIFO_SIZE__SHIFT) |
(adev->gfx.config.sc_hiz_tile_fifo_size << PA_SC_FIFO_SIZE__SC_HIZ_TILE_FIFO_SIZE__SHIFT) |
(adev->gfx.config.sc_earlyz_tile_fifo_size << PA_SC_FIFO_SIZE__SC_EARLYZ_TILE_FIFO_SIZE__SHIFT)));
WREG32(mmVGT_NUM_INSTANCES, 1);
WREG32(mmCP_PERFMON_CNTL, 0);
WREG32(mmSQ_CONFIG, 0);
WREG32(mmPA_SC_FORCE_EOV_MAX_CNTS,
((4095 << PA_SC_FORCE_EOV_MAX_CNTS__FORCE_EOV_MAX_CLK_CNT__SHIFT) |
(255 << PA_SC_FORCE_EOV_MAX_CNTS__FORCE_EOV_MAX_REZ_CNT__SHIFT)));
WREG32(mmVGT_CACHE_INVALIDATION,
(VC_AND_TC << VGT_CACHE_INVALIDATION__CACHE_INVALIDATION__SHIFT) |
(ES_AND_GS_AUTO << VGT_CACHE_INVALIDATION__AUTO_INVLD_EN__SHIFT));
WREG32(mmVGT_GS_VERTEX_REUSE, 16);
WREG32(mmPA_SC_LINE_STIPPLE_STATE, 0);
WREG32(mmPA_CL_ENHANCE, PA_CL_ENHANCE__CLIP_VTX_REORDER_ENA_MASK |
(3 << PA_CL_ENHANCE__NUM_CLIP_SEQ__SHIFT));
WREG32(mmPA_SC_ENHANCE, PA_SC_ENHANCE__ENABLE_PA_SC_OUT_OF_ORDER_MASK);
mutex_unlock(&adev->grbm_idx_mutex);
udelay(50);
}
/*
* GPU scratch registers helpers function.
*/
/**
* gfx_v7_0_scratch_init - setup driver info for CP scratch regs
*
* @adev: amdgpu_device pointer
*
* Set up the number and offset of the CP scratch registers.
* NOTE: use of CP scratch registers is a legacy inferface and
* is not used by default on newer asics (r6xx+). On newer asics,
* memory buffers are used for fences rather than scratch regs.
*/
static void gfx_v7_0_scratch_init(struct amdgpu_device *adev)
{
int i;
adev->gfx.scratch.num_reg = 7;
adev->gfx.scratch.reg_base = mmSCRATCH_REG0;
for (i = 0; i < adev->gfx.scratch.num_reg; i++) {
adev->gfx.scratch.free[i] = true;
adev->gfx.scratch.reg[i] = adev->gfx.scratch.reg_base + i;
}
}
/**
* gfx_v7_0_ring_test_ring - basic gfx ring test
*
* @adev: amdgpu_device pointer
* @ring: amdgpu_ring structure holding ring information
*
* Allocate a scratch register and write to it using the gfx ring (CIK).
* Provides a basic gfx ring test to verify that the ring is working.
* Used by gfx_v7_0_cp_gfx_resume();
* Returns 0 on success, error on failure.
*/
static int gfx_v7_0_ring_test_ring(struct amdgpu_ring *ring)
{
struct amdgpu_device *adev = ring->adev;
uint32_t scratch;
uint32_t tmp = 0;
unsigned i;
int r;
r = amdgpu_gfx_scratch_get(adev, &scratch);
if (r) {
DRM_ERROR("amdgpu: cp failed to get scratch reg (%d).\n", r);
return r;
}
WREG32(scratch, 0xCAFEDEAD);
r = amdgpu_ring_alloc(ring, 3);
if (r) {
DRM_ERROR("amdgpu: cp failed to lock ring %d (%d).\n", ring->idx, r);
amdgpu_gfx_scratch_free(adev, scratch);
return r;
}
amdgpu_ring_write(ring, PACKET3(PACKET3_SET_UCONFIG_REG, 1));
amdgpu_ring_write(ring, (scratch - PACKET3_SET_UCONFIG_REG_START));
amdgpu_ring_write(ring, 0xDEADBEEF);
amdgpu_ring_commit(ring);
for (i = 0; i < adev->usec_timeout; i++) {
tmp = RREG32(scratch);
if (tmp == 0xDEADBEEF)
break;
DRM_UDELAY(1);
}
if (i < adev->usec_timeout) {
DRM_INFO("ring test on %d succeeded in %d usecs\n", ring->idx, i);
} else {
DRM_ERROR("amdgpu: ring %d test failed (scratch(0x%04X)=0x%08X)\n",
ring->idx, scratch, tmp);
r = -EINVAL;
}
amdgpu_gfx_scratch_free(adev, scratch);
return r;
}
/**
* gfx_v7_0_ring_emit_hdp - emit an hdp flush on the cp
*
* @adev: amdgpu_device pointer
* @ridx: amdgpu ring index
*
* Emits an hdp flush on the cp.
*/
static void gfx_v7_0_ring_emit_hdp_flush(struct amdgpu_ring *ring)
{
u32 ref_and_mask;
int usepfp = ring->type == AMDGPU_RING_TYPE_COMPUTE ? 0 : 1;
if (ring->type == AMDGPU_RING_TYPE_COMPUTE) {
switch (ring->me) {
case 1:
ref_and_mask = GPU_HDP_FLUSH_DONE__CP2_MASK << ring->pipe;
break;
case 2:
ref_and_mask = GPU_HDP_FLUSH_DONE__CP6_MASK << ring->pipe;
break;
default:
return;
}
} else {
ref_and_mask = GPU_HDP_FLUSH_DONE__CP0_MASK;
}
amdgpu_ring_write(ring, PACKET3(PACKET3_WAIT_REG_MEM, 5));
amdgpu_ring_write(ring, (WAIT_REG_MEM_OPERATION(1) | /* write, wait, write */
WAIT_REG_MEM_FUNCTION(3) | /* == */
WAIT_REG_MEM_ENGINE(usepfp))); /* pfp or me */
amdgpu_ring_write(ring, mmGPU_HDP_FLUSH_REQ);
amdgpu_ring_write(ring, mmGPU_HDP_FLUSH_DONE);
amdgpu_ring_write(ring, ref_and_mask);
amdgpu_ring_write(ring, ref_and_mask);
amdgpu_ring_write(ring, 0x20); /* poll interval */
}
/**
* gfx_v7_0_ring_emit_hdp_invalidate - emit an hdp invalidate on the cp
*
* @adev: amdgpu_device pointer
* @ridx: amdgpu ring index
*
* Emits an hdp invalidate on the cp.
*/
static void gfx_v7_0_ring_emit_hdp_invalidate(struct amdgpu_ring *ring)
{
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, (WRITE_DATA_ENGINE_SEL(0) |
WRITE_DATA_DST_SEL(0) |
WR_CONFIRM));
amdgpu_ring_write(ring, mmHDP_DEBUG0);
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, 1);
}
/**
* gfx_v7_0_ring_emit_fence_gfx - emit a fence on the gfx ring
*
* @adev: amdgpu_device pointer
* @fence: amdgpu fence object
*
* Emits a fence sequnce number on the gfx ring and flushes
* GPU caches.
*/
static void gfx_v7_0_ring_emit_fence_gfx(struct amdgpu_ring *ring, u64 addr,
u64 seq, unsigned flags)
{
bool write64bit = flags & AMDGPU_FENCE_FLAG_64BIT;
bool int_sel = flags & AMDGPU_FENCE_FLAG_INT;
/* Workaround for cache flush problems. First send a dummy EOP
* event down the pipe with seq one below.
*/
amdgpu_ring_write(ring, PACKET3(PACKET3_EVENT_WRITE_EOP, 4));
amdgpu_ring_write(ring, (EOP_TCL1_ACTION_EN |
EOP_TC_ACTION_EN |
EVENT_TYPE(CACHE_FLUSH_AND_INV_TS_EVENT) |
EVENT_INDEX(5)));
amdgpu_ring_write(ring, addr & 0xfffffffc);
amdgpu_ring_write(ring, (upper_32_bits(addr) & 0xffff) |
DATA_SEL(1) | INT_SEL(0));
amdgpu_ring_write(ring, lower_32_bits(seq - 1));
amdgpu_ring_write(ring, upper_32_bits(seq - 1));
/* Then send the real EOP event down the pipe. */
amdgpu_ring_write(ring, PACKET3(PACKET3_EVENT_WRITE_EOP, 4));
amdgpu_ring_write(ring, (EOP_TCL1_ACTION_EN |
EOP_TC_ACTION_EN |
EVENT_TYPE(CACHE_FLUSH_AND_INV_TS_EVENT) |
EVENT_INDEX(5)));
amdgpu_ring_write(ring, addr & 0xfffffffc);
amdgpu_ring_write(ring, (upper_32_bits(addr) & 0xffff) |
DATA_SEL(write64bit ? 2 : 1) | INT_SEL(int_sel ? 2 : 0));
amdgpu_ring_write(ring, lower_32_bits(seq));
amdgpu_ring_write(ring, upper_32_bits(seq));
}
/**
* gfx_v7_0_ring_emit_fence_compute - emit a fence on the compute ring
*
* @adev: amdgpu_device pointer
* @fence: amdgpu fence object
*
* Emits a fence sequnce number on the compute ring and flushes
* GPU caches.
*/
static void gfx_v7_0_ring_emit_fence_compute(struct amdgpu_ring *ring,
u64 addr, u64 seq,
unsigned flags)
{
bool write64bit = flags & AMDGPU_FENCE_FLAG_64BIT;
bool int_sel = flags & AMDGPU_FENCE_FLAG_INT;
/* RELEASE_MEM - flush caches, send int */
amdgpu_ring_write(ring, PACKET3(PACKET3_RELEASE_MEM, 5));
amdgpu_ring_write(ring, (EOP_TCL1_ACTION_EN |
EOP_TC_ACTION_EN |
EVENT_TYPE(CACHE_FLUSH_AND_INV_TS_EVENT) |
EVENT_INDEX(5)));
amdgpu_ring_write(ring, DATA_SEL(write64bit ? 2 : 1) | INT_SEL(int_sel ? 2 : 0));
amdgpu_ring_write(ring, addr & 0xfffffffc);
amdgpu_ring_write(ring, upper_32_bits(addr));
amdgpu_ring_write(ring, lower_32_bits(seq));
amdgpu_ring_write(ring, upper_32_bits(seq));
}
/*
* IB stuff
*/
/**
* gfx_v7_0_ring_emit_ib - emit an IB (Indirect Buffer) on the ring
*
* @ring: amdgpu_ring structure holding ring information
* @ib: amdgpu indirect buffer object
*
* Emits an DE (drawing engine) or CE (constant engine) IB
* on the gfx ring. IBs are usually generated by userspace
* acceleration drivers and submitted to the kernel for
* sheduling on the ring. This function schedules the IB
* on the gfx ring for execution by the GPU.
*/
static void gfx_v7_0_ring_emit_ib_gfx(struct amdgpu_ring *ring,
struct amdgpu_ib *ib,
unsigned vm_id, bool ctx_switch)
{
u32 header, control = 0;
u32 next_rptr = ring->wptr + 5;
if (ctx_switch)
next_rptr += 2;
next_rptr += 4;
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, WRITE_DATA_DST_SEL(5) | WR_CONFIRM);
amdgpu_ring_write(ring, ring->next_rptr_gpu_addr & 0xfffffffc);
amdgpu_ring_write(ring, upper_32_bits(ring->next_rptr_gpu_addr) & 0xffffffff);
amdgpu_ring_write(ring, next_rptr);
/* insert SWITCH_BUFFER packet before first IB in the ring frame */
if (ctx_switch) {
amdgpu_ring_write(ring, PACKET3(PACKET3_SWITCH_BUFFER, 0));
amdgpu_ring_write(ring, 0);
}
if (ib->flags & AMDGPU_IB_FLAG_CE)
header = PACKET3(PACKET3_INDIRECT_BUFFER_CONST, 2);
else
header = PACKET3(PACKET3_INDIRECT_BUFFER, 2);
control |= ib->length_dw | (vm_id << 24);
amdgpu_ring_write(ring, header);
amdgpu_ring_write(ring,
#ifdef __BIG_ENDIAN
(2 << 0) |
#endif
(ib->gpu_addr & 0xFFFFFFFC));
amdgpu_ring_write(ring, upper_32_bits(ib->gpu_addr) & 0xFFFF);
amdgpu_ring_write(ring, control);
}
static void gfx_v7_0_ring_emit_ib_compute(struct amdgpu_ring *ring,
struct amdgpu_ib *ib,
unsigned vm_id, bool ctx_switch)
{
u32 header, control = 0;
u32 next_rptr = ring->wptr + 5;
control |= INDIRECT_BUFFER_VALID;
next_rptr += 4;
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, WRITE_DATA_DST_SEL(5) | WR_CONFIRM);
amdgpu_ring_write(ring, ring->next_rptr_gpu_addr & 0xfffffffc);
amdgpu_ring_write(ring, upper_32_bits(ring->next_rptr_gpu_addr) & 0xffffffff);
amdgpu_ring_write(ring, next_rptr);
header = PACKET3(PACKET3_INDIRECT_BUFFER, 2);
control |= ib->length_dw | (vm_id << 24);
amdgpu_ring_write(ring, header);
amdgpu_ring_write(ring,
#ifdef __BIG_ENDIAN
(2 << 0) |
#endif
(ib->gpu_addr & 0xFFFFFFFC));
amdgpu_ring_write(ring, upper_32_bits(ib->gpu_addr) & 0xFFFF);
amdgpu_ring_write(ring, control);
}
/**
* gfx_v7_0_ring_test_ib - basic ring IB test
*
* @ring: amdgpu_ring structure holding ring information
*
* Allocate an IB and execute it on the gfx ring (CIK).
* Provides a basic gfx ring test to verify that IBs are working.
* Returns 0 on success, error on failure.
*/
static int gfx_v7_0_ring_test_ib(struct amdgpu_ring *ring)
{
struct amdgpu_device *adev = ring->adev;
struct amdgpu_ib ib;
struct fence *f = NULL;
uint32_t scratch;
uint32_t tmp = 0;
unsigned i;
int r;
r = amdgpu_gfx_scratch_get(adev, &scratch);
if (r) {
DRM_ERROR("amdgpu: failed to get scratch reg (%d).\n", r);
return r;
}
WREG32(scratch, 0xCAFEDEAD);
memset(&ib, 0, sizeof(ib));
r = amdgpu_ib_get(adev, NULL, 256, &ib);
if (r) {
DRM_ERROR("amdgpu: failed to get ib (%d).\n", r);
goto err1;
}
ib.ptr[0] = PACKET3(PACKET3_SET_UCONFIG_REG, 1);
ib.ptr[1] = ((scratch - PACKET3_SET_UCONFIG_REG_START));
ib.ptr[2] = 0xDEADBEEF;
ib.length_dw = 3;
r = amdgpu_ib_schedule(ring, 1, &ib, NULL, NULL, &f);
if (r)
goto err2;
r = fence_wait(f, false);
if (r) {
DRM_ERROR("amdgpu: fence wait failed (%d).\n", r);
goto err2;
}
for (i = 0; i < adev->usec_timeout; i++) {
tmp = RREG32(scratch);
if (tmp == 0xDEADBEEF)
break;
DRM_UDELAY(1);
}
if (i < adev->usec_timeout) {
DRM_INFO("ib test on ring %d succeeded in %u usecs\n",
ring->idx, i);
goto err2;
} else {
DRM_ERROR("amdgpu: ib test failed (scratch(0x%04X)=0x%08X)\n",
scratch, tmp);
r = -EINVAL;
}
err2:
fence_put(f);
amdgpu_ib_free(adev, &ib, NULL);
fence_put(f);
err1:
amdgpu_gfx_scratch_free(adev, scratch);
return r;
}
/*
* CP.
* On CIK, gfx and compute now have independant command processors.
*
* GFX
* Gfx consists of a single ring and can process both gfx jobs and
* compute jobs. The gfx CP consists of three microengines (ME):
* PFP - Pre-Fetch Parser
* ME - Micro Engine
* CE - Constant Engine
* The PFP and ME make up what is considered the Drawing Engine (DE).
* The CE is an asynchronous engine used for updating buffer desciptors
* used by the DE so that they can be loaded into cache in parallel
* while the DE is processing state update packets.
*
* Compute
* The compute CP consists of two microengines (ME):
* MEC1 - Compute MicroEngine 1
* MEC2 - Compute MicroEngine 2
* Each MEC supports 4 compute pipes and each pipe supports 8 queues.
* The queues are exposed to userspace and are programmed directly
* by the compute runtime.
*/
/**
* gfx_v7_0_cp_gfx_enable - enable/disable the gfx CP MEs
*
* @adev: amdgpu_device pointer
* @enable: enable or disable the MEs
*
* Halts or unhalts the gfx MEs.
*/
static void gfx_v7_0_cp_gfx_enable(struct amdgpu_device *adev, bool enable)
{
int i;
if (enable) {
WREG32(mmCP_ME_CNTL, 0);
} else {
WREG32(mmCP_ME_CNTL, (CP_ME_CNTL__ME_HALT_MASK | CP_ME_CNTL__PFP_HALT_MASK | CP_ME_CNTL__CE_HALT_MASK));
for (i = 0; i < adev->gfx.num_gfx_rings; i++)
adev->gfx.gfx_ring[i].ready = false;
}
udelay(50);
}
/**
* gfx_v7_0_cp_gfx_load_microcode - load the gfx CP ME ucode
*
* @adev: amdgpu_device pointer
*
* Loads the gfx PFP, ME, and CE ucode.
* Returns 0 for success, -EINVAL if the ucode is not available.
*/
static int gfx_v7_0_cp_gfx_load_microcode(struct amdgpu_device *adev)
{
const struct gfx_firmware_header_v1_0 *pfp_hdr;
const struct gfx_firmware_header_v1_0 *ce_hdr;
const struct gfx_firmware_header_v1_0 *me_hdr;
const __le32 *fw_data;
unsigned i, fw_size;
if (!adev->gfx.me_fw || !adev->gfx.pfp_fw || !adev->gfx.ce_fw)
return -EINVAL;
pfp_hdr = (const struct gfx_firmware_header_v1_0 *)adev->gfx.pfp_fw->data;
ce_hdr = (const struct gfx_firmware_header_v1_0 *)adev->gfx.ce_fw->data;
me_hdr = (const struct gfx_firmware_header_v1_0 *)adev->gfx.me_fw->data;
amdgpu_ucode_print_gfx_hdr(&pfp_hdr->header);
amdgpu_ucode_print_gfx_hdr(&ce_hdr->header);
amdgpu_ucode_print_gfx_hdr(&me_hdr->header);
adev->gfx.pfp_fw_version = le32_to_cpu(pfp_hdr->header.ucode_version);
adev->gfx.ce_fw_version = le32_to_cpu(ce_hdr->header.ucode_version);
adev->gfx.me_fw_version = le32_to_cpu(me_hdr->header.ucode_version);
adev->gfx.me_feature_version = le32_to_cpu(me_hdr->ucode_feature_version);
adev->gfx.ce_feature_version = le32_to_cpu(ce_hdr->ucode_feature_version);
adev->gfx.pfp_feature_version = le32_to_cpu(pfp_hdr->ucode_feature_version);
gfx_v7_0_cp_gfx_enable(adev, false);
/* PFP */
fw_data = (const __le32 *)
(adev->gfx.pfp_fw->data +
le32_to_cpu(pfp_hdr->header.ucode_array_offset_bytes));
fw_size = le32_to_cpu(pfp_hdr->header.ucode_size_bytes) / 4;
WREG32(mmCP_PFP_UCODE_ADDR, 0);
for (i = 0; i < fw_size; i++)
WREG32(mmCP_PFP_UCODE_DATA, le32_to_cpup(fw_data++));
WREG32(mmCP_PFP_UCODE_ADDR, adev->gfx.pfp_fw_version);
/* CE */
fw_data = (const __le32 *)
(adev->gfx.ce_fw->data +
le32_to_cpu(ce_hdr->header.ucode_array_offset_bytes));
fw_size = le32_to_cpu(ce_hdr->header.ucode_size_bytes) / 4;
WREG32(mmCP_CE_UCODE_ADDR, 0);
for (i = 0; i < fw_size; i++)
WREG32(mmCP_CE_UCODE_DATA, le32_to_cpup(fw_data++));
WREG32(mmCP_CE_UCODE_ADDR, adev->gfx.ce_fw_version);
/* ME */
fw_data = (const __le32 *)
(adev->gfx.me_fw->data +
le32_to_cpu(me_hdr->header.ucode_array_offset_bytes));
fw_size = le32_to_cpu(me_hdr->header.ucode_size_bytes) / 4;
WREG32(mmCP_ME_RAM_WADDR, 0);
for (i = 0; i < fw_size; i++)
WREG32(mmCP_ME_RAM_DATA, le32_to_cpup(fw_data++));
WREG32(mmCP_ME_RAM_WADDR, adev->gfx.me_fw_version);
return 0;
}
/**
* gfx_v7_0_cp_gfx_start - start the gfx ring
*
* @adev: amdgpu_device pointer
*
* Enables the ring and loads the clear state context and other
* packets required to init the ring.
* Returns 0 for success, error for failure.
*/
static int gfx_v7_0_cp_gfx_start(struct amdgpu_device *adev)
{
struct amdgpu_ring *ring = &adev->gfx.gfx_ring[0];
const struct cs_section_def *sect = NULL;
const struct cs_extent_def *ext = NULL;
int r, i;
/* init the CP */
WREG32(mmCP_MAX_CONTEXT, adev->gfx.config.max_hw_contexts - 1);
WREG32(mmCP_ENDIAN_SWAP, 0);
WREG32(mmCP_DEVICE_ID, 1);
gfx_v7_0_cp_gfx_enable(adev, true);
r = amdgpu_ring_alloc(ring, gfx_v7_0_get_csb_size(adev) + 8);
if (r) {
DRM_ERROR("amdgpu: cp failed to lock ring (%d).\n", r);
return r;
}
/* init the CE partitions. CE only used for gfx on CIK */
amdgpu_ring_write(ring, PACKET3(PACKET3_SET_BASE, 2));
amdgpu_ring_write(ring, PACKET3_BASE_INDEX(CE_PARTITION_BASE));
amdgpu_ring_write(ring, 0x8000);
amdgpu_ring_write(ring, 0x8000);
/* clear state buffer */
amdgpu_ring_write(ring, PACKET3(PACKET3_PREAMBLE_CNTL, 0));
amdgpu_ring_write(ring, PACKET3_PREAMBLE_BEGIN_CLEAR_STATE);
amdgpu_ring_write(ring, PACKET3(PACKET3_CONTEXT_CONTROL, 1));
amdgpu_ring_write(ring, 0x80000000);
amdgpu_ring_write(ring, 0x80000000);
for (sect = adev->gfx.rlc.cs_data; sect->section != NULL; ++sect) {
for (ext = sect->section; ext->extent != NULL; ++ext) {
if (sect->id == SECT_CONTEXT) {
amdgpu_ring_write(ring,
PACKET3(PACKET3_SET_CONTEXT_REG, ext->reg_count));
amdgpu_ring_write(ring, ext->reg_index - PACKET3_SET_CONTEXT_REG_START);
for (i = 0; i < ext->reg_count; i++)
amdgpu_ring_write(ring, ext->extent[i]);
}
}
}
amdgpu_ring_write(ring, PACKET3(PACKET3_SET_CONTEXT_REG, 2));
amdgpu_ring_write(ring, mmPA_SC_RASTER_CONFIG - PACKET3_SET_CONTEXT_REG_START);
switch (adev->asic_type) {
case CHIP_BONAIRE:
amdgpu_ring_write(ring, 0x16000012);
amdgpu_ring_write(ring, 0x00000000);
break;
case CHIP_KAVERI:
amdgpu_ring_write(ring, 0x00000000); /* XXX */
amdgpu_ring_write(ring, 0x00000000);
break;
case CHIP_KABINI:
case CHIP_MULLINS:
amdgpu_ring_write(ring, 0x00000000); /* XXX */
amdgpu_ring_write(ring, 0x00000000);
break;
case CHIP_HAWAII:
amdgpu_ring_write(ring, 0x3a00161a);
amdgpu_ring_write(ring, 0x0000002e);
break;
default:
amdgpu_ring_write(ring, 0x00000000);
amdgpu_ring_write(ring, 0x00000000);
break;
}
amdgpu_ring_write(ring, PACKET3(PACKET3_PREAMBLE_CNTL, 0));
amdgpu_ring_write(ring, PACKET3_PREAMBLE_END_CLEAR_STATE);
amdgpu_ring_write(ring, PACKET3(PACKET3_CLEAR_STATE, 0));
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, PACKET3(PACKET3_SET_CONTEXT_REG, 2));
amdgpu_ring_write(ring, 0x00000316);
amdgpu_ring_write(ring, 0x0000000e); /* VGT_VERTEX_REUSE_BLOCK_CNTL */
amdgpu_ring_write(ring, 0x00000010); /* VGT_OUT_DEALLOC_CNTL */
amdgpu_ring_commit(ring);
return 0;
}
/**
* gfx_v7_0_cp_gfx_resume - setup the gfx ring buffer registers
*
* @adev: amdgpu_device pointer
*
* Program the location and size of the gfx ring buffer
* and test it to make sure it's working.
* Returns 0 for success, error for failure.
*/
static int gfx_v7_0_cp_gfx_resume(struct amdgpu_device *adev)
{
struct amdgpu_ring *ring;
u32 tmp;
u32 rb_bufsz;
u64 rb_addr, rptr_addr;
int r;
WREG32(mmCP_SEM_WAIT_TIMER, 0x0);
if (adev->asic_type != CHIP_HAWAII)
WREG32(mmCP_SEM_INCOMPLETE_TIMER_CNTL, 0x0);
/* Set the write pointer delay */
WREG32(mmCP_RB_WPTR_DELAY, 0);
/* set the RB to use vmid 0 */
WREG32(mmCP_RB_VMID, 0);
WREG32(mmSCRATCH_ADDR, 0);
/* ring 0 - compute and gfx */
/* Set ring buffer size */
ring = &adev->gfx.gfx_ring[0];
rb_bufsz = order_base_2(ring->ring_size / 8);
tmp = (order_base_2(AMDGPU_GPU_PAGE_SIZE/8) << 8) | rb_bufsz;
#ifdef __BIG_ENDIAN
tmp |= 2 << CP_RB0_CNTL__BUF_SWAP__SHIFT;
#endif
WREG32(mmCP_RB0_CNTL, tmp);
/* Initialize the ring buffer's read and write pointers */
WREG32(mmCP_RB0_CNTL, tmp | CP_RB0_CNTL__RB_RPTR_WR_ENA_MASK);
ring->wptr = 0;
WREG32(mmCP_RB0_WPTR, ring->wptr);
/* set the wb address wether it's enabled or not */
rptr_addr = adev->wb.gpu_addr + (ring->rptr_offs * 4);
WREG32(mmCP_RB0_RPTR_ADDR, lower_32_bits(rptr_addr));
WREG32(mmCP_RB0_RPTR_ADDR_HI, upper_32_bits(rptr_addr) & 0xFF);
/* scratch register shadowing is no longer supported */
WREG32(mmSCRATCH_UMSK, 0);
mdelay(1);
WREG32(mmCP_RB0_CNTL, tmp);
rb_addr = ring->gpu_addr >> 8;
WREG32(mmCP_RB0_BASE, rb_addr);
WREG32(mmCP_RB0_BASE_HI, upper_32_bits(rb_addr));
/* start the ring */
gfx_v7_0_cp_gfx_start(adev);
ring->ready = true;
r = amdgpu_ring_test_ring(ring);
if (r) {
ring->ready = false;
return r;
}
return 0;
}
static u32 gfx_v7_0_ring_get_rptr_gfx(struct amdgpu_ring *ring)
{
return ring->adev->wb.wb[ring->rptr_offs];
}
static u32 gfx_v7_0_ring_get_wptr_gfx(struct amdgpu_ring *ring)
{
struct amdgpu_device *adev = ring->adev;
return RREG32(mmCP_RB0_WPTR);
}
static void gfx_v7_0_ring_set_wptr_gfx(struct amdgpu_ring *ring)
{
struct amdgpu_device *adev = ring->adev;
WREG32(mmCP_RB0_WPTR, ring->wptr);
(void)RREG32(mmCP_RB0_WPTR);
}
static u32 gfx_v7_0_ring_get_rptr_compute(struct amdgpu_ring *ring)
{
return ring->adev->wb.wb[ring->rptr_offs];
}
static u32 gfx_v7_0_ring_get_wptr_compute(struct amdgpu_ring *ring)
{
/* XXX check if swapping is necessary on BE */
return ring->adev->wb.wb[ring->wptr_offs];
}
static void gfx_v7_0_ring_set_wptr_compute(struct amdgpu_ring *ring)
{
struct amdgpu_device *adev = ring->adev;
/* XXX check if swapping is necessary on BE */
adev->wb.wb[ring->wptr_offs] = ring->wptr;
WDOORBELL32(ring->doorbell_index, ring->wptr);
}
/**
* gfx_v7_0_cp_compute_enable - enable/disable the compute CP MEs
*
* @adev: amdgpu_device pointer
* @enable: enable or disable the MEs
*
* Halts or unhalts the compute MEs.
*/
static void gfx_v7_0_cp_compute_enable(struct amdgpu_device *adev, bool enable)
{
int i;
if (enable) {
WREG32(mmCP_MEC_CNTL, 0);
} else {
WREG32(mmCP_MEC_CNTL, (CP_MEC_CNTL__MEC_ME1_HALT_MASK | CP_MEC_CNTL__MEC_ME2_HALT_MASK));
for (i = 0; i < adev->gfx.num_compute_rings; i++)
adev->gfx.compute_ring[i].ready = false;
}
udelay(50);
}
/**
* gfx_v7_0_cp_compute_load_microcode - load the compute CP ME ucode
*
* @adev: amdgpu_device pointer
*
* Loads the compute MEC1&2 ucode.
* Returns 0 for success, -EINVAL if the ucode is not available.
*/
static int gfx_v7_0_cp_compute_load_microcode(struct amdgpu_device *adev)
{
const struct gfx_firmware_header_v1_0 *mec_hdr;
const __le32 *fw_data;
unsigned i, fw_size;
if (!adev->gfx.mec_fw)
return -EINVAL;
mec_hdr = (const struct gfx_firmware_header_v1_0 *)adev->gfx.mec_fw->data;
amdgpu_ucode_print_gfx_hdr(&mec_hdr->header);
adev->gfx.mec_fw_version = le32_to_cpu(mec_hdr->header.ucode_version);
adev->gfx.mec_feature_version = le32_to_cpu(
mec_hdr->ucode_feature_version);
gfx_v7_0_cp_compute_enable(adev, false);
/* MEC1 */
fw_data = (const __le32 *)
(adev->gfx.mec_fw->data +
le32_to_cpu(mec_hdr->header.ucode_array_offset_bytes));
fw_size = le32_to_cpu(mec_hdr->header.ucode_size_bytes) / 4;
WREG32(mmCP_MEC_ME1_UCODE_ADDR, 0);
for (i = 0; i < fw_size; i++)
WREG32(mmCP_MEC_ME1_UCODE_DATA, le32_to_cpup(fw_data++));
WREG32(mmCP_MEC_ME1_UCODE_ADDR, 0);
if (adev->asic_type == CHIP_KAVERI) {
const struct gfx_firmware_header_v1_0 *mec2_hdr;
if (!adev->gfx.mec2_fw)
return -EINVAL;
mec2_hdr = (const struct gfx_firmware_header_v1_0 *)adev->gfx.mec2_fw->data;
amdgpu_ucode_print_gfx_hdr(&mec2_hdr->header);
adev->gfx.mec2_fw_version = le32_to_cpu(mec2_hdr->header.ucode_version);
adev->gfx.mec2_feature_version = le32_to_cpu(
mec2_hdr->ucode_feature_version);
/* MEC2 */
fw_data = (const __le32 *)
(adev->gfx.mec2_fw->data +
le32_to_cpu(mec2_hdr->header.ucode_array_offset_bytes));
fw_size = le32_to_cpu(mec2_hdr->header.ucode_size_bytes) / 4;
WREG32(mmCP_MEC_ME2_UCODE_ADDR, 0);
for (i = 0; i < fw_size; i++)
WREG32(mmCP_MEC_ME2_UCODE_DATA, le32_to_cpup(fw_data++));
WREG32(mmCP_MEC_ME2_UCODE_ADDR, 0);
}
return 0;
}
/**
* gfx_v7_0_cp_compute_fini - stop the compute queues
*
* @adev: amdgpu_device pointer
*
* Stop the compute queues and tear down the driver queue
* info.
*/
static void gfx_v7_0_cp_compute_fini(struct amdgpu_device *adev)
{
int i, r;
for (i = 0; i < adev->gfx.num_compute_rings; i++) {
struct amdgpu_ring *ring = &adev->gfx.compute_ring[i];
if (ring->mqd_obj) {
r = amdgpu_bo_reserve(ring->mqd_obj, false);
if (unlikely(r != 0))
dev_warn(adev->dev, "(%d) reserve MQD bo failed\n", r);
amdgpu_bo_unpin(ring->mqd_obj);
amdgpu_bo_unreserve(ring->mqd_obj);
amdgpu_bo_unref(&ring->mqd_obj);
ring->mqd_obj = NULL;
}
}
}
static void gfx_v7_0_mec_fini(struct amdgpu_device *adev)
{
int r;
if (adev->gfx.mec.hpd_eop_obj) {
r = amdgpu_bo_reserve(adev->gfx.mec.hpd_eop_obj, false);
if (unlikely(r != 0))
dev_warn(adev->dev, "(%d) reserve HPD EOP bo failed\n", r);
amdgpu_bo_unpin(adev->gfx.mec.hpd_eop_obj);
amdgpu_bo_unreserve(adev->gfx.mec.hpd_eop_obj);
amdgpu_bo_unref(&adev->gfx.mec.hpd_eop_obj);
adev->gfx.mec.hpd_eop_obj = NULL;
}
}
#define MEC_HPD_SIZE 2048
static int gfx_v7_0_mec_init(struct amdgpu_device *adev)
{
int r;
u32 *hpd;
/*
* KV: 2 MEC, 4 Pipes/MEC, 8 Queues/Pipe - 64 Queues total
* CI/KB: 1 MEC, 4 Pipes/MEC, 8 Queues/Pipe - 32 Queues total
* Nonetheless, we assign only 1 pipe because all other pipes will
* be handled by KFD
*/
adev->gfx.mec.num_mec = 1;
adev->gfx.mec.num_pipe = 1;
adev->gfx.mec.num_queue = adev->gfx.mec.num_mec * adev->gfx.mec.num_pipe * 8;
if (adev->gfx.mec.hpd_eop_obj == NULL) {
r = amdgpu_bo_create(adev,
adev->gfx.mec.num_mec *adev->gfx.mec.num_pipe * MEC_HPD_SIZE * 2,
PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_GTT, 0, NULL, NULL,
&adev->gfx.mec.hpd_eop_obj);
if (r) {
dev_warn(adev->dev, "(%d) create HDP EOP bo failed\n", r);
return r;
}
}
r = amdgpu_bo_reserve(adev->gfx.mec.hpd_eop_obj, false);
if (unlikely(r != 0)) {
gfx_v7_0_mec_fini(adev);
return r;
}
r = amdgpu_bo_pin(adev->gfx.mec.hpd_eop_obj, AMDGPU_GEM_DOMAIN_GTT,
&adev->gfx.mec.hpd_eop_gpu_addr);
if (r) {
dev_warn(adev->dev, "(%d) pin HDP EOP bo failed\n", r);
gfx_v7_0_mec_fini(adev);
return r;
}
r = amdgpu_bo_kmap(adev->gfx.mec.hpd_eop_obj, (void **)&hpd);
if (r) {
dev_warn(adev->dev, "(%d) map HDP EOP bo failed\n", r);
gfx_v7_0_mec_fini(adev);
return r;
}
/* clear memory. Not sure if this is required or not */
memset(hpd, 0, adev->gfx.mec.num_mec *adev->gfx.mec.num_pipe * MEC_HPD_SIZE * 2);
amdgpu_bo_kunmap(adev->gfx.mec.hpd_eop_obj);
amdgpu_bo_unreserve(adev->gfx.mec.hpd_eop_obj);
return 0;
}
struct hqd_registers
{
u32 cp_mqd_base_addr;
u32 cp_mqd_base_addr_hi;
u32 cp_hqd_active;
u32 cp_hqd_vmid;
u32 cp_hqd_persistent_state;
u32 cp_hqd_pipe_priority;
u32 cp_hqd_queue_priority;
u32 cp_hqd_quantum;
u32 cp_hqd_pq_base;
u32 cp_hqd_pq_base_hi;
u32 cp_hqd_pq_rptr;
u32 cp_hqd_pq_rptr_report_addr;
u32 cp_hqd_pq_rptr_report_addr_hi;
u32 cp_hqd_pq_wptr_poll_addr;
u32 cp_hqd_pq_wptr_poll_addr_hi;
u32 cp_hqd_pq_doorbell_control;
u32 cp_hqd_pq_wptr;
u32 cp_hqd_pq_control;
u32 cp_hqd_ib_base_addr;
u32 cp_hqd_ib_base_addr_hi;
u32 cp_hqd_ib_rptr;
u32 cp_hqd_ib_control;
u32 cp_hqd_iq_timer;
u32 cp_hqd_iq_rptr;
u32 cp_hqd_dequeue_request;
u32 cp_hqd_dma_offload;
u32 cp_hqd_sema_cmd;
u32 cp_hqd_msg_type;
u32 cp_hqd_atomic0_preop_lo;
u32 cp_hqd_atomic0_preop_hi;
u32 cp_hqd_atomic1_preop_lo;
u32 cp_hqd_atomic1_preop_hi;
u32 cp_hqd_hq_scheduler0;
u32 cp_hqd_hq_scheduler1;
u32 cp_mqd_control;
};
struct bonaire_mqd
{
u32 header;
u32 dispatch_initiator;
u32 dimensions[3];
u32 start_idx[3];
u32 num_threads[3];
u32 pipeline_stat_enable;
u32 perf_counter_enable;
u32 pgm[2];
u32 tba[2];
u32 tma[2];
u32 pgm_rsrc[2];
u32 vmid;
u32 resource_limits;
u32 static_thread_mgmt01[2];
u32 tmp_ring_size;
u32 static_thread_mgmt23[2];
u32 restart[3];
u32 thread_trace_enable;
u32 reserved1;
u32 user_data[16];
u32 vgtcs_invoke_count[2];
struct hqd_registers queue_state;
u32 dequeue_cntr;
u32 interrupt_queue[64];
};
/**
* gfx_v7_0_cp_compute_resume - setup the compute queue registers
*
* @adev: amdgpu_device pointer
*
* Program the compute queues and test them to make sure they
* are working.
* Returns 0 for success, error for failure.
*/
static int gfx_v7_0_cp_compute_resume(struct amdgpu_device *adev)
{
int r, i, j;
u32 tmp;
bool use_doorbell = true;
u64 hqd_gpu_addr;
u64 mqd_gpu_addr;
u64 eop_gpu_addr;
u64 wb_gpu_addr;
u32 *buf;
struct bonaire_mqd *mqd;
gfx_v7_0_cp_compute_enable(adev, true);
/* fix up chicken bits */
tmp = RREG32(mmCP_CPF_DEBUG);
tmp |= (1 << 23);
WREG32(mmCP_CPF_DEBUG, tmp);
/* init the pipes */
mutex_lock(&adev->srbm_mutex);
for (i = 0; i < (adev->gfx.mec.num_pipe * adev->gfx.mec.num_mec); i++) {
int me = (i < 4) ? 1 : 2;
int pipe = (i < 4) ? i : (i - 4);
eop_gpu_addr = adev->gfx.mec.hpd_eop_gpu_addr + (i * MEC_HPD_SIZE * 2);
cik_srbm_select(adev, me, pipe, 0, 0);
/* write the EOP addr */
WREG32(mmCP_HPD_EOP_BASE_ADDR, eop_gpu_addr >> 8);
WREG32(mmCP_HPD_EOP_BASE_ADDR_HI, upper_32_bits(eop_gpu_addr) >> 8);
/* set the VMID assigned */
WREG32(mmCP_HPD_EOP_VMID, 0);
/* set the EOP size, register value is 2^(EOP_SIZE+1) dwords */
tmp = RREG32(mmCP_HPD_EOP_CONTROL);
tmp &= ~CP_HPD_EOP_CONTROL__EOP_SIZE_MASK;
tmp |= order_base_2(MEC_HPD_SIZE / 8);
WREG32(mmCP_HPD_EOP_CONTROL, tmp);
}
cik_srbm_select(adev, 0, 0, 0, 0);
mutex_unlock(&adev->srbm_mutex);
/* init the queues. Just two for now. */
for (i = 0; i < adev->gfx.num_compute_rings; i++) {
struct amdgpu_ring *ring = &adev->gfx.compute_ring[i];
if (ring->mqd_obj == NULL) {
r = amdgpu_bo_create(adev,
sizeof(struct bonaire_mqd),
PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_GTT, 0, NULL, NULL,
&ring->mqd_obj);
if (r) {
dev_warn(adev->dev, "(%d) create MQD bo failed\n", r);
return r;
}
}
r = amdgpu_bo_reserve(ring->mqd_obj, false);
if (unlikely(r != 0)) {
gfx_v7_0_cp_compute_fini(adev);
return r;
}
r = amdgpu_bo_pin(ring->mqd_obj, AMDGPU_GEM_DOMAIN_GTT,
&mqd_gpu_addr);
if (r) {
dev_warn(adev->dev, "(%d) pin MQD bo failed\n", r);
gfx_v7_0_cp_compute_fini(adev);
return r;
}
r = amdgpu_bo_kmap(ring->mqd_obj, (void **)&buf);
if (r) {
dev_warn(adev->dev, "(%d) map MQD bo failed\n", r);
gfx_v7_0_cp_compute_fini(adev);
return r;
}
/* init the mqd struct */
memset(buf, 0, sizeof(struct bonaire_mqd));
mqd = (struct bonaire_mqd *)buf;
mqd->header = 0xC0310800;
mqd->static_thread_mgmt01[0] = 0xffffffff;
mqd->static_thread_mgmt01[1] = 0xffffffff;
mqd->static_thread_mgmt23[0] = 0xffffffff;
mqd->static_thread_mgmt23[1] = 0xffffffff;
mutex_lock(&adev->srbm_mutex);
cik_srbm_select(adev, ring->me,
ring->pipe,
ring->queue, 0);
/* disable wptr polling */
tmp = RREG32(mmCP_PQ_WPTR_POLL_CNTL);
tmp &= ~CP_PQ_WPTR_POLL_CNTL__EN_MASK;
WREG32(mmCP_PQ_WPTR_POLL_CNTL, tmp);
/* enable doorbell? */
mqd->queue_state.cp_hqd_pq_doorbell_control =
RREG32(mmCP_HQD_PQ_DOORBELL_CONTROL);
if (use_doorbell)
mqd->queue_state.cp_hqd_pq_doorbell_control |= CP_HQD_PQ_DOORBELL_CONTROL__DOORBELL_EN_MASK;
else
mqd->queue_state.cp_hqd_pq_doorbell_control &= ~CP_HQD_PQ_DOORBELL_CONTROL__DOORBELL_EN_MASK;
WREG32(mmCP_HQD_PQ_DOORBELL_CONTROL,
mqd->queue_state.cp_hqd_pq_doorbell_control);
/* disable the queue if it's active */
mqd->queue_state.cp_hqd_dequeue_request = 0;
mqd->queue_state.cp_hqd_pq_rptr = 0;
mqd->queue_state.cp_hqd_pq_wptr= 0;
if (RREG32(mmCP_HQD_ACTIVE) & 1) {
WREG32(mmCP_HQD_DEQUEUE_REQUEST, 1);
for (j = 0; j < adev->usec_timeout; j++) {
if (!(RREG32(mmCP_HQD_ACTIVE) & 1))
break;
udelay(1);
}
WREG32(mmCP_HQD_DEQUEUE_REQUEST, mqd->queue_state.cp_hqd_dequeue_request);
WREG32(mmCP_HQD_PQ_RPTR, mqd->queue_state.cp_hqd_pq_rptr);
WREG32(mmCP_HQD_PQ_WPTR, mqd->queue_state.cp_hqd_pq_wptr);
}
/* set the pointer to the MQD */
mqd->queue_state.cp_mqd_base_addr = mqd_gpu_addr & 0xfffffffc;
mqd->queue_state.cp_mqd_base_addr_hi = upper_32_bits(mqd_gpu_addr);
WREG32(mmCP_MQD_BASE_ADDR, mqd->queue_state.cp_mqd_base_addr);
WREG32(mmCP_MQD_BASE_ADDR_HI, mqd->queue_state.cp_mqd_base_addr_hi);
/* set MQD vmid to 0 */
mqd->queue_state.cp_mqd_control = RREG32(mmCP_MQD_CONTROL);
mqd->queue_state.cp_mqd_control &= ~CP_MQD_CONTROL__VMID_MASK;
WREG32(mmCP_MQD_CONTROL, mqd->queue_state.cp_mqd_control);
/* set the pointer to the HQD, this is similar CP_RB0_BASE/_HI */
hqd_gpu_addr = ring->gpu_addr >> 8;
mqd->queue_state.cp_hqd_pq_base = hqd_gpu_addr;
mqd->queue_state.cp_hqd_pq_base_hi = upper_32_bits(hqd_gpu_addr);
WREG32(mmCP_HQD_PQ_BASE, mqd->queue_state.cp_hqd_pq_base);
WREG32(mmCP_HQD_PQ_BASE_HI, mqd->queue_state.cp_hqd_pq_base_hi);
/* set up the HQD, this is similar to CP_RB0_CNTL */
mqd->queue_state.cp_hqd_pq_control = RREG32(mmCP_HQD_PQ_CONTROL);
mqd->queue_state.cp_hqd_pq_control &=
~(CP_HQD_PQ_CONTROL__QUEUE_SIZE_MASK |
CP_HQD_PQ_CONTROL__RPTR_BLOCK_SIZE_MASK);
mqd->queue_state.cp_hqd_pq_control |=
order_base_2(ring->ring_size / 8);
mqd->queue_state.cp_hqd_pq_control |=
(order_base_2(AMDGPU_GPU_PAGE_SIZE/8) << 8);
#ifdef __BIG_ENDIAN
mqd->queue_state.cp_hqd_pq_control |=
2 << CP_HQD_PQ_CONTROL__ENDIAN_SWAP__SHIFT;
#endif
mqd->queue_state.cp_hqd_pq_control &=
~(CP_HQD_PQ_CONTROL__UNORD_DISPATCH_MASK |
CP_HQD_PQ_CONTROL__ROQ_PQ_IB_FLIP_MASK |
CP_HQD_PQ_CONTROL__PQ_VOLATILE_MASK);
mqd->queue_state.cp_hqd_pq_control |=
CP_HQD_PQ_CONTROL__PRIV_STATE_MASK |
CP_HQD_PQ_CONTROL__KMD_QUEUE_MASK; /* assuming kernel queue control */
WREG32(mmCP_HQD_PQ_CONTROL, mqd->queue_state.cp_hqd_pq_control);
/* only used if CP_PQ_WPTR_POLL_CNTL.CP_PQ_WPTR_POLL_CNTL__EN_MASK=1 */
wb_gpu_addr = adev->wb.gpu_addr + (ring->wptr_offs * 4);
mqd->queue_state.cp_hqd_pq_wptr_poll_addr = wb_gpu_addr & 0xfffffffc;
mqd->queue_state.cp_hqd_pq_wptr_poll_addr_hi = upper_32_bits(wb_gpu_addr) & 0xffff;
WREG32(mmCP_HQD_PQ_WPTR_POLL_ADDR, mqd->queue_state.cp_hqd_pq_wptr_poll_addr);
WREG32(mmCP_HQD_PQ_WPTR_POLL_ADDR_HI,
mqd->queue_state.cp_hqd_pq_wptr_poll_addr_hi);
/* set the wb address wether it's enabled or not */
wb_gpu_addr = adev->wb.gpu_addr + (ring->rptr_offs * 4);
mqd->queue_state.cp_hqd_pq_rptr_report_addr = wb_gpu_addr & 0xfffffffc;
mqd->queue_state.cp_hqd_pq_rptr_report_addr_hi =
upper_32_bits(wb_gpu_addr) & 0xffff;
WREG32(mmCP_HQD_PQ_RPTR_REPORT_ADDR,
mqd->queue_state.cp_hqd_pq_rptr_report_addr);
WREG32(mmCP_HQD_PQ_RPTR_REPORT_ADDR_HI,
mqd->queue_state.cp_hqd_pq_rptr_report_addr_hi);
/* enable the doorbell if requested */
if (use_doorbell) {
mqd->queue_state.cp_hqd_pq_doorbell_control =
RREG32(mmCP_HQD_PQ_DOORBELL_CONTROL);
mqd->queue_state.cp_hqd_pq_doorbell_control &=
~CP_HQD_PQ_DOORBELL_CONTROL__DOORBELL_OFFSET_MASK;
mqd->queue_state.cp_hqd_pq_doorbell_control |=
(ring->doorbell_index <<
CP_HQD_PQ_DOORBELL_CONTROL__DOORBELL_OFFSET__SHIFT);
mqd->queue_state.cp_hqd_pq_doorbell_control |=
CP_HQD_PQ_DOORBELL_CONTROL__DOORBELL_EN_MASK;
mqd->queue_state.cp_hqd_pq_doorbell_control &=
~(CP_HQD_PQ_DOORBELL_CONTROL__DOORBELL_SOURCE_MASK |
CP_HQD_PQ_DOORBELL_CONTROL__DOORBELL_HIT_MASK);
} else {
mqd->queue_state.cp_hqd_pq_doorbell_control = 0;
}
WREG32(mmCP_HQD_PQ_DOORBELL_CONTROL,
mqd->queue_state.cp_hqd_pq_doorbell_control);
/* read and write pointers, similar to CP_RB0_WPTR/_RPTR */
ring->wptr = 0;
mqd->queue_state.cp_hqd_pq_wptr = ring->wptr;
WREG32(mmCP_HQD_PQ_WPTR, mqd->queue_state.cp_hqd_pq_wptr);
mqd->queue_state.cp_hqd_pq_rptr = RREG32(mmCP_HQD_PQ_RPTR);
/* set the vmid for the queue */
mqd->queue_state.cp_hqd_vmid = 0;
WREG32(mmCP_HQD_VMID, mqd->queue_state.cp_hqd_vmid);
/* activate the queue */
mqd->queue_state.cp_hqd_active = 1;
WREG32(mmCP_HQD_ACTIVE, mqd->queue_state.cp_hqd_active);
cik_srbm_select(adev, 0, 0, 0, 0);
mutex_unlock(&adev->srbm_mutex);
amdgpu_bo_kunmap(ring->mqd_obj);
amdgpu_bo_unreserve(ring->mqd_obj);
ring->ready = true;
r = amdgpu_ring_test_ring(ring);
if (r)
ring->ready = false;
}
return 0;
}
static void gfx_v7_0_cp_enable(struct amdgpu_device *adev, bool enable)
{
gfx_v7_0_cp_gfx_enable(adev, enable);
gfx_v7_0_cp_compute_enable(adev, enable);
}
static int gfx_v7_0_cp_load_microcode(struct amdgpu_device *adev)
{
int r;
r = gfx_v7_0_cp_gfx_load_microcode(adev);
if (r)
return r;
r = gfx_v7_0_cp_compute_load_microcode(adev);
if (r)
return r;
return 0;
}
static void gfx_v7_0_enable_gui_idle_interrupt(struct amdgpu_device *adev,
bool enable)
{
u32 tmp = RREG32(mmCP_INT_CNTL_RING0);
if (enable)
tmp |= (CP_INT_CNTL_RING0__CNTX_BUSY_INT_ENABLE_MASK |
CP_INT_CNTL_RING0__CNTX_EMPTY_INT_ENABLE_MASK);
else
tmp &= ~(CP_INT_CNTL_RING0__CNTX_BUSY_INT_ENABLE_MASK |
CP_INT_CNTL_RING0__CNTX_EMPTY_INT_ENABLE_MASK);
WREG32(mmCP_INT_CNTL_RING0, tmp);
}
static int gfx_v7_0_cp_resume(struct amdgpu_device *adev)
{
int r;
gfx_v7_0_enable_gui_idle_interrupt(adev, false);
r = gfx_v7_0_cp_load_microcode(adev);
if (r)
return r;
r = gfx_v7_0_cp_gfx_resume(adev);
if (r)
return r;
r = gfx_v7_0_cp_compute_resume(adev);
if (r)
return r;
gfx_v7_0_enable_gui_idle_interrupt(adev, true);
return 0;
}
/**
* gfx_v7_0_ring_emit_vm_flush - cik vm flush using the CP
*
* @ring: the ring to emmit the commands to
*
* Sync the command pipeline with the PFP. E.g. wait for everything
* to be completed.
*/
static void gfx_v7_0_ring_emit_pipeline_sync(struct amdgpu_ring *ring)
{
int usepfp = (ring->type == AMDGPU_RING_TYPE_GFX);
uint32_t seq = ring->fence_drv.sync_seq;
uint64_t addr = ring->fence_drv.gpu_addr;
amdgpu_ring_write(ring, PACKET3(PACKET3_WAIT_REG_MEM, 5));
amdgpu_ring_write(ring, (WAIT_REG_MEM_MEM_SPACE(1) | /* memory */
WAIT_REG_MEM_FUNCTION(3) | /* equal */
WAIT_REG_MEM_ENGINE(usepfp))); /* pfp or me */
amdgpu_ring_write(ring, addr & 0xfffffffc);
amdgpu_ring_write(ring, upper_32_bits(addr) & 0xffffffff);
amdgpu_ring_write(ring, seq);
amdgpu_ring_write(ring, 0xffffffff);
amdgpu_ring_write(ring, 4); /* poll interval */
if (usepfp) {
/* synce CE with ME to prevent CE fetch CEIB before context switch done */
amdgpu_ring_write(ring, PACKET3(PACKET3_SWITCH_BUFFER, 0));
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, PACKET3(PACKET3_SWITCH_BUFFER, 0));
amdgpu_ring_write(ring, 0);
}
}
/*
* vm
* VMID 0 is the physical GPU addresses as used by the kernel.
* VMIDs 1-15 are used for userspace clients and are handled
* by the amdgpu vm/hsa code.
*/
/**
* gfx_v7_0_ring_emit_vm_flush - cik vm flush using the CP
*
* @adev: amdgpu_device pointer
*
* Update the page table base and flush the VM TLB
* using the CP (CIK).
*/
static void gfx_v7_0_ring_emit_vm_flush(struct amdgpu_ring *ring,
unsigned vm_id, uint64_t pd_addr)
{
int usepfp = (ring->type == AMDGPU_RING_TYPE_GFX);
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, (WRITE_DATA_ENGINE_SEL(usepfp) |
WRITE_DATA_DST_SEL(0)));
if (vm_id < 8) {
amdgpu_ring_write(ring,
(mmVM_CONTEXT0_PAGE_TABLE_BASE_ADDR + vm_id));
} else {
amdgpu_ring_write(ring,
(mmVM_CONTEXT8_PAGE_TABLE_BASE_ADDR + vm_id - 8));
}
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, pd_addr >> 12);
/* bits 0-15 are the VM contexts0-15 */
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, (WRITE_DATA_ENGINE_SEL(0) |
WRITE_DATA_DST_SEL(0)));
amdgpu_ring_write(ring, mmVM_INVALIDATE_REQUEST);
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, 1 << vm_id);
/* wait for the invalidate to complete */
amdgpu_ring_write(ring, PACKET3(PACKET3_WAIT_REG_MEM, 5));
amdgpu_ring_write(ring, (WAIT_REG_MEM_OPERATION(0) | /* wait */
WAIT_REG_MEM_FUNCTION(0) | /* always */
WAIT_REG_MEM_ENGINE(0))); /* me */
amdgpu_ring_write(ring, mmVM_INVALIDATE_REQUEST);
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, 0); /* ref */
amdgpu_ring_write(ring, 0); /* mask */
amdgpu_ring_write(ring, 0x20); /* poll interval */
/* compute doesn't have PFP */
if (usepfp) {
/* sync PFP to ME, otherwise we might get invalid PFP reads */
amdgpu_ring_write(ring, PACKET3(PACKET3_PFP_SYNC_ME, 0));
amdgpu_ring_write(ring, 0x0);
/* synce CE with ME to prevent CE fetch CEIB before context switch done */
amdgpu_ring_write(ring, PACKET3(PACKET3_SWITCH_BUFFER, 0));
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, PACKET3(PACKET3_SWITCH_BUFFER, 0));
amdgpu_ring_write(ring, 0);
}
}
/*
* RLC
* The RLC is a multi-purpose microengine that handles a
* variety of functions.
*/
static void gfx_v7_0_rlc_fini(struct amdgpu_device *adev)
{
int r;
/* save restore block */
if (adev->gfx.rlc.save_restore_obj) {
r = amdgpu_bo_reserve(adev->gfx.rlc.save_restore_obj, false);
if (unlikely(r != 0))
dev_warn(adev->dev, "(%d) reserve RLC sr bo failed\n", r);
amdgpu_bo_unpin(adev->gfx.rlc.save_restore_obj);
amdgpu_bo_unreserve(adev->gfx.rlc.save_restore_obj);
amdgpu_bo_unref(&adev->gfx.rlc.save_restore_obj);
adev->gfx.rlc.save_restore_obj = NULL;
}
/* clear state block */
if (adev->gfx.rlc.clear_state_obj) {
r = amdgpu_bo_reserve(adev->gfx.rlc.clear_state_obj, false);
if (unlikely(r != 0))
dev_warn(adev->dev, "(%d) reserve RLC c bo failed\n", r);
amdgpu_bo_unpin(adev->gfx.rlc.clear_state_obj);
amdgpu_bo_unreserve(adev->gfx.rlc.clear_state_obj);
amdgpu_bo_unref(&adev->gfx.rlc.clear_state_obj);
adev->gfx.rlc.clear_state_obj = NULL;
}
/* clear state block */
if (adev->gfx.rlc.cp_table_obj) {
r = amdgpu_bo_reserve(adev->gfx.rlc.cp_table_obj, false);
if (unlikely(r != 0))
dev_warn(adev->dev, "(%d) reserve RLC cp table bo failed\n", r);
amdgpu_bo_unpin(adev->gfx.rlc.cp_table_obj);
amdgpu_bo_unreserve(adev->gfx.rlc.cp_table_obj);
amdgpu_bo_unref(&adev->gfx.rlc.cp_table_obj);
adev->gfx.rlc.cp_table_obj = NULL;
}
}
static int gfx_v7_0_rlc_init(struct amdgpu_device *adev)
{
const u32 *src_ptr;
volatile u32 *dst_ptr;
u32 dws, i;
const struct cs_section_def *cs_data;
int r;
/* allocate rlc buffers */
if (adev->flags & AMD_IS_APU) {
if (adev->asic_type == CHIP_KAVERI) {
adev->gfx.rlc.reg_list = spectre_rlc_save_restore_register_list;
adev->gfx.rlc.reg_list_size =
(u32)ARRAY_SIZE(spectre_rlc_save_restore_register_list);
} else {
adev->gfx.rlc.reg_list = kalindi_rlc_save_restore_register_list;
adev->gfx.rlc.reg_list_size =
(u32)ARRAY_SIZE(kalindi_rlc_save_restore_register_list);
}
}
adev->gfx.rlc.cs_data = ci_cs_data;
adev->gfx.rlc.cp_table_size = CP_ME_TABLE_SIZE * 5 * 4;
src_ptr = adev->gfx.rlc.reg_list;
dws = adev->gfx.rlc.reg_list_size;
dws += (5 * 16) + 48 + 48 + 64;
cs_data = adev->gfx.rlc.cs_data;
if (src_ptr) {
/* save restore block */
if (adev->gfx.rlc.save_restore_obj == NULL) {
r = amdgpu_bo_create(adev, dws * 4, PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_VRAM,
AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
NULL, NULL,
&adev->gfx.rlc.save_restore_obj);
if (r) {
dev_warn(adev->dev, "(%d) create RLC sr bo failed\n", r);
return r;
}
}
r = amdgpu_bo_reserve(adev->gfx.rlc.save_restore_obj, false);
if (unlikely(r != 0)) {
gfx_v7_0_rlc_fini(adev);
return r;
}
r = amdgpu_bo_pin(adev->gfx.rlc.save_restore_obj, AMDGPU_GEM_DOMAIN_VRAM,
&adev->gfx.rlc.save_restore_gpu_addr);
if (r) {
amdgpu_bo_unreserve(adev->gfx.rlc.save_restore_obj);
dev_warn(adev->dev, "(%d) pin RLC sr bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
r = amdgpu_bo_kmap(adev->gfx.rlc.save_restore_obj, (void **)&adev->gfx.rlc.sr_ptr);
if (r) {
dev_warn(adev->dev, "(%d) map RLC sr bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
/* write the sr buffer */
dst_ptr = adev->gfx.rlc.sr_ptr;
for (i = 0; i < adev->gfx.rlc.reg_list_size; i++)
dst_ptr[i] = cpu_to_le32(src_ptr[i]);
amdgpu_bo_kunmap(adev->gfx.rlc.save_restore_obj);
amdgpu_bo_unreserve(adev->gfx.rlc.save_restore_obj);
}
if (cs_data) {
/* clear state block */
adev->gfx.rlc.clear_state_size = dws = gfx_v7_0_get_csb_size(adev);
if (adev->gfx.rlc.clear_state_obj == NULL) {
r = amdgpu_bo_create(adev, dws * 4, PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_VRAM,
AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
NULL, NULL,
&adev->gfx.rlc.clear_state_obj);
if (r) {
dev_warn(adev->dev, "(%d) create RLC c bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
}
r = amdgpu_bo_reserve(adev->gfx.rlc.clear_state_obj, false);
if (unlikely(r != 0)) {
gfx_v7_0_rlc_fini(adev);
return r;
}
r = amdgpu_bo_pin(adev->gfx.rlc.clear_state_obj, AMDGPU_GEM_DOMAIN_VRAM,
&adev->gfx.rlc.clear_state_gpu_addr);
if (r) {
amdgpu_bo_unreserve(adev->gfx.rlc.clear_state_obj);
dev_warn(adev->dev, "(%d) pin RLC c bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
r = amdgpu_bo_kmap(adev->gfx.rlc.clear_state_obj, (void **)&adev->gfx.rlc.cs_ptr);
if (r) {
dev_warn(adev->dev, "(%d) map RLC c bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
/* set up the cs buffer */
dst_ptr = adev->gfx.rlc.cs_ptr;
gfx_v7_0_get_csb_buffer(adev, dst_ptr);
amdgpu_bo_kunmap(adev->gfx.rlc.clear_state_obj);
amdgpu_bo_unreserve(adev->gfx.rlc.clear_state_obj);
}
if (adev->gfx.rlc.cp_table_size) {
if (adev->gfx.rlc.cp_table_obj == NULL) {
r = amdgpu_bo_create(adev, adev->gfx.rlc.cp_table_size, PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_VRAM,
AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
NULL, NULL,
&adev->gfx.rlc.cp_table_obj);
if (r) {
dev_warn(adev->dev, "(%d) create RLC cp table bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
}
r = amdgpu_bo_reserve(adev->gfx.rlc.cp_table_obj, false);
if (unlikely(r != 0)) {
dev_warn(adev->dev, "(%d) reserve RLC cp table bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
r = amdgpu_bo_pin(adev->gfx.rlc.cp_table_obj, AMDGPU_GEM_DOMAIN_VRAM,
&adev->gfx.rlc.cp_table_gpu_addr);
if (r) {
amdgpu_bo_unreserve(adev->gfx.rlc.cp_table_obj);
dev_warn(adev->dev, "(%d) pin RLC cp_table bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
r = amdgpu_bo_kmap(adev->gfx.rlc.cp_table_obj, (void **)&adev->gfx.rlc.cp_table_ptr);
if (r) {
dev_warn(adev->dev, "(%d) map RLC cp table bo failed\n", r);
gfx_v7_0_rlc_fini(adev);
return r;
}
gfx_v7_0_init_cp_pg_table(adev);
amdgpu_bo_kunmap(adev->gfx.rlc.cp_table_obj);
amdgpu_bo_unreserve(adev->gfx.rlc.cp_table_obj);
}
return 0;
}
static void gfx_v7_0_enable_lbpw(struct amdgpu_device *adev, bool enable)
{
u32 tmp;
tmp = RREG32(mmRLC_LB_CNTL);
if (enable)
tmp |= RLC_LB_CNTL__LOAD_BALANCE_ENABLE_MASK;
else
tmp &= ~RLC_LB_CNTL__LOAD_BALANCE_ENABLE_MASK;
WREG32(mmRLC_LB_CNTL, tmp);
}
static void gfx_v7_0_wait_for_rlc_serdes(struct amdgpu_device *adev)
{
u32 i, j, k;
u32 mask;
mutex_lock(&adev->grbm_idx_mutex);
for (i = 0; i < adev->gfx.config.max_shader_engines; i++) {
for (j = 0; j < adev->gfx.config.max_sh_per_se; j++) {
gfx_v7_0_select_se_sh(adev, i, j);
for (k = 0; k < adev->usec_timeout; k++) {
if (RREG32(mmRLC_SERDES_CU_MASTER_BUSY) == 0)
break;
udelay(1);
}
}
}
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
mutex_unlock(&adev->grbm_idx_mutex);
mask = RLC_SERDES_NONCU_MASTER_BUSY__SE_MASTER_BUSY_MASK |
RLC_SERDES_NONCU_MASTER_BUSY__GC_MASTER_BUSY_MASK |
RLC_SERDES_NONCU_MASTER_BUSY__TC0_MASTER_BUSY_MASK |
RLC_SERDES_NONCU_MASTER_BUSY__TC1_MASTER_BUSY_MASK;
for (k = 0; k < adev->usec_timeout; k++) {
if ((RREG32(mmRLC_SERDES_NONCU_MASTER_BUSY) & mask) == 0)
break;
udelay(1);
}
}
static void gfx_v7_0_update_rlc(struct amdgpu_device *adev, u32 rlc)
{
u32 tmp;
tmp = RREG32(mmRLC_CNTL);
if (tmp != rlc)
WREG32(mmRLC_CNTL, rlc);
}
static u32 gfx_v7_0_halt_rlc(struct amdgpu_device *adev)
{
u32 data, orig;
orig = data = RREG32(mmRLC_CNTL);
if (data & RLC_CNTL__RLC_ENABLE_F32_MASK) {
u32 i;
data &= ~RLC_CNTL__RLC_ENABLE_F32_MASK;
WREG32(mmRLC_CNTL, data);
for (i = 0; i < adev->usec_timeout; i++) {
if ((RREG32(mmRLC_GPM_STAT) & RLC_GPM_STAT__RLC_BUSY_MASK) == 0)
break;
udelay(1);
}
gfx_v7_0_wait_for_rlc_serdes(adev);
}
return orig;
}
void gfx_v7_0_enter_rlc_safe_mode(struct amdgpu_device *adev)
{
u32 tmp, i, mask;
tmp = 0x1 | (1 << 1);
WREG32(mmRLC_GPR_REG2, tmp);
mask = RLC_GPM_STAT__GFX_POWER_STATUS_MASK |
RLC_GPM_STAT__GFX_CLOCK_STATUS_MASK;
for (i = 0; i < adev->usec_timeout; i++) {
if ((RREG32(mmRLC_GPM_STAT) & mask) == mask)
break;
udelay(1);
}
for (i = 0; i < adev->usec_timeout; i++) {
if ((RREG32(mmRLC_GPR_REG2) & 0x1) == 0)
break;
udelay(1);
}
}
void gfx_v7_0_exit_rlc_safe_mode(struct amdgpu_device *adev)
{
u32 tmp;
tmp = 0x1 | (0 << 1);
WREG32(mmRLC_GPR_REG2, tmp);
}
/**
* gfx_v7_0_rlc_stop - stop the RLC ME
*
* @adev: amdgpu_device pointer
*
* Halt the RLC ME (MicroEngine) (CIK).
*/
void gfx_v7_0_rlc_stop(struct amdgpu_device *adev)
{
WREG32(mmRLC_CNTL, 0);
gfx_v7_0_enable_gui_idle_interrupt(adev, false);
gfx_v7_0_wait_for_rlc_serdes(adev);
}
/**
* gfx_v7_0_rlc_start - start the RLC ME
*
* @adev: amdgpu_device pointer
*
* Unhalt the RLC ME (MicroEngine) (CIK).
*/
static void gfx_v7_0_rlc_start(struct amdgpu_device *adev)
{
WREG32(mmRLC_CNTL, RLC_CNTL__RLC_ENABLE_F32_MASK);
gfx_v7_0_enable_gui_idle_interrupt(adev, true);
udelay(50);
}
static void gfx_v7_0_rlc_reset(struct amdgpu_device *adev)
{
u32 tmp = RREG32(mmGRBM_SOFT_RESET);
tmp |= GRBM_SOFT_RESET__SOFT_RESET_RLC_MASK;
WREG32(mmGRBM_SOFT_RESET, tmp);
udelay(50);
tmp &= ~GRBM_SOFT_RESET__SOFT_RESET_RLC_MASK;
WREG32(mmGRBM_SOFT_RESET, tmp);
udelay(50);
}
/**
* gfx_v7_0_rlc_resume - setup the RLC hw
*
* @adev: amdgpu_device pointer
*
* Initialize the RLC registers, load the ucode,
* and start the RLC (CIK).
* Returns 0 for success, -EINVAL if the ucode is not available.
*/
static int gfx_v7_0_rlc_resume(struct amdgpu_device *adev)
{
const struct rlc_firmware_header_v1_0 *hdr;
const __le32 *fw_data;
unsigned i, fw_size;
u32 tmp;
if (!adev->gfx.rlc_fw)
return -EINVAL;
hdr = (const struct rlc_firmware_header_v1_0 *)adev->gfx.rlc_fw->data;
amdgpu_ucode_print_rlc_hdr(&hdr->header);
adev->gfx.rlc_fw_version = le32_to_cpu(hdr->header.ucode_version);
adev->gfx.rlc_feature_version = le32_to_cpu(
hdr->ucode_feature_version);
gfx_v7_0_rlc_stop(adev);
/* disable CG */
tmp = RREG32(mmRLC_CGCG_CGLS_CTRL) & 0xfffffffc;
WREG32(mmRLC_CGCG_CGLS_CTRL, tmp);
gfx_v7_0_rlc_reset(adev);
gfx_v7_0_init_pg(adev);
WREG32(mmRLC_LB_CNTR_INIT, 0);
WREG32(mmRLC_LB_CNTR_MAX, 0x00008000);
mutex_lock(&adev->grbm_idx_mutex);
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
WREG32(mmRLC_LB_INIT_CU_MASK, 0xffffffff);
WREG32(mmRLC_LB_PARAMS, 0x00600408);
WREG32(mmRLC_LB_CNTL, 0x80000004);
mutex_unlock(&adev->grbm_idx_mutex);
WREG32(mmRLC_MC_CNTL, 0);
WREG32(mmRLC_UCODE_CNTL, 0);
fw_data = (const __le32 *)
(adev->gfx.rlc_fw->data + le32_to_cpu(hdr->header.ucode_array_offset_bytes));
fw_size = le32_to_cpu(hdr->header.ucode_size_bytes) / 4;
WREG32(mmRLC_GPM_UCODE_ADDR, 0);
for (i = 0; i < fw_size; i++)
WREG32(mmRLC_GPM_UCODE_DATA, le32_to_cpup(fw_data++));
WREG32(mmRLC_GPM_UCODE_ADDR, adev->gfx.rlc_fw_version);
/* XXX - find out what chips support lbpw */
gfx_v7_0_enable_lbpw(adev, false);
if (adev->asic_type == CHIP_BONAIRE)
WREG32(mmRLC_DRIVER_CPDMA_STATUS, 0);
gfx_v7_0_rlc_start(adev);
return 0;
}
static void gfx_v7_0_enable_cgcg(struct amdgpu_device *adev, bool enable)
{
u32 data, orig, tmp, tmp2;
orig = data = RREG32(mmRLC_CGCG_CGLS_CTRL);
if (enable && (adev->cg_flags & AMD_CG_SUPPORT_GFX_CGCG)) {
gfx_v7_0_enable_gui_idle_interrupt(adev, true);
tmp = gfx_v7_0_halt_rlc(adev);
mutex_lock(&adev->grbm_idx_mutex);
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
WREG32(mmRLC_SERDES_WR_CU_MASTER_MASK, 0xffffffff);
WREG32(mmRLC_SERDES_WR_NONCU_MASTER_MASK, 0xffffffff);
tmp2 = RLC_SERDES_WR_CTRL__BPM_ADDR_MASK |
RLC_SERDES_WR_CTRL__CGCG_OVERRIDE_0_MASK |
RLC_SERDES_WR_CTRL__CGLS_ENABLE_MASK;
WREG32(mmRLC_SERDES_WR_CTRL, tmp2);
mutex_unlock(&adev->grbm_idx_mutex);
gfx_v7_0_update_rlc(adev, tmp);
data |= RLC_CGCG_CGLS_CTRL__CGCG_EN_MASK | RLC_CGCG_CGLS_CTRL__CGLS_EN_MASK;
} else {
gfx_v7_0_enable_gui_idle_interrupt(adev, false);
RREG32(mmCB_CGTT_SCLK_CTRL);
RREG32(mmCB_CGTT_SCLK_CTRL);
RREG32(mmCB_CGTT_SCLK_CTRL);
RREG32(mmCB_CGTT_SCLK_CTRL);
data &= ~(RLC_CGCG_CGLS_CTRL__CGCG_EN_MASK | RLC_CGCG_CGLS_CTRL__CGLS_EN_MASK);
}
if (orig != data)
WREG32(mmRLC_CGCG_CGLS_CTRL, data);
}
static void gfx_v7_0_enable_mgcg(struct amdgpu_device *adev, bool enable)
{
u32 data, orig, tmp = 0;
if (enable && (adev->cg_flags & AMD_CG_SUPPORT_GFX_MGCG)) {
if (adev->cg_flags & AMD_CG_SUPPORT_GFX_MGLS) {
if (adev->cg_flags & AMD_CG_SUPPORT_GFX_CP_LS) {
orig = data = RREG32(mmCP_MEM_SLP_CNTL);
data |= CP_MEM_SLP_CNTL__CP_MEM_LS_EN_MASK;
if (orig != data)
WREG32(mmCP_MEM_SLP_CNTL, data);
}
}
orig = data = RREG32(mmRLC_CGTT_MGCG_OVERRIDE);
data |= 0x00000001;
data &= 0xfffffffd;
if (orig != data)
WREG32(mmRLC_CGTT_MGCG_OVERRIDE, data);
tmp = gfx_v7_0_halt_rlc(adev);
mutex_lock(&adev->grbm_idx_mutex);
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
WREG32(mmRLC_SERDES_WR_CU_MASTER_MASK, 0xffffffff);
WREG32(mmRLC_SERDES_WR_NONCU_MASTER_MASK, 0xffffffff);
data = RLC_SERDES_WR_CTRL__BPM_ADDR_MASK |
RLC_SERDES_WR_CTRL__MGCG_OVERRIDE_0_MASK;
WREG32(mmRLC_SERDES_WR_CTRL, data);
mutex_unlock(&adev->grbm_idx_mutex);
gfx_v7_0_update_rlc(adev, tmp);
if (adev->cg_flags & AMD_CG_SUPPORT_GFX_CGTS) {
orig = data = RREG32(mmCGTS_SM_CTRL_REG);
data &= ~CGTS_SM_CTRL_REG__SM_MODE_MASK;
data |= (0x2 << CGTS_SM_CTRL_REG__SM_MODE__SHIFT);
data |= CGTS_SM_CTRL_REG__SM_MODE_ENABLE_MASK;
data &= ~CGTS_SM_CTRL_REG__OVERRIDE_MASK;
if ((adev->cg_flags & AMD_CG_SUPPORT_GFX_MGLS) &&
(adev->cg_flags & AMD_CG_SUPPORT_GFX_CGTS_LS))
data &= ~CGTS_SM_CTRL_REG__LS_OVERRIDE_MASK;
data &= ~CGTS_SM_CTRL_REG__ON_MONITOR_ADD_MASK;
data |= CGTS_SM_CTRL_REG__ON_MONITOR_ADD_EN_MASK;
data |= (0x96 << CGTS_SM_CTRL_REG__ON_MONITOR_ADD__SHIFT);
if (orig != data)
WREG32(mmCGTS_SM_CTRL_REG, data);
}
} else {
orig = data = RREG32(mmRLC_CGTT_MGCG_OVERRIDE);
data |= 0x00000003;
if (orig != data)
WREG32(mmRLC_CGTT_MGCG_OVERRIDE, data);
data = RREG32(mmRLC_MEM_SLP_CNTL);
if (data & RLC_MEM_SLP_CNTL__RLC_MEM_LS_EN_MASK) {
data &= ~RLC_MEM_SLP_CNTL__RLC_MEM_LS_EN_MASK;
WREG32(mmRLC_MEM_SLP_CNTL, data);
}
data = RREG32(mmCP_MEM_SLP_CNTL);
if (data & CP_MEM_SLP_CNTL__CP_MEM_LS_EN_MASK) {
data &= ~CP_MEM_SLP_CNTL__CP_MEM_LS_EN_MASK;
WREG32(mmCP_MEM_SLP_CNTL, data);
}
orig = data = RREG32(mmCGTS_SM_CTRL_REG);
data |= CGTS_SM_CTRL_REG__OVERRIDE_MASK | CGTS_SM_CTRL_REG__LS_OVERRIDE_MASK;
if (orig != data)
WREG32(mmCGTS_SM_CTRL_REG, data);
tmp = gfx_v7_0_halt_rlc(adev);
mutex_lock(&adev->grbm_idx_mutex);
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
WREG32(mmRLC_SERDES_WR_CU_MASTER_MASK, 0xffffffff);
WREG32(mmRLC_SERDES_WR_NONCU_MASTER_MASK, 0xffffffff);
data = RLC_SERDES_WR_CTRL__BPM_ADDR_MASK | RLC_SERDES_WR_CTRL__MGCG_OVERRIDE_1_MASK;
WREG32(mmRLC_SERDES_WR_CTRL, data);
mutex_unlock(&adev->grbm_idx_mutex);
gfx_v7_0_update_rlc(adev, tmp);
}
}
static void gfx_v7_0_update_cg(struct amdgpu_device *adev,
bool enable)
{
gfx_v7_0_enable_gui_idle_interrupt(adev, false);
/* order matters! */
if (enable) {
gfx_v7_0_enable_mgcg(adev, true);
gfx_v7_0_enable_cgcg(adev, true);
} else {
gfx_v7_0_enable_cgcg(adev, false);
gfx_v7_0_enable_mgcg(adev, false);
}
gfx_v7_0_enable_gui_idle_interrupt(adev, true);
}
static void gfx_v7_0_enable_sclk_slowdown_on_pu(struct amdgpu_device *adev,
bool enable)
{
u32 data, orig;
orig = data = RREG32(mmRLC_PG_CNTL);
if (enable && (adev->pg_flags & AMD_PG_SUPPORT_RLC_SMU_HS))
data |= RLC_PG_CNTL__SMU_CLK_SLOWDOWN_ON_PU_ENABLE_MASK;
else
data &= ~RLC_PG_CNTL__SMU_CLK_SLOWDOWN_ON_PU_ENABLE_MASK;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
}
static void gfx_v7_0_enable_sclk_slowdown_on_pd(struct amdgpu_device *adev,
bool enable)
{
u32 data, orig;
orig = data = RREG32(mmRLC_PG_CNTL);
if (enable && (adev->pg_flags & AMD_PG_SUPPORT_RLC_SMU_HS))
data |= RLC_PG_CNTL__SMU_CLK_SLOWDOWN_ON_PD_ENABLE_MASK;
else
data &= ~RLC_PG_CNTL__SMU_CLK_SLOWDOWN_ON_PD_ENABLE_MASK;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
}
static void gfx_v7_0_enable_cp_pg(struct amdgpu_device *adev, bool enable)
{
u32 data, orig;
orig = data = RREG32(mmRLC_PG_CNTL);
if (enable && (adev->pg_flags & AMD_PG_SUPPORT_CP))
data &= ~0x8000;
else
data |= 0x8000;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
}
static void gfx_v7_0_enable_gds_pg(struct amdgpu_device *adev, bool enable)
{
u32 data, orig;
orig = data = RREG32(mmRLC_PG_CNTL);
if (enable && (adev->pg_flags & AMD_PG_SUPPORT_GDS))
data &= ~0x2000;
else
data |= 0x2000;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
}
static void gfx_v7_0_init_cp_pg_table(struct amdgpu_device *adev)
{
const __le32 *fw_data;
volatile u32 *dst_ptr;
int me, i, max_me = 4;
u32 bo_offset = 0;
u32 table_offset, table_size;
if (adev->asic_type == CHIP_KAVERI)
max_me = 5;
if (adev->gfx.rlc.cp_table_ptr == NULL)
return;
/* write the cp table buffer */
dst_ptr = adev->gfx.rlc.cp_table_ptr;
for (me = 0; me < max_me; me++) {
if (me == 0) {
const struct gfx_firmware_header_v1_0 *hdr =
(const struct gfx_firmware_header_v1_0 *)adev->gfx.ce_fw->data;
fw_data = (const __le32 *)
(adev->gfx.ce_fw->data +
le32_to_cpu(hdr->header.ucode_array_offset_bytes));
table_offset = le32_to_cpu(hdr->jt_offset);
table_size = le32_to_cpu(hdr->jt_size);
} else if (me == 1) {
const struct gfx_firmware_header_v1_0 *hdr =
(const struct gfx_firmware_header_v1_0 *)adev->gfx.pfp_fw->data;
fw_data = (const __le32 *)
(adev->gfx.pfp_fw->data +
le32_to_cpu(hdr->header.ucode_array_offset_bytes));
table_offset = le32_to_cpu(hdr->jt_offset);
table_size = le32_to_cpu(hdr->jt_size);
} else if (me == 2) {
const struct gfx_firmware_header_v1_0 *hdr =
(const struct gfx_firmware_header_v1_0 *)adev->gfx.me_fw->data;
fw_data = (const __le32 *)
(adev->gfx.me_fw->data +
le32_to_cpu(hdr->header.ucode_array_offset_bytes));
table_offset = le32_to_cpu(hdr->jt_offset);
table_size = le32_to_cpu(hdr->jt_size);
} else if (me == 3) {
const struct gfx_firmware_header_v1_0 *hdr =
(const struct gfx_firmware_header_v1_0 *)adev->gfx.mec_fw->data;
fw_data = (const __le32 *)
(adev->gfx.mec_fw->data +
le32_to_cpu(hdr->header.ucode_array_offset_bytes));
table_offset = le32_to_cpu(hdr->jt_offset);
table_size = le32_to_cpu(hdr->jt_size);
} else {
const struct gfx_firmware_header_v1_0 *hdr =
(const struct gfx_firmware_header_v1_0 *)adev->gfx.mec2_fw->data;
fw_data = (const __le32 *)
(adev->gfx.mec2_fw->data +
le32_to_cpu(hdr->header.ucode_array_offset_bytes));
table_offset = le32_to_cpu(hdr->jt_offset);
table_size = le32_to_cpu(hdr->jt_size);
}
for (i = 0; i < table_size; i ++) {
dst_ptr[bo_offset + i] =
cpu_to_le32(le32_to_cpu(fw_data[table_offset + i]));
}
bo_offset += table_size;
}
}
static void gfx_v7_0_enable_gfx_cgpg(struct amdgpu_device *adev,
bool enable)
{
u32 data, orig;
if (enable && (adev->pg_flags & AMD_PG_SUPPORT_GFX_PG)) {
orig = data = RREG32(mmRLC_PG_CNTL);
data |= RLC_PG_CNTL__GFX_POWER_GATING_ENABLE_MASK;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
orig = data = RREG32(mmRLC_AUTO_PG_CTRL);
data |= RLC_AUTO_PG_CTRL__AUTO_PG_EN_MASK;
if (orig != data)
WREG32(mmRLC_AUTO_PG_CTRL, data);
} else {
orig = data = RREG32(mmRLC_PG_CNTL);
data &= ~RLC_PG_CNTL__GFX_POWER_GATING_ENABLE_MASK;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
orig = data = RREG32(mmRLC_AUTO_PG_CTRL);
data &= ~RLC_AUTO_PG_CTRL__AUTO_PG_EN_MASK;
if (orig != data)
WREG32(mmRLC_AUTO_PG_CTRL, data);
data = RREG32(mmDB_RENDER_CONTROL);
}
}
static u32 gfx_v7_0_get_cu_active_bitmap(struct amdgpu_device *adev)
{
u32 data, mask;
data = RREG32(mmCC_GC_SHADER_ARRAY_CONFIG);
data |= RREG32(mmGC_USER_SHADER_ARRAY_CONFIG);
data &= CC_GC_SHADER_ARRAY_CONFIG__INACTIVE_CUS_MASK;
data >>= CC_GC_SHADER_ARRAY_CONFIG__INACTIVE_CUS__SHIFT;
mask = gfx_v7_0_create_bitmask(adev->gfx.config.max_cu_per_sh);
return (~data) & mask;
}
static void gfx_v7_0_init_ao_cu_mask(struct amdgpu_device *adev)
{
u32 tmp;
WREG32(mmRLC_PG_ALWAYS_ON_CU_MASK, adev->gfx.cu_info.ao_cu_mask);
tmp = RREG32(mmRLC_MAX_PG_CU);
tmp &= ~RLC_MAX_PG_CU__MAX_POWERED_UP_CU_MASK;
tmp |= (adev->gfx.cu_info.number << RLC_MAX_PG_CU__MAX_POWERED_UP_CU__SHIFT);
WREG32(mmRLC_MAX_PG_CU, tmp);
}
static void gfx_v7_0_enable_gfx_static_mgpg(struct amdgpu_device *adev,
bool enable)
{
u32 data, orig;
orig = data = RREG32(mmRLC_PG_CNTL);
if (enable && (adev->pg_flags & AMD_PG_SUPPORT_GFX_SMG))
data |= RLC_PG_CNTL__STATIC_PER_CU_PG_ENABLE_MASK;
else
data &= ~RLC_PG_CNTL__STATIC_PER_CU_PG_ENABLE_MASK;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
}
static void gfx_v7_0_enable_gfx_dynamic_mgpg(struct amdgpu_device *adev,
bool enable)
{
u32 data, orig;
orig = data = RREG32(mmRLC_PG_CNTL);
if (enable && (adev->pg_flags & AMD_PG_SUPPORT_GFX_DMG))
data |= RLC_PG_CNTL__DYN_PER_CU_PG_ENABLE_MASK;
else
data &= ~RLC_PG_CNTL__DYN_PER_CU_PG_ENABLE_MASK;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
}
#define RLC_SAVE_AND_RESTORE_STARTING_OFFSET 0x90
#define RLC_CLEAR_STATE_DESCRIPTOR_OFFSET 0x3D
static void gfx_v7_0_init_gfx_cgpg(struct amdgpu_device *adev)
{
u32 data, orig;
u32 i;
if (adev->gfx.rlc.cs_data) {
WREG32(mmRLC_GPM_SCRATCH_ADDR, RLC_CLEAR_STATE_DESCRIPTOR_OFFSET);
WREG32(mmRLC_GPM_SCRATCH_DATA, upper_32_bits(adev->gfx.rlc.clear_state_gpu_addr));
WREG32(mmRLC_GPM_SCRATCH_DATA, lower_32_bits(adev->gfx.rlc.clear_state_gpu_addr));
WREG32(mmRLC_GPM_SCRATCH_DATA, adev->gfx.rlc.clear_state_size);
} else {
WREG32(mmRLC_GPM_SCRATCH_ADDR, RLC_CLEAR_STATE_DESCRIPTOR_OFFSET);
for (i = 0; i < 3; i++)
WREG32(mmRLC_GPM_SCRATCH_DATA, 0);
}
if (adev->gfx.rlc.reg_list) {
WREG32(mmRLC_GPM_SCRATCH_ADDR, RLC_SAVE_AND_RESTORE_STARTING_OFFSET);
for (i = 0; i < adev->gfx.rlc.reg_list_size; i++)
WREG32(mmRLC_GPM_SCRATCH_DATA, adev->gfx.rlc.reg_list[i]);
}
orig = data = RREG32(mmRLC_PG_CNTL);
data |= RLC_PG_CNTL__GFX_POWER_GATING_SRC_MASK;
if (orig != data)
WREG32(mmRLC_PG_CNTL, data);
WREG32(mmRLC_SAVE_AND_RESTORE_BASE, adev->gfx.rlc.save_restore_gpu_addr >> 8);
WREG32(mmRLC_JUMP_TABLE_RESTORE, adev->gfx.rlc.cp_table_gpu_addr >> 8);
data = RREG32(mmCP_RB_WPTR_POLL_CNTL);
data &= ~CP_RB_WPTR_POLL_CNTL__IDLE_POLL_COUNT_MASK;
data |= (0x60 << CP_RB_WPTR_POLL_CNTL__IDLE_POLL_COUNT__SHIFT);
WREG32(mmCP_RB_WPTR_POLL_CNTL, data);
data = 0x10101010;
WREG32(mmRLC_PG_DELAY, data);
data = RREG32(mmRLC_PG_DELAY_2);
data &= ~0xff;
data |= 0x3;
WREG32(mmRLC_PG_DELAY_2, data);
data = RREG32(mmRLC_AUTO_PG_CTRL);
data &= ~RLC_AUTO_PG_CTRL__GRBM_REG_SAVE_GFX_IDLE_THRESHOLD_MASK;
data |= (0x700 << RLC_AUTO_PG_CTRL__GRBM_REG_SAVE_GFX_IDLE_THRESHOLD__SHIFT);
WREG32(mmRLC_AUTO_PG_CTRL, data);
}
static void gfx_v7_0_update_gfx_pg(struct amdgpu_device *adev, bool enable)
{
gfx_v7_0_enable_gfx_cgpg(adev, enable);
gfx_v7_0_enable_gfx_static_mgpg(adev, enable);
gfx_v7_0_enable_gfx_dynamic_mgpg(adev, enable);
}
static u32 gfx_v7_0_get_csb_size(struct amdgpu_device *adev)
{
u32 count = 0;
const struct cs_section_def *sect = NULL;
const struct cs_extent_def *ext = NULL;
if (adev->gfx.rlc.cs_data == NULL)
return 0;
/* begin clear state */
count += 2;
/* context control state */
count += 3;
for (sect = adev->gfx.rlc.cs_data; sect->section != NULL; ++sect) {
for (ext = sect->section; ext->extent != NULL; ++ext) {
if (sect->id == SECT_CONTEXT)
count += 2 + ext->reg_count;
else
return 0;
}
}
/* pa_sc_raster_config/pa_sc_raster_config1 */
count += 4;
/* end clear state */
count += 2;
/* clear state */
count += 2;
return count;
}
static void gfx_v7_0_get_csb_buffer(struct amdgpu_device *adev,
volatile u32 *buffer)
{
u32 count = 0, i;
const struct cs_section_def *sect = NULL;
const struct cs_extent_def *ext = NULL;
if (adev->gfx.rlc.cs_data == NULL)
return;
if (buffer == NULL)
return;
buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_BEGIN_CLEAR_STATE);
buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CONTEXT_CONTROL, 1));
buffer[count++] = cpu_to_le32(0x80000000);
buffer[count++] = cpu_to_le32(0x80000000);
for (sect = adev->gfx.rlc.cs_data; sect->section != NULL; ++sect) {
for (ext = sect->section; ext->extent != NULL; ++ext) {
if (sect->id == SECT_CONTEXT) {
buffer[count++] =
cpu_to_le32(PACKET3(PACKET3_SET_CONTEXT_REG, ext->reg_count));
buffer[count++] = cpu_to_le32(ext->reg_index - PACKET3_SET_CONTEXT_REG_START);
for (i = 0; i < ext->reg_count; i++)
buffer[count++] = cpu_to_le32(ext->extent[i]);
} else {
return;
}
}
}
buffer[count++] = cpu_to_le32(PACKET3(PACKET3_SET_CONTEXT_REG, 2));
buffer[count++] = cpu_to_le32(mmPA_SC_RASTER_CONFIG - PACKET3_SET_CONTEXT_REG_START);
switch (adev->asic_type) {
case CHIP_BONAIRE:
buffer[count++] = cpu_to_le32(0x16000012);
buffer[count++] = cpu_to_le32(0x00000000);
break;
case CHIP_KAVERI:
buffer[count++] = cpu_to_le32(0x00000000); /* XXX */
buffer[count++] = cpu_to_le32(0x00000000);
break;
case CHIP_KABINI:
case CHIP_MULLINS:
buffer[count++] = cpu_to_le32(0x00000000); /* XXX */
buffer[count++] = cpu_to_le32(0x00000000);
break;
case CHIP_HAWAII:
buffer[count++] = cpu_to_le32(0x3a00161a);
buffer[count++] = cpu_to_le32(0x0000002e);
break;
default:
buffer[count++] = cpu_to_le32(0x00000000);
buffer[count++] = cpu_to_le32(0x00000000);
break;
}
buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_END_CLEAR_STATE);
buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CLEAR_STATE, 0));
buffer[count++] = cpu_to_le32(0);
}
static void gfx_v7_0_init_pg(struct amdgpu_device *adev)
{
if (adev->pg_flags & (AMD_PG_SUPPORT_GFX_PG |
AMD_PG_SUPPORT_GFX_SMG |
AMD_PG_SUPPORT_GFX_DMG |
AMD_PG_SUPPORT_CP |
AMD_PG_SUPPORT_GDS |
AMD_PG_SUPPORT_RLC_SMU_HS)) {
gfx_v7_0_enable_sclk_slowdown_on_pu(adev, true);
gfx_v7_0_enable_sclk_slowdown_on_pd(adev, true);
if (adev->pg_flags & AMD_PG_SUPPORT_GFX_PG) {
gfx_v7_0_init_gfx_cgpg(adev);
gfx_v7_0_enable_cp_pg(adev, true);
gfx_v7_0_enable_gds_pg(adev, true);
}
gfx_v7_0_init_ao_cu_mask(adev);
gfx_v7_0_update_gfx_pg(adev, true);
}
}
static void gfx_v7_0_fini_pg(struct amdgpu_device *adev)
{
if (adev->pg_flags & (AMD_PG_SUPPORT_GFX_PG |
AMD_PG_SUPPORT_GFX_SMG |
AMD_PG_SUPPORT_GFX_DMG |
AMD_PG_SUPPORT_CP |
AMD_PG_SUPPORT_GDS |
AMD_PG_SUPPORT_RLC_SMU_HS)) {
gfx_v7_0_update_gfx_pg(adev, false);
if (adev->pg_flags & AMD_PG_SUPPORT_GFX_PG) {
gfx_v7_0_enable_cp_pg(adev, false);
gfx_v7_0_enable_gds_pg(adev, false);
}
}
}
/**
* gfx_v7_0_get_gpu_clock_counter - return GPU clock counter snapshot
*
* @adev: amdgpu_device pointer
*
* Fetches a GPU clock counter snapshot (SI).
* Returns the 64 bit clock counter snapshot.
*/
uint64_t gfx_v7_0_get_gpu_clock_counter(struct amdgpu_device *adev)
{
uint64_t clock;
mutex_lock(&adev->gfx.gpu_clock_mutex);
WREG32(mmRLC_CAPTURE_GPU_CLOCK_COUNT, 1);
clock = (uint64_t)RREG32(mmRLC_GPU_CLOCK_COUNT_LSB) |
((uint64_t)RREG32(mmRLC_GPU_CLOCK_COUNT_MSB) << 32ULL);
mutex_unlock(&adev->gfx.gpu_clock_mutex);
return clock;
}
static void gfx_v7_0_ring_emit_gds_switch(struct amdgpu_ring *ring,
uint32_t vmid,
uint32_t gds_base, uint32_t gds_size,
uint32_t gws_base, uint32_t gws_size,
uint32_t oa_base, uint32_t oa_size)
{
gds_base = gds_base >> AMDGPU_GDS_SHIFT;
gds_size = gds_size >> AMDGPU_GDS_SHIFT;
gws_base = gws_base >> AMDGPU_GWS_SHIFT;
gws_size = gws_size >> AMDGPU_GWS_SHIFT;
oa_base = oa_base >> AMDGPU_OA_SHIFT;
oa_size = oa_size >> AMDGPU_OA_SHIFT;
/* GDS Base */
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, (WRITE_DATA_ENGINE_SEL(0) |
WRITE_DATA_DST_SEL(0)));
amdgpu_ring_write(ring, amdgpu_gds_reg_offset[vmid].mem_base);
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, gds_base);
/* GDS Size */
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, (WRITE_DATA_ENGINE_SEL(0) |
WRITE_DATA_DST_SEL(0)));
amdgpu_ring_write(ring, amdgpu_gds_reg_offset[vmid].mem_size);
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, gds_size);
/* GWS */
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, (WRITE_DATA_ENGINE_SEL(0) |
WRITE_DATA_DST_SEL(0)));
amdgpu_ring_write(ring, amdgpu_gds_reg_offset[vmid].gws);
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, gws_size << GDS_GWS_VMID0__SIZE__SHIFT | gws_base);
/* OA */
amdgpu_ring_write(ring, PACKET3(PACKET3_WRITE_DATA, 3));
amdgpu_ring_write(ring, (WRITE_DATA_ENGINE_SEL(0) |
WRITE_DATA_DST_SEL(0)));
amdgpu_ring_write(ring, amdgpu_gds_reg_offset[vmid].oa);
amdgpu_ring_write(ring, 0);
amdgpu_ring_write(ring, (1 << (oa_size + oa_base)) - (1 << oa_base));
}
static int gfx_v7_0_early_init(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
adev->gfx.num_gfx_rings = GFX7_NUM_GFX_RINGS;
adev->gfx.num_compute_rings = GFX7_NUM_COMPUTE_RINGS;
gfx_v7_0_set_ring_funcs(adev);
gfx_v7_0_set_irq_funcs(adev);
gfx_v7_0_set_gds_init(adev);
return 0;
}
static int gfx_v7_0_late_init(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
int r;
r = amdgpu_irq_get(adev, &adev->gfx.priv_reg_irq, 0);
if (r)
return r;
r = amdgpu_irq_get(adev, &adev->gfx.priv_inst_irq, 0);
if (r)
return r;
return 0;
}
static void gfx_v7_0_gpu_early_init(struct amdgpu_device *adev)
{
u32 gb_addr_config;
u32 mc_shared_chmap, mc_arb_ramcfg;
u32 dimm00_addr_map, dimm01_addr_map, dimm10_addr_map, dimm11_addr_map;
u32 tmp;
switch (adev->asic_type) {
case CHIP_BONAIRE:
adev->gfx.config.max_shader_engines = 2;
adev->gfx.config.max_tile_pipes = 4;
adev->gfx.config.max_cu_per_sh = 7;
adev->gfx.config.max_sh_per_se = 1;
adev->gfx.config.max_backends_per_se = 2;
adev->gfx.config.max_texture_channel_caches = 4;
adev->gfx.config.max_gprs = 256;
adev->gfx.config.max_gs_threads = 32;
adev->gfx.config.max_hw_contexts = 8;
adev->gfx.config.sc_prim_fifo_size_frontend = 0x20;
adev->gfx.config.sc_prim_fifo_size_backend = 0x100;
adev->gfx.config.sc_hiz_tile_fifo_size = 0x30;
adev->gfx.config.sc_earlyz_tile_fifo_size = 0x130;
gb_addr_config = BONAIRE_GB_ADDR_CONFIG_GOLDEN;
break;
case CHIP_HAWAII:
adev->gfx.config.max_shader_engines = 4;
adev->gfx.config.max_tile_pipes = 16;
adev->gfx.config.max_cu_per_sh = 11;
adev->gfx.config.max_sh_per_se = 1;
adev->gfx.config.max_backends_per_se = 4;
adev->gfx.config.max_texture_channel_caches = 16;
adev->gfx.config.max_gprs = 256;
adev->gfx.config.max_gs_threads = 32;
adev->gfx.config.max_hw_contexts = 8;
adev->gfx.config.sc_prim_fifo_size_frontend = 0x20;
adev->gfx.config.sc_prim_fifo_size_backend = 0x100;
adev->gfx.config.sc_hiz_tile_fifo_size = 0x30;
adev->gfx.config.sc_earlyz_tile_fifo_size = 0x130;
gb_addr_config = HAWAII_GB_ADDR_CONFIG_GOLDEN;
break;
case CHIP_KAVERI:
adev->gfx.config.max_shader_engines = 1;
adev->gfx.config.max_tile_pipes = 4;
if ((adev->pdev->device == 0x1304) ||
(adev->pdev->device == 0x1305) ||
(adev->pdev->device == 0x130C) ||
(adev->pdev->device == 0x130F) ||
(adev->pdev->device == 0x1310) ||
(adev->pdev->device == 0x1311) ||
(adev->pdev->device == 0x131C)) {
adev->gfx.config.max_cu_per_sh = 8;
adev->gfx.config.max_backends_per_se = 2;
} else if ((adev->pdev->device == 0x1309) ||
(adev->pdev->device == 0x130A) ||
(adev->pdev->device == 0x130D) ||
(adev->pdev->device == 0x1313) ||
(adev->pdev->device == 0x131D)) {
adev->gfx.config.max_cu_per_sh = 6;
adev->gfx.config.max_backends_per_se = 2;
} else if ((adev->pdev->device == 0x1306) ||
(adev->pdev->device == 0x1307) ||
(adev->pdev->device == 0x130B) ||
(adev->pdev->device == 0x130E) ||
(adev->pdev->device == 0x1315) ||
(adev->pdev->device == 0x131B)) {
adev->gfx.config.max_cu_per_sh = 4;
adev->gfx.config.max_backends_per_se = 1;
} else {
adev->gfx.config.max_cu_per_sh = 3;
adev->gfx.config.max_backends_per_se = 1;
}
adev->gfx.config.max_sh_per_se = 1;
adev->gfx.config.max_texture_channel_caches = 4;
adev->gfx.config.max_gprs = 256;
adev->gfx.config.max_gs_threads = 16;
adev->gfx.config.max_hw_contexts = 8;
adev->gfx.config.sc_prim_fifo_size_frontend = 0x20;
adev->gfx.config.sc_prim_fifo_size_backend = 0x100;
adev->gfx.config.sc_hiz_tile_fifo_size = 0x30;
adev->gfx.config.sc_earlyz_tile_fifo_size = 0x130;
gb_addr_config = BONAIRE_GB_ADDR_CONFIG_GOLDEN;
break;
case CHIP_KABINI:
case CHIP_MULLINS:
default:
adev->gfx.config.max_shader_engines = 1;
adev->gfx.config.max_tile_pipes = 2;
adev->gfx.config.max_cu_per_sh = 2;
adev->gfx.config.max_sh_per_se = 1;
adev->gfx.config.max_backends_per_se = 1;
adev->gfx.config.max_texture_channel_caches = 2;
adev->gfx.config.max_gprs = 256;
adev->gfx.config.max_gs_threads = 16;
adev->gfx.config.max_hw_contexts = 8;
adev->gfx.config.sc_prim_fifo_size_frontend = 0x20;
adev->gfx.config.sc_prim_fifo_size_backend = 0x100;
adev->gfx.config.sc_hiz_tile_fifo_size = 0x30;
adev->gfx.config.sc_earlyz_tile_fifo_size = 0x130;
gb_addr_config = BONAIRE_GB_ADDR_CONFIG_GOLDEN;
break;
}
mc_shared_chmap = RREG32(mmMC_SHARED_CHMAP);
adev->gfx.config.mc_arb_ramcfg = RREG32(mmMC_ARB_RAMCFG);
mc_arb_ramcfg = adev->gfx.config.mc_arb_ramcfg;
adev->gfx.config.num_tile_pipes = adev->gfx.config.max_tile_pipes;
adev->gfx.config.mem_max_burst_length_bytes = 256;
if (adev->flags & AMD_IS_APU) {
/* Get memory bank mapping mode. */
tmp = RREG32(mmMC_FUS_DRAM0_BANK_ADDR_MAPPING);
dimm00_addr_map = REG_GET_FIELD(tmp, MC_FUS_DRAM0_BANK_ADDR_MAPPING, DIMM0ADDRMAP);
dimm01_addr_map = REG_GET_FIELD(tmp, MC_FUS_DRAM0_BANK_ADDR_MAPPING, DIMM1ADDRMAP);
tmp = RREG32(mmMC_FUS_DRAM1_BANK_ADDR_MAPPING);
dimm10_addr_map = REG_GET_FIELD(tmp, MC_FUS_DRAM1_BANK_ADDR_MAPPING, DIMM0ADDRMAP);
dimm11_addr_map = REG_GET_FIELD(tmp, MC_FUS_DRAM1_BANK_ADDR_MAPPING, DIMM1ADDRMAP);
/* Validate settings in case only one DIMM installed. */
if ((dimm00_addr_map == 0) || (dimm00_addr_map == 3) || (dimm00_addr_map == 4) || (dimm00_addr_map > 12))
dimm00_addr_map = 0;
if ((dimm01_addr_map == 0) || (dimm01_addr_map == 3) || (dimm01_addr_map == 4) || (dimm01_addr_map > 12))
dimm01_addr_map = 0;
if ((dimm10_addr_map == 0) || (dimm10_addr_map == 3) || (dimm10_addr_map == 4) || (dimm10_addr_map > 12))
dimm10_addr_map = 0;
if ((dimm11_addr_map == 0) || (dimm11_addr_map == 3) || (dimm11_addr_map == 4) || (dimm11_addr_map > 12))
dimm11_addr_map = 0;
/* If DIMM Addr map is 8GB, ROW size should be 2KB. Otherwise 1KB. */
/* If ROW size(DIMM1) != ROW size(DMIMM0), ROW size should be larger one. */
if ((dimm00_addr_map == 11) || (dimm01_addr_map == 11) || (dimm10_addr_map == 11) || (dimm11_addr_map == 11))
adev->gfx.config.mem_row_size_in_kb = 2;
else
adev->gfx.config.mem_row_size_in_kb = 1;
} else {
tmp = (mc_arb_ramcfg & MC_ARB_RAMCFG__NOOFCOLS_MASK) >> MC_ARB_RAMCFG__NOOFCOLS__SHIFT;
adev->gfx.config.mem_row_size_in_kb = (4 * (1 << (8 + tmp))) / 1024;
if (adev->gfx.config.mem_row_size_in_kb > 4)
adev->gfx.config.mem_row_size_in_kb = 4;
}
/* XXX use MC settings? */
adev->gfx.config.shader_engine_tile_size = 32;
adev->gfx.config.num_gpus = 1;
adev->gfx.config.multi_gpu_tile_size = 64;
/* fix up row size */
gb_addr_config &= ~GB_ADDR_CONFIG__ROW_SIZE_MASK;
switch (adev->gfx.config.mem_row_size_in_kb) {
case 1:
default:
gb_addr_config |= (0 << GB_ADDR_CONFIG__ROW_SIZE__SHIFT);
break;
case 2:
gb_addr_config |= (1 << GB_ADDR_CONFIG__ROW_SIZE__SHIFT);
break;
case 4:
gb_addr_config |= (2 << GB_ADDR_CONFIG__ROW_SIZE__SHIFT);
break;
}
adev->gfx.config.gb_addr_config = gb_addr_config;
}
static int gfx_v7_0_sw_init(void *handle)
{
struct amdgpu_ring *ring;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
int i, r;
/* EOP Event */
r = amdgpu_irq_add_id(adev, 181, &adev->gfx.eop_irq);
if (r)
return r;
/* Privileged reg */
r = amdgpu_irq_add_id(adev, 184, &adev->gfx.priv_reg_irq);
if (r)
return r;
/* Privileged inst */
r = amdgpu_irq_add_id(adev, 185, &adev->gfx.priv_inst_irq);
if (r)
return r;
gfx_v7_0_scratch_init(adev);
r = gfx_v7_0_init_microcode(adev);
if (r) {
DRM_ERROR("Failed to load gfx firmware!\n");
return r;
}
r = gfx_v7_0_rlc_init(adev);
if (r) {
DRM_ERROR("Failed to init rlc BOs!\n");
return r;
}
/* allocate mec buffers */
r = gfx_v7_0_mec_init(adev);
if (r) {
DRM_ERROR("Failed to init MEC BOs!\n");
return r;
}
for (i = 0; i < adev->gfx.num_gfx_rings; i++) {
ring = &adev->gfx.gfx_ring[i];
ring->ring_obj = NULL;
sprintf(ring->name, "gfx");
r = amdgpu_ring_init(adev, ring, 1024,
PACKET3(PACKET3_NOP, 0x3FFF), 0xf,
&adev->gfx.eop_irq, AMDGPU_CP_IRQ_GFX_EOP,
AMDGPU_RING_TYPE_GFX);
if (r)
return r;
}
/* set up the compute queues */
for (i = 0; i < adev->gfx.num_compute_rings; i++) {
unsigned irq_type;
/* max 32 queues per MEC */
if ((i >= 32) || (i >= AMDGPU_MAX_COMPUTE_RINGS)) {
DRM_ERROR("Too many (%d) compute rings!\n", i);
break;
}
ring = &adev->gfx.compute_ring[i];
ring->ring_obj = NULL;
ring->use_doorbell = true;
ring->doorbell_index = AMDGPU_DOORBELL_MEC_RING0 + i;
ring->me = 1; /* first MEC */
ring->pipe = i / 8;
ring->queue = i % 8;
sprintf(ring->name, "comp_%d.%d.%d", ring->me, ring->pipe, ring->queue);
irq_type = AMDGPU_CP_IRQ_COMPUTE_MEC1_PIPE0_EOP + ring->pipe;
/* type-2 packets are deprecated on MEC, use type-3 instead */
r = amdgpu_ring_init(adev, ring, 1024,
PACKET3(PACKET3_NOP, 0x3FFF), 0xf,
&adev->gfx.eop_irq, irq_type,
AMDGPU_RING_TYPE_COMPUTE);
if (r)
return r;
}
/* reserve GDS, GWS and OA resource for gfx */
r = amdgpu_bo_create(adev, adev->gds.mem.gfx_partition_size,
PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_GDS, 0,
NULL, NULL, &adev->gds.gds_gfx_bo);
if (r)
return r;
r = amdgpu_bo_create(adev, adev->gds.gws.gfx_partition_size,
PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_GWS, 0,
NULL, NULL, &adev->gds.gws_gfx_bo);
if (r)
return r;
r = amdgpu_bo_create(adev, adev->gds.oa.gfx_partition_size,
PAGE_SIZE, true,
AMDGPU_GEM_DOMAIN_OA, 0,
NULL, NULL, &adev->gds.oa_gfx_bo);
if (r)
return r;
adev->gfx.ce_ram_size = 0x8000;
gfx_v7_0_gpu_early_init(adev);
return r;
}
static int gfx_v7_0_sw_fini(void *handle)
{
int i;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
amdgpu_bo_unref(&adev->gds.oa_gfx_bo);
amdgpu_bo_unref(&adev->gds.gws_gfx_bo);
amdgpu_bo_unref(&adev->gds.gds_gfx_bo);
for (i = 0; i < adev->gfx.num_gfx_rings; i++)
amdgpu_ring_fini(&adev->gfx.gfx_ring[i]);
for (i = 0; i < adev->gfx.num_compute_rings; i++)
amdgpu_ring_fini(&adev->gfx.compute_ring[i]);
gfx_v7_0_cp_compute_fini(adev);
gfx_v7_0_rlc_fini(adev);
gfx_v7_0_mec_fini(adev);
gfx_v7_0_free_microcode(adev);
return 0;
}
static int gfx_v7_0_hw_init(void *handle)
{
int r;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
gfx_v7_0_gpu_init(adev);
/* init rlc */
r = gfx_v7_0_rlc_resume(adev);
if (r)
return r;
r = gfx_v7_0_cp_resume(adev);
if (r)
return r;
return r;
}
static int gfx_v7_0_hw_fini(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
amdgpu_irq_put(adev, &adev->gfx.priv_reg_irq, 0);
amdgpu_irq_put(adev, &adev->gfx.priv_inst_irq, 0);
gfx_v7_0_cp_enable(adev, false);
gfx_v7_0_rlc_stop(adev);
gfx_v7_0_fini_pg(adev);
return 0;
}
static int gfx_v7_0_suspend(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
return gfx_v7_0_hw_fini(adev);
}
static int gfx_v7_0_resume(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
return gfx_v7_0_hw_init(adev);
}
static bool gfx_v7_0_is_idle(void *handle)
{
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
if (RREG32(mmGRBM_STATUS) & GRBM_STATUS__GUI_ACTIVE_MASK)
return false;
else
return true;
}
static int gfx_v7_0_wait_for_idle(void *handle)
{
unsigned i;
u32 tmp;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
for (i = 0; i < adev->usec_timeout; i++) {
/* read MC_STATUS */
tmp = RREG32(mmGRBM_STATUS) & GRBM_STATUS__GUI_ACTIVE_MASK;
if (!tmp)
return 0;
udelay(1);
}
return -ETIMEDOUT;
}
static int gfx_v7_0_soft_reset(void *handle)
{
u32 grbm_soft_reset = 0, srbm_soft_reset = 0;
u32 tmp;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
/* GRBM_STATUS */
tmp = RREG32(mmGRBM_STATUS);
if (tmp & (GRBM_STATUS__PA_BUSY_MASK | GRBM_STATUS__SC_BUSY_MASK |
GRBM_STATUS__BCI_BUSY_MASK | GRBM_STATUS__SX_BUSY_MASK |
GRBM_STATUS__TA_BUSY_MASK | GRBM_STATUS__VGT_BUSY_MASK |
GRBM_STATUS__DB_BUSY_MASK | GRBM_STATUS__CB_BUSY_MASK |
GRBM_STATUS__GDS_BUSY_MASK | GRBM_STATUS__SPI_BUSY_MASK |
GRBM_STATUS__IA_BUSY_MASK | GRBM_STATUS__IA_BUSY_NO_DMA_MASK))
grbm_soft_reset |= GRBM_SOFT_RESET__SOFT_RESET_CP_MASK |
GRBM_SOFT_RESET__SOFT_RESET_GFX_MASK;
if (tmp & (GRBM_STATUS__CP_BUSY_MASK | GRBM_STATUS__CP_COHERENCY_BUSY_MASK)) {
grbm_soft_reset |= GRBM_SOFT_RESET__SOFT_RESET_CP_MASK;
srbm_soft_reset |= SRBM_SOFT_RESET__SOFT_RESET_GRBM_MASK;
}
/* GRBM_STATUS2 */
tmp = RREG32(mmGRBM_STATUS2);
if (tmp & GRBM_STATUS2__RLC_BUSY_MASK)
grbm_soft_reset |= GRBM_SOFT_RESET__SOFT_RESET_RLC_MASK;
/* SRBM_STATUS */
tmp = RREG32(mmSRBM_STATUS);
if (tmp & SRBM_STATUS__GRBM_RQ_PENDING_MASK)
srbm_soft_reset |= SRBM_SOFT_RESET__SOFT_RESET_GRBM_MASK;
if (grbm_soft_reset || srbm_soft_reset) {
/* disable CG/PG */
gfx_v7_0_fini_pg(adev);
gfx_v7_0_update_cg(adev, false);
/* stop the rlc */
gfx_v7_0_rlc_stop(adev);
/* Disable GFX parsing/prefetching */
WREG32(mmCP_ME_CNTL, CP_ME_CNTL__ME_HALT_MASK | CP_ME_CNTL__PFP_HALT_MASK | CP_ME_CNTL__CE_HALT_MASK);
/* Disable MEC parsing/prefetching */
WREG32(mmCP_MEC_CNTL, CP_MEC_CNTL__MEC_ME1_HALT_MASK | CP_MEC_CNTL__MEC_ME2_HALT_MASK);
if (grbm_soft_reset) {
tmp = RREG32(mmGRBM_SOFT_RESET);
tmp |= grbm_soft_reset;
dev_info(adev->dev, "GRBM_SOFT_RESET=0x%08X\n", tmp);
WREG32(mmGRBM_SOFT_RESET, tmp);
tmp = RREG32(mmGRBM_SOFT_RESET);
udelay(50);
tmp &= ~grbm_soft_reset;
WREG32(mmGRBM_SOFT_RESET, tmp);
tmp = RREG32(mmGRBM_SOFT_RESET);
}
if (srbm_soft_reset) {
tmp = RREG32(mmSRBM_SOFT_RESET);
tmp |= srbm_soft_reset;
dev_info(adev->dev, "SRBM_SOFT_RESET=0x%08X\n", tmp);
WREG32(mmSRBM_SOFT_RESET, tmp);
tmp = RREG32(mmSRBM_SOFT_RESET);
udelay(50);
tmp &= ~srbm_soft_reset;
WREG32(mmSRBM_SOFT_RESET, tmp);
tmp = RREG32(mmSRBM_SOFT_RESET);
}
/* Wait a little for things to settle down */
udelay(50);
}
return 0;
}
static void gfx_v7_0_set_gfx_eop_interrupt_state(struct amdgpu_device *adev,
enum amdgpu_interrupt_state state)
{
u32 cp_int_cntl;
switch (state) {
case AMDGPU_IRQ_STATE_DISABLE:
cp_int_cntl = RREG32(mmCP_INT_CNTL_RING0);
cp_int_cntl &= ~CP_INT_CNTL_RING0__TIME_STAMP_INT_ENABLE_MASK;
WREG32(mmCP_INT_CNTL_RING0, cp_int_cntl);
break;
case AMDGPU_IRQ_STATE_ENABLE:
cp_int_cntl = RREG32(mmCP_INT_CNTL_RING0);
cp_int_cntl |= CP_INT_CNTL_RING0__TIME_STAMP_INT_ENABLE_MASK;
WREG32(mmCP_INT_CNTL_RING0, cp_int_cntl);
break;
default:
break;
}
}
static void gfx_v7_0_set_compute_eop_interrupt_state(struct amdgpu_device *adev,
int me, int pipe,
enum amdgpu_interrupt_state state)
{
u32 mec_int_cntl, mec_int_cntl_reg;
/*
* amdgpu controls only pipe 0 of MEC1. That's why this function only
* handles the setting of interrupts for this specific pipe. All other
* pipes' interrupts are set by amdkfd.
*/
if (me == 1) {
switch (pipe) {
case 0:
mec_int_cntl_reg = mmCP_ME1_PIPE0_INT_CNTL;
break;
default:
DRM_DEBUG("invalid pipe %d\n", pipe);
return;
}
} else {
DRM_DEBUG("invalid me %d\n", me);
return;
}
switch (state) {
case AMDGPU_IRQ_STATE_DISABLE:
mec_int_cntl = RREG32(mec_int_cntl_reg);
mec_int_cntl &= ~CP_INT_CNTL_RING0__TIME_STAMP_INT_ENABLE_MASK;
WREG32(mec_int_cntl_reg, mec_int_cntl);
break;
case AMDGPU_IRQ_STATE_ENABLE:
mec_int_cntl = RREG32(mec_int_cntl_reg);
mec_int_cntl |= CP_INT_CNTL_RING0__TIME_STAMP_INT_ENABLE_MASK;
WREG32(mec_int_cntl_reg, mec_int_cntl);
break;
default:
break;
}
}
static int gfx_v7_0_set_priv_reg_fault_state(struct amdgpu_device *adev,
struct amdgpu_irq_src *src,
unsigned type,
enum amdgpu_interrupt_state state)
{
u32 cp_int_cntl;
switch (state) {
case AMDGPU_IRQ_STATE_DISABLE:
cp_int_cntl = RREG32(mmCP_INT_CNTL_RING0);
cp_int_cntl &= ~CP_INT_CNTL_RING0__PRIV_REG_INT_ENABLE_MASK;
WREG32(mmCP_INT_CNTL_RING0, cp_int_cntl);
break;
case AMDGPU_IRQ_STATE_ENABLE:
cp_int_cntl = RREG32(mmCP_INT_CNTL_RING0);
cp_int_cntl |= CP_INT_CNTL_RING0__PRIV_REG_INT_ENABLE_MASK;
WREG32(mmCP_INT_CNTL_RING0, cp_int_cntl);
break;
default:
break;
}
return 0;
}
static int gfx_v7_0_set_priv_inst_fault_state(struct amdgpu_device *adev,
struct amdgpu_irq_src *src,
unsigned type,
enum amdgpu_interrupt_state state)
{
u32 cp_int_cntl;
switch (state) {
case AMDGPU_IRQ_STATE_DISABLE:
cp_int_cntl = RREG32(mmCP_INT_CNTL_RING0);
cp_int_cntl &= ~CP_INT_CNTL_RING0__PRIV_INSTR_INT_ENABLE_MASK;
WREG32(mmCP_INT_CNTL_RING0, cp_int_cntl);
break;
case AMDGPU_IRQ_STATE_ENABLE:
cp_int_cntl = RREG32(mmCP_INT_CNTL_RING0);
cp_int_cntl |= CP_INT_CNTL_RING0__PRIV_INSTR_INT_ENABLE_MASK;
WREG32(mmCP_INT_CNTL_RING0, cp_int_cntl);
break;
default:
break;
}
return 0;
}
static int gfx_v7_0_set_eop_interrupt_state(struct amdgpu_device *adev,
struct amdgpu_irq_src *src,
unsigned type,
enum amdgpu_interrupt_state state)
{
switch (type) {
case AMDGPU_CP_IRQ_GFX_EOP:
gfx_v7_0_set_gfx_eop_interrupt_state(adev, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC1_PIPE0_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 1, 0, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC1_PIPE1_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 1, 1, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC1_PIPE2_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 1, 2, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC1_PIPE3_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 1, 3, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC2_PIPE0_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 2, 0, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC2_PIPE1_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 2, 1, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC2_PIPE2_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 2, 2, state);
break;
case AMDGPU_CP_IRQ_COMPUTE_MEC2_PIPE3_EOP:
gfx_v7_0_set_compute_eop_interrupt_state(adev, 2, 3, state);
break;
default:
break;
}
return 0;
}
static int gfx_v7_0_eop_irq(struct amdgpu_device *adev,
struct amdgpu_irq_src *source,
struct amdgpu_iv_entry *entry)
{
u8 me_id, pipe_id;
struct amdgpu_ring *ring;
int i;
DRM_DEBUG("IH: CP EOP\n");
me_id = (entry->ring_id & 0x0c) >> 2;
pipe_id = (entry->ring_id & 0x03) >> 0;
switch (me_id) {
case 0:
amdgpu_fence_process(&adev->gfx.gfx_ring[0]);
break;
case 1:
case 2:
for (i = 0; i < adev->gfx.num_compute_rings; i++) {
ring = &adev->gfx.compute_ring[i];
if ((ring->me == me_id) && (ring->pipe == pipe_id))
amdgpu_fence_process(ring);
}
break;
}
return 0;
}
static int gfx_v7_0_priv_reg_irq(struct amdgpu_device *adev,
struct amdgpu_irq_src *source,
struct amdgpu_iv_entry *entry)
{
DRM_ERROR("Illegal register access in command stream\n");
schedule_work(&adev->reset_work);
return 0;
}
static int gfx_v7_0_priv_inst_irq(struct amdgpu_device *adev,
struct amdgpu_irq_src *source,
struct amdgpu_iv_entry *entry)
{
DRM_ERROR("Illegal instruction in command stream\n");
// XXX soft reset the gfx block only
schedule_work(&adev->reset_work);
return 0;
}
static int gfx_v7_0_set_clockgating_state(void *handle,
enum amd_clockgating_state state)
{
bool gate = false;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
if (state == AMD_CG_STATE_GATE)
gate = true;
gfx_v7_0_enable_gui_idle_interrupt(adev, false);
/* order matters! */
if (gate) {
gfx_v7_0_enable_mgcg(adev, true);
gfx_v7_0_enable_cgcg(adev, true);
} else {
gfx_v7_0_enable_cgcg(adev, false);
gfx_v7_0_enable_mgcg(adev, false);
}
gfx_v7_0_enable_gui_idle_interrupt(adev, true);
return 0;
}
static int gfx_v7_0_set_powergating_state(void *handle,
enum amd_powergating_state state)
{
bool gate = false;
struct amdgpu_device *adev = (struct amdgpu_device *)handle;
if (state == AMD_PG_STATE_GATE)
gate = true;
if (adev->pg_flags & (AMD_PG_SUPPORT_GFX_PG |
AMD_PG_SUPPORT_GFX_SMG |
AMD_PG_SUPPORT_GFX_DMG |
AMD_PG_SUPPORT_CP |
AMD_PG_SUPPORT_GDS |
AMD_PG_SUPPORT_RLC_SMU_HS)) {
gfx_v7_0_update_gfx_pg(adev, gate);
if (adev->pg_flags & AMD_PG_SUPPORT_GFX_PG) {
gfx_v7_0_enable_cp_pg(adev, gate);
gfx_v7_0_enable_gds_pg(adev, gate);
}
}
return 0;
}
const struct amd_ip_funcs gfx_v7_0_ip_funcs = {
.name = "gfx_v7_0",
.early_init = gfx_v7_0_early_init,
.late_init = gfx_v7_0_late_init,
.sw_init = gfx_v7_0_sw_init,
.sw_fini = gfx_v7_0_sw_fini,
.hw_init = gfx_v7_0_hw_init,
.hw_fini = gfx_v7_0_hw_fini,
.suspend = gfx_v7_0_suspend,
.resume = gfx_v7_0_resume,
.is_idle = gfx_v7_0_is_idle,
.wait_for_idle = gfx_v7_0_wait_for_idle,
.soft_reset = gfx_v7_0_soft_reset,
.set_clockgating_state = gfx_v7_0_set_clockgating_state,
.set_powergating_state = gfx_v7_0_set_powergating_state,
};
static const struct amdgpu_ring_funcs gfx_v7_0_ring_funcs_gfx = {
.get_rptr = gfx_v7_0_ring_get_rptr_gfx,
.get_wptr = gfx_v7_0_ring_get_wptr_gfx,
.set_wptr = gfx_v7_0_ring_set_wptr_gfx,
.parse_cs = NULL,
.emit_ib = gfx_v7_0_ring_emit_ib_gfx,
.emit_fence = gfx_v7_0_ring_emit_fence_gfx,
.emit_pipeline_sync = gfx_v7_0_ring_emit_pipeline_sync,
.emit_vm_flush = gfx_v7_0_ring_emit_vm_flush,
.emit_gds_switch = gfx_v7_0_ring_emit_gds_switch,
.emit_hdp_flush = gfx_v7_0_ring_emit_hdp_flush,
.emit_hdp_invalidate = gfx_v7_0_ring_emit_hdp_invalidate,
.test_ring = gfx_v7_0_ring_test_ring,
.test_ib = gfx_v7_0_ring_test_ib,
.insert_nop = amdgpu_ring_insert_nop,
.pad_ib = amdgpu_ring_generic_pad_ib,
};
static const struct amdgpu_ring_funcs gfx_v7_0_ring_funcs_compute = {
.get_rptr = gfx_v7_0_ring_get_rptr_compute,
.get_wptr = gfx_v7_0_ring_get_wptr_compute,
.set_wptr = gfx_v7_0_ring_set_wptr_compute,
.parse_cs = NULL,
.emit_ib = gfx_v7_0_ring_emit_ib_compute,
.emit_fence = gfx_v7_0_ring_emit_fence_compute,
.emit_pipeline_sync = gfx_v7_0_ring_emit_pipeline_sync,
.emit_vm_flush = gfx_v7_0_ring_emit_vm_flush,
.emit_gds_switch = gfx_v7_0_ring_emit_gds_switch,
.emit_hdp_flush = gfx_v7_0_ring_emit_hdp_flush,
.emit_hdp_invalidate = gfx_v7_0_ring_emit_hdp_invalidate,
.test_ring = gfx_v7_0_ring_test_ring,
.test_ib = gfx_v7_0_ring_test_ib,
.insert_nop = amdgpu_ring_insert_nop,
.pad_ib = amdgpu_ring_generic_pad_ib,
};
static void gfx_v7_0_set_ring_funcs(struct amdgpu_device *adev)
{
int i;
for (i = 0; i < adev->gfx.num_gfx_rings; i++)
adev->gfx.gfx_ring[i].funcs = &gfx_v7_0_ring_funcs_gfx;
for (i = 0; i < adev->gfx.num_compute_rings; i++)
adev->gfx.compute_ring[i].funcs = &gfx_v7_0_ring_funcs_compute;
}
static const struct amdgpu_irq_src_funcs gfx_v7_0_eop_irq_funcs = {
.set = gfx_v7_0_set_eop_interrupt_state,
.process = gfx_v7_0_eop_irq,
};
static const struct amdgpu_irq_src_funcs gfx_v7_0_priv_reg_irq_funcs = {
.set = gfx_v7_0_set_priv_reg_fault_state,
.process = gfx_v7_0_priv_reg_irq,
};
static const struct amdgpu_irq_src_funcs gfx_v7_0_priv_inst_irq_funcs = {
.set = gfx_v7_0_set_priv_inst_fault_state,
.process = gfx_v7_0_priv_inst_irq,
};
static void gfx_v7_0_set_irq_funcs(struct amdgpu_device *adev)
{
adev->gfx.eop_irq.num_types = AMDGPU_CP_IRQ_LAST;
adev->gfx.eop_irq.funcs = &gfx_v7_0_eop_irq_funcs;
adev->gfx.priv_reg_irq.num_types = 1;
adev->gfx.priv_reg_irq.funcs = &gfx_v7_0_priv_reg_irq_funcs;
adev->gfx.priv_inst_irq.num_types = 1;
adev->gfx.priv_inst_irq.funcs = &gfx_v7_0_priv_inst_irq_funcs;
}
static void gfx_v7_0_set_gds_init(struct amdgpu_device *adev)
{
/* init asci gds info */
adev->gds.mem.total_size = RREG32(mmGDS_VMID0_SIZE);
adev->gds.gws.total_size = 64;
adev->gds.oa.total_size = 16;
if (adev->gds.mem.total_size == 64 * 1024) {
adev->gds.mem.gfx_partition_size = 4096;
adev->gds.mem.cs_partition_size = 4096;
adev->gds.gws.gfx_partition_size = 4;
adev->gds.gws.cs_partition_size = 4;
adev->gds.oa.gfx_partition_size = 4;
adev->gds.oa.cs_partition_size = 1;
} else {
adev->gds.mem.gfx_partition_size = 1024;
adev->gds.mem.cs_partition_size = 1024;
adev->gds.gws.gfx_partition_size = 16;
adev->gds.gws.cs_partition_size = 16;
adev->gds.oa.gfx_partition_size = 4;
adev->gds.oa.cs_partition_size = 4;
}
}
static void gfx_v7_0_get_cu_info(struct amdgpu_device *adev)
{
int i, j, k, counter, active_cu_number = 0;
u32 mask, bitmap, ao_bitmap, ao_cu_mask = 0;
struct amdgpu_cu_info *cu_info = &adev->gfx.cu_info;
memset(cu_info, 0, sizeof(*cu_info));
mutex_lock(&adev->grbm_idx_mutex);
for (i = 0; i < adev->gfx.config.max_shader_engines; i++) {
for (j = 0; j < adev->gfx.config.max_sh_per_se; j++) {
mask = 1;
ao_bitmap = 0;
counter = 0;
gfx_v7_0_select_se_sh(adev, i, j);
bitmap = gfx_v7_0_get_cu_active_bitmap(adev);
cu_info->bitmap[i][j] = bitmap;
for (k = 0; k < 16; k ++) {
if (bitmap & mask) {
if (counter < 2)
ao_bitmap |= mask;
counter ++;
}
mask <<= 1;
}
active_cu_number += counter;
ao_cu_mask |= (ao_bitmap << (i * 16 + j * 8));
}
}
gfx_v7_0_select_se_sh(adev, 0xffffffff, 0xffffffff);
mutex_unlock(&adev->grbm_idx_mutex);
cu_info->number = active_cu_number;
cu_info->ao_cu_mask = ao_cu_mask;
}
| gpl-2.0 |
maximus64/bbb-usbsniffer-kernel | arch/arm/mach-omap2/gpio.c | 30 | 5338 | /*
* OMAP2+ specific gpio initialization
*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/
*
* Author:
* Charulatha V <charu@ti.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.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/gpio.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/of.h>
#include <linux/platform_data/gpio-omap.h>
#include "soc.h"
#include "omap_hwmod.h"
#include "omap_device.h"
#include "omap-pm.h"
#include "powerdomain.h"
static int __init omap2_gpio_dev_init(struct omap_hwmod *oh, void *unused)
{
struct platform_device *pdev;
struct omap_gpio_platform_data *pdata;
struct omap_gpio_dev_attr *dev_attr;
char *name = "omap_gpio";
int id;
struct powerdomain *pwrdm;
/*
* extract the device id from name field available in the
* hwmod database and use the same for constructing ids for
* gpio devices.
* CAUTION: Make sure the name in the hwmod database does
* not change. If changed, make corresponding change here
* or make use of static variable mechanism to handle this.
*/
sscanf(oh->name, "gpio%d", &id);
pdata = kzalloc(sizeof(struct omap_gpio_platform_data), GFP_KERNEL);
if (!pdata) {
pr_err("gpio%d: Memory allocation failed\n", id);
return -ENOMEM;
}
dev_attr = (struct omap_gpio_dev_attr *)oh->dev_attr;
pdata->bank_width = dev_attr->bank_width;
pdata->dbck_flag = dev_attr->dbck_flag;
pdata->get_context_loss_count = omap_pm_get_dev_context_loss_count;
pdata->regs = kzalloc(sizeof(struct omap_gpio_reg_offs), GFP_KERNEL);
if (!pdata->regs) {
pr_err("gpio%d: Memory allocation failed\n", id);
kfree(pdata);
return -ENOMEM;
}
switch (oh->class->rev) {
case 0:
if (id == 1)
/* non-wakeup GPIO pins for OMAP2 Bank1 */
pdata->non_wakeup_gpios = 0xe203ffc0;
else if (id == 2)
/* non-wakeup GPIO pins for OMAP2 Bank2 */
pdata->non_wakeup_gpios = 0x08700040;
/* fall through */
case 1:
pdata->regs->revision = OMAP24XX_GPIO_REVISION;
pdata->regs->direction = OMAP24XX_GPIO_OE;
pdata->regs->datain = OMAP24XX_GPIO_DATAIN;
pdata->regs->dataout = OMAP24XX_GPIO_DATAOUT;
pdata->regs->set_dataout = OMAP24XX_GPIO_SETDATAOUT;
pdata->regs->clr_dataout = OMAP24XX_GPIO_CLEARDATAOUT;
pdata->regs->irqstatus = OMAP24XX_GPIO_IRQSTATUS1;
pdata->regs->irqstatus2 = OMAP24XX_GPIO_IRQSTATUS2;
pdata->regs->irqenable = OMAP24XX_GPIO_IRQENABLE1;
pdata->regs->irqenable2 = OMAP24XX_GPIO_IRQENABLE2;
pdata->regs->set_irqenable = OMAP24XX_GPIO_SETIRQENABLE1;
pdata->regs->clr_irqenable = OMAP24XX_GPIO_CLEARIRQENABLE1;
pdata->regs->debounce = OMAP24XX_GPIO_DEBOUNCE_VAL;
pdata->regs->debounce_en = OMAP24XX_GPIO_DEBOUNCE_EN;
pdata->regs->ctrl = OMAP24XX_GPIO_CTRL;
pdata->regs->wkup_en = OMAP24XX_GPIO_WAKE_EN;
pdata->regs->leveldetect0 = OMAP24XX_GPIO_LEVELDETECT0;
pdata->regs->leveldetect1 = OMAP24XX_GPIO_LEVELDETECT1;
pdata->regs->risingdetect = OMAP24XX_GPIO_RISINGDETECT;
pdata->regs->fallingdetect = OMAP24XX_GPIO_FALLINGDETECT;
break;
case 2:
pdata->regs->revision = OMAP4_GPIO_REVISION;
pdata->regs->direction = OMAP4_GPIO_OE;
pdata->regs->datain = OMAP4_GPIO_DATAIN;
pdata->regs->dataout = OMAP4_GPIO_DATAOUT;
pdata->regs->set_dataout = OMAP4_GPIO_SETDATAOUT;
pdata->regs->clr_dataout = OMAP4_GPIO_CLEARDATAOUT;
pdata->regs->irqstatus_raw0 = OMAP4_GPIO_IRQSTATUSRAW0;
pdata->regs->irqstatus_raw1 = OMAP4_GPIO_IRQSTATUSRAW1;
pdata->regs->irqstatus = OMAP4_GPIO_IRQSTATUS0;
pdata->regs->irqstatus2 = OMAP4_GPIO_IRQSTATUS1;
pdata->regs->irqenable = OMAP4_GPIO_IRQSTATUSSET0;
pdata->regs->irqenable2 = OMAP4_GPIO_IRQSTATUSSET1;
pdata->regs->set_irqenable = OMAP4_GPIO_IRQSTATUSSET0;
pdata->regs->clr_irqenable = OMAP4_GPIO_IRQSTATUSCLR0;
pdata->regs->debounce = OMAP4_GPIO_DEBOUNCINGTIME;
pdata->regs->debounce_en = OMAP4_GPIO_DEBOUNCENABLE;
pdata->regs->ctrl = OMAP4_GPIO_CTRL;
pdata->regs->wkup_en = OMAP4_GPIO_IRQWAKEN0;
pdata->regs->leveldetect0 = OMAP4_GPIO_LEVELDETECT0;
pdata->regs->leveldetect1 = OMAP4_GPIO_LEVELDETECT1;
pdata->regs->risingdetect = OMAP4_GPIO_RISINGDETECT;
pdata->regs->fallingdetect = OMAP4_GPIO_FALLINGDETECT;
break;
default:
WARN(1, "Invalid gpio bank_type\n");
kfree(pdata->regs);
kfree(pdata);
return -EINVAL;
}
pwrdm = omap_hwmod_get_pwrdm(oh);
pdev = omap_device_build(name, id - 1, oh, pdata, sizeof(*pdata));
kfree(pdata);
if (IS_ERR(pdev)) {
WARN(1, "Can't build omap_device for %s:%s.\n",
name, oh->name);
return PTR_ERR(pdev);
}
return 0;
}
/*
* gpio_init needs to be done before
* machine_init functions access gpio APIs.
* Hence gpio_init is a omap_postcore_initcall.
*/
static int __init omap2_gpio_init(void)
{
/* If dtb is there, the devices will be created dynamically */
if (of_have_populated_dt())
return -ENODEV;
return omap_hwmod_for_each_by_class("gpio", omap2_gpio_dev_init, NULL);
}
omap_postcore_initcall(omap2_gpio_init);
| gpl-2.0 |
XePeleato/ALE-L21_ESAL | drivers/gpu/arm/malit6_64/r5p0-00dev0/mali_kbase_instr.c | 30 | 19257 | /*
*
* (C) COPYRIGHT ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation, and any use by you of this program is subject to the terms
* of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained
* from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
/**
* @file mali_kbase_instr.c
* Base kernel instrumentation APIs.
*/
#include <mali_kbase.h>
#include <mali_midg_regmap.h>
/**
* @brief Issue Cache Clean & Invalidate command to hardware
*/
static void kbasep_instr_hwcnt_cacheclean(kbase_device *kbdev)
{
unsigned long flags;
unsigned long pm_flags;
u32 irq_mask;
KBASE_DEBUG_ASSERT(NULL != kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
/* Wait for any reset to complete */
while (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.cache_clean_wait,
kbdev->hwcnt.state != KBASE_INSTR_STATE_RESETTING);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_REQUEST_CLEAN);
/* Enable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask | CLEAN_CACHES_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* clean&invalidate the caches so we're sure the mmu tables for the dump buffer is valid */
KBASE_TRACE_ADD(kbdev, CORE_GPU_CLEAN_INV_CACHES, NULL, NULL, 0u, 0);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_COMMAND), GPU_COMMAND_CLEAN_INV_CACHES, NULL);
kbdev->hwcnt.state = KBASE_INSTR_STATE_CLEANING;
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
}
STATIC mali_error kbase_instr_hwcnt_enable_internal(kbase_device *kbdev, kbase_context *kctx, kbase_uk_hwcnt_setup *setup)
{
unsigned long flags, pm_flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
kbasep_js_device_data *js_devdata;
u32 irq_mask;
int ret;
u64 shader_cores_needed;
KBASE_DEBUG_ASSERT(NULL != kctx);
KBASE_DEBUG_ASSERT(NULL != kbdev);
KBASE_DEBUG_ASSERT(NULL != setup);
KBASE_DEBUG_ASSERT(NULL == kbdev->hwcnt.suspended_kctx);
shader_cores_needed = kbase_pm_get_present_cores(kbdev, KBASE_PM_CORE_SHADER);
js_devdata = &kbdev->js_data;
/* alignment failure */
if ((setup->dump_buffer == 0ULL) || (setup->dump_buffer & (2048 - 1)))
goto out_err;
/* Override core availability policy to ensure all cores are available */
kbase_pm_ca_instr_enable(kbdev);
/* Mark the context as active so the GPU is kept turned on */
/* A suspend won't happen here, because we're in a syscall from a userspace
* thread. */
kbase_pm_context_active(kbdev);
/* Request the cores early on synchronously - we'll release them on any errors
* (e.g. instrumentation already active) */
kbase_pm_request_cores_sync(kbdev, MALI_TRUE, shader_cores_needed);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
if (kbdev->hwcnt.state != KBASE_INSTR_STATE_DISABLED) {
/* Instrumentation is already enabled */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
goto out_unrequest_cores;
}
/* Enable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask | PRFCNT_SAMPLE_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* In use, this context is the owner */
kbdev->hwcnt.kctx = kctx;
/* Remember the dump address so we can reprogram it later */
kbdev->hwcnt.addr = setup->dump_buffer;
/* Remember all the settings for suspend/resume */
if (&kbdev->hwcnt.suspended_state != setup)
memcpy(&kbdev->hwcnt.suspended_state, setup, sizeof(kbdev->hwcnt.suspended_state));
/* Request the clean */
kbdev->hwcnt.state = KBASE_INSTR_STATE_REQUEST_CLEAN;
kbdev->hwcnt.triggered = 0;
/* Clean&invalidate the caches so we're sure the mmu tables for the dump buffer is valid */
ret = queue_work(kbdev->hwcnt.cache_clean_wq, &kbdev->hwcnt.cache_clean_work);
KBASE_DEBUG_ASSERT(ret);
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
/* Wait for cacheclean to complete */
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE);
/* Schedule the context in */
kbasep_js_schedule_privileged_ctx(kbdev, kctx);
/* Configure */
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_CONFIG), (kctx->as_nr << PRFCNT_CONFIG_AS_SHIFT) | PRFCNT_CONFIG_MODE_OFF, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_LO), setup->dump_buffer & 0xFFFFFFFF, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_HI), setup->dump_buffer >> 32, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_JM_EN), setup->jm_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_SHADER_EN), setup->shader_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_L3_CACHE_EN), setup->l3_cache_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_MMU_L2_EN), setup->mmu_l2_bm, kctx);
/* Due to PRLAM-8186 we need to disable the Tiler before we enable the HW counter dump. */
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8186))
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_TILER_EN), 0, kctx);
else
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_TILER_EN), setup->tiler_bm, kctx);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_CONFIG), (kctx->as_nr << PRFCNT_CONFIG_AS_SHIFT) | PRFCNT_CONFIG_MODE_MANUAL, kctx);
/* If HW has PRLAM-8186 we can now re-enable the tiler HW counters dump */
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8186))
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_TILER_EN), setup->tiler_bm, kctx);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
kbdev->hwcnt.triggered = 1;
wake_up(&kbdev->hwcnt.wait);
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
err = MALI_ERROR_NONE;
dev_dbg(kbdev->dev, "HW counters dumping set-up for context %p", kctx);
return err;
out_unrequest_cores:
kbase_pm_unrequest_cores(kbdev, MALI_TRUE, shader_cores_needed);
kbase_pm_context_idle(kbdev);
out_err:
return err;
}
/**
* @brief Enable HW counters collection
*
* Note: will wait for a cache clean to complete
*/
mali_error kbase_instr_hwcnt_enable(kbase_context *kctx, kbase_uk_hwcnt_setup *setup)
{
kbase_device *kbdev;
mali_bool access_allowed;
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
/* Determine if the calling task has access to this capability */
access_allowed = kbase_security_has_capability(kctx, KBASE_SEC_INSTR_HW_COUNTERS_COLLECT, KBASE_SEC_FLAG_NOAUDIT);
if (MALI_FALSE == access_allowed)
return MALI_ERROR_FUNCTION_FAILED;
return kbase_instr_hwcnt_enable_internal(kbdev, kctx, setup);
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_enable)
/**
* @brief Disable HW counters collection
*
* Note: might sleep, waiting for an ongoing dump to complete
*/
mali_error kbase_instr_hwcnt_disable(kbase_context *kctx)
{
unsigned long flags, pm_flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
u32 irq_mask;
kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
while (1) {
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_DISABLED) {
/* Instrumentation is not enabled */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
goto out;
}
if (kbdev->hwcnt.kctx != kctx) {
/* Instrumentation has been setup for another context */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
goto out;
}
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE)
break;
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
/* Ongoing dump/setup - wait for its completion */
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
}
kbdev->hwcnt.state = KBASE_INSTR_STATE_DISABLED;
kbdev->hwcnt.triggered = 0;
/* Disable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask & ~PRFCNT_SAMPLE_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* Disable the counters */
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_CONFIG), 0, kctx);
kbdev->hwcnt.kctx = NULL;
kbdev->hwcnt.addr = 0ULL;
kbase_pm_ca_instr_disable(kbdev);
kbase_pm_unrequest_cores(kbdev, MALI_TRUE, kbase_pm_get_present_cores(kbdev, KBASE_PM_CORE_SHADER));
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
/* Release the context. This had its own Power Manager Active reference */
kbasep_js_release_privileged_ctx(kbdev, kctx);
/* Also release our Power Manager Active reference */
kbase_pm_context_idle(kbdev);
dev_dbg(kbdev->dev, "HW counters dumping disabled for context %p", kctx);
err = MALI_ERROR_NONE;
out:
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_disable)
/**
* @brief Configure HW counters collection
*/
mali_error kbase_instr_hwcnt_setup(kbase_context *kctx, kbase_uk_hwcnt_setup *setup)
{
mali_error err = MALI_ERROR_FUNCTION_FAILED;
kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
if (NULL == setup) {
/* Bad parameter - abort */
goto out;
}
if (setup->dump_buffer != 0ULL) {
/* Enable HW counters */
err = kbase_instr_hwcnt_enable(kctx, setup);
} else {
/* Disable HW counters */
err = kbase_instr_hwcnt_disable(kctx);
}
out:
return err;
}
/**
* @brief Issue Dump command to hardware
*
* Notes:
* - does not sleep
*/
mali_error kbase_instr_hwcnt_dump_irq(kbase_context *kctx)
{
unsigned long flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.kctx != kctx) {
/* The instrumentation has been setup for another context */
goto unlock;
}
if (kbdev->hwcnt.state != KBASE_INSTR_STATE_IDLE) {
/* HW counters are disabled or another dump is ongoing, or we're resetting */
goto unlock;
}
kbdev->hwcnt.triggered = 0;
/* Mark that we're dumping - the PF handler can signal that we faulted */
kbdev->hwcnt.state = KBASE_INSTR_STATE_DUMPING;
/* Reconfigure the dump address */
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_LO), kbdev->hwcnt.addr & 0xFFFFFFFF, NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(PRFCNT_BASE_HI), kbdev->hwcnt.addr >> 32, NULL);
/* Start dumping */
KBASE_TRACE_ADD(kbdev, CORE_GPU_PRFCNT_SAMPLE, NULL, NULL, kbdev->hwcnt.addr, 0);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_COMMAND), GPU_COMMAND_PRFCNT_SAMPLE, kctx);
dev_dbg(kbdev->dev, "HW counters dumping done for context %p", kctx);
err = MALI_ERROR_NONE;
unlock:
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_dump_irq)
/**
* @brief Tell whether the HW counters dump has completed
*
* Notes:
* - does not sleep
* - success will be set to MALI_TRUE if the dump succeeded or
* MALI_FALSE on failure
*/
mali_bool kbase_instr_hwcnt_dump_complete(kbase_context *kctx, mali_bool * const success)
{
unsigned long flags;
mali_bool complete = MALI_FALSE;
kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
KBASE_DEBUG_ASSERT(NULL != success);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE) {
*success = MALI_TRUE;
complete = MALI_TRUE;
} else if (kbdev->hwcnt.state == KBASE_INSTR_STATE_FAULT) {
*success = MALI_FALSE;
complete = MALI_TRUE;
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
}
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
return complete;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_dump_complete)
/**
* @brief Issue Dump command to hardware and wait for completion
*/
mali_error kbase_instr_hwcnt_dump(kbase_context *kctx)
{
unsigned long flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
err = kbase_instr_hwcnt_dump_irq(kctx);
if (MALI_ERROR_NONE != err) {
/* Can't dump HW counters */
goto out;
}
/* Wait for dump & cacheclean to complete */
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_FAULT) {
err = MALI_ERROR_FUNCTION_FAILED;
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
} else {
/* Dump done */
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_IDLE);
err = MALI_ERROR_NONE;
}
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
out:
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_dump)
/**
* @brief Clear the HW counters
*/
mali_error kbase_instr_hwcnt_clear(kbase_context *kctx)
{
unsigned long flags;
mali_error err = MALI_ERROR_FUNCTION_FAILED;
kbase_device *kbdev;
KBASE_DEBUG_ASSERT(NULL != kctx);
kbdev = kctx->kbdev;
KBASE_DEBUG_ASSERT(NULL != kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING) {
/* GPU is being reset */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.wait, kbdev->hwcnt.triggered != 0);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
/* Check it's the context previously set up and we're not already dumping */
if (kbdev->hwcnt.kctx != kctx || kbdev->hwcnt.state != KBASE_INSTR_STATE_IDLE)
goto out;
/* Clear the counters */
KBASE_TRACE_ADD(kbdev, CORE_GPU_PRFCNT_CLEAR, NULL, NULL, 0u, 0);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_COMMAND), GPU_COMMAND_PRFCNT_CLEAR, kctx);
err = MALI_ERROR_NONE;
out:
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
return err;
}
KBASE_EXPORT_SYMBOL(kbase_instr_hwcnt_clear)
/**
* Workqueue for handling cache cleaning
*/
void kbasep_cache_clean_worker(struct work_struct *data)
{
kbase_device *kbdev;
unsigned long flags;
kbdev = container_of(data, kbase_device, hwcnt.cache_clean_work);
mutex_lock(&kbdev->cacheclean_lock);
kbasep_instr_hwcnt_cacheclean(kbdev);
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
/* Wait for our condition, and any reset to complete */
while (kbdev->hwcnt.state == KBASE_INSTR_STATE_RESETTING
|| kbdev->hwcnt.state == KBASE_INSTR_STATE_CLEANING) {
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
wait_event(kbdev->hwcnt.cache_clean_wait,
(kbdev->hwcnt.state != KBASE_INSTR_STATE_RESETTING
&& kbdev->hwcnt.state != KBASE_INSTR_STATE_CLEANING));
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
}
KBASE_DEBUG_ASSERT(kbdev->hwcnt.state == KBASE_INSTR_STATE_CLEANED);
/* All finished and idle */
kbdev->hwcnt.state = KBASE_INSTR_STATE_IDLE;
kbdev->hwcnt.triggered = 1;
wake_up(&kbdev->hwcnt.wait);
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
mutex_unlock(&kbdev->cacheclean_lock);
}
/**
* @brief Dump complete interrupt received
*/
void kbase_instr_hwcnt_sample_done(kbase_device *kbdev)
{
unsigned long flags;
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_FAULT) {
kbdev->hwcnt.triggered = 1;
wake_up(&kbdev->hwcnt.wait);
} else if (kbdev->hwcnt.state == KBASE_INSTR_STATE_DUMPING) {
int ret;
/* Always clean and invalidate the cache after a successful dump */
kbdev->hwcnt.state = KBASE_INSTR_STATE_REQUEST_CLEAN;
ret = queue_work(kbdev->hwcnt.cache_clean_wq, &kbdev->hwcnt.cache_clean_work);
KBASE_DEBUG_ASSERT(ret);
}
/* NOTE: In the state KBASE_INSTR_STATE_RESETTING, We're in a reset,
* and the instrumentation state hasn't been restored yet -
* kbasep_reset_timeout_worker() will do the rest of the work */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
}
/**
* @brief Cache clean interrupt received
*/
void kbase_clean_caches_done(kbase_device *kbdev)
{
u32 irq_mask;
if (kbdev->hwcnt.state != KBASE_INSTR_STATE_DISABLED) {
unsigned long flags;
unsigned long pm_flags;
spin_lock_irqsave(&kbdev->hwcnt.lock, flags);
/* Disable interrupt */
spin_lock_irqsave(&kbdev->pm.power_change_lock, pm_flags);
irq_mask = kbase_reg_read(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), NULL);
kbase_reg_write(kbdev, GPU_CONTROL_REG(GPU_IRQ_MASK), irq_mask & ~CLEAN_CACHES_COMPLETED, NULL);
spin_unlock_irqrestore(&kbdev->pm.power_change_lock, pm_flags);
/* Wakeup... */
if (kbdev->hwcnt.state == KBASE_INSTR_STATE_CLEANING) {
/* Only wake if we weren't resetting */
kbdev->hwcnt.state = KBASE_INSTR_STATE_CLEANED;
wake_up(&kbdev->hwcnt.cache_clean_wait);
}
/* NOTE: In the state KBASE_INSTR_STATE_RESETTING, We're in a reset,
* and the instrumentation state hasn't been restored yet -
* kbasep_reset_timeout_worker() will do the rest of the work */
spin_unlock_irqrestore(&kbdev->hwcnt.lock, flags);
}
}
/* Disable instrumentation and wait for any existing dump to complete
* It's assumed that there's only one privileged context
* Safe to do this without lock when doing an OS suspend, because it only
* changes in response to user-space IOCTLs */
void kbase_instr_hwcnt_suspend(kbase_device *kbdev)
{
kbase_context *kctx;
KBASE_DEBUG_ASSERT(kbdev);
KBASE_DEBUG_ASSERT(!kbdev->hwcnt.suspended_kctx);
kctx = kbdev->hwcnt.kctx;
kbdev->hwcnt.suspended_kctx = kctx;
/* Relevant state was saved into hwcnt.suspended_state when enabling the
* counters */
if (kctx)
{
KBASE_DEBUG_ASSERT(kctx->jctx.sched_info.ctx.flags & KBASE_CTX_FLAG_PRIVILEGED);
kbase_instr_hwcnt_disable(kctx);
}
}
void kbase_instr_hwcnt_resume(kbase_device *kbdev)
{
kbase_context *kctx;
KBASE_DEBUG_ASSERT(kbdev);
kctx = kbdev->hwcnt.suspended_kctx;
kbdev->hwcnt.suspended_kctx = NULL;
if (kctx)
{
mali_error err;
err = kbase_instr_hwcnt_enable_internal(kbdev, kctx, &kbdev->hwcnt.suspended_state);
WARN(err != MALI_ERROR_NONE,
"Failed to restore instrumented hardware counters on resume\n");
}
}
| gpl-2.0 |
dexter93/kernel_htc_msm8660 | drivers/video/msm/vidc/common/vcd/vcd_sub.c | 542 | 95771 | /* Copyright (c) 2010-2013, 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/memory_alloc.h>
#include <mach/msm_subsystem_map.h>
#include <asm/div64.h>
#include <media/msm/vidc_type.h>
#include "vcd.h"
#include "vdec_internal.h"
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MAP_TABLE_SZ 64
#define VCD_ENC_MAX_OUTBFRS_PER_FRAME 8
#define MAX_DEC_TIME 33
struct vcd_msm_map_buffer {
phys_addr_t phy_addr;
struct msm_mapped_buffer *mapped_buffer;
struct ion_handle *alloc_handle;
u32 in_use;
};
static struct vcd_msm_map_buffer msm_mapped_buffer_table[MAP_TABLE_SZ];
static unsigned int vidc_mmu_subsystem[] = {MSM_SUBSYSTEM_VIDEO};
static int vcd_pmem_alloc(size_t sz, u8 **kernel_vaddr, u8 **phy_addr,
struct vcd_clnt_ctxt *cctxt)
{
u32 memtype, i = 0, flags = 0;
struct vcd_msm_map_buffer *map_buffer = NULL;
struct msm_mapped_buffer *mapped_buffer = NULL;
unsigned long iova = 0;
unsigned long buffer_size = 0;
int ret = 0;
unsigned long ionflag = 0;
ion_phys_addr_t phyaddr = 0;
size_t len = 0;
if (!kernel_vaddr || !phy_addr || !cctxt) {
pr_err("\n%s: Invalid parameters", __func__);
goto bailout;
}
*phy_addr = NULL;
*kernel_vaddr = NULL;
for (i = 0; i < MAP_TABLE_SZ; i++) {
if (!msm_mapped_buffer_table[i].in_use) {
map_buffer = &msm_mapped_buffer_table[i];
map_buffer->in_use = 1;
break;
}
}
if (!map_buffer) {
pr_err("%s() map table is full", __func__);
goto bailout;
}
res_trk_set_mem_type(DDL_MM_MEM);
memtype = res_trk_get_mem_type();
if (!cctxt->vcd_enable_ion) {
map_buffer->phy_addr = (phys_addr_t)
allocate_contiguous_memory_nomap(sz, memtype, SZ_4K);
if (!map_buffer->phy_addr) {
pr_err("%s() acm alloc failed", __func__);
goto free_map_table;
}
flags = MSM_SUBSYSTEM_MAP_IOVA | MSM_SUBSYSTEM_MAP_KADDR;
map_buffer->mapped_buffer =
msm_subsystem_map_buffer((unsigned long)map_buffer->phy_addr,
sz, flags, vidc_mmu_subsystem,
sizeof(vidc_mmu_subsystem)/sizeof(unsigned int));
if (IS_ERR(map_buffer->mapped_buffer)) {
pr_err(" %s() buffer map failed", __func__);
goto free_acm_alloc;
}
mapped_buffer = map_buffer->mapped_buffer;
if (!mapped_buffer->vaddr || !mapped_buffer->iova[0]) {
pr_err("%s() map buffers failed", __func__);
goto free_map_buffers;
}
*phy_addr = (u8 *) mapped_buffer->iova[0];
*kernel_vaddr = (u8 *) mapped_buffer->vaddr;
VCD_MSG_LOW("vcd_pmem_alloc: phys(0x%x), virt(0x%x), "\
"sz(%u), flags(0x%x)", (u32)*phy_addr,
(u32)*kernel_vaddr, sz, (u32)flags);
} else {
map_buffer->alloc_handle = ion_alloc(
cctxt->vcd_ion_client, sz, SZ_4K,
memtype, res_trk_get_ion_flags());
if (!map_buffer->alloc_handle) {
pr_err("%s() ION alloc failed", __func__);
goto bailout;
}
if (ion_handle_get_flags(cctxt->vcd_ion_client,
map_buffer->alloc_handle,
&ionflag)) {
pr_err("%s() ION get flag failed", __func__);
goto bailout;
}
*kernel_vaddr = (u8 *) ion_map_kernel(
cctxt->vcd_ion_client,
map_buffer->alloc_handle);
if (!(*kernel_vaddr)) {
pr_err("%s() ION map failed", __func__);
goto ion_free_bailout;
}
if (res_trk_get_core_type() != (u32)VCD_CORE_720P) {
ret = ion_map_iommu(cctxt->vcd_ion_client,
map_buffer->alloc_handle,
VIDEO_DOMAIN,
VIDEO_MAIN_POOL,
SZ_4K,
0,
(unsigned long *)&iova,
(unsigned long *)&buffer_size,
0, 0);
if (ret || !iova) {
pr_err(
"%s() ION iommu map failed, ret = %d, iova = 0x%lx",
__func__, ret, iova);
goto ion_map_bailout;
}
map_buffer->phy_addr = iova;
} else {
ret = ion_phys(cctxt->vcd_ion_client,
map_buffer->alloc_handle,
&phyaddr,
&len);
if (ret) {
pr_err("%s() ion_phys failed", __func__);
goto ion_map_bailout;
}
map_buffer->phy_addr = phyaddr;
}
if (!map_buffer->phy_addr) {
pr_err("%s() acm alloc failed", __func__);
goto free_map_table;
}
*phy_addr = (u8 *)map_buffer->phy_addr;
mapped_buffer = NULL;
map_buffer->mapped_buffer = NULL;
VCD_MSG_LOW("vcd_ion_alloc: phys(0x%x), virt(0x%x), "\
"sz(%u), ionflags(0x%x)", (u32)*phy_addr,
(u32)*kernel_vaddr, sz, (u32)ionflag);
}
return 0;
free_map_buffers:
if (map_buffer->mapped_buffer)
msm_subsystem_unmap_buffer(map_buffer->mapped_buffer);
free_acm_alloc:
if (!cctxt->vcd_enable_ion) {
free_contiguous_memory_by_paddr(
(unsigned long)map_buffer->phy_addr);
}
return -ENOMEM;
ion_map_bailout:
ion_unmap_kernel(cctxt->vcd_ion_client, map_buffer->alloc_handle);
ion_free_bailout:
ion_free(cctxt->vcd_ion_client, map_buffer->alloc_handle);
free_map_table:
map_buffer->in_use = 0;
bailout:
return -ENOMEM;
}
static int vcd_pmem_free(u8 *kernel_vaddr, u8 *phy_addr,
struct vcd_clnt_ctxt *cctxt)
{
u32 i = 0;
struct vcd_msm_map_buffer *map_buffer = NULL;
if (!kernel_vaddr || !phy_addr || !cctxt) {
pr_err("\n%s: Invalid parameters", __func__);
goto bailout;
}
for (i = 0; i < MAP_TABLE_SZ; i++) {
if (msm_mapped_buffer_table[i].in_use &&
(msm_mapped_buffer_table[i]
.mapped_buffer->vaddr == kernel_vaddr)) {
map_buffer = &msm_mapped_buffer_table[i];
map_buffer->in_use = 0;
break;
}
}
if (!map_buffer) {
pr_err("%s() Entry not found", __func__);
goto bailout;
}
if (map_buffer->mapped_buffer)
msm_subsystem_unmap_buffer(map_buffer->mapped_buffer);
if (cctxt->vcd_enable_ion) {
VCD_MSG_LOW("vcd_ion_free: phys(0x%x), virt(0x%x)",
(u32)phy_addr, (u32)kernel_vaddr);
if (map_buffer->alloc_handle) {
ion_unmap_kernel(cctxt->vcd_ion_client,
map_buffer->alloc_handle);
if (res_trk_get_core_type() != (u32)VCD_CORE_720P)
ion_unmap_iommu(cctxt->vcd_ion_client,
map_buffer->alloc_handle,
VIDEO_DOMAIN,
VIDEO_MAIN_POOL);
ion_free(cctxt->vcd_ion_client,
map_buffer->alloc_handle);
}
} else {
VCD_MSG_LOW("vcd_pmem_free: phys(0x%x), virt(0x%x)",
(u32)phy_addr, (u32)kernel_vaddr);
free_contiguous_memory_by_paddr(
(unsigned long)map_buffer->phy_addr);
}
bailout:
kernel_vaddr = NULL;
phy_addr = NULL;
return 0;
}
u8 *vcd_pmem_get_physical(struct video_client_ctx *client_ctx,
unsigned long kernel_vaddr)
{
unsigned long phy_addr, user_vaddr;
int pmem_fd;
struct file *file;
s32 buffer_index = -1;
if (vidc_lookup_addr_table(client_ctx, BUFFER_TYPE_INPUT,
false, &user_vaddr, &kernel_vaddr,
&phy_addr, &pmem_fd, &file,
&buffer_index)) {
return (u8 *) phy_addr;
} else if (vidc_lookup_addr_table(client_ctx, BUFFER_TYPE_OUTPUT,
false, &user_vaddr, &kernel_vaddr, &phy_addr, &pmem_fd, &file,
&buffer_index)) {
return (u8 *) phy_addr;
} else {
VCD_MSG_ERROR("Couldn't get physical address");
return NULL;
}
}
u32 vcd_get_ion_flag(struct video_client_ctx *client_ctx,
unsigned long kernel_vaddr,
struct ion_handle **buff_ion_handle)
{
unsigned long phy_addr, user_vaddr;
int pmem_fd;
struct file *file;
s32 buffer_index = -1;
u32 ion_flag = 0;
struct ion_handle *buff_handle = NULL;
if (vidc_lookup_addr_table(client_ctx, BUFFER_TYPE_INPUT,
false, &user_vaddr, &kernel_vaddr,
&phy_addr, &pmem_fd, &file,
&buffer_index)) {
ion_flag = vidc_get_fd_info(client_ctx, BUFFER_TYPE_INPUT,
pmem_fd, kernel_vaddr, buffer_index,
&buff_handle);
*buff_ion_handle = buff_handle;
return ion_flag;
} else if (vidc_lookup_addr_table(client_ctx, BUFFER_TYPE_OUTPUT,
false, &user_vaddr, &kernel_vaddr, &phy_addr, &pmem_fd, &file,
&buffer_index)) {
ion_flag = vidc_get_fd_info(client_ctx, BUFFER_TYPE_OUTPUT,
pmem_fd, kernel_vaddr, buffer_index,
&buff_handle);
*buff_ion_handle = buff_handle;
return ion_flag;
} else {
VCD_MSG_ERROR("Couldn't get ion flag");
return 0;
}
}
void vcd_reset_device_channels(struct vcd_dev_ctxt *dev_ctxt)
{
dev_ctxt->ddl_frame_ch_free = dev_ctxt->ddl_frame_ch_depth;
dev_ctxt->ddl_cmd_ch_free = dev_ctxt->ddl_cmd_ch_depth;
dev_ctxt->ddl_frame_ch_interim = 0;
dev_ctxt->ddl_cmd_ch_interim = 0;
}
u32 vcd_get_command_channel(
struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc **transc)
{
u32 result = false;
*transc = NULL;
if (dev_ctxt->ddl_cmd_ch_free > 0) {
if (dev_ctxt->ddl_cmd_concurrency) {
--dev_ctxt->ddl_cmd_ch_free;
result = true;
} else if ((dev_ctxt->ddl_frame_ch_free +
dev_ctxt->ddl_frame_ch_interim)
== dev_ctxt->ddl_frame_ch_depth) {
--dev_ctxt->ddl_cmd_ch_free;
result = true;
}
}
if (result) {
*transc = vcd_get_free_trans_tbl_entry(dev_ctxt);
if (!*transc) {
result = false;
vcd_release_command_channel(dev_ctxt, *transc);
}
}
return result;
}
u32 vcd_get_command_channel_in_loop(
struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc **transc)
{
u32 result = false;
*transc = NULL;
if (dev_ctxt->ddl_cmd_ch_interim > 0) {
if (dev_ctxt->ddl_cmd_concurrency) {
--dev_ctxt->ddl_cmd_ch_interim;
result = true;
} else if ((dev_ctxt->ddl_frame_ch_free +
dev_ctxt->ddl_frame_ch_interim)
== dev_ctxt->ddl_frame_ch_depth) {
--dev_ctxt->ddl_cmd_ch_interim;
result = true;
}
} else {
result = vcd_get_command_channel(dev_ctxt, transc);
}
if (result && !*transc) {
*transc = vcd_get_free_trans_tbl_entry(dev_ctxt);
if (!*transc) {
result = false;
++dev_ctxt->ddl_cmd_ch_interim;
}
}
return result;
}
void vcd_mark_command_channel(struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc *transc)
{
++dev_ctxt->ddl_cmd_ch_interim;
vcd_release_trans_tbl_entry(transc);
if (dev_ctxt->ddl_cmd_ch_interim +
dev_ctxt->ddl_cmd_ch_free >
dev_ctxt->ddl_cmd_ch_depth) {
VCD_MSG_ERROR("\n Command channel access counters messed up");
}
}
void vcd_release_command_channel(
struct vcd_dev_ctxt *dev_ctxt, struct vcd_transc *transc)
{
++dev_ctxt->ddl_cmd_ch_free;
vcd_release_trans_tbl_entry(transc);
if (dev_ctxt->ddl_cmd_ch_interim + dev_ctxt->ddl_cmd_ch_free >
dev_ctxt->ddl_cmd_ch_depth) {
VCD_MSG_ERROR("\n Command channel access counters messed up");
}
}
void vcd_release_multiple_command_channels(struct vcd_dev_ctxt
*dev_ctxt, u32 channels)
{
dev_ctxt->ddl_cmd_ch_free += channels;
if (dev_ctxt->ddl_cmd_ch_interim +
dev_ctxt->ddl_cmd_ch_free >
dev_ctxt->ddl_cmd_ch_depth) {
VCD_MSG_ERROR("\n Command channel access counters messed up");
}
}
void vcd_release_interim_command_channels(struct vcd_dev_ctxt *dev_ctxt)
{
dev_ctxt->ddl_cmd_ch_free += dev_ctxt->ddl_cmd_ch_interim;
dev_ctxt->ddl_cmd_ch_interim = 0;
if (dev_ctxt->ddl_cmd_ch_interim + dev_ctxt->ddl_cmd_ch_free >
dev_ctxt->ddl_cmd_ch_depth) {
VCD_MSG_ERROR("\n Command channel access counters messed up");
}
}
u32 vcd_get_frame_channel(struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc **transc)
{
u32 result = false;
if (dev_ctxt->ddl_frame_ch_free > 0) {
if (dev_ctxt->ddl_cmd_concurrency) {
--dev_ctxt->ddl_frame_ch_free;
result = true;
} else if ((dev_ctxt->ddl_cmd_ch_free +
dev_ctxt->ddl_cmd_ch_interim)
== dev_ctxt->ddl_cmd_ch_depth) {
--dev_ctxt->ddl_frame_ch_free;
result = true;
}
}
if (result) {
*transc = vcd_get_free_trans_tbl_entry(dev_ctxt);
if (!*transc) {
result = false;
vcd_release_frame_channel(dev_ctxt, *transc);
} else {
(*transc)->type = VCD_CMD_CODE_FRAME;
}
}
return result;
}
u32 vcd_get_frame_channel_in_loop(
struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc **transc)
{
u32 result = false;
*transc = NULL;
if (dev_ctxt->ddl_frame_ch_interim > 0) {
if (dev_ctxt->ddl_cmd_concurrency) {
--dev_ctxt->ddl_frame_ch_interim;
result = true;
} else if ((dev_ctxt->ddl_cmd_ch_free +
dev_ctxt->ddl_cmd_ch_interim)
== dev_ctxt->ddl_cmd_ch_depth) {
--dev_ctxt->ddl_frame_ch_interim;
result = true;
}
} else {
result = vcd_get_frame_channel(dev_ctxt, transc);
}
if (result && !*transc) {
*transc = vcd_get_free_trans_tbl_entry(dev_ctxt);
if (!*transc) {
result = false;
VCD_MSG_FATAL("\n%s: All transactions are busy;"
"Couldnt find free one\n", __func__);
++dev_ctxt->ddl_frame_ch_interim;
} else
(*transc)->type = VCD_CMD_CODE_FRAME;
}
return result;
}
void vcd_mark_frame_channel(struct vcd_dev_ctxt *dev_ctxt)
{
++dev_ctxt->ddl_frame_ch_interim;
if (dev_ctxt->ddl_frame_ch_interim +
dev_ctxt->ddl_frame_ch_free >
dev_ctxt->ddl_cmd_ch_depth) {
VCD_MSG_FATAL("Frame channel access counters messed up");
}
}
void vcd_release_frame_channel(struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc *transc)
{
++dev_ctxt->ddl_frame_ch_free;
vcd_release_trans_tbl_entry(transc);
if (dev_ctxt->ddl_frame_ch_interim +
dev_ctxt->ddl_frame_ch_free >
dev_ctxt->ddl_cmd_ch_depth) {
VCD_MSG_FATAL("Frame channel access counters messed up");
}
}
void vcd_release_multiple_frame_channels(struct vcd_dev_ctxt
*dev_ctxt, u32 channels)
{
dev_ctxt->ddl_frame_ch_free += channels;
if (dev_ctxt->ddl_frame_ch_interim +
dev_ctxt->ddl_frame_ch_free >
dev_ctxt->ddl_frame_ch_depth) {
VCD_MSG_FATAL("Frame channel access counters messed up");
}
}
void vcd_release_interim_frame_channels(struct vcd_dev_ctxt
*dev_ctxt)
{
dev_ctxt->ddl_frame_ch_free +=
dev_ctxt->ddl_frame_ch_interim;
dev_ctxt->ddl_frame_ch_interim = 0;
if (dev_ctxt->ddl_frame_ch_free >
dev_ctxt->ddl_cmd_ch_depth) {
VCD_MSG_FATAL("Frame channel access counters messed up");
}
}
u32 vcd_core_is_busy(struct vcd_dev_ctxt *dev_ctxt)
{
if (((dev_ctxt->ddl_cmd_ch_free +
dev_ctxt->ddl_cmd_ch_interim) !=
dev_ctxt->ddl_cmd_ch_depth)
||
((dev_ctxt->ddl_frame_ch_free +
dev_ctxt->ddl_frame_ch_interim) !=
dev_ctxt->ddl_frame_ch_depth)
) {
return true;
} else {
return false;
}
}
void vcd_device_timer_start(struct vcd_dev_ctxt *dev_ctxt)
{
if (dev_ctxt->config.timer_start)
dev_ctxt->config.timer_start(dev_ctxt->hw_timer_handle,
dev_ctxt->hw_time_out);
}
void vcd_device_timer_stop(struct vcd_dev_ctxt *dev_ctxt)
{
if (dev_ctxt->config.timer_stop)
dev_ctxt->config.timer_stop(dev_ctxt->hw_timer_handle);
}
u32 vcd_common_allocate_set_buffer(
struct vcd_clnt_ctxt *cctxt,
enum vcd_buffer_type buffer,
u32 buf_size, struct vcd_buffer_pool **buffer_pool)
{
u32 rc = VCD_S_SUCCESS;
struct vcd_buffer_requirement Buf_req;
struct vcd_property_hdr Prop_hdr;
struct vcd_buffer_pool *buf_pool;
if (buffer == VCD_BUFFER_INPUT) {
Prop_hdr.prop_id = DDL_I_INPUT_BUF_REQ;
buf_pool = &cctxt->in_buf_pool;
} else if (buffer == VCD_BUFFER_OUTPUT) {
Prop_hdr.prop_id = DDL_I_OUTPUT_BUF_REQ;
buf_pool = &cctxt->out_buf_pool;
} else {
rc = VCD_ERR_ILLEGAL_PARM;
}
VCD_FAILED_RETURN(rc, "Invalid buffer type provided");
*buffer_pool = buf_pool;
if (buf_pool->count > 0 &&
buf_pool->validated == buf_pool->count) {
VCD_MSG_ERROR("Buffer pool is full");
return VCD_ERR_FAIL;
}
if (!buf_pool->entries) {
Prop_hdr.sz = sizeof(Buf_req);
rc = ddl_get_property(cctxt->ddl_handle, &Prop_hdr, &Buf_req);
if (!VCD_FAILED(rc)) {
rc = vcd_alloc_buffer_pool_entries(buf_pool,
&Buf_req);
} else {
VCD_MSG_ERROR("rc = 0x%x. Failed: ddl_get_property",
rc);
}
}
if (!VCD_FAILED(rc)) {
if (buf_pool->buf_req.sz > buf_size) {
VCD_MSG_ERROR("\n required buffer sz %u "
"allocated sz %u", buf_pool->buf_req.
sz, buf_size);
rc = VCD_ERR_ILLEGAL_PARM;
}
}
return rc;
}
u32 vcd_set_buffer_internal(
struct vcd_clnt_ctxt *cctxt,
struct vcd_buffer_pool *buf_pool, u8 *buffer, u32 buf_size)
{
struct vcd_buffer_entry *buf_entry;
u8 *physical;
u32 ion_flag = 0;
struct ion_handle *buff_handle = NULL;
buf_entry = vcd_find_buffer_pool_entry(buf_pool, buffer);
if (buf_entry) {
VCD_MSG_ERROR("This buffer address already exists");
return VCD_ERR_ILLEGAL_OP;
}
physical = (u8 *) vcd_pmem_get_physical(
cctxt->client_data, (unsigned long)buffer);
ion_flag = vcd_get_ion_flag(cctxt->client_data,
(unsigned long)buffer,
&buff_handle);
if (!physical) {
VCD_MSG_ERROR("Couldn't get physical address");
return VCD_ERR_BAD_POINTER;
}
if (((u32) physical % buf_pool->buf_req.align)) {
VCD_MSG_ERROR("Physical addr is not aligned");
return VCD_ERR_BAD_POINTER;
}
buf_entry = vcd_get_free_buffer_pool_entry(buf_pool);
if (!buf_entry) {
VCD_MSG_ERROR("Can't allocate buffer pool is full");
return VCD_ERR_FAIL;
}
buf_entry->virtual = buffer;
buf_entry->physical = physical;
buf_entry->sz = buf_size;
buf_entry->frame.alloc_len = buf_size;
buf_entry->allocated = false;
buf_entry->frame.virtual = buf_entry->virtual;
buf_entry->frame.physical = buf_entry->physical;
buf_entry->frame.ion_flag = ion_flag;
buf_entry->frame.buff_ion_handle = buff_handle;
buf_pool->validated++;
return VCD_S_SUCCESS;
}
u32 vcd_allocate_buffer_internal(
struct vcd_clnt_ctxt *cctxt,
struct vcd_buffer_pool *buf_pool,
u32 buf_size, u8 **vir_buf_addr, u8 **phy_buf_addr)
{
struct vcd_buffer_entry *buf_entry;
struct vcd_buffer_requirement *buf_req;
u32 addr;
int rc = 0;
buf_entry = vcd_get_free_buffer_pool_entry(buf_pool);
if (!buf_entry) {
VCD_MSG_ERROR("Can't allocate buffer pool is full");
return VCD_ERR_FAIL;
}
buf_req = &buf_pool->buf_req;
buf_size += buf_req->align;
rc = vcd_pmem_alloc(buf_size, &buf_entry->alloc,
&buf_entry->physical, cctxt);
if (rc < 0) {
VCD_MSG_ERROR("Buffer allocation failed");
return VCD_ERR_ALLOC_FAIL;
}
buf_entry->sz = buf_size;
buf_entry->frame.alloc_len = buf_size;
if (!buf_entry->physical) {
VCD_MSG_ERROR("Couldn't get physical address");
return VCD_ERR_BAD_POINTER;
}
buf_entry->allocated = true;
if (buf_req->align > 0) {
addr = (u32) buf_entry->physical;
addr += buf_req->align;
addr -= (addr % buf_req->align);
buf_entry->virtual = buf_entry->alloc;
buf_entry->virtual += (u32) (addr - (u32)
buf_entry->physical);
buf_entry->physical = (u8 *) addr;
} else {
VCD_MSG_LOW("No buffer alignment required");
buf_entry->virtual = buf_entry->alloc;
}
buf_entry->frame.virtual = buf_entry->virtual;
buf_entry->frame.physical = buf_entry->physical;
*vir_buf_addr = buf_entry->virtual;
*phy_buf_addr = buf_entry->physical;
buf_pool->allocated++;
buf_pool->validated++;
return VCD_S_SUCCESS;
}
u32 vcd_free_one_buffer_internal(
struct vcd_clnt_ctxt *cctxt,
enum vcd_buffer_type buffer_type, u8 *buffer)
{
struct vcd_buffer_pool *buf_pool;
u32 rc = VCD_S_SUCCESS;
struct vcd_buffer_entry *buf_entry;
u32 first_frm_recvd = 0;
if (buffer_type == VCD_BUFFER_INPUT) {
buf_pool = &cctxt->in_buf_pool;
first_frm_recvd = VCD_FIRST_IP_RCVD;
} else if (buffer_type == VCD_BUFFER_OUTPUT) {
buf_pool = &cctxt->out_buf_pool;
first_frm_recvd = VCD_FIRST_OP_RCVD;
} else
rc = VCD_ERR_ILLEGAL_PARM;
VCD_FAILED_RETURN(rc, "Invalid buffer type provided");
first_frm_recvd &= cctxt->status.mask;
if (first_frm_recvd && !cctxt->meta_mode) {
VCD_MSG_ERROR(
"VCD free buffer called when data path is active");
return VCD_ERR_BAD_STATE;
}
buf_entry = vcd_find_buffer_pool_entry(buf_pool, buffer);
if (!buf_entry) {
VCD_MSG_ERROR("Buffer addr %p not found. Can't free buffer",
buffer);
return VCD_ERR_ILLEGAL_PARM;
}
if (buf_entry->in_use) {
VCD_MSG_ERROR("Buffer is in use and is not flushed: %p, %d\n",
buf_entry, buf_entry->in_use);
return VCD_ERR_ILLEGAL_OP;
}
VCD_MSG_LOW("Freeing buffer %p. Allocated %d",
buf_entry->virtual, buf_entry->allocated);
if (buf_entry->allocated) {
vcd_pmem_free(buf_entry->alloc, buf_entry->physical, cctxt);
buf_pool->allocated--;
}
buf_entry->valid = buf_entry->allocated = buf_entry->in_use = 0;
buf_entry->alloc = buf_entry->virtual = buf_entry->physical = NULL;
buf_entry->sz = 0;
memset(&buf_entry->frame, 0, sizeof(struct vcd_frame_data));
buf_pool->validated--;
if (buf_pool->validated == 0)
vcd_free_buffer_pool_entries(buf_pool);
return VCD_S_SUCCESS;
}
u32 vcd_free_buffers_internal(
struct vcd_clnt_ctxt *cctxt,
struct vcd_buffer_pool *buf_pool)
{
u32 rc = VCD_S_SUCCESS;
u32 i;
VCD_MSG_LOW("vcd_free_buffers_internal:");
if (buf_pool->entries) {
for (i = 1; i <= buf_pool->count; i++) {
if (buf_pool->entries[i].valid &&
buf_pool->entries[i].allocated) {
vcd_pmem_free(buf_pool->entries[i].alloc,
buf_pool->entries[i].
physical, cctxt);
}
}
}
vcd_reset_buffer_pool_for_reuse(buf_pool);
return rc;
}
u32 vcd_alloc_buffer_pool_entries(
struct vcd_buffer_pool *buf_pool,
struct vcd_buffer_requirement *buf_req)
{
VCD_MSG_LOW("vcd_alloc_buffer_pool_entries:");
buf_pool->buf_req = *buf_req;
buf_pool->count = buf_req->actual_count;
buf_pool->entries = (struct vcd_buffer_entry *)
kzalloc((sizeof(struct vcd_buffer_entry) *
(VCD_MAX_BUFFER_ENTRIES + 1)), GFP_KERNEL);
if (!buf_pool->entries) {
VCD_MSG_ERROR("Buf_pool entries alloc failed");
return VCD_ERR_ALLOC_FAIL;
}
INIT_LIST_HEAD(&buf_pool->queue);
buf_pool->entries[0].valid = true;
buf_pool->q_len = 0;
buf_pool->validated = 0;
buf_pool->allocated = 0;
buf_pool->in_use = 0;
return VCD_S_SUCCESS;
}
void vcd_free_buffer_pool_entries(struct vcd_buffer_pool *buf_pool)
{
VCD_MSG_LOW("vcd_free_buffer_pool_entries:");
kfree(buf_pool->entries);
memset(buf_pool, 0, sizeof(struct vcd_buffer_pool));
INIT_LIST_HEAD(&buf_pool->queue);
}
void vcd_flush_in_use_buffer_pool_entries(struct vcd_clnt_ctxt *cctxt,
struct vcd_buffer_pool *buf_pool, u32 event)
{
u32 i;
VCD_MSG_LOW("vcd_flush_buffer_pool_entries: event=0x%x", event);
if (buf_pool->entries) {
for (i = 0; i <= buf_pool->count; i++) {
if (buf_pool->entries[i].virtual &&
buf_pool->entries[i].in_use) {
cctxt->callback(event, VCD_S_SUCCESS,
&buf_pool->entries[i].frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
buf_pool->entries[i].in_use = false;
VCD_BUFFERPOOL_INUSE_DECREMENT(
buf_pool->in_use);
}
}
}
}
void vcd_reset_buffer_pool_for_reuse(struct vcd_buffer_pool *buf_pool)
{
VCD_MSG_LOW("vcd_reset_buffer_pool_for_reuse:");
if (buf_pool->entries) {
memset(&buf_pool->entries[1], 0,
sizeof(struct vcd_buffer_entry) *
VCD_MAX_BUFFER_ENTRIES);
}
buf_pool->q_len = 0;
buf_pool->validated = 0;
buf_pool->allocated = 0;
buf_pool->in_use = 0;
INIT_LIST_HEAD(&buf_pool->queue);
}
struct vcd_buffer_entry *vcd_get_free_buffer_pool_entry
(struct vcd_buffer_pool *pool) {
u32 i;
i = 1;
while (i <= pool->count && pool->entries[i].valid)
i++;
if (i <= pool->count) {
pool->entries[i].valid = true;
return &pool->entries[i];
} else {
return NULL;
}
}
struct vcd_buffer_entry *vcd_find_buffer_pool_entry
(struct vcd_buffer_pool *pool, u8 *addr)
{
u32 i;
u32 found = false;
for (i = 1; i <= pool->count && !found; i++) {
if (pool->entries[i].virtual == addr)
found = true;
}
if (found)
return &pool->entries[i - 1];
else
return NULL;
}
u32 vcd_buffer_pool_entry_en_q(
struct vcd_buffer_pool *pool,
struct vcd_buffer_entry *entry)
{
struct vcd_buffer_entry *list_itr;
if (pool->q_len == pool->count)
return false;
list_for_each_entry(list_itr, &pool->queue, list)
if (list_itr == entry) {
VCD_MSG_HIGH("\n this output buffer is already present"
" in queue");
VCD_MSG_HIGH("\n Vir Addr %p Phys Addr %p",
entry->virtual, entry->physical);
return false;
}
list_add_tail(&entry->list, &pool->queue);
pool->q_len++;
return true;
}
struct vcd_buffer_entry *vcd_buffer_pool_entry_de_q
(struct vcd_buffer_pool *pool) {
struct vcd_buffer_entry *entry;
if (!pool || !pool->q_len)
return NULL;
entry = list_first_entry(&pool->queue,
struct vcd_buffer_entry, list);
if (entry) {
list_del(&entry->list);
pool->q_len--;
}
return entry;
}
void vcd_flush_bframe_buffers(struct vcd_clnt_ctxt *cctxt, u32 mode)
{
int i;
struct vcd_buffer_pool *buf_pool;
if (!cctxt->decoding && cctxt->bframe) {
buf_pool = (mode == VCD_FLUSH_INPUT) ?
&cctxt->in_buf_pool : &cctxt->out_buf_pool;
if (buf_pool->entries != NULL) {
for (i = 1; i <= buf_pool->count; i++) {
if ((buf_pool->entries[i].in_use) &&
(buf_pool->entries[i].frame.virtual
!= NULL)) {
if (mode == VCD_FLUSH_INPUT) {
cctxt->callback(
VCD_EVT_RESP_INPUT_FLUSHED,
VCD_S_SUCCESS,
&(buf_pool->entries[i].frame),
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
} else {
buf_pool->entries[i].
frame.data_len = 0;
cctxt->callback(
VCD_EVT_RESP_OUTPUT_FLUSHED,
VCD_S_SUCCESS,
&(buf_pool->entries[i].frame),
sizeof(struct vcd_frame_data),
cctxt,
cctxt->client_data);
}
VCD_BUFFERPOOL_INUSE_DECREMENT(
buf_pool->in_use);
buf_pool->entries[i].in_use = false;
}
}
}
}
}
void vcd_flush_output_buffers(struct vcd_clnt_ctxt *cctxt)
{
struct vcd_buffer_pool *buf_pool;
struct vcd_buffer_entry *buf_entry;
u32 count = 0;
struct vcd_property_hdr prop_hdr;
VCD_MSG_LOW("vcd_flush_output_buffers:");
buf_pool = &cctxt->out_buf_pool;
buf_entry = vcd_buffer_pool_entry_de_q(buf_pool);
while (buf_entry) {
if (!cctxt->decoding || buf_entry->in_use) {
buf_entry->frame.data_len = 0;
cctxt->callback(VCD_EVT_RESP_OUTPUT_FLUSHED,
VCD_S_SUCCESS,
&buf_entry->frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
if (buf_entry->in_use) {
VCD_BUFFERPOOL_INUSE_DECREMENT(
buf_pool->in_use);
buf_entry->in_use = false;
}
count++;
}
buf_entry = vcd_buffer_pool_entry_de_q(buf_pool);
}
vcd_flush_bframe_buffers(cctxt, VCD_FLUSH_OUTPUT);
if (buf_pool->in_use || buf_pool->q_len) {
VCD_MSG_ERROR("%s(): WARNING in_use(%u) or q_len(%u) not zero!",
__func__, buf_pool->in_use, buf_pool->q_len);
buf_pool->in_use = buf_pool->q_len = 0;
}
if (cctxt->sched_clnt_hdl) {
if (count > cctxt->sched_clnt_hdl->tkns)
cctxt->sched_clnt_hdl->tkns = 0;
else
cctxt->sched_clnt_hdl->tkns -= count;
}
if (cctxt->ddl_hdl_valid && cctxt->decoding) {
prop_hdr.prop_id = DDL_I_REQ_OUTPUT_FLUSH;
prop_hdr.sz = sizeof(u32);
count = 0x1;
(void)ddl_set_property(cctxt->ddl_handle, &prop_hdr,
&count);
}
vcd_release_all_clnt_frm_transc(cctxt);
cctxt->status.mask &= ~VCD_IN_RECONFIG;
}
u32 vcd_flush_buffers(struct vcd_clnt_ctxt *cctxt, u32 mode)
{
u32 rc = VCD_S_SUCCESS;
struct vcd_buffer_entry *buf_entry;
struct vcd_buffer_entry *orig_frame = NULL;
VCD_MSG_LOW("vcd_flush_buffers:");
if (mode > VCD_FLUSH_ALL || !(mode & VCD_FLUSH_ALL)) {
VCD_MSG_ERROR("Invalid flush mode %d", mode);
return VCD_ERR_ILLEGAL_PARM;
}
VCD_MSG_MED("Flush mode %d requested", mode);
if ((mode & VCD_FLUSH_INPUT) &&
cctxt->sched_clnt_hdl) {
rc = vcd_sched_dequeue_buffer(
cctxt->sched_clnt_hdl, &buf_entry);
while (!VCD_FAILED(rc) && buf_entry) {
if (buf_entry->virtual) {
cctxt->callback(VCD_EVT_RESP_INPUT_FLUSHED,
VCD_S_SUCCESS,
&buf_entry->frame,
sizeof(struct
vcd_frame_data),
cctxt,
cctxt->client_data);
orig_frame = vcd_find_buffer_pool_entry(
&cctxt->in_buf_pool,
buf_entry->virtual);
}
if (orig_frame) {
orig_frame->in_use--;
if (orig_frame != buf_entry)
kfree(buf_entry);
} else {
buf_entry->in_use = false;
VCD_MSG_ERROR("Original frame not found in buffer pool\n");
}
VCD_BUFFERPOOL_INUSE_DECREMENT(
cctxt->in_buf_pool.in_use);
buf_entry = NULL;
rc = vcd_sched_dequeue_buffer(
cctxt->sched_clnt_hdl, &buf_entry);
}
}
if (rc != VCD_ERR_QEMPTY)
VCD_FAILED_RETURN(rc, "Failed: vcd_sched_dequeue_buffer");
if (cctxt->status.frame_submitted > 0)
cctxt->status.mask |= mode;
else {
if (mode & VCD_FLUSH_INPUT)
vcd_flush_bframe_buffers(cctxt, VCD_FLUSH_INPUT);
if (mode & VCD_FLUSH_OUTPUT)
vcd_flush_output_buffers(cctxt);
}
return VCD_S_SUCCESS;
}
void vcd_flush_buffers_in_err_fatal(struct vcd_clnt_ctxt *cctxt)
{
VCD_MSG_LOW("\n vcd_flush_buffers_in_err_fatal:");
(void) vcd_flush_buffers(cctxt, VCD_FLUSH_ALL);
vcd_flush_in_use_buffer_pool_entries(cctxt,
&cctxt->in_buf_pool, VCD_EVT_RESP_INPUT_FLUSHED);
vcd_flush_in_use_buffer_pool_entries(cctxt,
&cctxt->out_buf_pool, VCD_EVT_RESP_OUTPUT_FLUSHED);
vcd_send_flush_done(cctxt, VCD_S_SUCCESS);
}
u32 vcd_init_client_context(struct vcd_clnt_ctxt *cctxt)
{
u32 rc;
VCD_MSG_LOW("vcd_init_client_context:");
rc = ddl_open(&cctxt->ddl_handle, cctxt->decoding);
VCD_FAILED_RETURN(rc, "Failed: ddl_open");
cctxt->vcd_enable_ion = res_trk_get_enable_ion();
if (cctxt->vcd_enable_ion) {
cctxt->vcd_ion_client = res_trk_get_ion_client();
if (!cctxt->vcd_ion_client) {
VCD_MSG_LOW("vcd_init_ion_get_client_failed:");
return -EINVAL;
}
}
cctxt->ddl_hdl_valid = true;
cctxt->clnt_state.state = VCD_CLIENT_STATE_OPEN;
cctxt->clnt_state.state_table =
vcd_get_client_state_table(VCD_CLIENT_STATE_OPEN);
cctxt->signature = VCD_SIGNATURE;
cctxt->live = true;
cctxt->bframe = 0;
cctxt->cmd_q.pending_cmd = VCD_CMD_NONE;
cctxt->status.last_evt = VCD_EVT_RESP_BASE;
cctxt->num_slices = 1;
return rc;
}
void vcd_destroy_client_context(struct vcd_clnt_ctxt *cctxt)
{
struct vcd_dev_ctxt *dev_ctxt;
struct vcd_clnt_ctxt *client;
struct vcd_buffer_entry *buf_entry;
u32 rc = VCD_S_SUCCESS;
VCD_MSG_LOW("vcd_destroy_client_context:");
dev_ctxt = cctxt->dev_ctxt;
if (cctxt == dev_ctxt->cctxt_list_head) {
VCD_MSG_MED("Clnt list head clnt being removed");
dev_ctxt->cctxt_list_head = cctxt->next;
} else {
client = dev_ctxt->cctxt_list_head;
while (client && cctxt != client->next)
client = client->next;
if (client)
client->next = cctxt->next;
if (!client) {
rc = VCD_ERR_FAIL;
VCD_MSG_ERROR("Client not found in client list");
}
}
if (VCD_FAILED(rc))
return;
if (cctxt->sched_clnt_hdl) {
rc = VCD_S_SUCCESS;
while (!VCD_FAILED(rc)) {
rc = vcd_sched_dequeue_buffer(
cctxt->sched_clnt_hdl, &buf_entry);
if (rc != VCD_ERR_QEMPTY && VCD_FAILED(rc))
VCD_MSG_ERROR("\n Failed: "
"vcd_sched_de_queue_buffer");
}
rc = vcd_sched_remove_client(cctxt->sched_clnt_hdl);
if (VCD_FAILED(rc))
VCD_MSG_ERROR("\n Failed: sched_remove_client");
cctxt->sched_clnt_hdl = NULL;
}
if (cctxt->seq_hdr.sequence_header) {
vcd_pmem_free(cctxt->seq_hdr.sequence_header,
cctxt->seq_hdr_phy_addr, cctxt);
cctxt->seq_hdr.sequence_header = NULL;
}
vcd_free_buffers_internal(cctxt, &cctxt->in_buf_pool);
vcd_free_buffers_internal(cctxt, &cctxt->out_buf_pool);
vcd_free_buffer_pool_entries(&cctxt->in_buf_pool);
vcd_free_buffer_pool_entries(&cctxt->out_buf_pool);
vcd_release_all_clnt_transc(cctxt);
if (cctxt->ddl_hdl_valid) {
(void)ddl_close(&cctxt->ddl_handle);
cctxt->ddl_hdl_valid = false;
}
cctxt->signature = 0;
cctxt->clnt_state.state = VCD_CLIENT_STATE_NULL;
cctxt->clnt_state.state_table = NULL;
cctxt->vcd_ion_client = NULL;
kfree(cctxt);
}
u32 vcd_check_for_client_context(
struct vcd_dev_ctxt *dev_ctxt, s32 driver_id)
{
struct vcd_clnt_ctxt *client;
client = dev_ctxt->cctxt_list_head;
while (client && client->driver_id != driver_id)
client = client->next;
if (!client)
return false;
else
return true;
}
u32 vcd_validate_driver_handle(
struct vcd_dev_ctxt *dev_ctxt, s32 driver_handle)
{
driver_handle--;
if (driver_handle < 0 ||
driver_handle >= VCD_DRIVER_CLIENTS_MAX ||
!dev_ctxt->driver_ids[driver_handle]) {
return false;
} else {
return true;
}
}
u32 vcd_client_cmd_en_q(
struct vcd_clnt_ctxt *cctxt, enum vcd_command command)
{
u32 result;
if (cctxt->cmd_q.pending_cmd == VCD_CMD_NONE) {
cctxt->cmd_q.pending_cmd = command;
result = true;
} else {
result = false;
}
return result;
}
void vcd_client_cmd_flush_and_en_q(
struct vcd_clnt_ctxt *cctxt, enum vcd_command command)
{
cctxt->cmd_q.pending_cmd = command;
}
u32 vcd_client_cmd_de_q(struct vcd_clnt_ctxt *cctxt,
enum vcd_command *command)
{
if (cctxt->cmd_q.pending_cmd == VCD_CMD_NONE)
return false;
*command = cctxt->cmd_q.pending_cmd;
cctxt->cmd_q.pending_cmd = VCD_CMD_NONE;
return true;
}
u32 vcd_get_next_queued_client_cmd(struct vcd_dev_ctxt *dev_ctxt,
struct vcd_clnt_ctxt **cctxt, enum vcd_command *command)
{
struct vcd_clnt_ctxt *client = dev_ctxt->cctxt_list_head;
u32 result = false;
while (client && !result) {
*cctxt = client;
result = vcd_client_cmd_de_q(client, command);
client = client->next;
}
return result;
}
u32 vcd_submit_cmd_sess_start(struct vcd_transc *transc)
{
u32 rc;
struct vcd_sequence_hdr Seq_hdr;
VCD_MSG_LOW("vcd_submit_cmd_sess_start:");
if (transc->cctxt->decoding) {
if (transc->cctxt->seq_hdr.sequence_header) {
Seq_hdr.sequence_header_len =
transc->cctxt->seq_hdr.
sequence_header_len;
Seq_hdr.sequence_header =
transc->cctxt->seq_hdr_phy_addr;
rc = ddl_decode_start(transc->cctxt->ddl_handle,
&Seq_hdr, (void *)transc);
} else {
rc = ddl_decode_start(transc->cctxt->ddl_handle,
NULL, (void *)transc);
}
} else {
vcd_set_num_slices(transc->cctxt);
rc = ddl_encode_start(transc->cctxt->ddl_handle,
(void *)transc);
}
if (!VCD_FAILED(rc)) {
transc->cctxt->status.cmd_submitted++;
vcd_device_timer_start(transc->cctxt->dev_ctxt);
} else
VCD_MSG_ERROR("rc = 0x%x. Failed: ddl start", rc);
return rc;
}
u32 vcd_submit_cmd_sess_end(struct vcd_transc *transc)
{
u32 rc;
VCD_MSG_LOW("vcd_submit_cmd_sess_end:");
if (transc->cctxt->decoding) {
rc = ddl_decode_end(transc->cctxt->ddl_handle,
(void *)transc);
} else {
rc = ddl_encode_end(transc->cctxt->ddl_handle,
(void *)transc);
}
if (!VCD_FAILED(rc)) {
transc->cctxt->status.cmd_submitted++;
vcd_device_timer_start(transc->cctxt->dev_ctxt);
} else
VCD_MSG_ERROR("rc = 0x%x. Failed: ddl end", rc);
return rc;
}
void vcd_submit_cmd_client_close(struct vcd_clnt_ctxt *cctxt)
{
(void) ddl_close(&cctxt->ddl_handle);
cctxt->ddl_hdl_valid = false;
cctxt->status.mask &= ~VCD_CLEANING_UP;
if (cctxt->status.mask & VCD_CLOSE_PENDING) {
vcd_destroy_client_context(cctxt);
vcd_handle_for_last_clnt_close(cctxt->dev_ctxt, true);
}
}
u32 vcd_submit_command_in_continue(struct vcd_dev_ctxt
*dev_ctxt, struct vcd_transc *transc)
{
struct vcd_property_hdr prop_hdr;
struct vcd_clnt_ctxt *client = NULL;
enum vcd_command cmd = VCD_CMD_NONE;
u32 rc = VCD_ERR_FAIL;
u32 result = false, flush = 0, event = 0;
u32 command_break = false;
VCD_MSG_LOW("\n vcd_submit_command_in_continue:");
while (!command_break) {
result = vcd_get_next_queued_client_cmd(dev_ctxt,
&client, &cmd);
if (!result)
command_break = true;
else {
transc->type = cmd;
transc->cctxt = client;
switch (cmd) {
case VCD_CMD_CODEC_START:
{
rc = vcd_submit_cmd_sess_start(transc);
event = VCD_EVT_RESP_START;
break;
}
case VCD_CMD_CODEC_STOP:
{
rc = vcd_submit_cmd_sess_end(transc);
event = VCD_EVT_RESP_STOP;
break;
}
case VCD_CMD_OUTPUT_FLUSH:
{
prop_hdr.prop_id = DDL_I_REQ_OUTPUT_FLUSH;
prop_hdr.sz = sizeof(u32);
flush = 0x1;
(void) ddl_set_property(client->ddl_handle,
&prop_hdr, &flush);
vcd_release_command_channel(dev_ctxt,
transc);
rc = VCD_S_SUCCESS;
break;
}
case VCD_CMD_CLIENT_CLOSE:
{
vcd_submit_cmd_client_close(client);
vcd_release_command_channel(dev_ctxt,
transc);
rc = VCD_S_SUCCESS;
break;
}
default:
{
VCD_MSG_ERROR("\n vcd_submit_command: Unknown"
"command %d", (int)cmd);
break;
}
}
if (!VCD_FAILED(rc)) {
command_break = true;
} else {
VCD_MSG_ERROR("vcd_submit_command %d: failed 0x%x",
cmd, rc);
client->callback(event, rc, NULL, 0, client,
client->client_data);
}
}
}
return result;
}
u32 vcd_schedule_frame(struct vcd_dev_ctxt *dev_ctxt,
struct vcd_clnt_ctxt **cctxt, struct vcd_buffer_entry
**ip_buf_entry)
{
u32 rc = VCD_S_SUCCESS;
VCD_MSG_LOW("vcd_schedule_frame:");
if (!dev_ctxt->cctxt_list_head) {
VCD_MSG_HIGH("Client list empty");
return false;
}
rc = vcd_sched_get_client_frame(&dev_ctxt->sched_clnt_list,
cctxt, ip_buf_entry);
if (rc == VCD_ERR_QEMPTY) {
VCD_MSG_HIGH("No frame available. Sched queues are empty");
return false;
}
if (VCD_FAILED(rc)) {
VCD_MSG_FATAL("vcd_submit_frame: sched_de_queue_frame"
"failed 0x%x", rc);
return false;
}
if (!*cctxt || !*ip_buf_entry) {
VCD_MSG_FATAL("Sched returned invalid values. ctxt=%p,"
"ipbuf=%p", *cctxt, *ip_buf_entry);
return false;
}
return true;
}
void vcd_try_submit_frame(struct vcd_dev_ctxt *dev_ctxt)
{
struct vcd_transc *transc;
u32 rc = VCD_S_SUCCESS;
struct vcd_clnt_ctxt *cctxt = NULL;
struct vcd_buffer_entry *ip_buf_entry = NULL;
u32 result = false;
VCD_MSG_LOW("vcd_try_submit_frame:");
if (!vcd_get_frame_channel(dev_ctxt, &transc))
return;
if (!vcd_schedule_frame(dev_ctxt, &cctxt, &ip_buf_entry)) {
vcd_release_frame_channel(dev_ctxt, transc);
return;
}
rc = vcd_power_event(dev_ctxt, cctxt, VCD_EVT_PWR_CLNT_CMD_BEGIN);
if (!VCD_FAILED(rc)) {
transc->cctxt = cctxt;
transc->ip_buf_entry = ip_buf_entry;
result = vcd_submit_frame(dev_ctxt, transc);
} else {
VCD_MSG_ERROR("Failed: VCD_EVT_PWR_CLNT_CMD_BEGIN");
(void) vcd_sched_queue_buffer(
cctxt->sched_clnt_hdl, ip_buf_entry, false);
cctxt->sched_clnt_hdl->tkns++;
}
if (!result) {
vcd_release_frame_channel(dev_ctxt, transc);
(void) vcd_power_event(dev_ctxt, cctxt,
VCD_EVT_PWR_CLNT_CMD_FAIL);
}
}
u32 vcd_submit_frame(struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc *transc)
{
struct vcd_clnt_ctxt *cctxt = NULL;
struct vcd_frame_data *ip_frm_entry;
struct vcd_buffer_entry *op_buf_entry = NULL;
u32 rc = VCD_S_SUCCESS;
u32 evcode = 0;
u32 perf_level = 0;
int decodeTime = 0;
struct ddl_frame_data_tag ddl_ip_frm;
struct ddl_frame_data_tag *ddl_op_frm;
u32 out_buf_cnt = 0;
VCD_MSG_LOW("vcd_submit_frame:");
cctxt = transc->cctxt;
ip_frm_entry = &transc->ip_buf_entry->frame;
transc->op_buf_entry = op_buf_entry;
transc->ip_frm_tag = ip_frm_entry->ip_frm_tag;
transc->time_stamp = ip_frm_entry->time_stamp;
transc->flags = ip_frm_entry->flags;
ip_frm_entry->ip_frm_tag = (u32) transc;
memset(&ddl_ip_frm, 0, sizeof(ddl_ip_frm));
if (cctxt->decoding) {
decodeTime = ddl_get_core_decode_proc_time(cctxt->ddl_handle);
if (decodeTime > MAX_DEC_TIME) {
if (res_trk_get_curr_perf_level(&perf_level)) {
vcd_update_decoder_perf_level(dev_ctxt,
res_trk_estimate_perf_level(perf_level));
ddl_reset_avg_dec_time(cctxt->ddl_handle);
} else
VCD_MSG_ERROR("%s(): retrieve curr_perf_level"
"returned FALSE\n", __func__);
}
evcode = CLIENT_STATE_EVENT_NUMBER(decode_frame);
ddl_ip_frm.vcd_frm = *ip_frm_entry;
rc = ddl_decode_frame(cctxt->ddl_handle, &ddl_ip_frm,
(void *) transc);
} else {
ddl_op_frm = (struct ddl_frame_data_tag *)
kmalloc((sizeof(struct ddl_frame_data_tag) *
VCD_ENC_MAX_OUTBFRS_PER_FRAME), GFP_KERNEL);
if (!ddl_op_frm) {
VCD_MSG_ERROR("Memory allocation failure");
return VCD_ERR_ALLOC_FAIL;
}
memset(ddl_op_frm, 0, (sizeof(struct ddl_frame_data_tag) *
VCD_ENC_MAX_OUTBFRS_PER_FRAME));
for (out_buf_cnt = 0; out_buf_cnt < cctxt->num_slices ;
out_buf_cnt++) {
op_buf_entry = vcd_buffer_pool_entry_de_q(
&cctxt->out_buf_pool);
if (!op_buf_entry) {
VCD_MSG_ERROR("Sched provided frame when no"
"op buffer was present");
rc = VCD_ERR_FAIL;
break;
}
op_buf_entry->in_use = true;
cctxt->out_buf_pool.in_use++;
ddl_op_frm[out_buf_cnt].vcd_frm = op_buf_entry->frame;
VCD_MSG_LOW("%s : buffer_cnt = %d framebfr(virtual)"
" 0x%p", __func__, out_buf_cnt,
op_buf_entry->frame.virtual);
VCD_MSG_LOW("framebfr(physical) 0x%p bfrlength %d",
op_buf_entry->frame.physical,
op_buf_entry->frame.alloc_len);
}
ddl_ip_frm.vcd_frm = *ip_frm_entry;
ddl_ip_frm.frm_delta =
vcd_calculate_frame_delta(cctxt,
ip_frm_entry);
evcode = CLIENT_STATE_EVENT_NUMBER(encode_frame);
if (!VCD_FAILED(rc)) {
rc = ddl_encode_frame(cctxt->ddl_handle,
&ddl_ip_frm, &ddl_op_frm[0], (void *) transc);
}
kfree(ddl_op_frm);
}
ip_frm_entry->ip_frm_tag = transc->ip_frm_tag;
if (!VCD_FAILED(rc)) {
vcd_device_timer_start(dev_ctxt);
cctxt->status.frame_submitted++;
if (ip_frm_entry->flags & VCD_FRAME_FLAG_EOS)
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_EOS, evcode);
} else {
VCD_MSG_ERROR("Frame submission failed. rc = 0x%x", rc);
vcd_handle_submit_frame_failed(dev_ctxt, transc);
}
return true;
}
u32 vcd_try_submit_frame_in_continue(struct vcd_dev_ctxt *dev_ctxt,
struct vcd_transc *transc)
{
struct vcd_clnt_ctxt *cctxt = NULL;
struct vcd_buffer_entry *ip_buf_entry = NULL;
VCD_MSG_LOW("vcd_try_submit_frame_in_continue:");
if (!vcd_schedule_frame(dev_ctxt, &cctxt, &ip_buf_entry))
return false;
transc->cctxt = cctxt;
transc->ip_buf_entry = ip_buf_entry;
return vcd_submit_frame(dev_ctxt, transc);
}
u32 vcd_process_cmd_sess_start(struct vcd_clnt_ctxt *cctxt)
{
struct vcd_transc *transc;
u32 rc = VCD_S_SUCCESS;
VCD_MSG_LOW("vcd_process_cmd_sess_start:");
if (vcd_get_command_channel(cctxt->dev_ctxt, &transc)) {
rc = vcd_power_event(cctxt->dev_ctxt,
cctxt, VCD_EVT_PWR_CLNT_CMD_BEGIN);
if (!VCD_FAILED(rc)) {
transc->type = VCD_CMD_CODEC_START;
transc->cctxt = cctxt;
rc = vcd_submit_cmd_sess_start(transc);
} else {
VCD_MSG_ERROR("Failed: VCD_EVT_PWR_CLNT_CMD_BEGIN");
}
if (VCD_FAILED(rc)) {
vcd_release_command_channel(cctxt->dev_ctxt,
transc);
}
} else {
u32 result;
result = vcd_client_cmd_en_q(cctxt, VCD_CMD_CODEC_START);
if (!result) {
rc = VCD_ERR_BUSY;
VCD_MSG_ERROR("%s(): vcd_client_cmd_en_q() "
"failed\n", __func__);
}
}
if (VCD_FAILED(rc)) {
(void)vcd_power_event(cctxt->dev_ctxt,
cctxt, VCD_EVT_PWR_CLNT_CMD_FAIL);
}
return rc;
}
void vcd_send_frame_done_in_eos(struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *input_frame, u32 valid_opbuf)
{
VCD_MSG_HIGH("vcd_send_frame_done_in_eos:");
if (!input_frame->virtual && !valid_opbuf) {
VCD_MSG_MED("Sending NULL output with EOS");
cctxt->out_buf_pool.entries[0].frame.flags =
VCD_FRAME_FLAG_EOS;
cctxt->out_buf_pool.entries[0].frame.data_len = 0;
cctxt->out_buf_pool.entries[0].frame.time_stamp =
input_frame->time_stamp;
cctxt->out_buf_pool.entries[0].frame.ip_frm_tag =
input_frame->ip_frm_tag;
cctxt->callback(VCD_EVT_RESP_OUTPUT_DONE,
VCD_S_SUCCESS,
&cctxt->out_buf_pool.entries[0].frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
memset(&cctxt->out_buf_pool.entries[0].frame,
0, sizeof(struct vcd_frame_data));
} else if (!input_frame->data_len) {
if (cctxt->decoding) {
vcd_send_frame_done_in_eos_for_dec(cctxt,
input_frame);
} else {
vcd_send_frame_done_in_eos_for_enc(cctxt,
input_frame);
}
}
}
void vcd_send_frame_done_in_eos_for_dec(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *input_frame)
{
struct vcd_buffer_entry *buf_entry;
struct vcd_property_hdr prop_hdr;
u32 rc;
struct ddl_frame_data_tag ddl_frm;
VCD_MSG_LOW("%s: ", __func__);
prop_hdr.prop_id = DDL_I_DPB_RETRIEVE;
prop_hdr.sz = sizeof(struct ddl_frame_data_tag);
memset(&ddl_frm, 0, sizeof(ddl_frm));
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr, &ddl_frm);
if (VCD_FAILED(rc) || !ddl_frm.vcd_frm.virtual) {
cctxt->status.eos_trig_ip_frm = *input_frame;
cctxt->status.mask |= VCD_EOS_WAIT_OP_BUF;
return;
}
buf_entry = vcd_find_buffer_pool_entry(&cctxt->out_buf_pool,
ddl_frm.vcd_frm.virtual);
if (!buf_entry) {
VCD_MSG_ERROR("Unrecognized buffer address provided = %p",
ddl_frm.vcd_frm.virtual);
return;
} else {
if (cctxt->sched_clnt_hdl->tkns)
cctxt->sched_clnt_hdl->tkns--;
VCD_MSG_MED("Sending non-NULL output with EOS");
buf_entry->frame.data_len = 0;
buf_entry->frame.offset = 0;
buf_entry->frame.flags |= VCD_FRAME_FLAG_EOS;
buf_entry->frame.ip_frm_tag = input_frame->ip_frm_tag;
buf_entry->frame.time_stamp = input_frame->time_stamp;
cctxt->callback(VCD_EVT_RESP_OUTPUT_DONE,
VCD_S_SUCCESS,
&buf_entry->frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
buf_entry->in_use = false;
VCD_BUFFERPOOL_INUSE_DECREMENT(cctxt->out_buf_pool.in_use);
}
}
void vcd_send_frame_done_in_eos_for_enc(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *input_frame)
{
struct vcd_buffer_entry *op_buf_entry;
if (!cctxt->out_buf_pool.q_len) {
cctxt->status.eos_trig_ip_frm = *input_frame;
cctxt->status.mask |= VCD_EOS_WAIT_OP_BUF;
return;
}
op_buf_entry = vcd_buffer_pool_entry_de_q(&cctxt->out_buf_pool);
if (!op_buf_entry) {
VCD_MSG_ERROR("%s(): vcd_buffer_pool_entry_de_q() "
"failed\n", __func__);
} else {
if (cctxt->sched_clnt_hdl->tkns)
cctxt->sched_clnt_hdl->tkns--;
VCD_MSG_MED("Sending non-NULL output with EOS");
op_buf_entry->frame.data_len = 0;
op_buf_entry->frame.flags |= VCD_FRAME_FLAG_EOS;
op_buf_entry->frame.ip_frm_tag =
input_frame->ip_frm_tag;
op_buf_entry->frame.time_stamp = input_frame->time_stamp;
cctxt->callback(VCD_EVT_RESP_OUTPUT_DONE,
VCD_S_SUCCESS,
&op_buf_entry->frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
}
}
struct vcd_transc *vcd_get_first_in_use_trans_for_clnt(
struct vcd_clnt_ctxt *cctxt)
{
u32 i;
struct vcd_dev_ctxt *dev_ctxt;
VCD_MSG_HIGH("%s: ", __func__);
dev_ctxt = cctxt->dev_ctxt;
if (!dev_ctxt->trans_tbl) {
VCD_MSG_ERROR("%s: Null trans_tbl", __func__);
return NULL;
}
i = 0;
while (i < dev_ctxt->trans_tbl_size) {
if ((cctxt == dev_ctxt->trans_tbl[i].cctxt) &&
(dev_ctxt->trans_tbl[i].in_use)) {
VCD_MSG_MED("%s: found transc = 0x%p",
__func__, &dev_ctxt->trans_tbl[i]);
break;
}
i++;
}
if (i == dev_ctxt->trans_tbl_size) {
VCD_MSG_ERROR("%s: in_use transction not found",
__func__);
return NULL;
} else
return &dev_ctxt->trans_tbl[i];
}
u32 vcd_handle_recvd_eos(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *input_frame, u32 *pb_eos_handled)
{
u32 rc;
struct vcd_transc *transc;
VCD_MSG_LOW("vcd_handle_recvd_eos:");
*pb_eos_handled = false;
if (input_frame->virtual &&
input_frame->data_len) {
VCD_MSG_LOW("%s: data available with EOS buffer", __func__);
return VCD_S_SUCCESS;
}
input_frame->data_len = 0;
rc = vcd_sched_mark_client_eof(cctxt->sched_clnt_hdl);
if (VCD_FAILED(rc) && rc != VCD_ERR_QEMPTY) {
VCD_MSG_LOW("%s: rc = %u", __func__, rc);
return rc;
}
if (rc == VCD_S_SUCCESS) {
*pb_eos_handled = true;
VCD_MSG_LOW("%s: EOS handled", __func__);
} else if (cctxt->decoding && !input_frame->virtual) {
cctxt->sched_clnt_hdl->tkns++;
VCD_MSG_LOW("%s: decoding & virtual addr is NULL", __func__);
} else if (!cctxt->decoding && !cctxt->status.frame_delayed) {
if (!cctxt->status.frame_submitted) {
vcd_send_frame_done_in_eos(cctxt, input_frame, false);
if (cctxt->status.mask & VCD_EOS_WAIT_OP_BUF)
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_EOS,
CLIENT_STATE_EVENT_NUMBER
(encode_frame));
} else {
transc = vcd_get_first_in_use_trans_for_clnt(cctxt);
if (transc) {
transc->flags |= VCD_FRAME_FLAG_EOS;
VCD_MSG_HIGH("%s: Add EOS flag to transc",
__func__);
}
}
*pb_eos_handled = true;
}
if (*pb_eos_handled &&
input_frame->virtual &&
!input_frame->data_len) {
VCD_MSG_LOW("%s: sending INPUT_DONE as eos was handled",
__func__);
cctxt->callback(VCD_EVT_RESP_INPUT_DONE,
VCD_S_SUCCESS,
input_frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
}
return VCD_S_SUCCESS;
}
u32 vcd_handle_first_decode_frame(struct vcd_clnt_ctxt *cctxt)
{
u32 rc = VCD_ERR_BAD_STATE;
VCD_MSG_LOW("vcd_handle_first_decode_frame:");
if (!cctxt->in_buf_pool.entries ||
!cctxt->out_buf_pool.entries ||
cctxt->in_buf_pool.validated !=
cctxt->in_buf_pool.count ||
cctxt->out_buf_pool.validated !=
cctxt->out_buf_pool.count)
VCD_MSG_ERROR("Buffer pool is not completely setup yet");
else if (!cctxt->sched_clnt_hdl) {
rc = vcd_sched_add_client(cctxt);
VCD_FAILED_RETURN(rc, "Failed: vcd_add_client_to_sched");
cctxt->sched_clnt_hdl->tkns =
cctxt->out_buf_pool.q_len;
} else
rc = vcd_sched_suspend_resume_clnt(cctxt, true);
return rc;
}
u32 vcd_setup_with_ddl_capabilities(struct vcd_dev_ctxt *dev_ctxt)
{
struct vcd_property_hdr Prop_hdr;
struct ddl_property_capability capability;
u32 rc = VCD_S_SUCCESS;
VCD_MSG_LOW("vcd_setup_with_ddl_capabilities:");
if (!dev_ctxt->ddl_cmd_ch_depth) {
Prop_hdr.prop_id = DDL_I_CAPABILITY;
Prop_hdr.sz = sizeof(capability);
/*
** Since this is underlying core's property we don't need a
** ddl client handle.
*/
rc = ddl_get_property(NULL, &Prop_hdr, &capability);
if (!VCD_FAILED(rc)) {
/*
** Allocate the transaction table.
*/
dev_ctxt->trans_tbl_size =
(VCD_MAX_CLIENT_TRANSACTIONS *
capability.max_num_client) +
capability.general_command_depth;
dev_ctxt->trans_tbl = (struct vcd_transc *)
kzalloc((sizeof(struct vcd_transc) *
dev_ctxt->trans_tbl_size), GFP_KERNEL);
if (!dev_ctxt->trans_tbl) {
VCD_MSG_ERROR("Transaction table alloc failed");
rc = VCD_ERR_ALLOC_FAIL;
} else {
dev_ctxt->ddl_cmd_concurrency =
!capability.exclusive;
dev_ctxt->ddl_frame_ch_depth =
capability.frame_command_depth;
dev_ctxt->ddl_cmd_ch_depth =
capability.general_command_depth;
vcd_reset_device_channels(dev_ctxt);
dev_ctxt->hw_time_out =
capability.ddl_time_out_in_ms;
}
}
}
return rc;
}
struct vcd_transc *vcd_get_free_trans_tbl_entry
(struct vcd_dev_ctxt *dev_ctxt) {
u32 i;
if (!dev_ctxt->trans_tbl)
return NULL;
i = 0;
while (i < dev_ctxt->trans_tbl_size &&
dev_ctxt->trans_tbl[i].in_use)
i++;
if (i == dev_ctxt->trans_tbl_size) {
return NULL;
} else {
memset(&dev_ctxt->trans_tbl[i], 0,
sizeof(struct vcd_transc));
dev_ctxt->trans_tbl[i].in_use = true;
VCD_MSG_LOW("%s: Get transc = 0x%x, in_use = %u\n",
__func__, (u32)(&dev_ctxt->trans_tbl[i]),
dev_ctxt->trans_tbl[i].in_use);
return &dev_ctxt->trans_tbl[i];
}
}
void vcd_release_trans_tbl_entry(struct vcd_transc *trans_entry)
{
if (trans_entry) {
trans_entry->in_use = false;
VCD_MSG_LOW("%s: Free transc = 0x%x, in_use = %u\n",
__func__, (u32)trans_entry, trans_entry->in_use);
}
}
u32 vcd_handle_input_done(
struct vcd_clnt_ctxt *cctxt,
void *payload, u32 event, u32 status)
{
struct vcd_transc *transc;
struct ddl_frame_data_tag *frame =
(struct ddl_frame_data_tag *) payload;
struct vcd_buffer_entry *orig_frame = NULL;
u32 rc;
VCD_MSG_LOW("%s\n", __func__);
if (!cctxt->status.frame_submitted &&
!cctxt->status.frame_delayed) {
VCD_MSG_ERROR("Input done was not expected");
return VCD_ERR_BAD_STATE;
}
rc = vcd_validate_io_done_pyld(cctxt, payload, status);
if (rc == VCD_ERR_CLIENT_FATAL)
vcd_handle_clnt_fatal_input_done(cctxt, frame->frm_trans_end);
VCD_FAILED_RETURN(rc, "Bad input done payload");
transc = (struct vcd_transc *)frame->vcd_frm.ip_frm_tag;
orig_frame = vcd_find_buffer_pool_entry(&cctxt->in_buf_pool,
transc->ip_buf_entry->virtual);
if (!orig_frame) {
rc = VCD_ERR_ILLEGAL_PARM;
VCD_FAILED_RETURN(rc, "Couldn't find buffer");
}
if ((transc->ip_buf_entry->frame.virtual !=
frame->vcd_frm.virtual)
|| !transc->ip_buf_entry->in_use) {
VCD_MSG_ERROR("Bad frm transaction state");
vcd_handle_clnt_fatal_input_done(cctxt, frame->frm_trans_end);
return VCD_ERR_BAD_POINTER;
}
frame->vcd_frm.ip_frm_tag = transc->ip_frm_tag;
transc->frame = frame->vcd_frm.frame;
cctxt->callback(event,
status,
&frame->vcd_frm,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
orig_frame->in_use--;
VCD_BUFFERPOOL_INUSE_DECREMENT(cctxt->in_buf_pool.in_use);
if (cctxt->decoding && orig_frame->in_use) {
VCD_MSG_ERROR("When decoding same input buffer not "
"supposed to be queued multiple times");
return VCD_ERR_FAIL;
}
if (orig_frame != transc->ip_buf_entry) {
VCD_MSG_HIGH("%s: free duplicate buffer", __func__);
kfree(transc->ip_buf_entry);
transc->ip_buf_entry = NULL;
}
transc->ip_buf_entry = NULL;
transc->input_done = true;
if (transc->input_done && transc->frame_done) {
VCD_MSG_LOW("%s Calling vcd_release_trans_tbl_entry\n",
__func__);
vcd_release_trans_tbl_entry(transc);
}
if (VCD_FAILED(status)) {
VCD_MSG_HIGH("INPUT_DONE returned err = 0x%x", status);
vcd_handle_input_done_failed(cctxt, transc);
} else
cctxt->status.mask |= VCD_FIRST_IP_DONE;
if (cctxt->status.frame_submitted > 0)
cctxt->status.frame_submitted--;
else
cctxt->status.frame_delayed--;
if (!VCD_FAILED(status) &&
cctxt->decoding) {
if (frame->vcd_frm.flags & VCD_FRAME_FLAG_CODECCONFIG) {
VCD_MSG_HIGH(
"INPUT_DONE with VCD_FRAME_FLAG_CODECCONFIG");
vcd_handle_input_done_with_codec_config(cctxt,
transc, frame);
frame->vcd_frm.flags &= ~VCD_FRAME_FLAG_CODECCONFIG;
}
if (frame->vcd_frm.interlaced)
vcd_handle_input_done_for_interlacing(cctxt);
if (frame->frm_trans_end)
vcd_handle_input_done_with_trans_end(cctxt);
}
return VCD_S_SUCCESS;
}
u32 vcd_handle_input_done_in_eos(
struct vcd_clnt_ctxt *cctxt, void *payload, u32 status)
{
struct vcd_transc *transc;
struct ddl_frame_data_tag *frame =
(struct ddl_frame_data_tag *) payload;
u32 rc = VCD_ERR_FAIL, codec_config = false;
u32 core_type = res_trk_get_core_type();
VCD_MSG_LOW("%s\n", __func__);
rc = vcd_validate_io_done_pyld(cctxt, payload, status);
if (rc == VCD_ERR_CLIENT_FATAL)
vcd_handle_clnt_fatal_input_done(cctxt, frame->frm_trans_end);
VCD_FAILED_RETURN(rc, "Failed: vcd_validate_io_done_pyld");
transc = (struct vcd_transc *)frame->vcd_frm.ip_frm_tag;
codec_config = frame->vcd_frm.flags & VCD_FRAME_FLAG_CODECCONFIG;
rc = vcd_handle_input_done(cctxt,
payload, VCD_EVT_RESP_INPUT_DONE, status);
VCD_FAILED_RETURN(rc, "Failed: vcd_handle_input_done");
if (frame->vcd_frm.flags & VCD_FRAME_FLAG_EOS) {
VCD_MSG_HIGH("Got input done for EOS initiator");
transc->input_done = false;
transc->in_use = true;
if ((codec_config &&
(status != VCD_ERR_BITSTREAM_ERR)) ||
(codec_config && (status == VCD_ERR_BITSTREAM_ERR) &&
!(cctxt->status.mask & VCD_FIRST_IP_DONE) &&
(core_type == VCD_CORE_720P))) {
VCD_MSG_HIGH("handle EOS for codec config");
vcd_handle_eos_done(cctxt, transc, VCD_S_SUCCESS);
}
}
return rc;
}
u32 vcd_validate_io_done_pyld(
struct vcd_clnt_ctxt *cctxt, void *payload, u32 status)
{
struct ddl_frame_data_tag *frame =
(struct ddl_frame_data_tag *) payload;
struct vcd_dev_ctxt *dev_ctxt = cctxt->dev_ctxt;
struct vcd_transc *transc = NULL;
u32 rc = VCD_S_SUCCESS, i = 0;
if (!frame) {
VCD_MSG_ERROR("Bad payload from DDL");
return VCD_ERR_BAD_POINTER;
}
transc = (struct vcd_transc *)frame->vcd_frm.ip_frm_tag;
if (dev_ctxt->trans_tbl) {
while (i < dev_ctxt->trans_tbl_size &&
transc != &dev_ctxt->trans_tbl[i])
i++;
if (i == dev_ctxt->trans_tbl_size ||
!dev_ctxt->trans_tbl[i].in_use)
rc = VCD_ERR_CLIENT_FATAL;
} else
rc = VCD_ERR_CLIENT_FATAL;
if (VCD_FAILED(rc)) {
VCD_MSG_FATAL("vcd_validate_io_done_pyld: "\
"invalid transaction 0x%x", (u32)transc);
} else if (!frame->vcd_frm.virtual &&
status != VCD_ERR_INTRLCD_FIELD_DROP)
rc = VCD_ERR_BAD_POINTER;
return rc;
}
void vcd_handle_input_done_failed(
struct vcd_clnt_ctxt *cctxt, struct vcd_transc *transc)
{
if (cctxt->decoding) {
cctxt->sched_clnt_hdl->tkns++;
vcd_release_trans_tbl_entry(transc);
}
}
void vcd_handle_input_done_with_codec_config(
struct vcd_clnt_ctxt *cctxt, struct vcd_transc *transc,
struct ddl_frame_data_tag *frm)
{
cctxt->sched_clnt_hdl->tkns++;
if (frm->frm_trans_end)
vcd_release_trans_tbl_entry(transc);
}
void vcd_handle_input_done_for_interlacing(struct vcd_clnt_ctxt *cctxt)
{
cctxt->status.int_field_cnt++;
if (cctxt->status.int_field_cnt == 1)
cctxt->sched_clnt_hdl->tkns++;
else if (cctxt->status.int_field_cnt ==
VCD_DEC_NUM_INTERLACED_FIELDS)
cctxt->status.int_field_cnt = 0;
}
void vcd_handle_input_done_with_trans_end(
struct vcd_clnt_ctxt *cctxt)
{
if (!cctxt->decoding)
return;
if (cctxt->out_buf_pool.in_use <
cctxt->out_buf_pool.buf_req.min_count)
return;
if (!cctxt->sched_clnt_hdl->tkns)
cctxt->sched_clnt_hdl->tkns++;
}
u32 vcd_handle_output_required(struct vcd_clnt_ctxt
*cctxt, void *payload, u32 status)
{
struct vcd_transc *transc;
struct ddl_frame_data_tag *frame =
(struct ddl_frame_data_tag *)payload;
u32 rc = VCD_S_SUCCESS;
VCD_MSG_LOW("%s\n", __func__);
if (!cctxt->status.frame_submitted &&
!cctxt->status.frame_delayed) {
VCD_MSG_ERROR("\n Input done was not expected");
return VCD_ERR_BAD_STATE;
}
rc = vcd_validate_io_done_pyld(cctxt, payload, status);
if (rc == VCD_ERR_CLIENT_FATAL)
vcd_handle_clnt_fatal_input_done(cctxt, frame->frm_trans_end);
VCD_FAILED_RETURN(rc, "\n Bad input done payload");
transc = (struct vcd_transc *)frame->
vcd_frm.ip_frm_tag;
if ((transc->ip_buf_entry->frame.virtual !=
frame->vcd_frm.virtual) ||
!transc->ip_buf_entry->in_use) {
VCD_MSG_ERROR("\n Bad frm transaction state");
vcd_handle_clnt_fatal_input_done(cctxt, frame->frm_trans_end);
return VCD_ERR_BAD_STATE;
}
rc = vcd_sched_queue_buffer(cctxt->sched_clnt_hdl,
transc->ip_buf_entry, false);
VCD_FAILED_RETURN(rc, "Failed: vcd_sched_queue_buffer");
transc->ip_buf_entry = NULL;
vcd_release_trans_tbl_entry(transc);
frame->frm_trans_end = true;
if (VCD_FAILED(status))
VCD_MSG_ERROR("\n OUTPUT_REQ returned err = 0x%x",
status);
if (cctxt->status.frame_submitted > 0)
cctxt->status.frame_submitted--;
else
cctxt->status.frame_delayed--;
if (!VCD_FAILED(status) &&
cctxt->decoding &&
frame->vcd_frm.interlaced) {
if (cctxt->status.int_field_cnt > 0) {
VCD_MSG_ERROR("\n Not expected: OUTPUT_REQ"
"for 2nd interlace field");
rc = VCD_ERR_FAIL;
}
}
return rc;
}
u32 vcd_handle_output_required_in_flushing(
struct vcd_clnt_ctxt *cctxt, void *payload)
{
u32 rc;
struct vcd_transc *transc;
struct ddl_frame_data_tag *frame =
(struct ddl_frame_data_tag *)payload;
VCD_MSG_LOW("%s\n", __func__);
rc = vcd_validate_io_done_pyld(cctxt, payload, VCD_S_SUCCESS);
if (rc == VCD_ERR_CLIENT_FATAL)
vcd_handle_clnt_fatal_input_done(cctxt, frame->frm_trans_end);
VCD_FAILED_RETURN(rc, "Bad input done payload");
transc = (struct vcd_transc *)
(((struct ddl_frame_data_tag *)payload)->
vcd_frm.ip_frm_tag);
((struct ddl_frame_data_tag *)payload)->
vcd_frm.interlaced = false;
rc = vcd_handle_input_done(cctxt, payload,
VCD_EVT_RESP_INPUT_FLUSHED, VCD_S_SUCCESS);
VCD_FAILED_RETURN(rc, "Failed: vcd_handle_input_done");
vcd_release_trans_tbl_entry(transc);
((struct ddl_frame_data_tag *)payload)->frm_trans_end = true;
return rc;
}
u32 vcd_handle_frame_done(
struct vcd_clnt_ctxt *cctxt,
void *payload, u32 event, u32 status)
{
struct vcd_buffer_entry *op_buf_entry = NULL;
struct ddl_frame_data_tag *op_frm =
(struct ddl_frame_data_tag *) payload;
struct vcd_transc *transc;
u32 rc;
s64 time_stamp;
VCD_MSG_LOW("%s\n", __func__);
rc = vcd_validate_io_done_pyld(cctxt, payload, status);
if (rc == VCD_ERR_CLIENT_FATAL)
vcd_handle_clnt_fatal(cctxt, op_frm->frm_trans_end);
VCD_FAILED_RETURN(rc, "Bad payload recvd");
transc = (struct vcd_transc *)op_frm->vcd_frm.ip_frm_tag;
if (op_frm->vcd_frm.virtual) {
if (!transc->op_buf_entry) {
op_buf_entry =
vcd_find_buffer_pool_entry(
&cctxt->out_buf_pool,
op_frm->vcd_frm.
virtual);
} else {
op_buf_entry = transc->op_buf_entry;
}
if (!op_buf_entry) {
VCD_MSG_ERROR("Invalid output buffer returned"
"from DDL");
vcd_handle_clnt_fatal(cctxt, op_frm->frm_trans_end);
rc = VCD_ERR_BAD_POINTER;
} else if (!op_buf_entry->in_use) {
VCD_MSG_ERROR("Bad output buffer 0x%p recvd from DDL",
op_buf_entry->frame.virtual);
vcd_handle_clnt_fatal(cctxt, op_frm->frm_trans_end);
rc = VCD_ERR_BAD_POINTER;
} else {
op_buf_entry->in_use = false;
VCD_BUFFERPOOL_INUSE_DECREMENT(
cctxt->out_buf_pool.in_use);
VCD_MSG_LOW("outBufPool.InUse = %d",
cctxt->out_buf_pool.in_use);
}
}
VCD_FAILED_RETURN(rc, "Bad output buffer pointer");
op_frm->vcd_frm.time_stamp = transc->time_stamp;
op_frm->vcd_frm.ip_frm_tag = transc->ip_frm_tag;
if (!(op_frm->vcd_frm.flags & VCD_FRAME_FLAG_EOSEQ)) {
if (transc->flags & VCD_FRAME_FLAG_EOSEQ)
op_frm->vcd_frm.flags |= VCD_FRAME_FLAG_EOSEQ;
else
op_frm->vcd_frm.flags &= ~VCD_FRAME_FLAG_EOSEQ;
}
if (cctxt->decoding)
op_frm->vcd_frm.frame = transc->frame;
else {
transc->frame = op_frm->vcd_frm.frame;
if ((transc->flags & VCD_FRAME_FLAG_EOS) &&
!(op_frm->vcd_frm.flags & VCD_FRAME_FLAG_EOS)) {
op_frm->vcd_frm.flags |= VCD_FRAME_FLAG_EOS;
VCD_MSG_HIGH("%s: add EOS flag to the output "\
"from transc(0x%x)",
__func__, (u32)transc);
}
}
transc->frame_done = true;
if (transc->input_done && transc->frame_done) {
time_stamp = transc->time_stamp;
vcd_release_trans_tbl_entry(transc);
}
if (status == VCD_ERR_INTRLCD_FIELD_DROP ||
(op_frm->vcd_frm.intrlcd_ip_frm_tag !=
VCD_FRAMETAG_INVALID &&
op_frm->vcd_frm.intrlcd_ip_frm_tag)) {
vcd_handle_frame_done_for_interlacing(cctxt, transc,
op_frm, status);
if (status == VCD_ERR_INTRLCD_FIELD_DROP) {
cctxt->callback(VCD_EVT_IND_INFO_FIELD_DROPPED,
VCD_S_SUCCESS,
&time_stamp,
sizeof(time_stamp),
cctxt, cctxt->client_data);
}
}
if (status != VCD_ERR_INTRLCD_FIELD_DROP) {
cctxt->callback(event,
status,
&op_frm->vcd_frm,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
}
return rc;
}
u32 vcd_handle_frame_done_in_eos(
struct vcd_clnt_ctxt *cctxt, void *payload, u32 status)
{
struct ddl_frame_data_tag *frame =
(struct ddl_frame_data_tag *) payload;
u32 rc = VCD_S_SUCCESS;
VCD_MSG_LOW("%s\n", __func__);
rc = vcd_validate_io_done_pyld(cctxt, payload, status);
if (rc == VCD_ERR_CLIENT_FATAL)
vcd_handle_clnt_fatal(cctxt, frame->frm_trans_end);
VCD_FAILED_RETURN(rc, "Bad payload received");
if (cctxt->status.mask & VCD_EOS_PREV_VALID) {
rc = vcd_handle_frame_done(cctxt,
(void *)&cctxt->status.
eos_prev_op_frm,
VCD_EVT_RESP_OUTPUT_DONE,
cctxt->status.eos_prev_op_frm_status);
VCD_FAILED_RETURN(rc, "Failed: vcd_handle_frame_done");
}
cctxt->status.eos_prev_op_frm = *frame;
cctxt->status.eos_prev_op_frm_status = status;
cctxt->status.mask |= VCD_EOS_PREV_VALID;
return rc;
}
void vcd_handle_frame_done_for_interlacing(
struct vcd_clnt_ctxt *cctxt,
struct vcd_transc *transc_ip1,
struct ddl_frame_data_tag *op_frm, u32 status)
{
struct vcd_transc *transc_ip2 =
(struct vcd_transc *)op_frm->\
vcd_frm.intrlcd_ip_frm_tag;
if (status == VCD_ERR_INTRLCD_FIELD_DROP) {
cctxt->status.int_field_cnt = 0;
return;
}
op_frm->vcd_frm.intrlcd_ip_frm_tag = transc_ip2->ip_frm_tag;
transc_ip2->frame_done = true;
if (transc_ip2->input_done && transc_ip2->frame_done)
vcd_release_trans_tbl_entry(transc_ip2);
if (!transc_ip1->frame || !transc_ip2->frame) {
VCD_MSG_ERROR("DDL didn't provided frame type");
return;
}
}
u32 vcd_handle_first_fill_output_buffer(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *buffer,
u32 *handled)
{
u32 rc = VCD_S_SUCCESS;
rc = vcd_check_if_buffer_req_met(cctxt, VCD_BUFFER_OUTPUT);
VCD_FAILED_RETURN(rc, "Output buffer requirements not met");
if (cctxt->out_buf_pool.q_len > 0) {
VCD_MSG_ERROR("Old output buffers were not flushed out");
return VCD_ERR_BAD_STATE;
}
cctxt->status.mask |= VCD_FIRST_OP_RCVD;
if (cctxt->sched_clnt_hdl)
rc = vcd_sched_suspend_resume_clnt(cctxt, true);
VCD_FAILED_RETURN(rc, "Failed: vcd_sched_suspend_resume_clnt");
if (cctxt->decoding)
rc = vcd_handle_first_fill_output_buffer_for_dec(
cctxt, buffer, handled);
else
rc = vcd_handle_first_fill_output_buffer_for_enc(
cctxt, buffer, handled);
return rc;
}
u32 vcd_handle_first_fill_output_buffer_for_enc(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *frm_entry,
u32 *handled)
{
u32 rc, seqhdr_present = 0;
struct vcd_property_hdr prop_hdr;
struct vcd_sequence_hdr seq_hdr;
struct vcd_property_sps_pps_for_idr_enable idr_enable;
struct vcd_property_codec codec;
u8 *kernel_vaddr = NULL;
*handled = true;
prop_hdr.prop_id = DDL_I_SEQHDR_PRESENT;
prop_hdr.sz = sizeof(seqhdr_present);
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr, &seqhdr_present);
VCD_FAILED_RETURN(rc, "Failed: DDL_I_SEQHDR_PRESENT");
if (!seqhdr_present) {
*handled = false;
return VCD_S_SUCCESS;
}
prop_hdr.prop_id = VCD_I_CODEC;
prop_hdr.sz = sizeof(struct vcd_property_codec);
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr, &codec);
if (!VCD_FAILED(rc)) {
if (codec.codec != VCD_CODEC_H263) {
/*
* The seq. header is stored in a seperate internal
* buffer and is memcopied into the output buffer
* that we provide. In secure sessions, we aren't
* allowed to touch these buffers. In these cases
* seq. headers are returned to client as part of
* I-frames. So for secure session, just return
* empty buffer.
*/
if (!cctxt->secure) {
prop_hdr.prop_id = VCD_I_SEQ_HEADER;
prop_hdr.sz = sizeof(struct vcd_sequence_hdr);
if (vcd_get_ion_status()) {
kernel_vaddr = (u8 *)ion_map_kernel(
cctxt->vcd_ion_client,
frm_entry->buff_ion_handle);
if (IS_ERR_OR_NULL(kernel_vaddr)) {
VCD_MSG_ERROR("%s: 0x%x = "\
"ion_map_kernel(0x%x, 0x%x) fail",
__func__,
(u32)kernel_vaddr,
(u32)cctxt->vcd_ion_client,
(u32)frm_entry->
buff_ion_handle);
return VCD_ERR_FAIL;
}
} else {
VCD_MSG_ERROR("%s: ION status is NULL",
__func__);
return VCD_ERR_FAIL;
}
seq_hdr.sequence_header = kernel_vaddr;
seq_hdr.sequence_header_len =
frm_entry->alloc_len;
rc = ddl_get_property(cctxt->ddl_handle,
&prop_hdr, &seq_hdr);
if (!VCD_FAILED(rc)) {
frm_entry->data_len =
seq_hdr.sequence_header_len;
frm_entry->time_stamp = 0;
frm_entry->flags |=
VCD_FRAME_FLAG_CODECCONFIG;
VCD_MSG_LOW("%s: header len = %u",
__func__, frm_entry->data_len);
} else
VCD_MSG_ERROR("rc = 0x%x. Failed:"
"ddl_get_property: VCD_I_SEQ_HEADER",
rc);
} else {
/*
* First check that the proper props are enabled
* so client can get the proper info eventually
*/
prop_hdr.prop_id = VCD_I_ENABLE_SPS_PPS_FOR_IDR;
prop_hdr.sz = sizeof(idr_enable);
rc = ddl_get_property(cctxt->ddl_handle,
&prop_hdr, &idr_enable);
if (!VCD_FAILED(rc)) {
if (!idr_enable.
sps_pps_for_idr_enable_flag) {
VCD_MSG_ERROR("SPS/PPS per IDR "
"needs to be enabled");
rc = VCD_ERR_BAD_STATE;
} else {
/* Send zero len frame */
frm_entry->data_len = 0;
frm_entry->time_stamp = 0;
frm_entry->flags = 0;
}
}
}
if (!VCD_FAILED(rc))
cctxt->callback(VCD_EVT_RESP_OUTPUT_DONE,
VCD_S_SUCCESS, frm_entry,
sizeof(struct vcd_frame_data),
cctxt,
cctxt->client_data);
} else
VCD_MSG_LOW("Codec Type is H.263\n");
} else
VCD_MSG_ERROR(
"rc = 0x%x. Failed: ddl_get_property:VCD_I_CODEC",
rc);
if (kernel_vaddr) {
if (!IS_ERR_OR_NULL(frm_entry->buff_ion_handle)) {
ion_map_kernel(cctxt->vcd_ion_client,
frm_entry->buff_ion_handle);
} else {
VCD_MSG_ERROR("%s: Invalid ion_handle (0x%x)",
__func__, (u32)frm_entry->buff_ion_handle);
rc = VCD_ERR_FAIL;
}
}
return rc;
}
u32 vcd_handle_first_fill_output_buffer_for_dec(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *frm_entry,
u32 *handled)
{
u32 rc;
struct vcd_property_hdr prop_hdr;
struct vcd_buffer_pool *out_buf_pool;
struct ddl_property_dec_pic_buffers dpb;
struct ddl_frame_data_tag *dpb_list;
u8 i;
(void)frm_entry;
*handled = true;
prop_hdr.prop_id = DDL_I_DPB;
prop_hdr.sz = sizeof(dpb);
out_buf_pool = &cctxt->out_buf_pool;
dpb_list = (struct ddl_frame_data_tag *)
kmalloc((sizeof(struct ddl_frame_data_tag) *
out_buf_pool->count), GFP_KERNEL);
if (!dpb_list) {
VCD_MSG_ERROR("Memory allocation failure");
return VCD_ERR_ALLOC_FAIL;
}
for (i = 1; i <= out_buf_pool->count; i++)
dpb_list[i - 1].vcd_frm = out_buf_pool->entries[i].frame;
dpb.dec_pic_buffers = dpb_list;
dpb.no_of_dec_pic_buf = out_buf_pool->count;
rc = ddl_set_property(cctxt->ddl_handle, &prop_hdr, &dpb);
kfree(dpb_list);
*handled = false;
return VCD_S_SUCCESS;
}
void vcd_handle_eos_trans_end(struct vcd_clnt_ctxt *cctxt)
{
u32 rc = VCD_S_SUCCESS;
if (cctxt->status.mask & VCD_EOS_PREV_VALID) {
rc = vcd_handle_frame_done(cctxt,
(void *)&cctxt->status.eos_prev_op_frm,
VCD_EVT_RESP_OUTPUT_DONE,
cctxt->status.eos_prev_op_frm_status);
cctxt->status.mask &= ~VCD_EOS_PREV_VALID;
}
if (VCD_FAILED(rc))
return;
if (cctxt->status.mask & VCD_FLUSH_ALL)
vcd_process_pending_flush_in_eos(cctxt);
if (cctxt->status.mask & VCD_STOP_PENDING)
vcd_process_pending_stop_in_eos(cctxt);
else {
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_RUN,
CLIENT_STATE_EVENT_NUMBER(clnt_cb));
}
}
void vcd_handle_eos_done(struct vcd_clnt_ctxt *cctxt,
struct vcd_transc *transc, u32 status)
{
struct vcd_frame_data vcd_frm;
u32 rc = VCD_S_SUCCESS, sent_eos_frm = false;
VCD_MSG_LOW("vcd_handle_eos_done:");
if (VCD_FAILED(status))
VCD_MSG_ERROR("EOS DONE returned error = 0x%x", status);
if (cctxt->status.mask & VCD_EOS_PREV_VALID) {
cctxt->status.eos_prev_op_frm.vcd_frm.flags |=
VCD_FRAME_FLAG_EOS;
rc = vcd_handle_frame_done(cctxt,
(void *)&cctxt->status.
eos_prev_op_frm,
VCD_EVT_RESP_OUTPUT_DONE,
cctxt->status.
eos_prev_op_frm_status);
cctxt->status.mask &= ~VCD_EOS_PREV_VALID;
if (!VCD_FAILED(rc) &&
cctxt->status.eos_prev_op_frm_status !=
VCD_ERR_INTRLCD_FIELD_DROP)
sent_eos_frm = true;
}
if (!sent_eos_frm) {
if (transc->ip_buf_entry) {
transc->ip_buf_entry->frame.ip_frm_tag =
transc->ip_frm_tag;
vcd_send_frame_done_in_eos(cctxt,
&transc->ip_buf_entry->frame, false);
} else {
memset(&vcd_frm, 0, sizeof(struct vcd_frame_data));
vcd_frm.ip_frm_tag = transc->ip_frm_tag;
vcd_frm.time_stamp = transc->time_stamp;
vcd_frm.flags = VCD_FRAME_FLAG_EOS;
vcd_send_frame_done_in_eos(cctxt, &vcd_frm, true);
}
}
if (VCD_FAILED(rc))
return;
if (transc->ip_buf_entry) {
if (transc->ip_buf_entry->frame.virtual) {
transc->ip_buf_entry->frame.ip_frm_tag =
transc->ip_frm_tag;
cctxt->callback(VCD_EVT_RESP_INPUT_DONE,
VCD_S_SUCCESS,
&transc->ip_buf_entry->frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
}
transc->ip_buf_entry->in_use = false;
VCD_BUFFERPOOL_INUSE_DECREMENT(cctxt->in_buf_pool.in_use);
transc->ip_buf_entry = NULL;
if (cctxt->status.frame_submitted)
cctxt->status.frame_submitted--;
else
cctxt->status.frame_delayed--;
}
vcd_release_trans_tbl_entry(transc);
if (cctxt->status.mask & VCD_FLUSH_ALL)
vcd_process_pending_flush_in_eos(cctxt);
if (cctxt->status.mask & VCD_STOP_PENDING) {
vcd_process_pending_stop_in_eos(cctxt);
} else if (!(cctxt->status.mask & VCD_EOS_WAIT_OP_BUF)) {
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_RUN,
CLIENT_STATE_EVENT_NUMBER
(clnt_cb));
}
}
void vcd_handle_start_done(struct vcd_clnt_ctxt *cctxt,
struct vcd_transc *transc, u32 status)
{
cctxt->status.cmd_submitted--;
vcd_mark_command_channel(cctxt->dev_ctxt, transc);
if (!VCD_FAILED(status)) {
cctxt->callback(VCD_EVT_RESP_START, status, NULL,
0, cctxt, cctxt->client_data);
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_RUN,
CLIENT_STATE_EVENT_NUMBER(clnt_cb));
} else {
VCD_MSG_ERROR("ddl callback returned failure."
"status = 0x%x", status);
vcd_handle_err_in_starting(cctxt, status);
}
}
void vcd_handle_stop_done(struct vcd_clnt_ctxt *cctxt,
struct vcd_transc *transc, u32 status)
{
VCD_MSG_LOW("vcd_handle_stop_done:");
cctxt->status.cmd_submitted--;
vcd_mark_command_channel(cctxt->dev_ctxt, transc);
if (!VCD_FAILED(status)) {
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_OPEN,
CLIENT_STATE_EVENT_NUMBER(clnt_cb));
} else {
VCD_MSG_FATAL("STOP_DONE returned error = 0x%x", status);
status = VCD_ERR_HW_FATAL;
vcd_handle_device_err_fatal(cctxt->dev_ctxt, cctxt);
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_INVALID,
CLIENT_STATE_EVENT_NUMBER(clnt_cb));
}
cctxt->callback(VCD_EVT_RESP_STOP, status, NULL, 0, cctxt,
cctxt->client_data);
memset(&cctxt->status, 0, sizeof(struct vcd_clnt_status));
}
void vcd_handle_stop_done_in_starting(struct vcd_clnt_ctxt
*cctxt, struct vcd_transc *transc, u32 status)
{
VCD_MSG_LOW("vcd_handle_stop_done_in_starting:");
cctxt->status.cmd_submitted--;
vcd_mark_command_channel(cctxt->dev_ctxt, transc);
if (!VCD_FAILED(status)) {
cctxt->callback(VCD_EVT_RESP_START, cctxt->status.
last_err, NULL, 0, cctxt, cctxt->client_data);
vcd_do_client_state_transition(cctxt, VCD_CLIENT_STATE_OPEN,
CLIENT_STATE_EVENT_NUMBER(clnt_cb));
} else {
VCD_MSG_FATAL("VCD Cleanup: STOP_DONE returned error "
"= 0x%x", status);
vcd_handle_err_fatal(cctxt, VCD_EVT_RESP_START,
VCD_ERR_HW_FATAL);
}
}
void vcd_handle_stop_done_in_invalid(struct vcd_clnt_ctxt *cctxt,
struct vcd_transc *transc, u32 status)
{
u32 rc;
VCD_MSG_LOW("vcd_handle_stop_done_in_invalid:");
cctxt->status.cmd_submitted--;
vcd_mark_command_channel(cctxt->dev_ctxt, transc);
if (!VCD_FAILED(status)) {
vcd_client_cmd_flush_and_en_q(cctxt, VCD_CMD_CLIENT_CLOSE);
if (cctxt->status.frame_submitted) {
vcd_release_multiple_frame_channels(cctxt->dev_ctxt,
cctxt->status.frame_submitted);
cctxt->status.frame_submitted = 0;
cctxt->status.frame_delayed = 0;
}
if (cctxt->status.cmd_submitted) {
vcd_release_multiple_command_channels(
cctxt->dev_ctxt,
cctxt->status.cmd_submitted);
cctxt->status.cmd_submitted = 0;
}
} else {
VCD_MSG_FATAL("VCD Cleanup: STOP_DONE returned error "
"= 0x%x", status);
vcd_handle_device_err_fatal(cctxt->dev_ctxt, cctxt);
cctxt->status.mask &= ~VCD_CLEANING_UP;
}
vcd_flush_buffers_in_err_fatal(cctxt);
VCD_MSG_HIGH("VCD cleanup: All buffers are returned");
if (cctxt->status.mask & VCD_STOP_PENDING) {
cctxt->callback(VCD_EVT_RESP_STOP, VCD_S_SUCCESS, NULL, 0,
cctxt, cctxt->client_data);
cctxt->status.mask &= ~VCD_STOP_PENDING;
}
rc = vcd_power_event(cctxt->dev_ctxt, cctxt,
VCD_EVT_PWR_CLNT_ERRFATAL);
if (VCD_FAILED(rc))
VCD_MSG_ERROR("VCD_EVT_PWR_CLNT_ERRFATAL failed");
if (!(cctxt->status.mask & VCD_CLEANING_UP) &&
cctxt->status.mask & VCD_CLOSE_PENDING) {
vcd_destroy_client_context(cctxt);
vcd_handle_for_last_clnt_close(cctxt->dev_ctxt, false);
}
}
u32 vcd_handle_input_frame(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *input_frame)
{
struct vcd_dev_ctxt *dev_ctxt = cctxt->dev_ctxt;
struct vcd_buffer_entry *buf_entry, *orig_frame;
struct vcd_frame_data *frm_entry;
u32 rc = VCD_S_SUCCESS;
u32 eos_handled = false;
u32 duplicate_buffer = false;
VCD_MSG_LOW("vcd_handle_input_frame:");
VCD_MSG_LOW("input buffer: addr=(0x%p), sz=(%d), len=(%d)",
input_frame->virtual, input_frame->alloc_len,
input_frame->data_len);
if (!input_frame->virtual &&
!(input_frame->flags & VCD_FRAME_FLAG_EOS)) {
VCD_MSG_ERROR("Bad frame ptr/len/EOS combination");
return VCD_ERR_ILLEGAL_PARM;
}
if (!input_frame->data_len &&
!(input_frame->flags & VCD_FRAME_FLAG_EOS)) {
VCD_MSG_MED("data_len = 0, returning INPUT DONE");
cctxt->callback(VCD_EVT_RESP_INPUT_DONE,
VCD_ERR_INPUT_NOT_PROCESSED,
input_frame,
sizeof(struct vcd_frame_data),
cctxt, cctxt->client_data);
return VCD_S_SUCCESS;
}
if (!(cctxt->status.mask & VCD_FIRST_IP_RCVD)) {
if (cctxt->decoding)
rc = vcd_handle_first_decode_frame(cctxt);
if (!VCD_FAILED(rc)) {
cctxt->status.first_ts = input_frame->time_stamp;
cctxt->status.prev_ts = cctxt->status.first_ts;
cctxt->status.mask |= VCD_FIRST_IP_RCVD;
(void)vcd_power_event(cctxt->dev_ctxt,
cctxt,
VCD_EVT_PWR_CLNT_FIRST_FRAME);
}
}
VCD_FAILED_RETURN(rc, "Failed: First frame handling");
orig_frame = vcd_find_buffer_pool_entry(&cctxt->in_buf_pool,
input_frame->virtual);
if (!orig_frame) {
VCD_MSG_ERROR("Bad buffer addr: %p", input_frame->virtual);
return VCD_ERR_FAIL;
}
if (orig_frame->in_use) {
/*
* This path only allowed for enc., dec. not allowed
* to queue same buffer multiple times
*/
if (cctxt->decoding) {
VCD_MSG_ERROR("An inuse input frame is being "
"re-queued to scheduler");
return VCD_ERR_FAIL;
}
buf_entry = kzalloc(sizeof(*buf_entry), GFP_KERNEL);
if (!buf_entry) {
VCD_MSG_ERROR("Unable to alloc memory");
return VCD_ERR_FAIL;
}
INIT_LIST_HEAD(&buf_entry->sched_list);
/*
* Pre-emptively poisoning this, as these dupe entries
* shouldn't get added to any list
*/
INIT_LIST_HEAD(&buf_entry->list);
buf_entry->list.next = LIST_POISON1;
buf_entry->list.prev = LIST_POISON2;
buf_entry->valid = orig_frame->valid;
buf_entry->alloc = orig_frame->alloc;
buf_entry->virtual = orig_frame->virtual;
buf_entry->physical = orig_frame->physical;
buf_entry->sz = orig_frame->sz;
buf_entry->allocated = orig_frame->allocated;
buf_entry->in_use = 1; /* meaningless for the dupe buffers */
buf_entry->frame = orig_frame->frame;
duplicate_buffer = true;
VCD_MSG_HIGH("%s: duplicate buffer", __func__);
} else
buf_entry = orig_frame;
if (input_frame->alloc_len > buf_entry->sz) {
VCD_MSG_ERROR("Bad buffer Alloc_len %d, Actual sz=%d",
input_frame->alloc_len, buf_entry->sz);
return VCD_ERR_ILLEGAL_PARM;
}
frm_entry = &buf_entry->frame;
*frm_entry = *input_frame;
frm_entry->physical = buf_entry->physical;
if (input_frame->flags & VCD_FRAME_FLAG_EOS) {
rc = vcd_handle_recvd_eos(cctxt, input_frame,
&eos_handled);
}
if (VCD_FAILED(rc) || eos_handled) {
VCD_MSG_HIGH("rc = 0x%x, eos_handled = %d", rc,
eos_handled);
if ((duplicate_buffer) && (buf_entry)) {
kfree(buf_entry);
buf_entry = NULL;
}
return rc;
}
rc = vcd_sched_queue_buffer(
cctxt->sched_clnt_hdl, buf_entry, true);
VCD_FAILED_RETURN(rc, "Failed: vcd_sched_queue_buffer");
orig_frame->in_use++;
cctxt->in_buf_pool.in_use++;
vcd_try_submit_frame(dev_ctxt);
return rc;
}
void vcd_release_all_clnt_frm_transc(struct vcd_clnt_ctxt *cctxt)
{
struct vcd_dev_ctxt *dev_ctxt = cctxt->dev_ctxt;
u32 i, cntr = 0;
VCD_MSG_LOW("vcd_release_all_clnt_frm_transc:");
for (i = 0; i < dev_ctxt->trans_tbl_size; i++) {
if (dev_ctxt->trans_tbl[i].in_use &&
cctxt == dev_ctxt->trans_tbl[i].cctxt) {
if (dev_ctxt->trans_tbl[i].
type == VCD_CMD_CODE_FRAME ||
dev_ctxt->trans_tbl[i].
type == VCD_CMD_NONE) {
vcd_release_trans_tbl_entry(&dev_ctxt->
trans_tbl[i]);
} else {
VCD_MSG_LOW("vcd_transaction in use type(%u)",
dev_ctxt->trans_tbl[i].type);
cntr++;
}
}
}
if (cntr)
VCD_MSG_ERROR("vcd_transactions still in use: (%d)", cntr);
}
void vcd_release_all_clnt_transc(struct vcd_clnt_ctxt *cctxt)
{
struct vcd_dev_ctxt *dev_ctxt = cctxt->dev_ctxt;
u32 i;
VCD_MSG_LOW("vcd_release_all_clnt_transc:");
for (i = 0; i < dev_ctxt->trans_tbl_size; i++) {
if (dev_ctxt->trans_tbl[i].in_use &&
cctxt == dev_ctxt->trans_tbl[i].cctxt) {
vcd_release_trans_tbl_entry(
&dev_ctxt->trans_tbl[i]);
}
}
}
void vcd_send_flush_done(struct vcd_clnt_ctxt *cctxt, u32 status)
{
VCD_MSG_LOW("vcd_send_flush_done:");
if (cctxt->status.mask & VCD_FLUSH_INPUT) {
cctxt->callback(VCD_EVT_RESP_FLUSH_INPUT_DONE,
status, NULL, 0, cctxt, cctxt->client_data);
cctxt->status.mask &= ~VCD_FLUSH_INPUT;
}
if (cctxt->status.mask & VCD_FLUSH_OUTPUT) {
cctxt->callback(VCD_EVT_RESP_FLUSH_OUTPUT_DONE,
status, NULL, 0, cctxt, cctxt->client_data);
cctxt->status.mask &= ~VCD_FLUSH_OUTPUT;
}
}
u32 vcd_store_seq_hdr(
struct vcd_clnt_ctxt *cctxt,
struct vcd_sequence_hdr *seq_hdr)
{
u32 rc;
struct vcd_property_hdr prop_hdr;
u32 align;
u8 *virtual_aligned;
u32 addr;
int ret = 0;
if (!seq_hdr->sequence_header_len
|| !seq_hdr->sequence_header) {
VCD_MSG_ERROR("Bad seq hdr");
return VCD_ERR_BAD_POINTER;
}
if (cctxt->seq_hdr.sequence_header) {
VCD_MSG_HIGH("Old seq hdr detected");
vcd_pmem_free(cctxt->seq_hdr.sequence_header,
cctxt->seq_hdr_phy_addr, cctxt);
cctxt->seq_hdr.sequence_header = NULL;
}
cctxt->seq_hdr.sequence_header_len =
seq_hdr->sequence_header_len;
prop_hdr.prop_id = DDL_I_SEQHDR_ALIGN_BYTES;
prop_hdr.sz = sizeof(u32);
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr, &align);
VCD_FAILED_RETURN(rc,
"Failed: ddl_get_property DDL_I_SEQHDR_ALIGN_BYTES");
VCD_MSG_MED("Seq hdr alignment bytes = %d", align);
ret = vcd_pmem_alloc(cctxt->seq_hdr.sequence_header_len + align +
VCD_SEQ_HDR_PADDING_BYTES,
&(cctxt->seq_hdr.sequence_header),
&(cctxt->seq_hdr_phy_addr), cctxt);
if (ret < 0) {
VCD_MSG_ERROR("Seq hdr allocation failed");
return VCD_ERR_ALLOC_FAIL;
}
if (!cctxt->seq_hdr_phy_addr) {
VCD_MSG_ERROR("Couldn't get physical address");
return VCD_ERR_BAD_POINTER;
}
if (align > 0) {
addr = (u32) cctxt->seq_hdr_phy_addr;
addr += align;
addr -= (addr % align);
virtual_aligned = cctxt->seq_hdr.sequence_header;
virtual_aligned += (u32) (addr -
(u32) cctxt->seq_hdr_phy_addr);
cctxt->seq_hdr_phy_addr = (u8 *) addr;
} else {
virtual_aligned = cctxt->seq_hdr.sequence_header;
}
memcpy(virtual_aligned, seq_hdr->sequence_header,
seq_hdr->sequence_header_len);
return VCD_S_SUCCESS;
}
u32 vcd_set_frame_rate(
struct vcd_clnt_ctxt *cctxt,
struct vcd_property_frame_rate *fps)
{
u32 rc;
cctxt->frm_rate = *fps;
rc = vcd_update_clnt_perf_lvl(cctxt, &cctxt->frm_rate,
cctxt->frm_p_units);
if (VCD_FAILED(rc)) {
VCD_MSG_ERROR("rc = 0x%x. Failed: vcd_update_clnt_perf_lvl",
rc);
}
rc = vcd_sched_update_config(cctxt);
return rc;
}
u32 vcd_req_perf_level(
struct vcd_clnt_ctxt *cctxt,
struct vcd_property_perf_level *perf_level)
{
u32 rc;
u32 res_trk_perf_level;
u32 turbo_perf_level;
if (!perf_level) {
VCD_MSG_ERROR("Invalid parameters\n");
return -EINVAL;
}
res_trk_perf_level = get_res_trk_perf_level(perf_level->level);
if ((int)res_trk_perf_level < 0) {
rc = -ENOTSUPP;
VCD_MSG_ERROR("%s: unsupported perf level(%d)",
__func__, res_trk_perf_level);
goto perf_level_not_supp;
}
turbo_perf_level = get_res_trk_perf_level(VCD_PERF_LEVEL_TURBO);
rc = vcd_set_perf_level(cctxt->dev_ctxt, res_trk_perf_level);
if (!rc) {
cctxt->reqd_perf_lvl = res_trk_perf_level;
cctxt->perf_set_by_client = 1;
if (res_trk_perf_level == turbo_perf_level)
cctxt->is_turbo_enabled = true;
}
VCD_MSG_HIGH("%s: client perf level = %u, "\
"perf_set_by_client = %u, is_turbo_enabled = %u",
__func__, cctxt->reqd_perf_lvl, cctxt->perf_set_by_client,
cctxt->is_turbo_enabled);
perf_level_not_supp:
return rc;
}
u32 vcd_set_frame_size(
struct vcd_clnt_ctxt *cctxt,
struct vcd_property_frame_size *frm_size)
{
struct vcd_property_hdr prop_hdr;
u32 rc;
u32 frm_p_units;
(void)frm_size;
if (res_trk_get_disable_fullhd() && frm_size &&
(frm_size->width * frm_size->height > 1280 * 720)) {
VCD_MSG_ERROR("Frame size = %dX%d greater than 1280X720 not"
"supported", frm_size->width, frm_size->height);
return VCD_ERR_FAIL;
}
prop_hdr.prop_id = DDL_I_FRAME_PROC_UNITS;
prop_hdr.sz = sizeof(frm_p_units);
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr, &frm_p_units);
VCD_FAILED_RETURN(rc, "Failed: Get DDL_I_FRAME_PROC_UNITS");
cctxt->frm_p_units = frm_p_units;
rc = vcd_update_clnt_perf_lvl(cctxt, &cctxt->frm_rate,
frm_p_units);
if (VCD_FAILED(rc)) {
VCD_MSG_ERROR("rc = 0x%x. Failed: vcd_update_clnt_perf_lvl",
rc);
}
return rc;
}
void vcd_process_pending_flush_in_eos(struct vcd_clnt_ctxt *cctxt)
{
u32 rc = VCD_S_SUCCESS;
VCD_MSG_HIGH("Buffer flush is pending");
rc = vcd_flush_buffers(cctxt, cctxt->status.mask & VCD_FLUSH_ALL);
if (VCD_FAILED(rc))
VCD_MSG_ERROR("rc = 0x%x. Failed: vcd_flush_buffers", rc);
cctxt->status.mask &= ~VCD_EOS_WAIT_OP_BUF;
vcd_send_flush_done(cctxt, VCD_S_SUCCESS);
}
void vcd_process_pending_stop_in_eos(struct vcd_clnt_ctxt *cctxt)
{
u32 rc = VCD_S_SUCCESS;
rc = vcd_flush_buffers(cctxt, VCD_FLUSH_ALL);
if (VCD_FAILED(rc))
VCD_MSG_ERROR("rc = 0x%x. Failed: vcd_flush_buffers", rc);
VCD_MSG_HIGH("All buffers are returned. Enqueuing stop cmd");
vcd_client_cmd_flush_and_en_q(cctxt, VCD_CMD_CODEC_STOP);
cctxt->status.mask &= ~VCD_STOP_PENDING;
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_STOPPING,
CLIENT_STATE_EVENT_NUMBER(stop));
}
u32 vcd_calculate_frame_delta(
struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *frame)
{
u32 frm_delta;
u64 temp, max = ~((u64)0);
if (cctxt->time_frame_delta)
temp = cctxt->time_frame_delta;
else if (frame->time_stamp >= cctxt->status.prev_ts)
temp = frame->time_stamp - cctxt->status.prev_ts;
else
temp = (max - cctxt->status.prev_ts) +
frame->time_stamp;
VCD_MSG_LOW("Curr_ts=%lld Prev_ts=%lld Diff=%llu\n",
frame->time_stamp, cctxt->status.prev_ts, temp);
temp *= cctxt->time_resoln;
(void)do_div(temp, VCD_TIMESTAMP_RESOLUTION);
frm_delta = temp;
cctxt->status.time_elapsed += frm_delta;
temp = (cctxt->status.time_elapsed * VCD_TIMESTAMP_RESOLUTION);
(void)do_div(temp, cctxt->time_resoln);
cctxt->status.prev_ts = cctxt->status.first_ts + temp;
VCD_MSG_LOW("Time_elapsed=%llu, Drift=%llu, new Prev_ts=%lld",
cctxt->status.time_elapsed, temp,
cctxt->status.prev_ts);
return frm_delta;
}
struct vcd_buffer_entry *vcd_check_fill_output_buffer
(struct vcd_clnt_ctxt *cctxt,
struct vcd_frame_data *buffer) {
struct vcd_buffer_pool *buf_pool = &cctxt->out_buf_pool;
struct vcd_buffer_entry *buf_entry;
if (!buf_pool->entries) {
VCD_MSG_ERROR("Buffers not set or allocated yet");
return NULL;
}
if (!buffer->virtual) {
VCD_MSG_ERROR("NULL buffer address provided");
return NULL;
}
buf_entry =
vcd_find_buffer_pool_entry(buf_pool, buffer->virtual);
if (!buf_entry) {
VCD_MSG_ERROR("Unrecognized buffer address provided = %p",
buffer->virtual);
return NULL;
}
if (buf_entry->in_use) {
VCD_MSG_ERROR
("An inuse output frame is being provided for reuse");
return NULL;
}
if ((buffer->alloc_len < buf_pool->buf_req.sz ||
buffer->alloc_len > buf_entry->sz) &&
!(cctxt->status.mask & VCD_IN_RECONFIG)) {
VCD_MSG_ERROR
("Bad buffer Alloc_len = %d, Actual sz = %d, "
" Min sz = %u",
buffer->alloc_len, buf_entry->sz,
buf_pool->buf_req.sz);
return NULL;
}
return buf_entry;
}
void vcd_handle_ind_hw_err_fatal(struct vcd_clnt_ctxt *cctxt,
u32 event, u32 status)
{
if (cctxt->status.frame_submitted) {
cctxt->status.frame_submitted--;
vcd_mark_frame_channel(cctxt->dev_ctxt);
}
vcd_handle_err_fatal(cctxt, event, status);
}
void vcd_handle_err_fatal(struct vcd_clnt_ctxt *cctxt, u32 event,
u32 status)
{
VCD_MSG_LOW("vcd_handle_err_fatal: event=%x, err=%x", event, status);
if (!VCD_FAILED_FATAL(status))
return;
if (VCD_FAILED_DEVICE_FATAL(status)) {
vcd_clnt_handle_device_err_fatal(cctxt, event);
vcd_handle_device_err_fatal(cctxt->dev_ctxt, cctxt);
} else if (VCD_FAILED_CLIENT_FATAL(status)) {
cctxt->status.last_evt = event;
cctxt->callback(event, VCD_ERR_HW_FATAL, NULL, 0, cctxt,
cctxt->client_data);
cctxt->status.mask |= VCD_CLEANING_UP;
vcd_client_cmd_flush_and_en_q(cctxt, VCD_CMD_CODEC_STOP);
vcd_do_client_state_transition(cctxt,
VCD_CLIENT_STATE_INVALID,
CLIENT_STATE_EVENT_NUMBER(clnt_cb));
}
}
void vcd_handle_err_in_starting(struct vcd_clnt_ctxt *cctxt,
u32 status)
{
VCD_MSG_LOW("\n vcd_handle_err_in_starting:");
if (VCD_FAILED_FATAL(status)) {
vcd_handle_err_fatal(cctxt, VCD_EVT_RESP_START, status);
} else {
cctxt->status.last_err = status;
VCD_MSG_HIGH("\n VCD cleanup: Enqueuing stop cmd");
vcd_client_cmd_flush_and_en_q(cctxt, VCD_CMD_CODEC_STOP);
}
}
void vcd_handle_trans_pending(struct vcd_clnt_ctxt *cctxt)
{
if (!cctxt->status.frame_submitted) {
VCD_MSG_ERROR("Transaction pending response was not expected");
return;
}
cctxt->status.frame_submitted--;
cctxt->status.frame_delayed++;
vcd_mark_frame_channel(cctxt->dev_ctxt);
}
void vcd_handle_submit_frame_failed(struct vcd_dev_ctxt
*dev_ctxt, struct vcd_transc *transc)
{
struct vcd_clnt_ctxt *cctxt = transc->cctxt;
u32 rc;
vcd_mark_frame_channel(dev_ctxt);
vcd_release_trans_tbl_entry(transc);
vcd_handle_err_fatal(cctxt, VCD_EVT_IND_HWERRFATAL,
VCD_ERR_CLIENT_FATAL);
if (vcd_get_command_channel(dev_ctxt, &transc)) {
transc->type = VCD_CMD_CODEC_STOP;
transc->cctxt = cctxt;
rc = vcd_submit_cmd_sess_end(transc);
if (VCD_FAILED(rc)) {
vcd_release_command_channel(dev_ctxt, transc);
VCD_MSG_ERROR("rc = 0x%x. Failed: VCD_SubmitCmdSessEnd",
rc);
}
}
}
u32 vcd_check_if_buffer_req_met(struct vcd_clnt_ctxt *cctxt,
enum vcd_buffer_type buffer)
{
struct vcd_property_hdr prop_hdr;
struct vcd_buffer_pool *buf_pool;
struct vcd_buffer_requirement buf_req;
u32 rc;
u8 i;
if (buffer == VCD_BUFFER_INPUT) {
prop_hdr.prop_id = DDL_I_INPUT_BUF_REQ;
buf_pool = &cctxt->in_buf_pool;
} else {
prop_hdr.prop_id = DDL_I_OUTPUT_BUF_REQ;
buf_pool = &cctxt->out_buf_pool;
}
prop_hdr.sz = sizeof(buf_req);
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr, &buf_req);
VCD_FAILED_RETURN(rc, "Failed: ddl_GetProperty");
buf_pool->buf_req = buf_req;
if (buf_pool->count < buf_req.actual_count) {
VCD_MSG_ERROR("Buf requirement count not met");
return VCD_ERR_FAIL;
}
if (buf_pool->count > buf_req.actual_count)
buf_pool->count = buf_req.actual_count;
if (!buf_pool->entries ||
buf_pool->validated != buf_pool->count) {
VCD_MSG_ERROR("Buffer pool is not completely setup yet");
return VCD_ERR_BAD_STATE;
}
for (i = 1; (rc == VCD_S_SUCCESS && i <= buf_pool->count); i++) {
if (buf_pool->entries[i].sz <
buf_pool->buf_req.sz) {
VCD_MSG_ERROR(
"BufReq sz not met:\
addr=(0x%p) sz=%d ReqSize=%d",
buf_pool->entries[i].virtual,
buf_pool->entries[i].sz,
buf_pool->buf_req.sz);
rc = VCD_ERR_FAIL;
}
}
return rc;
}
u32 vcd_handle_ind_output_reconfig(
struct vcd_clnt_ctxt *cctxt, void* payload, u32 status)
{
struct ddl_frame_data_tag *frame =
(struct ddl_frame_data_tag *)payload;
struct vcd_property_hdr prop_hdr;
u32 rc = VCD_S_SUCCESS;
struct vcd_buffer_pool *out_buf_pool;
struct vcd_buffer_requirement buf_req;
if (frame)
rc = vcd_handle_output_required(cctxt, payload, status);
VCD_FAILED_RETURN(rc, "Failed: vcd_handle_output_required in reconfig");
vcd_mark_frame_channel(cctxt->dev_ctxt);
rc = vcd_sched_suspend_resume_clnt(cctxt, false);
VCD_FAILED_RETURN(rc, "Failed: vcd_sched_suspend_resume_clnt");
out_buf_pool = &cctxt->out_buf_pool;
prop_hdr.prop_id = DDL_I_OUTPUT_BUF_REQ;
prop_hdr.sz = sizeof(buf_req);
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr, &buf_req);
VCD_FAILED_RETURN(rc, "Failed: ddl_GetProperty");
out_buf_pool->buf_req = buf_req;
if (out_buf_pool->count < buf_req.actual_count) {
VCD_MSG_HIGH("Output buf requirement count increased");
out_buf_pool->count = buf_req.actual_count;
}
if (buf_req.actual_count > VCD_MAX_BUFFER_ENTRIES) {
VCD_MSG_ERROR("\n New act count exceeds Max count(32)");
return VCD_ERR_FAIL;
}
if (!VCD_FAILED(rc)) {
rc = vcd_set_frame_size(cctxt, NULL);
VCD_FAILED_RETURN(rc, "Failed: set_frame_size in reconfig");
cctxt->status.mask &= ~VCD_FIRST_OP_RCVD;
cctxt->status.mask |= VCD_IN_RECONFIG;
cctxt->callback(VCD_EVT_IND_OUTPUT_RECONFIG,
status, NULL, 0, cctxt,
cctxt->client_data);
}
return rc;
}
u32 vcd_handle_ind_output_reconfig_in_flushing(
struct vcd_clnt_ctxt *cctxt, void* payload, u32 status)
{
u32 rc = VCD_S_SUCCESS;
if (cctxt->status.mask & VCD_FLUSH_INPUT && payload) {
(void)vcd_handle_input_done(cctxt, payload,
VCD_EVT_RESP_INPUT_FLUSHED, status);
payload = NULL;
}
rc = vcd_handle_ind_output_reconfig(cctxt, payload, status);
return rc;
}
u32 vcd_return_op_buffer_to_hw(struct vcd_clnt_ctxt *cctxt,
struct vcd_buffer_entry *buf_entry)
{
u32 rc = VCD_S_SUCCESS;
struct vcd_frame_data *frm_entry = &buf_entry->frame;
VCD_MSG_LOW("vcd_return_op_buffer_to_hw in %d:",
cctxt->clnt_state.state);
frm_entry->physical = buf_entry->physical;
frm_entry->ip_frm_tag = VCD_FRAMETAG_INVALID;
frm_entry->intrlcd_ip_frm_tag = VCD_FRAMETAG_INVALID;
frm_entry->data_len = 0;
if (cctxt->decoding) {
struct vcd_property_hdr Prop_hdr;
struct ddl_frame_data_tag ddl_frm;
Prop_hdr.prop_id = DDL_I_DPB_RELEASE;
Prop_hdr.sz =
sizeof(struct ddl_frame_data_tag);
memset(&ddl_frm, 0, sizeof(ddl_frm));
ddl_frm.vcd_frm = *frm_entry;
rc = ddl_set_property(cctxt->ddl_handle, &Prop_hdr,
&ddl_frm);
if (VCD_FAILED(rc)) {
VCD_MSG_ERROR("Error returning output buffer to"
" HW. rc = 0x%x", rc);
buf_entry->in_use = false;
} else {
cctxt->out_buf_pool.in_use++;
buf_entry->in_use = true;
}
}
return rc;
}
void vcd_handle_clnt_fatal(struct vcd_clnt_ctxt *cctxt, u32 trans_end)
{
if (trans_end)
vcd_mark_frame_channel(cctxt->dev_ctxt);
vcd_handle_err_fatal(cctxt,
VCD_EVT_IND_HWERRFATAL, VCD_ERR_CLIENT_FATAL);
}
void vcd_handle_clnt_fatal_input_done(struct vcd_clnt_ctxt *cctxt,
u32 trans_end)
{
if (cctxt->status.frame_submitted > 0)
cctxt->status.frame_submitted--;
vcd_handle_clnt_fatal(cctxt, trans_end);
}
void vcd_handle_ind_info_output_reconfig(
struct vcd_clnt_ctxt *cctxt, u32 status)
{
if (cctxt) {
cctxt->callback(VCD_EVT_IND_INFO_OUTPUT_RECONFIG, status, NULL,
0, cctxt, cctxt->client_data);
}
}
u32 vcd_set_num_slices(struct vcd_clnt_ctxt *cctxt)
{
struct vcd_property_hdr prop_hdr;
struct vcd_property_slice_delivery_info slice_delivery_info;
u32 rc = VCD_S_SUCCESS;
prop_hdr.prop_id = VCD_I_SLICE_DELIVERY_MODE;
prop_hdr.sz =
sizeof(struct vcd_property_slice_delivery_info);
rc = ddl_get_property(cctxt->ddl_handle, &prop_hdr,
&slice_delivery_info);
VCD_FAILED_RETURN(rc, "Failed: Get VCD_I_SLICE_DELIVERY_MODE");
if (slice_delivery_info.enable) {
cctxt->num_slices = slice_delivery_info.num_slices;
VCD_MSG_LOW("%s slice delivery mode num_slices = %u\n",
__func__, cctxt->num_slices);
} else {
cctxt->num_slices = 1;
}
return rc;
}
u32 vcd_handle_ltr_use_failed(struct vcd_clnt_ctxt *cctxt,
void *payload, size_t sz, u32 status)
{
u32 rc = VCD_S_SUCCESS;
if (payload && cctxt) {
cctxt->callback(VCD_EVT_IND_INFO_LTRUSE_FAILED,
status, payload, sz, cctxt, cctxt->client_data);
}
return rc;
}
| gpl-2.0 |
MyAOSP/kernel_htc_m7 | drivers/staging/comedi/comedi_fops.c | 542 | 63288 | /*
comedi/comedi_fops.c
comedi kernel module
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#undef DEBUG
#define __NO_VERSION__
#include "comedi_fops.h"
#include "comedi_compat32.h"
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fcntl.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/kmod.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include "comedidev.h"
#include <linux/cdev.h>
#include <linux/stat.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include "internal.h"
MODULE_AUTHOR("http://www.comedi.org");
MODULE_DESCRIPTION("Comedi core module");
MODULE_LICENSE("GPL");
#ifdef CONFIG_COMEDI_DEBUG
int comedi_debug;
EXPORT_SYMBOL(comedi_debug);
module_param(comedi_debug, int, 0644);
#endif
bool comedi_autoconfig = 1;
module_param(comedi_autoconfig, bool, 0444);
static int comedi_num_legacy_minors;
module_param(comedi_num_legacy_minors, int, 0444);
static DEFINE_SPINLOCK(comedi_file_info_table_lock);
static struct comedi_device_file_info
*comedi_file_info_table[COMEDI_NUM_MINORS];
static int do_devconfig_ioctl(struct comedi_device *dev,
struct comedi_devconfig __user *arg);
static int do_bufconfig_ioctl(struct comedi_device *dev,
struct comedi_bufconfig __user *arg);
static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file);
static int do_subdinfo_ioctl(struct comedi_device *dev,
struct comedi_subdinfo __user *arg, void *file);
static int do_chaninfo_ioctl(struct comedi_device *dev,
struct comedi_chaninfo __user *arg);
static int do_bufinfo_ioctl(struct comedi_device *dev,
struct comedi_bufinfo __user *arg, void *file);
static int do_cmd_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file);
static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg,
void *file);
static int do_cmdtest_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file);
static int do_insnlist_ioctl(struct comedi_device *dev,
struct comedi_insnlist __user *arg, void *file);
static int do_insn_ioctl(struct comedi_device *dev,
struct comedi_insn __user *arg, void *file);
static int do_poll_ioctl(struct comedi_device *dev, unsigned int subd,
void *file);
static void do_become_nonbusy(struct comedi_device *dev,
struct comedi_subdevice *s);
static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
static int comedi_fasync(int fd, struct file *file, int on);
static int is_device_busy(struct comedi_device *dev);
static int resize_async_buffer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_async *async, unsigned new_size);
/* declarations for sysfs attribute files */
static struct device_attribute dev_attr_max_read_buffer_kb;
static struct device_attribute dev_attr_read_buffer_kb;
static struct device_attribute dev_attr_max_write_buffer_kb;
static struct device_attribute dev_attr_write_buffer_kb;
static long comedi_unlocked_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev;
int rc;
if (dev_file_info == NULL || dev_file_info->device == NULL)
return -ENODEV;
dev = dev_file_info->device;
mutex_lock(&dev->mutex);
/* Device config is special, because it must work on
* an unconfigured device. */
if (cmd == COMEDI_DEVCONFIG) {
rc = do_devconfig_ioctl(dev,
(struct comedi_devconfig __user *)arg);
goto done;
}
if (!dev->attached) {
DPRINTK("no driver configured on /dev/comedi%i\n", dev->minor);
rc = -ENODEV;
goto done;
}
switch (cmd) {
case COMEDI_BUFCONFIG:
rc = do_bufconfig_ioctl(dev,
(struct comedi_bufconfig __user *)arg);
break;
case COMEDI_DEVINFO:
rc = do_devinfo_ioctl(dev, (struct comedi_devinfo __user *)arg,
file);
break;
case COMEDI_SUBDINFO:
rc = do_subdinfo_ioctl(dev,
(struct comedi_subdinfo __user *)arg,
file);
break;
case COMEDI_CHANINFO:
rc = do_chaninfo_ioctl(dev, (void __user *)arg);
break;
case COMEDI_RANGEINFO:
rc = do_rangeinfo_ioctl(dev, (void __user *)arg);
break;
case COMEDI_BUFINFO:
rc = do_bufinfo_ioctl(dev,
(struct comedi_bufinfo __user *)arg,
file);
break;
case COMEDI_LOCK:
rc = do_lock_ioctl(dev, arg, file);
break;
case COMEDI_UNLOCK:
rc = do_unlock_ioctl(dev, arg, file);
break;
case COMEDI_CANCEL:
rc = do_cancel_ioctl(dev, arg, file);
break;
case COMEDI_CMD:
rc = do_cmd_ioctl(dev, (struct comedi_cmd __user *)arg, file);
break;
case COMEDI_CMDTEST:
rc = do_cmdtest_ioctl(dev, (struct comedi_cmd __user *)arg,
file);
break;
case COMEDI_INSNLIST:
rc = do_insnlist_ioctl(dev,
(struct comedi_insnlist __user *)arg,
file);
break;
case COMEDI_INSN:
rc = do_insn_ioctl(dev, (struct comedi_insn __user *)arg,
file);
break;
case COMEDI_POLL:
rc = do_poll_ioctl(dev, arg, file);
break;
default:
rc = -ENOTTY;
break;
}
done:
mutex_unlock(&dev->mutex);
return rc;
}
/*
COMEDI_DEVCONFIG
device config ioctl
arg:
pointer to devconfig structure
reads:
devconfig structure at arg
writes:
none
*/
static int do_devconfig_ioctl(struct comedi_device *dev,
struct comedi_devconfig __user *arg)
{
struct comedi_devconfig it;
int ret;
unsigned char *aux_data = NULL;
int aux_len;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (arg == NULL) {
if (is_device_busy(dev))
return -EBUSY;
if (dev->attached) {
struct module *driver_module = dev->driver->module;
comedi_device_detach(dev);
module_put(driver_module);
}
return 0;
}
if (copy_from_user(&it, arg, sizeof(struct comedi_devconfig)))
return -EFAULT;
it.board_name[COMEDI_NAMELEN - 1] = 0;
if (comedi_aux_data(it.options, 0) &&
it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) {
int bit_shift;
aux_len = it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH];
if (aux_len < 0)
return -EFAULT;
aux_data = vmalloc(aux_len);
if (!aux_data)
return -ENOMEM;
if (copy_from_user(aux_data,
comedi_aux_data(it.options, 0), aux_len)) {
vfree(aux_data);
return -EFAULT;
}
it.options[COMEDI_DEVCONF_AUX_DATA_LO] =
(unsigned long)aux_data;
if (sizeof(void *) > sizeof(int)) {
bit_shift = sizeof(int) * 8;
it.options[COMEDI_DEVCONF_AUX_DATA_HI] =
((unsigned long)aux_data) >> bit_shift;
} else
it.options[COMEDI_DEVCONF_AUX_DATA_HI] = 0;
}
ret = comedi_device_attach(dev, &it);
if (ret == 0) {
if (!try_module_get(dev->driver->module)) {
comedi_device_detach(dev);
ret = -ENOSYS;
}
}
if (aux_data)
vfree(aux_data);
return ret;
}
/*
COMEDI_BUFCONFIG
buffer configuration ioctl
arg:
pointer to bufconfig structure
reads:
bufconfig at arg
writes:
modified bufconfig at arg
*/
static int do_bufconfig_ioctl(struct comedi_device *dev,
struct comedi_bufconfig __user *arg)
{
struct comedi_bufconfig bc;
struct comedi_async *async;
struct comedi_subdevice *s;
int retval = 0;
if (copy_from_user(&bc, arg, sizeof(struct comedi_bufconfig)))
return -EFAULT;
if (bc.subdevice >= dev->n_subdevices || bc.subdevice < 0)
return -EINVAL;
s = dev->subdevices + bc.subdevice;
async = s->async;
if (!async) {
DPRINTK("subdevice does not have async capability\n");
bc.size = 0;
bc.maximum_size = 0;
goto copyback;
}
if (bc.maximum_size) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
async->max_bufsize = bc.maximum_size;
}
if (bc.size) {
retval = resize_async_buffer(dev, s, async, bc.size);
if (retval < 0)
return retval;
}
bc.size = async->prealloc_bufsz;
bc.maximum_size = async->max_bufsize;
copyback:
if (copy_to_user(arg, &bc, sizeof(struct comedi_bufconfig)))
return -EFAULT;
return 0;
}
/*
COMEDI_DEVINFO
device info ioctl
arg:
pointer to devinfo structure
reads:
none
writes:
devinfo structure
*/
static int do_devinfo_ioctl(struct comedi_device *dev,
struct comedi_devinfo __user *arg,
struct file *file)
{
struct comedi_devinfo devinfo;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_subdevice *read_subdev =
comedi_get_read_subdevice(dev_file_info);
struct comedi_subdevice *write_subdev =
comedi_get_write_subdevice(dev_file_info);
memset(&devinfo, 0, sizeof(devinfo));
/* fill devinfo structure */
devinfo.version_code = COMEDI_VERSION_CODE;
devinfo.n_subdevs = dev->n_subdevices;
strlcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN);
strlcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN);
if (read_subdev)
devinfo.read_subdevice = read_subdev - dev->subdevices;
else
devinfo.read_subdevice = -1;
if (write_subdev)
devinfo.write_subdevice = write_subdev - dev->subdevices;
else
devinfo.write_subdevice = -1;
if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo)))
return -EFAULT;
return 0;
}
/*
COMEDI_SUBDINFO
subdevice info ioctl
arg:
pointer to array of subdevice info structures
reads:
none
writes:
array of subdevice info structures at arg
*/
static int do_subdinfo_ioctl(struct comedi_device *dev,
struct comedi_subdinfo __user *arg, void *file)
{
int ret, i;
struct comedi_subdinfo *tmp, *us;
struct comedi_subdevice *s;
tmp =
kcalloc(dev->n_subdevices, sizeof(struct comedi_subdinfo),
GFP_KERNEL);
if (!tmp)
return -ENOMEM;
/* fill subdinfo structs */
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
us = tmp + i;
us->type = s->type;
us->n_chan = s->n_chan;
us->subd_flags = s->subdev_flags;
if (comedi_get_subdevice_runflags(s) & SRF_RUNNING)
us->subd_flags |= SDF_RUNNING;
#define TIMER_nanosec 5 /* backwards compatibility */
us->timer_type = TIMER_nanosec;
us->len_chanlist = s->len_chanlist;
us->maxdata = s->maxdata;
if (s->range_table) {
us->range_type =
(i << 24) | (0 << 16) | (s->range_table->length);
} else {
us->range_type = 0; /* XXX */
}
us->flags = s->flags;
if (s->busy)
us->subd_flags |= SDF_BUSY;
if (s->busy == file)
us->subd_flags |= SDF_BUSY_OWNER;
if (s->lock)
us->subd_flags |= SDF_LOCKED;
if (s->lock == file)
us->subd_flags |= SDF_LOCK_OWNER;
if (!s->maxdata && s->maxdata_list)
us->subd_flags |= SDF_MAXDATA;
if (s->flaglist)
us->subd_flags |= SDF_FLAGS;
if (s->range_table_list)
us->subd_flags |= SDF_RANGETYPE;
if (s->do_cmd)
us->subd_flags |= SDF_CMD;
if (s->insn_bits != &insn_inval)
us->insn_bits_support = COMEDI_SUPPORTED;
else
us->insn_bits_support = COMEDI_UNSUPPORTED;
us->settling_time_0 = s->settling_time_0;
}
ret = copy_to_user(arg, tmp,
dev->n_subdevices * sizeof(struct comedi_subdinfo));
kfree(tmp);
return ret ? -EFAULT : 0;
}
/*
COMEDI_CHANINFO
subdevice info ioctl
arg:
pointer to chaninfo structure
reads:
chaninfo structure at arg
writes:
arrays at elements of chaninfo structure
*/
static int do_chaninfo_ioctl(struct comedi_device *dev,
struct comedi_chaninfo __user *arg)
{
struct comedi_subdevice *s;
struct comedi_chaninfo it;
if (copy_from_user(&it, arg, sizeof(struct comedi_chaninfo)))
return -EFAULT;
if (it.subdev >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + it.subdev;
if (it.maxdata_list) {
if (s->maxdata || !s->maxdata_list)
return -EINVAL;
if (copy_to_user(it.maxdata_list, s->maxdata_list,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
}
if (it.flaglist) {
if (!s->flaglist)
return -EINVAL;
if (copy_to_user(it.flaglist, s->flaglist,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
}
if (it.rangelist) {
int i;
if (!s->range_table_list)
return -EINVAL;
for (i = 0; i < s->n_chan; i++) {
int x;
x = (dev->minor << 28) | (it.subdev << 24) | (i << 16) |
(s->range_table_list[i]->length);
if (put_user(x, it.rangelist + i))
return -EFAULT;
}
#if 0
if (copy_to_user(it.rangelist, s->range_type_list,
s->n_chan * sizeof(unsigned int)))
return -EFAULT;
#endif
}
return 0;
}
/*
COMEDI_BUFINFO
buffer information ioctl
arg:
pointer to bufinfo structure
reads:
bufinfo at arg
writes:
modified bufinfo at arg
*/
static int do_bufinfo_ioctl(struct comedi_device *dev,
struct comedi_bufinfo __user *arg, void *file)
{
struct comedi_bufinfo bi;
struct comedi_subdevice *s;
struct comedi_async *async;
if (copy_from_user(&bi, arg, sizeof(struct comedi_bufinfo)))
return -EFAULT;
if (bi.subdevice >= dev->n_subdevices || bi.subdevice < 0)
return -EINVAL;
s = dev->subdevices + bi.subdevice;
if (s->lock && s->lock != file)
return -EACCES;
async = s->async;
if (!async) {
DPRINTK("subdevice does not have async capability\n");
bi.buf_write_ptr = 0;
bi.buf_read_ptr = 0;
bi.buf_write_count = 0;
bi.buf_read_count = 0;
bi.bytes_read = 0;
bi.bytes_written = 0;
goto copyback;
}
if (!s->busy) {
bi.bytes_read = 0;
bi.bytes_written = 0;
goto copyback_position;
}
if (s->busy != file)
return -EACCES;
if (bi.bytes_read && (s->subdev_flags & SDF_CMD_READ)) {
bi.bytes_read = comedi_buf_read_alloc(async, bi.bytes_read);
comedi_buf_read_free(async, bi.bytes_read);
if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR |
SRF_RUNNING))
&& async->buf_write_count == async->buf_read_count) {
do_become_nonbusy(dev, s);
}
}
if (bi.bytes_written && (s->subdev_flags & SDF_CMD_WRITE)) {
bi.bytes_written =
comedi_buf_write_alloc(async, bi.bytes_written);
comedi_buf_write_free(async, bi.bytes_written);
}
copyback_position:
bi.buf_write_count = async->buf_write_count;
bi.buf_write_ptr = async->buf_write_ptr;
bi.buf_read_count = async->buf_read_count;
bi.buf_read_ptr = async->buf_read_ptr;
copyback:
if (copy_to_user(arg, &bi, sizeof(struct comedi_bufinfo)))
return -EFAULT;
return 0;
}
static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn,
unsigned int *data, void *file);
/*
* COMEDI_INSNLIST
* synchronous instructions
*
* arg:
* pointer to sync cmd structure
*
* reads:
* sync cmd struct at arg
* instruction list
* data (for writes)
*
* writes:
* data (for reads)
*/
/* arbitrary limits */
#define MAX_SAMPLES 256
static int do_insnlist_ioctl(struct comedi_device *dev,
struct comedi_insnlist __user *arg, void *file)
{
struct comedi_insnlist insnlist;
struct comedi_insn *insns = NULL;
unsigned int *data = NULL;
int i = 0;
int ret = 0;
if (copy_from_user(&insnlist, arg, sizeof(struct comedi_insnlist)))
return -EFAULT;
data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
if (!data) {
DPRINTK("kmalloc failed\n");
ret = -ENOMEM;
goto error;
}
insns =
kcalloc(insnlist.n_insns, sizeof(struct comedi_insn), GFP_KERNEL);
if (!insns) {
DPRINTK("kmalloc failed\n");
ret = -ENOMEM;
goto error;
}
if (copy_from_user(insns, insnlist.insns,
sizeof(struct comedi_insn) * insnlist.n_insns)) {
DPRINTK("copy_from_user failed\n");
ret = -EFAULT;
goto error;
}
for (i = 0; i < insnlist.n_insns; i++) {
if (insns[i].n > MAX_SAMPLES) {
DPRINTK("number of samples too large\n");
ret = -EINVAL;
goto error;
}
if (insns[i].insn & INSN_MASK_WRITE) {
if (copy_from_user(data, insns[i].data,
insns[i].n * sizeof(unsigned int))) {
DPRINTK("copy_from_user failed\n");
ret = -EFAULT;
goto error;
}
}
ret = parse_insn(dev, insns + i, data, file);
if (ret < 0)
goto error;
if (insns[i].insn & INSN_MASK_READ) {
if (copy_to_user(insns[i].data, data,
insns[i].n * sizeof(unsigned int))) {
DPRINTK("copy_to_user failed\n");
ret = -EFAULT;
goto error;
}
}
if (need_resched())
schedule();
}
error:
kfree(insns);
kfree(data);
if (ret < 0)
return ret;
return i;
}
static int check_insn_config_length(struct comedi_insn *insn,
unsigned int *data)
{
if (insn->n < 1)
return -EINVAL;
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
case INSN_CONFIG_DIO_INPUT:
case INSN_CONFIG_DISARM:
case INSN_CONFIG_RESET:
if (insn->n == 1)
return 0;
break;
case INSN_CONFIG_ARM:
case INSN_CONFIG_DIO_QUERY:
case INSN_CONFIG_BLOCK_SIZE:
case INSN_CONFIG_FILTER:
case INSN_CONFIG_SERIAL_CLOCK:
case INSN_CONFIG_BIDIRECTIONAL_DATA:
case INSN_CONFIG_ALT_SOURCE:
case INSN_CONFIG_SET_COUNTER_MODE:
case INSN_CONFIG_8254_READ_STATUS:
case INSN_CONFIG_SET_ROUTING:
case INSN_CONFIG_GET_ROUTING:
case INSN_CONFIG_GET_PWM_STATUS:
case INSN_CONFIG_PWM_SET_PERIOD:
case INSN_CONFIG_PWM_GET_PERIOD:
if (insn->n == 2)
return 0;
break;
case INSN_CONFIG_SET_GATE_SRC:
case INSN_CONFIG_GET_GATE_SRC:
case INSN_CONFIG_SET_CLOCK_SRC:
case INSN_CONFIG_GET_CLOCK_SRC:
case INSN_CONFIG_SET_OTHER_SRC:
case INSN_CONFIG_GET_COUNTER_STATUS:
case INSN_CONFIG_PWM_SET_H_BRIDGE:
case INSN_CONFIG_PWM_GET_H_BRIDGE:
case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE:
if (insn->n == 3)
return 0;
break;
case INSN_CONFIG_PWM_OUTPUT:
case INSN_CONFIG_ANALOG_TRIG:
if (insn->n == 5)
return 0;
break;
/* by default we allow the insn since we don't have checks for
* all possible cases yet */
default:
printk(KERN_WARNING
"comedi: no check for data length of config insn id "
"%i is implemented.\n"
" Add a check to %s in %s.\n"
" Assuming n=%i is correct.\n", data[0], __func__,
__FILE__, insn->n);
return 0;
break;
}
return -EINVAL;
}
static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn,
unsigned int *data, void *file)
{
struct comedi_subdevice *s;
int ret = 0;
int i;
if (insn->insn & INSN_MASK_SPECIAL) {
/* a non-subdevice instruction */
switch (insn->insn) {
case INSN_GTOD:
{
struct timeval tv;
if (insn->n != 2) {
ret = -EINVAL;
break;
}
do_gettimeofday(&tv);
data[0] = tv.tv_sec;
data[1] = tv.tv_usec;
ret = 2;
break;
}
case INSN_WAIT:
if (insn->n != 1 || data[0] >= 100000) {
ret = -EINVAL;
break;
}
udelay(data[0] / 1000);
ret = 1;
break;
case INSN_INTTRIG:
if (insn->n != 1) {
ret = -EINVAL;
break;
}
if (insn->subdev >= dev->n_subdevices) {
DPRINTK("%d not usable subdevice\n",
insn->subdev);
ret = -EINVAL;
break;
}
s = dev->subdevices + insn->subdev;
if (!s->async) {
DPRINTK("no async\n");
ret = -EINVAL;
break;
}
if (!s->async->inttrig) {
DPRINTK("no inttrig\n");
ret = -EAGAIN;
break;
}
ret = s->async->inttrig(dev, s, insn->data[0]);
if (ret >= 0)
ret = 1;
break;
default:
DPRINTK("invalid insn\n");
ret = -EINVAL;
break;
}
} else {
/* a subdevice instruction */
unsigned int maxdata;
if (insn->subdev >= dev->n_subdevices) {
DPRINTK("subdevice %d out of range\n", insn->subdev);
ret = -EINVAL;
goto out;
}
s = dev->subdevices + insn->subdev;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not usable subdevice\n", insn->subdev);
ret = -EIO;
goto out;
}
/* are we locked? (ioctl lock) */
if (s->lock && s->lock != file) {
DPRINTK("device locked\n");
ret = -EACCES;
goto out;
}
ret = comedi_check_chanlist(s, 1, &insn->chanspec);
if (ret < 0) {
ret = -EINVAL;
DPRINTK("bad chanspec\n");
goto out;
}
if (s->busy) {
ret = -EBUSY;
goto out;
}
/* This looks arbitrary. It is. */
s->busy = &parse_insn;
switch (insn->insn) {
case INSN_READ:
ret = s->insn_read(dev, s, insn, data);
break;
case INSN_WRITE:
maxdata = s->maxdata_list
? s->maxdata_list[CR_CHAN(insn->chanspec)]
: s->maxdata;
for (i = 0; i < insn->n; ++i) {
if (data[i] > maxdata) {
ret = -EINVAL;
DPRINTK("bad data value(s)\n");
break;
}
}
if (ret == 0)
ret = s->insn_write(dev, s, insn, data);
break;
case INSN_BITS:
if (insn->n != 2) {
ret = -EINVAL;
} else {
/* Most drivers ignore the base channel in
* insn->chanspec. Fix this here if
* the subdevice has <= 32 channels. */
unsigned int shift;
unsigned int orig_mask;
orig_mask = data[0];
if (s->n_chan <= 32) {
shift = CR_CHAN(insn->chanspec);
if (shift > 0) {
insn->chanspec = 0;
data[0] <<= shift;
data[1] <<= shift;
}
} else
shift = 0;
ret = s->insn_bits(dev, s, insn, data);
data[0] = orig_mask;
if (shift > 0)
data[1] >>= shift;
}
break;
case INSN_CONFIG:
ret = check_insn_config_length(insn, data);
if (ret)
break;
ret = s->insn_config(dev, s, insn, data);
break;
default:
ret = -EINVAL;
break;
}
s->busy = NULL;
}
out:
return ret;
}
/*
* COMEDI_INSN
* synchronous instructions
*
* arg:
* pointer to insn
*
* reads:
* struct comedi_insn struct at arg
* data (for writes)
*
* writes:
* data (for reads)
*/
static int do_insn_ioctl(struct comedi_device *dev,
struct comedi_insn __user *arg, void *file)
{
struct comedi_insn insn;
unsigned int *data = NULL;
int ret = 0;
data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
if (!data) {
ret = -ENOMEM;
goto error;
}
if (copy_from_user(&insn, arg, sizeof(struct comedi_insn))) {
ret = -EFAULT;
goto error;
}
/* This is where the behavior of insn and insnlist deviate. */
if (insn.n > MAX_SAMPLES)
insn.n = MAX_SAMPLES;
if (insn.insn & INSN_MASK_WRITE) {
if (copy_from_user(data,
insn.data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = parse_insn(dev, &insn, data, file);
if (ret < 0)
goto error;
if (insn.insn & INSN_MASK_READ) {
if (copy_to_user(insn.data,
data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = insn.n;
error:
kfree(data);
return ret;
}
static void comedi_set_subdevice_runflags(struct comedi_subdevice *s,
unsigned mask, unsigned bits)
{
unsigned long flags;
spin_lock_irqsave(&s->spin_lock, flags);
s->runflags &= ~mask;
s->runflags |= (bits & mask);
spin_unlock_irqrestore(&s->spin_lock, flags);
}
static int do_cmd_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *cmd, void *file)
{
struct comedi_cmd user_cmd;
struct comedi_subdevice *s;
struct comedi_async *async;
int ret = 0;
unsigned int __user *chanlist_saver = NULL;
if (copy_from_user(&user_cmd, cmd, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
return -EFAULT;
}
/* save user's chanlist pointer so it can be restored later */
chanlist_saver = user_cmd.chanlist;
if (user_cmd.subdev >= dev->n_subdevices) {
DPRINTK("%d no such subdevice\n", user_cmd.subdev);
return -ENODEV;
}
s = dev->subdevices + user_cmd.subdev;
async = s->async;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not valid subdevice\n", user_cmd.subdev);
return -EIO;
}
if (!s->do_cmd || !s->do_cmdtest || !s->async) {
DPRINTK("subdevice %i does not support commands\n",
user_cmd.subdev);
return -EIO;
}
/* are we locked? (ioctl lock) */
if (s->lock && s->lock != file) {
DPRINTK("subdevice locked\n");
return -EACCES;
}
/* are we busy? */
if (s->busy) {
DPRINTK("subdevice busy\n");
return -EBUSY;
}
s->busy = file;
/* make sure channel/gain list isn't too long */
if (user_cmd.chanlist_len > s->len_chanlist) {
DPRINTK("channel/gain list too long %u > %d\n",
user_cmd.chanlist_len, s->len_chanlist);
ret = -EINVAL;
goto cleanup;
}
/* make sure channel/gain list isn't too short */
if (user_cmd.chanlist_len < 1) {
DPRINTK("channel/gain list too short %u < 1\n",
user_cmd.chanlist_len);
ret = -EINVAL;
goto cleanup;
}
kfree(async->cmd.chanlist);
async->cmd = user_cmd;
async->cmd.data = NULL;
/* load channel/gain list */
async->cmd.chanlist =
kmalloc(async->cmd.chanlist_len * sizeof(int), GFP_KERNEL);
if (!async->cmd.chanlist) {
DPRINTK("allocation failed\n");
ret = -ENOMEM;
goto cleanup;
}
if (copy_from_user(async->cmd.chanlist, user_cmd.chanlist,
async->cmd.chanlist_len * sizeof(int))) {
DPRINTK("fault reading chanlist\n");
ret = -EFAULT;
goto cleanup;
}
/* make sure each element in channel/gain list is valid */
ret = comedi_check_chanlist(s,
async->cmd.chanlist_len,
async->cmd.chanlist);
if (ret < 0) {
DPRINTK("bad chanlist\n");
goto cleanup;
}
ret = s->do_cmdtest(dev, s, &async->cmd);
if (async->cmd.flags & TRIG_BOGUS || ret) {
DPRINTK("test returned %d\n", ret);
user_cmd = async->cmd;
/* restore chanlist pointer before copying back */
user_cmd.chanlist = chanlist_saver;
user_cmd.data = NULL;
if (copy_to_user(cmd, &user_cmd, sizeof(struct comedi_cmd))) {
DPRINTK("fault writing cmd\n");
ret = -EFAULT;
goto cleanup;
}
ret = -EAGAIN;
goto cleanup;
}
if (!async->prealloc_bufsz) {
ret = -ENOMEM;
DPRINTK("no buffer (?)\n");
goto cleanup;
}
comedi_reset_async_buf(async);
async->cb_mask =
COMEDI_CB_EOA | COMEDI_CB_BLOCK | COMEDI_CB_ERROR |
COMEDI_CB_OVERFLOW;
if (async->cmd.flags & TRIG_WAKE_EOS)
async->cb_mask |= COMEDI_CB_EOS;
comedi_set_subdevice_runflags(s, ~0, SRF_USER | SRF_RUNNING);
ret = s->do_cmd(dev, s);
if (ret == 0)
return 0;
cleanup:
do_become_nonbusy(dev, s);
return ret;
}
/*
COMEDI_CMDTEST
command testing ioctl
arg:
pointer to cmd structure
reads:
cmd structure at arg
channel/range list
writes:
modified cmd structure at arg
*/
static int do_cmdtest_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file)
{
struct comedi_cmd user_cmd;
struct comedi_subdevice *s;
int ret = 0;
unsigned int *chanlist = NULL;
unsigned int __user *chanlist_saver = NULL;
if (copy_from_user(&user_cmd, arg, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
return -EFAULT;
}
/* save user's chanlist pointer so it can be restored later */
chanlist_saver = user_cmd.chanlist;
if (user_cmd.subdev >= dev->n_subdevices) {
DPRINTK("%d no such subdevice\n", user_cmd.subdev);
return -ENODEV;
}
s = dev->subdevices + user_cmd.subdev;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not valid subdevice\n", user_cmd.subdev);
return -EIO;
}
if (!s->do_cmd || !s->do_cmdtest) {
DPRINTK("subdevice %i does not support commands\n",
user_cmd.subdev);
return -EIO;
}
/* make sure channel/gain list isn't too long */
if (user_cmd.chanlist_len > s->len_chanlist) {
DPRINTK("channel/gain list too long %d > %d\n",
user_cmd.chanlist_len, s->len_chanlist);
ret = -EINVAL;
goto cleanup;
}
/* load channel/gain list */
if (user_cmd.chanlist) {
chanlist =
kmalloc(user_cmd.chanlist_len * sizeof(int), GFP_KERNEL);
if (!chanlist) {
DPRINTK("allocation failed\n");
ret = -ENOMEM;
goto cleanup;
}
if (copy_from_user(chanlist, user_cmd.chanlist,
user_cmd.chanlist_len * sizeof(int))) {
DPRINTK("fault reading chanlist\n");
ret = -EFAULT;
goto cleanup;
}
/* make sure each element in channel/gain list is valid */
ret = comedi_check_chanlist(s, user_cmd.chanlist_len, chanlist);
if (ret < 0) {
DPRINTK("bad chanlist\n");
goto cleanup;
}
user_cmd.chanlist = chanlist;
}
ret = s->do_cmdtest(dev, s, &user_cmd);
/* restore chanlist pointer before copying back */
user_cmd.chanlist = chanlist_saver;
if (copy_to_user(arg, &user_cmd, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
ret = -EFAULT;
goto cleanup;
}
cleanup:
kfree(chanlist);
return ret;
}
/*
COMEDI_LOCK
lock subdevice
arg:
subdevice number
reads:
none
writes:
none
*/
static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
int ret = 0;
unsigned long flags;
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
spin_lock_irqsave(&s->spin_lock, flags);
if (s->busy || s->lock)
ret = -EBUSY;
else
s->lock = file;
spin_unlock_irqrestore(&s->spin_lock, flags);
#if 0
if (ret < 0)
return ret;
if (s->lock_f)
ret = s->lock_f(dev, s);
#endif
return ret;
}
/*
COMEDI_UNLOCK
unlock subdevice
arg:
subdevice number
reads:
none
writes:
none
This function isn't protected by the semaphore, since
we already own the lock.
*/
static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->busy)
return -EBUSY;
if (s->lock && s->lock != file)
return -EACCES;
if (s->lock == file) {
#if 0
if (s->unlock)
s->unlock(dev, s);
#endif
s->lock = NULL;
}
return 0;
}
/*
COMEDI_CANCEL
cancel acquisition ioctl
arg:
subdevice number
reads:
nothing
writes:
nothing
*/
static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->async == NULL)
return -EINVAL;
if (s->lock && s->lock != file)
return -EACCES;
if (!s->busy)
return 0;
if (s->busy != file)
return -EBUSY;
return do_cancel(dev, s);
}
/*
COMEDI_POLL ioctl
instructs driver to synchronize buffers
arg:
subdevice number
reads:
nothing
writes:
nothing
*/
static int do_poll_ioctl(struct comedi_device *dev, unsigned int arg,
void *file)
{
struct comedi_subdevice *s;
if (arg >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + arg;
if (s->lock && s->lock != file)
return -EACCES;
if (!s->busy)
return 0;
if (s->busy != file)
return -EBUSY;
if (s->poll)
return s->poll(dev, s);
return -EINVAL;
}
static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
int ret = 0;
if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) && s->cancel)
ret = s->cancel(dev, s);
do_become_nonbusy(dev, s);
return ret;
}
static void comedi_vm_open(struct vm_area_struct *area)
{
struct comedi_async *async;
struct comedi_device *dev;
async = area->vm_private_data;
dev = async->subdevice->device;
mutex_lock(&dev->mutex);
async->mmap_count++;
mutex_unlock(&dev->mutex);
}
static void comedi_vm_close(struct vm_area_struct *area)
{
struct comedi_async *async;
struct comedi_device *dev;
async = area->vm_private_data;
dev = async->subdevice->device;
mutex_lock(&dev->mutex);
async->mmap_count--;
mutex_unlock(&dev->mutex);
}
static struct vm_operations_struct comedi_vm_ops = {
.open = comedi_vm_open,
.close = comedi_vm_close,
};
static int comedi_mmap(struct file *file, struct vm_area_struct *vma)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_async *async = NULL;
unsigned long start = vma->vm_start;
unsigned long size;
int n_pages;
int i;
int retval;
struct comedi_subdevice *s;
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
mutex_lock(&dev->mutex);
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
if (vma->vm_flags & VM_WRITE)
s = comedi_get_write_subdevice(dev_file_info);
else
s = comedi_get_read_subdevice(dev_file_info);
if (s == NULL) {
retval = -EINVAL;
goto done;
}
async = s->async;
if (async == NULL) {
retval = -EINVAL;
goto done;
}
if (vma->vm_pgoff != 0) {
DPRINTK("comedi: mmap() offset must be 0.\n");
retval = -EINVAL;
goto done;
}
size = vma->vm_end - vma->vm_start;
if (size > async->prealloc_bufsz) {
retval = -EFAULT;
goto done;
}
if (size & (~PAGE_MASK)) {
retval = -EFAULT;
goto done;
}
n_pages = size >> PAGE_SHIFT;
for (i = 0; i < n_pages; ++i) {
if (remap_pfn_range(vma, start,
page_to_pfn(virt_to_page
(async->buf_page_list
[i].virt_addr)), PAGE_SIZE,
PAGE_SHARED)) {
retval = -EAGAIN;
goto done;
}
start += PAGE_SIZE;
}
vma->vm_ops = &comedi_vm_ops;
vma->vm_private_data = async;
async->mmap_count++;
retval = 0;
done:
mutex_unlock(&dev->mutex);
return retval;
}
static unsigned int comedi_poll(struct file *file, poll_table * wait)
{
unsigned int mask = 0;
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_subdevice *read_subdev;
struct comedi_subdevice *write_subdev;
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
mutex_lock(&dev->mutex);
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
mutex_unlock(&dev->mutex);
return 0;
}
mask = 0;
read_subdev = comedi_get_read_subdevice(dev_file_info);
if (read_subdev) {
poll_wait(file, &read_subdev->async->wait_head, wait);
if (!read_subdev->busy
|| comedi_buf_read_n_available(read_subdev->async) > 0
|| !(comedi_get_subdevice_runflags(read_subdev) &
SRF_RUNNING)) {
mask |= POLLIN | POLLRDNORM;
}
}
write_subdev = comedi_get_write_subdevice(dev_file_info);
if (write_subdev) {
poll_wait(file, &write_subdev->async->wait_head, wait);
comedi_buf_write_alloc(write_subdev->async,
write_subdev->async->prealloc_bufsz);
if (!write_subdev->busy
|| !(comedi_get_subdevice_runflags(write_subdev) &
SRF_RUNNING)
|| comedi_buf_write_n_allocated(write_subdev->async) >=
bytes_per_sample(write_subdev->async->subdevice)) {
mask |= POLLOUT | POLLWRNORM;
}
}
mutex_unlock(&dev->mutex);
return mask;
}
static ssize_t comedi_write(struct file *file, const char __user *buf,
size_t nbytes, loff_t *offset)
{
struct comedi_subdevice *s;
struct comedi_async *async;
int n, m, count = 0, retval = 0;
DECLARE_WAITQUEUE(wait, current);
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
s = comedi_get_write_subdevice(dev_file_info);
if (s == NULL) {
retval = -EIO;
goto done;
}
async = s->async;
if (!nbytes) {
retval = 0;
goto done;
}
if (!s->busy) {
retval = 0;
goto done;
}
if (s->busy != file) {
retval = -EACCES;
goto done;
}
add_wait_queue(&async->wait_head, &wait);
while (nbytes > 0 && !retval) {
set_current_state(TASK_INTERRUPTIBLE);
if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) {
if (count == 0) {
if (comedi_get_subdevice_runflags(s) &
SRF_ERROR) {
retval = -EPIPE;
} else {
retval = 0;
}
do_become_nonbusy(dev, s);
}
break;
}
n = nbytes;
m = n;
if (async->buf_write_ptr + m > async->prealloc_bufsz)
m = async->prealloc_bufsz - async->buf_write_ptr;
comedi_buf_write_alloc(async, async->prealloc_bufsz);
if (m > comedi_buf_write_n_allocated(async))
m = comedi_buf_write_n_allocated(async);
if (m < n)
n = m;
if (n == 0) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
schedule();
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (!s->busy)
break;
if (s->busy != file) {
retval = -EACCES;
break;
}
continue;
}
m = copy_from_user(async->prealloc_buf + async->buf_write_ptr,
buf, n);
if (m) {
n -= m;
retval = -EFAULT;
}
comedi_buf_write_free(async, n);
count += n;
nbytes -= n;
buf += n;
break; /* makes device work like a pipe */
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&async->wait_head, &wait);
done:
return count ? count : retval;
}
static ssize_t comedi_read(struct file *file, char __user *buf, size_t nbytes,
loff_t *offset)
{
struct comedi_subdevice *s;
struct comedi_async *async;
int n, m, count = 0, retval = 0;
DECLARE_WAITQUEUE(wait, current);
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
if (!dev->attached) {
DPRINTK("no driver configured on comedi%i\n", dev->minor);
retval = -ENODEV;
goto done;
}
s = comedi_get_read_subdevice(dev_file_info);
if (s == NULL) {
retval = -EIO;
goto done;
}
async = s->async;
if (!nbytes) {
retval = 0;
goto done;
}
if (!s->busy) {
retval = 0;
goto done;
}
if (s->busy != file) {
retval = -EACCES;
goto done;
}
add_wait_queue(&async->wait_head, &wait);
while (nbytes > 0 && !retval) {
set_current_state(TASK_INTERRUPTIBLE);
n = nbytes;
m = comedi_buf_read_n_available(async);
/* printk("%d available\n",m); */
if (async->buf_read_ptr + m > async->prealloc_bufsz)
m = async->prealloc_bufsz - async->buf_read_ptr;
/* printk("%d contiguous\n",m); */
if (m < n)
n = m;
if (n == 0) {
if (!(comedi_get_subdevice_runflags(s) & SRF_RUNNING)) {
do_become_nonbusy(dev, s);
if (comedi_get_subdevice_runflags(s) &
SRF_ERROR) {
retval = -EPIPE;
} else {
retval = 0;
}
break;
}
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
schedule();
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (!s->busy) {
retval = 0;
break;
}
if (s->busy != file) {
retval = -EACCES;
break;
}
continue;
}
m = copy_to_user(buf, async->prealloc_buf +
async->buf_read_ptr, n);
if (m) {
n -= m;
retval = -EFAULT;
}
comedi_buf_read_alloc(async, n);
comedi_buf_read_free(async, n);
count += n;
nbytes -= n;
buf += n;
break; /* makes device work like a pipe */
}
if (!(comedi_get_subdevice_runflags(s) & (SRF_ERROR | SRF_RUNNING)) &&
async->buf_read_count - async->buf_write_count == 0) {
do_become_nonbusy(dev, s);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&async->wait_head, &wait);
done:
return count ? count : retval;
}
/*
This function restores a subdevice to an idle state.
*/
void do_become_nonbusy(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_async *async = s->async;
comedi_set_subdevice_runflags(s, SRF_RUNNING, 0);
if (async) {
comedi_reset_async_buf(async);
async->inttrig = NULL;
} else {
printk(KERN_ERR
"BUG: (?) do_become_nonbusy called with async=0\n");
}
s->busy = NULL;
}
static int comedi_open(struct inode *inode, struct file *file)
{
const unsigned minor = iminor(inode);
struct comedi_device_file_info *dev_file_info =
comedi_get_device_file_info(minor);
struct comedi_device *dev =
dev_file_info ? dev_file_info->device : NULL;
if (dev == NULL) {
DPRINTK("invalid minor number\n");
return -ENODEV;
}
/* This is slightly hacky, but we want module autoloading
* to work for root.
* case: user opens device, attached -> ok
* case: user opens device, unattached, in_request_module=0 -> autoload
* case: user opens device, unattached, in_request_module=1 -> fail
* case: root opens device, attached -> ok
* case: root opens device, unattached, in_request_module=1 -> ok
* (typically called from modprobe)
* case: root opens device, unattached, in_request_module=0 -> autoload
*
* The last could be changed to "-> ok", which would deny root
* autoloading.
*/
mutex_lock(&dev->mutex);
if (dev->attached)
goto ok;
if (!capable(CAP_NET_ADMIN) && dev->in_request_module) {
DPRINTK("in request module\n");
mutex_unlock(&dev->mutex);
return -ENODEV;
}
if (capable(CAP_NET_ADMIN) && dev->in_request_module)
goto ok;
dev->in_request_module = 1;
#ifdef CONFIG_KMOD
mutex_unlock(&dev->mutex);
request_module("char-major-%i-%i", COMEDI_MAJOR, dev->minor);
mutex_lock(&dev->mutex);
#endif
dev->in_request_module = 0;
if (!dev->attached && !capable(CAP_NET_ADMIN)) {
DPRINTK("not attached and not CAP_NET_ADMIN\n");
mutex_unlock(&dev->mutex);
return -ENODEV;
}
ok:
__module_get(THIS_MODULE);
if (dev->attached) {
if (!try_module_get(dev->driver->module)) {
module_put(THIS_MODULE);
mutex_unlock(&dev->mutex);
return -ENOSYS;
}
}
if (dev->attached && dev->use_count == 0 && dev->open) {
int rc = dev->open(dev);
if (rc < 0) {
module_put(dev->driver->module);
module_put(THIS_MODULE);
mutex_unlock(&dev->mutex);
return rc;
}
}
dev->use_count++;
mutex_unlock(&dev->mutex);
return 0;
}
static int comedi_close(struct inode *inode, struct file *file)
{
const unsigned minor = iminor(inode);
struct comedi_subdevice *s = NULL;
int i;
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
mutex_lock(&dev->mutex);
if (dev->subdevices) {
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
if (s->busy == file)
do_cancel(dev, s);
if (s->lock == file)
s->lock = NULL;
}
}
if (dev->attached && dev->use_count == 1 && dev->close)
dev->close(dev);
module_put(THIS_MODULE);
if (dev->attached)
module_put(dev->driver->module);
dev->use_count--;
mutex_unlock(&dev->mutex);
if (file->f_flags & FASYNC)
comedi_fasync(-1, file, 0);
return 0;
}
static int comedi_fasync(int fd, struct file *file, int on)
{
const unsigned minor = iminor(file->f_dentry->d_inode);
struct comedi_device_file_info *dev_file_info;
struct comedi_device *dev;
dev_file_info = comedi_get_device_file_info(minor);
if (dev_file_info == NULL)
return -ENODEV;
dev = dev_file_info->device;
if (dev == NULL)
return -ENODEV;
return fasync_helper(fd, file, on, &dev->async_queue);
}
const struct file_operations comedi_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = comedi_unlocked_ioctl,
.compat_ioctl = comedi_compat_ioctl,
.open = comedi_open,
.release = comedi_close,
.read = comedi_read,
.write = comedi_write,
.mmap = comedi_mmap,
.poll = comedi_poll,
.fasync = comedi_fasync,
.llseek = noop_llseek,
};
struct class *comedi_class;
static struct cdev comedi_cdev;
static void comedi_cleanup_legacy_minors(void)
{
unsigned i;
for (i = 0; i < comedi_num_legacy_minors; i++)
comedi_free_board_minor(i);
}
static int __init comedi_init(void)
{
int i;
int retval;
printk(KERN_INFO "comedi: version " COMEDI_RELEASE
" - http://www.comedi.org\n");
if (comedi_num_legacy_minors < 0 ||
comedi_num_legacy_minors > COMEDI_NUM_BOARD_MINORS) {
printk(KERN_ERR "comedi: error: invalid value for module "
"parameter \"comedi_num_legacy_minors\". Valid values "
"are 0 through %i.\n", COMEDI_NUM_BOARD_MINORS);
return -EINVAL;
}
/*
* comedi is unusable if both comedi_autoconfig and
* comedi_num_legacy_minors are zero, so we might as well adjust the
* defaults in that case
*/
if (comedi_autoconfig == 0 && comedi_num_legacy_minors == 0)
comedi_num_legacy_minors = 16;
memset(comedi_file_info_table, 0,
sizeof(struct comedi_device_file_info *) * COMEDI_NUM_MINORS);
retval = register_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS, "comedi");
if (retval)
return -EIO;
cdev_init(&comedi_cdev, &comedi_fops);
comedi_cdev.owner = THIS_MODULE;
kobject_set_name(&comedi_cdev.kobj, "comedi");
if (cdev_add(&comedi_cdev, MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS)) {
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return -EIO;
}
comedi_class = class_create(THIS_MODULE, "comedi");
if (IS_ERR(comedi_class)) {
printk(KERN_ERR "comedi: failed to create class");
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return PTR_ERR(comedi_class);
}
/* XXX requires /proc interface */
comedi_proc_init();
/* create devices files for legacy/manual use */
for (i = 0; i < comedi_num_legacy_minors; i++) {
int minor;
minor = comedi_alloc_board_minor(NULL);
if (minor < 0) {
comedi_cleanup_legacy_minors();
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
COMEDI_NUM_MINORS);
return minor;
}
}
return 0;
}
static void __exit comedi_cleanup(void)
{
int i;
comedi_cleanup_legacy_minors();
for (i = 0; i < COMEDI_NUM_MINORS; ++i)
BUG_ON(comedi_file_info_table[i]);
class_destroy(comedi_class);
cdev_del(&comedi_cdev);
unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS);
comedi_proc_cleanup();
}
module_init(comedi_init);
module_exit(comedi_cleanup);
void comedi_error(const struct comedi_device *dev, const char *s)
{
printk(KERN_ERR "comedi%d: %s: %s\n", dev->minor,
dev->driver->driver_name, s);
}
EXPORT_SYMBOL(comedi_error);
void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_async *async = s->async;
unsigned runflags = 0;
unsigned runflags_mask = 0;
/* DPRINTK("comedi_event 0x%x\n",mask); */
if ((comedi_get_subdevice_runflags(s) & SRF_RUNNING) == 0)
return;
if (s->
async->events & (COMEDI_CB_EOA | COMEDI_CB_ERROR |
COMEDI_CB_OVERFLOW)) {
runflags_mask |= SRF_RUNNING;
}
/* remember if an error event has occurred, so an error
* can be returned the next time the user does a read() */
if (s->async->events & (COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW)) {
runflags_mask |= SRF_ERROR;
runflags |= SRF_ERROR;
}
if (runflags_mask) {
/*sets SRF_ERROR and SRF_RUNNING together atomically */
comedi_set_subdevice_runflags(s, runflags_mask, runflags);
}
if (async->cb_mask & s->async->events) {
if (comedi_get_subdevice_runflags(s) & SRF_USER) {
wake_up_interruptible(&async->wait_head);
if (s->subdev_flags & SDF_CMD_READ)
kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
if (s->subdev_flags & SDF_CMD_WRITE)
kill_fasync(&dev->async_queue, SIGIO, POLL_OUT);
} else {
if (async->cb_func)
async->cb_func(s->async->events, async->cb_arg);
}
}
s->async->events = 0;
}
EXPORT_SYMBOL(comedi_event);
unsigned comedi_get_subdevice_runflags(struct comedi_subdevice *s)
{
unsigned long flags;
unsigned runflags;
spin_lock_irqsave(&s->spin_lock, flags);
runflags = s->runflags;
spin_unlock_irqrestore(&s->spin_lock, flags);
return runflags;
}
EXPORT_SYMBOL(comedi_get_subdevice_runflags);
static int is_device_busy(struct comedi_device *dev)
{
struct comedi_subdevice *s;
int i;
if (!dev->attached)
return 0;
for (i = 0; i < dev->n_subdevices; i++) {
s = dev->subdevices + i;
if (s->busy)
return 1;
if (s->async && s->async->mmap_count)
return 1;
}
return 0;
}
static void comedi_device_init(struct comedi_device *dev)
{
memset(dev, 0, sizeof(struct comedi_device));
spin_lock_init(&dev->spinlock);
mutex_init(&dev->mutex);
dev->minor = -1;
}
static void comedi_device_cleanup(struct comedi_device *dev)
{
if (dev == NULL)
return;
mutex_lock(&dev->mutex);
comedi_device_detach(dev);
mutex_unlock(&dev->mutex);
mutex_destroy(&dev->mutex);
}
int comedi_alloc_board_minor(struct device *hardware_device)
{
unsigned long flags;
struct comedi_device_file_info *info;
struct device *csdev;
unsigned i;
int retval;
info = kzalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
if (info == NULL)
return -ENOMEM;
info->device = kzalloc(sizeof(struct comedi_device), GFP_KERNEL);
if (info->device == NULL) {
kfree(info);
return -ENOMEM;
}
comedi_device_init(info->device);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
for (i = 0; i < COMEDI_NUM_BOARD_MINORS; ++i) {
if (comedi_file_info_table[i] == NULL) {
comedi_file_info_table[i] = info;
break;
}
}
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (i == COMEDI_NUM_BOARD_MINORS) {
comedi_device_cleanup(info->device);
kfree(info->device);
kfree(info);
printk(KERN_ERR
"comedi: error: "
"ran out of minor numbers for board device files.\n");
return -EBUSY;
}
info->device->minor = i;
csdev = device_create(comedi_class, hardware_device,
MKDEV(COMEDI_MAJOR, i), NULL, "comedi%i", i);
if (!IS_ERR(csdev))
info->device->class_dev = csdev;
dev_set_drvdata(csdev, info);
retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_read_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_read_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_write_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_write_buffer_kb.attr.name);
comedi_free_board_minor(i);
return retval;
}
return i;
}
void comedi_free_board_minor(unsigned minor)
{
unsigned long flags;
struct comedi_device_file_info *info;
BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[minor];
comedi_file_info_table[minor] = NULL;
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (info) {
struct comedi_device *dev = info->device;
if (dev) {
if (dev->class_dev) {
device_destroy(comedi_class,
MKDEV(COMEDI_MAJOR, dev->minor));
}
comedi_device_cleanup(dev);
kfree(dev);
}
kfree(info);
}
}
int comedi_alloc_subdevice_minor(struct comedi_device *dev,
struct comedi_subdevice *s)
{
unsigned long flags;
struct comedi_device_file_info *info;
struct device *csdev;
unsigned i;
int retval;
info = kmalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
if (info == NULL)
return -ENOMEM;
info->device = dev;
info->read_subdevice = s;
info->write_subdevice = s;
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
for (i = COMEDI_FIRST_SUBDEVICE_MINOR; i < COMEDI_NUM_MINORS; ++i) {
if (comedi_file_info_table[i] == NULL) {
comedi_file_info_table[i] = info;
break;
}
}
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (i == COMEDI_NUM_MINORS) {
kfree(info);
printk(KERN_ERR
"comedi: error: "
"ran out of minor numbers for board device files.\n");
return -EBUSY;
}
s->minor = i;
csdev = device_create(comedi_class, dev->class_dev,
MKDEV(COMEDI_MAJOR, i), NULL, "comedi%i_subd%i",
dev->minor, (int)(s - dev->subdevices));
if (!IS_ERR(csdev))
s->class_dev = csdev;
dev_set_drvdata(csdev, info);
retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_read_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_read_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_max_write_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
if (retval) {
printk(KERN_ERR
"comedi: "
"failed to create sysfs attribute file \"%s\".\n",
dev_attr_write_buffer_kb.attr.name);
comedi_free_subdevice_minor(s);
return retval;
}
return i;
}
void comedi_free_subdevice_minor(struct comedi_subdevice *s)
{
unsigned long flags;
struct comedi_device_file_info *info;
if (s == NULL)
return;
if (s->minor < 0)
return;
BUG_ON(s->minor >= COMEDI_NUM_MINORS);
BUG_ON(s->minor < COMEDI_FIRST_SUBDEVICE_MINOR);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[s->minor];
comedi_file_info_table[s->minor] = NULL;
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
if (s->class_dev) {
device_destroy(comedi_class, MKDEV(COMEDI_MAJOR, s->minor));
s->class_dev = NULL;
}
kfree(info);
}
struct comedi_device_file_info *comedi_get_device_file_info(unsigned minor)
{
unsigned long flags;
struct comedi_device_file_info *info;
BUG_ON(minor >= COMEDI_NUM_MINORS);
spin_lock_irqsave(&comedi_file_info_table_lock, flags);
info = comedi_file_info_table[minor];
spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
return info;
}
EXPORT_SYMBOL_GPL(comedi_get_device_file_info);
static int resize_async_buffer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_async *async, unsigned new_size)
{
int retval;
if (new_size > async->max_bufsize)
return -EPERM;
if (s->busy) {
DPRINTK("subdevice is busy, cannot resize buffer\n");
return -EBUSY;
}
if (async->mmap_count) {
DPRINTK("subdevice is mmapped, cannot resize buffer\n");
return -EBUSY;
}
if (!async->prealloc_buf)
return -EINVAL;
/* make sure buffer is an integral number of pages
* (we round up) */
new_size = (new_size + PAGE_SIZE - 1) & PAGE_MASK;
retval = comedi_buf_alloc(dev, s, new_size);
if (retval < 0)
return retval;
if (s->buf_change) {
retval = s->buf_change(dev, s, new_size);
if (retval < 0)
return retval;
}
DPRINTK("comedi%i subd %d buffer resized to %i bytes\n",
dev->minor, (int)(s - dev->subdevices), async->prealloc_bufsz);
return 0;
}
/* sysfs attribute files */
static const unsigned bytes_per_kibi = 1024;
static ssize_t show_max_read_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned max_buffer_size_kb = 0;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
mutex_lock(&info->device->mutex);
if (read_subdevice &&
(read_subdevice->subdev_flags & SDF_CMD_READ) &&
read_subdevice->async) {
max_buffer_size_kb = read_subdevice->async->max_bufsize /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_max_read_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_max_size_kb;
unsigned int new_max_size;
int ret;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
ret = kstrtouint(buf, 10, &new_max_size_kb);
if (ret)
return ret;
if (new_max_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_max_size = new_max_size_kb * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (read_subdevice == NULL ||
(read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
read_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
read_subdevice->async->max_bufsize = new_max_size;
mutex_unlock(&info->device->mutex);
return count;
}
static struct device_attribute dev_attr_max_read_buffer_kb = {
.attr = {
.name = "max_read_buffer_kb",
.mode = S_IRUGO | S_IWUSR},
.show = &show_max_read_buffer_kb,
.store = &store_max_read_buffer_kb
};
static ssize_t show_read_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned buffer_size_kb = 0;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
mutex_lock(&info->device->mutex);
if (read_subdevice &&
(read_subdevice->subdev_flags & SDF_CMD_READ) &&
read_subdevice->async) {
buffer_size_kb = read_subdevice->async->prealloc_bufsz /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_read_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_size_kb;
unsigned int new_size;
int retval;
int ret;
struct comedi_subdevice *const read_subdevice =
comedi_get_read_subdevice(info);
ret = kstrtouint(buf, 10, &new_size_kb);
if (ret)
return ret;
if (new_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_size = new_size_kb * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (read_subdevice == NULL ||
(read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
read_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
retval = resize_async_buffer(info->device, read_subdevice,
read_subdevice->async, new_size);
mutex_unlock(&info->device->mutex);
if (retval < 0)
return retval;
return count;
}
static struct device_attribute dev_attr_read_buffer_kb = {
.attr = {
.name = "read_buffer_kb",
.mode = S_IRUGO | S_IWUSR | S_IWGRP},
.show = &show_read_buffer_kb,
.store = &store_read_buffer_kb
};
static ssize_t show_max_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned max_buffer_size_kb = 0;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
mutex_lock(&info->device->mutex);
if (write_subdevice &&
(write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
write_subdevice->async) {
max_buffer_size_kb = write_subdevice->async->max_bufsize /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_max_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_max_size_kb;
unsigned int new_max_size;
int ret;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
ret = kstrtouint(buf, 10, &new_max_size_kb);
if (ret)
return ret;
if (new_max_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_max_size = new_max_size_kb * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (write_subdevice == NULL ||
(write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
write_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
write_subdevice->async->max_bufsize = new_max_size;
mutex_unlock(&info->device->mutex);
return count;
}
static struct device_attribute dev_attr_max_write_buffer_kb = {
.attr = {
.name = "max_write_buffer_kb",
.mode = S_IRUGO | S_IWUSR},
.show = &show_max_write_buffer_kb,
.store = &store_max_write_buffer_kb
};
static ssize_t show_write_buffer_kb(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t retval;
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned buffer_size_kb = 0;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
mutex_lock(&info->device->mutex);
if (write_subdevice &&
(write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
write_subdevice->async) {
buffer_size_kb = write_subdevice->async->prealloc_bufsz /
bytes_per_kibi;
}
retval = snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
mutex_unlock(&info->device->mutex);
return retval;
}
static ssize_t store_write_buffer_kb(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct comedi_device_file_info *info = dev_get_drvdata(dev);
unsigned int new_size_kb;
unsigned int new_size;
int retval;
int ret;
struct comedi_subdevice *const write_subdevice =
comedi_get_write_subdevice(info);
ret = kstrtouint(buf, 10, &new_size_kb);
if (ret)
return ret;
if (new_size_kb > (UINT_MAX / bytes_per_kibi))
return -EINVAL;
new_size = ((uint64_t) new_size_kb) * bytes_per_kibi;
mutex_lock(&info->device->mutex);
if (write_subdevice == NULL ||
(write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
write_subdevice->async == NULL) {
mutex_unlock(&info->device->mutex);
return -EINVAL;
}
retval = resize_async_buffer(info->device, write_subdevice,
write_subdevice->async, new_size);
mutex_unlock(&info->device->mutex);
if (retval < 0)
return retval;
return count;
}
static struct device_attribute dev_attr_write_buffer_kb = {
.attr = {
.name = "write_buffer_kb",
.mode = S_IRUGO | S_IWUSR | S_IWGRP},
.show = &show_write_buffer_kb,
.store = &store_write_buffer_kb
};
| gpl-2.0 |
omonar/linux | drivers/mfd/mc13xxx-i2c.c | 542 | 2848 | /*
* Copyright 2009-2010 Creative Product Design
* Marc Reilly marc@cpdesign.com.au
*
* 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/slab.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mfd/core.h>
#include <linux/mfd/mc13xxx.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include "mc13xxx.h"
static const struct i2c_device_id mc13xxx_i2c_device_id[] = {
{
.name = "mc13892",
.driver_data = (kernel_ulong_t)&mc13xxx_variant_mc13892,
}, {
.name = "mc34708",
.driver_data = (kernel_ulong_t)&mc13xxx_variant_mc34708,
}, {
/* sentinel */
}
};
MODULE_DEVICE_TABLE(i2c, mc13xxx_i2c_device_id);
static const struct of_device_id mc13xxx_dt_ids[] = {
{
.compatible = "fsl,mc13892",
.data = &mc13xxx_variant_mc13892,
}, {
.compatible = "fsl,mc34708",
.data = &mc13xxx_variant_mc34708,
}, {
/* sentinel */
}
};
MODULE_DEVICE_TABLE(of, mc13xxx_dt_ids);
static const struct regmap_config mc13xxx_regmap_i2c_config = {
.reg_bits = 8,
.val_bits = 24,
.max_register = MC13XXX_NUMREGS,
.cache_type = REGCACHE_NONE,
};
static int mc13xxx_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct mc13xxx *mc13xxx;
int ret;
mc13xxx = devm_kzalloc(&client->dev, sizeof(*mc13xxx), GFP_KERNEL);
if (!mc13xxx)
return -ENOMEM;
dev_set_drvdata(&client->dev, mc13xxx);
mc13xxx->irq = client->irq;
mc13xxx->regmap = devm_regmap_init_i2c(client,
&mc13xxx_regmap_i2c_config);
if (IS_ERR(mc13xxx->regmap)) {
ret = PTR_ERR(mc13xxx->regmap);
dev_err(&client->dev, "Failed to initialize regmap: %d\n", ret);
return ret;
}
if (client->dev.of_node) {
const struct of_device_id *of_id =
of_match_device(mc13xxx_dt_ids, &client->dev);
mc13xxx->variant = of_id->data;
} else {
mc13xxx->variant = (void *)id->driver_data;
}
return mc13xxx_common_init(&client->dev);
}
static int mc13xxx_i2c_remove(struct i2c_client *client)
{
return mc13xxx_common_exit(&client->dev);
}
static struct i2c_driver mc13xxx_i2c_driver = {
.id_table = mc13xxx_i2c_device_id,
.driver = {
.owner = THIS_MODULE,
.name = "mc13xxx",
.of_match_table = mc13xxx_dt_ids,
},
.probe = mc13xxx_i2c_probe,
.remove = mc13xxx_i2c_remove,
};
static int __init mc13xxx_i2c_init(void)
{
return i2c_add_driver(&mc13xxx_i2c_driver);
}
subsys_initcall(mc13xxx_i2c_init);
static void __exit mc13xxx_i2c_exit(void)
{
i2c_del_driver(&mc13xxx_i2c_driver);
}
module_exit(mc13xxx_i2c_exit);
MODULE_DESCRIPTION("i2c driver for Freescale MC13XXX PMIC");
MODULE_AUTHOR("Marc Reilly <marc@cpdesign.com.au");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
MoKee/android_kernel_htc_endeavoru | drivers/rtc/rtc-cmos.c | 542 | 29739 | /*
* RTC class driver for "CMOS RTC": PCs, ACPI, etc
*
* Copyright (C) 1996 Paul Gortmaker (drivers/char/rtc.c)
* Copyright (C) 2006 David Brownell (convert to new framework)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
/*
* The original "cmos clock" chip was an MC146818 chip, now obsolete.
* That defined the register interface now provided by all PCs, some
* non-PC systems, and incorporated into ACPI. Modern PC chipsets
* integrate an MC146818 clone in their southbridge, and boards use
* that instead of discrete clones like the DS12887 or M48T86. There
* are also clones that connect using the LPC bus.
*
* That register API is also used directly by various other drivers
* (notably for integrated NVRAM), infrastructure (x86 has code to
* bypass the RTC framework, directly reading the RTC during boot
* and updating minutes/seconds for systems using NTP synch) and
* utilities (like userspace 'hwclock', if no /dev node exists).
*
* So **ALL** calls to CMOS_READ and CMOS_WRITE must be done with
* interrupts disabled, holding the global rtc_lock, to exclude those
* other drivers and utilities on correctly configured systems.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
#include <linux/log2.h>
#include <linux/pm.h>
#include <linux/of.h>
#include <linux/of_platform.h>
/* this is for "generic access to PC-style RTC" using CMOS_READ/CMOS_WRITE */
#include <asm-generic/rtc.h>
struct cmos_rtc {
struct rtc_device *rtc;
struct device *dev;
int irq;
struct resource *iomem;
void (*wake_on)(struct device *);
void (*wake_off)(struct device *);
u8 enabled_wake;
u8 suspend_ctrl;
/* newer hardware extends the original register set */
u8 day_alrm;
u8 mon_alrm;
u8 century;
};
/* both platform and pnp busses use negative numbers for invalid irqs */
#define is_valid_irq(n) ((n) > 0)
static const char driver_name[] = "rtc_cmos";
/* The RTC_INTR register may have e.g. RTC_PF set even if RTC_PIE is clear;
* always mask it against the irq enable bits in RTC_CONTROL. Bit values
* are the same: PF==PIE, AF=AIE, UF=UIE; so RTC_IRQMASK works with both.
*/
#define RTC_IRQMASK (RTC_PF | RTC_AF | RTC_UF)
static inline int is_intr(u8 rtc_intr)
{
if (!(rtc_intr & RTC_IRQF))
return 0;
return rtc_intr & RTC_IRQMASK;
}
/*----------------------------------------------------------------*/
/* Much modern x86 hardware has HPETs (10+ MHz timers) which, because
* many BIOS programmers don't set up "sane mode" IRQ routing, are mostly
* used in a broken "legacy replacement" mode. The breakage includes
* HPET #1 hijacking the IRQ for this RTC, and being unavailable for
* other (better) use.
*
* When that broken mode is in use, platform glue provides a partial
* emulation of hardware RTC IRQ facilities using HPET #1. We don't
* want to use HPET for anything except those IRQs though...
*/
#ifdef CONFIG_HPET_EMULATE_RTC
#include <asm/hpet.h>
#else
static inline int is_hpet_enabled(void)
{
return 0;
}
static inline int hpet_mask_rtc_irq_bit(unsigned long mask)
{
return 0;
}
static inline int hpet_set_rtc_irq_bit(unsigned long mask)
{
return 0;
}
static inline int
hpet_set_alarm_time(unsigned char hrs, unsigned char min, unsigned char sec)
{
return 0;
}
static inline int hpet_set_periodic_freq(unsigned long freq)
{
return 0;
}
static inline int hpet_rtc_dropped_irq(void)
{
return 0;
}
static inline int hpet_rtc_timer_init(void)
{
return 0;
}
extern irq_handler_t hpet_rtc_interrupt;
static inline int hpet_register_irq_handler(irq_handler_t handler)
{
return 0;
}
static inline int hpet_unregister_irq_handler(irq_handler_t handler)
{
return 0;
}
#endif
/*----------------------------------------------------------------*/
#ifdef RTC_PORT
/* Most newer x86 systems have two register banks, the first used
* for RTC and NVRAM and the second only for NVRAM. Caller must
* own rtc_lock ... and we won't worry about access during NMI.
*/
#define can_bank2 true
static inline unsigned char cmos_read_bank2(unsigned char addr)
{
outb(addr, RTC_PORT(2));
return inb(RTC_PORT(3));
}
static inline void cmos_write_bank2(unsigned char val, unsigned char addr)
{
outb(addr, RTC_PORT(2));
outb(val, RTC_PORT(2));
}
#else
#define can_bank2 false
static inline unsigned char cmos_read_bank2(unsigned char addr)
{
return 0;
}
static inline void cmos_write_bank2(unsigned char val, unsigned char addr)
{
}
#endif
/*----------------------------------------------------------------*/
static int cmos_read_time(struct device *dev, struct rtc_time *t)
{
/* REVISIT: if the clock has a "century" register, use
* that instead of the heuristic in get_rtc_time().
* That'll make Y3K compatility (year > 2070) easy!
*/
get_rtc_time(t);
return 0;
}
static int cmos_set_time(struct device *dev, struct rtc_time *t)
{
/* REVISIT: set the "century" register if available
*
* NOTE: this ignores the issue whereby updating the seconds
* takes effect exactly 500ms after we write the register.
* (Also queueing and other delays before we get this far.)
*/
return set_rtc_time(t);
}
static int cmos_read_alarm(struct device *dev, struct rtc_wkalrm *t)
{
struct cmos_rtc *cmos = dev_get_drvdata(dev);
unsigned char rtc_control;
if (!is_valid_irq(cmos->irq))
return -EIO;
/* Basic alarms only support hour, minute, and seconds fields.
* Some also support day and month, for alarms up to a year in
* the future.
*/
t->time.tm_mday = -1;
t->time.tm_mon = -1;
spin_lock_irq(&rtc_lock);
t->time.tm_sec = CMOS_READ(RTC_SECONDS_ALARM);
t->time.tm_min = CMOS_READ(RTC_MINUTES_ALARM);
t->time.tm_hour = CMOS_READ(RTC_HOURS_ALARM);
if (cmos->day_alrm) {
/* ignore upper bits on readback per ACPI spec */
t->time.tm_mday = CMOS_READ(cmos->day_alrm) & 0x3f;
if (!t->time.tm_mday)
t->time.tm_mday = -1;
if (cmos->mon_alrm) {
t->time.tm_mon = CMOS_READ(cmos->mon_alrm);
if (!t->time.tm_mon)
t->time.tm_mon = -1;
}
}
rtc_control = CMOS_READ(RTC_CONTROL);
spin_unlock_irq(&rtc_lock);
if (!(rtc_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
if (((unsigned)t->time.tm_sec) < 0x60)
t->time.tm_sec = bcd2bin(t->time.tm_sec);
else
t->time.tm_sec = -1;
if (((unsigned)t->time.tm_min) < 0x60)
t->time.tm_min = bcd2bin(t->time.tm_min);
else
t->time.tm_min = -1;
if (((unsigned)t->time.tm_hour) < 0x24)
t->time.tm_hour = bcd2bin(t->time.tm_hour);
else
t->time.tm_hour = -1;
if (cmos->day_alrm) {
if (((unsigned)t->time.tm_mday) <= 0x31)
t->time.tm_mday = bcd2bin(t->time.tm_mday);
else
t->time.tm_mday = -1;
if (cmos->mon_alrm) {
if (((unsigned)t->time.tm_mon) <= 0x12)
t->time.tm_mon = bcd2bin(t->time.tm_mon)-1;
else
t->time.tm_mon = -1;
}
}
}
t->time.tm_year = -1;
t->enabled = !!(rtc_control & RTC_AIE);
t->pending = 0;
return 0;
}
static void cmos_checkintr(struct cmos_rtc *cmos, unsigned char rtc_control)
{
unsigned char rtc_intr;
/* NOTE after changing RTC_xIE bits we always read INTR_FLAGS;
* allegedly some older rtcs need that to handle irqs properly
*/
rtc_intr = CMOS_READ(RTC_INTR_FLAGS);
if (is_hpet_enabled())
return;
rtc_intr &= (rtc_control & RTC_IRQMASK) | RTC_IRQF;
if (is_intr(rtc_intr))
rtc_update_irq(cmos->rtc, 1, rtc_intr);
}
static void cmos_irq_enable(struct cmos_rtc *cmos, unsigned char mask)
{
unsigned char rtc_control;
/* flush any pending IRQ status, notably for update irqs,
* before we enable new IRQs
*/
rtc_control = CMOS_READ(RTC_CONTROL);
cmos_checkintr(cmos, rtc_control);
rtc_control |= mask;
CMOS_WRITE(rtc_control, RTC_CONTROL);
hpet_set_rtc_irq_bit(mask);
cmos_checkintr(cmos, rtc_control);
}
static void cmos_irq_disable(struct cmos_rtc *cmos, unsigned char mask)
{
unsigned char rtc_control;
rtc_control = CMOS_READ(RTC_CONTROL);
rtc_control &= ~mask;
CMOS_WRITE(rtc_control, RTC_CONTROL);
hpet_mask_rtc_irq_bit(mask);
cmos_checkintr(cmos, rtc_control);
}
static int cmos_set_alarm(struct device *dev, struct rtc_wkalrm *t)
{
struct cmos_rtc *cmos = dev_get_drvdata(dev);
unsigned char mon, mday, hrs, min, sec, rtc_control;
if (!is_valid_irq(cmos->irq))
return -EIO;
mon = t->time.tm_mon + 1;
mday = t->time.tm_mday;
hrs = t->time.tm_hour;
min = t->time.tm_min;
sec = t->time.tm_sec;
rtc_control = CMOS_READ(RTC_CONTROL);
if (!(rtc_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
/* Writing 0xff means "don't care" or "match all". */
mon = (mon <= 12) ? bin2bcd(mon) : 0xff;
mday = (mday >= 1 && mday <= 31) ? bin2bcd(mday) : 0xff;
hrs = (hrs < 24) ? bin2bcd(hrs) : 0xff;
min = (min < 60) ? bin2bcd(min) : 0xff;
sec = (sec < 60) ? bin2bcd(sec) : 0xff;
}
spin_lock_irq(&rtc_lock);
/* next rtc irq must not be from previous alarm setting */
cmos_irq_disable(cmos, RTC_AIE);
/* update alarm */
CMOS_WRITE(hrs, RTC_HOURS_ALARM);
CMOS_WRITE(min, RTC_MINUTES_ALARM);
CMOS_WRITE(sec, RTC_SECONDS_ALARM);
/* the system may support an "enhanced" alarm */
if (cmos->day_alrm) {
CMOS_WRITE(mday, cmos->day_alrm);
if (cmos->mon_alrm)
CMOS_WRITE(mon, cmos->mon_alrm);
}
/* FIXME the HPET alarm glue currently ignores day_alrm
* and mon_alrm ...
*/
hpet_set_alarm_time(t->time.tm_hour, t->time.tm_min, t->time.tm_sec);
if (t->enabled)
cmos_irq_enable(cmos, RTC_AIE);
spin_unlock_irq(&rtc_lock);
return 0;
}
static int cmos_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct cmos_rtc *cmos = dev_get_drvdata(dev);
unsigned long flags;
if (!is_valid_irq(cmos->irq))
return -EINVAL;
spin_lock_irqsave(&rtc_lock, flags);
if (enabled)
cmos_irq_enable(cmos, RTC_AIE);
else
cmos_irq_disable(cmos, RTC_AIE);
spin_unlock_irqrestore(&rtc_lock, flags);
return 0;
}
#if defined(CONFIG_RTC_INTF_PROC) || defined(CONFIG_RTC_INTF_PROC_MODULE)
static int cmos_procfs(struct device *dev, struct seq_file *seq)
{
struct cmos_rtc *cmos = dev_get_drvdata(dev);
unsigned char rtc_control, valid;
spin_lock_irq(&rtc_lock);
rtc_control = CMOS_READ(RTC_CONTROL);
valid = CMOS_READ(RTC_VALID);
spin_unlock_irq(&rtc_lock);
/* NOTE: at least ICH6 reports battery status using a different
* (non-RTC) bit; and SQWE is ignored on many current systems.
*/
return seq_printf(seq,
"periodic_IRQ\t: %s\n"
"update_IRQ\t: %s\n"
"HPET_emulated\t: %s\n"
// "square_wave\t: %s\n"
"BCD\t\t: %s\n"
"DST_enable\t: %s\n"
"periodic_freq\t: %d\n"
"batt_status\t: %s\n",
(rtc_control & RTC_PIE) ? "yes" : "no",
(rtc_control & RTC_UIE) ? "yes" : "no",
is_hpet_enabled() ? "yes" : "no",
// (rtc_control & RTC_SQWE) ? "yes" : "no",
(rtc_control & RTC_DM_BINARY) ? "no" : "yes",
(rtc_control & RTC_DST_EN) ? "yes" : "no",
cmos->rtc->irq_freq,
(valid & RTC_VRT) ? "okay" : "dead");
}
#else
#define cmos_procfs NULL
#endif
static const struct rtc_class_ops cmos_rtc_ops = {
.read_time = cmos_read_time,
.set_time = cmos_set_time,
.read_alarm = cmos_read_alarm,
.set_alarm = cmos_set_alarm,
.proc = cmos_procfs,
.alarm_irq_enable = cmos_alarm_irq_enable,
};
/*----------------------------------------------------------------*/
/*
* All these chips have at least 64 bytes of address space, shared by
* RTC registers and NVRAM. Most of those bytes of NVRAM are used
* by boot firmware. Modern chips have 128 or 256 bytes.
*/
#define NVRAM_OFFSET (RTC_REG_D + 1)
static ssize_t
cmos_nvram_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
int retval;
if (unlikely(off >= attr->size))
return 0;
if (unlikely(off < 0))
return -EINVAL;
if ((off + count) > attr->size)
count = attr->size - off;
off += NVRAM_OFFSET;
spin_lock_irq(&rtc_lock);
for (retval = 0; count; count--, off++, retval++) {
if (off < 128)
*buf++ = CMOS_READ(off);
else if (can_bank2)
*buf++ = cmos_read_bank2(off);
else
break;
}
spin_unlock_irq(&rtc_lock);
return retval;
}
static ssize_t
cmos_nvram_write(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct cmos_rtc *cmos;
int retval;
cmos = dev_get_drvdata(container_of(kobj, struct device, kobj));
if (unlikely(off >= attr->size))
return -EFBIG;
if (unlikely(off < 0))
return -EINVAL;
if ((off + count) > attr->size)
count = attr->size - off;
/* NOTE: on at least PCs and Ataris, the boot firmware uses a
* checksum on part of the NVRAM data. That's currently ignored
* here. If userspace is smart enough to know what fields of
* NVRAM to update, updating checksums is also part of its job.
*/
off += NVRAM_OFFSET;
spin_lock_irq(&rtc_lock);
for (retval = 0; count; count--, off++, retval++) {
/* don't trash RTC registers */
if (off == cmos->day_alrm
|| off == cmos->mon_alrm
|| off == cmos->century)
buf++;
else if (off < 128)
CMOS_WRITE(*buf++, off);
else if (can_bank2)
cmos_write_bank2(*buf++, off);
else
break;
}
spin_unlock_irq(&rtc_lock);
return retval;
}
static struct bin_attribute nvram = {
.attr = {
.name = "nvram",
.mode = S_IRUGO | S_IWUSR,
},
.read = cmos_nvram_read,
.write = cmos_nvram_write,
/* size gets set up later */
};
/*----------------------------------------------------------------*/
static struct cmos_rtc cmos_rtc;
static irqreturn_t cmos_interrupt(int irq, void *p)
{
u8 irqstat;
u8 rtc_control;
spin_lock(&rtc_lock);
/* When the HPET interrupt handler calls us, the interrupt
* status is passed as arg1 instead of the irq number. But
* always clear irq status, even when HPET is in the way.
*
* Note that HPET and RTC are almost certainly out of phase,
* giving different IRQ status ...
*/
irqstat = CMOS_READ(RTC_INTR_FLAGS);
rtc_control = CMOS_READ(RTC_CONTROL);
if (is_hpet_enabled())
irqstat = (unsigned long)irq & 0xF0;
irqstat &= (rtc_control & RTC_IRQMASK) | RTC_IRQF;
/* All Linux RTC alarms should be treated as if they were oneshot.
* Similar code may be needed in system wakeup paths, in case the
* alarm woke the system.
*/
if (irqstat & RTC_AIE) {
rtc_control &= ~RTC_AIE;
CMOS_WRITE(rtc_control, RTC_CONTROL);
hpet_mask_rtc_irq_bit(RTC_AIE);
CMOS_READ(RTC_INTR_FLAGS);
}
spin_unlock(&rtc_lock);
if (is_intr(irqstat)) {
rtc_update_irq(p, 1, irqstat);
return IRQ_HANDLED;
} else
return IRQ_NONE;
}
#ifdef CONFIG_PNP
#define INITSECTION
#else
#define INITSECTION __init
#endif
static int INITSECTION
cmos_do_probe(struct device *dev, struct resource *ports, int rtc_irq)
{
struct cmos_rtc_board_info *info = dev->platform_data;
int retval = 0;
unsigned char rtc_control;
unsigned address_space;
/* there can be only one ... */
if (cmos_rtc.dev)
return -EBUSY;
if (!ports)
return -ENODEV;
/* Claim I/O ports ASAP, minimizing conflict with legacy driver.
*
* REVISIT non-x86 systems may instead use memory space resources
* (needing ioremap etc), not i/o space resources like this ...
*/
ports = request_region(ports->start,
resource_size(ports),
driver_name);
if (!ports) {
dev_dbg(dev, "i/o registers already in use\n");
return -EBUSY;
}
cmos_rtc.irq = rtc_irq;
cmos_rtc.iomem = ports;
/* Heuristic to deduce NVRAM size ... do what the legacy NVRAM
* driver did, but don't reject unknown configs. Old hardware
* won't address 128 bytes. Newer chips have multiple banks,
* though they may not be listed in one I/O resource.
*/
#if defined(CONFIG_ATARI)
address_space = 64;
#elif defined(__i386__) || defined(__x86_64__) || defined(__arm__) \
|| defined(__sparc__) || defined(__mips__) \
|| defined(__powerpc__)
address_space = 128;
#else
#warning Assuming 128 bytes of RTC+NVRAM address space, not 64 bytes.
address_space = 128;
#endif
if (can_bank2 && ports->end > (ports->start + 1))
address_space = 256;
/* For ACPI systems extension info comes from the FADT. On others,
* board specific setup provides it as appropriate. Systems where
* the alarm IRQ isn't automatically a wakeup IRQ (like ACPI, and
* some almost-clones) can provide hooks to make that behave.
*
* Note that ACPI doesn't preclude putting these registers into
* "extended" areas of the chip, including some that we won't yet
* expect CMOS_READ and friends to handle.
*/
if (info) {
if (info->rtc_day_alarm && info->rtc_day_alarm < 128)
cmos_rtc.day_alrm = info->rtc_day_alarm;
if (info->rtc_mon_alarm && info->rtc_mon_alarm < 128)
cmos_rtc.mon_alrm = info->rtc_mon_alarm;
if (info->rtc_century && info->rtc_century < 128)
cmos_rtc.century = info->rtc_century;
if (info->wake_on && info->wake_off) {
cmos_rtc.wake_on = info->wake_on;
cmos_rtc.wake_off = info->wake_off;
}
}
cmos_rtc.dev = dev;
dev_set_drvdata(dev, &cmos_rtc);
cmos_rtc.rtc = rtc_device_register(driver_name, dev,
&cmos_rtc_ops, THIS_MODULE);
if (IS_ERR(cmos_rtc.rtc)) {
retval = PTR_ERR(cmos_rtc.rtc);
goto cleanup0;
}
rename_region(ports, dev_name(&cmos_rtc.rtc->dev));
spin_lock_irq(&rtc_lock);
/* force periodic irq to CMOS reset default of 1024Hz;
*
* REVISIT it's been reported that at least one x86_64 ALI mobo
* doesn't use 32KHz here ... for portability we might need to
* do something about other clock frequencies.
*/
cmos_rtc.rtc->irq_freq = 1024;
hpet_set_periodic_freq(cmos_rtc.rtc->irq_freq);
CMOS_WRITE(RTC_REF_CLCK_32KHZ | 0x06, RTC_FREQ_SELECT);
/* disable irqs */
cmos_irq_disable(&cmos_rtc, RTC_PIE | RTC_AIE | RTC_UIE);
rtc_control = CMOS_READ(RTC_CONTROL);
spin_unlock_irq(&rtc_lock);
/* FIXME:
* <asm-generic/rtc.h> doesn't know 12-hour mode either.
*/
if (is_valid_irq(rtc_irq) && !(rtc_control & RTC_24H)) {
dev_warn(dev, "only 24-hr supported\n");
retval = -ENXIO;
goto cleanup1;
}
if (is_valid_irq(rtc_irq)) {
irq_handler_t rtc_cmos_int_handler;
if (is_hpet_enabled()) {
int err;
rtc_cmos_int_handler = hpet_rtc_interrupt;
err = hpet_register_irq_handler(cmos_interrupt);
if (err != 0) {
printk(KERN_WARNING "hpet_register_irq_handler "
" failed in rtc_init().");
goto cleanup1;
}
} else
rtc_cmos_int_handler = cmos_interrupt;
retval = request_irq(rtc_irq, rtc_cmos_int_handler,
IRQF_DISABLED, dev_name(&cmos_rtc.rtc->dev),
cmos_rtc.rtc);
if (retval < 0) {
dev_dbg(dev, "IRQ %d is already in use\n", rtc_irq);
goto cleanup1;
}
}
hpet_rtc_timer_init();
/* export at least the first block of NVRAM */
nvram.size = address_space - NVRAM_OFFSET;
retval = sysfs_create_bin_file(&dev->kobj, &nvram);
if (retval < 0) {
dev_dbg(dev, "can't create nvram file? %d\n", retval);
goto cleanup2;
}
pr_info("%s: %s%s, %zd bytes nvram%s\n",
dev_name(&cmos_rtc.rtc->dev),
!is_valid_irq(rtc_irq) ? "no alarms" :
cmos_rtc.mon_alrm ? "alarms up to one year" :
cmos_rtc.day_alrm ? "alarms up to one month" :
"alarms up to one day",
cmos_rtc.century ? ", y3k" : "",
nvram.size,
is_hpet_enabled() ? ", hpet irqs" : "");
return 0;
cleanup2:
if (is_valid_irq(rtc_irq))
free_irq(rtc_irq, cmos_rtc.rtc);
cleanup1:
cmos_rtc.dev = NULL;
rtc_device_unregister(cmos_rtc.rtc);
cleanup0:
release_region(ports->start, resource_size(ports));
return retval;
}
static void cmos_do_shutdown(void)
{
spin_lock_irq(&rtc_lock);
cmos_irq_disable(&cmos_rtc, RTC_IRQMASK);
spin_unlock_irq(&rtc_lock);
}
static void __exit cmos_do_remove(struct device *dev)
{
struct cmos_rtc *cmos = dev_get_drvdata(dev);
struct resource *ports;
cmos_do_shutdown();
sysfs_remove_bin_file(&dev->kobj, &nvram);
if (is_valid_irq(cmos->irq)) {
free_irq(cmos->irq, cmos->rtc);
hpet_unregister_irq_handler(cmos_interrupt);
}
rtc_device_unregister(cmos->rtc);
cmos->rtc = NULL;
ports = cmos->iomem;
release_region(ports->start, resource_size(ports));
cmos->iomem = NULL;
cmos->dev = NULL;
dev_set_drvdata(dev, NULL);
}
#ifdef CONFIG_PM
static int cmos_suspend(struct device *dev)
{
struct cmos_rtc *cmos = dev_get_drvdata(dev);
unsigned char tmp;
/* only the alarm might be a wakeup event source */
spin_lock_irq(&rtc_lock);
cmos->suspend_ctrl = tmp = CMOS_READ(RTC_CONTROL);
if (tmp & (RTC_PIE|RTC_AIE|RTC_UIE)) {
unsigned char mask;
if (device_may_wakeup(dev))
mask = RTC_IRQMASK & ~RTC_AIE;
else
mask = RTC_IRQMASK;
tmp &= ~mask;
CMOS_WRITE(tmp, RTC_CONTROL);
/* shut down hpet emulation - we don't need it for alarm */
hpet_mask_rtc_irq_bit(RTC_PIE|RTC_AIE|RTC_UIE);
cmos_checkintr(cmos, tmp);
}
spin_unlock_irq(&rtc_lock);
if (tmp & RTC_AIE) {
cmos->enabled_wake = 1;
if (cmos->wake_on)
cmos->wake_on(dev);
else
enable_irq_wake(cmos->irq);
}
pr_debug("%s: suspend%s, ctrl %02x\n",
dev_name(&cmos_rtc.rtc->dev),
(tmp & RTC_AIE) ? ", alarm may wake" : "",
tmp);
return 0;
}
/* We want RTC alarms to wake us from e.g. ACPI G2/S5 "soft off", even
* after a detour through G3 "mechanical off", although the ACPI spec
* says wakeup should only work from G1/S4 "hibernate". To most users,
* distinctions between S4 and S5 are pointless. So when the hardware
* allows, don't draw that distinction.
*/
static inline int cmos_poweroff(struct device *dev)
{
return cmos_suspend(dev);
}
static int cmos_resume(struct device *dev)
{
struct cmos_rtc *cmos = dev_get_drvdata(dev);
unsigned char tmp = cmos->suspend_ctrl;
/* re-enable any irqs previously active */
if (tmp & RTC_IRQMASK) {
unsigned char mask;
if (cmos->enabled_wake) {
if (cmos->wake_off)
cmos->wake_off(dev);
else
disable_irq_wake(cmos->irq);
cmos->enabled_wake = 0;
}
spin_lock_irq(&rtc_lock);
do {
CMOS_WRITE(tmp, RTC_CONTROL);
hpet_set_rtc_irq_bit(tmp & RTC_IRQMASK);
mask = CMOS_READ(RTC_INTR_FLAGS);
mask &= (tmp & RTC_IRQMASK) | RTC_IRQF;
if (!is_hpet_enabled() || !is_intr(mask))
break;
/* force one-shot behavior if HPET blocked
* the wake alarm's irq
*/
rtc_update_irq(cmos->rtc, 1, mask);
tmp &= ~RTC_AIE;
hpet_mask_rtc_irq_bit(RTC_AIE);
} while (mask & RTC_AIE);
spin_unlock_irq(&rtc_lock);
}
pr_debug("%s: resume, ctrl %02x\n",
dev_name(&cmos_rtc.rtc->dev),
tmp);
return 0;
}
static SIMPLE_DEV_PM_OPS(cmos_pm_ops, cmos_suspend, cmos_resume);
#else
static inline int cmos_poweroff(struct device *dev)
{
return -ENOSYS;
}
#endif
/*----------------------------------------------------------------*/
/* On non-x86 systems, a "CMOS" RTC lives most naturally on platform_bus.
* ACPI systems always list these as PNPACPI devices, and pre-ACPI PCs
* probably list them in similar PNPBIOS tables; so PNP is more common.
*
* We don't use legacy "poke at the hardware" probing. Ancient PCs that
* predate even PNPBIOS should set up platform_bus devices.
*/
#ifdef CONFIG_ACPI
#include <linux/acpi.h>
static u32 rtc_handler(void *context)
{
acpi_clear_event(ACPI_EVENT_RTC);
acpi_disable_event(ACPI_EVENT_RTC, 0);
return ACPI_INTERRUPT_HANDLED;
}
static inline void rtc_wake_setup(void)
{
acpi_install_fixed_event_handler(ACPI_EVENT_RTC, rtc_handler, NULL);
/*
* After the RTC handler is installed, the Fixed_RTC event should
* be disabled. Only when the RTC alarm is set will it be enabled.
*/
acpi_clear_event(ACPI_EVENT_RTC);
acpi_disable_event(ACPI_EVENT_RTC, 0);
}
static void rtc_wake_on(struct device *dev)
{
acpi_clear_event(ACPI_EVENT_RTC);
acpi_enable_event(ACPI_EVENT_RTC, 0);
}
static void rtc_wake_off(struct device *dev)
{
acpi_disable_event(ACPI_EVENT_RTC, 0);
}
/* Every ACPI platform has a mc146818 compatible "cmos rtc". Here we find
* its device node and pass extra config data. This helps its driver use
* capabilities that the now-obsolete mc146818 didn't have, and informs it
* that this board's RTC is wakeup-capable (per ACPI spec).
*/
static struct cmos_rtc_board_info acpi_rtc_info;
static void __devinit
cmos_wake_setup(struct device *dev)
{
if (acpi_disabled)
return;
rtc_wake_setup();
acpi_rtc_info.wake_on = rtc_wake_on;
acpi_rtc_info.wake_off = rtc_wake_off;
/* workaround bug in some ACPI tables */
if (acpi_gbl_FADT.month_alarm && !acpi_gbl_FADT.day_alarm) {
dev_dbg(dev, "bogus FADT month_alarm (%d)\n",
acpi_gbl_FADT.month_alarm);
acpi_gbl_FADT.month_alarm = 0;
}
acpi_rtc_info.rtc_day_alarm = acpi_gbl_FADT.day_alarm;
acpi_rtc_info.rtc_mon_alarm = acpi_gbl_FADT.month_alarm;
acpi_rtc_info.rtc_century = acpi_gbl_FADT.century;
/* NOTE: S4_RTC_WAKE is NOT currently useful to Linux */
if (acpi_gbl_FADT.flags & ACPI_FADT_S4_RTC_WAKE)
dev_info(dev, "RTC can wake from S4\n");
dev->platform_data = &acpi_rtc_info;
/* RTC always wakes from S1/S2/S3, and often S4/STD */
device_init_wakeup(dev, 1);
}
#else
static void __devinit
cmos_wake_setup(struct device *dev)
{
}
#endif
#ifdef CONFIG_PNP
#include <linux/pnp.h>
static int __devinit
cmos_pnp_probe(struct pnp_dev *pnp, const struct pnp_device_id *id)
{
cmos_wake_setup(&pnp->dev);
if (pnp_port_start(pnp,0) == 0x70 && !pnp_irq_valid(pnp,0))
/* Some machines contain a PNP entry for the RTC, but
* don't define the IRQ. It should always be safe to
* hardcode it in these cases
*/
return cmos_do_probe(&pnp->dev,
pnp_get_resource(pnp, IORESOURCE_IO, 0), 8);
else
return cmos_do_probe(&pnp->dev,
pnp_get_resource(pnp, IORESOURCE_IO, 0),
pnp_irq(pnp, 0));
}
static void __exit cmos_pnp_remove(struct pnp_dev *pnp)
{
cmos_do_remove(&pnp->dev);
}
#ifdef CONFIG_PM
static int cmos_pnp_suspend(struct pnp_dev *pnp, pm_message_t mesg)
{
return cmos_suspend(&pnp->dev);
}
static int cmos_pnp_resume(struct pnp_dev *pnp)
{
return cmos_resume(&pnp->dev);
}
#else
#define cmos_pnp_suspend NULL
#define cmos_pnp_resume NULL
#endif
static void cmos_pnp_shutdown(struct pnp_dev *pnp)
{
if (system_state == SYSTEM_POWER_OFF && !cmos_poweroff(&pnp->dev))
return;
cmos_do_shutdown();
}
static const struct pnp_device_id rtc_ids[] = {
{ .id = "PNP0b00", },
{ .id = "PNP0b01", },
{ .id = "PNP0b02", },
{ },
};
MODULE_DEVICE_TABLE(pnp, rtc_ids);
static struct pnp_driver cmos_pnp_driver = {
.name = (char *) driver_name,
.id_table = rtc_ids,
.probe = cmos_pnp_probe,
.remove = __exit_p(cmos_pnp_remove),
.shutdown = cmos_pnp_shutdown,
/* flag ensures resume() gets called, and stops syslog spam */
.flags = PNP_DRIVER_RES_DO_NOT_CHANGE,
.suspend = cmos_pnp_suspend,
.resume = cmos_pnp_resume,
};
#endif /* CONFIG_PNP */
#ifdef CONFIG_OF
static const struct of_device_id of_cmos_match[] = {
{
.compatible = "motorola,mc146818",
},
{ },
};
MODULE_DEVICE_TABLE(of, of_cmos_match);
static __init void cmos_of_init(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
struct rtc_time time;
int ret;
const __be32 *val;
if (!node)
return;
val = of_get_property(node, "ctrl-reg", NULL);
if (val)
CMOS_WRITE(be32_to_cpup(val), RTC_CONTROL);
val = of_get_property(node, "freq-reg", NULL);
if (val)
CMOS_WRITE(be32_to_cpup(val), RTC_FREQ_SELECT);
get_rtc_time(&time);
ret = rtc_valid_tm(&time);
if (ret) {
struct rtc_time def_time = {
.tm_year = 1,
.tm_mday = 1,
};
set_rtc_time(&def_time);
}
}
#else
static inline void cmos_of_init(struct platform_device *pdev) {}
#define of_cmos_match NULL
#endif
/*----------------------------------------------------------------*/
/* Platform setup should have set up an RTC device, when PNP is
* unavailable ... this could happen even on (older) PCs.
*/
static int __init cmos_platform_probe(struct platform_device *pdev)
{
cmos_of_init(pdev);
cmos_wake_setup(&pdev->dev);
return cmos_do_probe(&pdev->dev,
platform_get_resource(pdev, IORESOURCE_IO, 0),
platform_get_irq(pdev, 0));
}
static int __exit cmos_platform_remove(struct platform_device *pdev)
{
cmos_do_remove(&pdev->dev);
return 0;
}
static void cmos_platform_shutdown(struct platform_device *pdev)
{
if (system_state == SYSTEM_POWER_OFF && !cmos_poweroff(&pdev->dev))
return;
cmos_do_shutdown();
}
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:rtc_cmos");
static struct platform_driver cmos_platform_driver = {
.remove = __exit_p(cmos_platform_remove),
.shutdown = cmos_platform_shutdown,
.driver = {
.name = (char *) driver_name,
#ifdef CONFIG_PM
.pm = &cmos_pm_ops,
#endif
.of_match_table = of_cmos_match,
}
};
#ifdef CONFIG_PNP
static bool pnp_driver_registered;
#endif
static bool platform_driver_registered;
static int __init cmos_init(void)
{
int retval = 0;
#ifdef CONFIG_PNP
retval = pnp_register_driver(&cmos_pnp_driver);
if (retval == 0)
pnp_driver_registered = true;
#endif
if (!cmos_rtc.dev) {
retval = platform_driver_probe(&cmos_platform_driver,
cmos_platform_probe);
if (retval == 0)
platform_driver_registered = true;
}
if (retval == 0)
return 0;
#ifdef CONFIG_PNP
if (pnp_driver_registered)
pnp_unregister_driver(&cmos_pnp_driver);
#endif
return retval;
}
module_init(cmos_init);
static void __exit cmos_exit(void)
{
#ifdef CONFIG_PNP
if (pnp_driver_registered)
pnp_unregister_driver(&cmos_pnp_driver);
#endif
if (platform_driver_registered)
platform_driver_unregister(&cmos_platform_driver);
}
module_exit(cmos_exit);
MODULE_AUTHOR("David Brownell");
MODULE_DESCRIPTION("Driver for PC-style 'CMOS' RTCs");
MODULE_LICENSE("GPL");
| gpl-2.0 |
telf/error_state_capture_improvement | drivers/media/dvb-frontends/si2165.c | 542 | 24413 | /*
Driver for Silicon Labs Si2161 DVB-T and Si2165 DVB-C/-T Demodulator
Copyright (C) 2013-2014 Matthias Schwarzott <zzam@gentoo.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.
References:
http://www.silabs.com/Support%20Documents/TechnicalDocs/Si2165-short.pdf
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/firmware.h>
#include "dvb_frontend.h"
#include "dvb_math.h"
#include "si2165_priv.h"
#include "si2165.h"
/* Hauppauge WinTV-HVR-930C-HD B130 / PCTV QuatroStick 521e 1113xx
* uses 16 MHz xtal */
/* Hauppauge WinTV-HVR-930C-HD B131 / PCTV QuatroStick 522e 1114xx
* uses 24 MHz clock provided by tuner */
struct si2165_state {
struct i2c_adapter *i2c;
struct dvb_frontend frontend;
struct si2165_config config;
u8 chip_revcode;
u8 chip_type;
/* calculated by xtal and div settings */
u32 fvco_hz;
u32 sys_clk;
u32 adc_clk;
bool has_dvbc;
bool has_dvbt;
bool firmware_loaded;
};
#define DEBUG_OTHER 0x01
#define DEBUG_I2C_WRITE 0x02
#define DEBUG_I2C_READ 0x04
#define DEBUG_REG_READ 0x08
#define DEBUG_REG_WRITE 0x10
#define DEBUG_FW_LOAD 0x20
static int debug = 0x00;
#define dprintk(args...) \
do { \
if (debug & DEBUG_OTHER) \
printk(KERN_DEBUG "si2165: " args); \
} while (0)
#define deb_i2c_write(args...) \
do { \
if (debug & DEBUG_I2C_WRITE) \
printk(KERN_DEBUG "si2165: i2c write: " args); \
} while (0)
#define deb_i2c_read(args...) \
do { \
if (debug & DEBUG_I2C_READ) \
printk(KERN_DEBUG "si2165: i2c read: " args); \
} while (0)
#define deb_readreg(args...) \
do { \
if (debug & DEBUG_REG_READ) \
printk(KERN_DEBUG "si2165: reg read: " args); \
} while (0)
#define deb_writereg(args...) \
do { \
if (debug & DEBUG_REG_WRITE) \
printk(KERN_DEBUG "si2165: reg write: " args); \
} while (0)
#define deb_fw_load(args...) \
do { \
if (debug & DEBUG_FW_LOAD) \
printk(KERN_DEBUG "si2165: fw load: " args); \
} while (0)
static int si2165_write(struct si2165_state *state, const u16 reg,
const u8 *src, const int count)
{
int ret;
struct i2c_msg msg;
u8 buf[2 + 4]; /* write a maximum of 4 bytes of data */
if (count + 2 > sizeof(buf)) {
dev_warn(&state->i2c->dev,
"%s: i2c wr reg=%04x: count=%d is too big!\n",
KBUILD_MODNAME, reg, count);
return -EINVAL;
}
buf[0] = reg >> 8;
buf[1] = reg & 0xff;
memcpy(buf + 2, src, count);
msg.addr = state->config.i2c_addr;
msg.flags = 0;
msg.buf = buf;
msg.len = count + 2;
if (debug & DEBUG_I2C_WRITE)
deb_i2c_write("reg: 0x%04x, data: %*ph\n", reg, count, src);
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1) {
dev_err(&state->i2c->dev, "%s: ret == %d\n", __func__, ret);
if (ret < 0)
return ret;
else
return -EREMOTEIO;
}
return 0;
}
static int si2165_read(struct si2165_state *state,
const u16 reg, u8 *val, const int count)
{
int ret;
u8 reg_buf[] = { reg >> 8, reg & 0xff };
struct i2c_msg msg[] = {
{ .addr = state->config.i2c_addr,
.flags = 0, .buf = reg_buf, .len = 2 },
{ .addr = state->config.i2c_addr,
.flags = I2C_M_RD, .buf = val, .len = count },
};
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
dev_err(&state->i2c->dev, "%s: error (addr %02x reg %04x error (ret == %i)\n",
__func__, state->config.i2c_addr, reg, ret);
if (ret < 0)
return ret;
else
return -EREMOTEIO;
}
if (debug & DEBUG_I2C_READ)
deb_i2c_read("reg: 0x%04x, data: %*ph\n", reg, count, val);
return 0;
}
static int si2165_readreg8(struct si2165_state *state,
const u16 reg, u8 *val)
{
int ret;
ret = si2165_read(state, reg, val, 1);
deb_readreg("R(0x%04x)=0x%02x\n", reg, *val);
return ret;
}
static int si2165_readreg16(struct si2165_state *state,
const u16 reg, u16 *val)
{
u8 buf[2];
int ret = si2165_read(state, reg, buf, 2);
*val = buf[0] | buf[1] << 8;
deb_readreg("R(0x%04x)=0x%04x\n", reg, *val);
return ret;
}
static int si2165_writereg8(struct si2165_state *state, const u16 reg, u8 val)
{
return si2165_write(state, reg, &val, 1);
}
static int si2165_writereg16(struct si2165_state *state, const u16 reg, u16 val)
{
u8 buf[2] = { val & 0xff, (val >> 8) & 0xff };
return si2165_write(state, reg, buf, 2);
}
static int si2165_writereg24(struct si2165_state *state, const u16 reg, u32 val)
{
u8 buf[3] = { val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff };
return si2165_write(state, reg, buf, 3);
}
static int si2165_writereg32(struct si2165_state *state, const u16 reg, u32 val)
{
u8 buf[4] = {
val & 0xff,
(val >> 8) & 0xff,
(val >> 16) & 0xff,
(val >> 24) & 0xff
};
return si2165_write(state, reg, buf, 4);
}
static int si2165_writereg_mask8(struct si2165_state *state, const u16 reg,
u8 val, u8 mask)
{
int ret;
u8 tmp;
if (mask != 0xff) {
ret = si2165_readreg8(state, reg, &tmp);
if (ret < 0)
goto err;
val &= mask;
tmp &= ~mask;
val |= tmp;
}
ret = si2165_writereg8(state, reg, val);
err:
return ret;
}
static int si2165_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *s)
{
s->min_delay_ms = 1000;
return 0;
}
static int si2165_init_pll(struct si2165_state *state)
{
u32 ref_freq_Hz = state->config.ref_freq_Hz;
u8 divr = 1; /* 1..7 */
u8 divp = 1; /* only 1 or 4 */
u8 divn = 56; /* 1..63 */
u8 divm = 8;
u8 divl = 12;
u8 buf[4];
/* hardcoded values can be deleted if calculation is verified
* or it yields the same values as the windows driver */
switch (ref_freq_Hz) {
case 16000000u:
divn = 56;
break;
case 24000000u:
divr = 2;
divp = 4;
divn = 19;
break;
default:
/* ref_freq / divr must be between 4 and 16 MHz */
if (ref_freq_Hz > 16000000u)
divr = 2;
/* now select divn and divp such that
* fvco is in 1624..1824 MHz */
if (1624000000u * divr > ref_freq_Hz * 2u * 63u)
divp = 4;
/* is this already correct regarding rounding? */
divn = 1624000000u * divr / (ref_freq_Hz * 2u * divp);
break;
}
/* adc_clk and sys_clk depend on xtal and pll settings */
state->fvco_hz = ref_freq_Hz / divr
* 2u * divn * divp;
state->adc_clk = state->fvco_hz / (divm * 4u);
state->sys_clk = state->fvco_hz / (divl * 2u);
/* write pll registers 0x00a0..0x00a3 at once */
buf[0] = divl;
buf[1] = divm;
buf[2] = (divn & 0x3f) | ((divp == 1) ? 0x40 : 0x00) | 0x80;
buf[3] = divr;
return si2165_write(state, 0x00a0, buf, 4);
}
static int si2165_adjust_pll_divl(struct si2165_state *state, u8 divl)
{
state->sys_clk = state->fvco_hz / (divl * 2u);
return si2165_writereg8(state, 0x00a0, divl); /* pll_divl */
}
static u32 si2165_get_fe_clk(struct si2165_state *state)
{
/* assume Oversampling mode Ovr4 is used */
return state->adc_clk;
}
static int si2165_wait_init_done(struct si2165_state *state)
{
int ret = -EINVAL;
u8 val = 0;
int i;
for (i = 0; i < 3; ++i) {
si2165_readreg8(state, 0x0054, &val);
if (val == 0x01)
return 0;
usleep_range(1000, 50000);
}
dev_err(&state->i2c->dev, "%s: init_done was not set\n",
KBUILD_MODNAME);
return ret;
}
static int si2165_upload_firmware_block(struct si2165_state *state,
const u8 *data, u32 len, u32 *poffset, u32 block_count)
{
int ret;
u8 buf_ctrl[4] = { 0x00, 0x00, 0x00, 0xc0 };
u8 wordcount;
u32 cur_block = 0;
u32 offset = poffset ? *poffset : 0;
if (len < 4)
return -EINVAL;
if (len % 4 != 0)
return -EINVAL;
deb_fw_load("si2165_upload_firmware_block called with len=0x%x offset=0x%x blockcount=0x%x\n",
len, offset, block_count);
while (offset+12 <= len && cur_block < block_count) {
deb_fw_load("si2165_upload_firmware_block in while len=0x%x offset=0x%x cur_block=0x%x blockcount=0x%x\n",
len, offset, cur_block, block_count);
wordcount = data[offset];
if (wordcount < 1 || data[offset+1] ||
data[offset+2] || data[offset+3]) {
dev_warn(&state->i2c->dev,
"%s: bad fw data[0..3] = %*ph\n",
KBUILD_MODNAME, 4, data);
return -EINVAL;
}
if (offset + 8 + wordcount * 4 > len) {
dev_warn(&state->i2c->dev,
"%s: len is too small for block len=%d, wordcount=%d\n",
KBUILD_MODNAME, len, wordcount);
return -EINVAL;
}
buf_ctrl[0] = wordcount - 1;
ret = si2165_write(state, 0x0364, buf_ctrl, 4);
if (ret < 0)
goto error;
ret = si2165_write(state, 0x0368, data+offset+4, 4);
if (ret < 0)
goto error;
offset += 8;
while (wordcount > 0) {
ret = si2165_write(state, 0x36c, data+offset, 4);
if (ret < 0)
goto error;
wordcount--;
offset += 4;
}
cur_block++;
}
deb_fw_load("si2165_upload_firmware_block after while len=0x%x offset=0x%x cur_block=0x%x blockcount=0x%x\n",
len, offset, cur_block, block_count);
if (poffset)
*poffset = offset;
deb_fw_load("si2165_upload_firmware_block returned offset=0x%x\n",
offset);
return 0;
error:
return ret;
}
static int si2165_upload_firmware(struct si2165_state *state)
{
/* int ret; */
u8 val[3];
u16 val16;
int ret;
const struct firmware *fw = NULL;
u8 *fw_file;
const u8 *data;
u32 len;
u32 offset;
u8 patch_version;
u8 block_count;
u16 crc_expected;
switch (state->chip_revcode) {
case 0x03: /* revision D */
fw_file = SI2165_FIRMWARE_REV_D;
break;
default:
dev_info(&state->i2c->dev, "%s: no firmware file for revision=%d\n",
KBUILD_MODNAME, state->chip_revcode);
return 0;
}
/* request the firmware, this will block and timeout */
ret = request_firmware(&fw, fw_file, state->i2c->dev.parent);
if (ret) {
dev_warn(&state->i2c->dev, "%s: firmware file '%s' not found\n",
KBUILD_MODNAME, fw_file);
goto error;
}
data = fw->data;
len = fw->size;
dev_info(&state->i2c->dev, "%s: downloading firmware from file '%s' size=%d\n",
KBUILD_MODNAME, fw_file, len);
if (len % 4 != 0) {
dev_warn(&state->i2c->dev, "%s: firmware size is not multiple of 4\n",
KBUILD_MODNAME);
ret = -EINVAL;
goto error;
}
/* check header (8 bytes) */
if (len < 8) {
dev_warn(&state->i2c->dev, "%s: firmware header is missing\n",
KBUILD_MODNAME);
ret = -EINVAL;
goto error;
}
if (data[0] != 1 || data[1] != 0) {
dev_warn(&state->i2c->dev, "%s: firmware file version is wrong\n",
KBUILD_MODNAME);
ret = -EINVAL;
goto error;
}
patch_version = data[2];
block_count = data[4];
crc_expected = data[7] << 8 | data[6];
/* start uploading fw */
/* boot/wdog status */
ret = si2165_writereg8(state, 0x0341, 0x00);
if (ret < 0)
goto error;
/* reset */
ret = si2165_writereg8(state, 0x00c0, 0x00);
if (ret < 0)
goto error;
/* boot/wdog status */
ret = si2165_readreg8(state, 0x0341, val);
if (ret < 0)
goto error;
/* enable reset on error */
ret = si2165_readreg8(state, 0x035c, val);
if (ret < 0)
goto error;
ret = si2165_readreg8(state, 0x035c, val);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x035c, 0x02);
if (ret < 0)
goto error;
/* start right after the header */
offset = 8;
dev_info(&state->i2c->dev, "%s: si2165_upload_firmware extracted patch_version=0x%02x, block_count=0x%02x, crc_expected=0x%04x\n",
KBUILD_MODNAME, patch_version, block_count, crc_expected);
ret = si2165_upload_firmware_block(state, data, len, &offset, 1);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x0344, patch_version);
if (ret < 0)
goto error;
/* reset crc */
ret = si2165_writereg8(state, 0x0379, 0x01);
if (ret)
goto error;
ret = si2165_upload_firmware_block(state, data, len,
&offset, block_count);
if (ret < 0) {
dev_err(&state->i2c->dev,
"%s: firmare could not be uploaded\n",
KBUILD_MODNAME);
goto error;
}
/* read crc */
ret = si2165_readreg16(state, 0x037a, &val16);
if (ret)
goto error;
if (val16 != crc_expected) {
dev_err(&state->i2c->dev,
"%s: firmware crc mismatch %04x != %04x\n",
KBUILD_MODNAME, val16, crc_expected);
ret = -EINVAL;
goto error;
}
ret = si2165_upload_firmware_block(state, data, len, &offset, 5);
if (ret)
goto error;
if (len != offset) {
dev_err(&state->i2c->dev,
"%s: firmare len mismatch %04x != %04x\n",
KBUILD_MODNAME, len, offset);
ret = -EINVAL;
goto error;
}
/* reset watchdog error register */
ret = si2165_writereg_mask8(state, 0x0341, 0x02, 0x02);
if (ret < 0)
goto error;
/* enable reset on error */
ret = si2165_writereg_mask8(state, 0x035c, 0x01, 0x01);
if (ret < 0)
goto error;
dev_info(&state->i2c->dev, "%s: fw load finished\n", KBUILD_MODNAME);
ret = 0;
state->firmware_loaded = true;
error:
if (fw) {
release_firmware(fw);
fw = NULL;
}
return ret;
}
static int si2165_init(struct dvb_frontend *fe)
{
int ret = 0;
struct si2165_state *state = fe->demodulator_priv;
u8 val;
u8 patch_version = 0x00;
dprintk("%s: called\n", __func__);
/* powerup */
ret = si2165_writereg8(state, 0x0000, state->config.chip_mode);
if (ret < 0)
goto error;
/* dsp_clock_enable */
ret = si2165_writereg8(state, 0x0104, 0x01);
if (ret < 0)
goto error;
ret = si2165_readreg8(state, 0x0000, &val); /* verify chip_mode */
if (ret < 0)
goto error;
if (val != state->config.chip_mode) {
dev_err(&state->i2c->dev, "%s: could not set chip_mode\n",
KBUILD_MODNAME);
return -EINVAL;
}
/* agc */
ret = si2165_writereg8(state, 0x018b, 0x00);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x0190, 0x01);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x0170, 0x00);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x0171, 0x07);
if (ret < 0)
goto error;
/* rssi pad */
ret = si2165_writereg8(state, 0x0646, 0x00);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x0641, 0x00);
if (ret < 0)
goto error;
ret = si2165_init_pll(state);
if (ret < 0)
goto error;
/* enable chip_init */
ret = si2165_writereg8(state, 0x0050, 0x01);
if (ret < 0)
goto error;
/* set start_init */
ret = si2165_writereg8(state, 0x0096, 0x01);
if (ret < 0)
goto error;
ret = si2165_wait_init_done(state);
if (ret < 0)
goto error;
/* disable chip_init */
ret = si2165_writereg8(state, 0x0050, 0x00);
if (ret < 0)
goto error;
/* ber_pkt */
ret = si2165_writereg16(state, 0x0470 , 0x7530);
if (ret < 0)
goto error;
ret = si2165_readreg8(state, 0x0344, &patch_version);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x00cb, 0x00);
if (ret < 0)
goto error;
/* dsp_addr_jump */
ret = si2165_writereg32(state, 0x0348, 0xf4000000);
if (ret < 0)
goto error;
/* boot/wdog status */
ret = si2165_readreg8(state, 0x0341, &val);
if (ret < 0)
goto error;
if (patch_version == 0x00) {
ret = si2165_upload_firmware(state);
if (ret < 0)
goto error;
}
/* write adc values after each reset*/
ret = si2165_writereg8(state, 0x012a, 0x46);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x012c, 0x00);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x012e, 0x0a);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x012f, 0xff);
if (ret < 0)
goto error;
ret = si2165_writereg8(state, 0x0123, 0x70);
if (ret < 0)
goto error;
return 0;
error:
return ret;
}
static int si2165_sleep(struct dvb_frontend *fe)
{
int ret;
struct si2165_state *state = fe->demodulator_priv;
/* dsp clock disable */
ret = si2165_writereg8(state, 0x0104, 0x00);
if (ret < 0)
return ret;
/* chip mode */
ret = si2165_writereg8(state, 0x0000, SI2165_MODE_OFF);
if (ret < 0)
return ret;
return 0;
}
static int si2165_read_status(struct dvb_frontend *fe, enum fe_status *status)
{
int ret;
u8 fec_lock = 0;
struct si2165_state *state = fe->demodulator_priv;
if (!state->has_dvbt)
return -EINVAL;
/* check fec_lock */
ret = si2165_readreg8(state, 0x4e0, &fec_lock);
if (ret < 0)
return ret;
*status = 0;
if (fec_lock & 0x01) {
*status |= FE_HAS_SIGNAL;
*status |= FE_HAS_CARRIER;
*status |= FE_HAS_VITERBI;
*status |= FE_HAS_SYNC;
*status |= FE_HAS_LOCK;
}
return 0;
}
static int si2165_set_oversamp(struct si2165_state *state, u32 dvb_rate)
{
u64 oversamp;
u32 reg_value;
oversamp = si2165_get_fe_clk(state);
oversamp <<= 23;
do_div(oversamp, dvb_rate);
reg_value = oversamp & 0x3fffffff;
/* oversamp, usbdump contained 0x03100000; */
return si2165_writereg32(state, 0x00e4, reg_value);
}
static int si2165_set_if_freq_shift(struct si2165_state *state, u32 IF)
{
u64 if_freq_shift;
s32 reg_value = 0;
u32 fe_clk = si2165_get_fe_clk(state);
if_freq_shift = IF;
if_freq_shift <<= 29;
do_div(if_freq_shift, fe_clk);
reg_value = (s32)if_freq_shift;
if (state->config.inversion)
reg_value = -reg_value;
reg_value = reg_value & 0x1fffffff;
/* if_freq_shift, usbdump contained 0x023ee08f; */
return si2165_writereg32(state, 0x00e8, reg_value);
}
static int si2165_set_parameters(struct dvb_frontend *fe)
{
int ret;
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct si2165_state *state = fe->demodulator_priv;
u8 val[3];
u32 IF;
u32 dvb_rate = 0;
u16 bw10k;
dprintk("%s: called\n", __func__);
if (!fe->ops.tuner_ops.get_if_frequency) {
dev_err(&state->i2c->dev,
"%s: Error: get_if_frequency() not defined at tuner. Can't work without it!\n",
KBUILD_MODNAME);
return -EINVAL;
}
if (!state->has_dvbt)
return -EINVAL;
if (p->bandwidth_hz > 0) {
dvb_rate = p->bandwidth_hz * 8 / 7;
bw10k = p->bandwidth_hz / 10000;
} else {
dvb_rate = 8 * 8 / 7;
bw10k = 800;
}
/* standard = DVB-T */
ret = si2165_writereg8(state, 0x00ec, 0x01);
if (ret < 0)
return ret;
ret = si2165_adjust_pll_divl(state, 12);
if (ret < 0)
return ret;
fe->ops.tuner_ops.get_if_frequency(fe, &IF);
ret = si2165_set_if_freq_shift(state, IF);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x08f8, 0x00);
if (ret < 0)
return ret;
/* ts output config */
ret = si2165_writereg8(state, 0x04e4, 0x20);
if (ret < 0)
return ret;
ret = si2165_writereg16(state, 0x04ef, 0x00fe);
if (ret < 0)
return ret;
ret = si2165_writereg24(state, 0x04f4, 0x555555);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x04e5, 0x01);
if (ret < 0)
return ret;
/* bandwidth in 10KHz steps */
ret = si2165_writereg16(state, 0x0308, bw10k);
if (ret < 0)
return ret;
ret = si2165_set_oversamp(state, dvb_rate);
if (ret < 0)
return ret;
/* impulsive_noise_remover */
ret = si2165_writereg8(state, 0x031c, 0x01);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x00cb, 0x00);
if (ret < 0)
return ret;
/* agc2 */
ret = si2165_writereg8(state, 0x016e, 0x41);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x016c, 0x0e);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x016d, 0x10);
if (ret < 0)
return ret;
/* agc */
ret = si2165_writereg8(state, 0x015b, 0x03);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x0150, 0x78);
if (ret < 0)
return ret;
/* agc */
ret = si2165_writereg8(state, 0x01a0, 0x78);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x01c8, 0x68);
if (ret < 0)
return ret;
/* freq_sync_range */
ret = si2165_writereg16(state, 0x030c, 0x0064);
if (ret < 0)
return ret;
/* gp_reg0 */
ret = si2165_readreg8(state, 0x0387, val);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x0387, 0x00);
if (ret < 0)
return ret;
/* dsp_addr_jump */
ret = si2165_writereg32(state, 0x0348, 0xf4000000);
if (ret < 0)
return ret;
if (fe->ops.tuner_ops.set_params)
fe->ops.tuner_ops.set_params(fe);
/* recalc if_freq_shift if IF might has changed */
fe->ops.tuner_ops.get_if_frequency(fe, &IF);
ret = si2165_set_if_freq_shift(state, IF);
if (ret < 0)
return ret;
/* boot/wdog status */
ret = si2165_readreg8(state, 0x0341, val);
if (ret < 0)
return ret;
ret = si2165_writereg8(state, 0x0341, 0x00);
if (ret < 0)
return ret;
/* reset all */
ret = si2165_writereg8(state, 0x00c0, 0x00);
if (ret < 0)
return ret;
/* gp_reg0 */
ret = si2165_writereg32(state, 0x0384, 0x00000000);
if (ret < 0)
return ret;
/* start_synchro */
ret = si2165_writereg8(state, 0x02e0, 0x01);
if (ret < 0)
return ret;
/* boot/wdog status */
ret = si2165_readreg8(state, 0x0341, val);
if (ret < 0)
return ret;
return 0;
}
static void si2165_release(struct dvb_frontend *fe)
{
struct si2165_state *state = fe->demodulator_priv;
dprintk("%s: called\n", __func__);
kfree(state);
}
static struct dvb_frontend_ops si2165_ops = {
.info = {
.name = "Silicon Labs ",
.caps = FE_CAN_FEC_1_2 |
FE_CAN_FEC_2_3 |
FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 |
FE_CAN_FEC_7_8 |
FE_CAN_FEC_AUTO |
FE_CAN_QPSK |
FE_CAN_QAM_16 |
FE_CAN_QAM_32 |
FE_CAN_QAM_64 |
FE_CAN_QAM_128 |
FE_CAN_QAM_256 |
FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_HIERARCHY_AUTO |
FE_CAN_MUTE_TS |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_RECOVER
},
.get_tune_settings = si2165_get_tune_settings,
.init = si2165_init,
.sleep = si2165_sleep,
.set_frontend = si2165_set_parameters,
.read_status = si2165_read_status,
.release = si2165_release,
};
struct dvb_frontend *si2165_attach(const struct si2165_config *config,
struct i2c_adapter *i2c)
{
struct si2165_state *state = NULL;
int n;
int io_ret;
u8 val;
char rev_char;
const char *chip_name;
if (config == NULL || i2c == NULL)
goto error;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct si2165_state), GFP_KERNEL);
if (state == NULL)
goto error;
/* setup the state */
state->i2c = i2c;
state->config = *config;
if (state->config.ref_freq_Hz < 4000000
|| state->config.ref_freq_Hz > 27000000) {
dev_err(&state->i2c->dev, "%s: ref_freq of %d Hz not supported by this driver\n",
KBUILD_MODNAME, state->config.ref_freq_Hz);
goto error;
}
/* create dvb_frontend */
memcpy(&state->frontend.ops, &si2165_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
/* powerup */
io_ret = si2165_writereg8(state, 0x0000, state->config.chip_mode);
if (io_ret < 0)
goto error;
io_ret = si2165_readreg8(state, 0x0000, &val);
if (io_ret < 0)
goto error;
if (val != state->config.chip_mode)
goto error;
io_ret = si2165_readreg8(state, 0x0023, &state->chip_revcode);
if (io_ret < 0)
goto error;
io_ret = si2165_readreg8(state, 0x0118, &state->chip_type);
if (io_ret < 0)
goto error;
/* powerdown */
io_ret = si2165_writereg8(state, 0x0000, SI2165_MODE_OFF);
if (io_ret < 0)
goto error;
if (state->chip_revcode < 26)
rev_char = 'A' + state->chip_revcode;
else
rev_char = '?';
switch (state->chip_type) {
case 0x06:
chip_name = "Si2161";
state->has_dvbt = true;
break;
case 0x07:
chip_name = "Si2165";
state->has_dvbt = true;
state->has_dvbc = true;
break;
default:
dev_err(&state->i2c->dev, "%s: Unsupported Silicon Labs chip (type %d, rev %d)\n",
KBUILD_MODNAME, state->chip_type, state->chip_revcode);
goto error;
}
dev_info(&state->i2c->dev,
"%s: Detected Silicon Labs %s-%c (type %d, rev %d)\n",
KBUILD_MODNAME, chip_name, rev_char, state->chip_type,
state->chip_revcode);
strlcat(state->frontend.ops.info.name, chip_name,
sizeof(state->frontend.ops.info.name));
n = 0;
if (state->has_dvbt) {
state->frontend.ops.delsys[n++] = SYS_DVBT;
strlcat(state->frontend.ops.info.name, " DVB-T",
sizeof(state->frontend.ops.info.name));
}
if (state->has_dvbc)
dev_warn(&state->i2c->dev, "%s: DVB-C is not yet supported.\n",
KBUILD_MODNAME);
return &state->frontend;
error:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(si2165_attach);
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off).");
MODULE_DESCRIPTION("Silicon Labs Si2165 DVB-C/-T Demodulator driver");
MODULE_AUTHOR("Matthias Schwarzott <zzam@gentoo.org>");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE(SI2165_FIRMWARE_REV_D);
| gpl-2.0 |
mdxy2010/forlinux-ok6410 | kernel/arch/arm/mach-ks8695/board-dsm320.c | 2590 | 2846 | /*
* arch/arm/mach-ks8695/board-dsm320.c
*
* DSM-320 D-Link Wireless Media Player, board support.
*
* Copyright 2008 Simtec Electronics
* Daniel Silverstone <dsilvers@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/partitions.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/devices.h>
#include <mach/gpio.h>
#include "generic.h"
#ifdef CONFIG_PCI
static int dsm320_pci_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
switch (slot) {
case 0:
/* PCI-AHB bridge? */
return KS8695_IRQ_EXTERN0;
case 18:
/* Mini PCI slot */
return KS8695_IRQ_EXTERN2;
case 20:
/* RealMAGIC chip */
return KS8695_IRQ_EXTERN0;
}
BUG();
}
static struct ks8695_pci_cfg __initdata dsm320_pci = {
.mode = KS8695_MODE_MINIPCI,
.map_irq = dsm320_pci_map_irq,
};
static void __init dsm320_register_pci(void)
{
/* Initialise the GPIO lines for interrupt mode */
/* RealMAGIC */
ks8695_gpio_interrupt(KS8695_GPIO_0, IRQ_TYPE_LEVEL_LOW);
/* MiniPCI Slot */
ks8695_gpio_interrupt(KS8695_GPIO_2, IRQ_TYPE_LEVEL_LOW);
ks8695_init_pci(&dsm320_pci);
}
#else
static inline void __init dsm320_register_pci(void) { }
#endif
static struct physmap_flash_data dsm320_nor_pdata = {
.width = 4,
.nr_parts = 0,
};
static struct resource dsm320_nor_resource[] = {
[0] = {
.start = SZ_32M, /* We expect the bootloader to map
* the flash here.
*/
.end = SZ_32M + SZ_4M - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device dsm320_device_nor = {
.name = "physmap-flash",
.id = -1,
.num_resources = ARRAY_SIZE(dsm320_nor_resource),
.resource = dsm320_nor_resource,
.dev = {
.platform_data = &dsm320_nor_pdata,
},
};
void __init dsm320_register_nor(void)
{
int ret;
ret = platform_device_register(&dsm320_device_nor);
if (ret < 0)
printk(KERN_ERR "failed to register physmap-flash device\n");
}
static void __init dsm320_init(void)
{
/* GPIO registration */
ks8695_register_gpios();
/* PCI registration */
dsm320_register_pci();
/* Network device */
ks8695_add_device_lan(); /* eth0 = LAN */
/* NOR devices */
dsm320_register_nor();
}
MACHINE_START(DSM320, "D-Link DSM-320 Wireless Media Player")
/* Maintainer: Simtec Electronics. */
.boot_params = KS8695_SDRAM_PA + 0x100,
.map_io = ks8695_map_io,
.init_irq = ks8695_init_irq,
.init_machine = dsm320_init,
.timer = &ks8695_timer,
MACHINE_END
| gpl-2.0 |
arshull/GalaTab3_KK_Kernel_T310 | fs/logfs/inode.c | 2846 | 11035 | /*
* fs/logfs/inode.c - inode handling code
*
* As should be obvious for Linux kernel code, license is GPLv2
*
* Copyright (c) 2005-2008 Joern Engel <joern@logfs.org>
*/
#include "logfs.h"
#include <linux/slab.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
/*
* How soon to reuse old inode numbers? LogFS doesn't store deleted inodes
* on the medium. It therefore also lacks a method to store the previous
* generation number for deleted inodes. Instead a single generation number
* is stored which will be used for new inodes. Being just a 32bit counter,
* this can obvious wrap relatively quickly. So we only reuse inodes if we
* know that a fair number of inodes can be created before we have to increment
* the generation again - effectively adding some bits to the counter.
* But being too aggressive here means we keep a very large and very sparse
* inode file, wasting space on indirect blocks.
* So what is a good value? Beats me. 64k seems moderately bad on both
* fronts, so let's use that for now...
*
* NFS sucks, as everyone already knows.
*/
#define INOS_PER_WRAP (0x10000)
/*
* Logfs' requirement to read inodes for garbage collection makes life a bit
* harder. GC may have to read inodes that are in I_FREEING state, when they
* are being written out - and waiting for GC to make progress, naturally.
*
* So we cannot just call iget() or some variant of it, but first have to check
* wether the inode in question might be in I_FREEING state. Therefore we
* maintain our own per-sb list of "almost deleted" inodes and check against
* that list first. Normally this should be at most 1-2 entries long.
*
* Also, inodes have logfs-specific reference counting on top of what the vfs
* does. When .destroy_inode is called, normally the reference count will drop
* to zero and the inode gets deleted. But if GC accessed the inode, its
* refcount will remain nonzero and final deletion will have to wait.
*
* As a result we have two sets of functions to get/put inodes:
* logfs_safe_iget/logfs_safe_iput - safe to call from GC context
* logfs_iget/iput - normal version
*/
static struct kmem_cache *logfs_inode_cache;
static DEFINE_SPINLOCK(logfs_inode_lock);
static void logfs_inode_setops(struct inode *inode)
{
switch (inode->i_mode & S_IFMT) {
case S_IFDIR:
inode->i_op = &logfs_dir_iops;
inode->i_fop = &logfs_dir_fops;
inode->i_mapping->a_ops = &logfs_reg_aops;
break;
case S_IFREG:
inode->i_op = &logfs_reg_iops;
inode->i_fop = &logfs_reg_fops;
inode->i_mapping->a_ops = &logfs_reg_aops;
break;
case S_IFLNK:
inode->i_op = &logfs_symlink_iops;
inode->i_mapping->a_ops = &logfs_reg_aops;
break;
case S_IFSOCK: /* fall through */
case S_IFBLK: /* fall through */
case S_IFCHR: /* fall through */
case S_IFIFO:
init_special_inode(inode, inode->i_mode, inode->i_rdev);
break;
default:
BUG();
}
}
static struct inode *__logfs_iget(struct super_block *sb, ino_t ino)
{
struct inode *inode = iget_locked(sb, ino);
int err;
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
err = logfs_read_inode(inode);
if (err || inode->i_nlink == 0) {
/* inode->i_nlink == 0 can be true when called from
* block validator */
/* set i_nlink to 0 to prevent caching */
inode->i_nlink = 0;
logfs_inode(inode)->li_flags |= LOGFS_IF_ZOMBIE;
iget_failed(inode);
if (!err)
err = -ENOENT;
return ERR_PTR(err);
}
logfs_inode_setops(inode);
unlock_new_inode(inode);
return inode;
}
struct inode *logfs_iget(struct super_block *sb, ino_t ino)
{
BUG_ON(ino == LOGFS_INO_MASTER);
BUG_ON(ino == LOGFS_INO_SEGFILE);
return __logfs_iget(sb, ino);
}
/*
* is_cached is set to 1 if we hand out a cached inode, 0 otherwise.
* this allows logfs_iput to do the right thing later
*/
struct inode *logfs_safe_iget(struct super_block *sb, ino_t ino, int *is_cached)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_inode *li;
if (ino == LOGFS_INO_MASTER)
return super->s_master_inode;
if (ino == LOGFS_INO_SEGFILE)
return super->s_segfile_inode;
spin_lock(&logfs_inode_lock);
list_for_each_entry(li, &super->s_freeing_list, li_freeing_list)
if (li->vfs_inode.i_ino == ino) {
li->li_refcount++;
spin_unlock(&logfs_inode_lock);
*is_cached = 1;
return &li->vfs_inode;
}
spin_unlock(&logfs_inode_lock);
*is_cached = 0;
return __logfs_iget(sb, ino);
}
static void logfs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
INIT_LIST_HEAD(&inode->i_dentry);
kmem_cache_free(logfs_inode_cache, logfs_inode(inode));
}
static void __logfs_destroy_inode(struct inode *inode)
{
struct logfs_inode *li = logfs_inode(inode);
BUG_ON(li->li_block);
list_del(&li->li_freeing_list);
call_rcu(&inode->i_rcu, logfs_i_callback);
}
static void logfs_destroy_inode(struct inode *inode)
{
struct logfs_inode *li = logfs_inode(inode);
BUG_ON(list_empty(&li->li_freeing_list));
spin_lock(&logfs_inode_lock);
li->li_refcount--;
if (li->li_refcount == 0)
__logfs_destroy_inode(inode);
spin_unlock(&logfs_inode_lock);
}
void logfs_safe_iput(struct inode *inode, int is_cached)
{
if (inode->i_ino == LOGFS_INO_MASTER)
return;
if (inode->i_ino == LOGFS_INO_SEGFILE)
return;
if (is_cached) {
logfs_destroy_inode(inode);
return;
}
iput(inode);
}
static void logfs_init_inode(struct super_block *sb, struct inode *inode)
{
struct logfs_inode *li = logfs_inode(inode);
int i;
li->li_flags = 0;
li->li_height = 0;
li->li_used_bytes = 0;
li->li_block = NULL;
inode->i_uid = 0;
inode->i_gid = 0;
inode->i_size = 0;
inode->i_blocks = 0;
inode->i_ctime = CURRENT_TIME;
inode->i_mtime = CURRENT_TIME;
inode->i_nlink = 1;
li->li_refcount = 1;
INIT_LIST_HEAD(&li->li_freeing_list);
for (i = 0; i < LOGFS_EMBEDDED_FIELDS; i++)
li->li_data[i] = 0;
return;
}
static struct inode *logfs_alloc_inode(struct super_block *sb)
{
struct logfs_inode *li;
li = kmem_cache_alloc(logfs_inode_cache, GFP_NOFS);
if (!li)
return NULL;
logfs_init_inode(sb, &li->vfs_inode);
return &li->vfs_inode;
}
/*
* In logfs inodes are written to an inode file. The inode file, like any
* other file, is managed with a inode. The inode file's inode, aka master
* inode, requires special handling in several respects. First, it cannot be
* written to the inode file, so it is stored in the journal instead.
*
* Secondly, this inode cannot be written back and destroyed before all other
* inodes have been written. The ordering is important. Linux' VFS is happily
* unaware of the ordering constraint and would ordinarily destroy the master
* inode at umount time while other inodes are still in use and dirty. Not
* good.
*
* So logfs makes sure the master inode is not written until all other inodes
* have been destroyed. Sadly, this method has another side-effect. The VFS
* will notice one remaining inode and print a frightening warning message.
* Worse, it is impossible to judge whether such a warning was caused by the
* master inode or any other inodes have leaked as well.
*
* Our attempt of solving this is with logfs_new_meta_inode() below. Its
* purpose is to create a new inode that will not trigger the warning if such
* an inode is still in use. An ugly hack, no doubt. Suggections for
* improvement are welcome.
*
* AV: that's what ->put_super() is for...
*/
struct inode *logfs_new_meta_inode(struct super_block *sb, u64 ino)
{
struct inode *inode;
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
inode->i_mode = S_IFREG;
inode->i_ino = ino;
inode->i_data.a_ops = &logfs_reg_aops;
mapping_set_gfp_mask(&inode->i_data, GFP_NOFS);
return inode;
}
struct inode *logfs_read_meta_inode(struct super_block *sb, u64 ino)
{
struct inode *inode;
int err;
inode = logfs_new_meta_inode(sb, ino);
if (IS_ERR(inode))
return inode;
err = logfs_read_inode(inode);
if (err) {
iput(inode);
return ERR_PTR(err);
}
logfs_inode_setops(inode);
return inode;
}
static int logfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
int ret;
long flags = WF_LOCK;
/* Can only happen if creat() failed. Safe to skip. */
if (logfs_inode(inode)->li_flags & LOGFS_IF_STILLBORN)
return 0;
ret = __logfs_write_inode(inode, flags);
LOGFS_BUG_ON(ret, inode->i_sb);
return ret;
}
/* called with inode->i_lock held */
static int logfs_drop_inode(struct inode *inode)
{
struct logfs_super *super = logfs_super(inode->i_sb);
struct logfs_inode *li = logfs_inode(inode);
spin_lock(&logfs_inode_lock);
list_move(&li->li_freeing_list, &super->s_freeing_list);
spin_unlock(&logfs_inode_lock);
return generic_drop_inode(inode);
}
static void logfs_set_ino_generation(struct super_block *sb,
struct inode *inode)
{
struct logfs_super *super = logfs_super(sb);
u64 ino;
mutex_lock(&super->s_journal_mutex);
ino = logfs_seek_hole(super->s_master_inode, super->s_last_ino + 1);
super->s_last_ino = ino;
super->s_inos_till_wrap--;
if (super->s_inos_till_wrap < 0) {
super->s_last_ino = LOGFS_RESERVED_INOS;
super->s_generation++;
super->s_inos_till_wrap = INOS_PER_WRAP;
}
inode->i_ino = ino;
inode->i_generation = super->s_generation;
mutex_unlock(&super->s_journal_mutex);
}
struct inode *logfs_new_inode(struct inode *dir, int mode)
{
struct super_block *sb = dir->i_sb;
struct inode *inode;
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
logfs_init_inode(sb, inode);
/* inherit parent flags */
logfs_inode(inode)->li_flags |=
logfs_inode(dir)->li_flags & LOGFS_FL_INHERITED;
inode->i_mode = mode;
logfs_set_ino_generation(sb, inode);
inode_init_owner(inode, dir, mode);
logfs_inode_setops(inode);
insert_inode_hash(inode);
return inode;
}
static void logfs_init_once(void *_li)
{
struct logfs_inode *li = _li;
int i;
li->li_flags = 0;
li->li_used_bytes = 0;
li->li_refcount = 1;
for (i = 0; i < LOGFS_EMBEDDED_FIELDS; i++)
li->li_data[i] = 0;
inode_init_once(&li->vfs_inode);
}
static int logfs_sync_fs(struct super_block *sb, int wait)
{
logfs_write_anchor(sb);
return 0;
}
static void logfs_put_super(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
/* kill the meta-inodes */
iput(super->s_master_inode);
iput(super->s_segfile_inode);
iput(super->s_mapping_inode);
}
const struct super_operations logfs_super_operations = {
.alloc_inode = logfs_alloc_inode,
.destroy_inode = logfs_destroy_inode,
.evict_inode = logfs_evict_inode,
.drop_inode = logfs_drop_inode,
.put_super = logfs_put_super,
.write_inode = logfs_write_inode,
.statfs = logfs_statfs,
.sync_fs = logfs_sync_fs,
};
int logfs_init_inode_cache(void)
{
logfs_inode_cache = kmem_cache_create("logfs_inode_cache",
sizeof(struct logfs_inode), 0, SLAB_RECLAIM_ACCOUNT,
logfs_init_once);
if (!logfs_inode_cache)
return -ENOMEM;
return 0;
}
void logfs_destroy_inode_cache(void)
{
kmem_cache_destroy(logfs_inode_cache);
}
| gpl-2.0 |
eyeballer/tf300t-10.4.2.9-kernel | net/dsa/mv88e6060.c | 3102 | 6142 | /*
* net/dsa/mv88e6060.c - Driver for Marvell 88e6060 switch chips
* Copyright (c) 2008-2009 Marvell Semiconductor
*
* 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/list.h>
#include <linux/netdevice.h>
#include <linux/phy.h>
#include "dsa_priv.h"
#define REG_PORT(p) (8 + (p))
#define REG_GLOBAL 0x0f
static int reg_read(struct dsa_switch *ds, int addr, int reg)
{
return mdiobus_read(ds->master_mii_bus, ds->pd->sw_addr + addr, reg);
}
#define REG_READ(addr, reg) \
({ \
int __ret; \
\
__ret = reg_read(ds, addr, reg); \
if (__ret < 0) \
return __ret; \
__ret; \
})
static int reg_write(struct dsa_switch *ds, int addr, int reg, u16 val)
{
return mdiobus_write(ds->master_mii_bus, ds->pd->sw_addr + addr,
reg, val);
}
#define REG_WRITE(addr, reg, val) \
({ \
int __ret; \
\
__ret = reg_write(ds, addr, reg, val); \
if (__ret < 0) \
return __ret; \
})
static char *mv88e6060_probe(struct mii_bus *bus, int sw_addr)
{
int ret;
ret = mdiobus_read(bus, sw_addr + REG_PORT(0), 0x03);
if (ret >= 0) {
ret &= 0xfff0;
if (ret == 0x0600)
return "Marvell 88E6060";
}
return NULL;
}
static int mv88e6060_switch_reset(struct dsa_switch *ds)
{
int i;
int ret;
/*
* Set all ports to the disabled state.
*/
for (i = 0; i < 6; i++) {
ret = REG_READ(REG_PORT(i), 0x04);
REG_WRITE(REG_PORT(i), 0x04, ret & 0xfffc);
}
/*
* Wait for transmit queues to drain.
*/
msleep(2);
/*
* Reset the switch.
*/
REG_WRITE(REG_GLOBAL, 0x0a, 0xa130);
/*
* Wait up to one second for reset to complete.
*/
for (i = 0; i < 1000; i++) {
ret = REG_READ(REG_GLOBAL, 0x00);
if ((ret & 0x8000) == 0x0000)
break;
msleep(1);
}
if (i == 1000)
return -ETIMEDOUT;
return 0;
}
static int mv88e6060_setup_global(struct dsa_switch *ds)
{
/*
* Disable discarding of frames with excessive collisions,
* set the maximum frame size to 1536 bytes, and mask all
* interrupt sources.
*/
REG_WRITE(REG_GLOBAL, 0x04, 0x0800);
/*
* Enable automatic address learning, set the address
* database size to 1024 entries, and set the default aging
* time to 5 minutes.
*/
REG_WRITE(REG_GLOBAL, 0x0a, 0x2130);
return 0;
}
static int mv88e6060_setup_port(struct dsa_switch *ds, int p)
{
int addr = REG_PORT(p);
/*
* Do not force flow control, disable Ingress and Egress
* Header tagging, disable VLAN tunneling, and set the port
* state to Forwarding. Additionally, if this is the CPU
* port, enable Ingress and Egress Trailer tagging mode.
*/
REG_WRITE(addr, 0x04, dsa_is_cpu_port(ds, p) ? 0x4103 : 0x0003);
/*
* Port based VLAN map: give each port its own address
* database, allow the CPU port to talk to each of the 'real'
* ports, and allow each of the 'real' ports to only talk to
* the CPU port.
*/
REG_WRITE(addr, 0x06,
((p & 0xf) << 12) |
(dsa_is_cpu_port(ds, p) ?
ds->phys_port_mask :
(1 << ds->dst->cpu_port)));
/*
* Port Association Vector: when learning source addresses
* of packets, add the address to the address database using
* a port bitmap that has only the bit for this port set and
* the other bits clear.
*/
REG_WRITE(addr, 0x0b, 1 << p);
return 0;
}
static int mv88e6060_setup(struct dsa_switch *ds)
{
int i;
int ret;
ret = mv88e6060_switch_reset(ds);
if (ret < 0)
return ret;
/* @@@ initialise atu */
ret = mv88e6060_setup_global(ds);
if (ret < 0)
return ret;
for (i = 0; i < 6; i++) {
ret = mv88e6060_setup_port(ds, i);
if (ret < 0)
return ret;
}
return 0;
}
static int mv88e6060_set_addr(struct dsa_switch *ds, u8 *addr)
{
REG_WRITE(REG_GLOBAL, 0x01, (addr[0] << 8) | addr[1]);
REG_WRITE(REG_GLOBAL, 0x02, (addr[2] << 8) | addr[3]);
REG_WRITE(REG_GLOBAL, 0x03, (addr[4] << 8) | addr[5]);
return 0;
}
static int mv88e6060_port_to_phy_addr(int port)
{
if (port >= 0 && port <= 5)
return port;
return -1;
}
static int mv88e6060_phy_read(struct dsa_switch *ds, int port, int regnum)
{
int addr;
addr = mv88e6060_port_to_phy_addr(port);
if (addr == -1)
return 0xffff;
return reg_read(ds, addr, regnum);
}
static int
mv88e6060_phy_write(struct dsa_switch *ds, int port, int regnum, u16 val)
{
int addr;
addr = mv88e6060_port_to_phy_addr(port);
if (addr == -1)
return 0xffff;
return reg_write(ds, addr, regnum, val);
}
static void mv88e6060_poll_link(struct dsa_switch *ds)
{
int i;
for (i = 0; i < DSA_MAX_PORTS; i++) {
struct net_device *dev;
int uninitialized_var(port_status);
int link;
int speed;
int duplex;
int fc;
dev = ds->ports[i];
if (dev == NULL)
continue;
link = 0;
if (dev->flags & IFF_UP) {
port_status = reg_read(ds, REG_PORT(i), 0x00);
if (port_status < 0)
continue;
link = !!(port_status & 0x1000);
}
if (!link) {
if (netif_carrier_ok(dev)) {
printk(KERN_INFO "%s: link down\n", dev->name);
netif_carrier_off(dev);
}
continue;
}
speed = (port_status & 0x0100) ? 100 : 10;
duplex = (port_status & 0x0200) ? 1 : 0;
fc = ((port_status & 0xc000) == 0xc000) ? 1 : 0;
if (!netif_carrier_ok(dev)) {
printk(KERN_INFO "%s: link up, %d Mb/s, %s duplex, "
"flow control %sabled\n", dev->name,
speed, duplex ? "full" : "half",
fc ? "en" : "dis");
netif_carrier_on(dev);
}
}
}
static struct dsa_switch_driver mv88e6060_switch_driver = {
.tag_protocol = htons(ETH_P_TRAILER),
.probe = mv88e6060_probe,
.setup = mv88e6060_setup,
.set_addr = mv88e6060_set_addr,
.phy_read = mv88e6060_phy_read,
.phy_write = mv88e6060_phy_write,
.poll_link = mv88e6060_poll_link,
};
static int __init mv88e6060_init(void)
{
register_switch_driver(&mv88e6060_switch_driver);
return 0;
}
module_init(mv88e6060_init);
static void __exit mv88e6060_cleanup(void)
{
unregister_switch_driver(&mv88e6060_switch_driver);
}
module_exit(mv88e6060_cleanup);
| gpl-2.0 |
RenderBroken/msm8974_OPO-CAF_render_kernel | drivers/media/video/au0828/au0828-video.c | 3870 | 50041 | /*
* Auvitek AU0828 USB Bridge (Analog video support)
*
* Copyright (C) 2009 Devin Heitmueller <dheitmueller@linuxtv.org>
* Copyright (C) 2005-2008 Auvitek International, 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/* Developer Notes:
*
* VBI support is not yet working
* The hardware scaler supported is unimplemented
* AC97 audio support is unimplemented (only i2s audio mode)
*
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/suspend.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-chip-ident.h>
#include <media/tuner.h>
#include "au0828.h"
#include "au0828-reg.h"
static DEFINE_MUTEX(au0828_sysfs_lock);
/* ------------------------------------------------------------------
Videobuf operations
------------------------------------------------------------------*/
static unsigned int isoc_debug;
module_param(isoc_debug, int, 0644);
MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
#define au0828_isocdbg(fmt, arg...) \
do {\
if (isoc_debug) { \
printk(KERN_INFO "au0828 %s :"fmt, \
__func__ , ##arg); \
} \
} while (0)
static inline void print_err_status(struct au0828_dev *dev,
int packet, int status)
{
char *errmsg = "Unknown";
switch (status) {
case -ENOENT:
errmsg = "unlinked synchronuously";
break;
case -ECONNRESET:
errmsg = "unlinked asynchronuously";
break;
case -ENOSR:
errmsg = "Buffer error (overrun)";
break;
case -EPIPE:
errmsg = "Stalled (device not responding)";
break;
case -EOVERFLOW:
errmsg = "Babble (bad cable?)";
break;
case -EPROTO:
errmsg = "Bit-stuff error (bad cable?)";
break;
case -EILSEQ:
errmsg = "CRC/Timeout (could be anything)";
break;
case -ETIME:
errmsg = "Device does not respond";
break;
}
if (packet < 0) {
au0828_isocdbg("URB status %d [%s].\n", status, errmsg);
} else {
au0828_isocdbg("URB packet %d, status %d [%s].\n",
packet, status, errmsg);
}
}
static int check_dev(struct au0828_dev *dev)
{
if (dev->dev_state & DEV_DISCONNECTED) {
printk(KERN_INFO "v4l2 ioctl: device not present\n");
return -ENODEV;
}
if (dev->dev_state & DEV_MISCONFIGURED) {
printk(KERN_INFO "v4l2 ioctl: device is misconfigured; "
"close and open it again\n");
return -EIO;
}
return 0;
}
/*
* IRQ callback, called by URB callback
*/
static void au0828_irq_callback(struct urb *urb)
{
struct au0828_dmaqueue *dma_q = urb->context;
struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vidq);
unsigned long flags = 0;
int rc, i;
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
au0828_isocdbg("au0828_irq_callback called: status kill\n");
return;
default: /* unknown error */
au0828_isocdbg("urb completition error %d.\n", urb->status);
break;
}
/* Copy data from URB */
spin_lock_irqsave(&dev->slock, flags);
rc = dev->isoc_ctl.isoc_copy(dev, urb);
spin_unlock_irqrestore(&dev->slock, flags);
/* Reset urb buffers */
for (i = 0; i < urb->number_of_packets; i++) {
urb->iso_frame_desc[i].status = 0;
urb->iso_frame_desc[i].actual_length = 0;
}
urb->status = 0;
urb->status = usb_submit_urb(urb, GFP_ATOMIC);
if (urb->status) {
au0828_isocdbg("urb resubmit failed (error=%i)\n",
urb->status);
}
}
/*
* Stop and Deallocate URBs
*/
void au0828_uninit_isoc(struct au0828_dev *dev)
{
struct urb *urb;
int i;
au0828_isocdbg("au0828: called au0828_uninit_isoc\n");
dev->isoc_ctl.nfields = -1;
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
urb = dev->isoc_ctl.urb[i];
if (urb) {
if (!irqs_disabled())
usb_kill_urb(urb);
else
usb_unlink_urb(urb);
if (dev->isoc_ctl.transfer_buffer[i]) {
usb_free_coherent(dev->usbdev,
urb->transfer_buffer_length,
dev->isoc_ctl.transfer_buffer[i],
urb->transfer_dma);
}
usb_free_urb(urb);
dev->isoc_ctl.urb[i] = NULL;
}
dev->isoc_ctl.transfer_buffer[i] = NULL;
}
kfree(dev->isoc_ctl.urb);
kfree(dev->isoc_ctl.transfer_buffer);
dev->isoc_ctl.urb = NULL;
dev->isoc_ctl.transfer_buffer = NULL;
dev->isoc_ctl.num_bufs = 0;
}
/*
* Allocate URBs and start IRQ
*/
int au0828_init_isoc(struct au0828_dev *dev, int max_packets,
int num_bufs, int max_pkt_size,
int (*isoc_copy) (struct au0828_dev *dev, struct urb *urb))
{
struct au0828_dmaqueue *dma_q = &dev->vidq;
int i;
int sb_size, pipe;
struct urb *urb;
int j, k;
int rc;
au0828_isocdbg("au0828: called au0828_prepare_isoc\n");
/* De-allocates all pending stuff */
au0828_uninit_isoc(dev);
dev->isoc_ctl.isoc_copy = isoc_copy;
dev->isoc_ctl.num_bufs = num_bufs;
dev->isoc_ctl.urb = kzalloc(sizeof(void *)*num_bufs, GFP_KERNEL);
if (!dev->isoc_ctl.urb) {
au0828_isocdbg("cannot alloc memory for usb buffers\n");
return -ENOMEM;
}
dev->isoc_ctl.transfer_buffer = kzalloc(sizeof(void *)*num_bufs,
GFP_KERNEL);
if (!dev->isoc_ctl.transfer_buffer) {
au0828_isocdbg("cannot allocate memory for usb transfer\n");
kfree(dev->isoc_ctl.urb);
return -ENOMEM;
}
dev->isoc_ctl.max_pkt_size = max_pkt_size;
dev->isoc_ctl.buf = NULL;
sb_size = max_packets * dev->isoc_ctl.max_pkt_size;
/* allocate urbs and transfer buffers */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
urb = usb_alloc_urb(max_packets, GFP_KERNEL);
if (!urb) {
au0828_isocdbg("cannot alloc isoc_ctl.urb %i\n", i);
au0828_uninit_isoc(dev);
return -ENOMEM;
}
dev->isoc_ctl.urb[i] = urb;
dev->isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->usbdev,
sb_size, GFP_KERNEL, &urb->transfer_dma);
if (!dev->isoc_ctl.transfer_buffer[i]) {
printk("unable to allocate %i bytes for transfer"
" buffer %i%s\n",
sb_size, i,
in_interrupt() ? " while in int" : "");
au0828_uninit_isoc(dev);
return -ENOMEM;
}
memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
pipe = usb_rcvisocpipe(dev->usbdev,
dev->isoc_in_endpointaddr),
usb_fill_int_urb(urb, dev->usbdev, pipe,
dev->isoc_ctl.transfer_buffer[i], sb_size,
au0828_irq_callback, dma_q, 1);
urb->number_of_packets = max_packets;
urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
k = 0;
for (j = 0; j < max_packets; j++) {
urb->iso_frame_desc[j].offset = k;
urb->iso_frame_desc[j].length =
dev->isoc_ctl.max_pkt_size;
k += dev->isoc_ctl.max_pkt_size;
}
}
init_waitqueue_head(&dma_q->wq);
/* submit urbs and enables IRQ */
for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
if (rc) {
au0828_isocdbg("submit of urb %i failed (error=%i)\n",
i, rc);
au0828_uninit_isoc(dev);
return rc;
}
}
return 0;
}
/*
* Announces that a buffer were filled and request the next
*/
static inline void buffer_filled(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf)
{
/* Advice that buffer was filled */
au0828_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
do_gettimeofday(&buf->vb.ts);
dev->isoc_ctl.buf = NULL;
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
}
static inline void vbi_buffer_filled(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf)
{
/* Advice that buffer was filled */
au0828_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
buf->vb.state = VIDEOBUF_DONE;
buf->vb.field_count++;
do_gettimeofday(&buf->vb.ts);
dev->isoc_ctl.vbi_buf = NULL;
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
}
/*
* Identify the buffer header type and properly handles
*/
static void au0828_copy_video(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf,
unsigned char *p,
unsigned char *outp, unsigned long len)
{
void *fieldstart, *startwrite, *startread;
int linesdone, currlinedone, offset, lencopy, remain;
int bytesperline = dev->width << 1; /* Assumes 16-bit depth @@@@ */
if (len == 0)
return;
if (dma_q->pos + len > buf->vb.size)
len = buf->vb.size - dma_q->pos;
startread = p;
remain = len;
/* Interlaces frame */
if (buf->top_field)
fieldstart = outp;
else
fieldstart = outp + bytesperline;
linesdone = dma_q->pos / bytesperline;
currlinedone = dma_q->pos % bytesperline;
offset = linesdone * bytesperline * 2 + currlinedone;
startwrite = fieldstart + offset;
lencopy = bytesperline - currlinedone;
lencopy = lencopy > remain ? remain : lencopy;
if ((char *)startwrite + lencopy > (char *)outp + buf->vb.size) {
au0828_isocdbg("Overflow of %zi bytes past buffer end (1)\n",
((char *)startwrite + lencopy) -
((char *)outp + buf->vb.size));
remain = (char *)outp + buf->vb.size - (char *)startwrite;
lencopy = remain;
}
if (lencopy <= 0)
return;
memcpy(startwrite, startread, lencopy);
remain -= lencopy;
while (remain > 0) {
startwrite += lencopy + bytesperline;
startread += lencopy;
if (bytesperline > remain)
lencopy = remain;
else
lencopy = bytesperline;
if ((char *)startwrite + lencopy > (char *)outp +
buf->vb.size) {
au0828_isocdbg("Overflow %zi bytes past buf end (2)\n",
((char *)startwrite + lencopy) -
((char *)outp + buf->vb.size));
lencopy = remain = (char *)outp + buf->vb.size -
(char *)startwrite;
}
if (lencopy <= 0)
break;
memcpy(startwrite, startread, lencopy);
remain -= lencopy;
}
if (offset > 1440) {
/* We have enough data to check for greenscreen */
if (outp[0] < 0x60 && outp[1440] < 0x60)
dev->greenscreen_detected = 1;
}
dma_q->pos += len;
}
/*
* video-buf generic routine to get the next available buffer
*/
static inline void get_next_buf(struct au0828_dmaqueue *dma_q,
struct au0828_buffer **buf)
{
struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vidq);
if (list_empty(&dma_q->active)) {
au0828_isocdbg("No active queue to serve\n");
dev->isoc_ctl.buf = NULL;
*buf = NULL;
return;
}
/* Get the next buffer */
*buf = list_entry(dma_q->active.next, struct au0828_buffer, vb.queue);
dev->isoc_ctl.buf = *buf;
return;
}
static void au0828_copy_vbi(struct au0828_dev *dev,
struct au0828_dmaqueue *dma_q,
struct au0828_buffer *buf,
unsigned char *p,
unsigned char *outp, unsigned long len)
{
unsigned char *startwrite, *startread;
int bytesperline;
int i, j = 0;
if (dev == NULL) {
au0828_isocdbg("dev is null\n");
return;
}
if (dma_q == NULL) {
au0828_isocdbg("dma_q is null\n");
return;
}
if (buf == NULL)
return;
if (p == NULL) {
au0828_isocdbg("p is null\n");
return;
}
if (outp == NULL) {
au0828_isocdbg("outp is null\n");
return;
}
bytesperline = dev->vbi_width;
if (dma_q->pos + len > buf->vb.size)
len = buf->vb.size - dma_q->pos;
startread = p;
startwrite = outp + (dma_q->pos / 2);
/* Make sure the bottom field populates the second half of the frame */
if (buf->top_field == 0)
startwrite += bytesperline * dev->vbi_height;
for (i = 0; i < len; i += 2)
startwrite[j++] = startread[i+1];
dma_q->pos += len;
}
/*
* video-buf generic routine to get the next available VBI buffer
*/
static inline void vbi_get_next_buf(struct au0828_dmaqueue *dma_q,
struct au0828_buffer **buf)
{
struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vbiq);
char *outp;
if (list_empty(&dma_q->active)) {
au0828_isocdbg("No active queue to serve\n");
dev->isoc_ctl.vbi_buf = NULL;
*buf = NULL;
return;
}
/* Get the next buffer */
*buf = list_entry(dma_q->active.next, struct au0828_buffer, vb.queue);
/* Cleans up buffer - Useful for testing for frame/URB loss */
outp = videobuf_to_vmalloc(&(*buf)->vb);
memset(outp, 0x00, (*buf)->vb.size);
dev->isoc_ctl.vbi_buf = *buf;
return;
}
/*
* Controls the isoc copy of each urb packet
*/
static inline int au0828_isoc_copy(struct au0828_dev *dev, struct urb *urb)
{
struct au0828_buffer *buf;
struct au0828_buffer *vbi_buf;
struct au0828_dmaqueue *dma_q = urb->context;
struct au0828_dmaqueue *vbi_dma_q = &dev->vbiq;
unsigned char *outp = NULL;
unsigned char *vbioutp = NULL;
int i, len = 0, rc = 1;
unsigned char *p;
unsigned char fbyte;
unsigned int vbi_field_size;
unsigned int remain, lencopy;
if (!dev)
return 0;
if ((dev->dev_state & DEV_DISCONNECTED) ||
(dev->dev_state & DEV_MISCONFIGURED))
return 0;
if (urb->status < 0) {
print_err_status(dev, -1, urb->status);
if (urb->status == -ENOENT)
return 0;
}
buf = dev->isoc_ctl.buf;
if (buf != NULL)
outp = videobuf_to_vmalloc(&buf->vb);
vbi_buf = dev->isoc_ctl.vbi_buf;
if (vbi_buf != NULL)
vbioutp = videobuf_to_vmalloc(&vbi_buf->vb);
for (i = 0; i < urb->number_of_packets; i++) {
int status = urb->iso_frame_desc[i].status;
if (status < 0) {
print_err_status(dev, i, status);
if (urb->iso_frame_desc[i].status != -EPROTO)
continue;
}
if (urb->iso_frame_desc[i].actual_length <= 0)
continue;
if (urb->iso_frame_desc[i].actual_length >
dev->max_pkt_size) {
au0828_isocdbg("packet bigger than packet size");
continue;
}
p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
fbyte = p[0];
len = urb->iso_frame_desc[i].actual_length - 4;
p += 4;
if (fbyte & 0x80) {
len -= 4;
p += 4;
au0828_isocdbg("Video frame %s\n",
(fbyte & 0x40) ? "odd" : "even");
if (fbyte & 0x40) {
/* VBI */
if (vbi_buf != NULL)
vbi_buffer_filled(dev,
vbi_dma_q,
vbi_buf);
vbi_get_next_buf(vbi_dma_q, &vbi_buf);
if (vbi_buf == NULL)
vbioutp = NULL;
else
vbioutp = videobuf_to_vmalloc(
&vbi_buf->vb);
/* Video */
if (buf != NULL)
buffer_filled(dev, dma_q, buf);
get_next_buf(dma_q, &buf);
if (buf == NULL)
outp = NULL;
else
outp = videobuf_to_vmalloc(&buf->vb);
/* As long as isoc traffic is arriving, keep
resetting the timer */
if (dev->vid_timeout_running)
mod_timer(&dev->vid_timeout,
jiffies + (HZ / 10));
if (dev->vbi_timeout_running)
mod_timer(&dev->vbi_timeout,
jiffies + (HZ / 10));
}
if (buf != NULL) {
if (fbyte & 0x40)
buf->top_field = 1;
else
buf->top_field = 0;
}
if (vbi_buf != NULL) {
if (fbyte & 0x40)
vbi_buf->top_field = 1;
else
vbi_buf->top_field = 0;
}
dev->vbi_read = 0;
vbi_dma_q->pos = 0;
dma_q->pos = 0;
}
vbi_field_size = dev->vbi_width * dev->vbi_height * 2;
if (dev->vbi_read < vbi_field_size) {
remain = vbi_field_size - dev->vbi_read;
if (len < remain)
lencopy = len;
else
lencopy = remain;
if (vbi_buf != NULL)
au0828_copy_vbi(dev, vbi_dma_q, vbi_buf, p,
vbioutp, len);
len -= lencopy;
p += lencopy;
dev->vbi_read += lencopy;
}
if (dev->vbi_read >= vbi_field_size && buf != NULL)
au0828_copy_video(dev, dma_q, buf, p, outp, len);
}
return rc;
}
static int
buffer_setup(struct videobuf_queue *vq, unsigned int *count,
unsigned int *size)
{
struct au0828_fh *fh = vq->priv_data;
*size = (fh->dev->width * fh->dev->height * 16 + 7) >> 3;
if (0 == *count)
*count = AU0828_DEF_BUF;
if (*count < AU0828_MIN_BUF)
*count = AU0828_MIN_BUF;
return 0;
}
/* This is called *without* dev->slock held; please keep it that way */
static void free_buffer(struct videobuf_queue *vq, struct au0828_buffer *buf)
{
struct au0828_fh *fh = vq->priv_data;
struct au0828_dev *dev = fh->dev;
unsigned long flags = 0;
if (in_interrupt())
BUG();
/* We used to wait for the buffer to finish here, but this didn't work
because, as we were keeping the state as VIDEOBUF_QUEUED,
videobuf_queue_cancel marked it as finished for us.
(Also, it could wedge forever if the hardware was misconfigured.)
This should be safe; by the time we get here, the buffer isn't
queued anymore. If we ever start marking the buffers as
VIDEOBUF_ACTIVE, it won't be, though.
*/
spin_lock_irqsave(&dev->slock, flags);
if (dev->isoc_ctl.buf == buf)
dev->isoc_ctl.buf = NULL;
spin_unlock_irqrestore(&dev->slock, flags);
videobuf_vmalloc_free(&buf->vb);
buf->vb.state = VIDEOBUF_NEEDS_INIT;
}
static int
buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct au0828_fh *fh = vq->priv_data;
struct au0828_buffer *buf = container_of(vb, struct au0828_buffer, vb);
struct au0828_dev *dev = fh->dev;
int rc = 0, urb_init = 0;
buf->vb.size = (fh->dev->width * fh->dev->height * 16 + 7) >> 3;
if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
return -EINVAL;
buf->vb.width = dev->width;
buf->vb.height = dev->height;
buf->vb.field = field;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
rc = videobuf_iolock(vq, &buf->vb, NULL);
if (rc < 0) {
printk(KERN_INFO "videobuf_iolock failed\n");
goto fail;
}
}
if (!dev->isoc_ctl.num_bufs)
urb_init = 1;
if (urb_init) {
rc = au0828_init_isoc(dev, AU0828_ISO_PACKETS_PER_URB,
AU0828_MAX_ISO_BUFS, dev->max_pkt_size,
au0828_isoc_copy);
if (rc < 0) {
printk(KERN_INFO "au0828_init_isoc failed\n");
goto fail;
}
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
free_buffer(vq, buf);
return rc;
}
static void
buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct au0828_buffer *buf = container_of(vb,
struct au0828_buffer,
vb);
struct au0828_fh *fh = vq->priv_data;
struct au0828_dev *dev = fh->dev;
struct au0828_dmaqueue *vidq = &dev->vidq;
buf->vb.state = VIDEOBUF_QUEUED;
list_add_tail(&buf->vb.queue, &vidq->active);
}
static void buffer_release(struct videobuf_queue *vq,
struct videobuf_buffer *vb)
{
struct au0828_buffer *buf = container_of(vb,
struct au0828_buffer,
vb);
free_buffer(vq, buf);
}
static struct videobuf_queue_ops au0828_video_qops = {
.buf_setup = buffer_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.buf_release = buffer_release,
};
/* ------------------------------------------------------------------
V4L2 interface
------------------------------------------------------------------*/
static int au0828_i2s_init(struct au0828_dev *dev)
{
/* Enable i2s mode */
au0828_writereg(dev, AU0828_AUDIOCTRL_50C, 0x01);
return 0;
}
/*
* Auvitek au0828 analog stream enable
* Please set interface0 to AS5 before enable the stream
*/
int au0828_analog_stream_enable(struct au0828_dev *d)
{
dprintk(1, "au0828_analog_stream_enable called\n");
au0828_writereg(d, AU0828_SENSORCTRL_VBI_103, 0x00);
au0828_writereg(d, 0x106, 0x00);
/* set x position */
au0828_writereg(d, 0x110, 0x00);
au0828_writereg(d, 0x111, 0x00);
au0828_writereg(d, 0x114, 0xa0);
au0828_writereg(d, 0x115, 0x05);
/* set y position */
au0828_writereg(d, 0x112, 0x00);
au0828_writereg(d, 0x113, 0x00);
au0828_writereg(d, 0x116, 0xf2);
au0828_writereg(d, 0x117, 0x00);
au0828_writereg(d, AU0828_SENSORCTRL_100, 0xb3);
return 0;
}
int au0828_analog_stream_disable(struct au0828_dev *d)
{
dprintk(1, "au0828_analog_stream_disable called\n");
au0828_writereg(d, AU0828_SENSORCTRL_100, 0x0);
return 0;
}
void au0828_analog_stream_reset(struct au0828_dev *dev)
{
dprintk(1, "au0828_analog_stream_reset called\n");
au0828_writereg(dev, AU0828_SENSORCTRL_100, 0x0);
mdelay(30);
au0828_writereg(dev, AU0828_SENSORCTRL_100, 0xb3);
}
/*
* Some operations needs to stop current streaming
*/
static int au0828_stream_interrupt(struct au0828_dev *dev)
{
int ret = 0;
dev->stream_state = STREAM_INTERRUPT;
if (dev->dev_state == DEV_DISCONNECTED)
return -ENODEV;
else if (ret) {
dev->dev_state = DEV_MISCONFIGURED;
dprintk(1, "%s device is misconfigured!\n", __func__);
return ret;
}
return 0;
}
/*
* au0828_release_resources
* unregister v4l2 devices
*/
void au0828_analog_unregister(struct au0828_dev *dev)
{
dprintk(1, "au0828_release_resources called\n");
mutex_lock(&au0828_sysfs_lock);
if (dev->vdev)
video_unregister_device(dev->vdev);
if (dev->vbi_dev)
video_unregister_device(dev->vbi_dev);
mutex_unlock(&au0828_sysfs_lock);
}
/* Usage lock check functions */
static int res_get(struct au0828_fh *fh, unsigned int bit)
{
struct au0828_dev *dev = fh->dev;
if (fh->resources & bit)
/* have it already allocated */
return 1;
/* is it free? */
mutex_lock(&dev->lock);
if (dev->resources & bit) {
/* no, someone else uses it */
mutex_unlock(&dev->lock);
return 0;
}
/* it's free, grab it */
fh->resources |= bit;
dev->resources |= bit;
dprintk(1, "res: get %d\n", bit);
mutex_unlock(&dev->lock);
return 1;
}
static int res_check(struct au0828_fh *fh, unsigned int bit)
{
return fh->resources & bit;
}
static int res_locked(struct au0828_dev *dev, unsigned int bit)
{
return dev->resources & bit;
}
static void res_free(struct au0828_fh *fh, unsigned int bits)
{
struct au0828_dev *dev = fh->dev;
BUG_ON((fh->resources & bits) != bits);
mutex_lock(&dev->lock);
fh->resources &= ~bits;
dev->resources &= ~bits;
dprintk(1, "res: put %d\n", bits);
mutex_unlock(&dev->lock);
}
static int get_ressource(struct au0828_fh *fh)
{
switch (fh->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
return AU0828_RESOURCE_VIDEO;
case V4L2_BUF_TYPE_VBI_CAPTURE:
return AU0828_RESOURCE_VBI;
default:
BUG();
return 0;
}
}
/* This function ensures that video frames continue to be delivered even if
the ITU-656 input isn't receiving any data (thereby preventing applications
such as tvtime from hanging) */
void au0828_vid_buffer_timeout(unsigned long data)
{
struct au0828_dev *dev = (struct au0828_dev *) data;
struct au0828_dmaqueue *dma_q = &dev->vidq;
struct au0828_buffer *buf;
unsigned char *vid_data;
unsigned long flags = 0;
spin_lock_irqsave(&dev->slock, flags);
buf = dev->isoc_ctl.buf;
if (buf != NULL) {
vid_data = videobuf_to_vmalloc(&buf->vb);
memset(vid_data, 0x00, buf->vb.size); /* Blank green frame */
buffer_filled(dev, dma_q, buf);
}
get_next_buf(dma_q, &buf);
if (dev->vid_timeout_running == 1)
mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
spin_unlock_irqrestore(&dev->slock, flags);
}
void au0828_vbi_buffer_timeout(unsigned long data)
{
struct au0828_dev *dev = (struct au0828_dev *) data;
struct au0828_dmaqueue *dma_q = &dev->vbiq;
struct au0828_buffer *buf;
unsigned char *vbi_data;
unsigned long flags = 0;
spin_lock_irqsave(&dev->slock, flags);
buf = dev->isoc_ctl.vbi_buf;
if (buf != NULL) {
vbi_data = videobuf_to_vmalloc(&buf->vb);
memset(vbi_data, 0x00, buf->vb.size);
vbi_buffer_filled(dev, dma_q, buf);
}
vbi_get_next_buf(dma_q, &buf);
if (dev->vbi_timeout_running == 1)
mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
spin_unlock_irqrestore(&dev->slock, flags);
}
static int au0828_v4l2_open(struct file *filp)
{
int ret = 0;
struct video_device *vdev = video_devdata(filp);
struct au0828_dev *dev = video_drvdata(filp);
struct au0828_fh *fh;
int type;
switch (vdev->vfl_type) {
case VFL_TYPE_GRABBER:
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
break;
case VFL_TYPE_VBI:
type = V4L2_BUF_TYPE_VBI_CAPTURE;
break;
default:
return -EINVAL;
}
fh = kzalloc(sizeof(struct au0828_fh), GFP_KERNEL);
if (NULL == fh) {
dprintk(1, "Failed allocate au0828_fh struct!\n");
return -ENOMEM;
}
fh->type = type;
fh->dev = dev;
filp->private_data = fh;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
/* set au0828 interface0 to AS5 here again */
ret = usb_set_interface(dev->usbdev, 0, 5);
if (ret < 0) {
printk(KERN_INFO "Au0828 can't set alternate to 5!\n");
return -EBUSY;
}
dev->width = NTSC_STD_W;
dev->height = NTSC_STD_H;
dev->frame_size = dev->width * dev->height * 2;
dev->field_size = dev->width * dev->height;
dev->bytesperline = dev->width * 2;
au0828_analog_stream_enable(dev);
au0828_analog_stream_reset(dev);
/* If we were doing ac97 instead of i2s, it would go here...*/
au0828_i2s_init(dev);
dev->stream_state = STREAM_OFF;
dev->dev_state |= DEV_INITIALIZED;
}
dev->users++;
videobuf_queue_vmalloc_init(&fh->vb_vidq, &au0828_video_qops,
NULL, &dev->slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_INTERLACED,
sizeof(struct au0828_buffer), fh, NULL);
/* VBI Setup */
dev->vbi_width = 720;
dev->vbi_height = 1;
videobuf_queue_vmalloc_init(&fh->vb_vbiq, &au0828_vbi_qops,
NULL, &dev->slock,
V4L2_BUF_TYPE_VBI_CAPTURE,
V4L2_FIELD_SEQ_TB,
sizeof(struct au0828_buffer), fh, NULL);
return ret;
}
static int au0828_v4l2_close(struct file *filp)
{
int ret;
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
if (res_check(fh, AU0828_RESOURCE_VIDEO)) {
/* Cancel timeout thread in case they didn't call streamoff */
dev->vid_timeout_running = 0;
del_timer_sync(&dev->vid_timeout);
videobuf_stop(&fh->vb_vidq);
res_free(fh, AU0828_RESOURCE_VIDEO);
}
if (res_check(fh, AU0828_RESOURCE_VBI)) {
/* Cancel timeout thread in case they didn't call streamoff */
dev->vbi_timeout_running = 0;
del_timer_sync(&dev->vbi_timeout);
videobuf_stop(&fh->vb_vbiq);
res_free(fh, AU0828_RESOURCE_VBI);
}
if (dev->users == 1) {
if (dev->dev_state & DEV_DISCONNECTED) {
au0828_analog_unregister(dev);
kfree(dev);
return 0;
}
au0828_analog_stream_disable(dev);
au0828_uninit_isoc(dev);
/* Save some power by putting tuner to sleep */
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_power, 0);
/* When close the device, set the usb intf0 into alt0 to free
USB bandwidth */
ret = usb_set_interface(dev->usbdev, 0, 0);
if (ret < 0)
printk(KERN_INFO "Au0828 can't set alternate to 0!\n");
}
videobuf_mmap_free(&fh->vb_vidq);
videobuf_mmap_free(&fh->vb_vbiq);
kfree(fh);
dev->users--;
wake_up_interruptible_nr(&dev->open, 1);
return 0;
}
static ssize_t au0828_v4l2_read(struct file *filp, char __user *buf,
size_t count, loff_t *pos)
{
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
if (res_locked(dev, AU0828_RESOURCE_VIDEO))
return -EBUSY;
return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
filp->f_flags & O_NONBLOCK);
}
if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
if (!res_get(fh, AU0828_RESOURCE_VBI))
return -EBUSY;
if (dev->vbi_timeout_running == 0) {
/* Handle case where caller tries to read without
calling streamon first */
dev->vbi_timeout_running = 1;
mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
}
return videobuf_read_stream(&fh->vb_vbiq, buf, count, pos, 0,
filp->f_flags & O_NONBLOCK);
}
return 0;
}
static unsigned int au0828_v4l2_poll(struct file *filp, poll_table *wait)
{
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
if (!res_get(fh, AU0828_RESOURCE_VIDEO))
return POLLERR;
return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
if (!res_get(fh, AU0828_RESOURCE_VBI))
return POLLERR;
return videobuf_poll_stream(filp, &fh->vb_vbiq, wait);
} else {
return POLLERR;
}
}
static int au0828_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
{
struct au0828_fh *fh = filp->private_data;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_mmap_mapper(&fh->vb_vbiq, vma);
return rc;
}
static int au0828_set_format(struct au0828_dev *dev, unsigned int cmd,
struct v4l2_format *format)
{
int ret;
int width = format->fmt.pix.width;
int height = format->fmt.pix.height;
if (format->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
/* If they are demanding a format other than the one we support,
bail out (tvtime asks for UYVY and then retries with YUYV) */
if (format->fmt.pix.pixelformat != V4L2_PIX_FMT_UYVY)
return -EINVAL;
/* format->fmt.pix.width only support 720 and height 480 */
if (width != 720)
width = 720;
if (height != 480)
height = 480;
format->fmt.pix.width = width;
format->fmt.pix.height = height;
format->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
format->fmt.pix.bytesperline = width * 2;
format->fmt.pix.sizeimage = width * height * 2;
format->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
format->fmt.pix.field = V4L2_FIELD_INTERLACED;
if (cmd == VIDIOC_TRY_FMT)
return 0;
/* maybe set new image format, driver current only support 720*480 */
dev->width = width;
dev->height = height;
dev->frame_size = width * height * 2;
dev->field_size = width * height;
dev->bytesperline = width * 2;
if (dev->stream_state == STREAM_ON) {
dprintk(1, "VIDIOC_SET_FMT: interrupting stream!\n");
ret = au0828_stream_interrupt(dev);
if (ret != 0) {
dprintk(1, "error interrupting video stream!\n");
return ret;
}
}
/* set au0828 interface0 to AS5 here again */
ret = usb_set_interface(dev->usbdev, 0, 5);
if (ret < 0) {
printk(KERN_INFO "Au0828 can't set alt setting to 5!\n");
return -EBUSY;
}
au0828_analog_stream_enable(dev);
return 0;
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
v4l2_device_call_all(&dev->v4l2_dev, 0, core, queryctrl, qc);
if (qc->type)
return 0;
else
return -EINVAL;
}
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
strlcpy(cap->driver, "au0828", sizeof(cap->driver));
strlcpy(cap->card, dev->board.name, sizeof(cap->card));
strlcpy(cap->bus_info, dev->v4l2_dev.name, sizeof(cap->bus_info));
/*set the device capabilities */
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_VBI_CAPTURE |
V4L2_CAP_AUDIO |
V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING |
V4L2_CAP_TUNER;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index)
return -EINVAL;
f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
strcpy(f->description, "Packed YUV2");
f->flags = 0;
f->pixelformat = V4L2_PIX_FMT_UYVY;
return 0;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
f->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
f->fmt.pix.bytesperline = dev->bytesperline;
f->fmt.pix.sizeimage = dev->frame_size;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M; /* NTSC/PAL */
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
return au0828_set_format(dev, VIDIOC_TRY_FMT, f);
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
mutex_lock(&dev->lock);
if (videobuf_queue_is_busy(&fh->vb_vidq)) {
printk(KERN_INFO "%s queue busy\n", __func__);
rc = -EBUSY;
goto out;
}
rc = au0828_set_format(dev, VIDIOC_S_FMT, f);
out:
mutex_unlock(&dev->lock);
return rc;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id * norm)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
/* FIXME: when we support something other than NTSC, we are going to
have to make the au0828 bridge adjust the size of its capture
buffer, which is currently hardcoded at 720x480 */
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_std, *norm);
return 0;
}
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *input)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
unsigned int tmp;
static const char *inames[] = {
[AU0828_VMUX_UNDEFINED] = "Undefined",
[AU0828_VMUX_COMPOSITE] = "Composite",
[AU0828_VMUX_SVIDEO] = "S-Video",
[AU0828_VMUX_CABLE] = "Cable TV",
[AU0828_VMUX_TELEVISION] = "Television",
[AU0828_VMUX_DVB] = "DVB",
[AU0828_VMUX_DEBUG] = "tv debug"
};
tmp = input->index;
if (tmp >= AU0828_MAX_INPUT)
return -EINVAL;
if (AUVI_INPUT(tmp).type == 0)
return -EINVAL;
input->index = tmp;
strcpy(input->name, inames[AUVI_INPUT(tmp).type]);
if ((AUVI_INPUT(tmp).type == AU0828_VMUX_TELEVISION) ||
(AUVI_INPUT(tmp).type == AU0828_VMUX_CABLE))
input->type |= V4L2_INPUT_TYPE_TUNER;
else
input->type |= V4L2_INPUT_TYPE_CAMERA;
input->std = dev->vdev->tvnorms;
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
*i = dev->ctrl_input;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int index)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int i;
dprintk(1, "VIDIOC_S_INPUT in function %s, input=%d\n", __func__,
index);
if (index >= AU0828_MAX_INPUT)
return -EINVAL;
if (AUVI_INPUT(index).type == 0)
return -EINVAL;
dev->ctrl_input = index;
switch (AUVI_INPUT(index).type) {
case AU0828_VMUX_SVIDEO:
dev->input_type = AU0828_VMUX_SVIDEO;
break;
case AU0828_VMUX_COMPOSITE:
dev->input_type = AU0828_VMUX_COMPOSITE;
break;
case AU0828_VMUX_TELEVISION:
dev->input_type = AU0828_VMUX_TELEVISION;
break;
default:
dprintk(1, "VIDIOC_S_INPUT unknown input type set [%d]\n",
AUVI_INPUT(index).type);
break;
}
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_routing,
AUVI_INPUT(index).vmux, 0, 0);
for (i = 0; i < AU0828_MAX_INPUT; i++) {
int enable = 0;
if (AUVI_INPUT(i).audio_setup == NULL)
continue;
if (i == index)
enable = 1;
else
enable = 0;
if (enable) {
(AUVI_INPUT(i).audio_setup)(dev, enable);
} else {
/* Make sure we leave it turned on if some
other input is routed to this callback */
if ((AUVI_INPUT(i).audio_setup) !=
((AUVI_INPUT(index).audio_setup))) {
(AUVI_INPUT(i).audio_setup)(dev, enable);
}
}
}
v4l2_device_call_all(&dev->v4l2_dev, 0, audio, s_routing,
AUVI_INPUT(index).amux, 0, 0);
return 0;
}
static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
unsigned int index = a->index;
if (a->index > 1)
return -EINVAL;
index = dev->ctrl_ainput;
if (index == 0)
strcpy(a->name, "Television");
else
strcpy(a->name, "Line in");
a->capability = V4L2_AUDCAP_STEREO;
a->index = index;
return 0;
}
static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (a->index != dev->ctrl_ainput)
return -EINVAL;
return 0;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_ctrl, ctrl);
return 0;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_ctrl, ctrl);
return 0;
}
static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (t->index != 0)
return -EINVAL;
strcpy(t->name, "Auvitek tuner");
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (t->index != 0)
return -EINVAL;
t->type = V4L2_TUNER_ANALOG_TV;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
dprintk(1, "VIDIOC_S_TUNER: signal = %x, afc = %x\n", t->signal,
t->afc);
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *freq)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
freq->type = V4L2_TUNER_ANALOG_TV;
freq->frequency = dev->ctrl_freq;
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *freq)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (freq->tuner != 0)
return -EINVAL;
if (freq->type != V4L2_TUNER_ANALOG_TV)
return -EINVAL;
dev->ctrl_freq = freq->frequency;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, freq);
au0828_analog_stream_reset(dev);
return 0;
}
/* RAW VBI ioctls */
static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
struct v4l2_format *format)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
format->fmt.vbi.samples_per_line = dev->vbi_width;
format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
format->fmt.vbi.offset = 0;
format->fmt.vbi.flags = 0;
format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
format->fmt.vbi.count[0] = dev->vbi_height;
format->fmt.vbi.count[1] = dev->vbi_height;
format->fmt.vbi.start[0] = 21;
format->fmt.vbi.start[1] = 284;
return 0;
}
static int vidioc_g_chip_ident(struct file *file, void *priv,
struct v4l2_dbg_chip_ident *chip)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
chip->ident = V4L2_IDENT_NONE;
chip->revision = 0;
if (v4l2_chip_match_host(&chip->match)) {
chip->ident = V4L2_IDENT_AU0828;
return 0;
}
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_chip_ident, chip);
if (chip->ident == V4L2_IDENT_NONE)
return -EINVAL;
return 0;
}
static int vidioc_cropcap(struct file *file, void *priv,
struct v4l2_cropcap *cc)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
cc->bounds.left = 0;
cc->bounds.top = 0;
cc->bounds.width = dev->width;
cc->bounds.height = dev->height;
cc->defrect = cc->bounds;
cc->pixelaspect.numerator = 54;
cc->pixelaspect.denominator = 59;
return 0;
}
static int vidioc_streamon(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc = -EINVAL;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (unlikely(type != fh->type))
return -EINVAL;
dprintk(1, "vidioc_streamon fh=%p t=%d fh->res=%d dev->res=%d\n",
fh, type, fh->resources, dev->resources);
if (unlikely(!res_get(fh, get_ressource(fh))))
return -EBUSY;
if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
au0828_analog_stream_enable(dev);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 1);
}
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
rc = videobuf_streamon(&fh->vb_vidq);
dev->vid_timeout_running = 1;
mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
rc = videobuf_streamon(&fh->vb_vbiq);
dev->vbi_timeout_running = 1;
mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
}
return rc;
}
static int vidioc_streamoff(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
int i;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
fh->type != V4L2_BUF_TYPE_VBI_CAPTURE)
return -EINVAL;
if (type != fh->type)
return -EINVAL;
dprintk(1, "vidioc_streamoff fh=%p t=%d fh->res=%d dev->res=%d\n",
fh, type, fh->resources, dev->resources);
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
dev->vid_timeout_running = 0;
del_timer_sync(&dev->vid_timeout);
v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
rc = au0828_stream_interrupt(dev);
if (rc != 0)
return rc;
for (i = 0; i < AU0828_MAX_INPUT; i++) {
if (AUVI_INPUT(i).audio_setup == NULL)
continue;
(AUVI_INPUT(i).audio_setup)(dev, 0);
}
videobuf_streamoff(&fh->vb_vidq);
res_free(fh, AU0828_RESOURCE_VIDEO);
} else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
dev->vbi_timeout_running = 0;
del_timer_sync(&dev->vbi_timeout);
videobuf_streamoff(&fh->vb_vbiq);
res_free(fh, AU0828_RESOURCE_VBI);
}
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int vidioc_g_register(struct file *file, void *priv,
struct v4l2_dbg_register *reg)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
switch (reg->match.type) {
case V4L2_CHIP_MATCH_I2C_DRIVER:
v4l2_device_call_all(&dev->v4l2_dev, 0, core, g_register, reg);
return 0;
default:
return -EINVAL;
}
}
static int vidioc_s_register(struct file *file, void *priv,
struct v4l2_dbg_register *reg)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
switch (reg->match.type) {
case V4L2_CHIP_MATCH_I2C_DRIVER:
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_register, reg);
return 0;
default:
return -EINVAL;
}
return 0;
}
#endif
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *rb)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_reqbufs(&fh->vb_vidq, rb);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_reqbufs(&fh->vb_vbiq, rb);
return rc;
}
static int vidioc_querybuf(struct file *file, void *priv,
struct v4l2_buffer *b)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_querybuf(&fh->vb_vidq, b);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_querybuf(&fh->vb_vbiq, b);
return rc;
}
static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_qbuf(&fh->vb_vidq, b);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_qbuf(&fh->vb_vbiq, b);
return rc;
}
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
{
struct au0828_fh *fh = priv;
struct au0828_dev *dev = fh->dev;
int rc;
rc = check_dev(dev);
if (rc < 0)
return rc;
/* Workaround for a bug in the au0828 hardware design that sometimes
results in the colorspace being inverted */
if (dev->greenscreen_detected == 1) {
dprintk(1, "Detected green frame. Resetting stream...\n");
au0828_analog_stream_reset(dev);
dev->greenscreen_detected = 0;
}
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
rc = videobuf_dqbuf(&fh->vb_vidq, b, file->f_flags & O_NONBLOCK);
else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
rc = videobuf_dqbuf(&fh->vb_vbiq, b, file->f_flags & O_NONBLOCK);
return rc;
}
static struct v4l2_file_operations au0828_v4l_fops = {
.owner = THIS_MODULE,
.open = au0828_v4l2_open,
.release = au0828_v4l2_close,
.read = au0828_v4l2_read,
.poll = au0828_v4l2_poll,
.mmap = au0828_v4l2_mmap,
.ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops video_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_g_fmt_vbi_cap = vidioc_g_fmt_vbi_cap,
.vidioc_s_fmt_vbi_cap = vidioc_g_fmt_vbi_cap,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_cropcap = vidioc_cropcap,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_s_std = vidioc_s_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.vidioc_g_register = vidioc_g_register,
.vidioc_s_register = vidioc_s_register,
#endif
.vidioc_g_chip_ident = vidioc_g_chip_ident,
};
static const struct video_device au0828_video_template = {
.fops = &au0828_v4l_fops,
.release = video_device_release,
.ioctl_ops = &video_ioctl_ops,
.tvnorms = V4L2_STD_NTSC_M,
.current_norm = V4L2_STD_NTSC_M,
};
/**************************************************************************/
int au0828_analog_register(struct au0828_dev *dev,
struct usb_interface *interface)
{
int retval = -ENOMEM;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int i;
dprintk(1, "au0828_analog_register called!\n");
/* set au0828 usb interface0 to as5 */
retval = usb_set_interface(dev->usbdev,
interface->cur_altsetting->desc.bInterfaceNumber, 5);
if (retval != 0) {
printk(KERN_INFO "Failure setting usb interface0 to as5\n");
return retval;
}
/* Figure out which endpoint has the isoc interface */
iface_desc = interface->cur_altsetting;
for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
endpoint = &iface_desc->endpoint[i].desc;
if (((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
== USB_DIR_IN) &&
((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)) {
/* we find our isoc in endpoint */
u16 tmp = le16_to_cpu(endpoint->wMaxPacketSize);
dev->max_pkt_size = (tmp & 0x07ff) *
(((tmp & 0x1800) >> 11) + 1);
dev->isoc_in_endpointaddr = endpoint->bEndpointAddress;
}
}
if (!(dev->isoc_in_endpointaddr)) {
printk(KERN_INFO "Could not locate isoc endpoint\n");
kfree(dev);
return -ENODEV;
}
init_waitqueue_head(&dev->open);
spin_lock_init(&dev->slock);
mutex_init(&dev->lock);
/* init video dma queues */
INIT_LIST_HEAD(&dev->vidq.active);
INIT_LIST_HEAD(&dev->vidq.queued);
INIT_LIST_HEAD(&dev->vbiq.active);
INIT_LIST_HEAD(&dev->vbiq.queued);
dev->vid_timeout.function = au0828_vid_buffer_timeout;
dev->vid_timeout.data = (unsigned long) dev;
init_timer(&dev->vid_timeout);
dev->vbi_timeout.function = au0828_vbi_buffer_timeout;
dev->vbi_timeout.data = (unsigned long) dev;
init_timer(&dev->vbi_timeout);
dev->width = NTSC_STD_W;
dev->height = NTSC_STD_H;
dev->field_size = dev->width * dev->height;
dev->frame_size = dev->field_size << 1;
dev->bytesperline = dev->width << 1;
dev->ctrl_ainput = 0;
/* allocate and fill v4l2 video struct */
dev->vdev = video_device_alloc();
if (NULL == dev->vdev) {
dprintk(1, "Can't allocate video_device.\n");
return -ENOMEM;
}
/* allocate the VBI struct */
dev->vbi_dev = video_device_alloc();
if (NULL == dev->vbi_dev) {
dprintk(1, "Can't allocate vbi_device.\n");
kfree(dev->vdev);
return -ENOMEM;
}
/* Fill the video capture device struct */
*dev->vdev = au0828_video_template;
dev->vdev->parent = &dev->usbdev->dev;
strcpy(dev->vdev->name, "au0828a video");
/* Setup the VBI device */
*dev->vbi_dev = au0828_video_template;
dev->vbi_dev->parent = &dev->usbdev->dev;
strcpy(dev->vbi_dev->name, "au0828a vbi");
/* Register the v4l2 device */
video_set_drvdata(dev->vdev, dev);
retval = video_register_device(dev->vdev, VFL_TYPE_GRABBER, -1);
if (retval != 0) {
dprintk(1, "unable to register video device (error = %d).\n",
retval);
video_device_release(dev->vdev);
return -ENODEV;
}
/* Register the vbi device */
video_set_drvdata(dev->vbi_dev, dev);
retval = video_register_device(dev->vbi_dev, VFL_TYPE_VBI, -1);
if (retval != 0) {
dprintk(1, "unable to register vbi device (error = %d).\n",
retval);
video_device_release(dev->vbi_dev);
video_device_release(dev->vdev);
return -ENODEV;
}
dprintk(1, "%s completed!\n", __func__);
return 0;
}
| gpl-2.0 |
multirom-armani/android_kernel_xiaomi_armani | sound/pci/cs4281.c | 4894 | 66178 | /*
* Driver for Cirrus Logic CS4281 based PCI soundcard
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>,
*
*
* 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 <asm/io.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/rawmidi.h>
#include <sound/ac97_codec.h>
#include <sound/tlv.h>
#include <sound/opl3.h>
#include <sound/initval.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("Cirrus Logic CS4281");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Cirrus Logic,CS4281}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable switches */
static bool dual_codec[SNDRV_CARDS]; /* dual codec */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for CS4281 soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for CS4281 soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable CS4281 soundcard.");
module_param_array(dual_codec, bool, NULL, 0444);
MODULE_PARM_DESC(dual_codec, "Secondary Codec ID (0 = disabled).");
/*
* Direct registers
*/
#define CS4281_BA0_SIZE 0x1000
#define CS4281_BA1_SIZE 0x10000
/*
* BA0 registers
*/
#define BA0_HISR 0x0000 /* Host Interrupt Status Register */
#define BA0_HISR_INTENA (1<<31) /* Internal Interrupt Enable Bit */
#define BA0_HISR_MIDI (1<<22) /* MIDI port interrupt */
#define BA0_HISR_FIFOI (1<<20) /* FIFO polled interrupt */
#define BA0_HISR_DMAI (1<<18) /* DMA interrupt (half or end) */
#define BA0_HISR_FIFO(c) (1<<(12+(c))) /* FIFO channel interrupt */
#define BA0_HISR_DMA(c) (1<<(8+(c))) /* DMA channel interrupt */
#define BA0_HISR_GPPI (1<<5) /* General Purpose Input (Primary chip) */
#define BA0_HISR_GPSI (1<<4) /* General Purpose Input (Secondary chip) */
#define BA0_HISR_GP3I (1<<3) /* GPIO3 pin Interrupt */
#define BA0_HISR_GP1I (1<<2) /* GPIO1 pin Interrupt */
#define BA0_HISR_VUPI (1<<1) /* VOLUP pin Interrupt */
#define BA0_HISR_VDNI (1<<0) /* VOLDN pin Interrupt */
#define BA0_HICR 0x0008 /* Host Interrupt Control Register */
#define BA0_HICR_CHGM (1<<1) /* INTENA Change Mask */
#define BA0_HICR_IEV (1<<0) /* INTENA Value */
#define BA0_HICR_EOI (3<<0) /* End of Interrupt command */
#define BA0_HIMR 0x000c /* Host Interrupt Mask Register */
/* Use same contants as for BA0_HISR */
#define BA0_IIER 0x0010 /* ISA Interrupt Enable Register */
#define BA0_HDSR0 0x00f0 /* Host DMA Engine 0 Status Register */
#define BA0_HDSR1 0x00f4 /* Host DMA Engine 1 Status Register */
#define BA0_HDSR2 0x00f8 /* Host DMA Engine 2 Status Register */
#define BA0_HDSR3 0x00fc /* Host DMA Engine 3 Status Register */
#define BA0_HDSR_CH1P (1<<25) /* Channel 1 Pending */
#define BA0_HDSR_CH2P (1<<24) /* Channel 2 Pending */
#define BA0_HDSR_DHTC (1<<17) /* DMA Half Terminal Count */
#define BA0_HDSR_DTC (1<<16) /* DMA Terminal Count */
#define BA0_HDSR_DRUN (1<<15) /* DMA Running */
#define BA0_HDSR_RQ (1<<7) /* Pending Request */
#define BA0_DCA0 0x0110 /* Host DMA Engine 0 Current Address */
#define BA0_DCC0 0x0114 /* Host DMA Engine 0 Current Count */
#define BA0_DBA0 0x0118 /* Host DMA Engine 0 Base Address */
#define BA0_DBC0 0x011c /* Host DMA Engine 0 Base Count */
#define BA0_DCA1 0x0120 /* Host DMA Engine 1 Current Address */
#define BA0_DCC1 0x0124 /* Host DMA Engine 1 Current Count */
#define BA0_DBA1 0x0128 /* Host DMA Engine 1 Base Address */
#define BA0_DBC1 0x012c /* Host DMA Engine 1 Base Count */
#define BA0_DCA2 0x0130 /* Host DMA Engine 2 Current Address */
#define BA0_DCC2 0x0134 /* Host DMA Engine 2 Current Count */
#define BA0_DBA2 0x0138 /* Host DMA Engine 2 Base Address */
#define BA0_DBC2 0x013c /* Host DMA Engine 2 Base Count */
#define BA0_DCA3 0x0140 /* Host DMA Engine 3 Current Address */
#define BA0_DCC3 0x0144 /* Host DMA Engine 3 Current Count */
#define BA0_DBA3 0x0148 /* Host DMA Engine 3 Base Address */
#define BA0_DBC3 0x014c /* Host DMA Engine 3 Base Count */
#define BA0_DMR0 0x0150 /* Host DMA Engine 0 Mode */
#define BA0_DCR0 0x0154 /* Host DMA Engine 0 Command */
#define BA0_DMR1 0x0158 /* Host DMA Engine 1 Mode */
#define BA0_DCR1 0x015c /* Host DMA Engine 1 Command */
#define BA0_DMR2 0x0160 /* Host DMA Engine 2 Mode */
#define BA0_DCR2 0x0164 /* Host DMA Engine 2 Command */
#define BA0_DMR3 0x0168 /* Host DMA Engine 3 Mode */
#define BA0_DCR3 0x016c /* Host DMA Engine 3 Command */
#define BA0_DMR_DMA (1<<29) /* Enable DMA mode */
#define BA0_DMR_POLL (1<<28) /* Enable poll mode */
#define BA0_DMR_TBC (1<<25) /* Transfer By Channel */
#define BA0_DMR_CBC (1<<24) /* Count By Channel (0 = frame resolution) */
#define BA0_DMR_SWAPC (1<<22) /* Swap Left/Right Channels */
#define BA0_DMR_SIZE20 (1<<20) /* Sample is 20-bit */
#define BA0_DMR_USIGN (1<<19) /* Unsigned */
#define BA0_DMR_BEND (1<<18) /* Big Endian */
#define BA0_DMR_MONO (1<<17) /* Mono */
#define BA0_DMR_SIZE8 (1<<16) /* Sample is 8-bit */
#define BA0_DMR_TYPE_DEMAND (0<<6)
#define BA0_DMR_TYPE_SINGLE (1<<6)
#define BA0_DMR_TYPE_BLOCK (2<<6)
#define BA0_DMR_TYPE_CASCADE (3<<6) /* Not supported */
#define BA0_DMR_DEC (1<<5) /* Access Increment (0) or Decrement (1) */
#define BA0_DMR_AUTO (1<<4) /* Auto-Initialize */
#define BA0_DMR_TR_VERIFY (0<<2) /* Verify Transfer */
#define BA0_DMR_TR_WRITE (1<<2) /* Write Transfer */
#define BA0_DMR_TR_READ (2<<2) /* Read Transfer */
#define BA0_DCR_HTCIE (1<<17) /* Half Terminal Count Interrupt */
#define BA0_DCR_TCIE (1<<16) /* Terminal Count Interrupt */
#define BA0_DCR_MSK (1<<0) /* DMA Mask bit */
#define BA0_FCR0 0x0180 /* FIFO Control 0 */
#define BA0_FCR1 0x0184 /* FIFO Control 1 */
#define BA0_FCR2 0x0188 /* FIFO Control 2 */
#define BA0_FCR3 0x018c /* FIFO Control 3 */
#define BA0_FCR_FEN (1<<31) /* FIFO Enable bit */
#define BA0_FCR_DACZ (1<<30) /* DAC Zero */
#define BA0_FCR_PSH (1<<29) /* Previous Sample Hold */
#define BA0_FCR_RS(x) (((x)&0x1f)<<24) /* Right Slot Mapping */
#define BA0_FCR_LS(x) (((x)&0x1f)<<16) /* Left Slot Mapping */
#define BA0_FCR_SZ(x) (((x)&0x7f)<<8) /* FIFO buffer size (in samples) */
#define BA0_FCR_OF(x) (((x)&0x7f)<<0) /* FIFO starting offset (in samples) */
#define BA0_FPDR0 0x0190 /* FIFO Polled Data 0 */
#define BA0_FPDR1 0x0194 /* FIFO Polled Data 1 */
#define BA0_FPDR2 0x0198 /* FIFO Polled Data 2 */
#define BA0_FPDR3 0x019c /* FIFO Polled Data 3 */
#define BA0_FCHS 0x020c /* FIFO Channel Status */
#define BA0_FCHS_RCO(x) (1<<(7+(((x)&3)<<3))) /* Right Channel Out */
#define BA0_FCHS_LCO(x) (1<<(6+(((x)&3)<<3))) /* Left Channel Out */
#define BA0_FCHS_MRP(x) (1<<(5+(((x)&3)<<3))) /* Move Read Pointer */
#define BA0_FCHS_FE(x) (1<<(4+(((x)&3)<<3))) /* FIFO Empty */
#define BA0_FCHS_FF(x) (1<<(3+(((x)&3)<<3))) /* FIFO Full */
#define BA0_FCHS_IOR(x) (1<<(2+(((x)&3)<<3))) /* Internal Overrun Flag */
#define BA0_FCHS_RCI(x) (1<<(1+(((x)&3)<<3))) /* Right Channel In */
#define BA0_FCHS_LCI(x) (1<<(0+(((x)&3)<<3))) /* Left Channel In */
#define BA0_FSIC0 0x0210 /* FIFO Status and Interrupt Control 0 */
#define BA0_FSIC1 0x0214 /* FIFO Status and Interrupt Control 1 */
#define BA0_FSIC2 0x0218 /* FIFO Status and Interrupt Control 2 */
#define BA0_FSIC3 0x021c /* FIFO Status and Interrupt Control 3 */
#define BA0_FSIC_FIC(x) (((x)&0x7f)<<24) /* FIFO Interrupt Count */
#define BA0_FSIC_FORIE (1<<23) /* FIFO OverRun Interrupt Enable */
#define BA0_FSIC_FURIE (1<<22) /* FIFO UnderRun Interrupt Enable */
#define BA0_FSIC_FSCIE (1<<16) /* FIFO Sample Count Interrupt Enable */
#define BA0_FSIC_FSC(x) (((x)&0x7f)<<8) /* FIFO Sample Count */
#define BA0_FSIC_FOR (1<<7) /* FIFO OverRun */
#define BA0_FSIC_FUR (1<<6) /* FIFO UnderRun */
#define BA0_FSIC_FSCR (1<<0) /* FIFO Sample Count Reached */
#define BA0_PMCS 0x0344 /* Power Management Control/Status */
#define BA0_CWPR 0x03e0 /* Configuration Write Protect */
#define BA0_EPPMC 0x03e4 /* Extended PCI Power Management Control */
#define BA0_EPPMC_FPDN (1<<14) /* Full Power DowN */
#define BA0_GPIOR 0x03e8 /* GPIO Pin Interface Register */
#define BA0_SPMC 0x03ec /* Serial Port Power Management Control (& ASDIN2 enable) */
#define BA0_SPMC_GIPPEN (1<<15) /* GP INT Primary PME# Enable */
#define BA0_SPMC_GISPEN (1<<14) /* GP INT Secondary PME# Enable */
#define BA0_SPMC_EESPD (1<<9) /* EEPROM Serial Port Disable */
#define BA0_SPMC_ASDI2E (1<<8) /* ASDIN2 Enable */
#define BA0_SPMC_ASDO (1<<7) /* Asynchronous ASDOUT Assertion */
#define BA0_SPMC_WUP2 (1<<3) /* Wakeup for Secondary Input */
#define BA0_SPMC_WUP1 (1<<2) /* Wakeup for Primary Input */
#define BA0_SPMC_ASYNC (1<<1) /* Asynchronous ASYNC Assertion */
#define BA0_SPMC_RSTN (1<<0) /* Reset Not! */
#define BA0_CFLR 0x03f0 /* Configuration Load Register (EEPROM or BIOS) */
#define BA0_CFLR_DEFAULT 0x00000001 /* CFLR must be in AC97 link mode */
#define BA0_IISR 0x03f4 /* ISA Interrupt Select */
#define BA0_TMS 0x03f8 /* Test Register */
#define BA0_SSVID 0x03fc /* Subsystem ID register */
#define BA0_CLKCR1 0x0400 /* Clock Control Register 1 */
#define BA0_CLKCR1_CLKON (1<<25) /* Read Only */
#define BA0_CLKCR1_DLLRDY (1<<24) /* DLL Ready */
#define BA0_CLKCR1_DLLOS (1<<6) /* DLL Output Select */
#define BA0_CLKCR1_SWCE (1<<5) /* Clock Enable */
#define BA0_CLKCR1_DLLP (1<<4) /* DLL PowerUp */
#define BA0_CLKCR1_DLLSS (((x)&3)<<3) /* DLL Source Select */
#define BA0_FRR 0x0410 /* Feature Reporting Register */
#define BA0_SLT12O 0x041c /* Slot 12 GPIO Output Register for AC-Link */
#define BA0_SERMC 0x0420 /* Serial Port Master Control */
#define BA0_SERMC_FCRN (1<<27) /* Force Codec Ready Not */
#define BA0_SERMC_ODSEN2 (1<<25) /* On-Demand Support Enable ASDIN2 */
#define BA0_SERMC_ODSEN1 (1<<24) /* On-Demand Support Enable ASDIN1 */
#define BA0_SERMC_SXLB (1<<21) /* ASDIN2 to ASDOUT Loopback */
#define BA0_SERMC_SLB (1<<20) /* ASDOUT to ASDIN2 Loopback */
#define BA0_SERMC_LOVF (1<<19) /* Loopback Output Valid Frame bit */
#define BA0_SERMC_TCID(x) (((x)&3)<<16) /* Target Secondary Codec ID */
#define BA0_SERMC_PXLB (5<<1) /* Primary Port External Loopback */
#define BA0_SERMC_PLB (4<<1) /* Primary Port Internal Loopback */
#define BA0_SERMC_PTC (7<<1) /* Port Timing Configuration */
#define BA0_SERMC_PTC_AC97 (1<<1) /* AC97 mode */
#define BA0_SERMC_MSPE (1<<0) /* Master Serial Port Enable */
#define BA0_SERC1 0x0428 /* Serial Port Configuration 1 */
#define BA0_SERC1_SO1F(x) (((x)&7)>>1) /* Primary Output Port Format */
#define BA0_SERC1_AC97 (1<<1)
#define BA0_SERC1_SO1EN (1<<0) /* Primary Output Port Enable */
#define BA0_SERC2 0x042c /* Serial Port Configuration 2 */
#define BA0_SERC2_SI1F(x) (((x)&7)>>1) /* Primary Input Port Format */
#define BA0_SERC2_AC97 (1<<1)
#define BA0_SERC2_SI1EN (1<<0) /* Primary Input Port Enable */
#define BA0_SLT12M 0x045c /* Slot 12 Monitor Register for Primary AC-Link */
#define BA0_ACCTL 0x0460 /* AC'97 Control */
#define BA0_ACCTL_TC (1<<6) /* Target Codec */
#define BA0_ACCTL_CRW (1<<4) /* 0=Write, 1=Read Command */
#define BA0_ACCTL_DCV (1<<3) /* Dynamic Command Valid */
#define BA0_ACCTL_VFRM (1<<2) /* Valid Frame */
#define BA0_ACCTL_ESYN (1<<1) /* Enable Sync */
#define BA0_ACSTS 0x0464 /* AC'97 Status */
#define BA0_ACSTS_VSTS (1<<1) /* Valid Status */
#define BA0_ACSTS_CRDY (1<<0) /* Codec Ready */
#define BA0_ACOSV 0x0468 /* AC'97 Output Slot Valid */
#define BA0_ACOSV_SLV(x) (1<<((x)-3))
#define BA0_ACCAD 0x046c /* AC'97 Command Address */
#define BA0_ACCDA 0x0470 /* AC'97 Command Data */
#define BA0_ACISV 0x0474 /* AC'97 Input Slot Valid */
#define BA0_ACISV_SLV(x) (1<<((x)-3))
#define BA0_ACSAD 0x0478 /* AC'97 Status Address */
#define BA0_ACSDA 0x047c /* AC'97 Status Data */
#define BA0_JSPT 0x0480 /* Joystick poll/trigger */
#define BA0_JSCTL 0x0484 /* Joystick control */
#define BA0_JSC1 0x0488 /* Joystick control */
#define BA0_JSC2 0x048c /* Joystick control */
#define BA0_JSIO 0x04a0
#define BA0_MIDCR 0x0490 /* MIDI Control */
#define BA0_MIDCR_MRST (1<<5) /* Reset MIDI Interface */
#define BA0_MIDCR_MLB (1<<4) /* MIDI Loop Back Enable */
#define BA0_MIDCR_TIE (1<<3) /* MIDI Transmuit Interrupt Enable */
#define BA0_MIDCR_RIE (1<<2) /* MIDI Receive Interrupt Enable */
#define BA0_MIDCR_RXE (1<<1) /* MIDI Receive Enable */
#define BA0_MIDCR_TXE (1<<0) /* MIDI Transmit Enable */
#define BA0_MIDCMD 0x0494 /* MIDI Command (wo) */
#define BA0_MIDSR 0x0494 /* MIDI Status (ro) */
#define BA0_MIDSR_RDA (1<<15) /* Sticky bit (RBE 1->0) */
#define BA0_MIDSR_TBE (1<<14) /* Sticky bit (TBF 0->1) */
#define BA0_MIDSR_RBE (1<<7) /* Receive Buffer Empty */
#define BA0_MIDSR_TBF (1<<6) /* Transmit Buffer Full */
#define BA0_MIDWP 0x0498 /* MIDI Write */
#define BA0_MIDRP 0x049c /* MIDI Read (ro) */
#define BA0_AODSD1 0x04a8 /* AC'97 On-Demand Slot Disable for primary link (ro) */
#define BA0_AODSD1_NDS(x) (1<<((x)-3))
#define BA0_AODSD2 0x04ac /* AC'97 On-Demand Slot Disable for secondary link (ro) */
#define BA0_AODSD2_NDS(x) (1<<((x)-3))
#define BA0_CFGI 0x04b0 /* Configure Interface (EEPROM interface) */
#define BA0_SLT12M2 0x04dc /* Slot 12 Monitor Register 2 for secondary AC-link */
#define BA0_ACSTS2 0x04e4 /* AC'97 Status Register 2 */
#define BA0_ACISV2 0x04f4 /* AC'97 Input Slot Valid Register 2 */
#define BA0_ACSAD2 0x04f8 /* AC'97 Status Address Register 2 */
#define BA0_ACSDA2 0x04fc /* AC'97 Status Data Register 2 */
#define BA0_FMSR 0x0730 /* FM Synthesis Status (ro) */
#define BA0_B0AP 0x0730 /* FM Bank 0 Address Port (wo) */
#define BA0_FMDP 0x0734 /* FM Data Port */
#define BA0_B1AP 0x0738 /* FM Bank 1 Address Port */
#define BA0_B1DP 0x073c /* FM Bank 1 Data Port */
#define BA0_SSPM 0x0740 /* Sound System Power Management */
#define BA0_SSPM_MIXEN (1<<6) /* Playback SRC + FM/Wavetable MIX */
#define BA0_SSPM_CSRCEN (1<<5) /* Capture Sample Rate Converter Enable */
#define BA0_SSPM_PSRCEN (1<<4) /* Playback Sample Rate Converter Enable */
#define BA0_SSPM_JSEN (1<<3) /* Joystick Enable */
#define BA0_SSPM_ACLEN (1<<2) /* Serial Port Engine and AC-Link Enable */
#define BA0_SSPM_FMEN (1<<1) /* FM Synthesis Block Enable */
#define BA0_DACSR 0x0744 /* DAC Sample Rate - Playback SRC */
#define BA0_ADCSR 0x0748 /* ADC Sample Rate - Capture SRC */
#define BA0_SSCR 0x074c /* Sound System Control Register */
#define BA0_SSCR_HVS1 (1<<23) /* Hardwave Volume Step (0=1,1=2) */
#define BA0_SSCR_MVCS (1<<19) /* Master Volume Codec Select */
#define BA0_SSCR_MVLD (1<<18) /* Master Volume Line Out Disable */
#define BA0_SSCR_MVAD (1<<17) /* Master Volume Alternate Out Disable */
#define BA0_SSCR_MVMD (1<<16) /* Master Volume Mono Out Disable */
#define BA0_SSCR_XLPSRC (1<<8) /* External SRC Loopback Mode */
#define BA0_SSCR_LPSRC (1<<7) /* SRC Loopback Mode */
#define BA0_SSCR_CDTX (1<<5) /* CD Transfer Data */
#define BA0_SSCR_HVC (1<<3) /* Harware Volume Control Enable */
#define BA0_FMLVC 0x0754 /* FM Synthesis Left Volume Control */
#define BA0_FMRVC 0x0758 /* FM Synthesis Right Volume Control */
#define BA0_SRCSA 0x075c /* SRC Slot Assignments */
#define BA0_PPLVC 0x0760 /* PCM Playback Left Volume Control */
#define BA0_PPRVC 0x0764 /* PCM Playback Right Volume Control */
#define BA0_PASR 0x0768 /* playback sample rate */
#define BA0_CASR 0x076C /* capture sample rate */
/* Source Slot Numbers - Playback */
#define SRCSLOT_LEFT_PCM_PLAYBACK 0
#define SRCSLOT_RIGHT_PCM_PLAYBACK 1
#define SRCSLOT_PHONE_LINE_1_DAC 2
#define SRCSLOT_CENTER_PCM_PLAYBACK 3
#define SRCSLOT_LEFT_SURROUND_PCM_PLAYBACK 4
#define SRCSLOT_RIGHT_SURROUND_PCM_PLAYBACK 5
#define SRCSLOT_LFE_PCM_PLAYBACK 6
#define SRCSLOT_PHONE_LINE_2_DAC 7
#define SRCSLOT_HEADSET_DAC 8
#define SRCSLOT_LEFT_WT 29 /* invalid for BA0_SRCSA */
#define SRCSLOT_RIGHT_WT 30 /* invalid for BA0_SRCSA */
/* Source Slot Numbers - Capture */
#define SRCSLOT_LEFT_PCM_RECORD 10
#define SRCSLOT_RIGHT_PCM_RECORD 11
#define SRCSLOT_PHONE_LINE_1_ADC 12
#define SRCSLOT_MIC_ADC 13
#define SRCSLOT_PHONE_LINE_2_ADC 17
#define SRCSLOT_HEADSET_ADC 18
#define SRCSLOT_SECONDARY_LEFT_PCM_RECORD 20
#define SRCSLOT_SECONDARY_RIGHT_PCM_RECORD 21
#define SRCSLOT_SECONDARY_PHONE_LINE_1_ADC 22
#define SRCSLOT_SECONDARY_MIC_ADC 23
#define SRCSLOT_SECONDARY_PHONE_LINE_2_ADC 27
#define SRCSLOT_SECONDARY_HEADSET_ADC 28
/* Source Slot Numbers - Others */
#define SRCSLOT_POWER_DOWN 31
/* MIDI modes */
#define CS4281_MODE_OUTPUT (1<<0)
#define CS4281_MODE_INPUT (1<<1)
/* joystick bits */
/* Bits for JSPT */
#define JSPT_CAX 0x00000001
#define JSPT_CAY 0x00000002
#define JSPT_CBX 0x00000004
#define JSPT_CBY 0x00000008
#define JSPT_BA1 0x00000010
#define JSPT_BA2 0x00000020
#define JSPT_BB1 0x00000040
#define JSPT_BB2 0x00000080
/* Bits for JSCTL */
#define JSCTL_SP_MASK 0x00000003
#define JSCTL_SP_SLOW 0x00000000
#define JSCTL_SP_MEDIUM_SLOW 0x00000001
#define JSCTL_SP_MEDIUM_FAST 0x00000002
#define JSCTL_SP_FAST 0x00000003
#define JSCTL_ARE 0x00000004
/* Data register pairs masks */
#define JSC1_Y1V_MASK 0x0000FFFF
#define JSC1_X1V_MASK 0xFFFF0000
#define JSC1_Y1V_SHIFT 0
#define JSC1_X1V_SHIFT 16
#define JSC2_Y2V_MASK 0x0000FFFF
#define JSC2_X2V_MASK 0xFFFF0000
#define JSC2_Y2V_SHIFT 0
#define JSC2_X2V_SHIFT 16
/* JS GPIO */
#define JSIO_DAX 0x00000001
#define JSIO_DAY 0x00000002
#define JSIO_DBX 0x00000004
#define JSIO_DBY 0x00000008
#define JSIO_AXOE 0x00000010
#define JSIO_AYOE 0x00000020
#define JSIO_BXOE 0x00000040
#define JSIO_BYOE 0x00000080
/*
*
*/
struct cs4281_dma {
struct snd_pcm_substream *substream;
unsigned int regDBA; /* offset to DBA register */
unsigned int regDCA; /* offset to DCA register */
unsigned int regDBC; /* offset to DBC register */
unsigned int regDCC; /* offset to DCC register */
unsigned int regDMR; /* offset to DMR register */
unsigned int regDCR; /* offset to DCR register */
unsigned int regHDSR; /* offset to HDSR register */
unsigned int regFCR; /* offset to FCR register */
unsigned int regFSIC; /* offset to FSIC register */
unsigned int valDMR; /* DMA mode */
unsigned int valDCR; /* DMA command */
unsigned int valFCR; /* FIFO control */
unsigned int fifo_offset; /* FIFO offset within BA1 */
unsigned char left_slot; /* FIFO left slot */
unsigned char right_slot; /* FIFO right slot */
int frag; /* period number */
};
#define SUSPEND_REGISTERS 20
struct cs4281 {
int irq;
void __iomem *ba0; /* virtual (accessible) address */
void __iomem *ba1; /* virtual (accessible) address */
unsigned long ba0_addr;
unsigned long ba1_addr;
int dual_codec;
struct snd_ac97_bus *ac97_bus;
struct snd_ac97 *ac97;
struct snd_ac97 *ac97_secondary;
struct pci_dev *pci;
struct snd_card *card;
struct snd_pcm *pcm;
struct snd_rawmidi *rmidi;
struct snd_rawmidi_substream *midi_input;
struct snd_rawmidi_substream *midi_output;
struct cs4281_dma dma[4];
unsigned char src_left_play_slot;
unsigned char src_right_play_slot;
unsigned char src_left_rec_slot;
unsigned char src_right_rec_slot;
unsigned int spurious_dhtc_irq;
unsigned int spurious_dtc_irq;
spinlock_t reg_lock;
unsigned int midcr;
unsigned int uartm;
struct gameport *gameport;
#ifdef CONFIG_PM
u32 suspend_regs[SUSPEND_REGISTERS];
#endif
};
static irqreturn_t snd_cs4281_interrupt(int irq, void *dev_id);
static DEFINE_PCI_DEVICE_TABLE(snd_cs4281_ids) = {
{ PCI_VDEVICE(CIRRUS, 0x6005), 0, }, /* CS4281 */
{ 0, }
};
MODULE_DEVICE_TABLE(pci, snd_cs4281_ids);
/*
* constants
*/
#define CS4281_FIFO_SIZE 32
/*
* common I/O routines
*/
static inline void snd_cs4281_pokeBA0(struct cs4281 *chip, unsigned long offset,
unsigned int val)
{
writel(val, chip->ba0 + offset);
}
static inline unsigned int snd_cs4281_peekBA0(struct cs4281 *chip, unsigned long offset)
{
return readl(chip->ba0 + offset);
}
static void snd_cs4281_ac97_write(struct snd_ac97 *ac97,
unsigned short reg, unsigned short val)
{
/*
* 1. Write ACCAD = Command Address Register = 46Ch for AC97 register address
* 2. Write ACCDA = Command Data Register = 470h for data to write to AC97
* 3. Write ACCTL = Control Register = 460h for initiating the write
* 4. Read ACCTL = 460h, DCV should be reset by now and 460h = 07h
* 5. if DCV not cleared, break and return error
*/
struct cs4281 *chip = ac97->private_data;
int count;
/*
* Setup the AC97 control registers on the CS461x to send the
* appropriate command to the AC97 to perform the read.
* ACCAD = Command Address Register = 46Ch
* ACCDA = Command Data Register = 470h
* ACCTL = Control Register = 460h
* set DCV - will clear when process completed
* reset CRW - Write command
* set VFRM - valid frame enabled
* set ESYN - ASYNC generation enabled
* set RSTN - ARST# inactive, AC97 codec not reset
*/
snd_cs4281_pokeBA0(chip, BA0_ACCAD, reg);
snd_cs4281_pokeBA0(chip, BA0_ACCDA, val);
snd_cs4281_pokeBA0(chip, BA0_ACCTL, BA0_ACCTL_DCV | BA0_ACCTL_VFRM |
BA0_ACCTL_ESYN | (ac97->num ? BA0_ACCTL_TC : 0));
for (count = 0; count < 2000; count++) {
/*
* First, we want to wait for a short time.
*/
udelay(10);
/*
* Now, check to see if the write has completed.
* ACCTL = 460h, DCV should be reset by now and 460h = 07h
*/
if (!(snd_cs4281_peekBA0(chip, BA0_ACCTL) & BA0_ACCTL_DCV)) {
return;
}
}
snd_printk(KERN_ERR "AC'97 write problem, reg = 0x%x, val = 0x%x\n", reg, val);
}
static unsigned short snd_cs4281_ac97_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct cs4281 *chip = ac97->private_data;
int count;
unsigned short result;
// FIXME: volatile is necessary in the following due to a bug of
// some gcc versions
volatile int ac97_num = ((volatile struct snd_ac97 *)ac97)->num;
/*
* 1. Write ACCAD = Command Address Register = 46Ch for AC97 register address
* 2. Write ACCDA = Command Data Register = 470h for data to write to AC97
* 3. Write ACCTL = Control Register = 460h for initiating the write
* 4. Read ACCTL = 460h, DCV should be reset by now and 460h = 17h
* 5. if DCV not cleared, break and return error
* 6. Read ACSTS = Status Register = 464h, check VSTS bit
*/
snd_cs4281_peekBA0(chip, ac97_num ? BA0_ACSDA2 : BA0_ACSDA);
/*
* Setup the AC97 control registers on the CS461x to send the
* appropriate command to the AC97 to perform the read.
* ACCAD = Command Address Register = 46Ch
* ACCDA = Command Data Register = 470h
* ACCTL = Control Register = 460h
* set DCV - will clear when process completed
* set CRW - Read command
* set VFRM - valid frame enabled
* set ESYN - ASYNC generation enabled
* set RSTN - ARST# inactive, AC97 codec not reset
*/
snd_cs4281_pokeBA0(chip, BA0_ACCAD, reg);
snd_cs4281_pokeBA0(chip, BA0_ACCDA, 0);
snd_cs4281_pokeBA0(chip, BA0_ACCTL, BA0_ACCTL_DCV | BA0_ACCTL_CRW |
BA0_ACCTL_VFRM | BA0_ACCTL_ESYN |
(ac97_num ? BA0_ACCTL_TC : 0));
/*
* Wait for the read to occur.
*/
for (count = 0; count < 500; count++) {
/*
* First, we want to wait for a short time.
*/
udelay(10);
/*
* Now, check to see if the read has completed.
* ACCTL = 460h, DCV should be reset by now and 460h = 17h
*/
if (!(snd_cs4281_peekBA0(chip, BA0_ACCTL) & BA0_ACCTL_DCV))
goto __ok1;
}
snd_printk(KERN_ERR "AC'97 read problem (ACCTL_DCV), reg = 0x%x\n", reg);
result = 0xffff;
goto __end;
__ok1:
/*
* Wait for the valid status bit to go active.
*/
for (count = 0; count < 100; count++) {
/*
* Read the AC97 status register.
* ACSTS = Status Register = 464h
* VSTS - Valid Status
*/
if (snd_cs4281_peekBA0(chip, ac97_num ? BA0_ACSTS2 : BA0_ACSTS) & BA0_ACSTS_VSTS)
goto __ok2;
udelay(10);
}
snd_printk(KERN_ERR "AC'97 read problem (ACSTS_VSTS), reg = 0x%x\n", reg);
result = 0xffff;
goto __end;
__ok2:
/*
* Read the data returned from the AC97 register.
* ACSDA = Status Data Register = 474h
*/
result = snd_cs4281_peekBA0(chip, ac97_num ? BA0_ACSDA2 : BA0_ACSDA);
__end:
return result;
}
/*
* PCM part
*/
static int snd_cs4281_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct cs4281_dma *dma = substream->runtime->private_data;
struct cs4281 *chip = snd_pcm_substream_chip(substream);
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
dma->valDCR |= BA0_DCR_MSK;
dma->valFCR |= BA0_FCR_FEN;
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
dma->valDCR &= ~BA0_DCR_MSK;
dma->valFCR &= ~BA0_FCR_FEN;
break;
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
snd_cs4281_pokeBA0(chip, dma->regDMR, dma->valDMR & ~BA0_DMR_DMA);
dma->valDMR |= BA0_DMR_DMA;
dma->valDCR &= ~BA0_DCR_MSK;
dma->valFCR |= BA0_FCR_FEN;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
dma->valDMR &= ~(BA0_DMR_DMA|BA0_DMR_POLL);
dma->valDCR |= BA0_DCR_MSK;
dma->valFCR &= ~BA0_FCR_FEN;
/* Leave wave playback FIFO enabled for FM */
if (dma->regFCR != BA0_FCR0)
dma->valFCR &= ~BA0_FCR_FEN;
break;
default:
spin_unlock(&chip->reg_lock);
return -EINVAL;
}
snd_cs4281_pokeBA0(chip, dma->regDMR, dma->valDMR);
snd_cs4281_pokeBA0(chip, dma->regFCR, dma->valFCR);
snd_cs4281_pokeBA0(chip, dma->regDCR, dma->valDCR);
spin_unlock(&chip->reg_lock);
return 0;
}
static unsigned int snd_cs4281_rate(unsigned int rate, unsigned int *real_rate)
{
unsigned int val = ~0;
if (real_rate)
*real_rate = rate;
/* special "hardcoded" rates */
switch (rate) {
case 8000: return 5;
case 11025: return 4;
case 16000: return 3;
case 22050: return 2;
case 44100: return 1;
case 48000: return 0;
default:
goto __variable;
}
__variable:
val = 1536000 / rate;
if (real_rate)
*real_rate = 1536000 / val;
return val;
}
static void snd_cs4281_mode(struct cs4281 *chip, struct cs4281_dma *dma,
struct snd_pcm_runtime *runtime,
int capture, int src)
{
int rec_mono;
dma->valDMR = BA0_DMR_TYPE_SINGLE | BA0_DMR_AUTO |
(capture ? BA0_DMR_TR_WRITE : BA0_DMR_TR_READ);
if (runtime->channels == 1)
dma->valDMR |= BA0_DMR_MONO;
if (snd_pcm_format_unsigned(runtime->format) > 0)
dma->valDMR |= BA0_DMR_USIGN;
if (snd_pcm_format_big_endian(runtime->format) > 0)
dma->valDMR |= BA0_DMR_BEND;
switch (snd_pcm_format_width(runtime->format)) {
case 8: dma->valDMR |= BA0_DMR_SIZE8;
if (runtime->channels == 1)
dma->valDMR |= BA0_DMR_SWAPC;
break;
case 32: dma->valDMR |= BA0_DMR_SIZE20; break;
}
dma->frag = 0; /* for workaround */
dma->valDCR = BA0_DCR_TCIE | BA0_DCR_MSK;
if (runtime->buffer_size != runtime->period_size)
dma->valDCR |= BA0_DCR_HTCIE;
/* Initialize DMA */
snd_cs4281_pokeBA0(chip, dma->regDBA, runtime->dma_addr);
snd_cs4281_pokeBA0(chip, dma->regDBC, runtime->buffer_size - 1);
rec_mono = (chip->dma[1].valDMR & BA0_DMR_MONO) == BA0_DMR_MONO;
snd_cs4281_pokeBA0(chip, BA0_SRCSA, (chip->src_left_play_slot << 0) |
(chip->src_right_play_slot << 8) |
(chip->src_left_rec_slot << 16) |
((rec_mono ? 31 : chip->src_right_rec_slot) << 24));
if (!src)
goto __skip_src;
if (!capture) {
if (dma->left_slot == chip->src_left_play_slot) {
unsigned int val = snd_cs4281_rate(runtime->rate, NULL);
snd_BUG_ON(dma->right_slot != chip->src_right_play_slot);
snd_cs4281_pokeBA0(chip, BA0_DACSR, val);
}
} else {
if (dma->left_slot == chip->src_left_rec_slot) {
unsigned int val = snd_cs4281_rate(runtime->rate, NULL);
snd_BUG_ON(dma->right_slot != chip->src_right_rec_slot);
snd_cs4281_pokeBA0(chip, BA0_ADCSR, val);
}
}
__skip_src:
/* Deactivate wave playback FIFO before changing slot assignments */
if (dma->regFCR == BA0_FCR0)
snd_cs4281_pokeBA0(chip, dma->regFCR, snd_cs4281_peekBA0(chip, dma->regFCR) & ~BA0_FCR_FEN);
/* Initialize FIFO */
dma->valFCR = BA0_FCR_LS(dma->left_slot) |
BA0_FCR_RS(capture && (dma->valDMR & BA0_DMR_MONO) ? 31 : dma->right_slot) |
BA0_FCR_SZ(CS4281_FIFO_SIZE) |
BA0_FCR_OF(dma->fifo_offset);
snd_cs4281_pokeBA0(chip, dma->regFCR, dma->valFCR | (capture ? BA0_FCR_PSH : 0));
/* Activate FIFO again for FM playback */
if (dma->regFCR == BA0_FCR0)
snd_cs4281_pokeBA0(chip, dma->regFCR, dma->valFCR | BA0_FCR_FEN);
/* Clear FIFO Status and Interrupt Control Register */
snd_cs4281_pokeBA0(chip, dma->regFSIC, 0);
}
static int snd_cs4281_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_cs4281_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
static int snd_cs4281_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct cs4281_dma *dma = runtime->private_data;
struct cs4281 *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
snd_cs4281_mode(chip, dma, runtime, 0, 1);
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cs4281_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct cs4281_dma *dma = runtime->private_data;
struct cs4281 *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
snd_cs4281_mode(chip, dma, runtime, 1, 1);
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static snd_pcm_uframes_t snd_cs4281_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct cs4281_dma *dma = runtime->private_data;
struct cs4281 *chip = snd_pcm_substream_chip(substream);
/*
printk(KERN_DEBUG "DCC = 0x%x, buffer_size = 0x%x, jiffies = %li\n",
snd_cs4281_peekBA0(chip, dma->regDCC), runtime->buffer_size,
jiffies);
*/
return runtime->buffer_size -
snd_cs4281_peekBA0(chip, dma->regDCC) - 1;
}
static struct snd_pcm_hardware snd_cs4281_playback =
{
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME,
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S8 |
SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_U16_BE | SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_U32_LE | SNDRV_PCM_FMTBIT_S32_LE |
SNDRV_PCM_FMTBIT_U32_BE | SNDRV_PCM_FMTBIT_S32_BE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (512*1024),
.period_bytes_min = 64,
.period_bytes_max = (512*1024),
.periods_min = 1,
.periods_max = 2,
.fifo_size = CS4281_FIFO_SIZE,
};
static struct snd_pcm_hardware snd_cs4281_capture =
{
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME,
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S8 |
SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_U16_BE | SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_U32_LE | SNDRV_PCM_FMTBIT_S32_LE |
SNDRV_PCM_FMTBIT_U32_BE | SNDRV_PCM_FMTBIT_S32_BE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (512*1024),
.period_bytes_min = 64,
.period_bytes_max = (512*1024),
.periods_min = 1,
.periods_max = 2,
.fifo_size = CS4281_FIFO_SIZE,
};
static int snd_cs4281_playback_open(struct snd_pcm_substream *substream)
{
struct cs4281 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct cs4281_dma *dma;
dma = &chip->dma[0];
dma->substream = substream;
dma->left_slot = 0;
dma->right_slot = 1;
runtime->private_data = dma;
runtime->hw = snd_cs4281_playback;
/* should be detected from the AC'97 layer, but it seems
that although CS4297A rev B reports 18-bit ADC resolution,
samples are 20-bit */
snd_pcm_hw_constraint_msbits(runtime, 0, 32, 20);
return 0;
}
static int snd_cs4281_capture_open(struct snd_pcm_substream *substream)
{
struct cs4281 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct cs4281_dma *dma;
dma = &chip->dma[1];
dma->substream = substream;
dma->left_slot = 10;
dma->right_slot = 11;
runtime->private_data = dma;
runtime->hw = snd_cs4281_capture;
/* should be detected from the AC'97 layer, but it seems
that although CS4297A rev B reports 18-bit ADC resolution,
samples are 20-bit */
snd_pcm_hw_constraint_msbits(runtime, 0, 32, 20);
return 0;
}
static int snd_cs4281_playback_close(struct snd_pcm_substream *substream)
{
struct cs4281_dma *dma = substream->runtime->private_data;
dma->substream = NULL;
return 0;
}
static int snd_cs4281_capture_close(struct snd_pcm_substream *substream)
{
struct cs4281_dma *dma = substream->runtime->private_data;
dma->substream = NULL;
return 0;
}
static struct snd_pcm_ops snd_cs4281_playback_ops = {
.open = snd_cs4281_playback_open,
.close = snd_cs4281_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cs4281_hw_params,
.hw_free = snd_cs4281_hw_free,
.prepare = snd_cs4281_playback_prepare,
.trigger = snd_cs4281_trigger,
.pointer = snd_cs4281_pointer,
};
static struct snd_pcm_ops snd_cs4281_capture_ops = {
.open = snd_cs4281_capture_open,
.close = snd_cs4281_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cs4281_hw_params,
.hw_free = snd_cs4281_hw_free,
.prepare = snd_cs4281_capture_prepare,
.trigger = snd_cs4281_trigger,
.pointer = snd_cs4281_pointer,
};
static int __devinit snd_cs4281_pcm(struct cs4281 * chip, int device,
struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
err = snd_pcm_new(chip->card, "CS4281", device, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cs4281_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cs4281_capture_ops);
pcm->private_data = chip;
pcm->info_flags = 0;
strcpy(pcm->name, "CS4281");
chip->pcm = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 512*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
/*
* Mixer section
*/
#define CS_VOL_MASK 0x1f
static int snd_cs4281_info_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = CS_VOL_MASK;
return 0;
}
static int snd_cs4281_get_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cs4281 *chip = snd_kcontrol_chip(kcontrol);
int regL = (kcontrol->private_value >> 16) & 0xffff;
int regR = kcontrol->private_value & 0xffff;
int volL, volR;
volL = CS_VOL_MASK - (snd_cs4281_peekBA0(chip, regL) & CS_VOL_MASK);
volR = CS_VOL_MASK - (snd_cs4281_peekBA0(chip, regR) & CS_VOL_MASK);
ucontrol->value.integer.value[0] = volL;
ucontrol->value.integer.value[1] = volR;
return 0;
}
static int snd_cs4281_put_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct cs4281 *chip = snd_kcontrol_chip(kcontrol);
int change = 0;
int regL = (kcontrol->private_value >> 16) & 0xffff;
int regR = kcontrol->private_value & 0xffff;
int volL, volR;
volL = CS_VOL_MASK - (snd_cs4281_peekBA0(chip, regL) & CS_VOL_MASK);
volR = CS_VOL_MASK - (snd_cs4281_peekBA0(chip, regR) & CS_VOL_MASK);
if (ucontrol->value.integer.value[0] != volL) {
volL = CS_VOL_MASK - (ucontrol->value.integer.value[0] & CS_VOL_MASK);
snd_cs4281_pokeBA0(chip, regL, volL);
change = 1;
}
if (ucontrol->value.integer.value[1] != volR) {
volR = CS_VOL_MASK - (ucontrol->value.integer.value[1] & CS_VOL_MASK);
snd_cs4281_pokeBA0(chip, regR, volR);
change = 1;
}
return change;
}
static const DECLARE_TLV_DB_SCALE(db_scale_dsp, -4650, 150, 0);
static struct snd_kcontrol_new snd_cs4281_fm_vol =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Synth Playback Volume",
.info = snd_cs4281_info_volume,
.get = snd_cs4281_get_volume,
.put = snd_cs4281_put_volume,
.private_value = ((BA0_FMLVC << 16) | BA0_FMRVC),
.tlv = { .p = db_scale_dsp },
};
static struct snd_kcontrol_new snd_cs4281_pcm_vol =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Stream Playback Volume",
.info = snd_cs4281_info_volume,
.get = snd_cs4281_get_volume,
.put = snd_cs4281_put_volume,
.private_value = ((BA0_PPLVC << 16) | BA0_PPRVC),
.tlv = { .p = db_scale_dsp },
};
static void snd_cs4281_mixer_free_ac97_bus(struct snd_ac97_bus *bus)
{
struct cs4281 *chip = bus->private_data;
chip->ac97_bus = NULL;
}
static void snd_cs4281_mixer_free_ac97(struct snd_ac97 *ac97)
{
struct cs4281 *chip = ac97->private_data;
if (ac97->num)
chip->ac97_secondary = NULL;
else
chip->ac97 = NULL;
}
static int __devinit snd_cs4281_mixer(struct cs4281 * chip)
{
struct snd_card *card = chip->card;
struct snd_ac97_template ac97;
int err;
static struct snd_ac97_bus_ops ops = {
.write = snd_cs4281_ac97_write,
.read = snd_cs4281_ac97_read,
};
if ((err = snd_ac97_bus(card, 0, &ops, chip, &chip->ac97_bus)) < 0)
return err;
chip->ac97_bus->private_free = snd_cs4281_mixer_free_ac97_bus;
memset(&ac97, 0, sizeof(ac97));
ac97.private_data = chip;
ac97.private_free = snd_cs4281_mixer_free_ac97;
if ((err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97)) < 0)
return err;
if (chip->dual_codec) {
ac97.num = 1;
if ((err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97_secondary)) < 0)
return err;
}
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_cs4281_fm_vol, chip))) < 0)
return err;
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_cs4281_pcm_vol, chip))) < 0)
return err;
return 0;
}
/*
* proc interface
*/
static void snd_cs4281_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct cs4281 *chip = entry->private_data;
snd_iprintf(buffer, "Cirrus Logic CS4281\n\n");
snd_iprintf(buffer, "Spurious half IRQs : %u\n", chip->spurious_dhtc_irq);
snd_iprintf(buffer, "Spurious end IRQs : %u\n", chip->spurious_dtc_irq);
}
static ssize_t snd_cs4281_BA0_read(struct snd_info_entry *entry,
void *file_private_data,
struct file *file, char __user *buf,
size_t count, loff_t pos)
{
struct cs4281 *chip = entry->private_data;
if (copy_to_user_fromio(buf, chip->ba0 + pos, count))
return -EFAULT;
return count;
}
static ssize_t snd_cs4281_BA1_read(struct snd_info_entry *entry,
void *file_private_data,
struct file *file, char __user *buf,
size_t count, loff_t pos)
{
struct cs4281 *chip = entry->private_data;
if (copy_to_user_fromio(buf, chip->ba1 + pos, count))
return -EFAULT;
return count;
}
static struct snd_info_entry_ops snd_cs4281_proc_ops_BA0 = {
.read = snd_cs4281_BA0_read,
};
static struct snd_info_entry_ops snd_cs4281_proc_ops_BA1 = {
.read = snd_cs4281_BA1_read,
};
static void __devinit snd_cs4281_proc_init(struct cs4281 * chip)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(chip->card, "cs4281", &entry))
snd_info_set_text_ops(entry, chip, snd_cs4281_proc_read);
if (! snd_card_proc_new(chip->card, "cs4281_BA0", &entry)) {
entry->content = SNDRV_INFO_CONTENT_DATA;
entry->private_data = chip;
entry->c.ops = &snd_cs4281_proc_ops_BA0;
entry->size = CS4281_BA0_SIZE;
}
if (! snd_card_proc_new(chip->card, "cs4281_BA1", &entry)) {
entry->content = SNDRV_INFO_CONTENT_DATA;
entry->private_data = chip;
entry->c.ops = &snd_cs4281_proc_ops_BA1;
entry->size = CS4281_BA1_SIZE;
}
}
/*
* joystick support
*/
#if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
static void snd_cs4281_gameport_trigger(struct gameport *gameport)
{
struct cs4281 *chip = gameport_get_port_data(gameport);
if (snd_BUG_ON(!chip))
return;
snd_cs4281_pokeBA0(chip, BA0_JSPT, 0xff);
}
static unsigned char snd_cs4281_gameport_read(struct gameport *gameport)
{
struct cs4281 *chip = gameport_get_port_data(gameport);
if (snd_BUG_ON(!chip))
return 0;
return snd_cs4281_peekBA0(chip, BA0_JSPT);
}
#ifdef COOKED_MODE
static int snd_cs4281_gameport_cooked_read(struct gameport *gameport,
int *axes, int *buttons)
{
struct cs4281 *chip = gameport_get_port_data(gameport);
unsigned js1, js2, jst;
if (snd_BUG_ON(!chip))
return 0;
js1 = snd_cs4281_peekBA0(chip, BA0_JSC1);
js2 = snd_cs4281_peekBA0(chip, BA0_JSC2);
jst = snd_cs4281_peekBA0(chip, BA0_JSPT);
*buttons = (~jst >> 4) & 0x0F;
axes[0] = ((js1 & JSC1_Y1V_MASK) >> JSC1_Y1V_SHIFT) & 0xFFFF;
axes[1] = ((js1 & JSC1_X1V_MASK) >> JSC1_X1V_SHIFT) & 0xFFFF;
axes[2] = ((js2 & JSC2_Y2V_MASK) >> JSC2_Y2V_SHIFT) & 0xFFFF;
axes[3] = ((js2 & JSC2_X2V_MASK) >> JSC2_X2V_SHIFT) & 0xFFFF;
for (jst = 0; jst < 4; ++jst)
if (axes[jst] == 0xFFFF) axes[jst] = -1;
return 0;
}
#else
#define snd_cs4281_gameport_cooked_read NULL
#endif
static int snd_cs4281_gameport_open(struct gameport *gameport, int mode)
{
switch (mode) {
#ifdef COOKED_MODE
case GAMEPORT_MODE_COOKED:
return 0;
#endif
case GAMEPORT_MODE_RAW:
return 0;
default:
return -1;
}
return 0;
}
static int __devinit snd_cs4281_create_gameport(struct cs4281 *chip)
{
struct gameport *gp;
chip->gameport = gp = gameport_allocate_port();
if (!gp) {
printk(KERN_ERR "cs4281: cannot allocate memory for gameport\n");
return -ENOMEM;
}
gameport_set_name(gp, "CS4281 Gameport");
gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci));
gameport_set_dev_parent(gp, &chip->pci->dev);
gp->open = snd_cs4281_gameport_open;
gp->read = snd_cs4281_gameport_read;
gp->trigger = snd_cs4281_gameport_trigger;
gp->cooked_read = snd_cs4281_gameport_cooked_read;
gameport_set_port_data(gp, chip);
snd_cs4281_pokeBA0(chip, BA0_JSIO, 0xFF); // ?
snd_cs4281_pokeBA0(chip, BA0_JSCTL, JSCTL_SP_MEDIUM_SLOW);
gameport_register_port(gp);
return 0;
}
static void snd_cs4281_free_gameport(struct cs4281 *chip)
{
if (chip->gameport) {
gameport_unregister_port(chip->gameport);
chip->gameport = NULL;
}
}
#else
static inline int snd_cs4281_create_gameport(struct cs4281 *chip) { return -ENOSYS; }
static inline void snd_cs4281_free_gameport(struct cs4281 *chip) { }
#endif /* CONFIG_GAMEPORT || (MODULE && CONFIG_GAMEPORT_MODULE) */
static int snd_cs4281_free(struct cs4281 *chip)
{
snd_cs4281_free_gameport(chip);
if (chip->irq >= 0)
synchronize_irq(chip->irq);
/* Mask interrupts */
snd_cs4281_pokeBA0(chip, BA0_HIMR, 0x7fffffff);
/* Stop the DLL Clock logic. */
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, 0);
/* Sound System Power Management - Turn Everything OFF */
snd_cs4281_pokeBA0(chip, BA0_SSPM, 0);
/* PCI interface - D3 state */
pci_set_power_state(chip->pci, 3);
if (chip->irq >= 0)
free_irq(chip->irq, chip);
if (chip->ba0)
iounmap(chip->ba0);
if (chip->ba1)
iounmap(chip->ba1);
pci_release_regions(chip->pci);
pci_disable_device(chip->pci);
kfree(chip);
return 0;
}
static int snd_cs4281_dev_free(struct snd_device *device)
{
struct cs4281 *chip = device->device_data;
return snd_cs4281_free(chip);
}
static int snd_cs4281_chip_init(struct cs4281 *chip); /* defined below */
static int __devinit snd_cs4281_create(struct snd_card *card,
struct pci_dev *pci,
struct cs4281 ** rchip,
int dual_codec)
{
struct cs4281 *chip;
unsigned int tmp;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_cs4281_dev_free,
};
*rchip = NULL;
if ((err = pci_enable_device(pci)) < 0)
return err;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&chip->reg_lock);
chip->card = card;
chip->pci = pci;
chip->irq = -1;
pci_set_master(pci);
if (dual_codec < 0 || dual_codec > 3) {
snd_printk(KERN_ERR "invalid dual_codec option %d\n", dual_codec);
dual_codec = 0;
}
chip->dual_codec = dual_codec;
if ((err = pci_request_regions(pci, "CS4281")) < 0) {
kfree(chip);
pci_disable_device(pci);
return err;
}
chip->ba0_addr = pci_resource_start(pci, 0);
chip->ba1_addr = pci_resource_start(pci, 1);
chip->ba0 = pci_ioremap_bar(pci, 0);
chip->ba1 = pci_ioremap_bar(pci, 1);
if (!chip->ba0 || !chip->ba1) {
snd_cs4281_free(chip);
return -ENOMEM;
}
if (request_irq(pci->irq, snd_cs4281_interrupt, IRQF_SHARED,
KBUILD_MODNAME, chip)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_cs4281_free(chip);
return -ENOMEM;
}
chip->irq = pci->irq;
tmp = snd_cs4281_chip_init(chip);
if (tmp) {
snd_cs4281_free(chip);
return tmp;
}
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_cs4281_free(chip);
return err;
}
snd_cs4281_proc_init(chip);
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
return 0;
}
static int snd_cs4281_chip_init(struct cs4281 *chip)
{
unsigned int tmp;
unsigned long end_time;
int retry_count = 2;
/* Having EPPMC.FPDN=1 prevent proper chip initialisation */
tmp = snd_cs4281_peekBA0(chip, BA0_EPPMC);
if (tmp & BA0_EPPMC_FPDN)
snd_cs4281_pokeBA0(chip, BA0_EPPMC, tmp & ~BA0_EPPMC_FPDN);
__retry:
tmp = snd_cs4281_peekBA0(chip, BA0_CFLR);
if (tmp != BA0_CFLR_DEFAULT) {
snd_cs4281_pokeBA0(chip, BA0_CFLR, BA0_CFLR_DEFAULT);
tmp = snd_cs4281_peekBA0(chip, BA0_CFLR);
if (tmp != BA0_CFLR_DEFAULT) {
snd_printk(KERN_ERR "CFLR setup failed (0x%x)\n", tmp);
return -EIO;
}
}
/* Set the 'Configuration Write Protect' register
* to 4281h. Allows vendor-defined configuration
* space between 0e4h and 0ffh to be written. */
snd_cs4281_pokeBA0(chip, BA0_CWPR, 0x4281);
if ((tmp = snd_cs4281_peekBA0(chip, BA0_SERC1)) != (BA0_SERC1_SO1EN | BA0_SERC1_AC97)) {
snd_printk(KERN_ERR "SERC1 AC'97 check failed (0x%x)\n", tmp);
return -EIO;
}
if ((tmp = snd_cs4281_peekBA0(chip, BA0_SERC2)) != (BA0_SERC2_SI1EN | BA0_SERC2_AC97)) {
snd_printk(KERN_ERR "SERC2 AC'97 check failed (0x%x)\n", tmp);
return -EIO;
}
/* Sound System Power Management */
snd_cs4281_pokeBA0(chip, BA0_SSPM, BA0_SSPM_MIXEN | BA0_SSPM_CSRCEN |
BA0_SSPM_PSRCEN | BA0_SSPM_JSEN |
BA0_SSPM_ACLEN | BA0_SSPM_FMEN);
/* Serial Port Power Management */
/* Blast the clock control register to zero so that the
* PLL starts out in a known state, and blast the master serial
* port control register to zero so that the serial ports also
* start out in a known state. */
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, 0);
snd_cs4281_pokeBA0(chip, BA0_SERMC, 0);
/* Make ESYN go to zero to turn off
* the Sync pulse on the AC97 link. */
snd_cs4281_pokeBA0(chip, BA0_ACCTL, 0);
udelay(50);
/* Drive the ARST# pin low for a minimum of 1uS (as defined in the AC97
* spec) and then drive it high. This is done for non AC97 modes since
* there might be logic external to the CS4281 that uses the ARST# line
* for a reset. */
snd_cs4281_pokeBA0(chip, BA0_SPMC, 0);
udelay(50);
snd_cs4281_pokeBA0(chip, BA0_SPMC, BA0_SPMC_RSTN);
msleep(50);
if (chip->dual_codec)
snd_cs4281_pokeBA0(chip, BA0_SPMC, BA0_SPMC_RSTN | BA0_SPMC_ASDI2E);
/*
* Set the serial port timing configuration.
*/
snd_cs4281_pokeBA0(chip, BA0_SERMC,
(chip->dual_codec ? BA0_SERMC_TCID(chip->dual_codec) : BA0_SERMC_TCID(1)) |
BA0_SERMC_PTC_AC97 | BA0_SERMC_MSPE);
/*
* Start the DLL Clock logic.
*/
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, BA0_CLKCR1_DLLP);
msleep(50);
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, BA0_CLKCR1_SWCE | BA0_CLKCR1_DLLP);
/*
* Wait for the DLL ready signal from the clock logic.
*/
end_time = jiffies + HZ;
do {
/*
* Read the AC97 status register to see if we've seen a CODEC
* signal from the AC97 codec.
*/
if (snd_cs4281_peekBA0(chip, BA0_CLKCR1) & BA0_CLKCR1_DLLRDY)
goto __ok0;
schedule_timeout_uninterruptible(1);
} while (time_after_eq(end_time, jiffies));
snd_printk(KERN_ERR "DLLRDY not seen\n");
return -EIO;
__ok0:
/*
* The first thing we do here is to enable sync generation. As soon
* as we start receiving bit clock, we'll start producing the SYNC
* signal.
*/
snd_cs4281_pokeBA0(chip, BA0_ACCTL, BA0_ACCTL_ESYN);
/*
* Wait for the codec ready signal from the AC97 codec.
*/
end_time = jiffies + HZ;
do {
/*
* Read the AC97 status register to see if we've seen a CODEC
* signal from the AC97 codec.
*/
if (snd_cs4281_peekBA0(chip, BA0_ACSTS) & BA0_ACSTS_CRDY)
goto __ok1;
schedule_timeout_uninterruptible(1);
} while (time_after_eq(end_time, jiffies));
snd_printk(KERN_ERR "never read codec ready from AC'97 (0x%x)\n", snd_cs4281_peekBA0(chip, BA0_ACSTS));
return -EIO;
__ok1:
if (chip->dual_codec) {
end_time = jiffies + HZ;
do {
if (snd_cs4281_peekBA0(chip, BA0_ACSTS2) & BA0_ACSTS_CRDY)
goto __codec2_ok;
schedule_timeout_uninterruptible(1);
} while (time_after_eq(end_time, jiffies));
snd_printk(KERN_INFO "secondary codec doesn't respond. disable it...\n");
chip->dual_codec = 0;
__codec2_ok: ;
}
/*
* Assert the valid frame signal so that we can start sending commands
* to the AC97 codec.
*/
snd_cs4281_pokeBA0(chip, BA0_ACCTL, BA0_ACCTL_VFRM | BA0_ACCTL_ESYN);
/*
* Wait until we've sampled input slots 3 and 4 as valid, meaning that
* the codec is pumping ADC data across the AC-link.
*/
end_time = jiffies + HZ;
do {
/*
* Read the input slot valid register and see if input slots 3
* 4 are valid yet.
*/
if ((snd_cs4281_peekBA0(chip, BA0_ACISV) & (BA0_ACISV_SLV(3) | BA0_ACISV_SLV(4))) == (BA0_ACISV_SLV(3) | BA0_ACISV_SLV(4)))
goto __ok2;
schedule_timeout_uninterruptible(1);
} while (time_after_eq(end_time, jiffies));
if (--retry_count > 0)
goto __retry;
snd_printk(KERN_ERR "never read ISV3 and ISV4 from AC'97\n");
return -EIO;
__ok2:
/*
* Now, assert valid frame and the slot 3 and 4 valid bits. This will
* commense the transfer of digital audio data to the AC97 codec.
*/
snd_cs4281_pokeBA0(chip, BA0_ACOSV, BA0_ACOSV_SLV(3) | BA0_ACOSV_SLV(4));
/*
* Initialize DMA structures
*/
for (tmp = 0; tmp < 4; tmp++) {
struct cs4281_dma *dma = &chip->dma[tmp];
dma->regDBA = BA0_DBA0 + (tmp * 0x10);
dma->regDCA = BA0_DCA0 + (tmp * 0x10);
dma->regDBC = BA0_DBC0 + (tmp * 0x10);
dma->regDCC = BA0_DCC0 + (tmp * 0x10);
dma->regDMR = BA0_DMR0 + (tmp * 8);
dma->regDCR = BA0_DCR0 + (tmp * 8);
dma->regHDSR = BA0_HDSR0 + (tmp * 4);
dma->regFCR = BA0_FCR0 + (tmp * 4);
dma->regFSIC = BA0_FSIC0 + (tmp * 4);
dma->fifo_offset = tmp * CS4281_FIFO_SIZE;
snd_cs4281_pokeBA0(chip, dma->regFCR,
BA0_FCR_LS(31) |
BA0_FCR_RS(31) |
BA0_FCR_SZ(CS4281_FIFO_SIZE) |
BA0_FCR_OF(dma->fifo_offset));
}
chip->src_left_play_slot = 0; /* AC'97 left PCM playback (3) */
chip->src_right_play_slot = 1; /* AC'97 right PCM playback (4) */
chip->src_left_rec_slot = 10; /* AC'97 left PCM record (3) */
chip->src_right_rec_slot = 11; /* AC'97 right PCM record (4) */
/* Activate wave playback FIFO for FM playback */
chip->dma[0].valFCR = BA0_FCR_FEN | BA0_FCR_LS(0) |
BA0_FCR_RS(1) |
BA0_FCR_SZ(CS4281_FIFO_SIZE) |
BA0_FCR_OF(chip->dma[0].fifo_offset);
snd_cs4281_pokeBA0(chip, chip->dma[0].regFCR, chip->dma[0].valFCR);
snd_cs4281_pokeBA0(chip, BA0_SRCSA, (chip->src_left_play_slot << 0) |
(chip->src_right_play_slot << 8) |
(chip->src_left_rec_slot << 16) |
(chip->src_right_rec_slot << 24));
/* Initialize digital volume */
snd_cs4281_pokeBA0(chip, BA0_PPLVC, 0);
snd_cs4281_pokeBA0(chip, BA0_PPRVC, 0);
/* Enable IRQs */
snd_cs4281_pokeBA0(chip, BA0_HICR, BA0_HICR_EOI);
/* Unmask interrupts */
snd_cs4281_pokeBA0(chip, BA0_HIMR, 0x7fffffff & ~(
BA0_HISR_MIDI |
BA0_HISR_DMAI |
BA0_HISR_DMA(0) |
BA0_HISR_DMA(1) |
BA0_HISR_DMA(2) |
BA0_HISR_DMA(3)));
synchronize_irq(chip->irq);
return 0;
}
/*
* MIDI section
*/
static void snd_cs4281_midi_reset(struct cs4281 *chip)
{
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr | BA0_MIDCR_MRST);
udelay(100);
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
static int snd_cs4281_midi_input_open(struct snd_rawmidi_substream *substream)
{
struct cs4281 *chip = substream->rmidi->private_data;
spin_lock_irq(&chip->reg_lock);
chip->midcr |= BA0_MIDCR_RXE;
chip->midi_input = substream;
if (!(chip->uartm & CS4281_MODE_OUTPUT)) {
snd_cs4281_midi_reset(chip);
} else {
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cs4281_midi_input_close(struct snd_rawmidi_substream *substream)
{
struct cs4281 *chip = substream->rmidi->private_data;
spin_lock_irq(&chip->reg_lock);
chip->midcr &= ~(BA0_MIDCR_RXE | BA0_MIDCR_RIE);
chip->midi_input = NULL;
if (!(chip->uartm & CS4281_MODE_OUTPUT)) {
snd_cs4281_midi_reset(chip);
} else {
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
chip->uartm &= ~CS4281_MODE_INPUT;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cs4281_midi_output_open(struct snd_rawmidi_substream *substream)
{
struct cs4281 *chip = substream->rmidi->private_data;
spin_lock_irq(&chip->reg_lock);
chip->uartm |= CS4281_MODE_OUTPUT;
chip->midcr |= BA0_MIDCR_TXE;
chip->midi_output = substream;
if (!(chip->uartm & CS4281_MODE_INPUT)) {
snd_cs4281_midi_reset(chip);
} else {
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_cs4281_midi_output_close(struct snd_rawmidi_substream *substream)
{
struct cs4281 *chip = substream->rmidi->private_data;
spin_lock_irq(&chip->reg_lock);
chip->midcr &= ~(BA0_MIDCR_TXE | BA0_MIDCR_TIE);
chip->midi_output = NULL;
if (!(chip->uartm & CS4281_MODE_INPUT)) {
snd_cs4281_midi_reset(chip);
} else {
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
chip->uartm &= ~CS4281_MODE_OUTPUT;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static void snd_cs4281_midi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
unsigned long flags;
struct cs4281 *chip = substream->rmidi->private_data;
spin_lock_irqsave(&chip->reg_lock, flags);
if (up) {
if ((chip->midcr & BA0_MIDCR_RIE) == 0) {
chip->midcr |= BA0_MIDCR_RIE;
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
} else {
if (chip->midcr & BA0_MIDCR_RIE) {
chip->midcr &= ~BA0_MIDCR_RIE;
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
}
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
static void snd_cs4281_midi_output_trigger(struct snd_rawmidi_substream *substream, int up)
{
unsigned long flags;
struct cs4281 *chip = substream->rmidi->private_data;
unsigned char byte;
spin_lock_irqsave(&chip->reg_lock, flags);
if (up) {
if ((chip->midcr & BA0_MIDCR_TIE) == 0) {
chip->midcr |= BA0_MIDCR_TIE;
/* fill UART FIFO buffer at first, and turn Tx interrupts only if necessary */
while ((chip->midcr & BA0_MIDCR_TIE) &&
(snd_cs4281_peekBA0(chip, BA0_MIDSR) & BA0_MIDSR_TBF) == 0) {
if (snd_rawmidi_transmit(substream, &byte, 1) != 1) {
chip->midcr &= ~BA0_MIDCR_TIE;
} else {
snd_cs4281_pokeBA0(chip, BA0_MIDWP, byte);
}
}
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
} else {
if (chip->midcr & BA0_MIDCR_TIE) {
chip->midcr &= ~BA0_MIDCR_TIE;
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
}
}
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
static struct snd_rawmidi_ops snd_cs4281_midi_output =
{
.open = snd_cs4281_midi_output_open,
.close = snd_cs4281_midi_output_close,
.trigger = snd_cs4281_midi_output_trigger,
};
static struct snd_rawmidi_ops snd_cs4281_midi_input =
{
.open = snd_cs4281_midi_input_open,
.close = snd_cs4281_midi_input_close,
.trigger = snd_cs4281_midi_input_trigger,
};
static int __devinit snd_cs4281_midi(struct cs4281 * chip, int device,
struct snd_rawmidi **rrawmidi)
{
struct snd_rawmidi *rmidi;
int err;
if (rrawmidi)
*rrawmidi = NULL;
if ((err = snd_rawmidi_new(chip->card, "CS4281", device, 1, 1, &rmidi)) < 0)
return err;
strcpy(rmidi->name, "CS4281");
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_cs4281_midi_output);
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_cs4281_midi_input);
rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT | SNDRV_RAWMIDI_INFO_INPUT | SNDRV_RAWMIDI_INFO_DUPLEX;
rmidi->private_data = chip;
chip->rmidi = rmidi;
if (rrawmidi)
*rrawmidi = rmidi;
return 0;
}
/*
* Interrupt handler
*/
static irqreturn_t snd_cs4281_interrupt(int irq, void *dev_id)
{
struct cs4281 *chip = dev_id;
unsigned int status, dma, val;
struct cs4281_dma *cdma;
if (chip == NULL)
return IRQ_NONE;
status = snd_cs4281_peekBA0(chip, BA0_HISR);
if ((status & 0x7fffffff) == 0) {
snd_cs4281_pokeBA0(chip, BA0_HICR, BA0_HICR_EOI);
return IRQ_NONE;
}
if (status & (BA0_HISR_DMA(0)|BA0_HISR_DMA(1)|BA0_HISR_DMA(2)|BA0_HISR_DMA(3))) {
for (dma = 0; dma < 4; dma++)
if (status & BA0_HISR_DMA(dma)) {
cdma = &chip->dma[dma];
spin_lock(&chip->reg_lock);
/* ack DMA IRQ */
val = snd_cs4281_peekBA0(chip, cdma->regHDSR);
/* workaround, sometimes CS4281 acknowledges */
/* end or middle transfer position twice */
cdma->frag++;
if ((val & BA0_HDSR_DHTC) && !(cdma->frag & 1)) {
cdma->frag--;
chip->spurious_dhtc_irq++;
spin_unlock(&chip->reg_lock);
continue;
}
if ((val & BA0_HDSR_DTC) && (cdma->frag & 1)) {
cdma->frag--;
chip->spurious_dtc_irq++;
spin_unlock(&chip->reg_lock);
continue;
}
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(cdma->substream);
}
}
if ((status & BA0_HISR_MIDI) && chip->rmidi) {
unsigned char c;
spin_lock(&chip->reg_lock);
while ((snd_cs4281_peekBA0(chip, BA0_MIDSR) & BA0_MIDSR_RBE) == 0) {
c = snd_cs4281_peekBA0(chip, BA0_MIDRP);
if ((chip->midcr & BA0_MIDCR_RIE) == 0)
continue;
snd_rawmidi_receive(chip->midi_input, &c, 1);
}
while ((snd_cs4281_peekBA0(chip, BA0_MIDSR) & BA0_MIDSR_TBF) == 0) {
if ((chip->midcr & BA0_MIDCR_TIE) == 0)
break;
if (snd_rawmidi_transmit(chip->midi_output, &c, 1) != 1) {
chip->midcr &= ~BA0_MIDCR_TIE;
snd_cs4281_pokeBA0(chip, BA0_MIDCR, chip->midcr);
break;
}
snd_cs4281_pokeBA0(chip, BA0_MIDWP, c);
}
spin_unlock(&chip->reg_lock);
}
/* EOI to the PCI part... reenables interrupts */
snd_cs4281_pokeBA0(chip, BA0_HICR, BA0_HICR_EOI);
return IRQ_HANDLED;
}
/*
* OPL3 command
*/
static void snd_cs4281_opl3_command(struct snd_opl3 *opl3, unsigned short cmd,
unsigned char val)
{
unsigned long flags;
struct cs4281 *chip = opl3->private_data;
void __iomem *port;
if (cmd & OPL3_RIGHT)
port = chip->ba0 + BA0_B1AP; /* right port */
else
port = chip->ba0 + BA0_B0AP; /* left port */
spin_lock_irqsave(&opl3->reg_lock, flags);
writel((unsigned int)cmd, port);
udelay(10);
writel((unsigned int)val, port + 4);
udelay(30);
spin_unlock_irqrestore(&opl3->reg_lock, flags);
}
static int __devinit snd_cs4281_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct cs4281 *chip;
struct snd_opl3 *opl3;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
if ((err = snd_cs4281_create(card, pci, &chip, dual_codec[dev])) < 0) {
snd_card_free(card);
return err;
}
card->private_data = chip;
if ((err = snd_cs4281_mixer(chip)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_cs4281_pcm(chip, 0, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_cs4281_midi(chip, 0, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_opl3_new(card, OPL3_HW_OPL3_CS4281, &opl3)) < 0) {
snd_card_free(card);
return err;
}
opl3->private_data = chip;
opl3->command = snd_cs4281_opl3_command;
snd_opl3_init(opl3);
if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) {
snd_card_free(card);
return err;
}
snd_cs4281_create_gameport(chip);
strcpy(card->driver, "CS4281");
strcpy(card->shortname, "Cirrus Logic CS4281");
sprintf(card->longname, "%s at 0x%lx, irq %d",
card->shortname,
chip->ba0_addr,
chip->irq);
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
dev++;
return 0;
}
static void __devexit snd_cs4281_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
/*
* Power Management
*/
#ifdef CONFIG_PM
static int saved_regs[SUSPEND_REGISTERS] = {
BA0_JSCTL,
BA0_GPIOR,
BA0_SSCR,
BA0_MIDCR,
BA0_SRCSA,
BA0_PASR,
BA0_CASR,
BA0_DACSR,
BA0_ADCSR,
BA0_FMLVC,
BA0_FMRVC,
BA0_PPLVC,
BA0_PPRVC,
};
#define CLKCR1_CKRA 0x00010000L
static int cs4281_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct cs4281 *chip = card->private_data;
u32 ulCLK;
unsigned int i;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
snd_ac97_suspend(chip->ac97);
snd_ac97_suspend(chip->ac97_secondary);
ulCLK = snd_cs4281_peekBA0(chip, BA0_CLKCR1);
ulCLK |= CLKCR1_CKRA;
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, ulCLK);
/* Disable interrupts. */
snd_cs4281_pokeBA0(chip, BA0_HICR, BA0_HICR_CHGM);
/* remember the status registers */
for (i = 0; i < ARRAY_SIZE(saved_regs); i++)
if (saved_regs[i])
chip->suspend_regs[i] = snd_cs4281_peekBA0(chip, saved_regs[i]);
/* Turn off the serial ports. */
snd_cs4281_pokeBA0(chip, BA0_SERMC, 0);
/* Power off FM, Joystick, AC link, */
snd_cs4281_pokeBA0(chip, BA0_SSPM, 0);
/* DLL off. */
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, 0);
/* AC link off. */
snd_cs4281_pokeBA0(chip, BA0_SPMC, 0);
ulCLK = snd_cs4281_peekBA0(chip, BA0_CLKCR1);
ulCLK &= ~CLKCR1_CKRA;
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, ulCLK);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
static int cs4281_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct cs4281 *chip = card->private_data;
unsigned int i;
u32 ulCLK;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "cs4281: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
ulCLK = snd_cs4281_peekBA0(chip, BA0_CLKCR1);
ulCLK |= CLKCR1_CKRA;
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, ulCLK);
snd_cs4281_chip_init(chip);
/* restore the status registers */
for (i = 0; i < ARRAY_SIZE(saved_regs); i++)
if (saved_regs[i])
snd_cs4281_pokeBA0(chip, saved_regs[i], chip->suspend_regs[i]);
snd_ac97_resume(chip->ac97);
snd_ac97_resume(chip->ac97_secondary);
ulCLK = snd_cs4281_peekBA0(chip, BA0_CLKCR1);
ulCLK &= ~CLKCR1_CKRA;
snd_cs4281_pokeBA0(chip, BA0_CLKCR1, ulCLK);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
static struct pci_driver driver = {
.name = KBUILD_MODNAME,
.id_table = snd_cs4281_ids,
.probe = snd_cs4281_probe,
.remove = __devexit_p(snd_cs4281_remove),
#ifdef CONFIG_PM
.suspend = cs4281_suspend,
.resume = cs4281_resume,
#endif
};
static int __init alsa_card_cs4281_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_cs4281_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_cs4281_init)
module_exit(alsa_card_cs4281_exit)
| gpl-2.0 |
kernel-hut/android_kernel_xiaomi_dior | drivers/mfd/wm8350-core.c | 4894 | 18523 | /*
* wm8350-core.c -- Device access for Wolfson WM8350
*
* Copyright 2007, 2008 Wolfson Microelectronics PLC.
*
* Author: Liam Girdwood, Mark Brown
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/bug.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/mfd/wm8350/core.h>
#include <linux/mfd/wm8350/audio.h>
#include <linux/mfd/wm8350/comparator.h>
#include <linux/mfd/wm8350/gpio.h>
#include <linux/mfd/wm8350/pmic.h>
#include <linux/mfd/wm8350/rtc.h>
#include <linux/mfd/wm8350/supply.h>
#include <linux/mfd/wm8350/wdt.h>
#define WM8350_UNLOCK_KEY 0x0013
#define WM8350_LOCK_KEY 0x0000
#define WM8350_CLOCK_CONTROL_1 0x28
#define WM8350_AIF_TEST 0x74
/* debug */
#define WM8350_BUS_DEBUG 0
#if WM8350_BUS_DEBUG
#define dump(regs, src) do { \
int i_; \
u16 *src_ = src; \
printk(KERN_DEBUG); \
for (i_ = 0; i_ < regs; i_++) \
printk(" 0x%4.4x", *src_++); \
printk("\n"); \
} while (0);
#else
#define dump(bytes, src)
#endif
#define WM8350_LOCK_DEBUG 0
#if WM8350_LOCK_DEBUG
#define ldbg(format, arg...) printk(format, ## arg)
#else
#define ldbg(format, arg...)
#endif
/*
* WM8350 Device IO
*/
static DEFINE_MUTEX(io_mutex);
static DEFINE_MUTEX(reg_lock_mutex);
/* Perform a physical read from the device.
*/
static int wm8350_phys_read(struct wm8350 *wm8350, u8 reg, int num_regs,
u16 *dest)
{
int i, ret;
int bytes = num_regs * 2;
dev_dbg(wm8350->dev, "volatile read\n");
ret = wm8350->read_dev(wm8350, reg, bytes, (char *)dest);
for (i = reg; i < reg + num_regs; i++) {
/* Cache is CPU endian */
dest[i - reg] = be16_to_cpu(dest[i - reg]);
/* Mask out non-readable bits */
dest[i - reg] &= wm8350_reg_io_map[i].readable;
}
dump(num_regs, dest);
return ret;
}
static int wm8350_read(struct wm8350 *wm8350, u8 reg, int num_regs, u16 *dest)
{
int i;
int end = reg + num_regs;
int ret = 0;
int bytes = num_regs * 2;
if (wm8350->read_dev == NULL)
return -ENODEV;
if ((reg + num_regs - 1) > WM8350_MAX_REGISTER) {
dev_err(wm8350->dev, "invalid reg %x\n",
reg + num_regs - 1);
return -EINVAL;
}
dev_dbg(wm8350->dev,
"%s R%d(0x%2.2x) %d regs\n", __func__, reg, reg, num_regs);
#if WM8350_BUS_DEBUG
/* we can _safely_ read any register, but warn if read not supported */
for (i = reg; i < end; i++) {
if (!wm8350_reg_io_map[i].readable)
dev_warn(wm8350->dev,
"reg R%d is not readable\n", i);
}
#endif
/* if any volatile registers are required, then read back all */
for (i = reg; i < end; i++)
if (wm8350_reg_io_map[i].vol)
return wm8350_phys_read(wm8350, reg, num_regs, dest);
/* no volatiles, then cache is good */
dev_dbg(wm8350->dev, "cache read\n");
memcpy(dest, &wm8350->reg_cache[reg], bytes);
dump(num_regs, dest);
return ret;
}
static inline int is_reg_locked(struct wm8350 *wm8350, u8 reg)
{
if (reg == WM8350_SECURITY ||
wm8350->reg_cache[WM8350_SECURITY] == WM8350_UNLOCK_KEY)
return 0;
if ((reg >= WM8350_GPIO_FUNCTION_SELECT_1 &&
reg <= WM8350_GPIO_FUNCTION_SELECT_4) ||
(reg >= WM8350_BATTERY_CHARGER_CONTROL_1 &&
reg <= WM8350_BATTERY_CHARGER_CONTROL_3))
return 1;
return 0;
}
static int wm8350_write(struct wm8350 *wm8350, u8 reg, int num_regs, u16 *src)
{
int i;
int end = reg + num_regs;
int bytes = num_regs * 2;
if (wm8350->write_dev == NULL)
return -ENODEV;
if ((reg + num_regs - 1) > WM8350_MAX_REGISTER) {
dev_err(wm8350->dev, "invalid reg %x\n",
reg + num_regs - 1);
return -EINVAL;
}
/* it's generally not a good idea to write to RO or locked registers */
for (i = reg; i < end; i++) {
if (!wm8350_reg_io_map[i].writable) {
dev_err(wm8350->dev,
"attempted write to read only reg R%d\n", i);
return -EINVAL;
}
if (is_reg_locked(wm8350, i)) {
dev_err(wm8350->dev,
"attempted write to locked reg R%d\n", i);
return -EINVAL;
}
src[i - reg] &= wm8350_reg_io_map[i].writable;
wm8350->reg_cache[i] =
(wm8350->reg_cache[i] & ~wm8350_reg_io_map[i].writable)
| src[i - reg];
src[i - reg] = cpu_to_be16(src[i - reg]);
}
/* Actually write it out */
return wm8350->write_dev(wm8350, reg, bytes, (char *)src);
}
/*
* Safe read, modify, write methods
*/
int wm8350_clear_bits(struct wm8350 *wm8350, u16 reg, u16 mask)
{
u16 data;
int err;
mutex_lock(&io_mutex);
err = wm8350_read(wm8350, reg, 1, &data);
if (err) {
dev_err(wm8350->dev, "read from reg R%d failed\n", reg);
goto out;
}
data &= ~mask;
err = wm8350_write(wm8350, reg, 1, &data);
if (err)
dev_err(wm8350->dev, "write to reg R%d failed\n", reg);
out:
mutex_unlock(&io_mutex);
return err;
}
EXPORT_SYMBOL_GPL(wm8350_clear_bits);
int wm8350_set_bits(struct wm8350 *wm8350, u16 reg, u16 mask)
{
u16 data;
int err;
mutex_lock(&io_mutex);
err = wm8350_read(wm8350, reg, 1, &data);
if (err) {
dev_err(wm8350->dev, "read from reg R%d failed\n", reg);
goto out;
}
data |= mask;
err = wm8350_write(wm8350, reg, 1, &data);
if (err)
dev_err(wm8350->dev, "write to reg R%d failed\n", reg);
out:
mutex_unlock(&io_mutex);
return err;
}
EXPORT_SYMBOL_GPL(wm8350_set_bits);
u16 wm8350_reg_read(struct wm8350 *wm8350, int reg)
{
u16 data;
int err;
mutex_lock(&io_mutex);
err = wm8350_read(wm8350, reg, 1, &data);
if (err)
dev_err(wm8350->dev, "read from reg R%d failed\n", reg);
mutex_unlock(&io_mutex);
return data;
}
EXPORT_SYMBOL_GPL(wm8350_reg_read);
int wm8350_reg_write(struct wm8350 *wm8350, int reg, u16 val)
{
int ret;
u16 data = val;
mutex_lock(&io_mutex);
ret = wm8350_write(wm8350, reg, 1, &data);
if (ret)
dev_err(wm8350->dev, "write to reg R%d failed\n", reg);
mutex_unlock(&io_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(wm8350_reg_write);
int wm8350_block_read(struct wm8350 *wm8350, int start_reg, int regs,
u16 *dest)
{
int err = 0;
mutex_lock(&io_mutex);
err = wm8350_read(wm8350, start_reg, regs, dest);
if (err)
dev_err(wm8350->dev, "block read starting from R%d failed\n",
start_reg);
mutex_unlock(&io_mutex);
return err;
}
EXPORT_SYMBOL_GPL(wm8350_block_read);
int wm8350_block_write(struct wm8350 *wm8350, int start_reg, int regs,
u16 *src)
{
int ret = 0;
mutex_lock(&io_mutex);
ret = wm8350_write(wm8350, start_reg, regs, src);
if (ret)
dev_err(wm8350->dev, "block write starting at R%d failed\n",
start_reg);
mutex_unlock(&io_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(wm8350_block_write);
/**
* wm8350_reg_lock()
*
* The WM8350 has a hardware lock which can be used to prevent writes to
* some registers (generally those which can cause particularly serious
* problems if misused). This function enables that lock.
*/
int wm8350_reg_lock(struct wm8350 *wm8350)
{
u16 key = WM8350_LOCK_KEY;
int ret;
ldbg(__func__);
mutex_lock(&io_mutex);
ret = wm8350_write(wm8350, WM8350_SECURITY, 1, &key);
if (ret)
dev_err(wm8350->dev, "lock failed\n");
mutex_unlock(&io_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(wm8350_reg_lock);
/**
* wm8350_reg_unlock()
*
* The WM8350 has a hardware lock which can be used to prevent writes to
* some registers (generally those which can cause particularly serious
* problems if misused). This function disables that lock so updates
* can be performed. For maximum safety this should be done only when
* required.
*/
int wm8350_reg_unlock(struct wm8350 *wm8350)
{
u16 key = WM8350_UNLOCK_KEY;
int ret;
ldbg(__func__);
mutex_lock(&io_mutex);
ret = wm8350_write(wm8350, WM8350_SECURITY, 1, &key);
if (ret)
dev_err(wm8350->dev, "unlock failed\n");
mutex_unlock(&io_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(wm8350_reg_unlock);
int wm8350_read_auxadc(struct wm8350 *wm8350, int channel, int scale, int vref)
{
u16 reg, result = 0;
if (channel < WM8350_AUXADC_AUX1 || channel > WM8350_AUXADC_TEMP)
return -EINVAL;
if (channel >= WM8350_AUXADC_USB && channel <= WM8350_AUXADC_TEMP
&& (scale != 0 || vref != 0))
return -EINVAL;
mutex_lock(&wm8350->auxadc_mutex);
/* Turn on the ADC */
reg = wm8350_reg_read(wm8350, WM8350_POWER_MGMT_5);
wm8350_reg_write(wm8350, WM8350_POWER_MGMT_5, reg | WM8350_AUXADC_ENA);
if (scale || vref) {
reg = scale << 13;
reg |= vref << 12;
wm8350_reg_write(wm8350, WM8350_AUX1_READBACK + channel, reg);
}
reg = wm8350_reg_read(wm8350, WM8350_DIGITISER_CONTROL_1);
reg |= 1 << channel | WM8350_AUXADC_POLL;
wm8350_reg_write(wm8350, WM8350_DIGITISER_CONTROL_1, reg);
/* If a late IRQ left the completion signalled then consume
* the completion. */
try_wait_for_completion(&wm8350->auxadc_done);
/* We ignore the result of the completion and just check for a
* conversion result, allowing us to soldier on if the IRQ
* infrastructure is not set up for the chip. */
wait_for_completion_timeout(&wm8350->auxadc_done, msecs_to_jiffies(5));
reg = wm8350_reg_read(wm8350, WM8350_DIGITISER_CONTROL_1);
if (reg & WM8350_AUXADC_POLL)
dev_err(wm8350->dev, "adc chn %d read timeout\n", channel);
else
result = wm8350_reg_read(wm8350,
WM8350_AUX1_READBACK + channel);
/* Turn off the ADC */
reg = wm8350_reg_read(wm8350, WM8350_POWER_MGMT_5);
wm8350_reg_write(wm8350, WM8350_POWER_MGMT_5,
reg & ~WM8350_AUXADC_ENA);
mutex_unlock(&wm8350->auxadc_mutex);
return result & WM8350_AUXADC_DATA1_MASK;
}
EXPORT_SYMBOL_GPL(wm8350_read_auxadc);
static irqreturn_t wm8350_auxadc_irq(int irq, void *irq_data)
{
struct wm8350 *wm8350 = irq_data;
complete(&wm8350->auxadc_done);
return IRQ_HANDLED;
}
/*
* Cache is always host endian.
*/
static int wm8350_create_cache(struct wm8350 *wm8350, int type, int mode)
{
int i, ret = 0;
u16 value;
const u16 *reg_map;
switch (type) {
case 0:
switch (mode) {
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_0
case 0:
reg_map = wm8350_mode0_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_1
case 1:
reg_map = wm8350_mode1_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_2
case 2:
reg_map = wm8350_mode2_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8350_CONFIG_MODE_3
case 3:
reg_map = wm8350_mode3_defaults;
break;
#endif
default:
dev_err(wm8350->dev,
"WM8350 configuration mode %d not supported\n",
mode);
return -EINVAL;
}
break;
case 1:
switch (mode) {
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_0
case 0:
reg_map = wm8351_mode0_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_1
case 1:
reg_map = wm8351_mode1_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_2
case 2:
reg_map = wm8351_mode2_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8351_CONFIG_MODE_3
case 3:
reg_map = wm8351_mode3_defaults;
break;
#endif
default:
dev_err(wm8350->dev,
"WM8351 configuration mode %d not supported\n",
mode);
return -EINVAL;
}
break;
case 2:
switch (mode) {
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_0
case 0:
reg_map = wm8352_mode0_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_1
case 1:
reg_map = wm8352_mode1_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_2
case 2:
reg_map = wm8352_mode2_defaults;
break;
#endif
#ifdef CONFIG_MFD_WM8352_CONFIG_MODE_3
case 3:
reg_map = wm8352_mode3_defaults;
break;
#endif
default:
dev_err(wm8350->dev,
"WM8352 configuration mode %d not supported\n",
mode);
return -EINVAL;
}
break;
default:
dev_err(wm8350->dev,
"WM835x configuration mode %d not supported\n",
mode);
return -EINVAL;
}
wm8350->reg_cache =
kmalloc(sizeof(u16) * (WM8350_MAX_REGISTER + 1), GFP_KERNEL);
if (wm8350->reg_cache == NULL)
return -ENOMEM;
/* Read the initial cache state back from the device - this is
* a PMIC so the device many not be in a virgin state and we
* can't rely on the silicon values.
*/
ret = wm8350->read_dev(wm8350, 0,
sizeof(u16) * (WM8350_MAX_REGISTER + 1),
wm8350->reg_cache);
if (ret < 0) {
dev_err(wm8350->dev,
"failed to read initial cache values\n");
goto out;
}
/* Mask out uncacheable/unreadable bits and the audio. */
for (i = 0; i < WM8350_MAX_REGISTER; i++) {
if (wm8350_reg_io_map[i].readable &&
(i < WM8350_CLOCK_CONTROL_1 || i > WM8350_AIF_TEST)) {
value = be16_to_cpu(wm8350->reg_cache[i]);
value &= wm8350_reg_io_map[i].readable;
wm8350->reg_cache[i] = value;
} else
wm8350->reg_cache[i] = reg_map[i];
}
out:
kfree(wm8350->reg_cache);
return ret;
}
/*
* Register a client device. This is non-fatal since there is no need to
* fail the entire device init due to a single platform device failing.
*/
static void wm8350_client_dev_register(struct wm8350 *wm8350,
const char *name,
struct platform_device **pdev)
{
int ret;
*pdev = platform_device_alloc(name, -1);
if (*pdev == NULL) {
dev_err(wm8350->dev, "Failed to allocate %s\n", name);
return;
}
(*pdev)->dev.parent = wm8350->dev;
platform_set_drvdata(*pdev, wm8350);
ret = platform_device_add(*pdev);
if (ret != 0) {
dev_err(wm8350->dev, "Failed to register %s: %d\n", name, ret);
platform_device_put(*pdev);
*pdev = NULL;
}
}
int wm8350_device_init(struct wm8350 *wm8350, int irq,
struct wm8350_platform_data *pdata)
{
int ret;
u16 id1, id2, mask_rev;
u16 cust_id, mode, chip_rev;
dev_set_drvdata(wm8350->dev, wm8350);
/* get WM8350 revision and config mode */
ret = wm8350->read_dev(wm8350, WM8350_RESET_ID, sizeof(id1), &id1);
if (ret != 0) {
dev_err(wm8350->dev, "Failed to read ID: %d\n", ret);
goto err;
}
ret = wm8350->read_dev(wm8350, WM8350_ID, sizeof(id2), &id2);
if (ret != 0) {
dev_err(wm8350->dev, "Failed to read ID: %d\n", ret);
goto err;
}
ret = wm8350->read_dev(wm8350, WM8350_REVISION, sizeof(mask_rev),
&mask_rev);
if (ret != 0) {
dev_err(wm8350->dev, "Failed to read revision: %d\n", ret);
goto err;
}
id1 = be16_to_cpu(id1);
id2 = be16_to_cpu(id2);
mask_rev = be16_to_cpu(mask_rev);
if (id1 != 0x6143) {
dev_err(wm8350->dev,
"Device with ID %x is not a WM8350\n", id1);
ret = -ENODEV;
goto err;
}
mode = id2 & WM8350_CONF_STS_MASK >> 10;
cust_id = id2 & WM8350_CUST_ID_MASK;
chip_rev = (id2 & WM8350_CHIP_REV_MASK) >> 12;
dev_info(wm8350->dev,
"CONF_STS %d, CUST_ID %d, MASK_REV %d, CHIP_REV %d\n",
mode, cust_id, mask_rev, chip_rev);
if (cust_id != 0) {
dev_err(wm8350->dev, "Unsupported CUST_ID\n");
ret = -ENODEV;
goto err;
}
switch (mask_rev) {
case 0:
wm8350->pmic.max_dcdc = WM8350_DCDC_6;
wm8350->pmic.max_isink = WM8350_ISINK_B;
switch (chip_rev) {
case WM8350_REV_E:
dev_info(wm8350->dev, "WM8350 Rev E\n");
break;
case WM8350_REV_F:
dev_info(wm8350->dev, "WM8350 Rev F\n");
break;
case WM8350_REV_G:
dev_info(wm8350->dev, "WM8350 Rev G\n");
wm8350->power.rev_g_coeff = 1;
break;
case WM8350_REV_H:
dev_info(wm8350->dev, "WM8350 Rev H\n");
wm8350->power.rev_g_coeff = 1;
break;
default:
/* For safety we refuse to run on unknown hardware */
dev_err(wm8350->dev, "Unknown WM8350 CHIP_REV\n");
ret = -ENODEV;
goto err;
}
break;
case 1:
wm8350->pmic.max_dcdc = WM8350_DCDC_4;
wm8350->pmic.max_isink = WM8350_ISINK_A;
switch (chip_rev) {
case 0:
dev_info(wm8350->dev, "WM8351 Rev A\n");
wm8350->power.rev_g_coeff = 1;
break;
case 1:
dev_info(wm8350->dev, "WM8351 Rev B\n");
wm8350->power.rev_g_coeff = 1;
break;
default:
dev_err(wm8350->dev, "Unknown WM8351 CHIP_REV\n");
ret = -ENODEV;
goto err;
}
break;
case 2:
wm8350->pmic.max_dcdc = WM8350_DCDC_6;
wm8350->pmic.max_isink = WM8350_ISINK_B;
switch (chip_rev) {
case 0:
dev_info(wm8350->dev, "WM8352 Rev A\n");
wm8350->power.rev_g_coeff = 1;
break;
default:
dev_err(wm8350->dev, "Unknown WM8352 CHIP_REV\n");
ret = -ENODEV;
goto err;
}
break;
default:
dev_err(wm8350->dev, "Unknown MASK_REV\n");
ret = -ENODEV;
goto err;
}
ret = wm8350_create_cache(wm8350, mask_rev, mode);
if (ret < 0) {
dev_err(wm8350->dev, "Failed to create register cache\n");
return ret;
}
mutex_init(&wm8350->auxadc_mutex);
init_completion(&wm8350->auxadc_done);
ret = wm8350_irq_init(wm8350, irq, pdata);
if (ret < 0)
goto err_free;
if (wm8350->irq_base) {
ret = request_threaded_irq(wm8350->irq_base +
WM8350_IRQ_AUXADC_DATARDY,
NULL, wm8350_auxadc_irq, 0,
"auxadc", wm8350);
if (ret < 0)
dev_warn(wm8350->dev,
"Failed to request AUXADC IRQ: %d\n", ret);
}
if (pdata && pdata->init) {
ret = pdata->init(wm8350);
if (ret != 0) {
dev_err(wm8350->dev, "Platform init() failed: %d\n",
ret);
goto err_irq;
}
}
wm8350_reg_write(wm8350, WM8350_SYSTEM_INTERRUPTS_MASK, 0x0);
wm8350_client_dev_register(wm8350, "wm8350-codec",
&(wm8350->codec.pdev));
wm8350_client_dev_register(wm8350, "wm8350-gpio",
&(wm8350->gpio.pdev));
wm8350_client_dev_register(wm8350, "wm8350-hwmon",
&(wm8350->hwmon.pdev));
wm8350_client_dev_register(wm8350, "wm8350-power",
&(wm8350->power.pdev));
wm8350_client_dev_register(wm8350, "wm8350-rtc", &(wm8350->rtc.pdev));
wm8350_client_dev_register(wm8350, "wm8350-wdt", &(wm8350->wdt.pdev));
return 0;
err_irq:
wm8350_irq_exit(wm8350);
err_free:
kfree(wm8350->reg_cache);
err:
return ret;
}
EXPORT_SYMBOL_GPL(wm8350_device_init);
void wm8350_device_exit(struct wm8350 *wm8350)
{
int i;
for (i = 0; i < ARRAY_SIZE(wm8350->pmic.led); i++)
platform_device_unregister(wm8350->pmic.led[i].pdev);
for (i = 0; i < ARRAY_SIZE(wm8350->pmic.pdev); i++)
platform_device_unregister(wm8350->pmic.pdev[i]);
platform_device_unregister(wm8350->wdt.pdev);
platform_device_unregister(wm8350->rtc.pdev);
platform_device_unregister(wm8350->power.pdev);
platform_device_unregister(wm8350->hwmon.pdev);
platform_device_unregister(wm8350->gpio.pdev);
platform_device_unregister(wm8350->codec.pdev);
if (wm8350->irq_base)
free_irq(wm8350->irq_base + WM8350_IRQ_AUXADC_DATARDY, wm8350);
wm8350_irq_exit(wm8350);
kfree(wm8350->reg_cache);
}
EXPORT_SYMBOL_GPL(wm8350_device_exit);
MODULE_DESCRIPTION("WM8350 AudioPlus PMIC core driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
MoKee/android_kernel_lge_gproj | drivers/usb/gadget/uvc_video.c | 5406 | 9621 | /*
* uvc_video.c -- USB Video Class Gadget driver
*
* Copyright (C) 2009-2010
* Laurent Pinchart (laurent.pinchart@ideasonboard.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <media/v4l2-dev.h>
#include "uvc.h"
#include "uvc_queue.h"
/* --------------------------------------------------------------------------
* Video codecs
*/
static int
uvc_video_encode_header(struct uvc_video *video, struct uvc_buffer *buf,
u8 *data, int len)
{
data[0] = 2;
data[1] = UVC_STREAM_EOH | video->fid;
if (buf->buf.bytesused - video->queue.buf_used <= len - 2)
data[1] |= UVC_STREAM_EOF;
return 2;
}
static int
uvc_video_encode_data(struct uvc_video *video, struct uvc_buffer *buf,
u8 *data, int len)
{
struct uvc_video_queue *queue = &video->queue;
unsigned int nbytes;
void *mem;
/* Copy video data to the USB buffer. */
mem = queue->mem + buf->buf.m.offset + queue->buf_used;
nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
memcpy(data, mem, nbytes);
queue->buf_used += nbytes;
return nbytes;
}
static void
uvc_video_encode_bulk(struct usb_request *req, struct uvc_video *video,
struct uvc_buffer *buf)
{
void *mem = req->buf;
int len = video->req_size;
int ret;
/* Add a header at the beginning of the payload. */
if (video->payload_size == 0) {
ret = uvc_video_encode_header(video, buf, mem, len);
video->payload_size += ret;
mem += ret;
len -= ret;
}
/* Process video data. */
len = min((int)(video->max_payload_size - video->payload_size), len);
ret = uvc_video_encode_data(video, buf, mem, len);
video->payload_size += ret;
len -= ret;
req->length = video->req_size - len;
req->zero = video->payload_size == video->max_payload_size;
if (buf->buf.bytesused == video->queue.buf_used) {
video->queue.buf_used = 0;
buf->state = UVC_BUF_STATE_DONE;
uvc_queue_next_buffer(&video->queue, buf);
video->fid ^= UVC_STREAM_FID;
video->payload_size = 0;
}
if (video->payload_size == video->max_payload_size ||
buf->buf.bytesused == video->queue.buf_used)
video->payload_size = 0;
}
static void
uvc_video_encode_isoc(struct usb_request *req, struct uvc_video *video,
struct uvc_buffer *buf)
{
void *mem = req->buf;
int len = video->req_size;
int ret;
/* Add the header. */
ret = uvc_video_encode_header(video, buf, mem, len);
mem += ret;
len -= ret;
/* Process video data. */
ret = uvc_video_encode_data(video, buf, mem, len);
len -= ret;
req->length = video->req_size - len;
if (buf->buf.bytesused == video->queue.buf_used) {
video->queue.buf_used = 0;
buf->state = UVC_BUF_STATE_DONE;
uvc_queue_next_buffer(&video->queue, buf);
video->fid ^= UVC_STREAM_FID;
}
}
/* --------------------------------------------------------------------------
* Request handling
*/
/*
* I somehow feel that synchronisation won't be easy to achieve here. We have
* three events that control USB requests submission:
*
* - USB request completion: the completion handler will resubmit the request
* if a video buffer is available.
*
* - USB interface setting selection: in response to a SET_INTERFACE request,
* the handler will start streaming if a video buffer is available and if
* video is not currently streaming.
*
* - V4L2 buffer queueing: the driver will start streaming if video is not
* currently streaming.
*
* Race conditions between those 3 events might lead to deadlocks or other
* nasty side effects.
*
* The "video currently streaming" condition can't be detected by the irqqueue
* being empty, as a request can still be in flight. A separate "queue paused"
* flag is thus needed.
*
* The paused flag will be set when we try to retrieve the irqqueue head if the
* queue is empty, and cleared when we queue a buffer.
*
* The USB request completion handler will get the buffer at the irqqueue head
* under protection of the queue spinlock. If the queue is empty, the streaming
* paused flag will be set. Right after releasing the spinlock a userspace
* application can queue a buffer. The flag will then cleared, and the ioctl
* handler will restart the video stream.
*/
static void
uvc_video_complete(struct usb_ep *ep, struct usb_request *req)
{
struct uvc_video *video = req->context;
struct uvc_buffer *buf;
unsigned long flags;
int ret;
switch (req->status) {
case 0:
break;
case -ESHUTDOWN:
printk(KERN_INFO "VS request cancelled.\n");
goto requeue;
default:
printk(KERN_INFO "VS request completed with status %d.\n",
req->status);
goto requeue;
}
spin_lock_irqsave(&video->queue.irqlock, flags);
buf = uvc_queue_head(&video->queue);
if (buf == NULL) {
spin_unlock_irqrestore(&video->queue.irqlock, flags);
goto requeue;
}
video->encode(req, video, buf);
if ((ret = usb_ep_queue(ep, req, GFP_ATOMIC)) < 0) {
printk(KERN_INFO "Failed to queue request (%d).\n", ret);
usb_ep_set_halt(ep);
spin_unlock_irqrestore(&video->queue.irqlock, flags);
goto requeue;
}
spin_unlock_irqrestore(&video->queue.irqlock, flags);
return;
requeue:
spin_lock_irqsave(&video->req_lock, flags);
list_add_tail(&req->list, &video->req_free);
spin_unlock_irqrestore(&video->req_lock, flags);
}
static int
uvc_video_free_requests(struct uvc_video *video)
{
unsigned int i;
for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
if (video->req[i]) {
usb_ep_free_request(video->ep, video->req[i]);
video->req[i] = NULL;
}
if (video->req_buffer[i]) {
kfree(video->req_buffer[i]);
video->req_buffer[i] = NULL;
}
}
INIT_LIST_HEAD(&video->req_free);
video->req_size = 0;
return 0;
}
static int
uvc_video_alloc_requests(struct uvc_video *video)
{
unsigned int i;
int ret = -ENOMEM;
BUG_ON(video->req_size);
for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
video->req_buffer[i] = kmalloc(video->ep->maxpacket, GFP_KERNEL);
if (video->req_buffer[i] == NULL)
goto error;
video->req[i] = usb_ep_alloc_request(video->ep, GFP_KERNEL);
if (video->req[i] == NULL)
goto error;
video->req[i]->buf = video->req_buffer[i];
video->req[i]->length = 0;
video->req[i]->dma = DMA_ADDR_INVALID;
video->req[i]->complete = uvc_video_complete;
video->req[i]->context = video;
list_add_tail(&video->req[i]->list, &video->req_free);
}
video->req_size = video->ep->maxpacket;
return 0;
error:
uvc_video_free_requests(video);
return ret;
}
/* --------------------------------------------------------------------------
* Video streaming
*/
/*
* uvc_video_pump - Pump video data into the USB requests
*
* This function fills the available USB requests (listed in req_free) with
* video data from the queued buffers.
*/
static int
uvc_video_pump(struct uvc_video *video)
{
struct usb_request *req;
struct uvc_buffer *buf;
unsigned long flags;
int ret;
/* FIXME TODO Race between uvc_video_pump and requests completion
* handler ???
*/
while (1) {
/* Retrieve the first available USB request, protected by the
* request lock.
*/
spin_lock_irqsave(&video->req_lock, flags);
if (list_empty(&video->req_free)) {
spin_unlock_irqrestore(&video->req_lock, flags);
return 0;
}
req = list_first_entry(&video->req_free, struct usb_request,
list);
list_del(&req->list);
spin_unlock_irqrestore(&video->req_lock, flags);
/* Retrieve the first available video buffer and fill the
* request, protected by the video queue irqlock.
*/
spin_lock_irqsave(&video->queue.irqlock, flags);
buf = uvc_queue_head(&video->queue);
if (buf == NULL) {
spin_unlock_irqrestore(&video->queue.irqlock, flags);
break;
}
video->encode(req, video, buf);
/* Queue the USB request */
if ((ret = usb_ep_queue(video->ep, req, GFP_KERNEL)) < 0) {
printk(KERN_INFO "Failed to queue request (%d)\n", ret);
usb_ep_set_halt(video->ep);
spin_unlock_irqrestore(&video->queue.irqlock, flags);
break;
}
spin_unlock_irqrestore(&video->queue.irqlock, flags);
}
spin_lock_irqsave(&video->req_lock, flags);
list_add_tail(&req->list, &video->req_free);
spin_unlock_irqrestore(&video->req_lock, flags);
return 0;
}
/*
* Enable or disable the video stream.
*/
static int
uvc_video_enable(struct uvc_video *video, int enable)
{
unsigned int i;
int ret;
if (video->ep == NULL) {
printk(KERN_INFO "Video enable failed, device is "
"uninitialized.\n");
return -ENODEV;
}
if (!enable) {
for (i = 0; i < UVC_NUM_REQUESTS; ++i)
usb_ep_dequeue(video->ep, video->req[i]);
uvc_video_free_requests(video);
uvc_queue_enable(&video->queue, 0);
return 0;
}
if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
return ret;
if ((ret = uvc_video_alloc_requests(video)) < 0)
return ret;
if (video->max_payload_size) {
video->encode = uvc_video_encode_bulk;
video->payload_size = 0;
} else
video->encode = uvc_video_encode_isoc;
return uvc_video_pump(video);
}
/*
* Initialize the UVC video stream.
*/
static int
uvc_video_init(struct uvc_video *video)
{
INIT_LIST_HEAD(&video->req_free);
spin_lock_init(&video->req_lock);
video->fcc = V4L2_PIX_FMT_YUYV;
video->bpp = 16;
video->width = 320;
video->height = 240;
video->imagesize = 320 * 240 * 2;
/* Initialize the video buffers queue. */
uvc_queue_init(&video->queue, V4L2_BUF_TYPE_VIDEO_OUTPUT);
return 0;
}
| gpl-2.0 |
zlatinski/omap-android-drm-kms | drivers/gpu/drm/nouveau/nouveau_notifier.c | 5406 | 5290 | /*
* Copyright (C) 2007 Ben Skeggs.
*
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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 "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_ramht.h"
int
nouveau_notifier_init_channel(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_bo *ntfy = NULL;
uint32_t flags, ttmpl;
int ret;
if (nouveau_vram_notify) {
flags = NOUVEAU_GEM_DOMAIN_VRAM;
ttmpl = TTM_PL_FLAG_VRAM;
} else {
flags = NOUVEAU_GEM_DOMAIN_GART;
ttmpl = TTM_PL_FLAG_TT;
}
ret = nouveau_gem_new(dev, PAGE_SIZE, 0, flags, 0, 0, &ntfy);
if (ret)
return ret;
ret = nouveau_bo_pin(ntfy, ttmpl);
if (ret)
goto out_err;
ret = nouveau_bo_map(ntfy);
if (ret)
goto out_err;
if (dev_priv->card_type >= NV_50) {
ret = nouveau_bo_vma_add(ntfy, chan->vm, &chan->notifier_vma);
if (ret)
goto out_err;
}
ret = drm_mm_init(&chan->notifier_heap, 0, ntfy->bo.mem.size);
if (ret)
goto out_err;
chan->notifier_bo = ntfy;
out_err:
if (ret) {
nouveau_bo_vma_del(ntfy, &chan->notifier_vma);
drm_gem_object_unreference_unlocked(ntfy->gem);
}
return ret;
}
void
nouveau_notifier_takedown_channel(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
if (!chan->notifier_bo)
return;
nouveau_bo_vma_del(chan->notifier_bo, &chan->notifier_vma);
nouveau_bo_unmap(chan->notifier_bo);
mutex_lock(&dev->struct_mutex);
nouveau_bo_unpin(chan->notifier_bo);
mutex_unlock(&dev->struct_mutex);
drm_gem_object_unreference_unlocked(chan->notifier_bo->gem);
drm_mm_takedown(&chan->notifier_heap);
}
static void
nouveau_notifier_gpuobj_dtor(struct drm_device *dev,
struct nouveau_gpuobj *gpuobj)
{
NV_DEBUG(dev, "\n");
if (gpuobj->priv)
drm_mm_put_block(gpuobj->priv);
}
int
nouveau_notifier_alloc(struct nouveau_channel *chan, uint32_t handle,
int size, uint32_t start, uint32_t end,
uint32_t *b_offset)
{
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_gpuobj *nobj = NULL;
struct drm_mm_node *mem;
uint64_t offset;
int target, ret;
mem = drm_mm_search_free_in_range(&chan->notifier_heap, size, 0,
start, end, 0);
if (mem)
mem = drm_mm_get_block_range(mem, size, 0, start, end);
if (!mem) {
NV_ERROR(dev, "Channel %d notifier block full\n", chan->id);
return -ENOMEM;
}
if (dev_priv->card_type < NV_50) {
if (chan->notifier_bo->bo.mem.mem_type == TTM_PL_VRAM)
target = NV_MEM_TARGET_VRAM;
else
target = NV_MEM_TARGET_GART;
offset = chan->notifier_bo->bo.offset;
} else {
target = NV_MEM_TARGET_VM;
offset = chan->notifier_vma.offset;
}
offset += mem->start;
ret = nouveau_gpuobj_dma_new(chan, NV_CLASS_DMA_IN_MEMORY, offset,
mem->size, NV_MEM_ACCESS_RW, target,
&nobj);
if (ret) {
drm_mm_put_block(mem);
NV_ERROR(dev, "Error creating notifier ctxdma: %d\n", ret);
return ret;
}
nobj->dtor = nouveau_notifier_gpuobj_dtor;
nobj->priv = mem;
ret = nouveau_ramht_insert(chan, handle, nobj);
nouveau_gpuobj_ref(NULL, &nobj);
if (ret) {
drm_mm_put_block(mem);
NV_ERROR(dev, "Error adding notifier to ramht: %d\n", ret);
return ret;
}
*b_offset = mem->start;
return 0;
}
int
nouveau_notifier_offset(struct nouveau_gpuobj *nobj, uint32_t *poffset)
{
if (!nobj || nobj->dtor != nouveau_notifier_gpuobj_dtor)
return -EINVAL;
if (poffset) {
struct drm_mm_node *mem = nobj->priv;
if (*poffset >= mem->size)
return false;
*poffset += mem->start;
}
return 0;
}
int
nouveau_ioctl_notifier_alloc(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct drm_nouveau_notifierobj_alloc *na = data;
struct nouveau_channel *chan;
int ret;
/* completely unnecessary for these chipsets... */
if (unlikely(dev_priv->card_type >= NV_C0))
return -EINVAL;
chan = nouveau_channel_get(file_priv, na->channel);
if (IS_ERR(chan))
return PTR_ERR(chan);
ret = nouveau_notifier_alloc(chan, na->handle, na->size, 0, 0x1000,
&na->offset);
nouveau_channel_put(&chan);
return ret;
}
| gpl-2.0 |
jollaman999/jolla-kernel_G_Gen3-Stock | drivers/usb/gadget/uvc_video.c | 5406 | 9621 | /*
* uvc_video.c -- USB Video Class Gadget driver
*
* Copyright (C) 2009-2010
* Laurent Pinchart (laurent.pinchart@ideasonboard.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <media/v4l2-dev.h>
#include "uvc.h"
#include "uvc_queue.h"
/* --------------------------------------------------------------------------
* Video codecs
*/
static int
uvc_video_encode_header(struct uvc_video *video, struct uvc_buffer *buf,
u8 *data, int len)
{
data[0] = 2;
data[1] = UVC_STREAM_EOH | video->fid;
if (buf->buf.bytesused - video->queue.buf_used <= len - 2)
data[1] |= UVC_STREAM_EOF;
return 2;
}
static int
uvc_video_encode_data(struct uvc_video *video, struct uvc_buffer *buf,
u8 *data, int len)
{
struct uvc_video_queue *queue = &video->queue;
unsigned int nbytes;
void *mem;
/* Copy video data to the USB buffer. */
mem = queue->mem + buf->buf.m.offset + queue->buf_used;
nbytes = min((unsigned int)len, buf->buf.bytesused - queue->buf_used);
memcpy(data, mem, nbytes);
queue->buf_used += nbytes;
return nbytes;
}
static void
uvc_video_encode_bulk(struct usb_request *req, struct uvc_video *video,
struct uvc_buffer *buf)
{
void *mem = req->buf;
int len = video->req_size;
int ret;
/* Add a header at the beginning of the payload. */
if (video->payload_size == 0) {
ret = uvc_video_encode_header(video, buf, mem, len);
video->payload_size += ret;
mem += ret;
len -= ret;
}
/* Process video data. */
len = min((int)(video->max_payload_size - video->payload_size), len);
ret = uvc_video_encode_data(video, buf, mem, len);
video->payload_size += ret;
len -= ret;
req->length = video->req_size - len;
req->zero = video->payload_size == video->max_payload_size;
if (buf->buf.bytesused == video->queue.buf_used) {
video->queue.buf_used = 0;
buf->state = UVC_BUF_STATE_DONE;
uvc_queue_next_buffer(&video->queue, buf);
video->fid ^= UVC_STREAM_FID;
video->payload_size = 0;
}
if (video->payload_size == video->max_payload_size ||
buf->buf.bytesused == video->queue.buf_used)
video->payload_size = 0;
}
static void
uvc_video_encode_isoc(struct usb_request *req, struct uvc_video *video,
struct uvc_buffer *buf)
{
void *mem = req->buf;
int len = video->req_size;
int ret;
/* Add the header. */
ret = uvc_video_encode_header(video, buf, mem, len);
mem += ret;
len -= ret;
/* Process video data. */
ret = uvc_video_encode_data(video, buf, mem, len);
len -= ret;
req->length = video->req_size - len;
if (buf->buf.bytesused == video->queue.buf_used) {
video->queue.buf_used = 0;
buf->state = UVC_BUF_STATE_DONE;
uvc_queue_next_buffer(&video->queue, buf);
video->fid ^= UVC_STREAM_FID;
}
}
/* --------------------------------------------------------------------------
* Request handling
*/
/*
* I somehow feel that synchronisation won't be easy to achieve here. We have
* three events that control USB requests submission:
*
* - USB request completion: the completion handler will resubmit the request
* if a video buffer is available.
*
* - USB interface setting selection: in response to a SET_INTERFACE request,
* the handler will start streaming if a video buffer is available and if
* video is not currently streaming.
*
* - V4L2 buffer queueing: the driver will start streaming if video is not
* currently streaming.
*
* Race conditions between those 3 events might lead to deadlocks or other
* nasty side effects.
*
* The "video currently streaming" condition can't be detected by the irqqueue
* being empty, as a request can still be in flight. A separate "queue paused"
* flag is thus needed.
*
* The paused flag will be set when we try to retrieve the irqqueue head if the
* queue is empty, and cleared when we queue a buffer.
*
* The USB request completion handler will get the buffer at the irqqueue head
* under protection of the queue spinlock. If the queue is empty, the streaming
* paused flag will be set. Right after releasing the spinlock a userspace
* application can queue a buffer. The flag will then cleared, and the ioctl
* handler will restart the video stream.
*/
static void
uvc_video_complete(struct usb_ep *ep, struct usb_request *req)
{
struct uvc_video *video = req->context;
struct uvc_buffer *buf;
unsigned long flags;
int ret;
switch (req->status) {
case 0:
break;
case -ESHUTDOWN:
printk(KERN_INFO "VS request cancelled.\n");
goto requeue;
default:
printk(KERN_INFO "VS request completed with status %d.\n",
req->status);
goto requeue;
}
spin_lock_irqsave(&video->queue.irqlock, flags);
buf = uvc_queue_head(&video->queue);
if (buf == NULL) {
spin_unlock_irqrestore(&video->queue.irqlock, flags);
goto requeue;
}
video->encode(req, video, buf);
if ((ret = usb_ep_queue(ep, req, GFP_ATOMIC)) < 0) {
printk(KERN_INFO "Failed to queue request (%d).\n", ret);
usb_ep_set_halt(ep);
spin_unlock_irqrestore(&video->queue.irqlock, flags);
goto requeue;
}
spin_unlock_irqrestore(&video->queue.irqlock, flags);
return;
requeue:
spin_lock_irqsave(&video->req_lock, flags);
list_add_tail(&req->list, &video->req_free);
spin_unlock_irqrestore(&video->req_lock, flags);
}
static int
uvc_video_free_requests(struct uvc_video *video)
{
unsigned int i;
for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
if (video->req[i]) {
usb_ep_free_request(video->ep, video->req[i]);
video->req[i] = NULL;
}
if (video->req_buffer[i]) {
kfree(video->req_buffer[i]);
video->req_buffer[i] = NULL;
}
}
INIT_LIST_HEAD(&video->req_free);
video->req_size = 0;
return 0;
}
static int
uvc_video_alloc_requests(struct uvc_video *video)
{
unsigned int i;
int ret = -ENOMEM;
BUG_ON(video->req_size);
for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
video->req_buffer[i] = kmalloc(video->ep->maxpacket, GFP_KERNEL);
if (video->req_buffer[i] == NULL)
goto error;
video->req[i] = usb_ep_alloc_request(video->ep, GFP_KERNEL);
if (video->req[i] == NULL)
goto error;
video->req[i]->buf = video->req_buffer[i];
video->req[i]->length = 0;
video->req[i]->dma = DMA_ADDR_INVALID;
video->req[i]->complete = uvc_video_complete;
video->req[i]->context = video;
list_add_tail(&video->req[i]->list, &video->req_free);
}
video->req_size = video->ep->maxpacket;
return 0;
error:
uvc_video_free_requests(video);
return ret;
}
/* --------------------------------------------------------------------------
* Video streaming
*/
/*
* uvc_video_pump - Pump video data into the USB requests
*
* This function fills the available USB requests (listed in req_free) with
* video data from the queued buffers.
*/
static int
uvc_video_pump(struct uvc_video *video)
{
struct usb_request *req;
struct uvc_buffer *buf;
unsigned long flags;
int ret;
/* FIXME TODO Race between uvc_video_pump and requests completion
* handler ???
*/
while (1) {
/* Retrieve the first available USB request, protected by the
* request lock.
*/
spin_lock_irqsave(&video->req_lock, flags);
if (list_empty(&video->req_free)) {
spin_unlock_irqrestore(&video->req_lock, flags);
return 0;
}
req = list_first_entry(&video->req_free, struct usb_request,
list);
list_del(&req->list);
spin_unlock_irqrestore(&video->req_lock, flags);
/* Retrieve the first available video buffer and fill the
* request, protected by the video queue irqlock.
*/
spin_lock_irqsave(&video->queue.irqlock, flags);
buf = uvc_queue_head(&video->queue);
if (buf == NULL) {
spin_unlock_irqrestore(&video->queue.irqlock, flags);
break;
}
video->encode(req, video, buf);
/* Queue the USB request */
if ((ret = usb_ep_queue(video->ep, req, GFP_KERNEL)) < 0) {
printk(KERN_INFO "Failed to queue request (%d)\n", ret);
usb_ep_set_halt(video->ep);
spin_unlock_irqrestore(&video->queue.irqlock, flags);
break;
}
spin_unlock_irqrestore(&video->queue.irqlock, flags);
}
spin_lock_irqsave(&video->req_lock, flags);
list_add_tail(&req->list, &video->req_free);
spin_unlock_irqrestore(&video->req_lock, flags);
return 0;
}
/*
* Enable or disable the video stream.
*/
static int
uvc_video_enable(struct uvc_video *video, int enable)
{
unsigned int i;
int ret;
if (video->ep == NULL) {
printk(KERN_INFO "Video enable failed, device is "
"uninitialized.\n");
return -ENODEV;
}
if (!enable) {
for (i = 0; i < UVC_NUM_REQUESTS; ++i)
usb_ep_dequeue(video->ep, video->req[i]);
uvc_video_free_requests(video);
uvc_queue_enable(&video->queue, 0);
return 0;
}
if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
return ret;
if ((ret = uvc_video_alloc_requests(video)) < 0)
return ret;
if (video->max_payload_size) {
video->encode = uvc_video_encode_bulk;
video->payload_size = 0;
} else
video->encode = uvc_video_encode_isoc;
return uvc_video_pump(video);
}
/*
* Initialize the UVC video stream.
*/
static int
uvc_video_init(struct uvc_video *video)
{
INIT_LIST_HEAD(&video->req_free);
spin_lock_init(&video->req_lock);
video->fcc = V4L2_PIX_FMT_YUYV;
video->bpp = 16;
video->width = 320;
video->height = 240;
video->imagesize = 320 * 240 * 2;
/* Initialize the video buffers queue. */
uvc_queue_init(&video->queue, V4L2_BUF_TYPE_VIDEO_OUTPUT);
return 0;
}
| gpl-2.0 |
1nv4d3r5/android_kernel_oppo_find5 | drivers/video/msm/mddi_client_toshiba.c | 5918 | 7531 | /* drivers/video/msm_fb/mddi_client_toshiba.c
*
* Support for Toshiba TC358720XBG mddi client devices which require no
* special initialization code.
*
* Copyright (C) 2007 Google Incorporated
*
* 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/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/sched.h>
#include <mach/msm_fb.h>
#define LCD_CONTROL_BLOCK_BASE 0x110000
#define CMN (LCD_CONTROL_BLOCK_BASE|0x10)
#define INTFLG (LCD_CONTROL_BLOCK_BASE|0x18)
#define HCYCLE (LCD_CONTROL_BLOCK_BASE|0x34)
#define HDE_START (LCD_CONTROL_BLOCK_BASE|0x3C)
#define VPOS (LCD_CONTROL_BLOCK_BASE|0xC0)
#define MPLFBUF (LCD_CONTROL_BLOCK_BASE|0x20)
#define WAKEUP (LCD_CONTROL_BLOCK_BASE|0x54)
#define WSYN_DLY (LCD_CONTROL_BLOCK_BASE|0x58)
#define REGENB (LCD_CONTROL_BLOCK_BASE|0x5C)
#define BASE5 0x150000
#define BASE6 0x160000
#define BASE7 0x170000
#define GPIOIEV (BASE5 + 0x10)
#define GPIOIE (BASE5 + 0x14)
#define GPIORIS (BASE5 + 0x18)
#define GPIOMIS (BASE5 + 0x1C)
#define GPIOIC (BASE5 + 0x20)
#define INTMASK (BASE6 + 0x0C)
#define INTMASK_VWAKEOUT (1U << 0)
#define INTMASK_VWAKEOUT_ACTIVE_LOW (1U << 8)
#define GPIOSEL (BASE7 + 0x00)
#define GPIOSEL_VWAKEINT (1U << 0)
static DECLARE_WAIT_QUEUE_HEAD(toshiba_vsync_wait);
struct panel_info {
struct msm_mddi_client_data *client_data;
struct platform_device pdev;
struct msm_panel_data panel_data;
struct msmfb_callback *toshiba_callback;
int toshiba_got_int;
int irq;
};
static void toshiba_request_vsync(struct msm_panel_data *panel_data,
struct msmfb_callback *callback)
{
struct panel_info *panel = container_of(panel_data, struct panel_info,
panel_data);
struct msm_mddi_client_data *client_data = panel->client_data;
panel->toshiba_callback = callback;
if (panel->toshiba_got_int) {
panel->toshiba_got_int = 0;
client_data->activate_link(client_data);
}
}
static void toshiba_clear_vsync(struct msm_panel_data *panel_data)
{
struct panel_info *panel = container_of(panel_data, struct panel_info,
panel_data);
struct msm_mddi_client_data *client_data = panel->client_data;
client_data->activate_link(client_data);
}
static void toshiba_wait_vsync(struct msm_panel_data *panel_data)
{
struct panel_info *panel = container_of(panel_data, struct panel_info,
panel_data);
struct msm_mddi_client_data *client_data = panel->client_data;
if (panel->toshiba_got_int) {
panel->toshiba_got_int = 0;
client_data->activate_link(client_data); /* clears interrupt */
}
if (wait_event_timeout(toshiba_vsync_wait, panel->toshiba_got_int,
HZ/2) == 0)
printk(KERN_ERR "timeout waiting for VSYNC\n");
panel->toshiba_got_int = 0;
/* interrupt clears when screen dma starts */
}
static int toshiba_suspend(struct msm_panel_data *panel_data)
{
struct panel_info *panel = container_of(panel_data, struct panel_info,
panel_data);
struct msm_mddi_client_data *client_data = panel->client_data;
struct msm_mddi_bridge_platform_data *bridge_data =
client_data->private_client_data;
int ret;
ret = bridge_data->uninit(bridge_data, client_data);
if (ret) {
printk(KERN_INFO "mddi toshiba client: non zero return from "
"uninit\n");
return ret;
}
client_data->suspend(client_data);
return 0;
}
static int toshiba_resume(struct msm_panel_data *panel_data)
{
struct panel_info *panel = container_of(panel_data, struct panel_info,
panel_data);
struct msm_mddi_client_data *client_data = panel->client_data;
struct msm_mddi_bridge_platform_data *bridge_data =
client_data->private_client_data;
int ret;
client_data->resume(client_data);
ret = bridge_data->init(bridge_data, client_data);
if (ret)
return ret;
return 0;
}
static int toshiba_blank(struct msm_panel_data *panel_data)
{
struct panel_info *panel = container_of(panel_data, struct panel_info,
panel_data);
struct msm_mddi_client_data *client_data = panel->client_data;
struct msm_mddi_bridge_platform_data *bridge_data =
client_data->private_client_data;
return bridge_data->blank(bridge_data, client_data);
}
static int toshiba_unblank(struct msm_panel_data *panel_data)
{
struct panel_info *panel = container_of(panel_data, struct panel_info,
panel_data);
struct msm_mddi_client_data *client_data = panel->client_data;
struct msm_mddi_bridge_platform_data *bridge_data =
client_data->private_client_data;
return bridge_data->unblank(bridge_data, client_data);
}
irqreturn_t toshiba_vsync_interrupt(int irq, void *data)
{
struct panel_info *panel = data;
panel->toshiba_got_int = 1;
if (panel->toshiba_callback) {
panel->toshiba_callback->func(panel->toshiba_callback);
panel->toshiba_callback = 0;
}
wake_up(&toshiba_vsync_wait);
return IRQ_HANDLED;
}
static int mddi_toshiba_probe(struct platform_device *pdev)
{
int ret;
struct msm_mddi_client_data *client_data = pdev->dev.platform_data;
struct msm_mddi_bridge_platform_data *bridge_data =
client_data->private_client_data;
struct panel_info *panel =
kzalloc(sizeof(struct panel_info), GFP_KERNEL);
if (!panel)
return -ENOMEM;
platform_set_drvdata(pdev, panel);
/* mddi_remote_write(mddi, 0, WAKEUP); */
client_data->remote_write(client_data, GPIOSEL_VWAKEINT, GPIOSEL);
client_data->remote_write(client_data, INTMASK_VWAKEOUT, INTMASK);
ret = platform_get_irq_byname(pdev, "vsync");
if (ret < 0)
goto err_plat_get_irq;
panel->irq = ret;
ret = request_irq(panel->irq, toshiba_vsync_interrupt,
IRQF_TRIGGER_RISING, "vsync", panel);
if (ret) {
dev_err(&pdev->dev, "mddi_bridge_setup_vsync failed\n");
goto err_req_irq;
}
panel->client_data = client_data;
panel->panel_data.suspend = toshiba_suspend;
panel->panel_data.resume = toshiba_resume;
panel->panel_data.wait_vsync = toshiba_wait_vsync;
panel->panel_data.request_vsync = toshiba_request_vsync;
panel->panel_data.clear_vsync = toshiba_clear_vsync;
panel->panel_data.blank = toshiba_blank;
panel->panel_data.unblank = toshiba_unblank;
panel->panel_data.fb_data = &bridge_data->fb_data;
panel->panel_data.caps = MSMFB_CAP_PARTIAL_UPDATES;
panel->pdev.name = "msm_panel";
panel->pdev.id = pdev->id;
panel->pdev.resource = client_data->fb_resource;
panel->pdev.num_resources = 1;
panel->pdev.dev.platform_data = &panel->panel_data;
bridge_data->init(bridge_data, client_data);
platform_device_register(&panel->pdev);
return 0;
err_req_irq:
err_plat_get_irq:
kfree(panel);
return ret;
}
static int mddi_toshiba_remove(struct platform_device *pdev)
{
struct panel_info *panel = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
free_irq(panel->irq, panel);
kfree(panel);
return 0;
}
static struct platform_driver mddi_client_d263_0000 = {
.probe = mddi_toshiba_probe,
.remove = mddi_toshiba_remove,
.driver = { .name = "mddi_c_d263_0000" },
};
static int __init mddi_client_toshiba_init(void)
{
platform_driver_register(&mddi_client_d263_0000);
return 0;
}
module_init(mddi_client_toshiba_init);
| gpl-2.0 |
FrancescoCG/CrazySuperKernel-CM13-KLTE | drivers/input/mouse/logips2pp.c | 7198 | 11714 | /*
* Logitech PS/2++ mouse driver
*
* Copyright (c) 1999-2003 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2003 Eric Wong <eric@yhbt.net>
*
* 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/input.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include "psmouse.h"
#include "logips2pp.h"
/* Logitech mouse types */
#define PS2PP_KIND_WHEEL 1
#define PS2PP_KIND_MX 2
#define PS2PP_KIND_TP3 3
#define PS2PP_KIND_TRACKMAN 4
/* Logitech mouse features */
#define PS2PP_WHEEL 0x01
#define PS2PP_HWHEEL 0x02
#define PS2PP_SIDE_BTN 0x04
#define PS2PP_EXTRA_BTN 0x08
#define PS2PP_TASK_BTN 0x10
#define PS2PP_NAV_BTN 0x20
struct ps2pp_info {
u8 model;
u8 kind;
u16 features;
};
/*
* Process a PS2++ or PS2T++ packet.
*/
static psmouse_ret_t ps2pp_process_byte(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
if (psmouse->pktcnt < 3)
return PSMOUSE_GOOD_DATA;
/*
* Full packet accumulated, process it
*/
if ((packet[0] & 0x48) == 0x48 && (packet[1] & 0x02) == 0x02) {
/* Logitech extended packet */
switch ((packet[1] >> 4) | (packet[0] & 0x30)) {
case 0x0d: /* Mouse extra info */
input_report_rel(dev, packet[2] & 0x80 ? REL_HWHEEL : REL_WHEEL,
(int) (packet[2] & 8) - (int) (packet[2] & 7));
input_report_key(dev, BTN_SIDE, (packet[2] >> 4) & 1);
input_report_key(dev, BTN_EXTRA, (packet[2] >> 5) & 1);
break;
case 0x0e: /* buttons 4, 5, 6, 7, 8, 9, 10 info */
input_report_key(dev, BTN_SIDE, (packet[2]) & 1);
input_report_key(dev, BTN_EXTRA, (packet[2] >> 1) & 1);
input_report_key(dev, BTN_BACK, (packet[2] >> 3) & 1);
input_report_key(dev, BTN_FORWARD, (packet[2] >> 4) & 1);
input_report_key(dev, BTN_TASK, (packet[2] >> 2) & 1);
break;
case 0x0f: /* TouchPad extra info */
input_report_rel(dev, packet[2] & 0x08 ? REL_HWHEEL : REL_WHEEL,
(int) ((packet[2] >> 4) & 8) - (int) ((packet[2] >> 4) & 7));
packet[0] = packet[2] | 0x08;
break;
default:
psmouse_dbg(psmouse,
"Received PS2++ packet #%x, but don't know how to handle.\n",
(packet[1] >> 4) | (packet[0] & 0x30));
break;
}
} else {
/* Standard PS/2 motion data */
input_report_rel(dev, REL_X, packet[1] ? (int) packet[1] - (int) ((packet[0] << 4) & 0x100) : 0);
input_report_rel(dev, REL_Y, packet[2] ? (int) ((packet[0] << 3) & 0x100) - (int) packet[2] : 0);
}
input_report_key(dev, BTN_LEFT, packet[0] & 1);
input_report_key(dev, BTN_MIDDLE, (packet[0] >> 2) & 1);
input_report_key(dev, BTN_RIGHT, (packet[0] >> 1) & 1);
input_sync(dev);
return PSMOUSE_FULL_PACKET;
}
/*
* ps2pp_cmd() sends a PS2++ command, sliced into two bit
* pieces through the SETRES command. This is needed to send extended
* commands to mice on notebooks that try to understand the PS/2 protocol
* Ugly.
*/
static int ps2pp_cmd(struct psmouse *psmouse, unsigned char *param, unsigned char command)
{
if (psmouse_sliced_command(psmouse, command))
return -1;
if (ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_POLL | 0x0300))
return -1;
return 0;
}
/*
* SmartScroll / CruiseControl for some newer Logitech mice Defaults to
* enabled if we do nothing to it. Of course I put this in because I want it
* disabled :P
* 1 - enabled (if previously disabled, also default)
* 0 - disabled
*/
static void ps2pp_set_smartscroll(struct psmouse *psmouse, bool smartscroll)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
ps2pp_cmd(psmouse, param, 0x32);
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
param[0] = smartscroll;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
}
static ssize_t ps2pp_attr_show_smartscroll(struct psmouse *psmouse,
void *data, char *buf)
{
return sprintf(buf, "%d\n", psmouse->smartscroll);
}
static ssize_t ps2pp_attr_set_smartscroll(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
ps2pp_set_smartscroll(psmouse, value);
psmouse->smartscroll = value;
return count;
}
PSMOUSE_DEFINE_ATTR(smartscroll, S_IWUSR | S_IRUGO, NULL,
ps2pp_attr_show_smartscroll, ps2pp_attr_set_smartscroll);
/*
* Support 800 dpi resolution _only_ if the user wants it (there are good
* reasons to not use it even if the mouse supports it, and of course there are
* also good reasons to use it, let the user decide).
*/
static void ps2pp_set_resolution(struct psmouse *psmouse, unsigned int resolution)
{
if (resolution > 400) {
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param = 3;
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, ¶m, PSMOUSE_CMD_SETRES);
psmouse->resolution = 800;
} else
psmouse_set_resolution(psmouse, resolution);
}
static void ps2pp_disconnect(struct psmouse *psmouse)
{
device_remove_file(&psmouse->ps2dev.serio->dev, &psmouse_attr_smartscroll.dattr);
}
static const struct ps2pp_info *get_model_info(unsigned char model)
{
static const struct ps2pp_info ps2pp_list[] = {
{ 1, 0, 0 }, /* Simple 2-button mouse */
{ 12, 0, PS2PP_SIDE_BTN},
{ 13, 0, 0 },
{ 15, PS2PP_KIND_MX, /* MX1000 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 40, 0, PS2PP_SIDE_BTN },
{ 41, 0, PS2PP_SIDE_BTN },
{ 42, 0, PS2PP_SIDE_BTN },
{ 43, 0, PS2PP_SIDE_BTN },
{ 50, 0, 0 },
{ 51, 0, 0 },
{ 52, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 53, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 56, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL }, /* Cordless MouseMan Wheel */
{ 61, PS2PP_KIND_MX, /* MX700 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 66, PS2PP_KIND_MX, /* MX3100 reciver */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 72, PS2PP_KIND_TRACKMAN, 0 }, /* T-CH11: TrackMan Marble */
{ 73, PS2PP_KIND_TRACKMAN, PS2PP_SIDE_BTN }, /* TrackMan FX */
{ 75, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 76, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 79, PS2PP_KIND_TRACKMAN, PS2PP_WHEEL }, /* TrackMan with wheel */
{ 80, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 81, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 83, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 85, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 86, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 87, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 88, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 96, 0, 0 },
{ 97, PS2PP_KIND_TP3, PS2PP_WHEEL | PS2PP_HWHEEL },
{ 99, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 100, PS2PP_KIND_MX, /* MX510 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 111, PS2PP_KIND_MX, PS2PP_WHEEL | PS2PP_SIDE_BTN }, /* MX300 reports task button as side */
{ 112, PS2PP_KIND_MX, /* MX500 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 114, PS2PP_KIND_MX, /* MX310 */
PS2PP_WHEEL | PS2PP_SIDE_BTN |
PS2PP_TASK_BTN | PS2PP_EXTRA_BTN }
};
int i;
for (i = 0; i < ARRAY_SIZE(ps2pp_list); i++)
if (model == ps2pp_list[i].model)
return &ps2pp_list[i];
return NULL;
}
/*
* Set up input device's properties based on the detected mouse model.
*/
static void ps2pp_set_model_properties(struct psmouse *psmouse,
const struct ps2pp_info *model_info,
bool using_ps2pp)
{
struct input_dev *input_dev = psmouse->dev;
if (model_info->features & PS2PP_SIDE_BTN)
__set_bit(BTN_SIDE, input_dev->keybit);
if (model_info->features & PS2PP_EXTRA_BTN)
__set_bit(BTN_EXTRA, input_dev->keybit);
if (model_info->features & PS2PP_TASK_BTN)
__set_bit(BTN_TASK, input_dev->keybit);
if (model_info->features & PS2PP_NAV_BTN) {
__set_bit(BTN_FORWARD, input_dev->keybit);
__set_bit(BTN_BACK, input_dev->keybit);
}
if (model_info->features & PS2PP_WHEEL)
__set_bit(REL_WHEEL, input_dev->relbit);
if (model_info->features & PS2PP_HWHEEL)
__set_bit(REL_HWHEEL, input_dev->relbit);
switch (model_info->kind) {
case PS2PP_KIND_WHEEL:
psmouse->name = "Wheel Mouse";
break;
case PS2PP_KIND_MX:
psmouse->name = "MX Mouse";
break;
case PS2PP_KIND_TP3:
psmouse->name = "TouchPad 3";
break;
case PS2PP_KIND_TRACKMAN:
psmouse->name = "TrackMan";
break;
default:
/*
* Set name to "Mouse" only when using PS2++,
* otherwise let other protocols define suitable
* name
*/
if (using_ps2pp)
psmouse->name = "Mouse";
break;
}
}
/*
* Logitech magic init. Detect whether the mouse is a Logitech one
* and its exact model and try turning on extended protocol for ones
* that support it.
*/
int ps2pp_init(struct psmouse *psmouse, bool set_properties)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
unsigned char model, buttons;
const struct ps2pp_info *model_info;
bool use_ps2pp = false;
int error;
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
param[1] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO);
model = ((param[0] >> 4) & 0x07) | ((param[0] << 3) & 0x78);
buttons = param[1];
if (!model || !buttons)
return -1;
model_info = get_model_info(model);
if (model_info) {
/*
* Do Logitech PS2++ / PS2T++ magic init.
*/
if (model_info->kind == PS2PP_KIND_TP3) { /* Touch Pad 3 */
/* Unprotect RAM */
param[0] = 0x11; param[1] = 0x04; param[2] = 0x68;
ps2_command(ps2dev, param, 0x30d1);
/* Enable features */
param[0] = 0x11; param[1] = 0x05; param[2] = 0x0b;
ps2_command(ps2dev, param, 0x30d1);
/* Enable PS2++ */
param[0] = 0x11; param[1] = 0x09; param[2] = 0xc3;
ps2_command(ps2dev, param, 0x30d1);
param[0] = 0;
if (!ps2_command(ps2dev, param, 0x13d1) &&
param[0] == 0x06 && param[1] == 0x00 && param[2] == 0x14) {
use_ps2pp = true;
}
} else {
param[0] = param[1] = param[2] = 0;
ps2pp_cmd(psmouse, param, 0x39); /* Magic knock */
ps2pp_cmd(psmouse, param, 0xDB);
if ((param[0] & 0x78) == 0x48 &&
(param[1] & 0xf3) == 0xc2 &&
(param[2] & 0x03) == ((param[1] >> 2) & 3)) {
ps2pp_set_smartscroll(psmouse, false);
use_ps2pp = true;
}
}
} else {
psmouse_warn(psmouse, "Detected unknown Logitech mouse model %d\n", model);
}
if (set_properties) {
psmouse->vendor = "Logitech";
psmouse->model = model;
if (use_ps2pp) {
psmouse->protocol_handler = ps2pp_process_byte;
psmouse->pktsize = 3;
if (model_info->kind != PS2PP_KIND_TP3) {
psmouse->set_resolution = ps2pp_set_resolution;
psmouse->disconnect = ps2pp_disconnect;
error = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_smartscroll.dattr);
if (error) {
psmouse_err(psmouse,
"failed to create smartscroll sysfs attribute, error: %d\n",
error);
return -1;
}
}
}
if (buttons >= 3)
__set_bit(BTN_MIDDLE, psmouse->dev->keybit);
if (model_info)
ps2pp_set_model_properties(psmouse, model_info, use_ps2pp);
}
return use_ps2pp ? 0 : -1;
}
| gpl-2.0 |
devttys1/linux-fslc | arch/m68k/mac/macints.c | 8734 | 8348 | /*
* Macintosh interrupts
*
* General design:
* In contrary to the Amiga and Atari platforms, the Mac hardware seems to
* exclusively use the autovector interrupts (the 'generic level0-level7'
* interrupts with exception vectors 0x19-0x1f). The following interrupt levels
* are used:
* 1 - VIA1
* - slot 0: one second interrupt (CA2)
* - slot 1: VBlank (CA1)
* - slot 2: ADB data ready (SR full)
* - slot 3: ADB data (CB2)
* - slot 4: ADB clock (CB1)
* - slot 5: timer 2
* - slot 6: timer 1
* - slot 7: status of IRQ; signals 'any enabled int.'
*
* 2 - VIA2 or RBV
* - slot 0: SCSI DRQ (CA2)
* - slot 1: NUBUS IRQ (CA1) need to read port A to find which
* - slot 2: /EXP IRQ (only on IIci)
* - slot 3: SCSI IRQ (CB2)
* - slot 4: ASC IRQ (CB1)
* - slot 5: timer 2 (not on IIci)
* - slot 6: timer 1 (not on IIci)
* - slot 7: status of IRQ; signals 'any enabled int.'
*
* Levels 3-6 vary by machine type. For VIA or RBV Macintoshes:
*
* 3 - unused (?)
*
* 4 - SCC
*
* 5 - unused (?)
* [serial errors or special conditions seem to raise level 6
* interrupts on some models (LC4xx?)]
*
* 6 - off switch (?)
*
* Machines with Quadra-like VIA hardware, except PSC and PMU machines, support
* an alternate interrupt mapping, as used by A/UX. It spreads ethernet and
* sound out to their own autovector IRQs and gives VIA1 a higher priority:
*
* 1 - unused (?)
*
* 3 - on-board SONIC
*
* 5 - Apple Sound Chip (ASC)
*
* 6 - VIA1
*
* For OSS Macintoshes (IIfx only), we apply an interrupt mapping similar to
* the Quadra (A/UX) mapping:
*
* 1 - ISM IOP (ADB)
*
* 2 - SCSI
*
* 3 - NuBus
*
* 4 - SCC IOP
*
* 6 - VIA1
*
* For PSC Macintoshes (660AV, 840AV):
*
* 3 - PSC level 3
* - slot 0: MACE
*
* 4 - PSC level 4
* - slot 1: SCC channel A interrupt
* - slot 2: SCC channel B interrupt
* - slot 3: MACE DMA
*
* 5 - PSC level 5
*
* 6 - PSC level 6
*
* Finally we have good 'ole level 7, the non-maskable interrupt:
*
* 7 - NMI (programmer's switch on the back of some Macs)
* Also RAM parity error on models which support it (IIc, IIfx?)
*
* The current interrupt logic looks something like this:
*
* - We install dispatchers for the autovector interrupts (1-7). These
* dispatchers are responsible for querying the hardware (the
* VIA/RBV/OSS/PSC chips) to determine the actual interrupt source. Using
* this information a machspec interrupt number is generated by placing the
* index of the interrupt hardware into the low three bits and the original
* autovector interrupt number in the upper 5 bits. The handlers for the
* resulting machspec interrupt are then called.
*
* - Nubus is a special case because its interrupts are hidden behind two
* layers of hardware. Nubus interrupts come in as index 1 on VIA #2,
* which translates to IRQ number 17. In this spot we install _another_
* dispatcher. This dispatcher finds the interrupting slot number (9-F) and
* then forms a new machspec interrupt number as above with the slot number
* minus 9 in the low three bits and the pseudo-level 7 in the upper five
* bits. The handlers for this new machspec interrupt number are then
* called. This puts Nubus interrupts into the range 56-62.
*
* - The Baboon interrupts (used on some PowerBooks) are an even more special
* case. They're hidden behind the Nubus slot $C interrupt thus adding a
* third layer of indirection. Why oh why did the Apple engineers do that?
*
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <asm/macintosh.h>
#include <asm/macints.h>
#include <asm/mac_via.h>
#include <asm/mac_psc.h>
#include <asm/mac_oss.h>
#include <asm/mac_iop.h>
#include <asm/mac_baboon.h>
#include <asm/hwtest.h>
#include <asm/irq_regs.h>
#define SHUTUP_SONIC
/*
* console_loglevel determines NMI handler function
*/
irqreturn_t mac_nmi_handler(int, void *);
irqreturn_t mac_debug_handler(int, void *);
/* #define DEBUG_MACINTS */
static unsigned int mac_irq_startup(struct irq_data *);
static void mac_irq_shutdown(struct irq_data *);
static struct irq_chip mac_irq_chip = {
.name = "mac",
.irq_enable = mac_irq_enable,
.irq_disable = mac_irq_disable,
.irq_startup = mac_irq_startup,
.irq_shutdown = mac_irq_shutdown,
};
void __init mac_init_IRQ(void)
{
#ifdef DEBUG_MACINTS
printk("mac_init_IRQ(): Setting things up...\n");
#endif
m68k_setup_irq_controller(&mac_irq_chip, handle_simple_irq, IRQ_USER,
NUM_MAC_SOURCES - IRQ_USER);
/* Make sure the SONIC interrupt is cleared or things get ugly */
#ifdef SHUTUP_SONIC
printk("Killing onboard sonic... ");
/* This address should hopefully be mapped already */
if (hwreg_present((void*)(0x50f0a000))) {
*(long *)(0x50f0a014) = 0x7fffL;
*(long *)(0x50f0a010) = 0L;
}
printk("Done.\n");
#endif /* SHUTUP_SONIC */
/*
* Now register the handlers for the master IRQ handlers
* at levels 1-7. Most of the work is done elsewhere.
*/
if (oss_present)
oss_register_interrupts();
else
via_register_interrupts();
if (psc_present)
psc_register_interrupts();
if (baboon_present)
baboon_register_interrupts();
iop_register_interrupts();
if (request_irq(IRQ_AUTO_7, mac_nmi_handler, 0, "NMI",
mac_nmi_handler))
pr_err("Couldn't register NMI\n");
#ifdef DEBUG_MACINTS
printk("mac_init_IRQ(): Done!\n");
#endif
}
/*
* mac_irq_enable - enable an interrupt source
* mac_irq_disable - disable an interrupt source
*
* These routines are just dispatchers to the VIA/OSS/PSC routines.
*/
void mac_irq_enable(struct irq_data *data)
{
int irq = data->irq;
int irq_src = IRQ_SRC(irq);
switch(irq_src) {
case 1:
case 2:
case 7:
if (oss_present)
oss_irq_enable(irq);
else
via_irq_enable(irq);
break;
case 3:
case 4:
case 5:
case 6:
if (psc_present)
psc_irq_enable(irq);
else if (oss_present)
oss_irq_enable(irq);
break;
case 8:
if (baboon_present)
baboon_irq_enable(irq);
break;
}
}
void mac_irq_disable(struct irq_data *data)
{
int irq = data->irq;
int irq_src = IRQ_SRC(irq);
switch(irq_src) {
case 1:
case 2:
case 7:
if (oss_present)
oss_irq_disable(irq);
else
via_irq_disable(irq);
break;
case 3:
case 4:
case 5:
case 6:
if (psc_present)
psc_irq_disable(irq);
else if (oss_present)
oss_irq_disable(irq);
break;
case 8:
if (baboon_present)
baboon_irq_disable(irq);
break;
}
}
static unsigned int mac_irq_startup(struct irq_data *data)
{
int irq = data->irq;
if (IRQ_SRC(irq) == 7 && !oss_present)
via_nubus_irq_startup(irq);
else
mac_irq_enable(data);
return 0;
}
static void mac_irq_shutdown(struct irq_data *data)
{
int irq = data->irq;
if (IRQ_SRC(irq) == 7 && !oss_present)
via_nubus_irq_shutdown(irq);
else
mac_irq_disable(data);
}
static int num_debug[8];
irqreturn_t mac_debug_handler(int irq, void *dev_id)
{
if (num_debug[irq] < 10) {
printk("DEBUG: Unexpected IRQ %d\n", irq);
num_debug[irq]++;
}
return IRQ_HANDLED;
}
static int in_nmi;
static volatile int nmi_hold;
irqreturn_t mac_nmi_handler(int irq, void *dev_id)
{
int i;
/*
* generate debug output on NMI switch if 'debug' kernel option given
* (only works with Penguin!)
*/
in_nmi++;
for (i=0; i<100; i++)
udelay(1000);
if (in_nmi == 1) {
nmi_hold = 1;
printk("... pausing, press NMI to resume ...");
} else {
printk(" ok!\n");
nmi_hold = 0;
}
barrier();
while (nmi_hold == 1)
udelay(1000);
if (console_loglevel >= 8) {
#if 0
struct pt_regs *fp = get_irq_regs();
show_state();
printk("PC: %08lx\nSR: %04x SP: %p\n", fp->pc, fp->sr, fp);
printk("d0: %08lx d1: %08lx d2: %08lx d3: %08lx\n",
fp->d0, fp->d1, fp->d2, fp->d3);
printk("d4: %08lx d5: %08lx a0: %08lx a1: %08lx\n",
fp->d4, fp->d5, fp->a0, fp->a1);
if (STACK_MAGIC != *(unsigned long *)current->kernel_stack_page)
printk("Corrupted stack page\n");
printk("Process %s (pid: %d, stackpage=%08lx)\n",
current->comm, current->pid, current->kernel_stack_page);
if (intr_count == 1)
dump_stack((struct frame *)fp);
#else
/* printk("NMI "); */
#endif
}
in_nmi--;
return IRQ_HANDLED;
}
| gpl-2.0 |
Ca1ne/Enoch316 | arch/arm/common/gic.c | 31 | 28511 | /*
* linux/arch/arm/common/gic.c
*
* Copyright (C) 2002 ARM Limited, 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.
*
* Interrupt architecture for the GIC:
*
* o There is one Interrupt Distributor, which receives interrupts
* from system devices and sends them to the Interrupt Controllers.
*
* o There is one CPU Interface per CPU, which sends interrupts sent
* by the Distributor, and interrupts generated locally, to the
* associated CPU. The base address of the CPU interface is usually
* aliased so that the same address points to different chips depending
* on the CPU it is accessed from.
*
* Note that IRQs 0-31 are special - they are local to each CPU.
* As such, the enable set/clear, pending set/clear and active bit
* registers are banked per-cpu for these sources.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/smp.h>
#include <linux/cpu_pm.h>
#include <linux/cpumask.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/irqdomain.h>
#include <linux/interrupt.h>
#include <linux/percpu.h>
#include <linux/slab.h>
#include <linux/syscore_ops.h>
#include <asm/irq.h>
#include <asm/exception.h>
#include <asm/smp_plat.h>
#include <asm/mach/irq.h>
#include <asm/hardware/gic.h>
#include <asm/system.h>
#if defined(CONFIG_TRACING_SPINLOCK) || defined(CONFIG_TRACING_WORKQUEUE_HISTORY)
#include <mach/msm_iomap.h>
#endif
union gic_base {
void __iomem *common_base;
void __percpu __iomem **percpu_base;
};
struct gic_chip_data {
unsigned int irq_offset;
union gic_base dist_base;
union gic_base cpu_base;
#ifdef CONFIG_CPU_PM
u32 saved_spi_enable[DIV_ROUND_UP(1020, 32)];
u32 saved_spi_conf[DIV_ROUND_UP(1020, 16)];
u32 saved_spi_target[DIV_ROUND_UP(1020, 4)];
u32 saved_dist_pri[DIV_ROUND_UP(1020, 4)];
u32 __percpu *saved_ppi_enable;
u32 __percpu *saved_ppi_conf;
#endif
struct irq_domain *domain;
unsigned int gic_irqs;
#ifdef CONFIG_GIC_NON_BANKED
void __iomem *(*get_base)(union gic_base *);
#endif
unsigned int max_irq;
#ifdef CONFIG_PM
unsigned int wakeup_irqs[32];
unsigned int enabled_irqs[32];
#endif
};
static DEFINE_RAW_SPINLOCK(irq_controller_lock);
#ifdef CONFIG_CPU_PM
static unsigned int saved_dist_ctrl, saved_cpu_ctrl;
#endif
#ifdef CONFIG_TRACING_SPINLOCK
int *spin_locking_flag;
#endif
#ifdef CONFIG_TRACING_WORKQUEUE_HISTORY
char *wq_history_flag;
#endif
struct irq_chip gic_arch_extn = {
.irq_eoi = NULL,
.irq_mask = NULL,
.irq_unmask = NULL,
.irq_retrigger = NULL,
.irq_set_type = NULL,
.irq_set_wake = NULL,
.irq_disable = NULL,
};
#ifndef MAX_GIC_NR
#define MAX_GIC_NR 1
#endif
static struct gic_chip_data gic_data[MAX_GIC_NR] __read_mostly;
#ifdef CONFIG_GIC_NON_BANKED
static void __iomem *gic_get_percpu_base(union gic_base *base)
{
return *__this_cpu_ptr(base->percpu_base);
}
static void __iomem *gic_get_common_base(union gic_base *base)
{
return base->common_base;
}
static inline void __iomem *gic_data_dist_base(struct gic_chip_data *data)
{
return data->get_base(&data->dist_base);
}
static inline void __iomem *gic_data_cpu_base(struct gic_chip_data *data)
{
return data->get_base(&data->cpu_base);
}
static inline void gic_set_base_accessor(struct gic_chip_data *data,
void __iomem *(*f)(union gic_base *))
{
data->get_base = f;
}
#else
#define gic_data_dist_base(d) ((d)->dist_base.common_base)
#define gic_data_cpu_base(d) ((d)->cpu_base.common_base)
#define gic_set_base_accessor(d,f)
#endif
static inline void __iomem *gic_dist_base(struct irq_data *d)
{
struct gic_chip_data *gic_data = irq_data_get_irq_chip_data(d);
return gic_data_dist_base(gic_data);
}
static inline void __iomem *gic_cpu_base(struct irq_data *d)
{
struct gic_chip_data *gic_data = irq_data_get_irq_chip_data(d);
return gic_data_cpu_base(gic_data);
}
static inline unsigned int gic_irq(struct irq_data *d)
{
return d->hwirq;
}
#if defined(CONFIG_CPU_V7) && defined(CONFIG_GIC_SECURE)
static const inline bool is_cpu_secure(void)
{
unsigned int dscr;
asm volatile ("mrc p14, 0, %0, c0, c1, 0" : "=r" (dscr));
if (BIT(18) & dscr)
return false;
else
return true;
}
#else
static const inline bool is_cpu_secure(void)
{
return false;
}
#endif
static void gic_mask_irq(struct irq_data *d)
{
u32 mask = 1 << (gic_irq(d) % 32);
raw_spin_lock(&irq_controller_lock);
writel_relaxed(mask, gic_dist_base(d) + GIC_DIST_ENABLE_CLEAR + (gic_irq(d) / 32) * 4);
if (gic_arch_extn.irq_mask)
gic_arch_extn.irq_mask(d);
raw_spin_unlock(&irq_controller_lock);
}
static void gic_unmask_irq(struct irq_data *d)
{
u32 mask = 1 << (gic_irq(d) % 32);
raw_spin_lock(&irq_controller_lock);
if (gic_arch_extn.irq_unmask)
gic_arch_extn.irq_unmask(d);
writel_relaxed(mask, gic_dist_base(d) + GIC_DIST_ENABLE_SET + (gic_irq(d) / 32) * 4);
raw_spin_unlock(&irq_controller_lock);
}
static void gic_disable_irq(struct irq_data *d)
{
if (gic_arch_extn.irq_disable)
gic_arch_extn.irq_disable(d);
}
#ifdef CONFIG_PM
static int gic_suspend_one(struct gic_chip_data *gic)
{
unsigned int i;
void __iomem *base = gic_data_dist_base(gic);
#ifdef CONFIG_ARCH_MSM8625
unsigned long flags;
#endif
for (i = 0; i * 32 < gic->max_irq; i++) {
#ifdef CONFIG_ARCH_MSM8625
raw_spin_lock_irqsave(&irq_controller_lock, flags);
#endif
gic->enabled_irqs[i]
= readl_relaxed(base + GIC_DIST_ENABLE_SET + i * 4);
writel_relaxed(0xffffffff, base + GIC_DIST_ENABLE_CLEAR + i * 4);
writel_relaxed(gic->wakeup_irqs[i],
base + GIC_DIST_ENABLE_SET + i * 4);
#ifdef CONFIG_ARCH_MSM8625
raw_spin_unlock_irqrestore(&irq_controller_lock, flags);
#endif
}
mb();
return 0;
}
static int gic_suspend(void)
{
int i;
for (i = 0; i < MAX_GIC_NR; i++)
gic_suspend_one(&gic_data[i]);
return 0;
}
extern int msm_show_resume_irq_mask;
static void gic_show_resume_irq(struct gic_chip_data *gic)
{
unsigned int i;
u32 enabled;
unsigned long pending[32];
void __iomem *base = gic_data_dist_base(gic);
if (!msm_show_resume_irq_mask)
return;
raw_spin_lock(&irq_controller_lock);
for (i = 0; i * 32 < gic->max_irq; i++) {
enabled = readl_relaxed(base + GIC_DIST_ENABLE_CLEAR + i * 4);
pending[i] = readl_relaxed(base + GIC_DIST_PENDING_SET + i * 4);
pending[i] &= enabled;
}
raw_spin_unlock(&irq_controller_lock);
for (i = find_first_bit(pending, gic->max_irq);
i < gic->max_irq;
i = find_next_bit(pending, gic->max_irq, i+1)) {
pr_warning("%s: %d triggered", __func__, i + gic->irq_offset);
#if defined(CONFIG_ARCH_MSM8960) || defined(CONFIG_ARCH_APQ8064)
if (TLMM_MSM_SUMMARY_IRQ != i + gic->irq_offset) {
#endif
pr_warning("[K][WAKEUP] Resume caused by gic-%d\n",i + gic->irq_offset);
#if defined(CONFIG_ARCH_MSM8960) || defined(CONFIG_ARCH_APQ8064)
}
#endif
}
}
static void gic_resume_one(struct gic_chip_data *gic)
{
unsigned int i;
void __iomem *base = gic_data_dist_base(gic);
gic_show_resume_irq(gic);
for (i = 0; i * 32 < gic->max_irq; i++) {
writel_relaxed(0xffffffff, base + GIC_DIST_ENABLE_CLEAR + i * 4);
writel_relaxed(gic->enabled_irqs[i],
base + GIC_DIST_ENABLE_SET + i * 4);
}
mb();
}
static void gic_resume(void)
{
int i;
for (i = 0; i < MAX_GIC_NR; i++)
gic_resume_one(&gic_data[i]);
}
static struct syscore_ops gic_syscore_ops = {
.suspend = gic_suspend,
.resume = gic_resume,
};
static int __init gic_init_sys(void)
{
register_syscore_ops(&gic_syscore_ops);
return 0;
}
arch_initcall(gic_init_sys);
#endif
static void gic_eoi_irq(struct irq_data *d)
{
if (gic_arch_extn.irq_eoi) {
raw_spin_lock(&irq_controller_lock);
gic_arch_extn.irq_eoi(d);
raw_spin_unlock(&irq_controller_lock);
}
#ifdef CONFIG_ARCH_MSM8625
raw_spin_lock(&irq_controller_lock);
#endif
writel_relaxed(gic_irq(d), gic_cpu_base(d) + GIC_CPU_EOI);
#ifdef CONFIG_ARCH_MSM8625
raw_spin_unlock(&irq_controller_lock);
#endif
}
static int gic_set_type(struct irq_data *d, unsigned int type)
{
void __iomem *base = gic_dist_base(d);
unsigned int gicirq = gic_irq(d);
u32 enablemask = 1 << (gicirq % 32);
u32 enableoff = (gicirq / 32) * 4;
u32 confmask = 0x2 << ((gicirq % 16) * 2);
u32 confoff = (gicirq / 16) * 4;
bool enabled = false;
u32 val;
if (gicirq < 16)
return -EINVAL;
if (type != IRQ_TYPE_LEVEL_HIGH && type != IRQ_TYPE_EDGE_RISING)
return -EINVAL;
raw_spin_lock(&irq_controller_lock);
if (gic_arch_extn.irq_set_type)
gic_arch_extn.irq_set_type(d, type);
val = readl_relaxed(base + GIC_DIST_CONFIG + confoff);
if (type == IRQ_TYPE_LEVEL_HIGH)
val &= ~confmask;
else if (type == IRQ_TYPE_EDGE_RISING)
val |= confmask;
if (readl_relaxed(base + GIC_DIST_ENABLE_SET + enableoff) & enablemask) {
writel_relaxed(enablemask, base + GIC_DIST_ENABLE_CLEAR + enableoff);
enabled = true;
}
writel_relaxed(val, base + GIC_DIST_CONFIG + confoff);
if (enabled)
writel_relaxed(enablemask, base + GIC_DIST_ENABLE_SET + enableoff);
raw_spin_unlock(&irq_controller_lock);
return 0;
}
static int gic_retrigger(struct irq_data *d)
{
if (gic_arch_extn.irq_retrigger)
return gic_arch_extn.irq_retrigger(d);
return 0;
}
#ifdef CONFIG_SMP
static int gic_set_affinity(struct irq_data *d, const struct cpumask *mask_val,
bool force)
{
void __iomem *reg = gic_dist_base(d) + GIC_DIST_TARGET + (gic_irq(d) & ~3);
unsigned int shift = (gic_irq(d) % 4) * 8;
unsigned int cpu = cpumask_any_and(mask_val, cpu_online_mask);
u32 val, mask, bit;
if (cpu >= 8 || cpu >= nr_cpu_ids)
return -EINVAL;
mask = 0xff << shift;
bit = 1 << (cpu_logical_map(cpu) + shift);
raw_spin_lock(&irq_controller_lock);
val = readl_relaxed(reg) & ~mask;
writel_relaxed(val | bit, reg);
raw_spin_unlock(&irq_controller_lock);
return IRQ_SET_MASK_OK;
}
#endif
#ifdef CONFIG_PM
static int gic_set_wake(struct irq_data *d, unsigned int on)
{
int ret = -ENXIO;
unsigned int reg_offset, bit_offset;
unsigned int gicirq = gic_irq(d);
struct gic_chip_data *gic_data = irq_data_get_irq_chip_data(d);
WARN_ON(gicirq < 32);
reg_offset = gicirq / 32;
bit_offset = gicirq % 32;
if (on)
gic_data->wakeup_irqs[reg_offset] |= 1 << bit_offset;
else
gic_data->wakeup_irqs[reg_offset] &= ~(1 << bit_offset);
if (gic_arch_extn.irq_set_wake)
ret = gic_arch_extn.irq_set_wake(d, on);
return ret;
}
#else
#define gic_set_wake NULL
#endif
asmlinkage void __exception_irq_entry gic_handle_irq(struct pt_regs *regs)
{
u32 irqstat, irqnr;
struct gic_chip_data *gic = &gic_data[0];
void __iomem *cpu_base = gic_data_cpu_base(gic);
do {
#ifdef CONFIG_ARCH_MSM8625
raw_spin_lock(&irq_controller_lock);
#endif
irqstat = readl_relaxed(cpu_base + GIC_CPU_INTACK);
#ifdef CONFIG_ARCH_MSM8625
raw_spin_unlock(&irq_controller_lock);
#endif
irqnr = irqstat & ~0x1c00;
if (likely(irqnr > 15 && irqnr < 1021)) {
uncached_logk_pc(LOGK_IRQ,
(void *)get_current_timestamp(),
(void *)irqnr);
irqnr = irq_find_mapping(gic->domain, irqnr);
handle_IRQ(irqnr, regs);
continue;
}
if (irqnr < 16) {
uncached_logk(LOGK_IRQ, (void *)irqnr);
#ifdef CONFIG_ARCH_MSM8625
raw_spin_lock(&irq_controller_lock);
#endif
writel_relaxed(irqstat, cpu_base + GIC_CPU_EOI);
#ifdef CONFIG_ARCH_MSM8625
raw_spin_unlock(&irq_controller_lock);
#endif
#ifdef CONFIG_SMP
handle_IPI(irqnr, regs);
#endif
continue;
}
break;
} while (1);
}
static void gic_handle_cascade_irq(unsigned int irq, struct irq_desc *desc)
{
struct gic_chip_data *chip_data = irq_get_handler_data(irq);
struct irq_chip *chip = irq_get_chip(irq);
unsigned int cascade_irq, gic_irq;
unsigned long status;
chained_irq_enter(chip, desc);
raw_spin_lock(&irq_controller_lock);
status = readl_relaxed(gic_data_cpu_base(chip_data) + GIC_CPU_INTACK);
raw_spin_unlock(&irq_controller_lock);
gic_irq = (status & 0x3ff);
if (gic_irq == 1023)
goto out;
cascade_irq = irq_find_mapping(chip_data->domain, gic_irq);
if (unlikely(gic_irq < 32 || gic_irq > 1020))
do_bad_IRQ(cascade_irq, desc);
else
generic_handle_irq(cascade_irq);
out:
chained_irq_exit(chip, desc);
}
static struct irq_chip gic_chip = {
.name = "GIC",
.irq_mask = gic_mask_irq,
.irq_unmask = gic_unmask_irq,
.irq_eoi = gic_eoi_irq,
.irq_set_type = gic_set_type,
.irq_retrigger = gic_retrigger,
#ifdef CONFIG_SMP
.irq_set_affinity = gic_set_affinity,
#endif
.irq_disable = gic_disable_irq,
.irq_set_wake = gic_set_wake,
};
void __init gic_cascade_irq(unsigned int gic_nr, unsigned int irq)
{
if (gic_nr >= MAX_GIC_NR)
BUG();
if (irq_set_handler_data(irq, &gic_data[gic_nr]) != 0)
BUG();
irq_set_chained_handler(irq, gic_handle_cascade_irq);
}
static void __init gic_dist_init(struct gic_chip_data *gic)
{
unsigned int i;
u32 cpumask;
unsigned int gic_irqs = gic->gic_irqs;
void __iomem *base = gic_data_dist_base(gic);
u32 cpu = cpu_logical_map(smp_processor_id());
cpumask = 1 << cpu;
cpumask |= cpumask << 8;
cpumask |= cpumask << 16;
writel_relaxed(0, base + GIC_DIST_CTRL);
for (i = 32; i < gic_irqs; i += 16)
writel_relaxed(0, base + GIC_DIST_CONFIG + i * 4 / 16);
for (i = 32; i < gic_irqs; i += 4)
writel_relaxed(cpumask, base + GIC_DIST_TARGET + i * 4 / 4);
if (is_cpu_secure())
for (i = 32; i < gic_irqs; i += 32)
writel_relaxed(0xFFFFFFFF,
base + GIC_DIST_ISR + i * 4 / 32);
for (i = 32; i < gic_irqs; i += 4)
writel_relaxed(0xa0a0a0a0, base + GIC_DIST_PRI + i * 4 / 4);
for (i = 32; i < gic_irqs; i += 32)
writel_relaxed(0xffffffff, base + GIC_DIST_ENABLE_CLEAR + i * 4 / 32);
gic->max_irq = gic_irqs;
if (is_cpu_secure())
writel_relaxed(3, base + GIC_DIST_CTRL);
else
writel_relaxed(1, base + GIC_DIST_CTRL);
mb();
}
static void __cpuinit gic_cpu_init(struct gic_chip_data *gic)
{
void __iomem *dist_base = gic_data_dist_base(gic);
void __iomem *base = gic_data_cpu_base(gic);
int i;
#ifdef CONFIG_ARCH_MSM8625
raw_spin_lock(&irq_controller_lock);
#endif
writel_relaxed(0xffff0000, dist_base + GIC_DIST_ENABLE_CLEAR);
writel_relaxed(0x0000ffff, dist_base + GIC_DIST_ENABLE_SET);
if (is_cpu_secure())
writel_relaxed(0xFFFFFFFF, dist_base + GIC_DIST_ISR);
for (i = 0; i < 32; i += 4)
writel_relaxed(0xa0a0a0a0, dist_base + GIC_DIST_PRI + i * 4 / 4);
writel_relaxed(0xf0, base + GIC_CPU_PRIMASK);
if (is_cpu_secure())
writel_relaxed(0xF, base + GIC_CPU_CTRL);
else
writel_relaxed(1, base + GIC_CPU_CTRL);
#ifdef CONFIG_ARCH_MSM8625
raw_spin_unlock(&irq_controller_lock);
#endif
mb();
}
#ifdef CONFIG_CPU_PM
static void gic_dist_save(unsigned int gic_nr)
{
unsigned int gic_irqs;
void __iomem *dist_base;
int i;
if (gic_nr >= MAX_GIC_NR)
BUG();
gic_irqs = gic_data[gic_nr].gic_irqs;
dist_base = gic_data_dist_base(&gic_data[gic_nr]);
if (!dist_base)
return;
saved_dist_ctrl = readl_relaxed(dist_base + GIC_DIST_CTRL);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 16); i++)
gic_data[gic_nr].saved_spi_conf[i] =
readl_relaxed(dist_base + GIC_DIST_CONFIG + i * 4);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 4); i++)
gic_data[gic_nr].saved_spi_target[i] =
readl_relaxed(dist_base + GIC_DIST_TARGET + i * 4);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 4); i++)
gic_data[gic_nr].saved_dist_pri[i] =
readl_relaxed(dist_base + GIC_DIST_PRI + i * 4);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 32); i++)
gic_data[gic_nr].saved_spi_enable[i] =
readl_relaxed(dist_base + GIC_DIST_ENABLE_SET + i * 4);
}
static void gic_dist_restore(unsigned int gic_nr)
{
unsigned int gic_irqs;
unsigned int i;
void __iomem *dist_base;
if (gic_nr >= MAX_GIC_NR)
BUG();
gic_irqs = gic_data[gic_nr].gic_irqs;
dist_base = gic_data_dist_base(&gic_data[gic_nr]);
if (!dist_base)
return;
writel_relaxed(0, dist_base + GIC_DIST_CTRL);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 16); i++)
writel_relaxed(gic_data[gic_nr].saved_spi_conf[i],
dist_base + GIC_DIST_CONFIG + i * 4);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 4); i++)
writel_relaxed(gic_data[gic_nr].saved_dist_pri[i],
dist_base + GIC_DIST_PRI + i * 4);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 4); i++)
writel_relaxed(gic_data[gic_nr].saved_spi_target[i],
dist_base + GIC_DIST_TARGET + i * 4);
for (i = 0; i < DIV_ROUND_UP(gic_irqs, 32); i++)
writel_relaxed(gic_data[gic_nr].saved_spi_enable[i],
dist_base + GIC_DIST_ENABLE_SET + i * 4);
writel_relaxed(saved_dist_ctrl, dist_base + GIC_DIST_CTRL);
}
static void gic_cpu_save(unsigned int gic_nr)
{
int i;
u32 *ptr;
void __iomem *dist_base;
void __iomem *cpu_base;
if (gic_nr >= MAX_GIC_NR)
BUG();
dist_base = gic_data_dist_base(&gic_data[gic_nr]);
cpu_base = gic_data_cpu_base(&gic_data[gic_nr]);
if (!dist_base || !cpu_base)
return;
saved_cpu_ctrl = readl_relaxed(cpu_base + GIC_CPU_CTRL);
for (i = 0; i < DIV_ROUND_UP(32, 4); i++)
gic_data[gic_nr].saved_dist_pri[i] = readl_relaxed(dist_base +
GIC_DIST_PRI + i * 4);
ptr = __this_cpu_ptr(gic_data[gic_nr].saved_ppi_enable);
for (i = 0; i < DIV_ROUND_UP(32, 32); i++)
ptr[i] = readl_relaxed(dist_base + GIC_DIST_ENABLE_SET + i * 4);
ptr = __this_cpu_ptr(gic_data[gic_nr].saved_ppi_conf);
for (i = 0; i < DIV_ROUND_UP(32, 16); i++)
ptr[i] = readl_relaxed(dist_base + GIC_DIST_CONFIG + i * 4);
}
static void gic_cpu_restore(unsigned int gic_nr)
{
int i;
u32 *ptr;
void __iomem *dist_base;
void __iomem *cpu_base;
if (gic_nr >= MAX_GIC_NR)
BUG();
dist_base = gic_data_dist_base(&gic_data[gic_nr]);
cpu_base = gic_data_cpu_base(&gic_data[gic_nr]);
if (!dist_base || !cpu_base)
return;
ptr = __this_cpu_ptr(gic_data[gic_nr].saved_ppi_enable);
for (i = 0; i < DIV_ROUND_UP(32, 32); i++)
writel_relaxed(ptr[i], dist_base + GIC_DIST_ENABLE_SET + i * 4);
ptr = __this_cpu_ptr(gic_data[gic_nr].saved_ppi_conf);
for (i = 0; i < DIV_ROUND_UP(32, 16); i++)
writel_relaxed(ptr[i], dist_base + GIC_DIST_CONFIG + i * 4);
for (i = 0; i < DIV_ROUND_UP(32, 4); i++)
writel_relaxed(gic_data[gic_nr].saved_dist_pri[i],
dist_base + GIC_DIST_PRI + i * 4);
writel_relaxed(0xf0, cpu_base + GIC_CPU_PRIMASK);
writel_relaxed(saved_cpu_ctrl, cpu_base + GIC_CPU_CTRL);
}
static int gic_notifier(struct notifier_block *self, unsigned long cmd, void *v)
{
int i;
for (i = 0; i < MAX_GIC_NR; i++) {
#ifdef CONFIG_GIC_NON_BANKED
if (!gic_data[i].get_base)
continue;
#endif
switch (cmd) {
case CPU_PM_ENTER:
gic_cpu_save(i);
break;
case CPU_PM_ENTER_FAILED:
case CPU_PM_EXIT:
gic_cpu_restore(i);
break;
case CPU_CLUSTER_PM_ENTER:
gic_dist_save(i);
break;
case CPU_CLUSTER_PM_ENTER_FAILED:
case CPU_CLUSTER_PM_EXIT:
gic_dist_restore(i);
break;
}
}
return NOTIFY_OK;
}
static struct notifier_block gic_notifier_block = {
.notifier_call = gic_notifier,
};
static void __init gic_pm_init(struct gic_chip_data *gic)
{
gic->saved_ppi_enable = __alloc_percpu(DIV_ROUND_UP(32, 32) * 4,
sizeof(u32));
BUG_ON(!gic->saved_ppi_enable);
gic->saved_ppi_conf = __alloc_percpu(DIV_ROUND_UP(32, 16) * 4,
sizeof(u32));
BUG_ON(!gic->saved_ppi_conf);
if (gic == &gic_data[0])
cpu_pm_register_notifier(&gic_notifier_block);
}
#else
static void __init gic_pm_init(struct gic_chip_data *gic)
{
}
static void gic_cpu_restore(unsigned int gic_nr)
{
}
static void gic_cpu_save(unsigned int gic_nr)
{
}
static void gic_dist_restore(unsigned int gic_nr)
{
}
static void gic_dist_save(unsigned int gic_nr)
{
}
#endif
static int gic_irq_domain_map(struct irq_domain *d, unsigned int irq,
irq_hw_number_t hw)
{
if (hw < 32) {
irq_set_percpu_devid(irq);
irq_set_chip_and_handler(irq, &gic_chip,
handle_percpu_devid_irq);
set_irq_flags(irq, IRQF_VALID | IRQF_NOAUTOEN);
} else {
irq_set_chip_and_handler(irq, &gic_chip,
handle_fasteoi_irq);
set_irq_flags(irq, IRQF_VALID | IRQF_PROBE);
}
irq_set_chip_data(irq, d->host_data);
return 0;
}
static int gic_irq_domain_xlate(struct irq_domain *d,
struct device_node *controller,
const u32 *intspec, unsigned int intsize,
unsigned long *out_hwirq, unsigned int *out_type)
{
if (d->of_node != controller)
return -EINVAL;
if (intsize < 3)
return -EINVAL;
*out_hwirq = intspec[1] + 16;
if (!intspec[0])
*out_hwirq += 16;
*out_type = intspec[2] & IRQ_TYPE_SENSE_MASK;
return 0;
}
const struct irq_domain_ops gic_irq_domain_ops = {
.map = gic_irq_domain_map,
.xlate = gic_irq_domain_xlate,
};
void __init gic_init_bases(unsigned int gic_nr, int irq_start,
void __iomem *dist_base, void __iomem *cpu_base,
u32 percpu_offset, struct device_node *node)
{
irq_hw_number_t hwirq_base;
struct gic_chip_data *gic;
int gic_irqs, irq_base;
BUG_ON(gic_nr >= MAX_GIC_NR);
#ifdef CONFIG_TRACING_SPINLOCK
spin_locking_flag = MSM_SPIN_LOCK_IRQSAVE_INFO_BASE;
#endif
#ifdef CONFIG_TRACING_WORKQUEUE_HISTORY
wq_history_flag = MSM_WQ_INFO_BASE;
#endif
gic = &gic_data[gic_nr];
#ifdef CONFIG_GIC_NON_BANKED
if (percpu_offset) {
unsigned int cpu;
gic->dist_base.percpu_base = alloc_percpu(void __iomem *);
gic->cpu_base.percpu_base = alloc_percpu(void __iomem *);
if (WARN_ON(!gic->dist_base.percpu_base ||
!gic->cpu_base.percpu_base)) {
free_percpu(gic->dist_base.percpu_base);
free_percpu(gic->cpu_base.percpu_base);
return;
}
for_each_possible_cpu(cpu) {
unsigned long offset = percpu_offset * cpu_logical_map(cpu);
*per_cpu_ptr(gic->dist_base.percpu_base, cpu) = dist_base + offset;
*per_cpu_ptr(gic->cpu_base.percpu_base, cpu) = cpu_base + offset;
}
gic_set_base_accessor(gic, gic_get_percpu_base);
} else
#endif
{
WARN(percpu_offset,
"GIC_NON_BANKED not enabled, ignoring %08x offset!",
percpu_offset);
gic->dist_base.common_base = dist_base;
gic->cpu_base.common_base = cpu_base;
gic_set_base_accessor(gic, gic_get_common_base);
}
if (gic_nr == 0 && (irq_start & 31) > 0) {
hwirq_base = 16;
if (irq_start != -1)
irq_start = (irq_start & ~31) + 16;
} else {
hwirq_base = 32;
}
gic_irqs = readl_relaxed(gic_data_dist_base(gic) + GIC_DIST_CTR) & 0x1f;
gic_irqs = (gic_irqs + 1) * 32;
if (gic_irqs > 1020)
gic_irqs = 1020;
gic->gic_irqs = gic_irqs;
gic_irqs -= hwirq_base;
irq_base = irq_alloc_descs(irq_start, 16, gic_irqs, numa_node_id());
if (IS_ERR_VALUE(irq_base)) {
WARN(1, "Cannot allocate irq_descs @ IRQ%d, assuming pre-allocated\n",
irq_start);
irq_base = irq_start;
}
gic->domain = irq_domain_add_legacy(node, gic_irqs, irq_base,
hwirq_base, &gic_irq_domain_ops, gic);
if (WARN_ON(!gic->domain))
return;
gic_chip.flags |= gic_arch_extn.flags;
gic_dist_init(gic);
gic_cpu_init(gic);
gic_pm_init(gic);
}
void __cpuinit gic_secondary_init(unsigned int gic_nr)
{
BUG_ON(gic_nr >= MAX_GIC_NR);
gic_cpu_init(&gic_data[gic_nr]);
}
#ifdef CONFIG_SMP
void gic_raise_softirq(const struct cpumask *mask, unsigned int irq)
{
int cpu;
unsigned long sgir;
unsigned long map = 0;
#ifdef CONFIG_ARCH_MSM8625
unsigned long flags;
#endif
for_each_cpu(cpu, mask)
map |= 1 << cpu_logical_map(cpu);
sgir = (map << 16) | irq;
if (is_cpu_secure())
sgir |= (1 << 15);
dsb();
#ifdef CONFIG_ARCH_MSM8625
raw_spin_lock_irqsave(&irq_controller_lock, flags);
#endif
writel_relaxed(sgir,
gic_data_dist_base(&gic_data[0]) + GIC_DIST_SOFTINT);
#ifdef CONFIG_ARCH_MSM8625
raw_spin_unlock_irqrestore(&irq_controller_lock, flags);
#endif
mb();
}
#endif
void gic_set_irq_secure(unsigned int irq)
{
unsigned int gicd_isr_reg, gicd_pri_reg;
unsigned int mask = 0xFFFFFF00;
struct gic_chip_data *gic_data = &gic_data[0];
struct irq_data *d = irq_get_irq_data(irq);
if (is_cpu_secure()) {
raw_spin_lock(&irq_controller_lock);
gicd_isr_reg = readl_relaxed(gic_dist_base(d) +
GIC_DIST_ISR + gic_irq(d) / 32 * 4);
gicd_isr_reg &= ~BIT(gic_irq(d) % 32);
writel_relaxed(gicd_isr_reg, gic_dist_base(d) +
GIC_DIST_ISR + gic_irq(d) / 32 * 4);
gicd_pri_reg = readl_relaxed(gic_dist_base(d) +
GIC_DIST_PRI + (gic_irq(d) * 4 / 4));
gicd_pri_reg &= mask;
gicd_pri_reg |= 0x80;
writel_relaxed(gicd_pri_reg, gic_dist_base(d) + GIC_DIST_PRI +
gic_irq(d) * 4 / 4);
mb();
raw_spin_unlock(&irq_controller_lock);
} else {
WARN(1, "Trying to run secure operation from Non-secure mode");
}
}
#ifdef CONFIG_OF
static int gic_cnt __initdata = 0;
int __init gic_of_init(struct device_node *node, struct device_node *parent)
{
void __iomem *cpu_base;
void __iomem *dist_base;
u32 percpu_offset;
int irq;
if (WARN_ON(!node))
return -ENODEV;
dist_base = of_iomap(node, 0);
WARN(!dist_base, "unable to map gic dist registers\n");
cpu_base = of_iomap(node, 1);
WARN(!cpu_base, "unable to map gic cpu registers\n");
if (of_property_read_u32(node, "cpu-offset", &percpu_offset))
percpu_offset = 0;
gic_init_bases(gic_cnt, -1, dist_base, cpu_base, percpu_offset, node);
if (parent) {
irq = irq_of_parse_and_map(node, 0);
gic_cascade_irq(gic_cnt, irq);
}
gic_cnt++;
return 0;
}
#endif
bool gic_is_irq_pending(unsigned int irq)
{
struct irq_data *d = irq_get_irq_data(irq);
struct gic_chip_data *gic_data = &gic_data[0];
u32 mask, val;
WARN_ON(!irqs_disabled());
raw_spin_lock(&irq_controller_lock);
mask = 1 << (gic_irq(d) % 32);
val = readl(gic_dist_base(d) +
GIC_DIST_ENABLE_SET + (gic_irq(d) / 32) * 4);
WARN_ON(val & mask);
val = readl(gic_dist_base(d) +
GIC_DIST_PENDING_SET + (gic_irq(d) / 32) * 4);
raw_spin_unlock(&irq_controller_lock);
return (bool) (val & mask);
}
void gic_clear_irq_pending(unsigned int irq)
{
struct gic_chip_data *gic_data = &gic_data[0];
struct irq_data *d = irq_get_irq_data(irq);
u32 mask, val;
WARN_ON(!irqs_disabled());
raw_spin_lock(&irq_controller_lock);
mask = 1 << (gic_irq(d) % 32);
val = readl(gic_dist_base(d) +
GIC_DIST_ENABLE_SET + (gic_irq(d) / 32) * 4);
WARN_ON(val & mask);
writel(mask, gic_dist_base(d) +
GIC_DIST_PENDING_CLEAR + (gic_irq(d) / 32) * 4);
raw_spin_unlock(&irq_controller_lock);
}
#ifdef CONFIG_ARCH_MSM8625
unsigned int msm_gic_spi_ppi_pending(void)
{
unsigned int i, bit = 0;
unsigned int pending_enb = 0, pending = 0;
unsigned long value = 0;
struct gic_chip_data *gic = &gic_data[0];
void __iomem *base = gic_data_dist_base(gic);
unsigned long flags;
raw_spin_lock_irqsave(&irq_controller_lock, flags);
for (i = 0; (i * 32) < gic->max_irq; i++) {
pending = readl_relaxed(base +
GIC_DIST_PENDING_SET + i * 4);
pending_enb = readl_relaxed(base +
GIC_DIST_ENABLE_SET + i * 4);
value = pending & pending_enb;
if (value) {
for (bit = 0; bit < 32; bit++) {
bit = find_next_bit(&value, 32, bit);
if ((bit + 32 * i) != MSM8625_INT_A9_M2A_5) {
raw_spin_unlock_irqrestore(
&irq_controller_lock, flags);
return 1;
}
}
}
}
raw_spin_unlock_irqrestore(&irq_controller_lock, flags);
return 0;
}
#endif
void msm_gic_save(bool modem_wake, int from_idle)
{
unsigned int i;
struct gic_chip_data *gic = &gic_data[0];
void __iomem *base = gic_data_dist_base(gic);
gic_cpu_save(0);
gic_dist_save(0);
for (i = 0; (i * 32) < gic->max_irq; i++) {
raw_spin_lock(&irq_controller_lock);
writel_relaxed(0xffffffff, base
+ GIC_DIST_ENABLE_CLEAR + i * 4);
raw_spin_unlock(&irq_controller_lock);
}
}
void msm_gic_restore(void)
{
gic_dist_restore(0);
gic_cpu_restore(0);
}
void core1_gic_configure_and_raise(void)
{
struct gic_chip_data *gic = &gic_data[0];
void __iomem *base = gic_data_dist_base(gic);
unsigned int value = 0;
unsigned long flags;
raw_spin_lock_irqsave(&irq_controller_lock, flags);
value = __raw_readl(base + GIC_DIST_ACTIVE_BIT + 0x4);
value |= BIT(8);
__raw_writel(value, base + GIC_DIST_ACTIVE_BIT + 0x4);
mb();
value = __raw_readl(base + GIC_DIST_TARGET + 0x24);
value |= BIT(13);
__raw_writel(value, base + GIC_DIST_TARGET + 0x24);
mb();
value = __raw_readl(base + GIC_DIST_TARGET + 0x28);
value |= BIT(1);
__raw_writel(value, base + GIC_DIST_TARGET + 0x28);
mb();
value = __raw_readl(base + GIC_DIST_ENABLE_SET + 0x4);
value |= BIT(8);
__raw_writel(value, base + GIC_DIST_ENABLE_SET + 0x4);
mb();
value = __raw_readl(base + GIC_DIST_PENDING_SET + 0x4);
value |= BIT(8);
__raw_writel(value, base + GIC_DIST_PENDING_SET + 0x4);
mb();
raw_spin_unlock_irqrestore(&irq_controller_lock, flags);
}
| gpl-2.0 |
gdetal/kernel_msm_mptcp | drivers/coresight/coresight-stm.c | 31 | 18079 | /* Copyright (c) 2012, 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/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/of_coresight.h>
#include <linux/coresight.h>
#include <linux/coresight-stm.h>
#include <asm/unaligned.h>
#include "coresight-priv.h"
#define stm_writel(drvdata, val, off) __raw_writel((val), drvdata->base + off)
#define stm_readl(drvdata, off) __raw_readl(drvdata->base + off)
#define STM_LOCK(drvdata) \
do { \
mb(); \
stm_writel(drvdata, 0x0, CORESIGHT_LAR); \
} while (0)
#define STM_UNLOCK(drvdata) \
do { \
stm_writel(drvdata, CORESIGHT_UNLOCK, CORESIGHT_LAR); \
mb(); \
} while (0)
#define STMDMASTARTR (0xC04)
#define STMDMASTOPR (0xC08)
#define STMDMASTATR (0xC0C)
#define STMDMACTLR (0xC10)
#define STMDMAIDR (0xCFC)
#define STMHEER (0xD00)
#define STMHETER (0xD20)
#define STMHEMCR (0xD64)
#define STMHEMASTR (0xDF4)
#define STMHEFEAT1R (0xDF8)
#define STMHEIDR (0xDFC)
#define STMSPER (0xE00)
#define STMSPTER (0xE20)
#define STMSPSCR (0xE60)
#define STMSPMSCR (0xE64)
#define STMSPOVERRIDER (0xE68)
#define STMSPMOVERRIDER (0xE6C)
#define STMSPTRIGCSR (0xE70)
#define STMTCSR (0xE80)
#define STMTSSTIMR (0xE84)
#define STMTSFREQR (0xE8C)
#define STMSYNCR (0xE90)
#define STMAUXCR (0xE94)
#define STMSPFEAT1R (0xEA0)
#define STMSPFEAT2R (0xEA4)
#define STMSPFEAT3R (0xEA8)
#define STMITTRIGGER (0xEE8)
#define STMITATBDATA0 (0xEEC)
#define STMITATBCTR2 (0xEF0)
#define STMITATBID (0xEF4)
#define STMITATBCTR0 (0xEF8)
#define NR_STM_CHANNEL (32)
#define BYTES_PER_CHANNEL (256)
#define STM_TRACE_BUF_SIZE (1024)
#define OST_START_TOKEN (0x30)
#define OST_VERSION (0x1)
enum stm_pkt_type {
STM_PKT_TYPE_DATA = 0x98,
STM_PKT_TYPE_FLAG = 0xE8,
STM_PKT_TYPE_TRIG = 0xF8,
};
enum {
STM_OPTION_MARKED = 0x10,
};
#define stm_channel_addr(drvdata, ch) (drvdata->chs.base + \
(ch * BYTES_PER_CHANNEL))
#define stm_channel_off(type, opts) (type & ~opts)
#ifdef CONFIG_MSM_QDSS_STM_DEFAULT_ENABLE
static int boot_enable = 1;
#else
static int boot_enable;
#endif
module_param_named(
boot_enable, boot_enable, int, S_IRUGO
);
static int boot_nr_channel;
module_param_named(
boot_nr_channel, boot_nr_channel, int, S_IRUGO
);
struct channel_space {
void __iomem *base;
unsigned long *bitmap;
};
struct stm_drvdata {
void __iomem *base;
struct device *dev;
struct coresight_device *csdev;
struct miscdevice miscdev;
struct clk *clk;
spinlock_t spinlock;
struct channel_space chs;
bool enable;
uint32_t entity;
};
static struct stm_drvdata *stmdrvdata;
static int stm_hwevent_isenable(struct stm_drvdata *drvdata)
{
int ret = 0;
spin_lock(&drvdata->spinlock);
if (drvdata->enable)
if (BVAL(stm_readl(drvdata, STMHEMCR), 0))
ret = stm_readl(drvdata, STMHEER) == 0 ? 0 : 1;
spin_unlock(&drvdata->spinlock);
return ret;
}
static void __stm_hwevent_enable(struct stm_drvdata *drvdata)
{
STM_UNLOCK(drvdata);
stm_writel(drvdata, 0x0, STMHETER);
stm_writel(drvdata, 0xFFFFFFFF, STMHEER);
stm_writel(drvdata, 0x5, STMHEMCR);
STM_LOCK(drvdata);
}
static int stm_hwevent_enable(struct stm_drvdata *drvdata)
{
int ret = 0;
spin_lock(&drvdata->spinlock);
if (drvdata->enable)
__stm_hwevent_enable(drvdata);
else
ret = -EINVAL;
spin_unlock(&drvdata->spinlock);
return ret;
}
static int stm_port_isenable(struct stm_drvdata *drvdata)
{
int ret = 0;
spin_lock(&drvdata->spinlock);
if (drvdata->enable)
ret = stm_readl(drvdata, STMSPER) == 0 ? 0 : 1;
spin_unlock(&drvdata->spinlock);
return ret;
}
static void __stm_port_enable(struct stm_drvdata *drvdata)
{
STM_UNLOCK(drvdata);
stm_writel(drvdata, 0xFFFFFFFF, STMSPTER);
stm_writel(drvdata, 0xFFFFFFFF, STMSPER);
STM_LOCK(drvdata);
}
static int stm_port_enable(struct stm_drvdata *drvdata)
{
int ret = 0;
spin_lock(&drvdata->spinlock);
if (drvdata->enable)
__stm_port_enable(drvdata);
else
ret = -EINVAL;
spin_unlock(&drvdata->spinlock);
return ret;
}
static void __stm_enable(struct stm_drvdata *drvdata)
{
__stm_hwevent_enable(drvdata);
__stm_port_enable(drvdata);
STM_UNLOCK(drvdata);
stm_writel(drvdata, 0x80, STMSYNCR);
/* SYNCEN is read-only and HWTEN is not implemented */
stm_writel(drvdata, 0x30003, STMTCSR);
STM_LOCK(drvdata);
}
static int stm_enable(struct coresight_device *csdev)
{
struct stm_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
int ret;
ret = clk_prepare_enable(drvdata->clk);
if (ret)
return ret;
spin_lock(&drvdata->spinlock);
__stm_enable(drvdata);
drvdata->enable = true;
spin_unlock(&drvdata->spinlock);
dev_info(drvdata->dev, "STM tracing enabled\n");
return 0;
}
static void __stm_hwevent_disable(struct stm_drvdata *drvdata)
{
STM_UNLOCK(drvdata);
stm_writel(drvdata, 0x0, STMHETER);
stm_writel(drvdata, 0x0, STMHEER);
stm_writel(drvdata, 0x0, STMHEMCR);
STM_LOCK(drvdata);
}
static void stm_hwevent_disable(struct stm_drvdata *drvdata)
{
spin_lock(&drvdata->spinlock);
if (drvdata->enable)
__stm_hwevent_disable(drvdata);
spin_unlock(&drvdata->spinlock);
}
static void __stm_port_disable(struct stm_drvdata *drvdata)
{
STM_UNLOCK(drvdata);
stm_writel(drvdata, 0x0, STMSPER);
stm_writel(drvdata, 0x0, STMSPTER);
STM_LOCK(drvdata);
}
static void stm_port_disable(struct stm_drvdata *drvdata)
{
spin_lock(&drvdata->spinlock);
if (drvdata->enable)
__stm_port_disable(drvdata);
spin_unlock(&drvdata->spinlock);
}
static void __stm_disable(struct stm_drvdata *drvdata)
{
STM_UNLOCK(drvdata);
stm_writel(drvdata, 0x30000, STMTCSR);
STM_LOCK(drvdata);
__stm_hwevent_disable(drvdata);
__stm_port_disable(drvdata);
}
static void stm_disable(struct coresight_device *csdev)
{
struct stm_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
spin_lock(&drvdata->spinlock);
__stm_disable(drvdata);
drvdata->enable = false;
spin_unlock(&drvdata->spinlock);
/* Wait for 100ms so that pending data has been written to HW */
msleep(100);
clk_disable_unprepare(drvdata->clk);
dev_info(drvdata->dev, "STM tracing disabled\n");
}
static const struct coresight_ops_source stm_source_ops = {
.enable = stm_enable,
.disable = stm_disable,
};
static const struct coresight_ops stm_cs_ops = {
.source_ops = &stm_source_ops,
};
static uint32_t stm_channel_alloc(uint32_t off)
{
struct stm_drvdata *drvdata = stmdrvdata;
uint32_t ch;
do {
ch = find_next_zero_bit(drvdata->chs.bitmap,
NR_STM_CHANNEL, off);
} while ((ch < NR_STM_CHANNEL) &&
test_and_set_bit(ch, drvdata->chs.bitmap));
return ch;
}
static void stm_channel_free(uint32_t ch)
{
struct stm_drvdata *drvdata = stmdrvdata;
clear_bit(ch, drvdata->chs.bitmap);
}
static int stm_send(void *addr, const void *data, uint32_t size)
{
uint64_t prepad = 0;
uint64_t postpad = 0;
char *pad;
uint8_t off, endoff;
uint32_t len = size;
/* only 64bit writes are supported, we rely on the compiler to
* generate STRD instruction for the casted 64bit assignments
*/
off = (unsigned long)data & 0x7;
if (off) {
endoff = 8 - off;
pad = (char *)&prepad;
pad += off;
while (endoff && size) {
*pad++ = *(char *)data++;
endoff--;
size--;
}
*(volatile uint64_t __force *)addr = prepad;
}
/* now we are 64bit aligned */
while (size >= 8) {
*(volatile uint64_t __force *)addr = *(uint64_t *)data;
data += 8;
size -= 8;
}
if (size) {
pad = (char *)&postpad;
while (size) {
*pad++ = *(char *)data++;
size--;
}
*(volatile uint64_t __force *)addr = postpad;
}
return roundup(len + off, 8);
}
static int stm_trace_ost_header(unsigned long ch_addr, uint32_t options,
uint8_t entity_id, uint8_t proto_id,
const void *payload_data, uint32_t payload_size)
{
void *addr;
uint8_t prepad_size;
uint64_t header;
char *hdr;
hdr = (char *)&header;
hdr[0] = OST_START_TOKEN;
hdr[1] = OST_VERSION;
hdr[2] = entity_id;
hdr[3] = proto_id;
prepad_size = (unsigned long)payload_data & 0x7;
*(uint32_t *)(hdr + 4) = (prepad_size << 24) | payload_size;
/* for 64bit writes, header is expected to be of the D32M, D32M */
options |= STM_OPTION_MARKED;
options &= ~STM_OPTION_TIMESTAMPED;
addr = (void *)(ch_addr | stm_channel_off(STM_PKT_TYPE_DATA, options));
return stm_send(addr, &header, sizeof(header));
}
static int stm_trace_data(unsigned long ch_addr, uint32_t options,
const void *data, uint32_t size)
{
void *addr;
options &= ~STM_OPTION_TIMESTAMPED;
addr = (void *)(ch_addr | stm_channel_off(STM_PKT_TYPE_DATA, options));
return stm_send(addr, data, size);
}
static int stm_trace_ost_tail(unsigned long ch_addr, uint32_t options)
{
void *addr;
uint64_t tail = 0x0;
addr = (void *)(ch_addr | stm_channel_off(STM_PKT_TYPE_FLAG, options));
return stm_send(addr, &tail, sizeof(tail));
}
static inline int __stm_trace(uint32_t options, uint8_t entity_id,
uint8_t proto_id, const void *data, uint32_t size)
{
struct stm_drvdata *drvdata = stmdrvdata;
int len = 0;
uint32_t ch;
unsigned long ch_addr;
/* allocate channel and get the channel address */
ch = stm_channel_alloc(0);
ch_addr = (unsigned long)stm_channel_addr(drvdata, ch);
/* send the ost header */
len += stm_trace_ost_header(ch_addr, options, entity_id, proto_id, data,
size);
/* send the payload data */
len += stm_trace_data(ch_addr, options, data, size);
/* send the ost tail */
len += stm_trace_ost_tail(ch_addr, options);
/* we are done, free the channel */
stm_channel_free(ch);
return len;
}
/**
* stm_trace - trace the binary or string data through STM
* @options: tracing options - guaranteed, timestamped, etc
* @entity_id: entity representing the trace data
* @proto_id: protocol id to distinguish between different binary formats
* @data: pointer to binary or string data buffer
* @size: size of data to send
*
* Packetizes the data as the payload to an OST packet and sends it over STM
*
* CONTEXT:
* Can be called from any context.
*
* RETURNS:
* number of bytes transfered over STM
*/
int stm_trace(uint32_t options, uint8_t entity_id, uint8_t proto_id,
const void *data, uint32_t size)
{
struct stm_drvdata *drvdata = stmdrvdata;
/* we don't support sizes more than 24bits (0 to 23) */
if (!(drvdata && drvdata->enable && (drvdata->entity & entity_id) &&
(size < 0x1000000)))
return 0;
return __stm_trace(options, entity_id, proto_id, data, size);
}
EXPORT_SYMBOL_GPL(stm_trace);
static ssize_t stm_write(struct file *file, const char __user *data,
size_t size, loff_t *ppos)
{
struct stm_drvdata *drvdata = container_of(file->private_data,
struct stm_drvdata, miscdev);
char *buf;
if (!drvdata->enable)
return -EINVAL;
if (!(drvdata->entity & OST_ENTITY_DEV_NODE))
return size;
if (size > STM_TRACE_BUF_SIZE)
size = STM_TRACE_BUF_SIZE;
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (copy_from_user(buf, data, size)) {
kfree(buf);
dev_dbg(drvdata->dev, "%s: copy_from_user failed\n", __func__);
return -EFAULT;
}
__stm_trace(STM_OPTION_TIMESTAMPED, OST_ENTITY_DEV_NODE, 0, buf, size);
kfree(buf);
return size;
}
static const struct file_operations stm_fops = {
.owner = THIS_MODULE,
.open = nonseekable_open,
.write = stm_write,
.llseek = no_llseek,
};
static ssize_t stm_show_hwevent_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct stm_drvdata *drvdata = dev_get_drvdata(dev->parent);
unsigned long val = stm_hwevent_isenable(drvdata);
return scnprintf(buf, PAGE_SIZE, "%#lx\n", val);
}
static ssize_t stm_store_hwevent_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct stm_drvdata *drvdata = dev_get_drvdata(dev->parent);
unsigned long val;
int ret = 0;
if (sscanf(buf, "%lx", &val) != 1)
return -EINVAL;
if (val)
ret = stm_hwevent_enable(drvdata);
else
stm_hwevent_disable(drvdata);
if (ret)
return ret;
return size;
}
static DEVICE_ATTR(hwevent_enable, S_IRUGO | S_IWUSR, stm_show_hwevent_enable,
stm_store_hwevent_enable);
static ssize_t stm_show_port_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct stm_drvdata *drvdata = dev_get_drvdata(dev->parent);
unsigned long val = stm_port_isenable(drvdata);
return scnprintf(buf, PAGE_SIZE, "%#lx\n", val);
}
static ssize_t stm_store_port_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct stm_drvdata *drvdata = dev_get_drvdata(dev->parent);
unsigned long val;
int ret = 0;
if (sscanf(buf, "%lx", &val) != 1)
return -EINVAL;
if (val)
ret = stm_port_enable(drvdata);
else
stm_port_disable(drvdata);
if (ret)
return ret;
return size;
}
static DEVICE_ATTR(port_enable, S_IRUGO | S_IWUSR, stm_show_port_enable,
stm_store_port_enable);
static ssize_t stm_show_entity(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct stm_drvdata *drvdata = dev_get_drvdata(dev->parent);
unsigned long val = drvdata->entity;
return scnprintf(buf, PAGE_SIZE, "%#lx\n", val);
}
static ssize_t stm_store_entity(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct stm_drvdata *drvdata = dev_get_drvdata(dev->parent);
unsigned long val;
if (sscanf(buf, "%lx", &val) != 1)
return -EINVAL;
drvdata->entity = val;
return size;
}
static DEVICE_ATTR(entity, S_IRUGO | S_IWUSR, stm_show_entity,
stm_store_entity);
static struct attribute *stm_attrs[] = {
&dev_attr_hwevent_enable.attr,
&dev_attr_port_enable.attr,
&dev_attr_entity.attr,
NULL,
};
static struct attribute_group stm_attr_grp = {
.attrs = stm_attrs,
};
static const struct attribute_group *stm_attr_grps[] = {
&stm_attr_grp,
NULL,
};
static int __devinit stm_probe(struct platform_device *pdev)
{
int ret;
struct device *dev = &pdev->dev;
struct coresight_platform_data *pdata;
struct stm_drvdata *drvdata;
struct resource *res;
size_t res_size, bitmap_size;
struct coresight_desc *desc;
if (pdev->dev.of_node) {
pdata = of_get_coresight_platform_data(dev, pdev->dev.of_node);
if (IS_ERR(pdata))
return PTR_ERR(pdata);
pdev->dev.platform_data = pdata;
}
drvdata = devm_kzalloc(dev, sizeof(*drvdata), GFP_KERNEL);
if (!drvdata)
return -ENOMEM;
/* Store the driver data pointer for use in exported functions */
stmdrvdata = drvdata;
drvdata->dev = &pdev->dev;
platform_set_drvdata(pdev, drvdata);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
drvdata->base = devm_ioremap(dev, res->start, resource_size(res));
if (!drvdata->base)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res)
return -ENODEV;
if (boot_nr_channel) {
res_size = min((resource_size_t)(boot_nr_channel *
BYTES_PER_CHANNEL), resource_size(res));
bitmap_size = boot_nr_channel * sizeof(long);
} else {
res_size = min((resource_size_t)(NR_STM_CHANNEL *
BYTES_PER_CHANNEL), resource_size(res));
bitmap_size = NR_STM_CHANNEL * sizeof(long);
}
drvdata->chs.base = devm_ioremap(dev, res->start, res_size);
if (!drvdata->chs.base)
return -ENOMEM;
drvdata->chs.bitmap = devm_kzalloc(dev, bitmap_size, GFP_KERNEL);
if (!drvdata->chs.bitmap)
return -ENOMEM;
spin_lock_init(&drvdata->spinlock);
drvdata->clk = devm_clk_get(dev, "core_clk");
if (IS_ERR(drvdata->clk))
return PTR_ERR(drvdata->clk);
ret = clk_set_rate(drvdata->clk, CORESIGHT_CLK_RATE_TRACE);
if (ret)
return ret;
drvdata->entity = OST_ENTITY_ALL;
desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
if (!desc)
return -ENOMEM;
desc->type = CORESIGHT_DEV_TYPE_SOURCE;
desc->subtype.source_subtype = CORESIGHT_DEV_SUBTYPE_SOURCE_SOFTWARE;
desc->ops = &stm_cs_ops;
desc->pdata = pdev->dev.platform_data;
desc->dev = &pdev->dev;
desc->groups = stm_attr_grps;
desc->owner = THIS_MODULE;
drvdata->csdev = coresight_register(desc);
if (IS_ERR(drvdata->csdev))
return PTR_ERR(drvdata->csdev);
drvdata->miscdev.name = ((struct coresight_platform_data *)
(pdev->dev.platform_data))->name;
drvdata->miscdev.minor = MISC_DYNAMIC_MINOR;
drvdata->miscdev.fops = &stm_fops;
ret = misc_register(&drvdata->miscdev);
if (ret)
goto err;
dev_info(drvdata->dev, "STM initialized\n");
if (boot_enable)
coresight_enable(drvdata->csdev);
return 0;
err:
coresight_unregister(drvdata->csdev);
return ret;
}
static int __devexit stm_remove(struct platform_device *pdev)
{
struct stm_drvdata *drvdata = platform_get_drvdata(pdev);
misc_deregister(&drvdata->miscdev);
coresight_unregister(drvdata->csdev);
return 0;
}
static struct of_device_id stm_match[] = {
{.compatible = "arm,coresight-stm"},
{}
};
static struct platform_driver stm_driver = {
.probe = stm_probe,
.remove = __devexit_p(stm_remove),
.driver = {
.name = "coresight-stm",
.owner = THIS_MODULE,
.of_match_table = stm_match,
},
};
static int __init stm_init(void)
{
return platform_driver_register(&stm_driver);
}
module_init(stm_init);
static void __exit stm_exit(void)
{
platform_driver_unregister(&stm_driver);
}
module_exit(stm_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("CoreSight System Trace Macrocell driver");
| gpl-2.0 |
teeple/pns_server | work/install/node-v0.10.25/deps/uv/test/test-signal-multiple-loops.c | 31 | 7453 | /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/* This test does not pretend to be cross-platform. */
#ifndef _WIN32
#include "uv.h"
#include "task.h"
#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define NUM_SIGNAL_HANDLING_THREADS 25
#define NUM_LOOP_CREATING_THREADS 10
static uv_sem_t sem;
static uv_mutex_t counter_lock;
static volatile int stop = 0;
static volatile int signal1_cb_counter = 0;
static volatile int signal2_cb_counter = 0;
static volatile int loop_creation_counter = 0;
static void increment_counter(volatile int* counter) {
uv_mutex_lock(&counter_lock);
++(*counter);
uv_mutex_unlock(&counter_lock);
}
static void signal1_cb(uv_signal_t* handle, int signum) {
ASSERT(signum == SIGUSR1);
increment_counter(&signal1_cb_counter);
uv_signal_stop(handle);
}
static void signal2_cb(uv_signal_t* handle, int signum) {
ASSERT(signum == SIGUSR2);
increment_counter(&signal2_cb_counter);
uv_signal_stop(handle);
}
static void signal_handling_worker(void* context) {
uintptr_t mask = (uintptr_t) context;
uv_loop_t* loop;
uv_signal_t signal1a;
uv_signal_t signal1b;
uv_signal_t signal2;
int r;
loop = uv_loop_new();
ASSERT(loop != NULL);
/* Setup the signal watchers and start them. */
if (mask & SIGUSR1) {
r = uv_signal_init(loop, &signal1a);
ASSERT(r == 0);
r = uv_signal_start(&signal1a, signal1_cb, SIGUSR1);
ASSERT(r == 0);
r = uv_signal_init(loop, &signal1b);
ASSERT(r == 0);
r = uv_signal_start(&signal1b, signal1_cb, SIGUSR1);
ASSERT(r == 0);
}
if (mask & SIGUSR2) {
r = uv_signal_init(loop, &signal2);
ASSERT(r == 0);
r = uv_signal_start(&signal2, signal2_cb, SIGUSR2);
ASSERT(r == 0);
}
/* Signal watchers are now set up. */
uv_sem_post(&sem);
/* Wait for all signals. The signal callbacks stop the watcher, so uv_run
* will return when all signal watchers caught a signal.
*/
r = uv_run(loop, UV_RUN_DEFAULT);
ASSERT(r == 0);
/* Restart the signal watchers. */
if (mask & SIGUSR1) {
r = uv_signal_start(&signal1a, signal1_cb, SIGUSR1);
ASSERT(r == 0);
r = uv_signal_start(&signal1b, signal1_cb, SIGUSR1);
ASSERT(r == 0);
}
if (mask & SIGUSR2) {
r = uv_signal_start(&signal2, signal2_cb, SIGUSR2);
ASSERT(r == 0);
}
/* Wait for signals once more. */
uv_sem_post(&sem);
r = uv_run(loop, UV_RUN_DEFAULT);
ASSERT(r == 0);
/* Close the watchers. */
if (mask & SIGUSR1) {
uv_close((uv_handle_t*) &signal1a, NULL);
uv_close((uv_handle_t*) &signal1b, NULL);
}
if (mask & SIGUSR2) {
uv_close((uv_handle_t*) &signal2, NULL);
}
/* Wait for the signal watchers to close. */
r = uv_run(loop, UV_RUN_DEFAULT);
ASSERT(r == 0);
uv_loop_delete(loop);
}
static void signal_unexpected_cb(uv_signal_t* handle, int signum) {
ASSERT(0 && "signal_unexpected_cb should never be called");
}
static void loop_creating_worker(void* context) {
(void) context;
do {
uv_loop_t* loop;
uv_signal_t signal;
int r;
loop = uv_loop_new();
ASSERT(loop != NULL);
r = uv_signal_init(loop, &signal);
ASSERT(r == 0);
r = uv_signal_start(&signal, signal_unexpected_cb, SIGTERM);
ASSERT(r == 0);
uv_close((uv_handle_t*) &signal, NULL);
r = uv_run(loop, UV_RUN_DEFAULT);
ASSERT(r == 0);
uv_loop_delete(loop);
increment_counter(&loop_creation_counter);
} while (!stop);
}
TEST_IMPL(signal_multiple_loops) {
int i, r;
uv_thread_t loop_creating_threads[NUM_LOOP_CREATING_THREADS];
uv_thread_t signal_handling_threads[NUM_SIGNAL_HANDLING_THREADS];
sigset_t sigset;
r = uv_sem_init(&sem, 0);
ASSERT(r == 0);
r = uv_mutex_init(&counter_lock);
ASSERT(r == 0);
/* Create a couple of threads that create a destroy loops continuously. */
for (i = 0; i < NUM_LOOP_CREATING_THREADS; i++) {
r = uv_thread_create(&loop_creating_threads[i],
loop_creating_worker,
NULL);
ASSERT(r == 0);
}
/* Create a couple of threads that actually handle signals. */
for (i = 0; i < NUM_SIGNAL_HANDLING_THREADS; i++) {
uintptr_t mask;
switch (i % 3) {
case 0: mask = SIGUSR1; break;
case 1: mask = SIGUSR2; break;
case 2: mask = SIGUSR1 | SIGUSR2; break;
}
r = uv_thread_create(&signal_handling_threads[i],
signal_handling_worker,
(void*) mask);
ASSERT(r == 0);
}
/* Wait until all threads have started and set up their signal watchers. */
for (i = 0; i < NUM_SIGNAL_HANDLING_THREADS; i++)
uv_sem_wait(&sem);
r = kill(getpid(), SIGUSR1);
ASSERT(r == 0);
r = kill(getpid(), SIGUSR2);
ASSERT(r == 0);
/* Wait for all threads to handle these signals. */
for (i = 0; i < NUM_SIGNAL_HANDLING_THREADS; i++)
uv_sem_wait(&sem);
/* Block all signals to this thread, so we are sure that from here the signal
* handler runs in another thread. This is is more likely to catch thread and
* signal safety issues if there are any.
*/
sigfillset(&sigset);
pthread_sigmask(SIG_SETMASK, &sigset, NULL);
r = kill(getpid(), SIGUSR1);
ASSERT(r == 0);
r = kill(getpid(), SIGUSR2);
ASSERT(r == 0);
/* Wait for all signal handling threads to exit. */
for (i = 0; i < NUM_SIGNAL_HANDLING_THREADS; i++) {
r = uv_thread_join(&signal_handling_threads[i]);
ASSERT(r == 0);
}
/* Tell all loop creating threads to stop. */
stop = 1;
/* Wait for all loop creating threads to exit. */
for (i = 0; i < NUM_LOOP_CREATING_THREADS; i++) {
r = uv_thread_join(&loop_creating_threads[i]);
ASSERT(r == 0);
}
printf("signal1_cb calls: %d\n", signal1_cb_counter);
printf("signal2_cb calls: %d\n", signal2_cb_counter);
printf("loops created and destroyed: %d\n", loop_creation_counter);
ASSERT(signal1_cb_counter == 4 * NUM_SIGNAL_HANDLING_THREADS);
ASSERT(signal2_cb_counter == 2 * NUM_SIGNAL_HANDLING_THREADS);
/* We don't know exactly how much loops will be created and destroyed, but at
* least there should be 1 for every loop creating thread.
*/
ASSERT(loop_creation_counter >= NUM_LOOP_CREATING_THREADS);
MAKE_VALGRIND_HAPPY();
return 0;
}
#endif /* !_WIN32 */
| gpl-2.0 |
lovequilt/TrinityCore | src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp | 31 | 83432 | /*
* Copyright (C) 2008-2015 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 "ScriptedGossip.h"
#include "ScriptedEscortAI.h"
#include "Player.h"
#define LESS_MOB // if you do not have a good server and do not want it to be laggy as hell
//Light of Dawn
enum mograine
{
#ifdef LESS_MOB
ENCOUNTER_DK_NUMBER = 5, // how many player queue to start the quest, or -
ENCOUNTER_DK_TIMER = 10, // *every 5 minutes. These have to be done in instance data
ENCOUNTER_DEFENDER_NUMBER = 10, // how many of defender
ENCOUNTER_EARTHSHATTER_NUMBER = 1, // how many of earthshatter
ENCOUNTER_ABOMINATION_NUMBER = 2, // how many of abomination
ENCOUNTER_BEHEMOTH_NUMBER = 1, // how many of behemoth
ENCOUNTER_GHOUL_NUMBER = 5, // how many of ghoul
ENCOUNTER_WARRIOR_NUMBER = 1, // how many of warrior
#else
ENCOUNTER_DK_NUMBER = 5, // how many player queue to start the quest, or -
ENCOUNTER_DK_TIMER = 10, // *every 5 minutes. These have to be done in instance data
ENCOUNTER_DEFENDER_NUMBER = 20, // how many of defender
ENCOUNTER_EARTHSHATTER_NUMBER = 20, // how many of earthshatter
ENCOUNTER_ABOMINATION_NUMBER = 3, // how many of abomination
ENCOUNTER_BEHEMOTH_NUMBER = 2, // how many of behemoth
ENCOUNTER_GHOUL_NUMBER = 10, // how many of ghoul
ENCOUNTER_WARRIOR_NUMBER = 2, // how many of warrior
#endif
ENCOUNTER_TOTAL_DAWN = 300, // Total number
ENCOUNTER_TOTAL_SCOURGE = 10000,
WORLD_STATE_REMAINS = 3592,
WORLD_STATE_COUNTDOWN = 3603,
WORLD_STATE_EVENT_BEGIN = 3605,
SAY_LIGHT_OF_DAWN01 = 0, // pre text
SAY_LIGHT_OF_DAWN02 = 1,
SAY_LIGHT_OF_DAWN03 = 2,
SAY_LIGHT_OF_DAWN04 = 3, // intro
SAY_LIGHT_OF_DAWN05 = 4,
SAY_LIGHT_OF_DAWN06 = 5,
SAY_LIGHT_OF_DAWN07 = 6, // During the fight - Korfax, Champion of the Light
SAY_LIGHT_OF_DAWN08 = 7, // Lord Maxwell Tyrosus
SAY_LIGHT_OF_DAWN09 = 8, // Highlord Darion Mograine
SAY_LIGHT_OF_DAWN25 = 24, // After the fight
SAY_LIGHT_OF_DAWN26 = 25, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN27 = 26, // Highlord Darion Mograine
SAY_LIGHT_OF_DAWN28 = 27, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN29 = 28, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN30 = 29, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN31 = 30, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN32 = 31, // Highlord Alexandros Mograine
SAY_LIGHT_OF_DAWN33 = 32, // Highlord Darion Mograine
SAY_LIGHT_OF_DAWN34 = 33, // Highlord Darion Mograine
SAY_LIGHT_OF_DAWN35 = 34, // Darion Mograine
SAY_LIGHT_OF_DAWN36 = 35, // Darion Mograine
SAY_LIGHT_OF_DAWN37 = 36, // Highlord Alexandros Mograine
SAY_LIGHT_OF_DAWN38 = 37, // Darion Mograine
SAY_LIGHT_OF_DAWN39 = 38, // Highlord Alexandros Mograine
SAY_LIGHT_OF_DAWN40 = 39, // Darion Mograine
SAY_LIGHT_OF_DAWN41 = 40, // Highlord Alexandros Mograine
SAY_LIGHT_OF_DAWN42 = 41, // Highlord Alexandros Mograine
SAY_LIGHT_OF_DAWN43 = 42, // The Lich King
SAY_LIGHT_OF_DAWN44 = 43, // Highlord Darion Mograine
SAY_LIGHT_OF_DAWN45 = 44, // The Lich King
SAY_LIGHT_OF_DAWN46 = 45, // The Lich King
SAY_LIGHT_OF_DAWN47 = 46, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN48 = 47, // The Lich King
SAY_LIGHT_OF_DAWN49 = 48, // The Lich King
SAY_LIGHT_OF_DAWN50 = 49, // Lord Maxwell Tyrosus
SAY_LIGHT_OF_DAWN51 = 50, // The Lich King
SAY_LIGHT_OF_DAWN52 = 51, // Highlord Darion Mograine
SAY_LIGHT_OF_DAWN53 = 52, // Highlord Darion Mograine
SAY_LIGHT_OF_DAWN54 = 53, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN55 = 54, // The Lich King
SAY_LIGHT_OF_DAWN56 = 55, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN57 = 56, // The Lich King
SAY_LIGHT_OF_DAWN58 = 57, // The Lich King
SAY_LIGHT_OF_DAWN59 = 58, // The Lich King
SAY_LIGHT_OF_DAWN60 = 59, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN61 = 60, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN62 = 61, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN63 = 62, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN64 = 63, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN65 = 64, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN66 = 65, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN67 = 66, // Highlord Tirion Fordring
SAY_LIGHT_OF_DAWN68 = 67, // Highlord Darion Mograine
EMOTE_LIGHT_OF_DAWN01 = 68, // Emotes
EMOTE_LIGHT_OF_DAWN02 = 69,
EMOTE_LIGHT_OF_DAWN03 = 70,
EMOTE_LIGHT_OF_DAWN04 = 71,
EMOTE_LIGHT_OF_DAWN05 = 72,
EMOTE_LIGHT_OF_DAWN06 = 73,
EMOTE_LIGHT_OF_DAWN07 = 74,
EMOTE_LIGHT_OF_DAWN08 = 75,
EMOTE_LIGHT_OF_DAWN09 = 76,
EMOTE_LIGHT_OF_DAWN10 = 77,
EMOTE_LIGHT_OF_DAWN11 = 78,
EMOTE_LIGHT_OF_DAWN12 = 79,
EMOTE_LIGHT_OF_DAWN13 = 80,
EMOTE_LIGHT_OF_DAWN14 = 81,
EMOTE_LIGHT_OF_DAWN15 = 82,
EMOTE_LIGHT_OF_DAWN16 = 83,
EMOTE_LIGHT_OF_DAWN17 = 84,
EMOTE_LIGHT_OF_DAWN18 = 85,
GO_LIGHT_OF_DAWN = 191330,
SPELL_THE_LIGHT_OF_DAWN_Q = 53606, // quest credit
// ---- Dark Knight npc --------------------
// Highlord Darion Mograine
NPC_HIGHLORD_DARION_MOGRAINE = 29173,
SPELL_ANTI_MAGIC_ZONE1 = 52893,
SPELL_DEATH_STRIKE = 53639,
SPELL_DEATH_EMBRACE = 53635,
SPELL_ICY_TOUCH1 = 49723,
SPELL_THE_LIGHT_OF_DAWN = 53658,
SPELL_THE_MIGHT_OF_MOGRAINE = 53642, // on players when begins
SPELL_UNHOLY_BLIGHT = 53640,
SPELL_ALEXANDROS_MOGRAINE_SPAWN = 53667,
SPELL_MOGRAINE_CHARGE = 53679,
SPELL_ASHBRINGER = 53701,
// Koltira Deathweaver & Orbaz Bloodbane are using the same abilities
NPC_KOLTIRA_DEATHWEAVER = 29199,
NPC_ORBAZ_BLOODBANE = 29204, // this guy fleed
NPC_THASSARIAN = 29200, // he also does SPELL_THE_LIGHT_OF_DAWN 53658
SPELL_BLOOD_STRIKE1 = 52374,
SPELL_DEATH_GRIP = 49576,
SPELL_ICY_TOUCH2 = 52372,
SPELL_PLAGUE_STRIKE1 = 50668,
// all do SPELL_HERO_AGGRO_AURA 53627
// Lich King
NPC_THE_LICH_KING = 29183, // show up at end
SPELL_APOCALYPSE = 53210,
SPELL_TELEPORT_VISUAL = 52233,
SPELL_SOUL_FEAST_ALEX = 53677, // on Alexandros
SPELL_SOUL_FEAST_TIRION = 53685, // on Tirion
SPELL_ICEBOUND_VISAGE = 53274, // not sure what is it for
SPELL_REBUKE = 53680,
// others
NPC_RAMPAGING_ABOMINATION = 29186,
SPELL_CLEAVE1 = 53633,
SPELL_SCOURGE_HOOK = 50335,
SPELL_SCOURGE_AGGRO_AURA = 53624,
NPC_FLESH_BEHEMOTH = 29190, // giant guy
SPELL_STOMP = 53634,
SPELL_THUNDERCLAP = 36706,
SPELL_HERO_AGGRO_AURA = 53627,
NPC_ACHERUS_GHOUL = 29219, // just ghoul....
SPELL_GHOULPLOSION = 53632,
NPC_WARRIOR_OF_THE_FROZEN_WASTES = 29206, // use SPELL_CLEAVE 53631
NPC_HIGHLORD_ALEXANDROS_MOGRAINE = 29227, // ghost
NPC_DARION_MOGRAINE = 29228, // ghost
// ---- Dawn npc --------------------
// Highlord Tirion Fordring
NPC_HIGHLORD_TIRION_FORDRING = 29175,
EQUIP_HIGHLORD_TIRION_FORDRING = 13262,
SPELL_LAY_ON_HANDS = 53778,
SPELL_REBIRTH_OF_THE_ASHBRINGER = 53702,
SPELL_TIRION_CHARGE = 53705,
SPELL_TIRION_CHARGE_VISUAL = 53706,
// others
NPC_KORFAX_CHAMPION_OF_THE_LIGHT = 29176,
SPELL_CLEAVE = 53631,
SPELL_HEROIC_LEAP = 53625,
NPC_LORD_MAXWELL_TYROSUS = 29178,
NPC_LEONID_BARTHALOMEW_THE_REVERED = 29179,
NPC_DUKE_NICHOLAS_ZVERENHOFF = 29180,
NPC_COMMANDER_ELIGOR_DAWNBRINGER = 29177,
SPELL_HOLY_LIGHT2 = 37979,
NPC_RAYNE = 29181,
SPELL_REJUVENATION = 20664,
SPELL_STARFALL = 20678,
SPELL_TRANQUILITY = 25817,
SPELL_WRATH = 21807,
NPC_DEFENDER_OF_THE_LIGHT = 29174, // also does SPELL_HEROIC_LEAP 53625
SPELL_HOLY_LIGHT1 = 29427,
SPELL_HOLY_STRIKE = 53643,
SPELL_HOLY_WRATH = 53638,
SPELL_UPPERCUT = 53629,
NPC_RIMBLAT_EARTHSHATTER = 29182,
SPELL_CHAIN_HEAL = 33642,
SPELL_THUNDER = 53630
};
void UpdateWorldState(Map* map, uint32 id, uint32 state)
{
Map::PlayerList const& players = map->GetPlayers();
if (!players.isEmpty())
{
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
if (Player* player = itr->GetSource())
player->SendUpdateWorldState(id, state);
}
}
}
Position const LightofDawnLoc[] =
{
{2281.335f, -5300.409f, 85.170f, 0}, // 0 Tirion Fordring loc
{2283.896f, -5287.914f, 83.066f, 1.55f}, // 1 Tirion Fordring loc2
{2281.461f, -5263.014f, 81.164f, 0}, // 2 Tirion charges
{2262.277f, -5293.477f, 82.167f, 0}, // 3 Tirion run
{2270.286f, -5287.73f, 82.262f, 0}, // 4 Tirion relocate
{2269.511f, -5288.289f, 82.225f, 0}, // 5 Tirion forward
{2262.277f, -5293.477f, 82.167f, 0}, // 6 Tirion runs to Darion
{2270.286f, -5287.73f, 82.262f, 0},
{2269.511f, -5288.289f, 82.225f, 0},
{2273.205f, -5288.848f, 82.617f, 0}, // 9 Korfax loc1
{2274.739f, -5287.926f, 82.684f, 0}, // 10 Korfax loc2
{2253.673f, -5318.004f, 81.724f, 0}, // 11 Korfax kicked
{2287.028f, -5309.644f, 87.253f, 0}, // 12 Maxwell loc1
{2286.978f, -5308.025f, 86.83f, 0}, // 13 Maxwell loc2
{2248.877f, -5307.586f, 82.166f, 0}, // 14 maxwell kicked
{2278.58f, -5316.933f, 88.319f, 0}, // 15 Eligor loc1
{2278.535f, -5315.479f, 88.08f, 0}, // 16 Eligor loc2
{2259.416f, -5304.505f, 82.149f, 0}, // 17 eligor kicked
{2289.259f, -5280.355f, 82.112f, 0}, // 18 Koltira loc1
{2289.02f, -5281.985f, 82.207f, 0}, // 19 Koltira loc2
{2273.289f, -5273.675f, 81.701f, 0}, // 20 Thassarian loc1
{2273.332f, -5275.544f, 81.849f, 0}, // 21 Thassarian loc2
{2281.198f, -5257.397f, 80.224f, 4.66f}, // 22 Alexandros loc1
{2281.156f, -5259.934f, 80.647f, 0}, // 23 Alexandros loc2
{2281.294f, -5281.895f, 82.445f, 1.35f}, // 24 Darion loc1
{2281.093f, -5263.013f, 81.125f, 0}, // 25 Darion loc1
{2281.313f, -5250.282f, 79.322f, 4.69f}, // 26 Lich King spawns
{2281.523f, -5261.058f, 80.877f, 0}, // 27 Lich king move forwards
{2272.709f, -5255.552f, 78.226f, 0}, // 28 Lich king kicked
{2273.972f, -5257.676f, 78.862f, 0}, // 29 Lich king moves forward
};
class npc_highlord_darion_mograine : public CreatureScript
{
public:
npc_highlord_darion_mograine() : CreatureScript("npc_highlord_darion_mograine") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF+1:
player->CLOSE_GOSSIP_MENU();
ENSURE_AI(npc_highlord_darion_mograine::npc_highlord_darion_mograineAI, creature->AI())->uiStep = 1;
ENSURE_AI(npc_highlord_darion_mograine::npc_highlord_darion_mograineAI, creature->AI())->Start(true, false, player->GetGUID());
break;
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature) override
{
if (creature->IsQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (player->GetQuestStatus(12801) == QUEST_STATUS_INCOMPLETE)
player->ADD_GOSSIP_ITEM(0, "I am ready.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_highlord_darion_mograineAI(creature);
}
struct npc_highlord_darion_mograineAI : public npc_escortAI
{
npc_highlord_darion_mograineAI(Creature* creature) : npc_escortAI(creature)
{
Reset();
}
bool bIsBattle;
uint32 uiStep;
uint32 uiPhase_timer;
uint32 uiFight_duration;
uint32 uiTotal_dawn;
uint32 uiTotal_scourge;
uint32 uiSummon_counter;
// Darion Mograine
uint32 uiAnti_magic_zone;
uint32 uiDeath_strike;
uint32 uiDeath_embrace;
uint32 uiIcy_touch;
uint32 uiUnholy_blight;
uint32 uiFight_speech;
uint32 uiSpawncheck;
uint32 uiTargetcheck;
// Dawn
ObjectGuid uiTirionGUID;
ObjectGuid uiAlexandrosGUID;
ObjectGuid uiDarionGUID;
ObjectGuid uiKorfaxGUID;
ObjectGuid uiMaxwellGUID;
ObjectGuid uiEligorGUID;
ObjectGuid uiRayneGUID;
ObjectGuid uiDefenderGUID[ENCOUNTER_DEFENDER_NUMBER];
ObjectGuid uiEarthshatterGUID[ENCOUNTER_EARTHSHATTER_NUMBER];
// Death
ObjectGuid uiKoltiraGUID;
ObjectGuid uiOrbazGUID;
ObjectGuid uiThassarianGUID;
ObjectGuid uiLichKingGUID;
ObjectGuid uiAbominationGUID[ENCOUNTER_ABOMINATION_NUMBER];
ObjectGuid uiBehemothGUID[ENCOUNTER_BEHEMOTH_NUMBER];
ObjectGuid uiGhoulGUID[ENCOUNTER_GHOUL_NUMBER];
ObjectGuid uiWarriorGUID[ENCOUNTER_WARRIOR_NUMBER];
void Reset() override
{
if (!HasEscortState(STATE_ESCORT_ESCORTING))
{
bIsBattle = false;
uiStep = 0;
uiPhase_timer = 3000;
uiFight_duration = 300000; // 5 minutes
uiTotal_dawn = ENCOUNTER_TOTAL_DAWN;
uiTotal_scourge = ENCOUNTER_TOTAL_SCOURGE;
uiSummon_counter = 0;
uiAnti_magic_zone = urand(1000, 6000);
uiDeath_strike = urand(5000, 10000);
uiDeath_embrace = urand(5000, 10000);
uiIcy_touch = urand(5000, 10000);
uiUnholy_blight = urand(5000, 10000);
uiFight_speech = 15000;
uiSpawncheck = 1000;
uiTargetcheck = 10000;
me->SetStandState(UNIT_STAND_STATE_STAND);
me->Mount(25279);
me->SetVisible(true);
UpdateWorldState(me->GetMap(), WORLD_STATE_REMAINS, 0);
//UpdateWorldState(me->GetMap(), WORLD_STATE_COUNTDOWN, 0);
UpdateWorldState(me->GetMap(), WORLD_STATE_EVENT_BEGIN, 0);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->setDeathState(JUST_DIED);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID))
temp->setDeathState(JUST_DIED);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID))
temp->setDeathState(JUST_DIED);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEligorGUID))
temp->setDeathState(JUST_DIED);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiRayneGUID))
temp->setDeathState(JUST_DIED);
uiTirionGUID.Clear();
uiKorfaxGUID.Clear();
uiMaxwellGUID.Clear();
uiEligorGUID.Clear();
uiRayneGUID.Clear();
for (uint8 i = 0; i < ENCOUNTER_DEFENDER_NUMBER; ++i)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDefenderGUID[i]))
temp->setDeathState(JUST_DIED);
uiDefenderGUID[i].Clear();
}
for (uint8 i = 0; i < ENCOUNTER_EARTHSHATTER_NUMBER; ++i)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEarthshatterGUID[i]))
temp->setDeathState(JUST_DIED);
uiEarthshatterGUID[i].Clear();
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKoltiraGUID))
temp->Respawn();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiOrbazGUID))
temp->Respawn();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiThassarianGUID))
temp->Respawn();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->Respawn();
uiKoltiraGUID.Clear();
uiOrbazGUID.Clear();
uiThassarianGUID.Clear();
uiLichKingGUID.Clear();
for (uint8 i = 0; i < ENCOUNTER_ABOMINATION_NUMBER; ++i)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAbominationGUID[i]))
temp->setDeathState(JUST_DIED);
uiAbominationGUID[i].Clear();
}
for (uint8 i = 0; i < ENCOUNTER_BEHEMOTH_NUMBER; ++i)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiBehemothGUID[i]))
temp->setDeathState(JUST_DIED);
uiBehemothGUID[i].Clear();
}
for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiGhoulGUID[i]))
temp->setDeathState(JUST_DIED);
uiGhoulGUID[i].Clear();
}
for (uint8 i = 0; i < ENCOUNTER_WARRIOR_NUMBER; ++i)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiWarriorGUID[i]))
temp->setDeathState(JUST_DIED);
uiWarriorGUID[i].Clear();
}
}
}
void AttackStart(Unit* who) override
{
if (!who)
return;
if (who == me)
return;
if (me->Attack(who, true))
{
me->AddThreat(who, 0.0f);
me->SetInCombatWith(who);
who->SetInCombatWith(me);
DoStartMovement(who);
}
}
void MoveInLineOfSight(Unit* who) override
{
if (!who)
return;
if (me->IsValidAttackTarget(who))
if (me->IsWithinDistInMap(who, 20) && me->IsWithinLOSInMap(who))
AttackStart(who);
}
void SetHoldState(bool bOnHold)
{
SetEscortPaused(bOnHold);
}
void WaypointReached(uint32 waypointId) override
{
switch (waypointId)
{
case 0:
me->SetWalk(false);
SetHoldState(true);
break;
case 1:
SetHoldState(true);
SpawnNPC();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN07);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN08);
for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i)
NPCChangeTarget(uiGhoulGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_WARRIOR_NUMBER; ++i)
NPCChangeTarget(uiWarriorGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_ABOMINATION_NUMBER; ++i)
NPCChangeTarget(uiAbominationGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_BEHEMOTH_NUMBER; ++i)
NPCChangeTarget(uiBehemothGUID[i]);
NPCChangeTarget(uiKoltiraGUID);
NPCChangeTarget(uiOrbazGUID);
NPCChangeTarget(uiThassarianGUID);
me->Dismount();
me->CastSpell(me, SPELL_THE_MIGHT_OF_MOGRAINE, true); // need to fix, on player only
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKoltiraGUID))
temp->Dismount();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiThassarianGUID))
temp->Dismount();
bIsBattle = true;
break;
case 2:
me->SetWalk(true);
DoCast(me, SPELL_THE_LIGHT_OF_DAWN);
break;
case 3:
{
//Unit* pTirion = ObjectAccessor::GetCreature(*me, uiTirionGUID);
Talk(EMOTE_LIGHT_OF_DAWN05);
if (me->HasAura(SPELL_THE_LIGHT_OF_DAWN))
me->RemoveAurasDueToSpell(SPELL_THE_LIGHT_OF_DAWN);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKoltiraGUID))
{
if (temp->HasAura(SPELL_THE_LIGHT_OF_DAWN))
temp->RemoveAurasDueToSpell(SPELL_THE_LIGHT_OF_DAWN);
temp->SetWalk(true);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[19]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiThassarianGUID))
{
if (temp->HasAura(SPELL_THE_LIGHT_OF_DAWN))
temp->RemoveAurasDueToSpell(SPELL_THE_LIGHT_OF_DAWN);
temp->SetWalk(true);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[21]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID))
{
temp->SetWalk(true);
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_READY2H);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[10]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID))
{
temp->SetWalk(true);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[13]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEligorGUID))
{
temp->SetWalk(true);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[16]);
}
JumpToNextStep(10000);
}
break;
case 4:
Talk(SAY_LIGHT_OF_DAWN27);
me->SetStandState(UNIT_STAND_STATE_KNEEL);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKoltiraGUID))
temp->SetStandState(UNIT_STAND_STATE_KNEEL);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiThassarianGUID))
temp->SetStandState(UNIT_STAND_STATE_KNEEL);
SetHoldState(true);
break;
case 5:
Talk(SAY_LIGHT_OF_DAWN33);
SetHoldState(true);
break;
case 6:
SetHoldState(true);
me->HandleEmoteCommand(EMOTE_ONESHOT_SPECIALATTACK1H);
JumpToNextStep(1000);
break;
case 7:
SetHoldState(true);
JumpToNextStep(2000);
break;
case 8:
me->SetVirtualItem(0, uint32(EQUIP_UNEQUIP));
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
me->CastSpell(temp, SPELL_ASHBRINGER, true);
Talk(EMOTE_LIGHT_OF_DAWN14);
SetHoldState(true);
break;
}
}
void EnterEvadeMode() override
{
if (!bIsBattle)//do not reset self if we are in battle
npc_escortAI::EnterEvadeMode();
}
void UpdateAI(uint32 diff) override
{
npc_escortAI::UpdateAI(diff);
if (!bIsBattle)
{
if (uiPhase_timer <= diff)
{
// ******* Before battle *****************************************************************
switch (uiStep)
{
case 0: // countdown
//UpdateWorldState(me->GetMap(), WORLD_STATE_COUNTDOWN, 1);
break;
case 1: // just delay
//UpdateWorldState(me->GetMap(), WORLD_STATE_REMAINS, 1);
UpdateWorldState(me->GetMap(), WORLD_STATE_COUNTDOWN, 0);
UpdateWorldState(me->GetMap(), WORLD_STATE_EVENT_BEGIN, 1);
me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
JumpToNextStep(3000);
break;
case 2:
Talk(SAY_LIGHT_OF_DAWN04);
if (Creature* pKoltira = GetClosestCreatureWithEntry(me, NPC_KOLTIRA_DEATHWEAVER, 50.0f))
uiKoltiraGUID = pKoltira->GetGUID();
if (Creature* pOrbaz = GetClosestCreatureWithEntry(me, NPC_ORBAZ_BLOODBANE, 50.0f))
uiOrbazGUID = pOrbaz->GetGUID();
if (Creature* pThassarian = GetClosestCreatureWithEntry(me, NPC_THASSARIAN, 50.0f))
uiThassarianGUID = pThassarian->GetGUID();
JumpToNextStep(10000);
break;
case 3: // rise
Talk(SAY_LIGHT_OF_DAWN05);
JumpToNextStep(3000);
break;
case 4: // summon ghoul
// Dunno whats the summon spell, so workaround
DoCast(me, 33271); // shack effect
uiPhase_timer = 500;
if (uiSummon_counter < ENCOUNTER_GHOUL_NUMBER)
{
Unit* temp = me->SummonCreature(NPC_ACHERUS_GHOUL, (me->GetPositionX() - 20) + rand32() % 40, (me->GetPositionY() - 20) + rand32() % 40, me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->SetWalk(false);
temp->setFaction(2084);
uiGhoulGUID[uiSummon_counter] = temp->GetGUID();
++uiSummon_counter;
}
else
{
uiSummon_counter = 0;
++uiStep;
}
break;
case 5: // summon abomination
DoCast(me, 33271); // shack effect
uiPhase_timer = 500;
if (uiSummon_counter < ENCOUNTER_ABOMINATION_NUMBER)
{
Unit* temp = me->SummonCreature(NPC_RAMPAGING_ABOMINATION, (me->GetPositionX() - 20) + rand32() % 40, (me->GetPositionY() - 20) + rand32() % 40, me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->SetWalk(false);
temp->setFaction(2084);
uiAbominationGUID[uiSummon_counter] = temp->GetGUID();
++uiSummon_counter;
}
else
{
uiSummon_counter = 0;
++uiStep;
}
break;
case 6: // summon warrior
DoCast(me, 33271); // shack effect
uiPhase_timer = 500;
if (uiSummon_counter < ENCOUNTER_WARRIOR_NUMBER)
{
Unit* temp = me->SummonCreature(NPC_WARRIOR_OF_THE_FROZEN_WASTES, (me->GetPositionX() - 20) + rand32() % 40, (me->GetPositionY() - 20) + rand32() % 40, me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->SetWalk(false);
temp->setFaction(2084);
uiWarriorGUID[uiSummon_counter] = temp->GetGUID();
++uiSummon_counter;
}
else
{
uiSummon_counter = 0;
++uiStep;
}
break;
case 7: // summon warrior
DoCast(me, 33271); // shack effect
uiPhase_timer = 500;
if (uiSummon_counter < ENCOUNTER_BEHEMOTH_NUMBER)
{
Unit* temp = me->SummonCreature(NPC_FLESH_BEHEMOTH, (me->GetPositionX() - 20) + rand32() % 40, (me->GetPositionY() - 20) + rand32() % 40, me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->SetWalk(false);
temp->setFaction(2084);
uiBehemothGUID[uiSummon_counter] = temp->GetGUID();
++uiSummon_counter;
}
else
{
uiSummon_counter = 0;
++uiStep;
}
break;
case 8: // summon announce
Talk(SAY_LIGHT_OF_DAWN06);
JumpToNextStep(5000);
break;
case 9: // charge begins
SetHoldState(false);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKoltiraGUID))
{
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }));
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiOrbazGUID))
{
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }));
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiThassarianGUID))
{
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }));
}
for (uint8 i = 0; i < ENCOUNTER_ABOMINATION_NUMBER; ++i)
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAbominationGUID[i]))
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }));
for (uint8 i = 0; i < ENCOUNTER_BEHEMOTH_NUMBER; ++i)
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiBehemothGUID[i]))
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }));
for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i)
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiGhoulGUID[i]))
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }));
for (uint8 i = 0; i < ENCOUNTER_WARRIOR_NUMBER; ++i)
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiWarriorGUID[i]))
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }));
JumpToNextStep(5000);
break;
// ******* After battle *****************************************************************
case 11: // Tirion starts to speak
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN28);
JumpToNextStep(21000);
break;
case 12:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN29);
JumpToNextStep(13000);
break;
case 13:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN30);
JumpToNextStep(13000);
break;
case 14:
me->SetStandState(UNIT_STAND_STATE_STAND);
Talk(SAY_LIGHT_OF_DAWN31);
JumpToNextStep(7000);
break;
case 15: // summon gate
if (Creature* temp = me->SummonCreature(NPC_HIGHLORD_ALEXANDROS_MOGRAINE, LightofDawnLoc[22], TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000))
{
temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
temp->CastSpell(temp, SPELL_ALEXANDROS_MOGRAINE_SPAWN, true);
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN06);
uiAlexandrosGUID = temp->GetGUID();
}
JumpToNextStep(4000);
break;
case 16: // Alexandros out
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAlexandrosGUID))
{
temp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[23]);
temp->AI()->Talk(SAY_LIGHT_OF_DAWN32);
}
SetHoldState(false); // makes darion turns back
JumpToNextStep(5000);
break;
case 17:
me->SetStandState(UNIT_STAND_STATE_KNEEL);
Talk(SAY_LIGHT_OF_DAWN34);
JumpToNextStep(5000);
break;
case 18: // Darion's spirit out
if (Creature* temp = me->SummonCreature(NPC_DARION_MOGRAINE, LightofDawnLoc[24], TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000))
{
temp->AI()->Talk(SAY_LIGHT_OF_DAWN35);
temp->SetWalk(false);
uiDarionGUID = temp->GetGUID();
}
JumpToNextStep(4000);
break;
case 19: // runs to father
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDarionGUID))
{
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN07);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[25]);
}
JumpToNextStep(4000);
break;
case 20:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDarionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN36);
JumpToNextStep(4000);
break;
case 21:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDarionGUID))
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN08);
JumpToNextStep(4000);
break;
case 22:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAlexandrosGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN37);
JumpToNextStep(8000);
break;
case 23:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDarionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN38);
JumpToNextStep(8000);
break;
case 24:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAlexandrosGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN39);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID)) // Tirion moves forward here
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[1]);
JumpToNextStep(15000);
break;
case 25:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDarionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN40);
JumpToNextStep(11000);
break;
case 26:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAlexandrosGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN41);
JumpToNextStep(5000);
break;
case 27:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDarionGUID))
temp->setDeathState(JUST_DIED);
JumpToNextStep(24000);
break;
case 28:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAlexandrosGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN42);
JumpToNextStep(6000);
break;
case 29: // lich king spawns
if (Creature* temp = me->SummonCreature(NPC_THE_LICH_KING, LightofDawnLoc[26], TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000))
{
temp->AI()->Talk(SAY_LIGHT_OF_DAWN43);
uiLichKingGUID = temp->GetGUID();
if (Unit* pAlex = ObjectAccessor::GetCreature(*me, uiAlexandrosGUID))
temp->CastSpell(pAlex, SPELL_SOUL_FEAST_ALEX, false);
}
JumpToNextStep(2000);
break;
case 30:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiAlexandrosGUID)) // just hide him
{
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN09);
temp->SetVisible(false);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
{
temp->InterruptNonMeleeSpells(false);
temp->AI()->Talk(SAY_LIGHT_OF_DAWN45);
}
JumpToNextStep(3000);
break;
case 31:
me->SetStandState(UNIT_STAND_STATE_STAND);
Talk(EMOTE_LIGHT_OF_DAWN10);
Talk(SAY_LIGHT_OF_DAWN44);
JumpToNextStep(3000);
break;
case 32:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[27]);
JumpToNextStep(6000);
break;
case 33: // Darion supports to jump to lich king here
if (ObjectAccessor::GetCreature(*me, uiLichKingGUID))
DoCast(me, SPELL_MOGRAINE_CHARGE); // jumping charge
// doesn't make it looks well, so workarounds, Darion charges, looks better
me->SetSpeed(MOVE_RUN, 3.0f);
me->SetWalk(false);
SetHoldState(false);
JumpToNextStep(0);
break;
case 35: // Lich king counterattacks
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
{
temp->HandleEmoteCommand(EMOTE_ONESHOT_KICK);
temp->AI()->Talk(SAY_LIGHT_OF_DAWN46);
}
me->SetSpeed(MOVE_RUN, 6.0f);
me->SetStandState(UNIT_STAND_STATE_DEAD);
SetHoldState(false); // Darion got kicked by lich king
JumpToNextStep(0);
break;
case 37: // Lich king counterattacks
me->SetStandState(UNIT_STAND_STATE_KNEEL);
JumpToNextStep(3000);
break;
case 38:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN47);
JumpToNextStep(8000);
break;
case 39:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN48);
JumpToNextStep(15000);
break;
case 40:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN49);
JumpToNextStep(17000);
break;
case 41: // Lich king - Apocalypse
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
{
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN11);
temp->AI()->Talk(SAY_LIGHT_OF_DAWN51);
if (Creature* pTirion = ObjectAccessor::GetCreature(*me, uiTirionGUID))
{
pTirion->SetStandState(UNIT_STAND_STATE_KNEEL);
//temp->CastSpell(pTirion, SPELL_APOCALYPSE, false); // not working
temp->CastSpell(pTirion, SPELL_SOUL_FEAST_TIRION, false);
pTirion->AI()->Talk(EMOTE_LIGHT_OF_DAWN12);
}
}
JumpToNextStep(2000);
break;
case 42: // Maxwell yells for attack
{
float fLichPositionX = 0,
fLichPositionY = 0,
fLichPositionZ = 0;
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
{
fLichPositionX = temp->GetPositionX();
fLichPositionY = temp->GetPositionY();
fLichPositionZ = temp->GetPositionZ();
}
if (fLichPositionX && fLichPositionY)
{
Unit* temp = me->SummonCreature(NPC_DEFENDER_OF_THE_LIGHT, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 10000);
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED);
temp->SetWalk(false);
temp->SetSpeed(MOVE_RUN, 2.0f);
temp->setFaction(me->getFaction());
temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ);
uiDefenderGUID[0] = temp->GetGUID();
temp = me->SummonCreature(NPC_RIMBLAT_EARTHSHATTER, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 10000);
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED);
temp->SetWalk(false);
temp->SetSpeed(MOVE_RUN, 2.0f);
temp->setFaction(me->getFaction());
temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ);
uiEarthshatterGUID[0] = temp->GetGUID();
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID))
{
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED);
temp->SetWalk(false);
temp->SetSpeed(MOVE_RUN, 2.0f);
temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ);
temp->AI()->Talk(SAY_LIGHT_OF_DAWN50);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID))
{
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED);
temp->SetWalk(false);
temp->SetSpeed(MOVE_RUN, 2.0f);
temp->HandleEmoteCommand(EMOTE_STATE_ATTACK_UNARMED);
temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEligorGUID))
{
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED);
temp->SetWalk(false);
temp->SetSpeed(MOVE_RUN, 2.0f);
temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ);
}
}
JumpToNextStep(4500);
break;
case 43: // They all got kicked
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN13);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID))
{
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE);
temp->SetSpeed(MOVE_RUN, 6.0f);
temp->SetStandState(UNIT_STAND_STATE_DEAD);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[14]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID))
{
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE);
temp->SetSpeed(MOVE_RUN, 6.0f);
temp->SetStandState(UNIT_STAND_STATE_DEAD);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[11]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEligorGUID))
{
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE);
temp->SetSpeed(MOVE_RUN, 6.0f);
temp->SetStandState(UNIT_STAND_STATE_DEAD);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[17]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDefenderGUID[0]))
{
temp->SetSpeed(MOVE_RUN, 6.0f);
temp->SetStandState(UNIT_STAND_STATE_DEAD);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f }));
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEarthshatterGUID[0]))
{
temp->SetSpeed(MOVE_RUN, 6.0f);
temp->SetStandState(UNIT_STAND_STATE_DEAD);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f }));
}
JumpToNextStep(3000);
break;
case 44: // make them stand up
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID))
temp->SetStandState(UNIT_STAND_STATE_STAND);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID))
temp->SetStandState(UNIT_STAND_STATE_STAND);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEligorGUID))
temp->SetStandState(UNIT_STAND_STATE_STAND);
JumpToNextStep(1000);
break;
case 45:
Talk(SAY_LIGHT_OF_DAWN52);
JumpToNextStep(5000);
break;
case 46: // Darion stand up, "not today"
me->SetSpeed(MOVE_RUN, 1.0f);
me->SetWalk(true);
me->SetStandState(UNIT_STAND_STATE_STAND);
Talk(SAY_LIGHT_OF_DAWN53);
SetHoldState(false); // Darion throws sword
JumpToNextStep(7000);
break;
case 47: // Ashbringer rebirth
me->SetStandState(UNIT_STAND_STATE_KNEEL);
Talk(EMOTE_LIGHT_OF_DAWN15);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
{
temp->SetStandState(UNIT_STAND_STATE_STAND);
temp->SetVirtualItem(0, uint32(EQUIP_HIGHLORD_TIRION_FORDRING));
temp->CastSpell(temp, SPELL_REBIRTH_OF_THE_ASHBRINGER, false);
}
JumpToNextStep(1000);
break;
case 48: // Show the cleansing effect (dawn of light)
//if (GameObject* go = me->GetMap()->GetGameObject(uiDawnofLightGUID))
// go->SetPhaseMask(128, true);
me->SummonGameObject(GO_LIGHT_OF_DAWN, 2283.896f, -5287.914f, 83.066f, 0, 0, 0, 0, 0, 30);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
{
if (temp->HasAura(SPELL_REBIRTH_OF_THE_ASHBRINGER))
temp->RemoveAurasDueToSpell(SPELL_REBIRTH_OF_THE_ASHBRINGER);
temp->CastSpell(temp, 41542, false); // workarounds, light expoded, makes it cool
temp->HandleEmoteCommand(EMOTE_ONESHOT_ROAR);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->InterruptNonMeleeSpells(false);
JumpToNextStep(2500);
break;
case 49:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN54);
JumpToNextStep(4000);
break;
case 50:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN55);
JumpToNextStep(5000);
break;
case 51:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN56);
JumpToNextStep(1000);
break;
case 52: // Tiron charges
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
{
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN16);
temp->CastSpell(temp, SPELL_TIRION_CHARGE, false); // jumping charge
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_READY2H);
temp->SetSpeed(MOVE_RUN, 3.0f); // workarounds, make Tirion still running
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[2]);
if (Creature* lktemp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
lktemp->Relocate(LightofDawnLoc[28]); // workarounds, he should kick back by Tirion, but here we relocate him
}
JumpToNextStep(1500);
break;
case 53:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN57);
JumpToNextStep(1000);
break;
case 54:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
{
temp->SetSpeed(MOVE_RUN, 1.0f);
me->SetWalk(true);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[29]); // 26
}
JumpToNextStep(4000);
break;
case 55:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->SetStandState(UNIT_STAND_STATE_KNEEL);
JumpToNextStep(2000);
break;
case 56:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->SetStandState(UNIT_STAND_STATE_STAND);
JumpToNextStep(1500);
break;
case 57:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN58);
JumpToNextStep(10000);
break;
case 58:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN59);
JumpToNextStep(10000);
break;
case 59:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->CastSpell(temp, SPELL_TELEPORT_VISUAL, false);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID)) // Tirion runs to Darion
{
temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE);
temp->SetSpeed(MOVE_RUN, 1.0f);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[6]);
}
JumpToNextStep(2500);
break;
case 60:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID)) // Lich king disappears here
{
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN17);
temp->Kill(temp);
}
JumpToNextStep(10000);
break;
case 61:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN60);
JumpToNextStep(3000);
break;
case 62:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
{
temp->SetWalk(true);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[7]);
}
JumpToNextStep(5500);
break;
case 63:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
{
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[8]);
temp->AI()->Talk(SAY_LIGHT_OF_DAWN61);
}
JumpToNextStep(15000);
break;
case 64:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN62);
JumpToNextStep(7000);
break;
case 65:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN63);
JumpToNextStep(10000);
break;
case 66:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN64);
JumpToNextStep(11000);
break;
case 67:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN65);
JumpToNextStep(10000);
break;
case 68:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN66);
JumpToNextStep(8000);
break;
case 69:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN67);
JumpToNextStep(10000);
break;
case 70:
me->SetStandState(UNIT_STAND_STATE_STAND);
Talk(SAY_LIGHT_OF_DAWN68);
JumpToNextStep(10000);
break;
case 71:
//if (GameObject* go = me->GetMap()->GetGameObject(uiDawnofLightGUID)) // Turn off dawn of light
// go->SetPhaseMask(0, true);
{
Map* map = me->GetMap(); // search players with in 50 yards for quest credit
Map::PlayerList const &PlayerList = map->GetPlayers();
if (!PlayerList.isEmpty())
{
for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
if (i->GetSource()->IsAlive() && me->IsWithinDistInMap(i->GetSource(), 50))
i->GetSource()->CastSpell(i->GetSource(), SPELL_THE_LIGHT_OF_DAWN_Q, false);
}
}
me->SetVisible(false); // respawns another Darion for quest turn in
me->SummonCreature(NPC_HIGHLORD_DARION_MOGRAINE, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 180000);
JumpToNextStep(1000);
break;
case 72:
SetHoldState(false); // Escort ends
JumpToNextStep(25000);
break;
case 73:
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKoltiraGUID))
temp->DespawnOrUnsummon();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiOrbazGUID))
temp->DespawnOrUnsummon();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiThassarianGUID))
temp->DespawnOrUnsummon();
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID))
temp->DespawnOrUnsummon();
me->DespawnOrUnsummon();
break;
}
} else uiPhase_timer -= diff;
}
// ******* During battle *****************************************************************
else
{
if (uiAnti_magic_zone <= diff)
{
DoCast(me, SPELL_ANTI_MAGIC_ZONE1);
uiAnti_magic_zone = urand(25000, 30000);
} else uiAnti_magic_zone -= diff;
if (uiDeath_strike <= diff)
{
DoCastVictim(SPELL_DEATH_STRIKE);
uiDeath_strike = urand(5000, 10000);
} else uiDeath_strike -= diff;
if (uiDeath_embrace <= diff)
{
DoCastVictim(SPELL_DEATH_EMBRACE);
uiDeath_embrace = urand(5000, 10000);
} else uiDeath_embrace -= diff;
if (uiIcy_touch <= diff)
{
DoCastVictim(SPELL_ICY_TOUCH1);
uiIcy_touch = urand(5000, 10000);
} else uiIcy_touch -= diff;
if (uiUnholy_blight <= diff)
{
DoCastVictim(SPELL_UNHOLY_BLIGHT);
uiUnholy_blight = urand(5000, 10000);
} else uiUnholy_blight -= diff;
if (uiFight_speech <= diff)
{
Talk(SAY_LIGHT_OF_DAWN09);
uiFight_speech = urand(15000, 20000);
} else uiFight_speech -= diff;
// Check spawns
if (uiSpawncheck <= diff)
{
SpawnNPC();
uiSpawncheck = 1000;
} else uiSpawncheck -= diff;
// Check targets
if (uiTargetcheck <= diff)
{
for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i)
NPCChangeTarget(uiGhoulGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_WARRIOR_NUMBER; ++i)
NPCChangeTarget(uiWarriorGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_ABOMINATION_NUMBER; ++i)
NPCChangeTarget(uiAbominationGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_BEHEMOTH_NUMBER; ++i)
NPCChangeTarget(uiBehemothGUID[i]);
NPCChangeTarget(uiKoltiraGUID);
NPCChangeTarget(uiOrbazGUID);
NPCChangeTarget(uiThassarianGUID);
uiTargetcheck = 10000;
} else uiTargetcheck -= diff;
// Battle end
if (uiFight_duration <= diff + 5000)
{
if (!uiTirionGUID)
if (Creature* temp = me->SummonCreature(NPC_HIGHLORD_TIRION_FORDRING, LightofDawnLoc[0].GetPositionWithOffset({ 0.0f, 0.0f, 0.0f, 1.528f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 600000))
{
temp->setFaction(me->getFaction());
temp->SetVirtualItem(0, uint32(EQUIP_UNEQUIP));
temp->AI()->Talk(SAY_LIGHT_OF_DAWN25);
uiTirionGUID = temp->GetGUID();
}
}
if (uiFight_duration <= diff)
{
bIsBattle = false;
uiFight_duration = 300000;
if (me->HasAura(SPELL_THE_MIGHT_OF_MOGRAINE))
me->RemoveAurasDueToSpell(SPELL_THE_MIGHT_OF_MOGRAINE);
me->RemoveAllAuras();
me->DeleteThreatList();
me->CombatStop(true);
me->InterruptNonMeleeSpells(false);
me->SetWalk(false);
for (uint8 i = 0; i < ENCOUNTER_DEFENDER_NUMBER; ++i)
DespawnNPC(uiDefenderGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_EARTHSHATTER_NUMBER; ++i)
DespawnNPC(uiEarthshatterGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_ABOMINATION_NUMBER; ++i)
DespawnNPC(uiAbominationGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_BEHEMOTH_NUMBER; ++i)
DespawnNPC(uiBehemothGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i)
DespawnNPC(uiGhoulGUID[i]);
for (uint8 i = 0; i < ENCOUNTER_WARRIOR_NUMBER; ++i)
DespawnNPC(uiWarriorGUID[i]);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID))
{
temp->RemoveAllAuras();
temp->DeleteThreatList();
temp->CombatStop(true);
temp->AttackStop();
temp->setFaction(me->getFaction());
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[9]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID))
{
temp->RemoveAllAuras();
temp->DeleteThreatList();
temp->CombatStop(true);
temp->AttackStop();
temp->setFaction(me->getFaction());
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[12]);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEligorGUID))
{
temp->RemoveAllAuras();
temp->DeleteThreatList();
temp->CombatStop(true);
temp->AttackStop();
temp->setFaction(me->getFaction());
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[15]);
}
DespawnNPC(uiRayneGUID);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKoltiraGUID))
{
temp->RemoveAllAuras();
temp->DeleteThreatList();
temp->CombatStop(true);
temp->AttackStop();
temp->setFaction(me->getFaction());
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[18]);
temp->CastSpell(temp, SPELL_THE_LIGHT_OF_DAWN, false);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiOrbazGUID))
temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN04);
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiThassarianGUID))
{
temp->RemoveAllAuras();
temp->DeleteThreatList();
temp->CombatStop(true);
temp->AttackStop();
temp->setFaction(me->getFaction());
temp->SetWalk(false);
temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[20]);
temp->CastSpell(temp, SPELL_THE_LIGHT_OF_DAWN, false);
}
if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID))
temp->AI()->Talk(SAY_LIGHT_OF_DAWN26);
SetHoldState(false);
} else uiFight_duration -= diff;
DoMeleeAttackIfReady();
}
}
void JumpToNextStep(uint32 uiTimer)
{
uiPhase_timer = uiTimer;
++uiStep;
}
void NPCChangeTarget(ObjectGuid ui_GUID)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, ui_GUID))
if (temp->IsAlive())
if (Unit* pTarger = SelectTarget(SELECT_TARGET_RANDOM, 0))
if (pTarger->IsAlive())
{
// temp->DeleteThreatList();
temp->AddThreat(pTarger, 0.0f);
temp->AI()->AttackStart(pTarger);
temp->SetInCombatWith(pTarger);
pTarger->SetInCombatWith(temp);
// temp->GetMotionMaster()->MoveChase(pTarger, 20.0f);
}
}
void SpawnNPC()
{
Unit* temp = NULL;
// Death
for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i)
{
temp = ObjectAccessor::GetCreature(*me, uiGhoulGUID[i]);
if (!temp)
{
temp = me->SummonCreature(NPC_ACHERUS_GHOUL, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->setFaction(2084);
uiGhoulGUID[i] = temp->GetGUID();
}
}
for (uint8 i = 0; i < ENCOUNTER_ABOMINATION_NUMBER; ++i)
{
temp = ObjectAccessor::GetCreature(*me, uiAbominationGUID[i]);
if (!temp)
{
temp = me->SummonCreature(NPC_WARRIOR_OF_THE_FROZEN_WASTES, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->setFaction(2084);
uiAbominationGUID[i] = temp->GetGUID();
}
}
for (uint8 i = 0; i < ENCOUNTER_WARRIOR_NUMBER; ++i)
{
temp = ObjectAccessor::GetCreature(*me, uiWarriorGUID[i]);
if (!temp)
{
temp = me->SummonCreature(NPC_RAMPAGING_ABOMINATION, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->setFaction(2084);
uiWarriorGUID[i] = temp->GetGUID();
}
}
for (uint8 i = 0; i < ENCOUNTER_BEHEMOTH_NUMBER; ++i)
{
temp = ObjectAccessor::GetCreature(*me, uiBehemothGUID[i]);
if (!temp)
{
temp = me->SummonCreature(NPC_FLESH_BEHEMOTH, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->setFaction(2084);
uiBehemothGUID[i] = temp->GetGUID();
}
}
// Dawn
for (uint8 i = 0; i < ENCOUNTER_DEFENDER_NUMBER; ++i)
{
temp = ObjectAccessor::GetCreature(*me, uiDefenderGUID[i]);
if (!temp)
{
temp = me->SummonCreature(NPC_DEFENDER_OF_THE_LIGHT, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->setFaction(2089);
me->AddThreat(temp, 0.0f);
uiDefenderGUID[i] = temp->GetGUID();
}
}
for (uint8 i = 0; i < ENCOUNTER_EARTHSHATTER_NUMBER; ++i)
{
temp = ObjectAccessor::GetCreature(*me, uiEarthshatterGUID[i]);
if (!temp)
{
temp = me->SummonCreature(NPC_RIMBLAT_EARTHSHATTER, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->setFaction(2089);
me->AddThreat(temp, 0.0f);
uiEarthshatterGUID[i] = temp->GetGUID();
}
}
temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID);
if (!temp)
{
temp = me->SummonCreature(NPC_KORFAX_CHAMPION_OF_THE_LIGHT, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 600000);
temp->setFaction(2089);
me->AddThreat(temp, 0.0f);
uiKorfaxGUID = temp->GetGUID();
}
temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID);
if (!temp)
{
temp = me->SummonCreature(NPC_LORD_MAXWELL_TYROSUS, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 600000);
temp->setFaction(2089);
me->AddThreat(temp, 0.0f);
uiMaxwellGUID = temp->GetGUID();
}
temp = ObjectAccessor::GetCreature(*me, uiEligorGUID);
if (!temp)
{
temp = me->SummonCreature(NPC_COMMANDER_ELIGOR_DAWNBRINGER, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 600000);
temp->setFaction(2089);
me->AddThreat(temp, 0.0f);
uiEligorGUID = temp->GetGUID();
}
temp = ObjectAccessor::GetCreature(*me, uiRayneGUID);
if (!temp)
{
temp = me->SummonCreature(NPC_RAYNE, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 30), float(rand32() % 30), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 300000);
temp->setFaction(2089);
me->AddThreat(temp, 0.0f);
uiRayneGUID = temp->GetGUID();
}
}
void DespawnNPC(ObjectGuid pGUID)
{
if (Creature* temp = ObjectAccessor::GetCreature(*me, pGUID))
if (temp->IsAlive())
{
temp->SetVisible(false);
temp->Kill(temp);
}
}
};
};
/*######
## npc the lich king in dawn of light
######*/
class npc_the_lich_king_tirion_dawn : public CreatureScript
{
public:
npc_the_lich_king_tirion_dawn() : CreatureScript("npc_the_lich_king_tirion_dawn") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_the_lich_king_tirion_dawnAI(creature);
}
struct npc_the_lich_king_tirion_dawnAI : public ScriptedAI
{
npc_the_lich_king_tirion_dawnAI(Creature* creature) : ScriptedAI(creature) { Reset(); }
void Reset() override { }
void AttackStart(Unit* /*who*/) override { } // very sample, just don't make them aggreesive
void UpdateAI(uint32 /*diff*/) override { }
void JustDied(Unit* /*killer*/) override { }
};
};
void AddSC_the_scarlet_enclave_c5()
{
new npc_highlord_darion_mograine();
new npc_the_lich_king_tirion_dawn();
}
| gpl-2.0 |
Rockman18/kernel-lgnas | net/bluetooth/bnep/sock.c | 799 | 5683 | /*
BNEP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2001-2002 Inventel Systemes
Written 2001-2002 by
David Libault <david.libault@inventel.fr>
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.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;
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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/ioctl.h>
#include <linux/file.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/gfp.h>
#include <net/sock.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include "bnep.h"
static int bnep_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
BT_DBG("sock %p sk %p", sock, sk);
if (!sk)
return 0;
sock_orphan(sk);
sock_put(sk);
return 0;
}
static int bnep_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct bnep_connlist_req cl;
struct bnep_connadd_req ca;
struct bnep_conndel_req cd;
struct bnep_conninfo ci;
struct socket *nsock;
void __user *argp = (void __user *)arg;
int err;
BT_DBG("cmd %x arg %lx", cmd, arg);
switch (cmd) {
case BNEPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
nsock = sockfd_lookup(ca.sock, &err);
if (!nsock)
return err;
if (nsock->sk->sk_state != BT_CONNECTED) {
sockfd_put(nsock);
return -EBADFD;
}
err = bnep_add_connection(&ca, nsock);
if (!err) {
if (copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
} else
sockfd_put(nsock);
return err;
case BNEPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return bnep_del_connection(&cd);
case BNEPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = bnep_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case BNEPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = bnep_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
default:
return -EINVAL;
}
return 0;
}
#ifdef CONFIG_COMPAT
static int bnep_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
if (cmd == BNEPGETCONNLIST) {
struct bnep_connlist_req cl;
uint32_t uci;
int err;
if (get_user(cl.cnum, (uint32_t __user *) arg) ||
get_user(uci, (u32 __user *) (arg + 4)))
return -EFAULT;
cl.ci = compat_ptr(uci);
if (cl.cnum <= 0)
return -EINVAL;
err = bnep_get_connlist(&cl);
if (!err && put_user(cl.cnum, (uint32_t __user *) arg))
err = -EFAULT;
return err;
}
return bnep_sock_ioctl(sock, cmd, arg);
}
#endif
static const struct proto_ops bnep_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = bnep_sock_release,
.ioctl = bnep_sock_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = bnep_sock_compat_ioctl,
#endif
.bind = sock_no_bind,
.getname = sock_no_getname,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.poll = sock_no_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static struct proto bnep_proto = {
.name = "BNEP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct bt_sock)
};
static int bnep_sock_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &bnep_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->ops = &bnep_sock_ops;
sock->state = SS_UNCONNECTED;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sk->sk_state = BT_OPEN;
return 0;
}
static const struct net_proto_family bnep_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = bnep_sock_create
};
int __init bnep_sock_init(void)
{
int err;
err = proto_register(&bnep_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_BNEP, &bnep_sock_family_ops);
if (err < 0)
goto error;
return 0;
error:
BT_ERR("Can't register BNEP socket");
proto_unregister(&bnep_proto);
return err;
}
void __exit bnep_sock_cleanup(void)
{
if (bt_sock_unregister(BTPROTO_BNEP) < 0)
BT_ERR("Can't unregister BNEP socket");
proto_unregister(&bnep_proto);
}
| gpl-2.0 |
elelinux/hero_kernel | net/bluetooth/bnep/sock.c | 799 | 5683 | /*
BNEP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2001-2002 Inventel Systemes
Written 2001-2002 by
David Libault <david.libault@inventel.fr>
Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.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;
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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/ioctl.h>
#include <linux/file.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/gfp.h>
#include <net/sock.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include "bnep.h"
static int bnep_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
BT_DBG("sock %p sk %p", sock, sk);
if (!sk)
return 0;
sock_orphan(sk);
sock_put(sk);
return 0;
}
static int bnep_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct bnep_connlist_req cl;
struct bnep_connadd_req ca;
struct bnep_conndel_req cd;
struct bnep_conninfo ci;
struct socket *nsock;
void __user *argp = (void __user *)arg;
int err;
BT_DBG("cmd %x arg %lx", cmd, arg);
switch (cmd) {
case BNEPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
nsock = sockfd_lookup(ca.sock, &err);
if (!nsock)
return err;
if (nsock->sk->sk_state != BT_CONNECTED) {
sockfd_put(nsock);
return -EBADFD;
}
err = bnep_add_connection(&ca, nsock);
if (!err) {
if (copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
} else
sockfd_put(nsock);
return err;
case BNEPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EACCES;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return bnep_del_connection(&cd);
case BNEPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = bnep_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case BNEPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = bnep_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
default:
return -EINVAL;
}
return 0;
}
#ifdef CONFIG_COMPAT
static int bnep_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
if (cmd == BNEPGETCONNLIST) {
struct bnep_connlist_req cl;
uint32_t uci;
int err;
if (get_user(cl.cnum, (uint32_t __user *) arg) ||
get_user(uci, (u32 __user *) (arg + 4)))
return -EFAULT;
cl.ci = compat_ptr(uci);
if (cl.cnum <= 0)
return -EINVAL;
err = bnep_get_connlist(&cl);
if (!err && put_user(cl.cnum, (uint32_t __user *) arg))
err = -EFAULT;
return err;
}
return bnep_sock_ioctl(sock, cmd, arg);
}
#endif
static const struct proto_ops bnep_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = bnep_sock_release,
.ioctl = bnep_sock_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = bnep_sock_compat_ioctl,
#endif
.bind = sock_no_bind,
.getname = sock_no_getname,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.poll = sock_no_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static struct proto bnep_proto = {
.name = "BNEP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct bt_sock)
};
static int bnep_sock_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &bnep_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->ops = &bnep_sock_ops;
sock->state = SS_UNCONNECTED;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sk->sk_state = BT_OPEN;
return 0;
}
static const struct net_proto_family bnep_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = bnep_sock_create
};
int __init bnep_sock_init(void)
{
int err;
err = proto_register(&bnep_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_BNEP, &bnep_sock_family_ops);
if (err < 0)
goto error;
return 0;
error:
BT_ERR("Can't register BNEP socket");
proto_unregister(&bnep_proto);
return err;
}
void __exit bnep_sock_cleanup(void)
{
if (bt_sock_unregister(BTPROTO_BNEP) < 0)
BT_ERR("Can't unregister BNEP socket");
proto_unregister(&bnep_proto);
}
| gpl-2.0 |
Foxda-Tech/argo8-kernel | drivers/net/ethernet/broadcom/bnx2x/bnx2x_stats.c | 2079 | 62385 | /* bnx2x_stats.c: Broadcom Everest network driver.
*
* Copyright (c) 2007-2013 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.
*
* Maintained by: Eilon Greenstein <eilong@broadcom.com>
* Written by: Eliezer Tamir
* Based on code from Michael Chan's bnx2 driver
* UDP CSUM errata workaround by Arik Gendelman
* Slowpath and fastpath rework by Vladislav Zolotarov
* Statistics and Link management by Yitchak Gertner
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "bnx2x_stats.h"
#include "bnx2x_cmn.h"
#include "bnx2x_sriov.h"
/* Statistics */
/*
* General service functions
*/
static inline long bnx2x_hilo(u32 *hiref)
{
u32 lo = *(hiref + 1);
#if (BITS_PER_LONG == 64)
u32 hi = *hiref;
return HILO_U64(hi, lo);
#else
return lo;
#endif
}
static inline u16 bnx2x_get_port_stats_dma_len(struct bnx2x *bp)
{
u16 res = 0;
/* 'newest' convention - shmem2 cotains the size of the port stats */
if (SHMEM2_HAS(bp, sizeof_port_stats)) {
u32 size = SHMEM2_RD(bp, sizeof_port_stats);
if (size)
res = size;
/* prevent newer BC from causing buffer overflow */
if (res > sizeof(struct host_port_stats))
res = sizeof(struct host_port_stats);
}
/* Older convention - all BCs support the port stats' fields up until
* the 'not_used' field
*/
if (!res) {
res = offsetof(struct host_port_stats, not_used) + 4;
/* if PFC stats are supported by the MFW, DMA them as well */
if (bp->flags & BC_SUPPORTS_PFC_STATS) {
res += offsetof(struct host_port_stats,
pfc_frames_rx_lo) -
offsetof(struct host_port_stats,
pfc_frames_tx_hi) + 4 ;
}
}
res >>= 2;
WARN_ON(res > 2 * DMAE_LEN32_RD_MAX);
return res;
}
/*
* Init service functions
*/
static void bnx2x_dp_stats(struct bnx2x *bp)
{
int i;
DP(BNX2X_MSG_STATS, "dumping stats:\n"
"fw_stats_req\n"
" hdr\n"
" cmd_num %d\n"
" reserved0 %d\n"
" drv_stats_counter %d\n"
" reserved1 %d\n"
" stats_counters_addrs %x %x\n",
bp->fw_stats_req->hdr.cmd_num,
bp->fw_stats_req->hdr.reserved0,
bp->fw_stats_req->hdr.drv_stats_counter,
bp->fw_stats_req->hdr.reserved1,
bp->fw_stats_req->hdr.stats_counters_addrs.hi,
bp->fw_stats_req->hdr.stats_counters_addrs.lo);
for (i = 0; i < bp->fw_stats_req->hdr.cmd_num; i++) {
DP(BNX2X_MSG_STATS,
"query[%d]\n"
" kind %d\n"
" index %d\n"
" funcID %d\n"
" reserved %d\n"
" address %x %x\n",
i, bp->fw_stats_req->query[i].kind,
bp->fw_stats_req->query[i].index,
bp->fw_stats_req->query[i].funcID,
bp->fw_stats_req->query[i].reserved,
bp->fw_stats_req->query[i].address.hi,
bp->fw_stats_req->query[i].address.lo);
}
}
/* Post the next statistics ramrod. Protect it with the spin in
* order to ensure the strict order between statistics ramrods
* (each ramrod has a sequence number passed in a
* bp->fw_stats_req->hdr.drv_stats_counter and ramrods must be
* sent in order).
*/
static void bnx2x_storm_stats_post(struct bnx2x *bp)
{
if (!bp->stats_pending) {
int rc;
spin_lock_bh(&bp->stats_lock);
if (bp->stats_pending) {
spin_unlock_bh(&bp->stats_lock);
return;
}
bp->fw_stats_req->hdr.drv_stats_counter =
cpu_to_le16(bp->stats_counter++);
DP(BNX2X_MSG_STATS, "Sending statistics ramrod %d\n",
bp->fw_stats_req->hdr.drv_stats_counter);
/* adjust the ramrod to include VF queues statistics */
bnx2x_iov_adjust_stats_req(bp);
bnx2x_dp_stats(bp);
/* send FW stats ramrod */
rc = bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_STAT_QUERY, 0,
U64_HI(bp->fw_stats_req_mapping),
U64_LO(bp->fw_stats_req_mapping),
NONE_CONNECTION_TYPE);
if (rc == 0)
bp->stats_pending = 1;
spin_unlock_bh(&bp->stats_lock);
}
}
static void bnx2x_hw_stats_post(struct bnx2x *bp)
{
struct dmae_command *dmae = &bp->stats_dmae;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
*stats_comp = DMAE_COMP_VAL;
if (CHIP_REV_IS_SLOW(bp))
return;
/* Update MCP's statistics if possible */
if (bp->func_stx)
memcpy(bnx2x_sp(bp, func_stats), &bp->func_stats,
sizeof(bp->func_stats));
/* loader */
if (bp->executer_idx) {
int loader_idx = PMF_DMAE_C(bp);
u32 opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_PCI, DMAE_DST_GRC,
true, DMAE_COMP_GRC);
opcode = bnx2x_dmae_opcode_clr_src_reset(opcode);
memset(dmae, 0, sizeof(struct dmae_command));
dmae->opcode = opcode;
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, dmae[0]));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, dmae[0]));
dmae->dst_addr_lo = (DMAE_REG_CMD_MEM +
sizeof(struct dmae_command) *
(loader_idx + 1)) >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct dmae_command) >> 2;
if (CHIP_IS_E1(bp))
dmae->len--;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx + 1] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
*stats_comp = 0;
bnx2x_post_dmae(bp, dmae, loader_idx);
} else if (bp->func_stx) {
*stats_comp = 0;
bnx2x_post_dmae(bp, dmae, INIT_DMAE_C(bp));
}
}
static int bnx2x_stats_comp(struct bnx2x *bp)
{
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
int cnt = 10;
might_sleep();
while (*stats_comp != DMAE_COMP_VAL) {
if (!cnt) {
BNX2X_ERR("timeout waiting for stats finished\n");
break;
}
cnt--;
usleep_range(1000, 2000);
}
return 1;
}
/*
* Statistics service functions
*/
static void bnx2x_stats_pmf_update(struct bnx2x *bp)
{
struct dmae_command *dmae;
u32 opcode;
int loader_idx = PMF_DMAE_C(bp);
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->port.pmf || !bp->port.port_stx) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_GRC, DMAE_DST_PCI, false, 0);
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = bnx2x_dmae_opcode_add_comp(opcode, DMAE_COMP_GRC);
dmae->src_addr_lo = bp->port.port_stx >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->len = DMAE_LEN32_RD_MAX;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = bnx2x_dmae_opcode_add_comp(opcode, DMAE_COMP_PCI);
dmae->src_addr_lo = (bp->port.port_stx >> 2) + DMAE_LEN32_RD_MAX;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats) +
DMAE_LEN32_RD_MAX * 4);
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats) +
DMAE_LEN32_RD_MAX * 4);
dmae->len = bnx2x_get_port_stats_dma_len(bp) - DMAE_LEN32_RD_MAX;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
static void bnx2x_port_stats_init(struct bnx2x *bp)
{
struct dmae_command *dmae;
int port = BP_PORT(bp);
u32 opcode;
int loader_idx = PMF_DMAE_C(bp);
u32 mac_addr;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->link_vars.link_up || !bp->port.pmf) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
/* MCP */
opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_PCI, DMAE_DST_GRC,
true, DMAE_COMP_GRC);
if (bp->port.port_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_lo = bp->port.port_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = bnx2x_get_port_stats_dma_len(bp);
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
}
if (bp->func_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, func_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, func_stats));
dmae->dst_addr_lo = bp->func_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_func_stats) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
}
/* MAC */
opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_GRC, DMAE_DST_PCI,
true, DMAE_COMP_GRC);
/* EMAC is special */
if (bp->link_vars.mac_type == MAC_TYPE_EMAC) {
mac_addr = (port ? GRCBASE_EMAC1 : GRCBASE_EMAC0);
/* EMAC_REG_EMAC_RX_STAT_AC (EMAC_REG_EMAC_RX_STAT_AC_COUNT)*/
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
EMAC_REG_EMAC_RX_STAT_AC) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats));
dmae->len = EMAC_REG_EMAC_RX_STAT_AC_COUNT;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
/* EMAC_REG_EMAC_RX_STAT_AC_28 */
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
EMAC_REG_EMAC_RX_STAT_AC_28) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, rx_stat_falsecarriererrors));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, rx_stat_falsecarriererrors));
dmae->len = 1;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
/* EMAC_REG_EMAC_TX_STAT_AC (EMAC_REG_EMAC_TX_STAT_AC_COUNT)*/
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
EMAC_REG_EMAC_TX_STAT_AC) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, tx_stat_ifhcoutoctets));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, tx_stat_ifhcoutoctets));
dmae->len = EMAC_REG_EMAC_TX_STAT_AC_COUNT;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
} else {
u32 tx_src_addr_lo, rx_src_addr_lo;
u16 rx_len, tx_len;
/* configure the params according to MAC type */
switch (bp->link_vars.mac_type) {
case MAC_TYPE_BMAC:
mac_addr = (port ? NIG_REG_INGRESS_BMAC1_MEM :
NIG_REG_INGRESS_BMAC0_MEM);
/* BIGMAC_REGISTER_TX_STAT_GTPKT ..
BIGMAC_REGISTER_TX_STAT_GTBYT */
if (CHIP_IS_E1x(bp)) {
tx_src_addr_lo = (mac_addr +
BIGMAC_REGISTER_TX_STAT_GTPKT) >> 2;
tx_len = (8 + BIGMAC_REGISTER_TX_STAT_GTBYT -
BIGMAC_REGISTER_TX_STAT_GTPKT) >> 2;
rx_src_addr_lo = (mac_addr +
BIGMAC_REGISTER_RX_STAT_GR64) >> 2;
rx_len = (8 + BIGMAC_REGISTER_RX_STAT_GRIPJ -
BIGMAC_REGISTER_RX_STAT_GR64) >> 2;
} else {
tx_src_addr_lo = (mac_addr +
BIGMAC2_REGISTER_TX_STAT_GTPOK) >> 2;
tx_len = (8 + BIGMAC2_REGISTER_TX_STAT_GTBYT -
BIGMAC2_REGISTER_TX_STAT_GTPOK) >> 2;
rx_src_addr_lo = (mac_addr +
BIGMAC2_REGISTER_RX_STAT_GR64) >> 2;
rx_len = (8 + BIGMAC2_REGISTER_RX_STAT_GRIPJ -
BIGMAC2_REGISTER_RX_STAT_GR64) >> 2;
}
break;
case MAC_TYPE_UMAC: /* handled by MSTAT */
case MAC_TYPE_XMAC: /* handled by MSTAT */
default:
mac_addr = port ? GRCBASE_MSTAT1 : GRCBASE_MSTAT0;
tx_src_addr_lo = (mac_addr +
MSTAT_REG_TX_STAT_GTXPOK_LO) >> 2;
rx_src_addr_lo = (mac_addr +
MSTAT_REG_RX_STAT_GR64_LO) >> 2;
tx_len = sizeof(bp->slowpath->
mac_stats.mstat_stats.stats_tx) >> 2;
rx_len = sizeof(bp->slowpath->
mac_stats.mstat_stats.stats_rx) >> 2;
break;
}
/* TX stats */
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = tx_src_addr_lo;
dmae->src_addr_hi = 0;
dmae->len = tx_len;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats));
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
/* RX stats */
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_hi = 0;
dmae->src_addr_lo = rx_src_addr_lo;
dmae->dst_addr_lo =
U64_LO(bnx2x_sp_mapping(bp, mac_stats) + (tx_len << 2));
dmae->dst_addr_hi =
U64_HI(bnx2x_sp_mapping(bp, mac_stats) + (tx_len << 2));
dmae->len = rx_len;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
}
/* NIG */
if (!CHIP_IS_E3(bp)) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (port ? NIG_REG_STAT1_EGRESS_MAC_PKT0 :
NIG_REG_STAT0_EGRESS_MAC_PKT0) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt0_lo));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt0_lo));
dmae->len = (2*sizeof(u32)) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (port ? NIG_REG_STAT1_EGRESS_MAC_PKT1 :
NIG_REG_STAT0_EGRESS_MAC_PKT1) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt1_lo));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt1_lo));
dmae->len = (2*sizeof(u32)) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
}
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_GRC, DMAE_DST_PCI,
true, DMAE_COMP_PCI);
dmae->src_addr_lo = (port ? NIG_REG_STAT1_BRB_DISCARD :
NIG_REG_STAT0_BRB_DISCARD) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, nig_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, nig_stats));
dmae->len = (sizeof(struct nig_stats) - 4*sizeof(u32)) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
static void bnx2x_func_stats_init(struct bnx2x *bp)
{
struct dmae_command *dmae = &bp->stats_dmae;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->func_stx) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
memset(dmae, 0, sizeof(struct dmae_command));
dmae->opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_PCI, DMAE_DST_GRC,
true, DMAE_COMP_PCI);
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, func_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, func_stats));
dmae->dst_addr_lo = bp->func_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_func_stats) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
static void bnx2x_stats_start(struct bnx2x *bp)
{
/* vfs travel through here as part of the statistics FSM, but no action
* is required
*/
if (IS_VF(bp))
return;
if (bp->port.pmf)
bnx2x_port_stats_init(bp);
else if (bp->func_stx)
bnx2x_func_stats_init(bp);
bnx2x_hw_stats_post(bp);
bnx2x_storm_stats_post(bp);
}
static void bnx2x_stats_pmf_start(struct bnx2x *bp)
{
bnx2x_stats_comp(bp);
bnx2x_stats_pmf_update(bp);
bnx2x_stats_start(bp);
}
static void bnx2x_stats_restart(struct bnx2x *bp)
{
/* vfs travel through here as part of the statistics FSM, but no action
* is required
*/
if (IS_VF(bp))
return;
bnx2x_stats_comp(bp);
bnx2x_stats_start(bp);
}
static void bnx2x_bmac_stats_update(struct bnx2x *bp)
{
struct host_port_stats *pstats = bnx2x_sp(bp, port_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct {
u32 lo;
u32 hi;
} diff;
if (CHIP_IS_E1x(bp)) {
struct bmac1_stats *new = bnx2x_sp(bp, mac_stats.bmac1_stats);
/* the macros below will use "bmac1_stats" type */
UPDATE_STAT64(rx_stat_grerb, rx_stat_ifhcinbadoctets);
UPDATE_STAT64(rx_stat_grfcs, rx_stat_dot3statsfcserrors);
UPDATE_STAT64(rx_stat_grund, rx_stat_etherstatsundersizepkts);
UPDATE_STAT64(rx_stat_grovr, rx_stat_dot3statsframestoolong);
UPDATE_STAT64(rx_stat_grfrg, rx_stat_etherstatsfragments);
UPDATE_STAT64(rx_stat_grjbr, rx_stat_etherstatsjabbers);
UPDATE_STAT64(rx_stat_grxcf, rx_stat_maccontrolframesreceived);
UPDATE_STAT64(rx_stat_grxpf, rx_stat_xoffstateentered);
UPDATE_STAT64(rx_stat_grxpf, rx_stat_mac_xpf);
UPDATE_STAT64(tx_stat_gtxpf, tx_stat_outxoffsent);
UPDATE_STAT64(tx_stat_gtxpf, tx_stat_flowcontroldone);
UPDATE_STAT64(tx_stat_gt64, tx_stat_etherstatspkts64octets);
UPDATE_STAT64(tx_stat_gt127,
tx_stat_etherstatspkts65octetsto127octets);
UPDATE_STAT64(tx_stat_gt255,
tx_stat_etherstatspkts128octetsto255octets);
UPDATE_STAT64(tx_stat_gt511,
tx_stat_etherstatspkts256octetsto511octets);
UPDATE_STAT64(tx_stat_gt1023,
tx_stat_etherstatspkts512octetsto1023octets);
UPDATE_STAT64(tx_stat_gt1518,
tx_stat_etherstatspkts1024octetsto1522octets);
UPDATE_STAT64(tx_stat_gt2047, tx_stat_mac_2047);
UPDATE_STAT64(tx_stat_gt4095, tx_stat_mac_4095);
UPDATE_STAT64(tx_stat_gt9216, tx_stat_mac_9216);
UPDATE_STAT64(tx_stat_gt16383, tx_stat_mac_16383);
UPDATE_STAT64(tx_stat_gterr,
tx_stat_dot3statsinternalmactransmiterrors);
UPDATE_STAT64(tx_stat_gtufl, tx_stat_mac_ufl);
} else {
struct bmac2_stats *new = bnx2x_sp(bp, mac_stats.bmac2_stats);
/* the macros below will use "bmac2_stats" type */
UPDATE_STAT64(rx_stat_grerb, rx_stat_ifhcinbadoctets);
UPDATE_STAT64(rx_stat_grfcs, rx_stat_dot3statsfcserrors);
UPDATE_STAT64(rx_stat_grund, rx_stat_etherstatsundersizepkts);
UPDATE_STAT64(rx_stat_grovr, rx_stat_dot3statsframestoolong);
UPDATE_STAT64(rx_stat_grfrg, rx_stat_etherstatsfragments);
UPDATE_STAT64(rx_stat_grjbr, rx_stat_etherstatsjabbers);
UPDATE_STAT64(rx_stat_grxcf, rx_stat_maccontrolframesreceived);
UPDATE_STAT64(rx_stat_grxpf, rx_stat_xoffstateentered);
UPDATE_STAT64(rx_stat_grxpf, rx_stat_mac_xpf);
UPDATE_STAT64(tx_stat_gtxpf, tx_stat_outxoffsent);
UPDATE_STAT64(tx_stat_gtxpf, tx_stat_flowcontroldone);
UPDATE_STAT64(tx_stat_gt64, tx_stat_etherstatspkts64octets);
UPDATE_STAT64(tx_stat_gt127,
tx_stat_etherstatspkts65octetsto127octets);
UPDATE_STAT64(tx_stat_gt255,
tx_stat_etherstatspkts128octetsto255octets);
UPDATE_STAT64(tx_stat_gt511,
tx_stat_etherstatspkts256octetsto511octets);
UPDATE_STAT64(tx_stat_gt1023,
tx_stat_etherstatspkts512octetsto1023octets);
UPDATE_STAT64(tx_stat_gt1518,
tx_stat_etherstatspkts1024octetsto1522octets);
UPDATE_STAT64(tx_stat_gt2047, tx_stat_mac_2047);
UPDATE_STAT64(tx_stat_gt4095, tx_stat_mac_4095);
UPDATE_STAT64(tx_stat_gt9216, tx_stat_mac_9216);
UPDATE_STAT64(tx_stat_gt16383, tx_stat_mac_16383);
UPDATE_STAT64(tx_stat_gterr,
tx_stat_dot3statsinternalmactransmiterrors);
UPDATE_STAT64(tx_stat_gtufl, tx_stat_mac_ufl);
/* collect PFC stats */
pstats->pfc_frames_tx_hi = new->tx_stat_gtpp_hi;
pstats->pfc_frames_tx_lo = new->tx_stat_gtpp_lo;
pstats->pfc_frames_rx_hi = new->rx_stat_grpp_hi;
pstats->pfc_frames_rx_lo = new->rx_stat_grpp_lo;
}
estats->pause_frames_received_hi =
pstats->mac_stx[1].rx_stat_mac_xpf_hi;
estats->pause_frames_received_lo =
pstats->mac_stx[1].rx_stat_mac_xpf_lo;
estats->pause_frames_sent_hi =
pstats->mac_stx[1].tx_stat_outxoffsent_hi;
estats->pause_frames_sent_lo =
pstats->mac_stx[1].tx_stat_outxoffsent_lo;
estats->pfc_frames_received_hi =
pstats->pfc_frames_rx_hi;
estats->pfc_frames_received_lo =
pstats->pfc_frames_rx_lo;
estats->pfc_frames_sent_hi =
pstats->pfc_frames_tx_hi;
estats->pfc_frames_sent_lo =
pstats->pfc_frames_tx_lo;
}
static void bnx2x_mstat_stats_update(struct bnx2x *bp)
{
struct host_port_stats *pstats = bnx2x_sp(bp, port_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct mstat_stats *new = bnx2x_sp(bp, mac_stats.mstat_stats);
ADD_STAT64(stats_rx.rx_grerb, rx_stat_ifhcinbadoctets);
ADD_STAT64(stats_rx.rx_grfcs, rx_stat_dot3statsfcserrors);
ADD_STAT64(stats_rx.rx_grund, rx_stat_etherstatsundersizepkts);
ADD_STAT64(stats_rx.rx_grovr, rx_stat_dot3statsframestoolong);
ADD_STAT64(stats_rx.rx_grfrg, rx_stat_etherstatsfragments);
ADD_STAT64(stats_rx.rx_grxcf, rx_stat_maccontrolframesreceived);
ADD_STAT64(stats_rx.rx_grxpf, rx_stat_xoffstateentered);
ADD_STAT64(stats_rx.rx_grxpf, rx_stat_mac_xpf);
ADD_STAT64(stats_tx.tx_gtxpf, tx_stat_outxoffsent);
ADD_STAT64(stats_tx.tx_gtxpf, tx_stat_flowcontroldone);
/* collect pfc stats */
ADD_64(pstats->pfc_frames_tx_hi, new->stats_tx.tx_gtxpp_hi,
pstats->pfc_frames_tx_lo, new->stats_tx.tx_gtxpp_lo);
ADD_64(pstats->pfc_frames_rx_hi, new->stats_rx.rx_grxpp_hi,
pstats->pfc_frames_rx_lo, new->stats_rx.rx_grxpp_lo);
ADD_STAT64(stats_tx.tx_gt64, tx_stat_etherstatspkts64octets);
ADD_STAT64(stats_tx.tx_gt127,
tx_stat_etherstatspkts65octetsto127octets);
ADD_STAT64(stats_tx.tx_gt255,
tx_stat_etherstatspkts128octetsto255octets);
ADD_STAT64(stats_tx.tx_gt511,
tx_stat_etherstatspkts256octetsto511octets);
ADD_STAT64(stats_tx.tx_gt1023,
tx_stat_etherstatspkts512octetsto1023octets);
ADD_STAT64(stats_tx.tx_gt1518,
tx_stat_etherstatspkts1024octetsto1522octets);
ADD_STAT64(stats_tx.tx_gt2047, tx_stat_mac_2047);
ADD_STAT64(stats_tx.tx_gt4095, tx_stat_mac_4095);
ADD_STAT64(stats_tx.tx_gt9216, tx_stat_mac_9216);
ADD_STAT64(stats_tx.tx_gt16383, tx_stat_mac_16383);
ADD_STAT64(stats_tx.tx_gterr,
tx_stat_dot3statsinternalmactransmiterrors);
ADD_STAT64(stats_tx.tx_gtufl, tx_stat_mac_ufl);
estats->etherstatspkts1024octetsto1522octets_hi =
pstats->mac_stx[1].tx_stat_etherstatspkts1024octetsto1522octets_hi;
estats->etherstatspkts1024octetsto1522octets_lo =
pstats->mac_stx[1].tx_stat_etherstatspkts1024octetsto1522octets_lo;
estats->etherstatspktsover1522octets_hi =
pstats->mac_stx[1].tx_stat_mac_2047_hi;
estats->etherstatspktsover1522octets_lo =
pstats->mac_stx[1].tx_stat_mac_2047_lo;
ADD_64(estats->etherstatspktsover1522octets_hi,
pstats->mac_stx[1].tx_stat_mac_4095_hi,
estats->etherstatspktsover1522octets_lo,
pstats->mac_stx[1].tx_stat_mac_4095_lo);
ADD_64(estats->etherstatspktsover1522octets_hi,
pstats->mac_stx[1].tx_stat_mac_9216_hi,
estats->etherstatspktsover1522octets_lo,
pstats->mac_stx[1].tx_stat_mac_9216_lo);
ADD_64(estats->etherstatspktsover1522octets_hi,
pstats->mac_stx[1].tx_stat_mac_16383_hi,
estats->etherstatspktsover1522octets_lo,
pstats->mac_stx[1].tx_stat_mac_16383_lo);
estats->pause_frames_received_hi =
pstats->mac_stx[1].rx_stat_mac_xpf_hi;
estats->pause_frames_received_lo =
pstats->mac_stx[1].rx_stat_mac_xpf_lo;
estats->pause_frames_sent_hi =
pstats->mac_stx[1].tx_stat_outxoffsent_hi;
estats->pause_frames_sent_lo =
pstats->mac_stx[1].tx_stat_outxoffsent_lo;
estats->pfc_frames_received_hi =
pstats->pfc_frames_rx_hi;
estats->pfc_frames_received_lo =
pstats->pfc_frames_rx_lo;
estats->pfc_frames_sent_hi =
pstats->pfc_frames_tx_hi;
estats->pfc_frames_sent_lo =
pstats->pfc_frames_tx_lo;
}
static void bnx2x_emac_stats_update(struct bnx2x *bp)
{
struct emac_stats *new = bnx2x_sp(bp, mac_stats.emac_stats);
struct host_port_stats *pstats = bnx2x_sp(bp, port_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
UPDATE_EXTEND_STAT(rx_stat_ifhcinbadoctets);
UPDATE_EXTEND_STAT(tx_stat_ifhcoutbadoctets);
UPDATE_EXTEND_STAT(rx_stat_dot3statsfcserrors);
UPDATE_EXTEND_STAT(rx_stat_dot3statsalignmenterrors);
UPDATE_EXTEND_STAT(rx_stat_dot3statscarriersenseerrors);
UPDATE_EXTEND_STAT(rx_stat_falsecarriererrors);
UPDATE_EXTEND_STAT(rx_stat_etherstatsundersizepkts);
UPDATE_EXTEND_STAT(rx_stat_dot3statsframestoolong);
UPDATE_EXTEND_STAT(rx_stat_etherstatsfragments);
UPDATE_EXTEND_STAT(rx_stat_etherstatsjabbers);
UPDATE_EXTEND_STAT(rx_stat_maccontrolframesreceived);
UPDATE_EXTEND_STAT(rx_stat_xoffstateentered);
UPDATE_EXTEND_STAT(rx_stat_xonpauseframesreceived);
UPDATE_EXTEND_STAT(rx_stat_xoffpauseframesreceived);
UPDATE_EXTEND_STAT(tx_stat_outxonsent);
UPDATE_EXTEND_STAT(tx_stat_outxoffsent);
UPDATE_EXTEND_STAT(tx_stat_flowcontroldone);
UPDATE_EXTEND_STAT(tx_stat_etherstatscollisions);
UPDATE_EXTEND_STAT(tx_stat_dot3statssinglecollisionframes);
UPDATE_EXTEND_STAT(tx_stat_dot3statsmultiplecollisionframes);
UPDATE_EXTEND_STAT(tx_stat_dot3statsdeferredtransmissions);
UPDATE_EXTEND_STAT(tx_stat_dot3statsexcessivecollisions);
UPDATE_EXTEND_STAT(tx_stat_dot3statslatecollisions);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts64octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts65octetsto127octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts128octetsto255octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts256octetsto511octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts512octetsto1023octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts1024octetsto1522octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspktsover1522octets);
UPDATE_EXTEND_STAT(tx_stat_dot3statsinternalmactransmiterrors);
estats->pause_frames_received_hi =
pstats->mac_stx[1].rx_stat_xonpauseframesreceived_hi;
estats->pause_frames_received_lo =
pstats->mac_stx[1].rx_stat_xonpauseframesreceived_lo;
ADD_64(estats->pause_frames_received_hi,
pstats->mac_stx[1].rx_stat_xoffpauseframesreceived_hi,
estats->pause_frames_received_lo,
pstats->mac_stx[1].rx_stat_xoffpauseframesreceived_lo);
estats->pause_frames_sent_hi =
pstats->mac_stx[1].tx_stat_outxonsent_hi;
estats->pause_frames_sent_lo =
pstats->mac_stx[1].tx_stat_outxonsent_lo;
ADD_64(estats->pause_frames_sent_hi,
pstats->mac_stx[1].tx_stat_outxoffsent_hi,
estats->pause_frames_sent_lo,
pstats->mac_stx[1].tx_stat_outxoffsent_lo);
}
static int bnx2x_hw_stats_update(struct bnx2x *bp)
{
struct nig_stats *new = bnx2x_sp(bp, nig_stats);
struct nig_stats *old = &(bp->port.old_nig_stats);
struct host_port_stats *pstats = bnx2x_sp(bp, port_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct {
u32 lo;
u32 hi;
} diff;
switch (bp->link_vars.mac_type) {
case MAC_TYPE_BMAC:
bnx2x_bmac_stats_update(bp);
break;
case MAC_TYPE_EMAC:
bnx2x_emac_stats_update(bp);
break;
case MAC_TYPE_UMAC:
case MAC_TYPE_XMAC:
bnx2x_mstat_stats_update(bp);
break;
case MAC_TYPE_NONE: /* unreached */
DP(BNX2X_MSG_STATS,
"stats updated by DMAE but no MAC active\n");
return -1;
default: /* unreached */
BNX2X_ERR("Unknown MAC type\n");
}
ADD_EXTEND_64(pstats->brb_drop_hi, pstats->brb_drop_lo,
new->brb_discard - old->brb_discard);
ADD_EXTEND_64(estats->brb_truncate_hi, estats->brb_truncate_lo,
new->brb_truncate - old->brb_truncate);
if (!CHIP_IS_E3(bp)) {
UPDATE_STAT64_NIG(egress_mac_pkt0,
etherstatspkts1024octetsto1522octets);
UPDATE_STAT64_NIG(egress_mac_pkt1,
etherstatspktsover1522octets);
}
memcpy(old, new, sizeof(struct nig_stats));
memcpy(&(estats->rx_stat_ifhcinbadoctets_hi), &(pstats->mac_stx[1]),
sizeof(struct mac_stx));
estats->brb_drop_hi = pstats->brb_drop_hi;
estats->brb_drop_lo = pstats->brb_drop_lo;
pstats->host_port_stats_counter++;
if (CHIP_IS_E3(bp)) {
u32 lpi_reg = BP_PORT(bp) ? MISC_REG_CPMU_LP_SM_ENT_CNT_P1
: MISC_REG_CPMU_LP_SM_ENT_CNT_P0;
estats->eee_tx_lpi += REG_RD(bp, lpi_reg);
}
if (!BP_NOMCP(bp)) {
u32 nig_timer_max =
SHMEM_RD(bp, port_mb[BP_PORT(bp)].stat_nig_timer);
if (nig_timer_max != estats->nig_timer_max) {
estats->nig_timer_max = nig_timer_max;
BNX2X_ERR("NIG timer max (%u)\n",
estats->nig_timer_max);
}
}
return 0;
}
static int bnx2x_storm_stats_validate_counters(struct bnx2x *bp)
{
struct stats_counter *counters = &bp->fw_stats_data->storm_counters;
u16 cur_stats_counter;
/* Make sure we use the value of the counter
* used for sending the last stats ramrod.
*/
spin_lock_bh(&bp->stats_lock);
cur_stats_counter = bp->stats_counter - 1;
spin_unlock_bh(&bp->stats_lock);
/* are storm stats valid? */
if (le16_to_cpu(counters->xstats_counter) != cur_stats_counter) {
DP(BNX2X_MSG_STATS,
"stats not updated by xstorm xstorm counter (0x%x) != stats_counter (0x%x)\n",
le16_to_cpu(counters->xstats_counter), bp->stats_counter);
return -EAGAIN;
}
if (le16_to_cpu(counters->ustats_counter) != cur_stats_counter) {
DP(BNX2X_MSG_STATS,
"stats not updated by ustorm ustorm counter (0x%x) != stats_counter (0x%x)\n",
le16_to_cpu(counters->ustats_counter), bp->stats_counter);
return -EAGAIN;
}
if (le16_to_cpu(counters->cstats_counter) != cur_stats_counter) {
DP(BNX2X_MSG_STATS,
"stats not updated by cstorm cstorm counter (0x%x) != stats_counter (0x%x)\n",
le16_to_cpu(counters->cstats_counter), bp->stats_counter);
return -EAGAIN;
}
if (le16_to_cpu(counters->tstats_counter) != cur_stats_counter) {
DP(BNX2X_MSG_STATS,
"stats not updated by tstorm tstorm counter (0x%x) != stats_counter (0x%x)\n",
le16_to_cpu(counters->tstats_counter), bp->stats_counter);
return -EAGAIN;
}
return 0;
}
static int bnx2x_storm_stats_update(struct bnx2x *bp)
{
struct tstorm_per_port_stats *tport =
&bp->fw_stats_data->port.tstorm_port_statistics;
struct tstorm_per_pf_stats *tfunc =
&bp->fw_stats_data->pf.tstorm_pf_statistics;
struct host_func_stats *fstats = &bp->func_stats;
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct bnx2x_eth_stats_old *estats_old = &bp->eth_stats_old;
int i;
/* vfs stat counter is managed by pf */
if (IS_PF(bp) && bnx2x_storm_stats_validate_counters(bp))
return -EAGAIN;
estats->error_bytes_received_hi = 0;
estats->error_bytes_received_lo = 0;
for_each_eth_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
struct tstorm_per_queue_stats *tclient =
&bp->fw_stats_data->queue_stats[i].
tstorm_queue_statistics;
struct tstorm_per_queue_stats *old_tclient =
&bnx2x_fp_stats(bp, fp)->old_tclient;
struct ustorm_per_queue_stats *uclient =
&bp->fw_stats_data->queue_stats[i].
ustorm_queue_statistics;
struct ustorm_per_queue_stats *old_uclient =
&bnx2x_fp_stats(bp, fp)->old_uclient;
struct xstorm_per_queue_stats *xclient =
&bp->fw_stats_data->queue_stats[i].
xstorm_queue_statistics;
struct xstorm_per_queue_stats *old_xclient =
&bnx2x_fp_stats(bp, fp)->old_xclient;
struct bnx2x_eth_q_stats *qstats =
&bnx2x_fp_stats(bp, fp)->eth_q_stats;
struct bnx2x_eth_q_stats_old *qstats_old =
&bnx2x_fp_stats(bp, fp)->eth_q_stats_old;
u32 diff;
DP(BNX2X_MSG_STATS, "queue[%d]: ucast_sent 0x%x, bcast_sent 0x%x mcast_sent 0x%x\n",
i, xclient->ucast_pkts_sent,
xclient->bcast_pkts_sent, xclient->mcast_pkts_sent);
DP(BNX2X_MSG_STATS, "---------------\n");
UPDATE_QSTAT(tclient->rcv_bcast_bytes,
total_broadcast_bytes_received);
UPDATE_QSTAT(tclient->rcv_mcast_bytes,
total_multicast_bytes_received);
UPDATE_QSTAT(tclient->rcv_ucast_bytes,
total_unicast_bytes_received);
/*
* sum to total_bytes_received all
* unicast/multicast/broadcast
*/
qstats->total_bytes_received_hi =
qstats->total_broadcast_bytes_received_hi;
qstats->total_bytes_received_lo =
qstats->total_broadcast_bytes_received_lo;
ADD_64(qstats->total_bytes_received_hi,
qstats->total_multicast_bytes_received_hi,
qstats->total_bytes_received_lo,
qstats->total_multicast_bytes_received_lo);
ADD_64(qstats->total_bytes_received_hi,
qstats->total_unicast_bytes_received_hi,
qstats->total_bytes_received_lo,
qstats->total_unicast_bytes_received_lo);
qstats->valid_bytes_received_hi =
qstats->total_bytes_received_hi;
qstats->valid_bytes_received_lo =
qstats->total_bytes_received_lo;
UPDATE_EXTEND_TSTAT(rcv_ucast_pkts,
total_unicast_packets_received);
UPDATE_EXTEND_TSTAT(rcv_mcast_pkts,
total_multicast_packets_received);
UPDATE_EXTEND_TSTAT(rcv_bcast_pkts,
total_broadcast_packets_received);
UPDATE_EXTEND_E_TSTAT(pkts_too_big_discard,
etherstatsoverrsizepkts, 32);
UPDATE_EXTEND_E_TSTAT(no_buff_discard, no_buff_discard, 16);
SUB_EXTEND_USTAT(ucast_no_buff_pkts,
total_unicast_packets_received);
SUB_EXTEND_USTAT(mcast_no_buff_pkts,
total_multicast_packets_received);
SUB_EXTEND_USTAT(bcast_no_buff_pkts,
total_broadcast_packets_received);
UPDATE_EXTEND_E_USTAT(ucast_no_buff_pkts, no_buff_discard);
UPDATE_EXTEND_E_USTAT(mcast_no_buff_pkts, no_buff_discard);
UPDATE_EXTEND_E_USTAT(bcast_no_buff_pkts, no_buff_discard);
UPDATE_QSTAT(xclient->bcast_bytes_sent,
total_broadcast_bytes_transmitted);
UPDATE_QSTAT(xclient->mcast_bytes_sent,
total_multicast_bytes_transmitted);
UPDATE_QSTAT(xclient->ucast_bytes_sent,
total_unicast_bytes_transmitted);
/*
* sum to total_bytes_transmitted all
* unicast/multicast/broadcast
*/
qstats->total_bytes_transmitted_hi =
qstats->total_unicast_bytes_transmitted_hi;
qstats->total_bytes_transmitted_lo =
qstats->total_unicast_bytes_transmitted_lo;
ADD_64(qstats->total_bytes_transmitted_hi,
qstats->total_broadcast_bytes_transmitted_hi,
qstats->total_bytes_transmitted_lo,
qstats->total_broadcast_bytes_transmitted_lo);
ADD_64(qstats->total_bytes_transmitted_hi,
qstats->total_multicast_bytes_transmitted_hi,
qstats->total_bytes_transmitted_lo,
qstats->total_multicast_bytes_transmitted_lo);
UPDATE_EXTEND_XSTAT(ucast_pkts_sent,
total_unicast_packets_transmitted);
UPDATE_EXTEND_XSTAT(mcast_pkts_sent,
total_multicast_packets_transmitted);
UPDATE_EXTEND_XSTAT(bcast_pkts_sent,
total_broadcast_packets_transmitted);
UPDATE_EXTEND_TSTAT(checksum_discard,
total_packets_received_checksum_discarded);
UPDATE_EXTEND_TSTAT(ttl0_discard,
total_packets_received_ttl0_discarded);
UPDATE_EXTEND_XSTAT(error_drop_pkts,
total_transmitted_dropped_packets_error);
/* TPA aggregations completed */
UPDATE_EXTEND_E_USTAT(coalesced_events, total_tpa_aggregations);
/* Number of network frames aggregated by TPA */
UPDATE_EXTEND_E_USTAT(coalesced_pkts,
total_tpa_aggregated_frames);
/* Total number of bytes in completed TPA aggregations */
UPDATE_QSTAT(uclient->coalesced_bytes, total_tpa_bytes);
UPDATE_ESTAT_QSTAT_64(total_tpa_bytes);
UPDATE_FSTAT_QSTAT(total_bytes_received);
UPDATE_FSTAT_QSTAT(total_bytes_transmitted);
UPDATE_FSTAT_QSTAT(total_unicast_packets_received);
UPDATE_FSTAT_QSTAT(total_multicast_packets_received);
UPDATE_FSTAT_QSTAT(total_broadcast_packets_received);
UPDATE_FSTAT_QSTAT(total_unicast_packets_transmitted);
UPDATE_FSTAT_QSTAT(total_multicast_packets_transmitted);
UPDATE_FSTAT_QSTAT(total_broadcast_packets_transmitted);
UPDATE_FSTAT_QSTAT(valid_bytes_received);
}
ADD_64(estats->total_bytes_received_hi,
estats->rx_stat_ifhcinbadoctets_hi,
estats->total_bytes_received_lo,
estats->rx_stat_ifhcinbadoctets_lo);
ADD_64_LE(estats->total_bytes_received_hi,
tfunc->rcv_error_bytes.hi,
estats->total_bytes_received_lo,
tfunc->rcv_error_bytes.lo);
ADD_64_LE(estats->error_bytes_received_hi,
tfunc->rcv_error_bytes.hi,
estats->error_bytes_received_lo,
tfunc->rcv_error_bytes.lo);
UPDATE_ESTAT(etherstatsoverrsizepkts, rx_stat_dot3statsframestoolong);
ADD_64(estats->error_bytes_received_hi,
estats->rx_stat_ifhcinbadoctets_hi,
estats->error_bytes_received_lo,
estats->rx_stat_ifhcinbadoctets_lo);
if (bp->port.pmf) {
struct bnx2x_fw_port_stats_old *fwstats = &bp->fw_stats_old;
UPDATE_FW_STAT(mac_filter_discard);
UPDATE_FW_STAT(mf_tag_discard);
UPDATE_FW_STAT(brb_truncate_discard);
UPDATE_FW_STAT(mac_discard);
}
fstats->host_func_stats_start = ++fstats->host_func_stats_end;
bp->stats_pending = 0;
return 0;
}
static void bnx2x_net_stats_update(struct bnx2x *bp)
{
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct net_device_stats *nstats = &bp->dev->stats;
unsigned long tmp;
int i;
nstats->rx_packets =
bnx2x_hilo(&estats->total_unicast_packets_received_hi) +
bnx2x_hilo(&estats->total_multicast_packets_received_hi) +
bnx2x_hilo(&estats->total_broadcast_packets_received_hi);
nstats->tx_packets =
bnx2x_hilo(&estats->total_unicast_packets_transmitted_hi) +
bnx2x_hilo(&estats->total_multicast_packets_transmitted_hi) +
bnx2x_hilo(&estats->total_broadcast_packets_transmitted_hi);
nstats->rx_bytes = bnx2x_hilo(&estats->total_bytes_received_hi);
nstats->tx_bytes = bnx2x_hilo(&estats->total_bytes_transmitted_hi);
tmp = estats->mac_discard;
for_each_rx_queue(bp, i) {
struct tstorm_per_queue_stats *old_tclient =
&bp->fp_stats[i].old_tclient;
tmp += le32_to_cpu(old_tclient->checksum_discard);
}
nstats->rx_dropped = tmp + bp->net_stats_old.rx_dropped;
nstats->tx_dropped = 0;
nstats->multicast =
bnx2x_hilo(&estats->total_multicast_packets_received_hi);
nstats->collisions =
bnx2x_hilo(&estats->tx_stat_etherstatscollisions_hi);
nstats->rx_length_errors =
bnx2x_hilo(&estats->rx_stat_etherstatsundersizepkts_hi) +
bnx2x_hilo(&estats->etherstatsoverrsizepkts_hi);
nstats->rx_over_errors = bnx2x_hilo(&estats->brb_drop_hi) +
bnx2x_hilo(&estats->brb_truncate_hi);
nstats->rx_crc_errors =
bnx2x_hilo(&estats->rx_stat_dot3statsfcserrors_hi);
nstats->rx_frame_errors =
bnx2x_hilo(&estats->rx_stat_dot3statsalignmenterrors_hi);
nstats->rx_fifo_errors = bnx2x_hilo(&estats->no_buff_discard_hi);
nstats->rx_missed_errors = 0;
nstats->rx_errors = nstats->rx_length_errors +
nstats->rx_over_errors +
nstats->rx_crc_errors +
nstats->rx_frame_errors +
nstats->rx_fifo_errors +
nstats->rx_missed_errors;
nstats->tx_aborted_errors =
bnx2x_hilo(&estats->tx_stat_dot3statslatecollisions_hi) +
bnx2x_hilo(&estats->tx_stat_dot3statsexcessivecollisions_hi);
nstats->tx_carrier_errors =
bnx2x_hilo(&estats->rx_stat_dot3statscarriersenseerrors_hi);
nstats->tx_fifo_errors = 0;
nstats->tx_heartbeat_errors = 0;
nstats->tx_window_errors = 0;
nstats->tx_errors = nstats->tx_aborted_errors +
nstats->tx_carrier_errors +
bnx2x_hilo(&estats->tx_stat_dot3statsinternalmactransmiterrors_hi);
}
static void bnx2x_drv_stats_update(struct bnx2x *bp)
{
struct bnx2x_eth_stats *estats = &bp->eth_stats;
int i;
for_each_queue(bp, i) {
struct bnx2x_eth_q_stats *qstats = &bp->fp_stats[i].eth_q_stats;
struct bnx2x_eth_q_stats_old *qstats_old =
&bp->fp_stats[i].eth_q_stats_old;
UPDATE_ESTAT_QSTAT(driver_xoff);
UPDATE_ESTAT_QSTAT(rx_err_discard_pkt);
UPDATE_ESTAT_QSTAT(rx_skb_alloc_failed);
UPDATE_ESTAT_QSTAT(hw_csum_err);
UPDATE_ESTAT_QSTAT(driver_filtered_tx_pkt);
}
}
static bool bnx2x_edebug_stats_stopped(struct bnx2x *bp)
{
u32 val;
if (SHMEM2_HAS(bp, edebug_driver_if[1])) {
val = SHMEM2_RD(bp, edebug_driver_if[1]);
if (val == EDEBUG_DRIVER_IF_OP_CODE_DISABLE_STAT)
return true;
}
return false;
}
static void bnx2x_stats_update(struct bnx2x *bp)
{
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
if (bnx2x_edebug_stats_stopped(bp))
return;
if (IS_PF(bp)) {
if (*stats_comp != DMAE_COMP_VAL)
return;
if (bp->port.pmf)
bnx2x_hw_stats_update(bp);
if (bnx2x_storm_stats_update(bp)) {
if (bp->stats_pending++ == 3) {
BNX2X_ERR("storm stats were not updated for 3 times\n");
bnx2x_panic();
}
return;
}
} else {
/* vf doesn't collect HW statistics, and doesn't get completions
* perform only update
*/
bnx2x_storm_stats_update(bp);
}
bnx2x_net_stats_update(bp);
bnx2x_drv_stats_update(bp);
/* vf is done */
if (IS_VF(bp))
return;
if (netif_msg_timer(bp)) {
struct bnx2x_eth_stats *estats = &bp->eth_stats;
netdev_dbg(bp->dev, "brb drops %u brb truncate %u\n",
estats->brb_drop_lo, estats->brb_truncate_lo);
}
bnx2x_hw_stats_post(bp);
bnx2x_storm_stats_post(bp);
}
static void bnx2x_port_stats_stop(struct bnx2x *bp)
{
struct dmae_command *dmae;
u32 opcode;
int loader_idx = PMF_DMAE_C(bp);
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
bp->executer_idx = 0;
opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_PCI, DMAE_DST_GRC, false, 0);
if (bp->port.port_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
if (bp->func_stx)
dmae->opcode = bnx2x_dmae_opcode_add_comp(
opcode, DMAE_COMP_GRC);
else
dmae->opcode = bnx2x_dmae_opcode_add_comp(
opcode, DMAE_COMP_PCI);
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_lo = bp->port.port_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = bnx2x_get_port_stats_dma_len(bp);
if (bp->func_stx) {
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
} else {
dmae->comp_addr_lo =
U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi =
U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
}
if (bp->func_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode =
bnx2x_dmae_opcode_add_comp(opcode, DMAE_COMP_PCI);
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, func_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, func_stats));
dmae->dst_addr_lo = bp->func_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_func_stats) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
}
static void bnx2x_stats_stop(struct bnx2x *bp)
{
int update = 0;
bnx2x_stats_comp(bp);
if (bp->port.pmf)
update = (bnx2x_hw_stats_update(bp) == 0);
update |= (bnx2x_storm_stats_update(bp) == 0);
if (update) {
bnx2x_net_stats_update(bp);
if (bp->port.pmf)
bnx2x_port_stats_stop(bp);
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
}
static void bnx2x_stats_do_nothing(struct bnx2x *bp)
{
}
static const struct {
void (*action)(struct bnx2x *bp);
enum bnx2x_stats_state next_state;
} bnx2x_stats_stm[STATS_STATE_MAX][STATS_EVENT_MAX] = {
/* state event */
{
/* DISABLED PMF */ {bnx2x_stats_pmf_update, STATS_STATE_DISABLED},
/* LINK_UP */ {bnx2x_stats_start, STATS_STATE_ENABLED},
/* UPDATE */ {bnx2x_stats_do_nothing, STATS_STATE_DISABLED},
/* STOP */ {bnx2x_stats_do_nothing, STATS_STATE_DISABLED}
},
{
/* ENABLED PMF */ {bnx2x_stats_pmf_start, STATS_STATE_ENABLED},
/* LINK_UP */ {bnx2x_stats_restart, STATS_STATE_ENABLED},
/* UPDATE */ {bnx2x_stats_update, STATS_STATE_ENABLED},
/* STOP */ {bnx2x_stats_stop, STATS_STATE_DISABLED}
}
};
void bnx2x_stats_handle(struct bnx2x *bp, enum bnx2x_stats_event event)
{
enum bnx2x_stats_state state;
if (unlikely(bp->panic))
return;
spin_lock_bh(&bp->stats_lock);
state = bp->stats_state;
bp->stats_state = bnx2x_stats_stm[state][event].next_state;
spin_unlock_bh(&bp->stats_lock);
bnx2x_stats_stm[state][event].action(bp);
if ((event != STATS_EVENT_UPDATE) || netif_msg_timer(bp))
DP(BNX2X_MSG_STATS, "state %d -> event %d -> state %d\n",
state, event, bp->stats_state);
}
static void bnx2x_port_stats_base_init(struct bnx2x *bp)
{
struct dmae_command *dmae;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->port.pmf || !bp->port.port_stx) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = bnx2x_dmae_opcode(bp, DMAE_SRC_PCI, DMAE_DST_GRC,
true, DMAE_COMP_PCI);
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_lo = bp->port.port_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = bnx2x_get_port_stats_dma_len(bp);
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
/* This function will prepare the statistics ramrod data the way
* we will only have to increment the statistics counter and
* send the ramrod each time we have to.
*/
static void bnx2x_prep_fw_stats_req(struct bnx2x *bp)
{
int i;
int first_queue_query_index;
struct stats_query_header *stats_hdr = &bp->fw_stats_req->hdr;
dma_addr_t cur_data_offset;
struct stats_query_entry *cur_query_entry;
stats_hdr->cmd_num = bp->fw_stats_num;
stats_hdr->drv_stats_counter = 0;
/* storm_counters struct contains the counters of completed
* statistics requests per storm which are incremented by FW
* each time it completes hadning a statistics ramrod. We will
* check these counters in the timer handler and discard a
* (statistics) ramrod completion.
*/
cur_data_offset = bp->fw_stats_data_mapping +
offsetof(struct bnx2x_fw_stats_data, storm_counters);
stats_hdr->stats_counters_addrs.hi =
cpu_to_le32(U64_HI(cur_data_offset));
stats_hdr->stats_counters_addrs.lo =
cpu_to_le32(U64_LO(cur_data_offset));
/* prepare to the first stats ramrod (will be completed with
* the counters equal to zero) - init counters to somethig different.
*/
memset(&bp->fw_stats_data->storm_counters, 0xff,
sizeof(struct stats_counter));
/**** Port FW statistics data ****/
cur_data_offset = bp->fw_stats_data_mapping +
offsetof(struct bnx2x_fw_stats_data, port);
cur_query_entry = &bp->fw_stats_req->query[BNX2X_PORT_QUERY_IDX];
cur_query_entry->kind = STATS_TYPE_PORT;
/* For port query index is a DONT CARE */
cur_query_entry->index = BP_PORT(bp);
/* For port query funcID is a DONT CARE */
cur_query_entry->funcID = cpu_to_le16(BP_FUNC(bp));
cur_query_entry->address.hi = cpu_to_le32(U64_HI(cur_data_offset));
cur_query_entry->address.lo = cpu_to_le32(U64_LO(cur_data_offset));
/**** PF FW statistics data ****/
cur_data_offset = bp->fw_stats_data_mapping +
offsetof(struct bnx2x_fw_stats_data, pf);
cur_query_entry = &bp->fw_stats_req->query[BNX2X_PF_QUERY_IDX];
cur_query_entry->kind = STATS_TYPE_PF;
/* For PF query index is a DONT CARE */
cur_query_entry->index = BP_PORT(bp);
cur_query_entry->funcID = cpu_to_le16(BP_FUNC(bp));
cur_query_entry->address.hi = cpu_to_le32(U64_HI(cur_data_offset));
cur_query_entry->address.lo = cpu_to_le32(U64_LO(cur_data_offset));
/**** FCoE FW statistics data ****/
if (!NO_FCOE(bp)) {
cur_data_offset = bp->fw_stats_data_mapping +
offsetof(struct bnx2x_fw_stats_data, fcoe);
cur_query_entry =
&bp->fw_stats_req->query[BNX2X_FCOE_QUERY_IDX];
cur_query_entry->kind = STATS_TYPE_FCOE;
/* For FCoE query index is a DONT CARE */
cur_query_entry->index = BP_PORT(bp);
cur_query_entry->funcID = cpu_to_le16(BP_FUNC(bp));
cur_query_entry->address.hi =
cpu_to_le32(U64_HI(cur_data_offset));
cur_query_entry->address.lo =
cpu_to_le32(U64_LO(cur_data_offset));
}
/**** Clients' queries ****/
cur_data_offset = bp->fw_stats_data_mapping +
offsetof(struct bnx2x_fw_stats_data, queue_stats);
/* first queue query index depends whether FCoE offloaded request will
* be included in the ramrod
*/
if (!NO_FCOE(bp))
first_queue_query_index = BNX2X_FIRST_QUEUE_QUERY_IDX;
else
first_queue_query_index = BNX2X_FIRST_QUEUE_QUERY_IDX - 1;
for_each_eth_queue(bp, i) {
cur_query_entry =
&bp->fw_stats_req->
query[first_queue_query_index + i];
cur_query_entry->kind = STATS_TYPE_QUEUE;
cur_query_entry->index = bnx2x_stats_id(&bp->fp[i]);
cur_query_entry->funcID = cpu_to_le16(BP_FUNC(bp));
cur_query_entry->address.hi =
cpu_to_le32(U64_HI(cur_data_offset));
cur_query_entry->address.lo =
cpu_to_le32(U64_LO(cur_data_offset));
cur_data_offset += sizeof(struct per_queue_stats);
}
/* add FCoE queue query if needed */
if (!NO_FCOE(bp)) {
cur_query_entry =
&bp->fw_stats_req->
query[first_queue_query_index + i];
cur_query_entry->kind = STATS_TYPE_QUEUE;
cur_query_entry->index = bnx2x_stats_id(&bp->fp[FCOE_IDX(bp)]);
cur_query_entry->funcID = cpu_to_le16(BP_FUNC(bp));
cur_query_entry->address.hi =
cpu_to_le32(U64_HI(cur_data_offset));
cur_query_entry->address.lo =
cpu_to_le32(U64_LO(cur_data_offset));
}
}
void bnx2x_memset_stats(struct bnx2x *bp)
{
int i;
/* function stats */
for_each_queue(bp, i) {
struct bnx2x_fp_stats *fp_stats = &bp->fp_stats[i];
memset(&fp_stats->old_tclient, 0,
sizeof(fp_stats->old_tclient));
memset(&fp_stats->old_uclient, 0,
sizeof(fp_stats->old_uclient));
memset(&fp_stats->old_xclient, 0,
sizeof(fp_stats->old_xclient));
if (bp->stats_init) {
memset(&fp_stats->eth_q_stats, 0,
sizeof(fp_stats->eth_q_stats));
memset(&fp_stats->eth_q_stats_old, 0,
sizeof(fp_stats->eth_q_stats_old));
}
}
memset(&bp->dev->stats, 0, sizeof(bp->dev->stats));
if (bp->stats_init) {
memset(&bp->net_stats_old, 0, sizeof(bp->net_stats_old));
memset(&bp->fw_stats_old, 0, sizeof(bp->fw_stats_old));
memset(&bp->eth_stats_old, 0, sizeof(bp->eth_stats_old));
memset(&bp->eth_stats, 0, sizeof(bp->eth_stats));
memset(&bp->func_stats, 0, sizeof(bp->func_stats));
}
bp->stats_state = STATS_STATE_DISABLED;
if (bp->port.pmf && bp->port.port_stx)
bnx2x_port_stats_base_init(bp);
/* mark the end of statistics initializiation */
bp->stats_init = false;
}
void bnx2x_stats_init(struct bnx2x *bp)
{
int /*abs*/port = BP_PORT(bp);
int mb_idx = BP_FW_MB_IDX(bp);
bp->stats_pending = 0;
bp->executer_idx = 0;
bp->stats_counter = 0;
/* port and func stats for management */
if (!BP_NOMCP(bp)) {
bp->port.port_stx = SHMEM_RD(bp, port_mb[port].port_stx);
bp->func_stx = SHMEM_RD(bp, func_mb[mb_idx].fw_mb_param);
} else {
bp->port.port_stx = 0;
bp->func_stx = 0;
}
DP(BNX2X_MSG_STATS, "port_stx 0x%x func_stx 0x%x\n",
bp->port.port_stx, bp->func_stx);
/* pmf should retrieve port statistics from SP on a non-init*/
if (!bp->stats_init && bp->port.pmf && bp->port.port_stx)
bnx2x_stats_handle(bp, STATS_EVENT_PMF);
port = BP_PORT(bp);
/* port stats */
memset(&(bp->port.old_nig_stats), 0, sizeof(struct nig_stats));
bp->port.old_nig_stats.brb_discard =
REG_RD(bp, NIG_REG_STAT0_BRB_DISCARD + port*0x38);
bp->port.old_nig_stats.brb_truncate =
REG_RD(bp, NIG_REG_STAT0_BRB_TRUNCATE + port*0x38);
if (!CHIP_IS_E3(bp)) {
REG_RD_DMAE(bp, NIG_REG_STAT0_EGRESS_MAC_PKT0 + port*0x50,
&(bp->port.old_nig_stats.egress_mac_pkt0_lo), 2);
REG_RD_DMAE(bp, NIG_REG_STAT0_EGRESS_MAC_PKT1 + port*0x50,
&(bp->port.old_nig_stats.egress_mac_pkt1_lo), 2);
}
/* Prepare statistics ramrod data */
bnx2x_prep_fw_stats_req(bp);
/* Clean SP from previous statistics */
if (bp->stats_init) {
if (bp->func_stx) {
memset(bnx2x_sp(bp, func_stats), 0,
sizeof(struct host_func_stats));
bnx2x_func_stats_init(bp);
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
}
bnx2x_memset_stats(bp);
}
void bnx2x_save_statistics(struct bnx2x *bp)
{
int i;
struct net_device_stats *nstats = &bp->dev->stats;
/* save queue statistics */
for_each_eth_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
struct bnx2x_eth_q_stats *qstats =
&bnx2x_fp_stats(bp, fp)->eth_q_stats;
struct bnx2x_eth_q_stats_old *qstats_old =
&bnx2x_fp_stats(bp, fp)->eth_q_stats_old;
UPDATE_QSTAT_OLD(total_unicast_bytes_received_hi);
UPDATE_QSTAT_OLD(total_unicast_bytes_received_lo);
UPDATE_QSTAT_OLD(total_broadcast_bytes_received_hi);
UPDATE_QSTAT_OLD(total_broadcast_bytes_received_lo);
UPDATE_QSTAT_OLD(total_multicast_bytes_received_hi);
UPDATE_QSTAT_OLD(total_multicast_bytes_received_lo);
UPDATE_QSTAT_OLD(total_unicast_bytes_transmitted_hi);
UPDATE_QSTAT_OLD(total_unicast_bytes_transmitted_lo);
UPDATE_QSTAT_OLD(total_broadcast_bytes_transmitted_hi);
UPDATE_QSTAT_OLD(total_broadcast_bytes_transmitted_lo);
UPDATE_QSTAT_OLD(total_multicast_bytes_transmitted_hi);
UPDATE_QSTAT_OLD(total_multicast_bytes_transmitted_lo);
UPDATE_QSTAT_OLD(total_tpa_bytes_hi);
UPDATE_QSTAT_OLD(total_tpa_bytes_lo);
}
/* save net_device_stats statistics */
bp->net_stats_old.rx_dropped = nstats->rx_dropped;
/* store port firmware statistics */
if (bp->port.pmf && IS_MF(bp)) {
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct bnx2x_fw_port_stats_old *fwstats = &bp->fw_stats_old;
UPDATE_FW_STAT_OLD(mac_filter_discard);
UPDATE_FW_STAT_OLD(mf_tag_discard);
UPDATE_FW_STAT_OLD(brb_truncate_discard);
UPDATE_FW_STAT_OLD(mac_discard);
}
}
void bnx2x_afex_collect_stats(struct bnx2x *bp, void *void_afex_stats,
u32 stats_type)
{
int i;
struct afex_stats *afex_stats = (struct afex_stats *)void_afex_stats;
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct per_queue_stats *fcoe_q_stats =
&bp->fw_stats_data->queue_stats[FCOE_IDX(bp)];
struct tstorm_per_queue_stats *fcoe_q_tstorm_stats =
&fcoe_q_stats->tstorm_queue_statistics;
struct ustorm_per_queue_stats *fcoe_q_ustorm_stats =
&fcoe_q_stats->ustorm_queue_statistics;
struct xstorm_per_queue_stats *fcoe_q_xstorm_stats =
&fcoe_q_stats->xstorm_queue_statistics;
struct fcoe_statistics_params *fw_fcoe_stat =
&bp->fw_stats_data->fcoe;
memset(afex_stats, 0, sizeof(struct afex_stats));
for_each_eth_queue(bp, i) {
struct bnx2x_eth_q_stats *qstats = &bp->fp_stats[i].eth_q_stats;
ADD_64(afex_stats->rx_unicast_bytes_hi,
qstats->total_unicast_bytes_received_hi,
afex_stats->rx_unicast_bytes_lo,
qstats->total_unicast_bytes_received_lo);
ADD_64(afex_stats->rx_broadcast_bytes_hi,
qstats->total_broadcast_bytes_received_hi,
afex_stats->rx_broadcast_bytes_lo,
qstats->total_broadcast_bytes_received_lo);
ADD_64(afex_stats->rx_multicast_bytes_hi,
qstats->total_multicast_bytes_received_hi,
afex_stats->rx_multicast_bytes_lo,
qstats->total_multicast_bytes_received_lo);
ADD_64(afex_stats->rx_unicast_frames_hi,
qstats->total_unicast_packets_received_hi,
afex_stats->rx_unicast_frames_lo,
qstats->total_unicast_packets_received_lo);
ADD_64(afex_stats->rx_broadcast_frames_hi,
qstats->total_broadcast_packets_received_hi,
afex_stats->rx_broadcast_frames_lo,
qstats->total_broadcast_packets_received_lo);
ADD_64(afex_stats->rx_multicast_frames_hi,
qstats->total_multicast_packets_received_hi,
afex_stats->rx_multicast_frames_lo,
qstats->total_multicast_packets_received_lo);
/* sum to rx_frames_discarded all discraded
* packets due to size, ttl0 and checksum
*/
ADD_64(afex_stats->rx_frames_discarded_hi,
qstats->total_packets_received_checksum_discarded_hi,
afex_stats->rx_frames_discarded_lo,
qstats->total_packets_received_checksum_discarded_lo);
ADD_64(afex_stats->rx_frames_discarded_hi,
qstats->total_packets_received_ttl0_discarded_hi,
afex_stats->rx_frames_discarded_lo,
qstats->total_packets_received_ttl0_discarded_lo);
ADD_64(afex_stats->rx_frames_discarded_hi,
qstats->etherstatsoverrsizepkts_hi,
afex_stats->rx_frames_discarded_lo,
qstats->etherstatsoverrsizepkts_lo);
ADD_64(afex_stats->rx_frames_dropped_hi,
qstats->no_buff_discard_hi,
afex_stats->rx_frames_dropped_lo,
qstats->no_buff_discard_lo);
ADD_64(afex_stats->tx_unicast_bytes_hi,
qstats->total_unicast_bytes_transmitted_hi,
afex_stats->tx_unicast_bytes_lo,
qstats->total_unicast_bytes_transmitted_lo);
ADD_64(afex_stats->tx_broadcast_bytes_hi,
qstats->total_broadcast_bytes_transmitted_hi,
afex_stats->tx_broadcast_bytes_lo,
qstats->total_broadcast_bytes_transmitted_lo);
ADD_64(afex_stats->tx_multicast_bytes_hi,
qstats->total_multicast_bytes_transmitted_hi,
afex_stats->tx_multicast_bytes_lo,
qstats->total_multicast_bytes_transmitted_lo);
ADD_64(afex_stats->tx_unicast_frames_hi,
qstats->total_unicast_packets_transmitted_hi,
afex_stats->tx_unicast_frames_lo,
qstats->total_unicast_packets_transmitted_lo);
ADD_64(afex_stats->tx_broadcast_frames_hi,
qstats->total_broadcast_packets_transmitted_hi,
afex_stats->tx_broadcast_frames_lo,
qstats->total_broadcast_packets_transmitted_lo);
ADD_64(afex_stats->tx_multicast_frames_hi,
qstats->total_multicast_packets_transmitted_hi,
afex_stats->tx_multicast_frames_lo,
qstats->total_multicast_packets_transmitted_lo);
ADD_64(afex_stats->tx_frames_dropped_hi,
qstats->total_transmitted_dropped_packets_error_hi,
afex_stats->tx_frames_dropped_lo,
qstats->total_transmitted_dropped_packets_error_lo);
}
/* now add FCoE statistics which are collected separately
* (both offloaded and non offloaded)
*/
if (!NO_FCOE(bp)) {
ADD_64_LE(afex_stats->rx_unicast_bytes_hi,
LE32_0,
afex_stats->rx_unicast_bytes_lo,
fw_fcoe_stat->rx_stat0.fcoe_rx_byte_cnt);
ADD_64_LE(afex_stats->rx_unicast_bytes_hi,
fcoe_q_tstorm_stats->rcv_ucast_bytes.hi,
afex_stats->rx_unicast_bytes_lo,
fcoe_q_tstorm_stats->rcv_ucast_bytes.lo);
ADD_64_LE(afex_stats->rx_broadcast_bytes_hi,
fcoe_q_tstorm_stats->rcv_bcast_bytes.hi,
afex_stats->rx_broadcast_bytes_lo,
fcoe_q_tstorm_stats->rcv_bcast_bytes.lo);
ADD_64_LE(afex_stats->rx_multicast_bytes_hi,
fcoe_q_tstorm_stats->rcv_mcast_bytes.hi,
afex_stats->rx_multicast_bytes_lo,
fcoe_q_tstorm_stats->rcv_mcast_bytes.lo);
ADD_64_LE(afex_stats->rx_unicast_frames_hi,
LE32_0,
afex_stats->rx_unicast_frames_lo,
fw_fcoe_stat->rx_stat0.fcoe_rx_pkt_cnt);
ADD_64_LE(afex_stats->rx_unicast_frames_hi,
LE32_0,
afex_stats->rx_unicast_frames_lo,
fcoe_q_tstorm_stats->rcv_ucast_pkts);
ADD_64_LE(afex_stats->rx_broadcast_frames_hi,
LE32_0,
afex_stats->rx_broadcast_frames_lo,
fcoe_q_tstorm_stats->rcv_bcast_pkts);
ADD_64_LE(afex_stats->rx_multicast_frames_hi,
LE32_0,
afex_stats->rx_multicast_frames_lo,
fcoe_q_tstorm_stats->rcv_ucast_pkts);
ADD_64_LE(afex_stats->rx_frames_discarded_hi,
LE32_0,
afex_stats->rx_frames_discarded_lo,
fcoe_q_tstorm_stats->checksum_discard);
ADD_64_LE(afex_stats->rx_frames_discarded_hi,
LE32_0,
afex_stats->rx_frames_discarded_lo,
fcoe_q_tstorm_stats->pkts_too_big_discard);
ADD_64_LE(afex_stats->rx_frames_discarded_hi,
LE32_0,
afex_stats->rx_frames_discarded_lo,
fcoe_q_tstorm_stats->ttl0_discard);
ADD_64_LE16(afex_stats->rx_frames_dropped_hi,
LE16_0,
afex_stats->rx_frames_dropped_lo,
fcoe_q_tstorm_stats->no_buff_discard);
ADD_64_LE(afex_stats->rx_frames_dropped_hi,
LE32_0,
afex_stats->rx_frames_dropped_lo,
fcoe_q_ustorm_stats->ucast_no_buff_pkts);
ADD_64_LE(afex_stats->rx_frames_dropped_hi,
LE32_0,
afex_stats->rx_frames_dropped_lo,
fcoe_q_ustorm_stats->mcast_no_buff_pkts);
ADD_64_LE(afex_stats->rx_frames_dropped_hi,
LE32_0,
afex_stats->rx_frames_dropped_lo,
fcoe_q_ustorm_stats->bcast_no_buff_pkts);
ADD_64_LE(afex_stats->rx_frames_dropped_hi,
LE32_0,
afex_stats->rx_frames_dropped_lo,
fw_fcoe_stat->rx_stat1.fcoe_rx_drop_pkt_cnt);
ADD_64_LE(afex_stats->rx_frames_dropped_hi,
LE32_0,
afex_stats->rx_frames_dropped_lo,
fw_fcoe_stat->rx_stat2.fcoe_rx_drop_pkt_cnt);
ADD_64_LE(afex_stats->tx_unicast_bytes_hi,
LE32_0,
afex_stats->tx_unicast_bytes_lo,
fw_fcoe_stat->tx_stat.fcoe_tx_byte_cnt);
ADD_64_LE(afex_stats->tx_unicast_bytes_hi,
fcoe_q_xstorm_stats->ucast_bytes_sent.hi,
afex_stats->tx_unicast_bytes_lo,
fcoe_q_xstorm_stats->ucast_bytes_sent.lo);
ADD_64_LE(afex_stats->tx_broadcast_bytes_hi,
fcoe_q_xstorm_stats->bcast_bytes_sent.hi,
afex_stats->tx_broadcast_bytes_lo,
fcoe_q_xstorm_stats->bcast_bytes_sent.lo);
ADD_64_LE(afex_stats->tx_multicast_bytes_hi,
fcoe_q_xstorm_stats->mcast_bytes_sent.hi,
afex_stats->tx_multicast_bytes_lo,
fcoe_q_xstorm_stats->mcast_bytes_sent.lo);
ADD_64_LE(afex_stats->tx_unicast_frames_hi,
LE32_0,
afex_stats->tx_unicast_frames_lo,
fw_fcoe_stat->tx_stat.fcoe_tx_pkt_cnt);
ADD_64_LE(afex_stats->tx_unicast_frames_hi,
LE32_0,
afex_stats->tx_unicast_frames_lo,
fcoe_q_xstorm_stats->ucast_pkts_sent);
ADD_64_LE(afex_stats->tx_broadcast_frames_hi,
LE32_0,
afex_stats->tx_broadcast_frames_lo,
fcoe_q_xstorm_stats->bcast_pkts_sent);
ADD_64_LE(afex_stats->tx_multicast_frames_hi,
LE32_0,
afex_stats->tx_multicast_frames_lo,
fcoe_q_xstorm_stats->mcast_pkts_sent);
ADD_64_LE(afex_stats->tx_frames_dropped_hi,
LE32_0,
afex_stats->tx_frames_dropped_lo,
fcoe_q_xstorm_stats->error_drop_pkts);
}
/* if port stats are requested, add them to the PMF
* stats, as anyway they will be accumulated by the
* MCP before sent to the switch
*/
if ((bp->port.pmf) && (stats_type == VICSTATST_UIF_INDEX)) {
ADD_64(afex_stats->rx_frames_dropped_hi,
0,
afex_stats->rx_frames_dropped_lo,
estats->mac_filter_discard);
ADD_64(afex_stats->rx_frames_dropped_hi,
0,
afex_stats->rx_frames_dropped_lo,
estats->brb_truncate_discard);
ADD_64(afex_stats->rx_frames_discarded_hi,
0,
afex_stats->rx_frames_discarded_lo,
estats->mac_discard);
}
}
| gpl-2.0 |
Clouded/linux-rt-rpi2 | drivers/net/ethernet/natsemi/xtsonic.c | 2079 | 8323 | /*
* xtsonic.c
*
* (C) 2001 - 2007 Tensilica Inc.
* Kevin Chea <kchea@yahoo.com>
* Marc Gauthier <marc@linux-xtensa.org>
* Chris Zankel <chris@zankel.net>
*
* (C) 1996,1998 by Thomas Bogendoerfer (tsbogend@alpha.franken.de)
*
* This driver is based on work from Andreas Busse, but most of
* the code is rewritten.
*
* (C) 1995 by Andreas Busse (andy@waldorf-gmbh.de)
*
* A driver for the onboard Sonic ethernet controller on the XT2000.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/gfp.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/dma.h>
static char xtsonic_string[] = "xtsonic";
extern unsigned xtboard_nvram_valid(void);
extern void xtboard_get_ether_addr(unsigned char *buf);
#include "sonic.h"
/*
* According to the documentation for the Sonic ethernet controller,
* EOBC should be 760 words (1520 bytes) for 32-bit applications, and,
* as such, 2 words less than the buffer size. The value for RBSIZE
* defined in sonic.h, however is only 1520.
*
* (Note that in 16-bit configurations, EOBC is 759 words (1518 bytes) and
* RBSIZE 1520 bytes)
*/
#undef SONIC_RBSIZE
#define SONIC_RBSIZE 1524
/*
* The chip provides 256 byte register space.
*/
#define SONIC_MEM_SIZE 0x100
/*
* Macros to access SONIC registers
*/
#define SONIC_READ(reg) \
(0xffff & *((volatile unsigned int *)dev->base_addr+reg))
#define SONIC_WRITE(reg,val) \
*((volatile unsigned int *)dev->base_addr+reg) = val
/* Use 0 for production, 1 for verification, and >2 for debug */
#ifdef SONIC_DEBUG
static unsigned int sonic_debug = SONIC_DEBUG;
#else
static unsigned int sonic_debug = 1;
#endif
/*
* We cannot use station (ethernet) address prefixes to detect the
* sonic controller since these are board manufacturer depended.
* So we check for known Silicon Revision IDs instead.
*/
static unsigned short known_revisions[] =
{
0x101, /* SONIC 83934 */
0xffff /* end of list */
};
static int xtsonic_open(struct net_device *dev)
{
int retval;
retval = request_irq(dev->irq, sonic_interrupt, 0, "sonic", dev);
if (retval) {
printk(KERN_ERR "%s: unable to get IRQ %d.\n",
dev->name, dev->irq);
return -EAGAIN;
}
retval = sonic_open(dev);
if (retval)
free_irq(dev->irq, dev);
return retval;
}
static int xtsonic_close(struct net_device *dev)
{
int err;
err = sonic_close(dev);
free_irq(dev->irq, dev);
return err;
}
static const struct net_device_ops xtsonic_netdev_ops = {
.ndo_open = xtsonic_open,
.ndo_stop = xtsonic_close,
.ndo_start_xmit = sonic_send_packet,
.ndo_get_stats = sonic_get_stats,
.ndo_set_rx_mode = sonic_multicast_list,
.ndo_tx_timeout = sonic_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
};
static int __init sonic_probe1(struct net_device *dev)
{
static unsigned version_printed = 0;
unsigned int silicon_revision;
struct sonic_local *lp = netdev_priv(dev);
unsigned int base_addr = dev->base_addr;
int i;
int err = 0;
if (!request_mem_region(base_addr, 0x100, xtsonic_string))
return -EBUSY;
/*
* get the Silicon Revision ID. If this is one of the known
* one assume that we found a SONIC ethernet controller at
* the expected location.
*/
silicon_revision = SONIC_READ(SONIC_SR);
if (sonic_debug > 1)
printk("SONIC Silicon Revision = 0x%04x\n",silicon_revision);
i = 0;
while ((known_revisions[i] != 0xffff) &&
(known_revisions[i] != silicon_revision))
i++;
if (known_revisions[i] == 0xffff) {
printk("SONIC ethernet controller not found (0x%4x)\n",
silicon_revision);
return -ENODEV;
}
if (sonic_debug && version_printed++ == 0)
printk(version);
/*
* Put the sonic into software reset, then retrieve ethernet address.
* Note: we are assuming that the boot-loader has initialized the cam.
*/
SONIC_WRITE(SONIC_CMD,SONIC_CR_RST);
SONIC_WRITE(SONIC_DCR,
SONIC_DCR_WC0|SONIC_DCR_DW|SONIC_DCR_LBR|SONIC_DCR_SBUS);
SONIC_WRITE(SONIC_CEP,0);
SONIC_WRITE(SONIC_IMR,0);
SONIC_WRITE(SONIC_CMD,SONIC_CR_RST);
SONIC_WRITE(SONIC_CEP,0);
for (i=0; i<3; i++) {
unsigned int val = SONIC_READ(SONIC_CAP0-i);
dev->dev_addr[i*2] = val;
dev->dev_addr[i*2+1] = val >> 8;
}
/* Initialize the device structure. */
lp->dma_bitmode = SONIC_BITMODE32;
/*
* Allocate local private descriptor areas in uncached space.
* The entire structure must be located within the same 64kb segment.
* A simple way to ensure this is to allocate twice the
* size of the structure -- given that the structure is
* much less than 64 kB, at least one of the halves of
* the allocated area will be contained entirely in 64 kB.
* We also allocate extra space for a pointer to allow freeing
* this structure later on (in xtsonic_cleanup_module()).
*/
lp->descriptors = dma_alloc_coherent(lp->device,
SIZEOF_SONIC_DESC *
SONIC_BUS_SCALE(lp->dma_bitmode),
&lp->descriptors_laddr,
GFP_KERNEL);
if (lp->descriptors == NULL) {
err = -ENOMEM;
goto out;
}
lp->cda = lp->descriptors;
lp->tda = lp->cda + (SIZEOF_SONIC_CDA
* SONIC_BUS_SCALE(lp->dma_bitmode));
lp->rda = lp->tda + (SIZEOF_SONIC_TD * SONIC_NUM_TDS
* SONIC_BUS_SCALE(lp->dma_bitmode));
lp->rra = lp->rda + (SIZEOF_SONIC_RD * SONIC_NUM_RDS
* SONIC_BUS_SCALE(lp->dma_bitmode));
/* get the virtual dma address */
lp->cda_laddr = lp->descriptors_laddr;
lp->tda_laddr = lp->cda_laddr + (SIZEOF_SONIC_CDA
* SONIC_BUS_SCALE(lp->dma_bitmode));
lp->rda_laddr = lp->tda_laddr + (SIZEOF_SONIC_TD * SONIC_NUM_TDS
* SONIC_BUS_SCALE(lp->dma_bitmode));
lp->rra_laddr = lp->rda_laddr + (SIZEOF_SONIC_RD * SONIC_NUM_RDS
* SONIC_BUS_SCALE(lp->dma_bitmode));
dev->netdev_ops = &xtsonic_netdev_ops;
dev->watchdog_timeo = TX_TIMEOUT;
/*
* clear tally counter
*/
SONIC_WRITE(SONIC_CRCT,0xffff);
SONIC_WRITE(SONIC_FAET,0xffff);
SONIC_WRITE(SONIC_MPT,0xffff);
return 0;
out:
release_region(dev->base_addr, SONIC_MEM_SIZE);
return err;
}
/*
* Probe for a SONIC ethernet controller on an XT2000 board.
* Actually probing is superfluous but we're paranoid.
*/
int xtsonic_probe(struct platform_device *pdev)
{
struct net_device *dev;
struct sonic_local *lp;
struct resource *resmem, *resirq;
int err = 0;
if ((resmem = platform_get_resource(pdev, IORESOURCE_MEM, 0)) == NULL)
return -ENODEV;
if ((resirq = platform_get_resource(pdev, IORESOURCE_IRQ, 0)) == NULL)
return -ENODEV;
if ((dev = alloc_etherdev(sizeof(struct sonic_local))) == NULL)
return -ENOMEM;
lp = netdev_priv(dev);
lp->device = &pdev->dev;
platform_set_drvdata(pdev, dev);
SET_NETDEV_DEV(dev, &pdev->dev);
netdev_boot_setup_check(dev);
dev->base_addr = resmem->start;
dev->irq = resirq->start;
if ((err = sonic_probe1(dev)))
goto out;
if ((err = register_netdev(dev)))
goto out1;
printk("%s: SONIC ethernet @%08lx, MAC %pM, IRQ %d\n", dev->name,
dev->base_addr, dev->dev_addr, dev->irq);
return 0;
out1:
release_region(dev->base_addr, SONIC_MEM_SIZE);
out:
free_netdev(dev);
return err;
}
MODULE_DESCRIPTION("Xtensa XT2000 SONIC ethernet driver");
module_param(sonic_debug, int, 0);
MODULE_PARM_DESC(sonic_debug, "xtsonic debug level (1-4)");
#include "sonic.c"
static int xtsonic_device_remove(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct sonic_local *lp = netdev_priv(dev);
unregister_netdev(dev);
dma_free_coherent(lp->device,
SIZEOF_SONIC_DESC * SONIC_BUS_SCALE(lp->dma_bitmode),
lp->descriptors, lp->descriptors_laddr);
release_region (dev->base_addr, SONIC_MEM_SIZE);
free_netdev(dev);
return 0;
}
static struct platform_driver xtsonic_driver = {
.probe = xtsonic_probe,
.remove = xtsonic_device_remove,
.driver = {
.name = xtsonic_string,
},
};
module_platform_driver(xtsonic_driver);
| gpl-2.0 |
sandymanu/android_kernel_xiaomi_kenzo | drivers/ide/ide-cd.c | 2079 | 46946 | /*
* ATAPI CD-ROM driver.
*
* Copyright (C) 1994-1996 Scott Snyder <snyder@fnald0.fnal.gov>
* Copyright (C) 1996-1998 Erik Andersen <andersee@debian.org>
* Copyright (C) 1998-2000 Jens Axboe <axboe@suse.de>
* Copyright (C) 2005, 2007-2009 Bartlomiej Zolnierkiewicz
*
* May be copied or modified under the terms of the GNU General Public
* License. See linux/COPYING for more information.
*
* See Documentation/cdrom/ide-cd for usage information.
*
* Suggestions are welcome. Patches that work are more welcome though. ;-)
*
* Documentation:
* Mt. Fuji (SFF8090 version 4) and ATAPI (SFF-8020i rev 2.6) standards.
*
* For historical changelog please see:
* Documentation/ide/ChangeLog.ide-cd.1994-2004
*/
#define DRV_NAME "ide-cd"
#define PFX DRV_NAME ": "
#define IDECD_VERSION "5.00"
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/cdrom.h>
#include <linux/ide.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/bcd.h>
/* For SCSI -> ATAPI command conversion */
#include <scsi/scsi.h>
#include <linux/io.h>
#include <asm/byteorder.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include "ide-cd.h"
static DEFINE_MUTEX(ide_cd_mutex);
static DEFINE_MUTEX(idecd_ref_mutex);
static void ide_cd_release(struct device *);
static struct cdrom_info *ide_cd_get(struct gendisk *disk)
{
struct cdrom_info *cd = NULL;
mutex_lock(&idecd_ref_mutex);
cd = ide_drv_g(disk, cdrom_info);
if (cd) {
if (ide_device_get(cd->drive))
cd = NULL;
else
get_device(&cd->dev);
}
mutex_unlock(&idecd_ref_mutex);
return cd;
}
static void ide_cd_put(struct cdrom_info *cd)
{
ide_drive_t *drive = cd->drive;
mutex_lock(&idecd_ref_mutex);
put_device(&cd->dev);
ide_device_put(drive);
mutex_unlock(&idecd_ref_mutex);
}
/*
* Generic packet command support and error handling routines.
*/
/* Mark that we've seen a media change and invalidate our internal buffers. */
static void cdrom_saw_media_change(ide_drive_t *drive)
{
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags &= ~IDE_AFLAG_TOC_VALID;
}
static int cdrom_log_sense(ide_drive_t *drive, struct request *rq)
{
struct request_sense *sense = &drive->sense_data;
int log = 0;
if (!sense || !rq || (rq->cmd_flags & REQ_QUIET))
return 0;
ide_debug_log(IDE_DBG_SENSE, "sense_key: 0x%x", sense->sense_key);
switch (sense->sense_key) {
case NO_SENSE:
case RECOVERED_ERROR:
break;
case NOT_READY:
/*
* don't care about tray state messages for e.g. capacity
* commands or in-progress or becoming ready
*/
if (sense->asc == 0x3a || sense->asc == 0x04)
break;
log = 1;
break;
case ILLEGAL_REQUEST:
/*
* don't log START_STOP unit with LoEj set, since we cannot
* reliably check if drive can auto-close
*/
if (rq->cmd[0] == GPCMD_START_STOP_UNIT && sense->asc == 0x24)
break;
log = 1;
break;
case UNIT_ATTENTION:
/*
* Make good and sure we've seen this potential media change.
* Some drives (i.e. Creative) fail to present the correct sense
* key in the error register.
*/
cdrom_saw_media_change(drive);
break;
default:
log = 1;
break;
}
return log;
}
static void cdrom_analyze_sense_data(ide_drive_t *drive,
struct request *failed_command)
{
struct request_sense *sense = &drive->sense_data;
struct cdrom_info *info = drive->driver_data;
unsigned long sector;
unsigned long bio_sectors;
ide_debug_log(IDE_DBG_SENSE, "error_code: 0x%x, sense_key: 0x%x",
sense->error_code, sense->sense_key);
if (failed_command)
ide_debug_log(IDE_DBG_SENSE, "failed cmd: 0x%x",
failed_command->cmd[0]);
if (!cdrom_log_sense(drive, failed_command))
return;
/*
* If a read toc is executed for a CD-R or CD-RW medium where the first
* toc has not been recorded yet, it will fail with 05/24/00 (which is a
* confusing error)
*/
if (failed_command && failed_command->cmd[0] == GPCMD_READ_TOC_PMA_ATIP)
if (sense->sense_key == 0x05 && sense->asc == 0x24)
return;
/* current error */
if (sense->error_code == 0x70) {
switch (sense->sense_key) {
case MEDIUM_ERROR:
case VOLUME_OVERFLOW:
case ILLEGAL_REQUEST:
if (!sense->valid)
break;
if (failed_command == NULL ||
failed_command->cmd_type != REQ_TYPE_FS)
break;
sector = (sense->information[0] << 24) |
(sense->information[1] << 16) |
(sense->information[2] << 8) |
(sense->information[3]);
if (queue_logical_block_size(drive->queue) == 2048)
/* device sector size is 2K */
sector <<= 2;
bio_sectors = max(bio_sectors(failed_command->bio), 4U);
sector &= ~(bio_sectors - 1);
/*
* The SCSI specification allows for the value
* returned by READ CAPACITY to be up to 75 2K
* sectors past the last readable block.
* Therefore, if we hit a medium error within the
* last 75 2K sectors, we decrease the saved size
* value.
*/
if (sector < get_capacity(info->disk) &&
drive->probed_capacity - sector < 4 * 75)
set_capacity(info->disk, sector);
}
}
ide_cd_log_error(drive->name, failed_command, sense);
}
static void ide_cd_complete_failed_rq(ide_drive_t *drive, struct request *rq)
{
/*
* For REQ_TYPE_SENSE, "rq->special" points to the original
* failed request. Also, the sense data should be read
* directly from rq which might be different from the original
* sense buffer if it got copied during mapping.
*/
struct request *failed = (struct request *)rq->special;
void *sense = bio_data(rq->bio);
if (failed) {
if (failed->sense) {
/*
* Sense is always read into drive->sense_data.
* Copy back if the failed request has its
* sense pointer set.
*/
memcpy(failed->sense, sense, 18);
failed->sense_len = rq->sense_len;
}
cdrom_analyze_sense_data(drive, failed);
if (ide_end_rq(drive, failed, -EIO, blk_rq_bytes(failed)))
BUG();
} else
cdrom_analyze_sense_data(drive, NULL);
}
/*
* Allow the drive 5 seconds to recover; some devices will return NOT_READY
* while flushing data from cache.
*
* returns: 0 failed (write timeout expired)
* 1 success
*/
static int ide_cd_breathe(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *info = drive->driver_data;
if (!rq->errors)
info->write_timeout = jiffies + ATAPI_WAIT_WRITE_BUSY;
rq->errors = 1;
if (time_after(jiffies, info->write_timeout))
return 0;
else {
/*
* take a breather
*/
blk_delay_queue(drive->queue, 1);
return 1;
}
}
/**
* Returns:
* 0: if the request should be continued.
* 1: if the request will be going through error recovery.
* 2: if the request should be ended.
*/
static int cdrom_decode_status(ide_drive_t *drive, u8 stat)
{
ide_hwif_t *hwif = drive->hwif;
struct request *rq = hwif->rq;
int err, sense_key, do_end_request = 0;
/* get the IDE error register */
err = ide_read_error(drive);
sense_key = err >> 4;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, rq->cmd_type: 0x%x, err: 0x%x, "
"stat 0x%x",
rq->cmd[0], rq->cmd_type, err, stat);
if (rq->cmd_type == REQ_TYPE_SENSE) {
/*
* We got an error trying to get sense info from the drive
* (probably while trying to recover from a former error).
* Just give up.
*/
rq->cmd_flags |= REQ_FAILED;
return 2;
}
/* if we have an error, pass CHECK_CONDITION as the SCSI status byte */
if (rq->cmd_type == REQ_TYPE_BLOCK_PC && !rq->errors)
rq->errors = SAM_STAT_CHECK_CONDITION;
if (blk_noretry_request(rq))
do_end_request = 1;
switch (sense_key) {
case NOT_READY:
if (rq->cmd_type == REQ_TYPE_FS && rq_data_dir(rq) == WRITE) {
if (ide_cd_breathe(drive, rq))
return 1;
} else {
cdrom_saw_media_change(drive);
if (rq->cmd_type == REQ_TYPE_FS &&
!(rq->cmd_flags & REQ_QUIET))
printk(KERN_ERR PFX "%s: tray open\n",
drive->name);
}
do_end_request = 1;
break;
case UNIT_ATTENTION:
cdrom_saw_media_change(drive);
if (rq->cmd_type != REQ_TYPE_FS)
return 0;
/*
* Arrange to retry the request but be sure to give up if we've
* retried too many times.
*/
if (++rq->errors > ERROR_MAX)
do_end_request = 1;
break;
case ILLEGAL_REQUEST:
/*
* Don't print error message for this condition -- SFF8090i
* indicates that 5/24/00 is the correct response to a request
* to close the tray if the drive doesn't have that capability.
*
* cdrom_log_sense() knows this!
*/
if (rq->cmd[0] == GPCMD_START_STOP_UNIT)
break;
/* fall-through */
case DATA_PROTECT:
/*
* No point in retrying after an illegal request or data
* protect error.
*/
if (!(rq->cmd_flags & REQ_QUIET))
ide_dump_status(drive, "command error", stat);
do_end_request = 1;
break;
case MEDIUM_ERROR:
/*
* No point in re-trying a zillion times on a bad sector.
* If we got here the error is not correctable.
*/
if (!(rq->cmd_flags & REQ_QUIET))
ide_dump_status(drive, "media error "
"(bad sector)", stat);
do_end_request = 1;
break;
case BLANK_CHECK:
/* disk appears blank? */
if (!(rq->cmd_flags & REQ_QUIET))
ide_dump_status(drive, "media error (blank)",
stat);
do_end_request = 1;
break;
default:
if (rq->cmd_type != REQ_TYPE_FS)
break;
if (err & ~ATA_ABORTED) {
/* go to the default handler for other errors */
ide_error(drive, "cdrom_decode_status", stat);
return 1;
} else if (++rq->errors > ERROR_MAX)
/* we've racked up too many retries, abort */
do_end_request = 1;
}
if (rq->cmd_type != REQ_TYPE_FS) {
rq->cmd_flags |= REQ_FAILED;
do_end_request = 1;
}
/*
* End a request through request sense analysis when we have sense data.
* We need this in order to perform end of media processing.
*/
if (do_end_request)
goto end_request;
/* if we got a CHECK_CONDITION status, queue a request sense command */
if (stat & ATA_ERR)
return ide_queue_sense_rq(drive, NULL) ? 2 : 1;
return 1;
end_request:
if (stat & ATA_ERR) {
hwif->rq = NULL;
return ide_queue_sense_rq(drive, rq) ? 2 : 1;
} else
return 2;
}
static void ide_cd_request_sense_fixup(ide_drive_t *drive, struct ide_cmd *cmd)
{
struct request *rq = cmd->rq;
ide_debug_log(IDE_DBG_FUNC, "rq->cmd[0]: 0x%x", rq->cmd[0]);
/*
* Some of the trailing request sense fields are optional,
* and some drives don't send them. Sigh.
*/
if (rq->cmd[0] == GPCMD_REQUEST_SENSE &&
cmd->nleft > 0 && cmd->nleft <= 5)
cmd->nleft = 0;
}
int ide_cd_queue_pc(ide_drive_t *drive, const unsigned char *cmd,
int write, void *buffer, unsigned *bufflen,
struct request_sense *sense, int timeout,
unsigned int cmd_flags)
{
struct cdrom_info *info = drive->driver_data;
struct request_sense local_sense;
int retries = 10;
unsigned int flags = 0;
if (!sense)
sense = &local_sense;
ide_debug_log(IDE_DBG_PC, "cmd[0]: 0x%x, write: 0x%x, timeout: %d, "
"cmd_flags: 0x%x",
cmd[0], write, timeout, cmd_flags);
/* start of retry loop */
do {
struct request *rq;
int error;
rq = blk_get_request(drive->queue, write, __GFP_WAIT);
memcpy(rq->cmd, cmd, BLK_MAX_CDB);
rq->cmd_type = REQ_TYPE_ATA_PC;
rq->sense = sense;
rq->cmd_flags |= cmd_flags;
rq->timeout = timeout;
if (buffer) {
error = blk_rq_map_kern(drive->queue, rq, buffer,
*bufflen, GFP_NOIO);
if (error) {
blk_put_request(rq);
return error;
}
}
error = blk_execute_rq(drive->queue, info->disk, rq, 0);
if (buffer)
*bufflen = rq->resid_len;
flags = rq->cmd_flags;
blk_put_request(rq);
/*
* FIXME: we should probably abort/retry or something in case of
* failure.
*/
if (flags & REQ_FAILED) {
/*
* The request failed. Retry if it was due to a unit
* attention status (usually means media was changed).
*/
struct request_sense *reqbuf = sense;
if (reqbuf->sense_key == UNIT_ATTENTION)
cdrom_saw_media_change(drive);
else if (reqbuf->sense_key == NOT_READY &&
reqbuf->asc == 4 && reqbuf->ascq != 4) {
/*
* The drive is in the process of loading
* a disk. Retry, but wait a little to give
* the drive time to complete the load.
*/
ssleep(2);
} else {
/* otherwise, don't retry */
retries = 0;
}
--retries;
}
/* end of retry loop */
} while ((flags & REQ_FAILED) && retries >= 0);
/* return an error if the command failed */
return (flags & REQ_FAILED) ? -EIO : 0;
}
/*
* returns true if rq has been completed
*/
static bool ide_cd_error_cmd(ide_drive_t *drive, struct ide_cmd *cmd)
{
unsigned int nr_bytes = cmd->nbytes - cmd->nleft;
if (cmd->tf_flags & IDE_TFLAG_WRITE)
nr_bytes -= cmd->last_xfer_len;
if (nr_bytes > 0) {
ide_complete_rq(drive, 0, nr_bytes);
return true;
}
return false;
}
static ide_startstop_t cdrom_newpc_intr(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct ide_cmd *cmd = &hwif->cmd;
struct request *rq = hwif->rq;
ide_expiry_t *expiry = NULL;
int dma_error = 0, dma, thislen, uptodate = 0;
int write = (rq_data_dir(rq) == WRITE) ? 1 : 0, rc = 0;
int sense = (rq->cmd_type == REQ_TYPE_SENSE);
unsigned int timeout;
u16 len;
u8 ireason, stat;
ide_debug_log(IDE_DBG_PC, "cmd: 0x%x, write: 0x%x", rq->cmd[0], write);
/* check for errors */
dma = drive->dma;
if (dma) {
drive->dma = 0;
drive->waiting_for_dma = 0;
dma_error = hwif->dma_ops->dma_end(drive);
ide_dma_unmap_sg(drive, cmd);
if (dma_error) {
printk(KERN_ERR PFX "%s: DMA %s error\n", drive->name,
write ? "write" : "read");
ide_dma_off(drive);
}
}
/* check status */
stat = hwif->tp_ops->read_status(hwif);
if (!OK_STAT(stat, 0, BAD_R_STAT)) {
rc = cdrom_decode_status(drive, stat);
if (rc) {
if (rc == 2)
goto out_end;
return ide_stopped;
}
}
/* using dma, transfer is complete now */
if (dma) {
if (dma_error)
return ide_error(drive, "dma error", stat);
uptodate = 1;
goto out_end;
}
ide_read_bcount_and_ireason(drive, &len, &ireason);
thislen = (rq->cmd_type == REQ_TYPE_FS) ? len : cmd->nleft;
if (thislen > len)
thislen = len;
ide_debug_log(IDE_DBG_PC, "DRQ: stat: 0x%x, thislen: %d",
stat, thislen);
/* If DRQ is clear, the command has completed. */
if ((stat & ATA_DRQ) == 0) {
if (rq->cmd_type == REQ_TYPE_FS) {
/*
* If we're not done reading/writing, complain.
* Otherwise, complete the command normally.
*/
uptodate = 1;
if (cmd->nleft > 0) {
printk(KERN_ERR PFX "%s: %s: data underrun "
"(%u bytes)\n", drive->name, __func__,
cmd->nleft);
if (!write)
rq->cmd_flags |= REQ_FAILED;
uptodate = 0;
}
} else if (rq->cmd_type != REQ_TYPE_BLOCK_PC) {
ide_cd_request_sense_fixup(drive, cmd);
uptodate = cmd->nleft ? 0 : 1;
/*
* suck out the remaining bytes from the drive in an
* attempt to complete the data xfer. (see BZ#13399)
*/
if (!(stat & ATA_ERR) && !uptodate && thislen) {
ide_pio_bytes(drive, cmd, write, thislen);
uptodate = cmd->nleft ? 0 : 1;
}
if (!uptodate)
rq->cmd_flags |= REQ_FAILED;
}
goto out_end;
}
rc = ide_check_ireason(drive, rq, len, ireason, write);
if (rc)
goto out_end;
cmd->last_xfer_len = 0;
ide_debug_log(IDE_DBG_PC, "data transfer, rq->cmd_type: 0x%x, "
"ireason: 0x%x",
rq->cmd_type, ireason);
/* transfer data */
while (thislen > 0) {
int blen = min_t(int, thislen, cmd->nleft);
if (cmd->nleft == 0)
break;
ide_pio_bytes(drive, cmd, write, blen);
cmd->last_xfer_len += blen;
thislen -= blen;
len -= blen;
if (sense && write == 0)
rq->sense_len += blen;
}
/* pad, if necessary */
if (len > 0) {
if (rq->cmd_type != REQ_TYPE_FS || write == 0)
ide_pad_transfer(drive, write, len);
else {
printk(KERN_ERR PFX "%s: confused, missing data\n",
drive->name);
blk_dump_rq_flags(rq, "cdrom_newpc_intr");
}
}
if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
timeout = rq->timeout;
} else {
timeout = ATAPI_WAIT_PC;
if (rq->cmd_type != REQ_TYPE_FS)
expiry = ide_cd_expiry;
}
hwif->expiry = expiry;
ide_set_handler(drive, cdrom_newpc_intr, timeout);
return ide_started;
out_end:
if (rq->cmd_type == REQ_TYPE_BLOCK_PC && rc == 0) {
rq->resid_len = 0;
blk_end_request_all(rq, 0);
hwif->rq = NULL;
} else {
if (sense && uptodate)
ide_cd_complete_failed_rq(drive, rq);
if (rq->cmd_type == REQ_TYPE_FS) {
if (cmd->nleft == 0)
uptodate = 1;
} else {
if (uptodate <= 0 && rq->errors == 0)
rq->errors = -EIO;
}
if (uptodate == 0 && rq->bio)
if (ide_cd_error_cmd(drive, cmd))
return ide_stopped;
/* make sure it's fully ended */
if (rq->cmd_type != REQ_TYPE_FS) {
rq->resid_len -= cmd->nbytes - cmd->nleft;
if (uptodate == 0 && (cmd->tf_flags & IDE_TFLAG_WRITE))
rq->resid_len += cmd->last_xfer_len;
}
ide_complete_rq(drive, uptodate ? 0 : -EIO, blk_rq_bytes(rq));
if (sense && rc == 2)
ide_error(drive, "request sense failure", stat);
}
return ide_stopped;
}
static ide_startstop_t cdrom_start_rw(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *cd = drive->driver_data;
struct request_queue *q = drive->queue;
int write = rq_data_dir(rq) == WRITE;
unsigned short sectors_per_frame =
queue_logical_block_size(q) >> SECTOR_BITS;
ide_debug_log(IDE_DBG_RQ, "rq->cmd[0]: 0x%x, rq->cmd_flags: 0x%x, "
"secs_per_frame: %u",
rq->cmd[0], rq->cmd_flags, sectors_per_frame);
if (write) {
/* disk has become write protected */
if (get_disk_ro(cd->disk))
return ide_stopped;
} else {
/*
* We may be retrying this request after an error. Fix up any
* weirdness which might be present in the request packet.
*/
q->prep_rq_fn(q, rq);
}
/* fs requests *must* be hardware frame aligned */
if ((blk_rq_sectors(rq) & (sectors_per_frame - 1)) ||
(blk_rq_pos(rq) & (sectors_per_frame - 1)))
return ide_stopped;
/* use DMA, if possible */
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
if (write)
cd->devinfo.media_written = 1;
rq->timeout = ATAPI_WAIT_PC;
return ide_started;
}
static void cdrom_do_block_pc(ide_drive_t *drive, struct request *rq)
{
ide_debug_log(IDE_DBG_PC, "rq->cmd[0]: 0x%x, rq->cmd_type: 0x%x",
rq->cmd[0], rq->cmd_type);
if (rq->cmd_type == REQ_TYPE_BLOCK_PC)
rq->cmd_flags |= REQ_QUIET;
else
rq->cmd_flags &= ~REQ_FAILED;
drive->dma = 0;
/* sg request */
if (rq->bio) {
struct request_queue *q = drive->queue;
char *buf = bio_data(rq->bio);
unsigned int alignment;
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
/*
* check if dma is safe
*
* NOTE! The "len" and "addr" checks should possibly have
* separate masks.
*/
alignment = queue_dma_alignment(q) | q->dma_pad_mask;
if ((unsigned long)buf & alignment
|| blk_rq_bytes(rq) & q->dma_pad_mask
|| object_is_on_stack(buf))
drive->dma = 0;
}
}
static ide_startstop_t ide_cd_do_request(ide_drive_t *drive, struct request *rq,
sector_t block)
{
struct ide_cmd cmd;
int uptodate = 0;
unsigned int nsectors;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, block: %llu",
rq->cmd[0], (unsigned long long)block);
if (drive->debug_mask & IDE_DBG_RQ)
blk_dump_rq_flags(rq, "ide_cd_do_request");
switch (rq->cmd_type) {
case REQ_TYPE_FS:
if (cdrom_start_rw(drive, rq) == ide_stopped)
goto out_end;
break;
case REQ_TYPE_SENSE:
case REQ_TYPE_BLOCK_PC:
case REQ_TYPE_ATA_PC:
if (!rq->timeout)
rq->timeout = ATAPI_WAIT_PC;
cdrom_do_block_pc(drive, rq);
break;
case REQ_TYPE_SPECIAL:
/* right now this can only be a reset... */
uptodate = 1;
goto out_end;
default:
BUG();
}
/* prepare sense request for this command */
ide_prep_sense(drive, rq);
memset(&cmd, 0, sizeof(cmd));
if (rq_data_dir(rq))
cmd.tf_flags |= IDE_TFLAG_WRITE;
cmd.rq = rq;
if (rq->cmd_type == REQ_TYPE_FS || blk_rq_bytes(rq)) {
ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
ide_map_sg(drive, &cmd);
}
return ide_issue_pc(drive, &cmd);
out_end:
nsectors = blk_rq_sectors(rq);
if (nsectors == 0)
nsectors = 1;
ide_complete_rq(drive, uptodate ? 0 : -EIO, nsectors << 9);
return ide_stopped;
}
/*
* Ioctl handling.
*
* Routines which queue packet commands take as a final argument a pointer to a
* request_sense struct. If execution of the command results in an error with a
* CHECK CONDITION status, this structure will be filled with the results of the
* subsequent request sense command. The pointer can also be NULL, in which case
* no sense information is returned.
*/
static void msf_from_bcd(struct atapi_msf *msf)
{
msf->minute = bcd2bin(msf->minute);
msf->second = bcd2bin(msf->second);
msf->frame = bcd2bin(msf->frame);
}
int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_TEST_UNIT_READY;
/*
* Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to switch CDs
* instead of supporting the LOAD_UNLOAD opcode.
*/
cmd[7] = cdi->sanyo_slot % 3;
return ide_cd_queue_pc(drive, cmd, 0, NULL, NULL, sense, 0, REQ_QUIET);
}
static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
unsigned long *sectors_per_frame,
struct request_sense *sense)
{
struct {
__be32 lba;
__be32 blocklen;
} capbuf;
int stat;
unsigned char cmd[BLK_MAX_CDB];
unsigned len = sizeof(capbuf);
u32 blocklen;
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_CDVD_CAPACITY;
stat = ide_cd_queue_pc(drive, cmd, 0, &capbuf, &len, sense, 0,
REQ_QUIET);
if (stat)
return stat;
/*
* Sanity check the given block size, in so far as making
* sure the sectors_per_frame we give to the caller won't
* end up being bogus.
*/
blocklen = be32_to_cpu(capbuf.blocklen);
blocklen = (blocklen >> SECTOR_BITS) << SECTOR_BITS;
switch (blocklen) {
case 512:
case 1024:
case 2048:
case 4096:
break;
default:
printk_once(KERN_ERR PFX "%s: weird block size %u; "
"setting default block size to 2048\n",
drive->name, blocklen);
blocklen = 2048;
break;
}
*capacity = 1 + be32_to_cpu(capbuf.lba);
*sectors_per_frame = blocklen >> SECTOR_BITS;
ide_debug_log(IDE_DBG_PROBE, "cap: %lu, sectors_per_frame: %lu",
*capacity, *sectors_per_frame);
return 0;
}
static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
int format, char *buf, int buflen,
struct request_sense *sense)
{
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
cmd[6] = trackno;
cmd[7] = (buflen >> 8);
cmd[8] = (buflen & 0xff);
cmd[9] = (format << 6);
if (msf_flag)
cmd[1] = 2;
return ide_cd_queue_pc(drive, cmd, 0, buf, &buflen, sense, 0, REQ_QUIET);
}
/* Try to read the entire TOC for the disk into our internal buffer. */
int ide_cd_read_toc(ide_drive_t *drive, struct request_sense *sense)
{
int stat, ntracks, i;
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct atapi_toc *toc = info->toc;
struct {
struct atapi_toc_header hdr;
struct atapi_toc_entry ent;
} ms_tmp;
long last_written;
unsigned long sectors_per_frame = SECTORS_PER_FRAME;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (toc == NULL) {
/* try to allocate space */
toc = kmalloc(sizeof(struct atapi_toc), GFP_KERNEL);
if (toc == NULL) {
printk(KERN_ERR PFX "%s: No cdrom TOC buffer!\n",
drive->name);
return -ENOMEM;
}
info->toc = toc;
}
/*
* Check to see if the existing data is still valid. If it is,
* just return.
*/
(void) cdrom_check_status(drive, sense);
if (drive->atapi_flags & IDE_AFLAG_TOC_VALID)
return 0;
/* try to get the total cdrom capacity and sector size */
stat = cdrom_read_capacity(drive, &toc->capacity, §ors_per_frame,
sense);
if (stat)
toc->capacity = 0x1fffff;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
/* save a private copy of the TOC capacity for error handling */
drive->probed_capacity = toc->capacity * sectors_per_frame;
blk_queue_logical_block_size(drive->queue,
sectors_per_frame << SECTOR_BITS);
/* first read just the header, so we know how long the TOC is */
stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
sizeof(struct atapi_toc_header), sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
if (ntracks <= 0)
return -EIO;
if (ntracks > MAX_TRACKS)
ntracks = MAX_TRACKS;
/* now read the whole schmeer */
stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry), sense);
if (stat && toc->hdr.first_track > 1) {
/*
* Cds with CDI tracks only don't have any TOC entries, despite
* of this the returned values are
* first_track == last_track = number of CDI tracks + 1,
* so that this case is indistinguishable from the same layout
* plus an additional audio track. If we get an error for the
* regular case, we assume a CDI without additional audio
* tracks. In this case the readable TOC is empty (CDI tracks
* are not included) and only holds the Leadout entry.
*
* Heiko Eißfeldt.
*/
ntracks = 0;
stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry),
sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = (u8)bin2bcd(CDROM_LEADOUT);
toc->hdr.last_track = (u8)bin2bcd(CDROM_LEADOUT);
} else {
toc->hdr.first_track = CDROM_LEADOUT;
toc->hdr.last_track = CDROM_LEADOUT;
}
}
if (stat)
return stat;
toc->hdr.toc_length = be16_to_cpu(toc->hdr.toc_length);
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
for (i = 0; i <= ntracks; i++) {
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD)
toc->ent[i].track = bcd2bin(toc->ent[i].track);
msf_from_bcd(&toc->ent[i].addr.msf);
}
toc->ent[i].addr.lba = msf_to_lba(toc->ent[i].addr.msf.minute,
toc->ent[i].addr.msf.second,
toc->ent[i].addr.msf.frame);
}
if (toc->hdr.first_track != CDROM_LEADOUT) {
/* read the multisession information */
stat = cdrom_read_tocentry(drive, 0, 0, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
toc->last_session_lba = be32_to_cpu(ms_tmp.ent.addr.lba);
} else {
ms_tmp.hdr.last_track = CDROM_LEADOUT;
ms_tmp.hdr.first_track = ms_tmp.hdr.last_track;
toc->last_session_lba = msf_to_lba(0, 2, 0); /* 0m 2s 0f */
}
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
/* re-read multisession information using MSF format */
stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
msf_from_bcd(&ms_tmp.ent.addr.msf);
toc->last_session_lba = msf_to_lba(ms_tmp.ent.addr.msf.minute,
ms_tmp.ent.addr.msf.second,
ms_tmp.ent.addr.msf.frame);
}
toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
/* now try to get the total cdrom capacity */
stat = cdrom_get_last_written(cdi, &last_written);
if (!stat && (last_written > toc->capacity)) {
toc->capacity = last_written;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
drive->probed_capacity = toc->capacity * sectors_per_frame;
}
/* Remember that we've read this stuff. */
drive->atapi_flags |= IDE_AFLAG_TOC_VALID;
return 0;
}
int ide_cdrom_get_capabilities(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct packet_command cgc;
int stat, attempts = 3, size = ATAPI_CAPABILITIES_PAGE_SIZE;
ide_debug_log(IDE_DBG_FUNC, "enter");
if ((drive->atapi_flags & IDE_AFLAG_FULL_CAPS_PAGE) == 0)
size -= ATAPI_CAPABILITIES_PAGE_PAD_SIZE;
init_cdrom_command(&cgc, buf, size, CGC_DATA_UNKNOWN);
do {
/* we seem to get stat=0x01,err=0x00 the first time (??) */
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
if (!stat)
break;
} while (--attempts);
return stat;
}
void ide_cdrom_update_speed(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *cd = drive->driver_data;
u16 curspeed, maxspeed;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (drive->atapi_flags & IDE_AFLAG_LE_SPEED_FIELDS) {
curspeed = le16_to_cpup((__le16 *)&buf[8 + 14]);
maxspeed = le16_to_cpup((__le16 *)&buf[8 + 8]);
} else {
curspeed = be16_to_cpup((__be16 *)&buf[8 + 14]);
maxspeed = be16_to_cpup((__be16 *)&buf[8 + 8]);
}
ide_debug_log(IDE_DBG_PROBE, "curspeed: %u, maxspeed: %u",
curspeed, maxspeed);
cd->current_speed = DIV_ROUND_CLOSEST(curspeed, 176);
cd->max_speed = DIV_ROUND_CLOSEST(maxspeed, 176);
}
#define IDE_CD_CAPABILITIES \
(CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK | CDC_SELECT_SPEED | \
CDC_SELECT_DISC | CDC_MULTI_SESSION | CDC_MCN | CDC_MEDIA_CHANGED | \
CDC_PLAY_AUDIO | CDC_RESET | CDC_DRIVE_STATUS | CDC_CD_R | \
CDC_CD_RW | CDC_DVD | CDC_DVD_R | CDC_DVD_RAM | CDC_GENERIC_PACKET | \
CDC_MO_DRIVE | CDC_MRW | CDC_MRW_W | CDC_RAM)
static struct cdrom_device_ops ide_cdrom_dops = {
.open = ide_cdrom_open_real,
.release = ide_cdrom_release_real,
.drive_status = ide_cdrom_drive_status,
.check_events = ide_cdrom_check_events_real,
.tray_move = ide_cdrom_tray_move,
.lock_door = ide_cdrom_lock_door,
.select_speed = ide_cdrom_select_speed,
.get_last_session = ide_cdrom_get_last_session,
.get_mcn = ide_cdrom_get_mcn,
.reset = ide_cdrom_reset,
.audio_ioctl = ide_cdrom_audio_ioctl,
.capability = IDE_CD_CAPABILITIES,
.generic_packet = ide_cdrom_packet,
};
static int ide_cdrom_register(ide_drive_t *drive, int nslots)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *devinfo = &info->devinfo;
ide_debug_log(IDE_DBG_PROBE, "nslots: %d", nslots);
devinfo->ops = &ide_cdrom_dops;
devinfo->speed = info->current_speed;
devinfo->capacity = nslots;
devinfo->handle = drive;
strcpy(devinfo->name, drive->name);
if (drive->atapi_flags & IDE_AFLAG_NO_SPEED_SELECT)
devinfo->mask |= CDC_SELECT_SPEED;
devinfo->disk = info->disk;
return register_cdrom(devinfo);
}
static int ide_cdrom_probe_capabilities(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
u8 buf[ATAPI_CAPABILITIES_PAGE_SIZE];
mechtype_t mechtype;
int nslots = 1;
ide_debug_log(IDE_DBG_PROBE, "media: 0x%x, atapi_flags: 0x%lx",
drive->media, drive->atapi_flags);
cdi->mask = (CDC_CD_R | CDC_CD_RW | CDC_DVD | CDC_DVD_R |
CDC_DVD_RAM | CDC_SELECT_DISC | CDC_PLAY_AUDIO |
CDC_MO_DRIVE | CDC_RAM);
if (drive->media == ide_optical) {
cdi->mask &= ~(CDC_MO_DRIVE | CDC_RAM);
printk(KERN_ERR PFX "%s: ATAPI magneto-optical drive\n",
drive->name);
return nslots;
}
if (drive->atapi_flags & IDE_AFLAG_PRE_ATAPI12) {
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
cdi->mask &= ~CDC_PLAY_AUDIO;
return nslots;
}
/*
* We have to cheat a little here. the packet will eventually be queued
* with ide_cdrom_packet(), which extracts the drive from cdi->handle.
* Since this device hasn't been registered with the Uniform layer yet,
* it can't do this. Same goes for cdi->ops.
*/
cdi->handle = drive;
cdi->ops = &ide_cdrom_dops;
if (ide_cdrom_get_capabilities(drive, buf))
return 0;
if ((buf[8 + 6] & 0x01) == 0)
drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
if (buf[8 + 6] & 0x08)
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
if (buf[8 + 3] & 0x01)
cdi->mask &= ~CDC_CD_R;
if (buf[8 + 3] & 0x02)
cdi->mask &= ~(CDC_CD_RW | CDC_RAM);
if (buf[8 + 2] & 0x38)
cdi->mask &= ~CDC_DVD;
if (buf[8 + 3] & 0x20)
cdi->mask &= ~(CDC_DVD_RAM | CDC_RAM);
if (buf[8 + 3] & 0x10)
cdi->mask &= ~CDC_DVD_R;
if ((buf[8 + 4] & 0x01) || (drive->atapi_flags & IDE_AFLAG_PLAY_AUDIO_OK))
cdi->mask &= ~CDC_PLAY_AUDIO;
mechtype = buf[8 + 6] >> 5;
if (mechtype == mechtype_caddy ||
mechtype == mechtype_popup ||
(drive->atapi_flags & IDE_AFLAG_NO_AUTOCLOSE))
cdi->mask |= CDC_CLOSE_TRAY;
if (cdi->sanyo_slot > 0) {
cdi->mask &= ~CDC_SELECT_DISC;
nslots = 3;
} else if (mechtype == mechtype_individual_changer ||
mechtype == mechtype_cartridge_changer) {
nslots = cdrom_number_of_slots(cdi);
if (nslots > 1)
cdi->mask &= ~CDC_SELECT_DISC;
}
ide_cdrom_update_speed(drive, buf);
printk(KERN_INFO PFX "%s: ATAPI", drive->name);
/* don't print speed if the drive reported 0 */
if (cd->max_speed)
printk(KERN_CONT " %dX", cd->max_speed);
printk(KERN_CONT " %s", (cdi->mask & CDC_DVD) ? "CD-ROM" : "DVD-ROM");
if ((cdi->mask & CDC_DVD_R) == 0 || (cdi->mask & CDC_DVD_RAM) == 0)
printk(KERN_CONT " DVD%s%s",
(cdi->mask & CDC_DVD_R) ? "" : "-R",
(cdi->mask & CDC_DVD_RAM) ? "" : "/RAM");
if ((cdi->mask & CDC_CD_R) == 0 || (cdi->mask & CDC_CD_RW) == 0)
printk(KERN_CONT " CD%s%s",
(cdi->mask & CDC_CD_R) ? "" : "-R",
(cdi->mask & CDC_CD_RW) ? "" : "/RW");
if ((cdi->mask & CDC_SELECT_DISC) == 0)
printk(KERN_CONT " changer w/%d slots", nslots);
else
printk(KERN_CONT " drive");
printk(KERN_CONT ", %dkB Cache\n",
be16_to_cpup((__be16 *)&buf[8 + 12]));
return nslots;
}
/* standard prep_rq_fn that builds 10 byte cmds */
static int ide_cdrom_prep_fs(struct request_queue *q, struct request *rq)
{
int hard_sect = queue_logical_block_size(q);
long block = (long)blk_rq_pos(rq) / (hard_sect >> 9);
unsigned long blocks = blk_rq_sectors(rq) / (hard_sect >> 9);
memset(rq->cmd, 0, BLK_MAX_CDB);
if (rq_data_dir(rq) == READ)
rq->cmd[0] = GPCMD_READ_10;
else
rq->cmd[0] = GPCMD_WRITE_10;
/*
* fill in lba
*/
rq->cmd[2] = (block >> 24) & 0xff;
rq->cmd[3] = (block >> 16) & 0xff;
rq->cmd[4] = (block >> 8) & 0xff;
rq->cmd[5] = block & 0xff;
/*
* and transfer length
*/
rq->cmd[7] = (blocks >> 8) & 0xff;
rq->cmd[8] = blocks & 0xff;
rq->cmd_len = 10;
return BLKPREP_OK;
}
/*
* Most of the SCSI commands are supported directly by ATAPI devices.
* This transform handles the few exceptions.
*/
static int ide_cdrom_prep_pc(struct request *rq)
{
u8 *c = rq->cmd;
/* transform 6-byte read/write commands to the 10-byte version */
if (c[0] == READ_6 || c[0] == WRITE_6) {
c[8] = c[4];
c[5] = c[3];
c[4] = c[2];
c[3] = c[1] & 0x1f;
c[2] = 0;
c[1] &= 0xe0;
c[0] += (READ_10 - READ_6);
rq->cmd_len = 10;
return BLKPREP_OK;
}
/*
* it's silly to pretend we understand 6-byte sense commands, just
* reject with ILLEGAL_REQUEST and the caller should take the
* appropriate action
*/
if (c[0] == MODE_SENSE || c[0] == MODE_SELECT) {
rq->errors = ILLEGAL_REQUEST;
return BLKPREP_KILL;
}
return BLKPREP_OK;
}
static int ide_cdrom_prep_fn(struct request_queue *q, struct request *rq)
{
if (rq->cmd_type == REQ_TYPE_FS)
return ide_cdrom_prep_fs(q, rq);
else if (rq->cmd_type == REQ_TYPE_BLOCK_PC)
return ide_cdrom_prep_pc(rq);
return 0;
}
struct cd_list_entry {
const char *id_model;
const char *id_firmware;
unsigned int cd_flags;
};
#ifdef CONFIG_IDE_PROC_FS
static sector_t ide_cdrom_capacity(ide_drive_t *drive)
{
unsigned long capacity, sectors_per_frame;
if (cdrom_read_capacity(drive, &capacity, §ors_per_frame, NULL))
return 0;
return capacity * sectors_per_frame;
}
static int idecd_capacity_proc_show(struct seq_file *m, void *v)
{
ide_drive_t *drive = m->private;
seq_printf(m, "%llu\n", (long long)ide_cdrom_capacity(drive));
return 0;
}
static int idecd_capacity_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, idecd_capacity_proc_show, PDE_DATA(inode));
}
static const struct file_operations idecd_capacity_proc_fops = {
.owner = THIS_MODULE,
.open = idecd_capacity_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static ide_proc_entry_t idecd_proc[] = {
{ "capacity", S_IFREG|S_IRUGO, &idecd_capacity_proc_fops },
{}
};
static ide_proc_entry_t *ide_cd_proc_entries(ide_drive_t *drive)
{
return idecd_proc;
}
static const struct ide_proc_devset *ide_cd_proc_devsets(ide_drive_t *drive)
{
return NULL;
}
#endif
static const struct cd_list_entry ide_cd_quirks_list[] = {
/* SCR-3231 doesn't support the SET_CD_SPEED command. */
{ "SAMSUNG CD-ROM SCR-3231", NULL, IDE_AFLAG_NO_SPEED_SELECT },
/* Old NEC260 (not R) was released before ATAPI 1.2 spec. */
{ "NEC CD-ROM DRIVE:260", "1.01", IDE_AFLAG_TOCADDR_AS_BCD |
IDE_AFLAG_PRE_ATAPI12, },
/* Vertos 300, some versions of this drive like to talk BCD. */
{ "V003S0DS", NULL, IDE_AFLAG_VERTOS_300_SSD, },
/* Vertos 600 ESD. */
{ "V006E0DS", NULL, IDE_AFLAG_VERTOS_600_ESD, },
/*
* Sanyo 3 CD changer uses a non-standard command for CD changing
* (by default standard ATAPI support for CD changers is used).
*/
{ "CD-ROM CDR-C3 G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR-C3G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR_C36", NULL, IDE_AFLAG_SANYO_3CD },
/* Stingray 8X CD-ROM. */
{ "STINGRAY 8422 IDE 8X CD-ROM 7-27-95", NULL, IDE_AFLAG_PRE_ATAPI12 },
/*
* ACER 50X CD-ROM and WPI 32X CD-ROM require the full spec length
* mode sense page capabilities size, but older drives break.
*/
{ "ATAPI CD ROM DRIVE 50X MAX", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
{ "WPI CDS-32X", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
/* ACER/AOpen 24X CD-ROM has the speed fields byte-swapped. */
{ "", "241N", IDE_AFLAG_LE_SPEED_FIELDS },
/*
* Some drives used by Apple don't advertise audio play
* but they do support reading TOC & audio datas.
*/
{ "MATSHITADVD-ROM SR-8187", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8186", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8176", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8174", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-5200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7543A", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ "TEAC CD-ROM CD-224E", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ NULL, NULL, 0 }
};
static unsigned int ide_cd_flags(u16 *id)
{
const struct cd_list_entry *cle = ide_cd_quirks_list;
while (cle->id_model) {
if (strcmp(cle->id_model, (char *)&id[ATA_ID_PROD]) == 0 &&
(cle->id_firmware == NULL ||
strstr((char *)&id[ATA_ID_FW_REV], cle->id_firmware)))
return cle->cd_flags;
cle++;
}
return 0;
}
static int ide_cdrom_setup(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
struct request_queue *q = drive->queue;
u16 *id = drive->id;
char *fw_rev = (char *)&id[ATA_ID_FW_REV];
int nslots;
ide_debug_log(IDE_DBG_PROBE, "enter");
blk_queue_prep_rq(q, ide_cdrom_prep_fn);
blk_queue_dma_alignment(q, 31);
blk_queue_update_dma_pad(q, 15);
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags = IDE_AFLAG_NO_EJECT | ide_cd_flags(id);
if ((drive->atapi_flags & IDE_AFLAG_VERTOS_300_SSD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= (IDE_AFLAG_TOCTRACKS_AS_BCD |
IDE_AFLAG_TOCADDR_AS_BCD);
else if ((drive->atapi_flags & IDE_AFLAG_VERTOS_600_ESD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= IDE_AFLAG_TOCTRACKS_AS_BCD;
else if (drive->atapi_flags & IDE_AFLAG_SANYO_3CD)
/* 3 => use CD in slot 0 */
cdi->sanyo_slot = 3;
nslots = ide_cdrom_probe_capabilities(drive);
blk_queue_logical_block_size(q, CD_FRAMESIZE);
if (ide_cdrom_register(drive, nslots)) {
printk(KERN_ERR PFX "%s: %s failed to register device with the"
" cdrom driver.\n", drive->name, __func__);
cd->devinfo.handle = NULL;
return 1;
}
ide_proc_register_driver(drive, cd->driver);
return 0;
}
static void ide_cd_remove(ide_drive_t *drive)
{
struct cdrom_info *info = drive->driver_data;
ide_debug_log(IDE_DBG_FUNC, "enter");
ide_proc_unregister_driver(drive, info->driver);
device_del(&info->dev);
del_gendisk(info->disk);
mutex_lock(&idecd_ref_mutex);
put_device(&info->dev);
mutex_unlock(&idecd_ref_mutex);
}
static void ide_cd_release(struct device *dev)
{
struct cdrom_info *info = to_ide_drv(dev, cdrom_info);
struct cdrom_device_info *devinfo = &info->devinfo;
ide_drive_t *drive = info->drive;
struct gendisk *g = info->disk;
ide_debug_log(IDE_DBG_FUNC, "enter");
kfree(info->toc);
if (devinfo->handle == drive)
unregister_cdrom(devinfo);
drive->driver_data = NULL;
blk_queue_prep_rq(drive->queue, NULL);
g->private_data = NULL;
put_disk(g);
kfree(info);
}
static int ide_cd_probe(ide_drive_t *);
static struct ide_driver ide_cdrom_driver = {
.gen_driver = {
.owner = THIS_MODULE,
.name = "ide-cdrom",
.bus = &ide_bus_type,
},
.probe = ide_cd_probe,
.remove = ide_cd_remove,
.version = IDECD_VERSION,
.do_request = ide_cd_do_request,
#ifdef CONFIG_IDE_PROC_FS
.proc_entries = ide_cd_proc_entries,
.proc_devsets = ide_cd_proc_devsets,
#endif
};
static int idecd_open(struct block_device *bdev, fmode_t mode)
{
struct cdrom_info *info;
int rc = -ENXIO;
mutex_lock(&ide_cd_mutex);
info = ide_cd_get(bdev->bd_disk);
if (!info)
goto out;
rc = cdrom_open(&info->devinfo, bdev, mode);
if (rc < 0)
ide_cd_put(info);
out:
mutex_unlock(&ide_cd_mutex);
return rc;
}
static void idecd_release(struct gendisk *disk, fmode_t mode)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
mutex_lock(&ide_cd_mutex);
cdrom_release(&info->devinfo, mode);
ide_cd_put(info);
mutex_unlock(&ide_cd_mutex);
}
static int idecd_set_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
if (copy_from_user(&spindown, (void __user *)arg, sizeof(char)))
return -EFAULT;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
return cdrom_mode_select(cdi, &cgc);
}
static int idecd_get_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
spindown = buffer[11] & 0x0f;
if (copy_to_user((void __user *)arg, &spindown, sizeof(char)))
return -EFAULT;
return 0;
}
static int idecd_locked_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct cdrom_info *info = ide_drv_g(bdev->bd_disk, cdrom_info);
int err;
switch (cmd) {
case CDROMSETSPINDOWN:
return idecd_set_spindown(&info->devinfo, arg);
case CDROMGETSPINDOWN:
return idecd_get_spindown(&info->devinfo, arg);
default:
break;
}
err = generic_ide_ioctl(info->drive, bdev, cmd, arg);
if (err == -EINVAL)
err = cdrom_ioctl(&info->devinfo, bdev, mode, cmd, arg);
return err;
}
static int idecd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret;
mutex_lock(&ide_cd_mutex);
ret = idecd_locked_ioctl(bdev, mode, cmd, arg);
mutex_unlock(&ide_cd_mutex);
return ret;
}
static unsigned int idecd_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
return cdrom_check_events(&info->devinfo, clearing);
}
static int idecd_revalidate_disk(struct gendisk *disk)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
struct request_sense sense;
ide_cd_read_toc(info->drive, &sense);
return 0;
}
static const struct block_device_operations idecd_ops = {
.owner = THIS_MODULE,
.open = idecd_open,
.release = idecd_release,
.ioctl = idecd_ioctl,
.check_events = idecd_check_events,
.revalidate_disk = idecd_revalidate_disk
};
/* module options */
static unsigned long debug_mask;
module_param(debug_mask, ulong, 0644);
MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
static int ide_cd_probe(ide_drive_t *drive)
{
struct cdrom_info *info;
struct gendisk *g;
struct request_sense sense;
ide_debug_log(IDE_DBG_PROBE, "driver_req: %s, media: 0x%x",
drive->driver_req, drive->media);
if (!strstr("ide-cdrom", drive->driver_req))
goto failed;
if (drive->media != ide_cdrom && drive->media != ide_optical)
goto failed;
drive->debug_mask = debug_mask;
drive->irq_handler = cdrom_newpc_intr;
info = kzalloc(sizeof(struct cdrom_info), GFP_KERNEL);
if (info == NULL) {
printk(KERN_ERR PFX "%s: Can't allocate a cdrom structure\n",
drive->name);
goto failed;
}
g = alloc_disk(1 << PARTN_BITS);
if (!g)
goto out_free_cd;
ide_init_disk(g, drive);
info->dev.parent = &drive->gendev;
info->dev.release = ide_cd_release;
dev_set_name(&info->dev, dev_name(&drive->gendev));
if (device_register(&info->dev))
goto out_free_disk;
info->drive = drive;
info->driver = &ide_cdrom_driver;
info->disk = g;
g->private_data = &info->driver;
drive->driver_data = info;
g->minors = 1;
g->driverfs_dev = &drive->gendev;
g->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE;
if (ide_cdrom_setup(drive)) {
put_device(&info->dev);
goto failed;
}
ide_cd_read_toc(drive, &sense);
g->fops = &idecd_ops;
g->flags |= GENHD_FL_REMOVABLE | GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE;
add_disk(g);
return 0;
out_free_disk:
put_disk(g);
out_free_cd:
kfree(info);
failed:
return -ENODEV;
}
static void __exit ide_cdrom_exit(void)
{
driver_unregister(&ide_cdrom_driver.gen_driver);
}
static int __init ide_cdrom_init(void)
{
printk(KERN_INFO DRV_NAME " driver " IDECD_VERSION "\n");
return driver_register(&ide_cdrom_driver.gen_driver);
}
MODULE_ALIAS("ide:*m-cdrom*");
MODULE_ALIAS("ide-cd");
module_init(ide_cdrom_init);
module_exit(ide_cdrom_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
axxx007xxxz/cm_kernel_motorola_msm8916 | drivers/dma/dw_dmac.c | 2079 | 50472 | /*
* Core driver for the Synopsys DesignWare DMA Controller
*
* Copyright (C) 2007-2008 Atmel Corporation
* Copyright (C) 2010-2011 ST Microelectronics
*
* 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/clk.h>
#include <linux/delay.h>
#include <linux/dmaengine.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_dma.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/acpi.h>
#include <linux/acpi_dma.h>
#include "dw_dmac_regs.h"
#include "dmaengine.h"
/*
* This supports the Synopsys "DesignWare AHB Central DMA Controller",
* (DW_ahb_dmac) which is used with various AMBA 2.0 systems (not all
* of which use ARM any more). See the "Databook" from Synopsys for
* information beyond what licensees probably provide.
*
* The driver has currently been tested only with the Atmel AT32AP7000,
* which does not support descriptor writeback.
*/
static inline unsigned int dwc_get_dms(struct dw_dma_slave *slave)
{
return slave ? slave->dst_master : 0;
}
static inline unsigned int dwc_get_sms(struct dw_dma_slave *slave)
{
return slave ? slave->src_master : 1;
}
static inline void dwc_set_masters(struct dw_dma_chan *dwc)
{
struct dw_dma *dw = to_dw_dma(dwc->chan.device);
struct dw_dma_slave *dws = dwc->chan.private;
unsigned char mmax = dw->nr_masters - 1;
if (dwc->request_line == ~0) {
dwc->src_master = min_t(unsigned char, mmax, dwc_get_sms(dws));
dwc->dst_master = min_t(unsigned char, mmax, dwc_get_dms(dws));
}
}
#define DWC_DEFAULT_CTLLO(_chan) ({ \
struct dw_dma_chan *_dwc = to_dw_dma_chan(_chan); \
struct dma_slave_config *_sconfig = &_dwc->dma_sconfig; \
bool _is_slave = is_slave_direction(_dwc->direction); \
u8 _smsize = _is_slave ? _sconfig->src_maxburst : \
DW_DMA_MSIZE_16; \
u8 _dmsize = _is_slave ? _sconfig->dst_maxburst : \
DW_DMA_MSIZE_16; \
\
(DWC_CTLL_DST_MSIZE(_dmsize) \
| DWC_CTLL_SRC_MSIZE(_smsize) \
| DWC_CTLL_LLP_D_EN \
| DWC_CTLL_LLP_S_EN \
| DWC_CTLL_DMS(_dwc->dst_master) \
| DWC_CTLL_SMS(_dwc->src_master)); \
})
/*
* Number of descriptors to allocate for each channel. This should be
* made configurable somehow; preferably, the clients (at least the
* ones using slave transfers) should be able to give us a hint.
*/
#define NR_DESCS_PER_CHANNEL 64
/*----------------------------------------------------------------------*/
static struct device *chan2dev(struct dma_chan *chan)
{
return &chan->dev->device;
}
static struct device *chan2parent(struct dma_chan *chan)
{
return chan->dev->device.parent;
}
static struct dw_desc *dwc_first_active(struct dw_dma_chan *dwc)
{
return to_dw_desc(dwc->active_list.next);
}
static struct dw_desc *dwc_desc_get(struct dw_dma_chan *dwc)
{
struct dw_desc *desc, *_desc;
struct dw_desc *ret = NULL;
unsigned int i = 0;
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
list_for_each_entry_safe(desc, _desc, &dwc->free_list, desc_node) {
i++;
if (async_tx_test_ack(&desc->txd)) {
list_del(&desc->desc_node);
ret = desc;
break;
}
dev_dbg(chan2dev(&dwc->chan), "desc %p not ACKed\n", desc);
}
spin_unlock_irqrestore(&dwc->lock, flags);
dev_vdbg(chan2dev(&dwc->chan), "scanned %u descriptors on freelist\n", i);
return ret;
}
/*
* Move a descriptor, including any children, to the free list.
* `desc' must not be on any lists.
*/
static void dwc_desc_put(struct dw_dma_chan *dwc, struct dw_desc *desc)
{
unsigned long flags;
if (desc) {
struct dw_desc *child;
spin_lock_irqsave(&dwc->lock, flags);
list_for_each_entry(child, &desc->tx_list, desc_node)
dev_vdbg(chan2dev(&dwc->chan),
"moving child desc %p to freelist\n",
child);
list_splice_init(&desc->tx_list, &dwc->free_list);
dev_vdbg(chan2dev(&dwc->chan), "moving desc %p to freelist\n", desc);
list_add(&desc->desc_node, &dwc->free_list);
spin_unlock_irqrestore(&dwc->lock, flags);
}
}
static void dwc_initialize(struct dw_dma_chan *dwc)
{
struct dw_dma *dw = to_dw_dma(dwc->chan.device);
struct dw_dma_slave *dws = dwc->chan.private;
u32 cfghi = DWC_CFGH_FIFO_MODE;
u32 cfglo = DWC_CFGL_CH_PRIOR(dwc->priority);
if (dwc->initialized == true)
return;
if (dws) {
/*
* We need controller-specific data to set up slave
* transfers.
*/
BUG_ON(!dws->dma_dev || dws->dma_dev != dw->dma.dev);
cfghi = dws->cfg_hi;
cfglo |= dws->cfg_lo & ~DWC_CFGL_CH_PRIOR_MASK;
} else {
if (dwc->direction == DMA_MEM_TO_DEV)
cfghi = DWC_CFGH_DST_PER(dwc->request_line);
else if (dwc->direction == DMA_DEV_TO_MEM)
cfghi = DWC_CFGH_SRC_PER(dwc->request_line);
}
channel_writel(dwc, CFG_LO, cfglo);
channel_writel(dwc, CFG_HI, cfghi);
/* Enable interrupts */
channel_set_bit(dw, MASK.XFER, dwc->mask);
channel_set_bit(dw, MASK.ERROR, dwc->mask);
dwc->initialized = true;
}
/*----------------------------------------------------------------------*/
static inline unsigned int dwc_fast_fls(unsigned long long v)
{
/*
* We can be a lot more clever here, but this should take care
* of the most common optimization.
*/
if (!(v & 7))
return 3;
else if (!(v & 3))
return 2;
else if (!(v & 1))
return 1;
return 0;
}
static inline void dwc_dump_chan_regs(struct dw_dma_chan *dwc)
{
dev_err(chan2dev(&dwc->chan),
" SAR: 0x%x DAR: 0x%x LLP: 0x%x CTL: 0x%x:%08x\n",
channel_readl(dwc, SAR),
channel_readl(dwc, DAR),
channel_readl(dwc, LLP),
channel_readl(dwc, CTL_HI),
channel_readl(dwc, CTL_LO));
}
static inline void dwc_chan_disable(struct dw_dma *dw, struct dw_dma_chan *dwc)
{
channel_clear_bit(dw, CH_EN, dwc->mask);
while (dma_readl(dw, CH_EN) & dwc->mask)
cpu_relax();
}
/*----------------------------------------------------------------------*/
/* Perform single block transfer */
static inline void dwc_do_single_block(struct dw_dma_chan *dwc,
struct dw_desc *desc)
{
struct dw_dma *dw = to_dw_dma(dwc->chan.device);
u32 ctllo;
/* Software emulation of LLP mode relies on interrupts to continue
* multi block transfer. */
ctllo = desc->lli.ctllo | DWC_CTLL_INT_EN;
channel_writel(dwc, SAR, desc->lli.sar);
channel_writel(dwc, DAR, desc->lli.dar);
channel_writel(dwc, CTL_LO, ctllo);
channel_writel(dwc, CTL_HI, desc->lli.ctlhi);
channel_set_bit(dw, CH_EN, dwc->mask);
/* Move pointer to next descriptor */
dwc->tx_node_active = dwc->tx_node_active->next;
}
/* Called with dwc->lock held and bh disabled */
static void dwc_dostart(struct dw_dma_chan *dwc, struct dw_desc *first)
{
struct dw_dma *dw = to_dw_dma(dwc->chan.device);
unsigned long was_soft_llp;
/* ASSERT: channel is idle */
if (dma_readl(dw, CH_EN) & dwc->mask) {
dev_err(chan2dev(&dwc->chan),
"BUG: Attempted to start non-idle channel\n");
dwc_dump_chan_regs(dwc);
/* The tasklet will hopefully advance the queue... */
return;
}
if (dwc->nollp) {
was_soft_llp = test_and_set_bit(DW_DMA_IS_SOFT_LLP,
&dwc->flags);
if (was_soft_llp) {
dev_err(chan2dev(&dwc->chan),
"BUG: Attempted to start new LLP transfer "
"inside ongoing one\n");
return;
}
dwc_initialize(dwc);
dwc->residue = first->total_len;
dwc->tx_node_active = &first->tx_list;
/* Submit first block */
dwc_do_single_block(dwc, first);
return;
}
dwc_initialize(dwc);
channel_writel(dwc, LLP, first->txd.phys);
channel_writel(dwc, CTL_LO,
DWC_CTLL_LLP_D_EN | DWC_CTLL_LLP_S_EN);
channel_writel(dwc, CTL_HI, 0);
channel_set_bit(dw, CH_EN, dwc->mask);
}
/*----------------------------------------------------------------------*/
static void
dwc_descriptor_complete(struct dw_dma_chan *dwc, struct dw_desc *desc,
bool callback_required)
{
dma_async_tx_callback callback = NULL;
void *param = NULL;
struct dma_async_tx_descriptor *txd = &desc->txd;
struct dw_desc *child;
unsigned long flags;
dev_vdbg(chan2dev(&dwc->chan), "descriptor %u complete\n", txd->cookie);
spin_lock_irqsave(&dwc->lock, flags);
dma_cookie_complete(txd);
if (callback_required) {
callback = txd->callback;
param = txd->callback_param;
}
/* async_tx_ack */
list_for_each_entry(child, &desc->tx_list, desc_node)
async_tx_ack(&child->txd);
async_tx_ack(&desc->txd);
list_splice_init(&desc->tx_list, &dwc->free_list);
list_move(&desc->desc_node, &dwc->free_list);
if (!is_slave_direction(dwc->direction)) {
struct device *parent = chan2parent(&dwc->chan);
if (!(txd->flags & DMA_COMPL_SKIP_DEST_UNMAP)) {
if (txd->flags & DMA_COMPL_DEST_UNMAP_SINGLE)
dma_unmap_single(parent, desc->lli.dar,
desc->total_len, DMA_FROM_DEVICE);
else
dma_unmap_page(parent, desc->lli.dar,
desc->total_len, DMA_FROM_DEVICE);
}
if (!(txd->flags & DMA_COMPL_SKIP_SRC_UNMAP)) {
if (txd->flags & DMA_COMPL_SRC_UNMAP_SINGLE)
dma_unmap_single(parent, desc->lli.sar,
desc->total_len, DMA_TO_DEVICE);
else
dma_unmap_page(parent, desc->lli.sar,
desc->total_len, DMA_TO_DEVICE);
}
}
spin_unlock_irqrestore(&dwc->lock, flags);
if (callback)
callback(param);
}
static void dwc_complete_all(struct dw_dma *dw, struct dw_dma_chan *dwc)
{
struct dw_desc *desc, *_desc;
LIST_HEAD(list);
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
if (dma_readl(dw, CH_EN) & dwc->mask) {
dev_err(chan2dev(&dwc->chan),
"BUG: XFER bit set, but channel not idle!\n");
/* Try to continue after resetting the channel... */
dwc_chan_disable(dw, dwc);
}
/*
* Submit queued descriptors ASAP, i.e. before we go through
* the completed ones.
*/
list_splice_init(&dwc->active_list, &list);
if (!list_empty(&dwc->queue)) {
list_move(dwc->queue.next, &dwc->active_list);
dwc_dostart(dwc, dwc_first_active(dwc));
}
spin_unlock_irqrestore(&dwc->lock, flags);
list_for_each_entry_safe(desc, _desc, &list, desc_node)
dwc_descriptor_complete(dwc, desc, true);
}
/* Returns how many bytes were already received from source */
static inline u32 dwc_get_sent(struct dw_dma_chan *dwc)
{
u32 ctlhi = channel_readl(dwc, CTL_HI);
u32 ctllo = channel_readl(dwc, CTL_LO);
return (ctlhi & DWC_CTLH_BLOCK_TS_MASK) * (1 << (ctllo >> 4 & 7));
}
static void dwc_scan_descriptors(struct dw_dma *dw, struct dw_dma_chan *dwc)
{
dma_addr_t llp;
struct dw_desc *desc, *_desc;
struct dw_desc *child;
u32 status_xfer;
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
llp = channel_readl(dwc, LLP);
status_xfer = dma_readl(dw, RAW.XFER);
if (status_xfer & dwc->mask) {
/* Everything we've submitted is done */
dma_writel(dw, CLEAR.XFER, dwc->mask);
if (test_bit(DW_DMA_IS_SOFT_LLP, &dwc->flags)) {
struct list_head *head, *active = dwc->tx_node_active;
/*
* We are inside first active descriptor.
* Otherwise something is really wrong.
*/
desc = dwc_first_active(dwc);
head = &desc->tx_list;
if (active != head) {
/* Update desc to reflect last sent one */
if (active != head->next)
desc = to_dw_desc(active->prev);
dwc->residue -= desc->len;
child = to_dw_desc(active);
/* Submit next block */
dwc_do_single_block(dwc, child);
spin_unlock_irqrestore(&dwc->lock, flags);
return;
}
/* We are done here */
clear_bit(DW_DMA_IS_SOFT_LLP, &dwc->flags);
}
dwc->residue = 0;
spin_unlock_irqrestore(&dwc->lock, flags);
dwc_complete_all(dw, dwc);
return;
}
if (list_empty(&dwc->active_list)) {
dwc->residue = 0;
spin_unlock_irqrestore(&dwc->lock, flags);
return;
}
if (test_bit(DW_DMA_IS_SOFT_LLP, &dwc->flags)) {
dev_vdbg(chan2dev(&dwc->chan), "%s: soft LLP mode\n", __func__);
spin_unlock_irqrestore(&dwc->lock, flags);
return;
}
dev_vdbg(chan2dev(&dwc->chan), "%s: llp=0x%llx\n", __func__,
(unsigned long long)llp);
list_for_each_entry_safe(desc, _desc, &dwc->active_list, desc_node) {
/* Initial residue value */
dwc->residue = desc->total_len;
/* Check first descriptors addr */
if (desc->txd.phys == llp) {
spin_unlock_irqrestore(&dwc->lock, flags);
return;
}
/* Check first descriptors llp */
if (desc->lli.llp == llp) {
/* This one is currently in progress */
dwc->residue -= dwc_get_sent(dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
return;
}
dwc->residue -= desc->len;
list_for_each_entry(child, &desc->tx_list, desc_node) {
if (child->lli.llp == llp) {
/* Currently in progress */
dwc->residue -= dwc_get_sent(dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
return;
}
dwc->residue -= child->len;
}
/*
* No descriptors so far seem to be in progress, i.e.
* this one must be done.
*/
spin_unlock_irqrestore(&dwc->lock, flags);
dwc_descriptor_complete(dwc, desc, true);
spin_lock_irqsave(&dwc->lock, flags);
}
dev_err(chan2dev(&dwc->chan),
"BUG: All descriptors done, but channel not idle!\n");
/* Try to continue after resetting the channel... */
dwc_chan_disable(dw, dwc);
if (!list_empty(&dwc->queue)) {
list_move(dwc->queue.next, &dwc->active_list);
dwc_dostart(dwc, dwc_first_active(dwc));
}
spin_unlock_irqrestore(&dwc->lock, flags);
}
static inline void dwc_dump_lli(struct dw_dma_chan *dwc, struct dw_lli *lli)
{
dev_crit(chan2dev(&dwc->chan), " desc: s0x%x d0x%x l0x%x c0x%x:%x\n",
lli->sar, lli->dar, lli->llp, lli->ctlhi, lli->ctllo);
}
static void dwc_handle_error(struct dw_dma *dw, struct dw_dma_chan *dwc)
{
struct dw_desc *bad_desc;
struct dw_desc *child;
unsigned long flags;
dwc_scan_descriptors(dw, dwc);
spin_lock_irqsave(&dwc->lock, flags);
/*
* The descriptor currently at the head of the active list is
* borked. Since we don't have any way to report errors, we'll
* just have to scream loudly and try to carry on.
*/
bad_desc = dwc_first_active(dwc);
list_del_init(&bad_desc->desc_node);
list_move(dwc->queue.next, dwc->active_list.prev);
/* Clear the error flag and try to restart the controller */
dma_writel(dw, CLEAR.ERROR, dwc->mask);
if (!list_empty(&dwc->active_list))
dwc_dostart(dwc, dwc_first_active(dwc));
/*
* WARN may seem harsh, but since this only happens
* when someone submits a bad physical address in a
* descriptor, we should consider ourselves lucky that the
* controller flagged an error instead of scribbling over
* random memory locations.
*/
dev_WARN(chan2dev(&dwc->chan), "Bad descriptor submitted for DMA!\n"
" cookie: %d\n", bad_desc->txd.cookie);
dwc_dump_lli(dwc, &bad_desc->lli);
list_for_each_entry(child, &bad_desc->tx_list, desc_node)
dwc_dump_lli(dwc, &child->lli);
spin_unlock_irqrestore(&dwc->lock, flags);
/* Pretend the descriptor completed successfully */
dwc_descriptor_complete(dwc, bad_desc, true);
}
/* --------------------- Cyclic DMA API extensions -------------------- */
inline dma_addr_t dw_dma_get_src_addr(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
return channel_readl(dwc, SAR);
}
EXPORT_SYMBOL(dw_dma_get_src_addr);
inline dma_addr_t dw_dma_get_dst_addr(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
return channel_readl(dwc, DAR);
}
EXPORT_SYMBOL(dw_dma_get_dst_addr);
/* Called with dwc->lock held and all DMAC interrupts disabled */
static void dwc_handle_cyclic(struct dw_dma *dw, struct dw_dma_chan *dwc,
u32 status_err, u32 status_xfer)
{
unsigned long flags;
if (dwc->mask) {
void (*callback)(void *param);
void *callback_param;
dev_vdbg(chan2dev(&dwc->chan), "new cyclic period llp 0x%08x\n",
channel_readl(dwc, LLP));
callback = dwc->cdesc->period_callback;
callback_param = dwc->cdesc->period_callback_param;
if (callback)
callback(callback_param);
}
/*
* Error and transfer complete are highly unlikely, and will most
* likely be due to a configuration error by the user.
*/
if (unlikely(status_err & dwc->mask) ||
unlikely(status_xfer & dwc->mask)) {
int i;
dev_err(chan2dev(&dwc->chan), "cyclic DMA unexpected %s "
"interrupt, stopping DMA transfer\n",
status_xfer ? "xfer" : "error");
spin_lock_irqsave(&dwc->lock, flags);
dwc_dump_chan_regs(dwc);
dwc_chan_disable(dw, dwc);
/* Make sure DMA does not restart by loading a new list */
channel_writel(dwc, LLP, 0);
channel_writel(dwc, CTL_LO, 0);
channel_writel(dwc, CTL_HI, 0);
dma_writel(dw, CLEAR.ERROR, dwc->mask);
dma_writel(dw, CLEAR.XFER, dwc->mask);
for (i = 0; i < dwc->cdesc->periods; i++)
dwc_dump_lli(dwc, &dwc->cdesc->desc[i]->lli);
spin_unlock_irqrestore(&dwc->lock, flags);
}
}
/* ------------------------------------------------------------------------- */
static void dw_dma_tasklet(unsigned long data)
{
struct dw_dma *dw = (struct dw_dma *)data;
struct dw_dma_chan *dwc;
u32 status_xfer;
u32 status_err;
int i;
status_xfer = dma_readl(dw, RAW.XFER);
status_err = dma_readl(dw, RAW.ERROR);
dev_vdbg(dw->dma.dev, "%s: status_err=%x\n", __func__, status_err);
for (i = 0; i < dw->dma.chancnt; i++) {
dwc = &dw->chan[i];
if (test_bit(DW_DMA_IS_CYCLIC, &dwc->flags))
dwc_handle_cyclic(dw, dwc, status_err, status_xfer);
else if (status_err & (1 << i))
dwc_handle_error(dw, dwc);
else if (status_xfer & (1 << i))
dwc_scan_descriptors(dw, dwc);
}
/*
* Re-enable interrupts.
*/
channel_set_bit(dw, MASK.XFER, dw->all_chan_mask);
channel_set_bit(dw, MASK.ERROR, dw->all_chan_mask);
}
static irqreturn_t dw_dma_interrupt(int irq, void *dev_id)
{
struct dw_dma *dw = dev_id;
u32 status;
dev_vdbg(dw->dma.dev, "%s: status=0x%x\n", __func__,
dma_readl(dw, STATUS_INT));
/*
* Just disable the interrupts. We'll turn them back on in the
* softirq handler.
*/
channel_clear_bit(dw, MASK.XFER, dw->all_chan_mask);
channel_clear_bit(dw, MASK.ERROR, dw->all_chan_mask);
status = dma_readl(dw, STATUS_INT);
if (status) {
dev_err(dw->dma.dev,
"BUG: Unexpected interrupts pending: 0x%x\n",
status);
/* Try to recover */
channel_clear_bit(dw, MASK.XFER, (1 << 8) - 1);
channel_clear_bit(dw, MASK.SRC_TRAN, (1 << 8) - 1);
channel_clear_bit(dw, MASK.DST_TRAN, (1 << 8) - 1);
channel_clear_bit(dw, MASK.ERROR, (1 << 8) - 1);
}
tasklet_schedule(&dw->tasklet);
return IRQ_HANDLED;
}
/*----------------------------------------------------------------------*/
static dma_cookie_t dwc_tx_submit(struct dma_async_tx_descriptor *tx)
{
struct dw_desc *desc = txd_to_dw_desc(tx);
struct dw_dma_chan *dwc = to_dw_dma_chan(tx->chan);
dma_cookie_t cookie;
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
cookie = dma_cookie_assign(tx);
/*
* REVISIT: We should attempt to chain as many descriptors as
* possible, perhaps even appending to those already submitted
* for DMA. But this is hard to do in a race-free manner.
*/
if (list_empty(&dwc->active_list)) {
dev_vdbg(chan2dev(tx->chan), "%s: started %u\n", __func__,
desc->txd.cookie);
list_add_tail(&desc->desc_node, &dwc->active_list);
dwc_dostart(dwc, dwc_first_active(dwc));
} else {
dev_vdbg(chan2dev(tx->chan), "%s: queued %u\n", __func__,
desc->txd.cookie);
list_add_tail(&desc->desc_node, &dwc->queue);
}
spin_unlock_irqrestore(&dwc->lock, flags);
return cookie;
}
static struct dma_async_tx_descriptor *
dwc_prep_dma_memcpy(struct dma_chan *chan, dma_addr_t dest, dma_addr_t src,
size_t len, unsigned long flags)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(chan->device);
struct dw_desc *desc;
struct dw_desc *first;
struct dw_desc *prev;
size_t xfer_count;
size_t offset;
unsigned int src_width;
unsigned int dst_width;
unsigned int data_width;
u32 ctllo;
dev_vdbg(chan2dev(chan),
"%s: d0x%llx s0x%llx l0x%zx f0x%lx\n", __func__,
(unsigned long long)dest, (unsigned long long)src,
len, flags);
if (unlikely(!len)) {
dev_dbg(chan2dev(chan), "%s: length is zero!\n", __func__);
return NULL;
}
dwc->direction = DMA_MEM_TO_MEM;
data_width = min_t(unsigned int, dw->data_width[dwc->src_master],
dw->data_width[dwc->dst_master]);
src_width = dst_width = min_t(unsigned int, data_width,
dwc_fast_fls(src | dest | len));
ctllo = DWC_DEFAULT_CTLLO(chan)
| DWC_CTLL_DST_WIDTH(dst_width)
| DWC_CTLL_SRC_WIDTH(src_width)
| DWC_CTLL_DST_INC
| DWC_CTLL_SRC_INC
| DWC_CTLL_FC_M2M;
prev = first = NULL;
for (offset = 0; offset < len; offset += xfer_count << src_width) {
xfer_count = min_t(size_t, (len - offset) >> src_width,
dwc->block_size);
desc = dwc_desc_get(dwc);
if (!desc)
goto err_desc_get;
desc->lli.sar = src + offset;
desc->lli.dar = dest + offset;
desc->lli.ctllo = ctllo;
desc->lli.ctlhi = xfer_count;
desc->len = xfer_count << src_width;
if (!first) {
first = desc;
} else {
prev->lli.llp = desc->txd.phys;
list_add_tail(&desc->desc_node,
&first->tx_list);
}
prev = desc;
}
if (flags & DMA_PREP_INTERRUPT)
/* Trigger interrupt after last block */
prev->lli.ctllo |= DWC_CTLL_INT_EN;
prev->lli.llp = 0;
first->txd.flags = flags;
first->total_len = len;
return &first->txd;
err_desc_get:
dwc_desc_put(dwc, first);
return NULL;
}
static struct dma_async_tx_descriptor *
dwc_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
unsigned int sg_len, enum dma_transfer_direction direction,
unsigned long flags, void *context)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(chan->device);
struct dma_slave_config *sconfig = &dwc->dma_sconfig;
struct dw_desc *prev;
struct dw_desc *first;
u32 ctllo;
dma_addr_t reg;
unsigned int reg_width;
unsigned int mem_width;
unsigned int data_width;
unsigned int i;
struct scatterlist *sg;
size_t total_len = 0;
dev_vdbg(chan2dev(chan), "%s\n", __func__);
if (unlikely(!is_slave_direction(direction) || !sg_len))
return NULL;
dwc->direction = direction;
prev = first = NULL;
switch (direction) {
case DMA_MEM_TO_DEV:
reg_width = __fls(sconfig->dst_addr_width);
reg = sconfig->dst_addr;
ctllo = (DWC_DEFAULT_CTLLO(chan)
| DWC_CTLL_DST_WIDTH(reg_width)
| DWC_CTLL_DST_FIX
| DWC_CTLL_SRC_INC);
ctllo |= sconfig->device_fc ? DWC_CTLL_FC(DW_DMA_FC_P_M2P) :
DWC_CTLL_FC(DW_DMA_FC_D_M2P);
data_width = dw->data_width[dwc->src_master];
for_each_sg(sgl, sg, sg_len, i) {
struct dw_desc *desc;
u32 len, dlen, mem;
mem = sg_dma_address(sg);
len = sg_dma_len(sg);
mem_width = min_t(unsigned int,
data_width, dwc_fast_fls(mem | len));
slave_sg_todev_fill_desc:
desc = dwc_desc_get(dwc);
if (!desc) {
dev_err(chan2dev(chan),
"not enough descriptors available\n");
goto err_desc_get;
}
desc->lli.sar = mem;
desc->lli.dar = reg;
desc->lli.ctllo = ctllo | DWC_CTLL_SRC_WIDTH(mem_width);
if ((len >> mem_width) > dwc->block_size) {
dlen = dwc->block_size << mem_width;
mem += dlen;
len -= dlen;
} else {
dlen = len;
len = 0;
}
desc->lli.ctlhi = dlen >> mem_width;
desc->len = dlen;
if (!first) {
first = desc;
} else {
prev->lli.llp = desc->txd.phys;
list_add_tail(&desc->desc_node,
&first->tx_list);
}
prev = desc;
total_len += dlen;
if (len)
goto slave_sg_todev_fill_desc;
}
break;
case DMA_DEV_TO_MEM:
reg_width = __fls(sconfig->src_addr_width);
reg = sconfig->src_addr;
ctllo = (DWC_DEFAULT_CTLLO(chan)
| DWC_CTLL_SRC_WIDTH(reg_width)
| DWC_CTLL_DST_INC
| DWC_CTLL_SRC_FIX);
ctllo |= sconfig->device_fc ? DWC_CTLL_FC(DW_DMA_FC_P_P2M) :
DWC_CTLL_FC(DW_DMA_FC_D_P2M);
data_width = dw->data_width[dwc->dst_master];
for_each_sg(sgl, sg, sg_len, i) {
struct dw_desc *desc;
u32 len, dlen, mem;
mem = sg_dma_address(sg);
len = sg_dma_len(sg);
mem_width = min_t(unsigned int,
data_width, dwc_fast_fls(mem | len));
slave_sg_fromdev_fill_desc:
desc = dwc_desc_get(dwc);
if (!desc) {
dev_err(chan2dev(chan),
"not enough descriptors available\n");
goto err_desc_get;
}
desc->lli.sar = reg;
desc->lli.dar = mem;
desc->lli.ctllo = ctllo | DWC_CTLL_DST_WIDTH(mem_width);
if ((len >> reg_width) > dwc->block_size) {
dlen = dwc->block_size << reg_width;
mem += dlen;
len -= dlen;
} else {
dlen = len;
len = 0;
}
desc->lli.ctlhi = dlen >> reg_width;
desc->len = dlen;
if (!first) {
first = desc;
} else {
prev->lli.llp = desc->txd.phys;
list_add_tail(&desc->desc_node,
&first->tx_list);
}
prev = desc;
total_len += dlen;
if (len)
goto slave_sg_fromdev_fill_desc;
}
break;
default:
return NULL;
}
if (flags & DMA_PREP_INTERRUPT)
/* Trigger interrupt after last block */
prev->lli.ctllo |= DWC_CTLL_INT_EN;
prev->lli.llp = 0;
first->total_len = total_len;
return &first->txd;
err_desc_get:
dwc_desc_put(dwc, first);
return NULL;
}
/*
* Fix sconfig's burst size according to dw_dmac. We need to convert them as:
* 1 -> 0, 4 -> 1, 8 -> 2, 16 -> 3.
*
* NOTE: burst size 2 is not supported by controller.
*
* This can be done by finding least significant bit set: n & (n - 1)
*/
static inline void convert_burst(u32 *maxburst)
{
if (*maxburst > 1)
*maxburst = fls(*maxburst) - 2;
else
*maxburst = 0;
}
static int
set_runtime_config(struct dma_chan *chan, struct dma_slave_config *sconfig)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
/* Check if chan will be configured for slave transfers */
if (!is_slave_direction(sconfig->direction))
return -EINVAL;
memcpy(&dwc->dma_sconfig, sconfig, sizeof(*sconfig));
dwc->direction = sconfig->direction;
/* Take the request line from slave_id member */
if (dwc->request_line == ~0)
dwc->request_line = sconfig->slave_id;
convert_burst(&dwc->dma_sconfig.src_maxburst);
convert_burst(&dwc->dma_sconfig.dst_maxburst);
return 0;
}
static inline void dwc_chan_pause(struct dw_dma_chan *dwc)
{
u32 cfglo = channel_readl(dwc, CFG_LO);
unsigned int count = 20; /* timeout iterations */
channel_writel(dwc, CFG_LO, cfglo | DWC_CFGL_CH_SUSP);
while (!(channel_readl(dwc, CFG_LO) & DWC_CFGL_FIFO_EMPTY) && count--)
udelay(2);
dwc->paused = true;
}
static inline void dwc_chan_resume(struct dw_dma_chan *dwc)
{
u32 cfglo = channel_readl(dwc, CFG_LO);
channel_writel(dwc, CFG_LO, cfglo & ~DWC_CFGL_CH_SUSP);
dwc->paused = false;
}
static int dwc_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd,
unsigned long arg)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(chan->device);
struct dw_desc *desc, *_desc;
unsigned long flags;
LIST_HEAD(list);
if (cmd == DMA_PAUSE) {
spin_lock_irqsave(&dwc->lock, flags);
dwc_chan_pause(dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
} else if (cmd == DMA_RESUME) {
if (!dwc->paused)
return 0;
spin_lock_irqsave(&dwc->lock, flags);
dwc_chan_resume(dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
} else if (cmd == DMA_TERMINATE_ALL) {
spin_lock_irqsave(&dwc->lock, flags);
clear_bit(DW_DMA_IS_SOFT_LLP, &dwc->flags);
dwc_chan_disable(dw, dwc);
dwc_chan_resume(dwc);
/* active_list entries will end up before queued entries */
list_splice_init(&dwc->queue, &list);
list_splice_init(&dwc->active_list, &list);
spin_unlock_irqrestore(&dwc->lock, flags);
/* Flush all pending and queued descriptors */
list_for_each_entry_safe(desc, _desc, &list, desc_node)
dwc_descriptor_complete(dwc, desc, false);
} else if (cmd == DMA_SLAVE_CONFIG) {
return set_runtime_config(chan, (struct dma_slave_config *)arg);
} else {
return -ENXIO;
}
return 0;
}
static inline u32 dwc_get_residue(struct dw_dma_chan *dwc)
{
unsigned long flags;
u32 residue;
spin_lock_irqsave(&dwc->lock, flags);
residue = dwc->residue;
if (test_bit(DW_DMA_IS_SOFT_LLP, &dwc->flags) && residue)
residue -= dwc_get_sent(dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
return residue;
}
static enum dma_status
dwc_tx_status(struct dma_chan *chan,
dma_cookie_t cookie,
struct dma_tx_state *txstate)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
enum dma_status ret;
ret = dma_cookie_status(chan, cookie, txstate);
if (ret != DMA_SUCCESS) {
dwc_scan_descriptors(to_dw_dma(chan->device), dwc);
ret = dma_cookie_status(chan, cookie, txstate);
}
if (ret != DMA_SUCCESS)
dma_set_residue(txstate, dwc_get_residue(dwc));
if (dwc->paused)
return DMA_PAUSED;
return ret;
}
static void dwc_issue_pending(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
if (!list_empty(&dwc->queue))
dwc_scan_descriptors(to_dw_dma(chan->device), dwc);
}
static int dwc_alloc_chan_resources(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(chan->device);
struct dw_desc *desc;
int i;
unsigned long flags;
dev_vdbg(chan2dev(chan), "%s\n", __func__);
/* ASSERT: channel is idle */
if (dma_readl(dw, CH_EN) & dwc->mask) {
dev_dbg(chan2dev(chan), "DMA channel not idle?\n");
return -EIO;
}
dma_cookie_init(chan);
/*
* NOTE: some controllers may have additional features that we
* need to initialize here, like "scatter-gather" (which
* doesn't mean what you think it means), and status writeback.
*/
dwc_set_masters(dwc);
spin_lock_irqsave(&dwc->lock, flags);
i = dwc->descs_allocated;
while (dwc->descs_allocated < NR_DESCS_PER_CHANNEL) {
dma_addr_t phys;
spin_unlock_irqrestore(&dwc->lock, flags);
desc = dma_pool_alloc(dw->desc_pool, GFP_ATOMIC, &phys);
if (!desc)
goto err_desc_alloc;
memset(desc, 0, sizeof(struct dw_desc));
INIT_LIST_HEAD(&desc->tx_list);
dma_async_tx_descriptor_init(&desc->txd, chan);
desc->txd.tx_submit = dwc_tx_submit;
desc->txd.flags = DMA_CTRL_ACK;
desc->txd.phys = phys;
dwc_desc_put(dwc, desc);
spin_lock_irqsave(&dwc->lock, flags);
i = ++dwc->descs_allocated;
}
spin_unlock_irqrestore(&dwc->lock, flags);
dev_dbg(chan2dev(chan), "%s: allocated %d descriptors\n", __func__, i);
return i;
err_desc_alloc:
dev_info(chan2dev(chan), "only allocated %d descriptors\n", i);
return i;
}
static void dwc_free_chan_resources(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(chan->device);
struct dw_desc *desc, *_desc;
unsigned long flags;
LIST_HEAD(list);
dev_dbg(chan2dev(chan), "%s: descs allocated=%u\n", __func__,
dwc->descs_allocated);
/* ASSERT: channel is idle */
BUG_ON(!list_empty(&dwc->active_list));
BUG_ON(!list_empty(&dwc->queue));
BUG_ON(dma_readl(to_dw_dma(chan->device), CH_EN) & dwc->mask);
spin_lock_irqsave(&dwc->lock, flags);
list_splice_init(&dwc->free_list, &list);
dwc->descs_allocated = 0;
dwc->initialized = false;
dwc->request_line = ~0;
/* Disable interrupts */
channel_clear_bit(dw, MASK.XFER, dwc->mask);
channel_clear_bit(dw, MASK.ERROR, dwc->mask);
spin_unlock_irqrestore(&dwc->lock, flags);
list_for_each_entry_safe(desc, _desc, &list, desc_node) {
dev_vdbg(chan2dev(chan), " freeing descriptor %p\n", desc);
dma_pool_free(dw->desc_pool, desc, desc->txd.phys);
}
dev_vdbg(chan2dev(chan), "%s: done\n", __func__);
}
/*----------------------------------------------------------------------*/
struct dw_dma_of_filter_args {
struct dw_dma *dw;
unsigned int req;
unsigned int src;
unsigned int dst;
};
static bool dw_dma_of_filter(struct dma_chan *chan, void *param)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma_of_filter_args *fargs = param;
/* Ensure the device matches our channel */
if (chan->device != &fargs->dw->dma)
return false;
dwc->request_line = fargs->req;
dwc->src_master = fargs->src;
dwc->dst_master = fargs->dst;
return true;
}
static struct dma_chan *dw_dma_of_xlate(struct of_phandle_args *dma_spec,
struct of_dma *ofdma)
{
struct dw_dma *dw = ofdma->of_dma_data;
struct dw_dma_of_filter_args fargs = {
.dw = dw,
};
dma_cap_mask_t cap;
if (dma_spec->args_count != 3)
return NULL;
fargs.req = dma_spec->args[0];
fargs.src = dma_spec->args[1];
fargs.dst = dma_spec->args[2];
if (WARN_ON(fargs.req >= DW_DMA_MAX_NR_REQUESTS ||
fargs.src >= dw->nr_masters ||
fargs.dst >= dw->nr_masters))
return NULL;
dma_cap_zero(cap);
dma_cap_set(DMA_SLAVE, cap);
/* TODO: there should be a simpler way to do this */
return dma_request_channel(cap, dw_dma_of_filter, &fargs);
}
#ifdef CONFIG_ACPI
static bool dw_dma_acpi_filter(struct dma_chan *chan, void *param)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct acpi_dma_spec *dma_spec = param;
if (chan->device->dev != dma_spec->dev ||
chan->chan_id != dma_spec->chan_id)
return false;
dwc->request_line = dma_spec->slave_id;
dwc->src_master = dwc_get_sms(NULL);
dwc->dst_master = dwc_get_dms(NULL);
return true;
}
static void dw_dma_acpi_controller_register(struct dw_dma *dw)
{
struct device *dev = dw->dma.dev;
struct acpi_dma_filter_info *info;
int ret;
info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
if (!info)
return;
dma_cap_zero(info->dma_cap);
dma_cap_set(DMA_SLAVE, info->dma_cap);
info->filter_fn = dw_dma_acpi_filter;
ret = devm_acpi_dma_controller_register(dev, acpi_dma_simple_xlate,
info);
if (ret)
dev_err(dev, "could not register acpi_dma_controller\n");
}
#else /* !CONFIG_ACPI */
static inline void dw_dma_acpi_controller_register(struct dw_dma *dw) {}
#endif /* !CONFIG_ACPI */
/* --------------------- Cyclic DMA API extensions -------------------- */
/**
* dw_dma_cyclic_start - start the cyclic DMA transfer
* @chan: the DMA channel to start
*
* Must be called with soft interrupts disabled. Returns zero on success or
* -errno on failure.
*/
int dw_dma_cyclic_start(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(dwc->chan.device);
unsigned long flags;
if (!test_bit(DW_DMA_IS_CYCLIC, &dwc->flags)) {
dev_err(chan2dev(&dwc->chan), "missing prep for cyclic DMA\n");
return -ENODEV;
}
spin_lock_irqsave(&dwc->lock, flags);
/* Assert channel is idle */
if (dma_readl(dw, CH_EN) & dwc->mask) {
dev_err(chan2dev(&dwc->chan),
"BUG: Attempted to start non-idle channel\n");
dwc_dump_chan_regs(dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
return -EBUSY;
}
dma_writel(dw, CLEAR.ERROR, dwc->mask);
dma_writel(dw, CLEAR.XFER, dwc->mask);
/* Setup DMAC channel registers */
channel_writel(dwc, LLP, dwc->cdesc->desc[0]->txd.phys);
channel_writel(dwc, CTL_LO, DWC_CTLL_LLP_D_EN | DWC_CTLL_LLP_S_EN);
channel_writel(dwc, CTL_HI, 0);
channel_set_bit(dw, CH_EN, dwc->mask);
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
}
EXPORT_SYMBOL(dw_dma_cyclic_start);
/**
* dw_dma_cyclic_stop - stop the cyclic DMA transfer
* @chan: the DMA channel to stop
*
* Must be called with soft interrupts disabled.
*/
void dw_dma_cyclic_stop(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(dwc->chan.device);
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
dwc_chan_disable(dw, dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
}
EXPORT_SYMBOL(dw_dma_cyclic_stop);
/**
* dw_dma_cyclic_prep - prepare the cyclic DMA transfer
* @chan: the DMA channel to prepare
* @buf_addr: physical DMA address where the buffer starts
* @buf_len: total number of bytes for the entire buffer
* @period_len: number of bytes for each period
* @direction: transfer direction, to or from device
*
* Must be called before trying to start the transfer. Returns a valid struct
* dw_cyclic_desc if successful or an ERR_PTR(-errno) if not successful.
*/
struct dw_cyclic_desc *dw_dma_cyclic_prep(struct dma_chan *chan,
dma_addr_t buf_addr, size_t buf_len, size_t period_len,
enum dma_transfer_direction direction)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dma_slave_config *sconfig = &dwc->dma_sconfig;
struct dw_cyclic_desc *cdesc;
struct dw_cyclic_desc *retval = NULL;
struct dw_desc *desc;
struct dw_desc *last = NULL;
unsigned long was_cyclic;
unsigned int reg_width;
unsigned int periods;
unsigned int i;
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
if (dwc->nollp) {
spin_unlock_irqrestore(&dwc->lock, flags);
dev_dbg(chan2dev(&dwc->chan),
"channel doesn't support LLP transfers\n");
return ERR_PTR(-EINVAL);
}
if (!list_empty(&dwc->queue) || !list_empty(&dwc->active_list)) {
spin_unlock_irqrestore(&dwc->lock, flags);
dev_dbg(chan2dev(&dwc->chan),
"queue and/or active list are not empty\n");
return ERR_PTR(-EBUSY);
}
was_cyclic = test_and_set_bit(DW_DMA_IS_CYCLIC, &dwc->flags);
spin_unlock_irqrestore(&dwc->lock, flags);
if (was_cyclic) {
dev_dbg(chan2dev(&dwc->chan),
"channel already prepared for cyclic DMA\n");
return ERR_PTR(-EBUSY);
}
retval = ERR_PTR(-EINVAL);
if (unlikely(!is_slave_direction(direction)))
goto out_err;
dwc->direction = direction;
if (direction == DMA_MEM_TO_DEV)
reg_width = __ffs(sconfig->dst_addr_width);
else
reg_width = __ffs(sconfig->src_addr_width);
periods = buf_len / period_len;
/* Check for too big/unaligned periods and unaligned DMA buffer. */
if (period_len > (dwc->block_size << reg_width))
goto out_err;
if (unlikely(period_len & ((1 << reg_width) - 1)))
goto out_err;
if (unlikely(buf_addr & ((1 << reg_width) - 1)))
goto out_err;
retval = ERR_PTR(-ENOMEM);
if (periods > NR_DESCS_PER_CHANNEL)
goto out_err;
cdesc = kzalloc(sizeof(struct dw_cyclic_desc), GFP_KERNEL);
if (!cdesc)
goto out_err;
cdesc->desc = kzalloc(sizeof(struct dw_desc *) * periods, GFP_KERNEL);
if (!cdesc->desc)
goto out_err_alloc;
for (i = 0; i < periods; i++) {
desc = dwc_desc_get(dwc);
if (!desc)
goto out_err_desc_get;
switch (direction) {
case DMA_MEM_TO_DEV:
desc->lli.dar = sconfig->dst_addr;
desc->lli.sar = buf_addr + (period_len * i);
desc->lli.ctllo = (DWC_DEFAULT_CTLLO(chan)
| DWC_CTLL_DST_WIDTH(reg_width)
| DWC_CTLL_SRC_WIDTH(reg_width)
| DWC_CTLL_DST_FIX
| DWC_CTLL_SRC_INC
| DWC_CTLL_INT_EN);
desc->lli.ctllo |= sconfig->device_fc ?
DWC_CTLL_FC(DW_DMA_FC_P_M2P) :
DWC_CTLL_FC(DW_DMA_FC_D_M2P);
break;
case DMA_DEV_TO_MEM:
desc->lli.dar = buf_addr + (period_len * i);
desc->lli.sar = sconfig->src_addr;
desc->lli.ctllo = (DWC_DEFAULT_CTLLO(chan)
| DWC_CTLL_SRC_WIDTH(reg_width)
| DWC_CTLL_DST_WIDTH(reg_width)
| DWC_CTLL_DST_INC
| DWC_CTLL_SRC_FIX
| DWC_CTLL_INT_EN);
desc->lli.ctllo |= sconfig->device_fc ?
DWC_CTLL_FC(DW_DMA_FC_P_P2M) :
DWC_CTLL_FC(DW_DMA_FC_D_P2M);
break;
default:
break;
}
desc->lli.ctlhi = (period_len >> reg_width);
cdesc->desc[i] = desc;
if (last)
last->lli.llp = desc->txd.phys;
last = desc;
}
/* Let's make a cyclic list */
last->lli.llp = cdesc->desc[0]->txd.phys;
dev_dbg(chan2dev(&dwc->chan), "cyclic prepared buf 0x%llx len %zu "
"period %zu periods %d\n", (unsigned long long)buf_addr,
buf_len, period_len, periods);
cdesc->periods = periods;
dwc->cdesc = cdesc;
return cdesc;
out_err_desc_get:
while (i--)
dwc_desc_put(dwc, cdesc->desc[i]);
out_err_alloc:
kfree(cdesc);
out_err:
clear_bit(DW_DMA_IS_CYCLIC, &dwc->flags);
return (struct dw_cyclic_desc *)retval;
}
EXPORT_SYMBOL(dw_dma_cyclic_prep);
/**
* dw_dma_cyclic_free - free a prepared cyclic DMA transfer
* @chan: the DMA channel to free
*/
void dw_dma_cyclic_free(struct dma_chan *chan)
{
struct dw_dma_chan *dwc = to_dw_dma_chan(chan);
struct dw_dma *dw = to_dw_dma(dwc->chan.device);
struct dw_cyclic_desc *cdesc = dwc->cdesc;
int i;
unsigned long flags;
dev_dbg(chan2dev(&dwc->chan), "%s\n", __func__);
if (!cdesc)
return;
spin_lock_irqsave(&dwc->lock, flags);
dwc_chan_disable(dw, dwc);
dma_writel(dw, CLEAR.ERROR, dwc->mask);
dma_writel(dw, CLEAR.XFER, dwc->mask);
spin_unlock_irqrestore(&dwc->lock, flags);
for (i = 0; i < cdesc->periods; i++)
dwc_desc_put(dwc, cdesc->desc[i]);
kfree(cdesc->desc);
kfree(cdesc);
clear_bit(DW_DMA_IS_CYCLIC, &dwc->flags);
}
EXPORT_SYMBOL(dw_dma_cyclic_free);
/*----------------------------------------------------------------------*/
static void dw_dma_off(struct dw_dma *dw)
{
int i;
dma_writel(dw, CFG, 0);
channel_clear_bit(dw, MASK.XFER, dw->all_chan_mask);
channel_clear_bit(dw, MASK.SRC_TRAN, dw->all_chan_mask);
channel_clear_bit(dw, MASK.DST_TRAN, dw->all_chan_mask);
channel_clear_bit(dw, MASK.ERROR, dw->all_chan_mask);
while (dma_readl(dw, CFG) & DW_CFG_DMA_EN)
cpu_relax();
for (i = 0; i < dw->dma.chancnt; i++)
dw->chan[i].initialized = false;
}
#ifdef CONFIG_OF
static struct dw_dma_platform_data *
dw_dma_parse_dt(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct dw_dma_platform_data *pdata;
u32 tmp, arr[4];
if (!np) {
dev_err(&pdev->dev, "Missing DT data\n");
return NULL;
}
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return NULL;
if (of_property_read_u32(np, "dma-channels", &pdata->nr_channels))
return NULL;
if (of_property_read_bool(np, "is_private"))
pdata->is_private = true;
if (!of_property_read_u32(np, "chan_allocation_order", &tmp))
pdata->chan_allocation_order = (unsigned char)tmp;
if (!of_property_read_u32(np, "chan_priority", &tmp))
pdata->chan_priority = tmp;
if (!of_property_read_u32(np, "block_size", &tmp))
pdata->block_size = tmp;
if (!of_property_read_u32(np, "dma-masters", &tmp)) {
if (tmp > 4)
return NULL;
pdata->nr_masters = tmp;
}
if (!of_property_read_u32_array(np, "data_width", arr,
pdata->nr_masters))
for (tmp = 0; tmp < pdata->nr_masters; tmp++)
pdata->data_width[tmp] = arr[tmp];
return pdata;
}
#else
static inline struct dw_dma_platform_data *
dw_dma_parse_dt(struct platform_device *pdev)
{
return NULL;
}
#endif
static int dw_probe(struct platform_device *pdev)
{
struct dw_dma_platform_data *pdata;
struct resource *io;
struct dw_dma *dw;
size_t size;
void __iomem *regs;
bool autocfg;
unsigned int dw_params;
unsigned int nr_channels;
unsigned int max_blk_size = 0;
int irq;
int err;
int i;
io = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!io)
return -EINVAL;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
regs = devm_ioremap_resource(&pdev->dev, io);
if (IS_ERR(regs))
return PTR_ERR(regs);
/* Apply default dma_mask if needed */
if (!pdev->dev.dma_mask) {
pdev->dev.dma_mask = &pdev->dev.coherent_dma_mask;
pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32);
}
dw_params = dma_read_byaddr(regs, DW_PARAMS);
autocfg = dw_params >> DW_PARAMS_EN & 0x1;
dev_dbg(&pdev->dev, "DW_PARAMS: 0x%08x\n", dw_params);
pdata = dev_get_platdata(&pdev->dev);
if (!pdata)
pdata = dw_dma_parse_dt(pdev);
if (!pdata && autocfg) {
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
/* Fill platform data with the default values */
pdata->is_private = true;
pdata->chan_allocation_order = CHAN_ALLOCATION_ASCENDING;
pdata->chan_priority = CHAN_PRIORITY_ASCENDING;
} else if (!pdata || pdata->nr_channels > DW_DMA_MAX_NR_CHANNELS)
return -EINVAL;
if (autocfg)
nr_channels = (dw_params >> DW_PARAMS_NR_CHAN & 0x7) + 1;
else
nr_channels = pdata->nr_channels;
size = sizeof(struct dw_dma) + nr_channels * sizeof(struct dw_dma_chan);
dw = devm_kzalloc(&pdev->dev, size, GFP_KERNEL);
if (!dw)
return -ENOMEM;
dw->clk = devm_clk_get(&pdev->dev, "hclk");
if (IS_ERR(dw->clk))
return PTR_ERR(dw->clk);
clk_prepare_enable(dw->clk);
dw->regs = regs;
/* Get hardware configuration parameters */
if (autocfg) {
max_blk_size = dma_readl(dw, MAX_BLK_SIZE);
dw->nr_masters = (dw_params >> DW_PARAMS_NR_MASTER & 3) + 1;
for (i = 0; i < dw->nr_masters; i++) {
dw->data_width[i] =
(dw_params >> DW_PARAMS_DATA_WIDTH(i) & 3) + 2;
}
} else {
dw->nr_masters = pdata->nr_masters;
memcpy(dw->data_width, pdata->data_width, 4);
}
/* Calculate all channel mask before DMA setup */
dw->all_chan_mask = (1 << nr_channels) - 1;
/* Force dma off, just in case */
dw_dma_off(dw);
/* Disable BLOCK interrupts as well */
channel_clear_bit(dw, MASK.BLOCK, dw->all_chan_mask);
err = devm_request_irq(&pdev->dev, irq, dw_dma_interrupt, 0,
"dw_dmac", dw);
if (err)
return err;
platform_set_drvdata(pdev, dw);
/* Create a pool of consistent memory blocks for hardware descriptors */
dw->desc_pool = dmam_pool_create("dw_dmac_desc_pool", &pdev->dev,
sizeof(struct dw_desc), 4, 0);
if (!dw->desc_pool) {
dev_err(&pdev->dev, "No memory for descriptors dma pool\n");
return -ENOMEM;
}
tasklet_init(&dw->tasklet, dw_dma_tasklet, (unsigned long)dw);
INIT_LIST_HEAD(&dw->dma.channels);
for (i = 0; i < nr_channels; i++) {
struct dw_dma_chan *dwc = &dw->chan[i];
int r = nr_channels - i - 1;
dwc->chan.device = &dw->dma;
dma_cookie_init(&dwc->chan);
if (pdata->chan_allocation_order == CHAN_ALLOCATION_ASCENDING)
list_add_tail(&dwc->chan.device_node,
&dw->dma.channels);
else
list_add(&dwc->chan.device_node, &dw->dma.channels);
/* 7 is highest priority & 0 is lowest. */
if (pdata->chan_priority == CHAN_PRIORITY_ASCENDING)
dwc->priority = r;
else
dwc->priority = i;
dwc->ch_regs = &__dw_regs(dw)->CHAN[i];
spin_lock_init(&dwc->lock);
dwc->mask = 1 << i;
INIT_LIST_HEAD(&dwc->active_list);
INIT_LIST_HEAD(&dwc->queue);
INIT_LIST_HEAD(&dwc->free_list);
channel_clear_bit(dw, CH_EN, dwc->mask);
dwc->direction = DMA_TRANS_NONE;
dwc->request_line = ~0;
/* Hardware configuration */
if (autocfg) {
unsigned int dwc_params;
dwc_params = dma_read_byaddr(regs + r * sizeof(u32),
DWC_PARAMS);
dev_dbg(&pdev->dev, "DWC_PARAMS[%d]: 0x%08x\n", i,
dwc_params);
/* Decode maximum block size for given channel. The
* stored 4 bit value represents blocks from 0x00 for 3
* up to 0x0a for 4095. */
dwc->block_size =
(4 << ((max_blk_size >> 4 * i) & 0xf)) - 1;
dwc->nollp =
(dwc_params >> DWC_PARAMS_MBLK_EN & 0x1) == 0;
} else {
dwc->block_size = pdata->block_size;
/* Check if channel supports multi block transfer */
channel_writel(dwc, LLP, 0xfffffffc);
dwc->nollp =
(channel_readl(dwc, LLP) & 0xfffffffc) == 0;
channel_writel(dwc, LLP, 0);
}
}
/* Clear all interrupts on all channels. */
dma_writel(dw, CLEAR.XFER, dw->all_chan_mask);
dma_writel(dw, CLEAR.BLOCK, dw->all_chan_mask);
dma_writel(dw, CLEAR.SRC_TRAN, dw->all_chan_mask);
dma_writel(dw, CLEAR.DST_TRAN, dw->all_chan_mask);
dma_writel(dw, CLEAR.ERROR, dw->all_chan_mask);
dma_cap_set(DMA_MEMCPY, dw->dma.cap_mask);
dma_cap_set(DMA_SLAVE, dw->dma.cap_mask);
if (pdata->is_private)
dma_cap_set(DMA_PRIVATE, dw->dma.cap_mask);
dw->dma.dev = &pdev->dev;
dw->dma.device_alloc_chan_resources = dwc_alloc_chan_resources;
dw->dma.device_free_chan_resources = dwc_free_chan_resources;
dw->dma.device_prep_dma_memcpy = dwc_prep_dma_memcpy;
dw->dma.device_prep_slave_sg = dwc_prep_slave_sg;
dw->dma.device_control = dwc_control;
dw->dma.device_tx_status = dwc_tx_status;
dw->dma.device_issue_pending = dwc_issue_pending;
dma_writel(dw, CFG, DW_CFG_DMA_EN);
dev_info(&pdev->dev, "DesignWare DMA Controller, %d channels\n",
nr_channels);
dma_async_device_register(&dw->dma);
if (pdev->dev.of_node) {
err = of_dma_controller_register(pdev->dev.of_node,
dw_dma_of_xlate, dw);
if (err)
dev_err(&pdev->dev,
"could not register of_dma_controller\n");
}
if (ACPI_HANDLE(&pdev->dev))
dw_dma_acpi_controller_register(dw);
return 0;
}
static int dw_remove(struct platform_device *pdev)
{
struct dw_dma *dw = platform_get_drvdata(pdev);
struct dw_dma_chan *dwc, *_dwc;
if (pdev->dev.of_node)
of_dma_controller_free(pdev->dev.of_node);
dw_dma_off(dw);
dma_async_device_unregister(&dw->dma);
tasklet_kill(&dw->tasklet);
list_for_each_entry_safe(dwc, _dwc, &dw->dma.channels,
chan.device_node) {
list_del(&dwc->chan.device_node);
channel_clear_bit(dw, CH_EN, dwc->mask);
}
return 0;
}
static void dw_shutdown(struct platform_device *pdev)
{
struct dw_dma *dw = platform_get_drvdata(pdev);
dw_dma_off(dw);
clk_disable_unprepare(dw->clk);
}
static int dw_suspend_noirq(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct dw_dma *dw = platform_get_drvdata(pdev);
dw_dma_off(dw);
clk_disable_unprepare(dw->clk);
return 0;
}
static int dw_resume_noirq(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct dw_dma *dw = platform_get_drvdata(pdev);
clk_prepare_enable(dw->clk);
dma_writel(dw, CFG, DW_CFG_DMA_EN);
return 0;
}
static const struct dev_pm_ops dw_dev_pm_ops = {
.suspend_noirq = dw_suspend_noirq,
.resume_noirq = dw_resume_noirq,
.freeze_noirq = dw_suspend_noirq,
.thaw_noirq = dw_resume_noirq,
.restore_noirq = dw_resume_noirq,
.poweroff_noirq = dw_suspend_noirq,
};
#ifdef CONFIG_OF
static const struct of_device_id dw_dma_of_id_table[] = {
{ .compatible = "snps,dma-spear1340" },
{}
};
MODULE_DEVICE_TABLE(of, dw_dma_of_id_table);
#endif
#ifdef CONFIG_ACPI
static const struct acpi_device_id dw_dma_acpi_id_table[] = {
{ "INTL9C60", 0 },
{ }
};
#endif
static struct platform_driver dw_driver = {
.probe = dw_probe,
.remove = dw_remove,
.shutdown = dw_shutdown,
.driver = {
.name = "dw_dmac",
.pm = &dw_dev_pm_ops,
.of_match_table = of_match_ptr(dw_dma_of_id_table),
.acpi_match_table = ACPI_PTR(dw_dma_acpi_id_table),
},
};
static int __init dw_init(void)
{
return platform_driver_register(&dw_driver);
}
subsys_initcall(dw_init);
static void __exit dw_exit(void)
{
platform_driver_unregister(&dw_driver);
}
module_exit(dw_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Synopsys DesignWare DMA Controller driver");
MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
MODULE_AUTHOR("Viresh Kumar <viresh.linux@gmail.com>");
| gpl-2.0 |
TeamHorizon/android_kernel_lge_c50 | arch/mips/jazz/irq.c | 3615 | 4294 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 1992 Linus Torvalds
* Copyright (C) 1994 - 2001, 2003, 07 Ralf Baechle
*/
#include <linux/clockchips.h>
#include <linux/i8253.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/smp.h>
#include <linux/spinlock.h>
#include <linux/irq.h>
#include <asm/irq_cpu.h>
#include <asm/i8259.h>
#include <asm/io.h>
#include <asm/jazz.h>
#include <asm/pgtable.h>
#include <asm/tlbmisc.h>
static DEFINE_RAW_SPINLOCK(r4030_lock);
static void enable_r4030_irq(struct irq_data *d)
{
unsigned int mask = 1 << (d->irq - JAZZ_IRQ_START);
unsigned long flags;
raw_spin_lock_irqsave(&r4030_lock, flags);
mask |= r4030_read_reg16(JAZZ_IO_IRQ_ENABLE);
r4030_write_reg16(JAZZ_IO_IRQ_ENABLE, mask);
raw_spin_unlock_irqrestore(&r4030_lock, flags);
}
void disable_r4030_irq(struct irq_data *d)
{
unsigned int mask = ~(1 << (d->irq - JAZZ_IRQ_START));
unsigned long flags;
raw_spin_lock_irqsave(&r4030_lock, flags);
mask &= r4030_read_reg16(JAZZ_IO_IRQ_ENABLE);
r4030_write_reg16(JAZZ_IO_IRQ_ENABLE, mask);
raw_spin_unlock_irqrestore(&r4030_lock, flags);
}
static struct irq_chip r4030_irq_type = {
.name = "R4030",
.irq_mask = disable_r4030_irq,
.irq_unmask = enable_r4030_irq,
};
void __init init_r4030_ints(void)
{
int i;
for (i = JAZZ_IRQ_START; i <= JAZZ_IRQ_END; i++)
irq_set_chip_and_handler(i, &r4030_irq_type, handle_level_irq);
r4030_write_reg16(JAZZ_IO_IRQ_ENABLE, 0);
r4030_read_reg16(JAZZ_IO_IRQ_SOURCE); /* clear pending IRQs */
r4030_read_reg32(JAZZ_R4030_INVAL_ADDR); /* clear error bits */
}
/*
* On systems with i8259-style interrupt controllers we assume for
* driver compatibility reasons interrupts 0 - 15 to be the i8259
* interrupts even if the hardware uses a different interrupt numbering.
*/
void __init arch_init_irq(void)
{
/*
* this is a hack to get back the still needed wired mapping
* killed by init_mm()
*/
/* Map 0xe0000000 -> 0x0:800005C0, 0xe0010000 -> 0x1:30000580 */
add_wired_entry(0x02000017, 0x03c00017, 0xe0000000, PM_64K);
/* Map 0xe2000000 -> 0x0:900005C0, 0xe3010000 -> 0x0:910005C0 */
add_wired_entry(0x02400017, 0x02440017, 0xe2000000, PM_16M);
/* Map 0xe4000000 -> 0x0:600005C0, 0xe4100000 -> 400005C0 */
add_wired_entry(0x01800017, 0x01000017, 0xe4000000, PM_4M);
init_i8259_irqs(); /* Integrated i8259 */
mips_cpu_irq_init();
init_r4030_ints();
change_c0_status(ST0_IM, IE_IRQ2 | IE_IRQ1);
}
asmlinkage void plat_irq_dispatch(void)
{
unsigned int pending = read_c0_cause() & read_c0_status();
unsigned int irq;
if (pending & IE_IRQ4) {
r4030_read_reg32(JAZZ_TIMER_REGISTER);
do_IRQ(JAZZ_TIMER_IRQ);
} else if (pending & IE_IRQ2) {
irq = *(volatile u8 *)JAZZ_EISA_IRQ_ACK;
do_IRQ(irq);
} else if (pending & IE_IRQ1) {
irq = *(volatile u8 *)JAZZ_IO_IRQ_SOURCE >> 2;
if (likely(irq > 0))
do_IRQ(irq + JAZZ_IRQ_START - 1);
else
panic("Unimplemented loc_no_irq handler");
}
}
static void r4030_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
/* Nothing to do ... */
}
struct clock_event_device r4030_clockevent = {
.name = "r4030",
.features = CLOCK_EVT_FEAT_PERIODIC,
.rating = 300,
.irq = JAZZ_TIMER_IRQ,
.set_mode = r4030_set_mode,
};
static irqreturn_t r4030_timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *cd = dev_id;
cd->event_handler(cd);
return IRQ_HANDLED;
}
static struct irqaction r4030_timer_irqaction = {
.handler = r4030_timer_interrupt,
.flags = IRQF_TIMER,
.name = "R4030 timer",
};
void __init plat_time_init(void)
{
struct clock_event_device *cd = &r4030_clockevent;
struct irqaction *action = &r4030_timer_irqaction;
unsigned int cpu = smp_processor_id();
BUG_ON(HZ != 100);
cd->cpumask = cpumask_of(cpu);
clockevents_register_device(cd);
action->dev_id = cd;
setup_irq(JAZZ_TIMER_IRQ, action);
/*
* Set clock to 100Hz.
*
* The R4030 timer receives an input clock of 1kHz which is divieded by
* a programmable 4-bit divider. This makes it fairly inflexible.
*/
r4030_write_reg32(JAZZ_TIMER_INTERVAL, 9);
setup_pit_timer();
}
| gpl-2.0 |
Shelnutt2/android_kernel_lge_gee_3.4 | drivers/staging/media/lirc/lirc_imon.c | 4895 | 25360 | /*
* lirc_imon.c: LIRC/VFD/LCD driver for SoundGraph iMON IR/VFD/LCD
* including the iMON PAD model
*
* Copyright(C) 2004 Venky Raju(dev@venky.ws)
* Copyright(C) 2009 Jarod Wilson <jarod@wilsonet.com>
*
* lirc_imon 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/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <media/lirc.h>
#include <media/lirc_dev.h>
#define MOD_AUTHOR "Venky Raju <dev@venky.ws>"
#define MOD_DESC "Driver for SoundGraph iMON MultiMedia IR/Display"
#define MOD_NAME "lirc_imon"
#define MOD_VERSION "0.8"
#define DISPLAY_MINOR_BASE 144
#define DEVICE_NAME "lcd%d"
#define BUF_CHUNK_SIZE 4
#define BUF_SIZE 128
#define BIT_DURATION 250 /* each bit received is 250us */
/*** P R O T O T Y P E S ***/
/* USB Callback prototypes */
static int imon_probe(struct usb_interface *interface,
const struct usb_device_id *id);
static void imon_disconnect(struct usb_interface *interface);
static void usb_rx_callback(struct urb *urb);
static void usb_tx_callback(struct urb *urb);
/* suspend/resume support */
static int imon_resume(struct usb_interface *intf);
static int imon_suspend(struct usb_interface *intf, pm_message_t message);
/* Display file_operations function prototypes */
static int display_open(struct inode *inode, struct file *file);
static int display_close(struct inode *inode, struct file *file);
/* VFD write operation */
static ssize_t vfd_write(struct file *file, const char __user *buf,
size_t n_bytes, loff_t *pos);
/* LIRC driver function prototypes */
static int ir_open(void *data);
static void ir_close(void *data);
/* Driver init/exit prototypes */
static int __init imon_init(void);
static void __exit imon_exit(void);
/*** G L O B A L S ***/
#define IMON_DATA_BUF_SZ 35
struct imon_context {
struct usb_device *usbdev;
/* Newer devices have two interfaces */
int display; /* not all controllers do */
int display_isopen; /* display port has been opened */
int ir_isopen; /* IR port open */
int dev_present; /* USB device presence */
struct mutex ctx_lock; /* to lock this object */
wait_queue_head_t remove_ok; /* For unexpected USB disconnects */
int vfd_proto_6p; /* some VFD require a 6th packet */
struct lirc_driver *driver;
struct usb_endpoint_descriptor *rx_endpoint;
struct usb_endpoint_descriptor *tx_endpoint;
struct urb *rx_urb;
struct urb *tx_urb;
unsigned char usb_rx_buf[8];
unsigned char usb_tx_buf[8];
struct rx_data {
int count; /* length of 0 or 1 sequence */
int prev_bit; /* logic level of sequence */
int initial_space; /* initial space flag */
} rx;
struct tx_t {
unsigned char data_buf[IMON_DATA_BUF_SZ]; /* user data buffer */
struct completion finished; /* wait for write to finish */
atomic_t busy; /* write in progress */
int status; /* status of tx completion */
} tx;
};
static const struct file_operations display_fops = {
.owner = THIS_MODULE,
.open = &display_open,
.write = &vfd_write,
.release = &display_close,
.llseek = noop_llseek,
};
/*
* USB Device ID for iMON USB Control Boards
*
* The Windows drivers contain 6 different inf files, more or less one for
* each new device until the 0x0034-0x0046 devices, which all use the same
* driver. Some of the devices in the 34-46 range haven't been definitively
* identified yet. Early devices have either a TriGem Computer, Inc. or a
* Samsung vendor ID (0x0aa8 and 0x04e8 respectively), while all later
* devices use the SoundGraph vendor ID (0x15c2).
*/
static struct usb_device_id imon_usb_id_table[] = {
/* TriGem iMON (IR only) -- TG_iMON.inf */
{ USB_DEVICE(0x0aa8, 0x8001) },
/* SoundGraph iMON (IR only) -- sg_imon.inf */
{ USB_DEVICE(0x04e8, 0xff30) },
/* SoundGraph iMON VFD (IR & VFD) -- iMON_VFD.inf */
{ USB_DEVICE(0x0aa8, 0xffda) },
/* SoundGraph iMON SS (IR & VFD) -- iMON_SS.inf */
{ USB_DEVICE(0x15c2, 0xffda) },
{}
};
/* Some iMON VFD models requires a 6th packet for VFD writes */
static struct usb_device_id vfd_proto_6p_list[] = {
{ USB_DEVICE(0x15c2, 0xffda) },
{}
};
/* Some iMON devices have no lcd/vfd, don't set one up */
static struct usb_device_id ir_only_list[] = {
{ USB_DEVICE(0x0aa8, 0x8001) },
{ USB_DEVICE(0x04e8, 0xff30) },
{}
};
/* USB Device data */
static struct usb_driver imon_driver = {
.name = MOD_NAME,
.probe = imon_probe,
.disconnect = imon_disconnect,
.suspend = imon_suspend,
.resume = imon_resume,
.id_table = imon_usb_id_table,
};
static struct usb_class_driver imon_class = {
.name = DEVICE_NAME,
.fops = &display_fops,
.minor_base = DISPLAY_MINOR_BASE,
};
/* to prevent races between open() and disconnect(), probing, etc */
static DEFINE_MUTEX(driver_lock);
static int debug;
/*** M O D U L E C O D E ***/
MODULE_AUTHOR(MOD_AUTHOR);
MODULE_DESCRIPTION(MOD_DESC);
MODULE_VERSION(MOD_VERSION);
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(usb, imon_usb_id_table);
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug messages: 0=no, 1=yes(default: no)");
static void free_imon_context(struct imon_context *context)
{
struct device *dev = context->driver->dev;
usb_free_urb(context->tx_urb);
usb_free_urb(context->rx_urb);
lirc_buffer_free(context->driver->rbuf);
kfree(context->driver->rbuf);
kfree(context->driver);
kfree(context);
dev_dbg(dev, "%s: iMON context freed\n", __func__);
}
static void deregister_from_lirc(struct imon_context *context)
{
int retval;
int minor = context->driver->minor;
retval = lirc_unregister_driver(minor);
if (retval)
err("%s: unable to deregister from lirc(%d)",
__func__, retval);
else
printk(KERN_INFO MOD_NAME ": Deregistered iMON driver "
"(minor:%d)\n", minor);
}
/**
* Called when the Display device (e.g. /dev/lcd0)
* is opened by the application.
*/
static int display_open(struct inode *inode, struct file *file)
{
struct usb_interface *interface;
struct imon_context *context = NULL;
int subminor;
int retval = 0;
/* prevent races with disconnect */
mutex_lock(&driver_lock);
subminor = iminor(inode);
interface = usb_find_interface(&imon_driver, subminor);
if (!interface) {
err("%s: could not find interface for minor %d",
__func__, subminor);
retval = -ENODEV;
goto exit;
}
context = usb_get_intfdata(interface);
if (!context) {
err("%s: no context found for minor %d",
__func__, subminor);
retval = -ENODEV;
goto exit;
}
mutex_lock(&context->ctx_lock);
if (!context->display) {
err("%s: display not supported by device", __func__);
retval = -ENODEV;
} else if (context->display_isopen) {
err("%s: display port is already open", __func__);
retval = -EBUSY;
} else {
context->display_isopen = 1;
file->private_data = context;
dev_info(context->driver->dev, "display port opened\n");
}
mutex_unlock(&context->ctx_lock);
exit:
mutex_unlock(&driver_lock);
return retval;
}
/**
* Called when the display device (e.g. /dev/lcd0)
* is closed by the application.
*/
static int display_close(struct inode *inode, struct file *file)
{
struct imon_context *context = NULL;
int retval = 0;
context = file->private_data;
if (!context) {
err("%s: no context for device", __func__);
return -ENODEV;
}
mutex_lock(&context->ctx_lock);
if (!context->display) {
err("%s: display not supported by device", __func__);
retval = -ENODEV;
} else if (!context->display_isopen) {
err("%s: display is not open", __func__);
retval = -EIO;
} else {
context->display_isopen = 0;
dev_info(context->driver->dev, "display port closed\n");
if (!context->dev_present && !context->ir_isopen) {
/*
* Device disconnected before close and IR port is not
* open. If IR port is open, context will be deleted by
* ir_close.
*/
mutex_unlock(&context->ctx_lock);
free_imon_context(context);
return retval;
}
}
mutex_unlock(&context->ctx_lock);
return retval;
}
/**
* Sends a packet to the device -- this function must be called
* with context->ctx_lock held.
*/
static int send_packet(struct imon_context *context)
{
unsigned int pipe;
int interval = 0;
int retval = 0;
/* Check if we need to use control or interrupt urb */
pipe = usb_sndintpipe(context->usbdev,
context->tx_endpoint->bEndpointAddress);
interval = context->tx_endpoint->bInterval;
usb_fill_int_urb(context->tx_urb, context->usbdev, pipe,
context->usb_tx_buf,
sizeof(context->usb_tx_buf),
usb_tx_callback, context, interval);
context->tx_urb->actual_length = 0;
init_completion(&context->tx.finished);
atomic_set(&(context->tx.busy), 1);
retval = usb_submit_urb(context->tx_urb, GFP_KERNEL);
if (retval) {
atomic_set(&(context->tx.busy), 0);
err("%s: error submitting urb(%d)", __func__, retval);
} else {
/* Wait for transmission to complete (or abort) */
mutex_unlock(&context->ctx_lock);
retval = wait_for_completion_interruptible(
&context->tx.finished);
if (retval)
err("%s: task interrupted", __func__);
mutex_lock(&context->ctx_lock);
retval = context->tx.status;
if (retval)
err("%s: packet tx failed (%d)", __func__, retval);
}
return retval;
}
/**
* Writes data to the VFD. The iMON VFD is 2x16 characters
* and requires data in 5 consecutive USB interrupt packets,
* each packet but the last carrying 7 bytes.
*
* I don't know if the VFD board supports features such as
* scrolling, clearing rows, blanking, etc. so at
* the caller must provide a full screen of data. If fewer
* than 32 bytes are provided spaces will be appended to
* generate a full screen.
*/
static ssize_t vfd_write(struct file *file, const char __user *buf,
size_t n_bytes, loff_t *pos)
{
int i;
int offset;
int seq;
int retval = 0;
struct imon_context *context;
const unsigned char vfd_packet6[] = {
0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF };
int *data_buf = NULL;
context = file->private_data;
if (!context) {
err("%s: no context for device", __func__);
return -ENODEV;
}
mutex_lock(&context->ctx_lock);
if (!context->dev_present) {
err("%s: no iMON device present", __func__);
retval = -ENODEV;
goto exit;
}
if (n_bytes <= 0 || n_bytes > IMON_DATA_BUF_SZ - 3) {
err("%s: invalid payload size", __func__);
retval = -EINVAL;
goto exit;
}
data_buf = memdup_user(buf, n_bytes);
if (IS_ERR(data_buf)) {
retval = PTR_ERR(data_buf);
goto exit;
}
memcpy(context->tx.data_buf, data_buf, n_bytes);
/* Pad with spaces */
for (i = n_bytes; i < IMON_DATA_BUF_SZ - 3; ++i)
context->tx.data_buf[i] = ' ';
for (i = IMON_DATA_BUF_SZ - 3; i < IMON_DATA_BUF_SZ; ++i)
context->tx.data_buf[i] = 0xFF;
offset = 0;
seq = 0;
do {
memcpy(context->usb_tx_buf, context->tx.data_buf + offset, 7);
context->usb_tx_buf[7] = (unsigned char) seq;
retval = send_packet(context);
if (retval) {
err("%s: send packet failed for packet #%d",
__func__, seq/2);
goto exit;
} else {
seq += 2;
offset += 7;
}
} while (offset < IMON_DATA_BUF_SZ);
if (context->vfd_proto_6p) {
/* Send packet #6 */
memcpy(context->usb_tx_buf, &vfd_packet6, sizeof(vfd_packet6));
context->usb_tx_buf[7] = (unsigned char) seq;
retval = send_packet(context);
if (retval)
err("%s: send packet failed for packet #%d",
__func__, seq/2);
}
exit:
mutex_unlock(&context->ctx_lock);
kfree(data_buf);
return (!retval) ? n_bytes : retval;
}
/**
* Callback function for USB core API: transmit data
*/
static void usb_tx_callback(struct urb *urb)
{
struct imon_context *context;
if (!urb)
return;
context = (struct imon_context *)urb->context;
if (!context)
return;
context->tx.status = urb->status;
/* notify waiters that write has finished */
atomic_set(&context->tx.busy, 0);
complete(&context->tx.finished);
return;
}
/**
* Called by lirc_dev when the application opens /dev/lirc
*/
static int ir_open(void *data)
{
int retval = 0;
struct imon_context *context;
/* prevent races with disconnect */
mutex_lock(&driver_lock);
context = (struct imon_context *)data;
/* initial IR protocol decode variables */
context->rx.count = 0;
context->rx.initial_space = 1;
context->rx.prev_bit = 0;
context->ir_isopen = 1;
dev_info(context->driver->dev, "IR port opened\n");
mutex_unlock(&driver_lock);
return retval;
}
/**
* Called by lirc_dev when the application closes /dev/lirc
*/
static void ir_close(void *data)
{
struct imon_context *context;
context = (struct imon_context *)data;
if (!context) {
err("%s: no context for device", __func__);
return;
}
mutex_lock(&context->ctx_lock);
context->ir_isopen = 0;
dev_info(context->driver->dev, "IR port closed\n");
if (!context->dev_present) {
/*
* Device disconnected while IR port was still open. Driver
* was not deregistered at disconnect time, so do it now.
*/
deregister_from_lirc(context);
if (!context->display_isopen) {
mutex_unlock(&context->ctx_lock);
free_imon_context(context);
return;
}
/*
* If display port is open, context will be deleted by
* display_close
*/
}
mutex_unlock(&context->ctx_lock);
return;
}
/**
* Convert bit count to time duration (in us) and submit
* the value to lirc_dev.
*/
static void submit_data(struct imon_context *context)
{
unsigned char buf[4];
int value = context->rx.count;
int i;
dev_dbg(context->driver->dev, "submitting data to LIRC\n");
value *= BIT_DURATION;
value &= PULSE_MASK;
if (context->rx.prev_bit)
value |= PULSE_BIT;
for (i = 0; i < 4; ++i)
buf[i] = value>>(i*8);
lirc_buffer_write(context->driver->rbuf, buf);
wake_up(&context->driver->rbuf->wait_poll);
return;
}
static inline int tv2int(const struct timeval *a, const struct timeval *b)
{
int usecs = 0;
int sec = 0;
if (b->tv_usec > a->tv_usec) {
usecs = 1000000;
sec--;
}
usecs += a->tv_usec - b->tv_usec;
sec += a->tv_sec - b->tv_sec;
sec *= 1000;
usecs /= 1000;
sec += usecs;
if (sec < 0)
sec = 1000;
return sec;
}
/**
* Process the incoming packet
*/
static void imon_incoming_packet(struct imon_context *context,
struct urb *urb, int intf)
{
int len = urb->actual_length;
unsigned char *buf = urb->transfer_buffer;
struct device *dev = context->driver->dev;
int octet, bit;
unsigned char mask;
int i;
/*
* just bail out if no listening IR client
*/
if (!context->ir_isopen)
return;
if (len != 8) {
dev_warn(dev, "imon %s: invalid incoming packet "
"size (len = %d, intf%d)\n", __func__, len, intf);
return;
}
if (debug) {
printk(KERN_INFO "raw packet: ");
for (i = 0; i < len; ++i)
printk("%02x ", buf[i]);
printk("\n");
}
/*
* Translate received data to pulse and space lengths.
* Received data is active low, i.e. pulses are 0 and
* spaces are 1.
*
* My original algorithm was essentially similar to
* Changwoo Ryu's with the exception that he switched
* the incoming bits to active high and also fed an
* initial space to LIRC at the start of a new sequence
* if the previous bit was a pulse.
*
* I've decided to adopt his algorithm.
*/
if (buf[7] == 1 && context->rx.initial_space) {
/* LIRC requires a leading space */
context->rx.prev_bit = 0;
context->rx.count = 4;
submit_data(context);
context->rx.count = 0;
}
for (octet = 0; octet < 5; ++octet) {
mask = 0x80;
for (bit = 0; bit < 8; ++bit) {
int curr_bit = !(buf[octet] & mask);
if (curr_bit != context->rx.prev_bit) {
if (context->rx.count) {
submit_data(context);
context->rx.count = 0;
}
context->rx.prev_bit = curr_bit;
}
++context->rx.count;
mask >>= 1;
}
}
if (buf[7] == 10) {
if (context->rx.count) {
submit_data(context);
context->rx.count = 0;
}
context->rx.initial_space = context->rx.prev_bit;
}
}
/**
* Callback function for USB core API: receive data
*/
static void usb_rx_callback(struct urb *urb)
{
struct imon_context *context;
int intfnum = 0;
if (!urb)
return;
context = (struct imon_context *)urb->context;
if (!context)
return;
switch (urb->status) {
case -ENOENT: /* usbcore unlink successful! */
return;
case 0:
imon_incoming_packet(context, urb, intfnum);
break;
default:
dev_warn(context->driver->dev, "imon %s: status(%d): ignored\n",
__func__, urb->status);
break;
}
usb_submit_urb(context->rx_urb, GFP_ATOMIC);
return;
}
/**
* Callback function for USB core API: Probe
*/
static int imon_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *usbdev = NULL;
struct usb_host_interface *iface_desc = NULL;
struct usb_endpoint_descriptor *rx_endpoint = NULL;
struct usb_endpoint_descriptor *tx_endpoint = NULL;
struct urb *rx_urb = NULL;
struct urb *tx_urb = NULL;
struct lirc_driver *driver = NULL;
struct lirc_buffer *rbuf = NULL;
struct device *dev = &interface->dev;
int ifnum;
int lirc_minor = 0;
int num_endpts;
int retval = 0;
int display_ep_found = 0;
int ir_ep_found = 0;
int alloc_status = 0;
int vfd_proto_6p = 0;
struct imon_context *context = NULL;
int i;
u16 vendor, product;
/* prevent races probing devices w/multiple interfaces */
mutex_lock(&driver_lock);
context = kzalloc(sizeof(struct imon_context), GFP_KERNEL);
if (!context) {
err("%s: kzalloc failed for context", __func__);
alloc_status = 1;
goto alloc_status_switch;
}
/*
* Try to auto-detect the type of display if the user hasn't set
* it by hand via the display_type modparam. Default is VFD.
*/
if (usb_match_id(interface, ir_only_list))
context->display = 0;
else
context->display = 1;
usbdev = usb_get_dev(interface_to_usbdev(interface));
iface_desc = interface->cur_altsetting;
num_endpts = iface_desc->desc.bNumEndpoints;
ifnum = iface_desc->desc.bInterfaceNumber;
vendor = le16_to_cpu(usbdev->descriptor.idVendor);
product = le16_to_cpu(usbdev->descriptor.idProduct);
dev_dbg(dev, "%s: found iMON device (%04x:%04x, intf%d)\n",
__func__, vendor, product, ifnum);
/*
* Scan the endpoint list and set:
* first input endpoint = IR endpoint
* first output endpoint = display endpoint
*/
for (i = 0; i < num_endpts && !(ir_ep_found && display_ep_found); ++i) {
struct usb_endpoint_descriptor *ep;
int ep_dir;
int ep_type;
ep = &iface_desc->endpoint[i].desc;
ep_dir = ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK;
ep_type = ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
if (!ir_ep_found &&
ep_dir == USB_DIR_IN &&
ep_type == USB_ENDPOINT_XFER_INT) {
rx_endpoint = ep;
ir_ep_found = 1;
dev_dbg(dev, "%s: found IR endpoint\n", __func__);
} else if (!display_ep_found && ep_dir == USB_DIR_OUT &&
ep_type == USB_ENDPOINT_XFER_INT) {
tx_endpoint = ep;
display_ep_found = 1;
dev_dbg(dev, "%s: found display endpoint\n", __func__);
}
}
/*
* Some iMON receivers have no display. Unfortunately, it seems
* that SoundGraph recycles device IDs between devices both with
* and without... :\
*/
if (context->display == 0) {
display_ep_found = 0;
dev_dbg(dev, "%s: device has no display\n", __func__);
}
/* Input endpoint is mandatory */
if (!ir_ep_found) {
err("%s: no valid input (IR) endpoint found.", __func__);
retval = -ENODEV;
alloc_status = 2;
goto alloc_status_switch;
}
/* Determine if display requires 6 packets */
if (display_ep_found) {
if (usb_match_id(interface, vfd_proto_6p_list))
vfd_proto_6p = 1;
dev_dbg(dev, "%s: vfd_proto_6p: %d\n",
__func__, vfd_proto_6p);
}
driver = kzalloc(sizeof(struct lirc_driver), GFP_KERNEL);
if (!driver) {
err("%s: kzalloc failed for lirc_driver", __func__);
alloc_status = 2;
goto alloc_status_switch;
}
rbuf = kmalloc(sizeof(struct lirc_buffer), GFP_KERNEL);
if (!rbuf) {
err("%s: kmalloc failed for lirc_buffer", __func__);
alloc_status = 3;
goto alloc_status_switch;
}
if (lirc_buffer_init(rbuf, BUF_CHUNK_SIZE, BUF_SIZE)) {
err("%s: lirc_buffer_init failed", __func__);
alloc_status = 4;
goto alloc_status_switch;
}
rx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!rx_urb) {
err("%s: usb_alloc_urb failed for IR urb", __func__);
alloc_status = 5;
goto alloc_status_switch;
}
tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!tx_urb) {
err("%s: usb_alloc_urb failed for display urb",
__func__);
alloc_status = 6;
goto alloc_status_switch;
}
mutex_init(&context->ctx_lock);
context->vfd_proto_6p = vfd_proto_6p;
strcpy(driver->name, MOD_NAME);
driver->minor = -1;
driver->code_length = BUF_CHUNK_SIZE * 8;
driver->sample_rate = 0;
driver->features = LIRC_CAN_REC_MODE2;
driver->data = context;
driver->rbuf = rbuf;
driver->set_use_inc = ir_open;
driver->set_use_dec = ir_close;
driver->dev = &interface->dev;
driver->owner = THIS_MODULE;
mutex_lock(&context->ctx_lock);
context->driver = driver;
/* start out in keyboard mode */
lirc_minor = lirc_register_driver(driver);
if (lirc_minor < 0) {
err("%s: lirc_register_driver failed", __func__);
alloc_status = 7;
goto unlock;
} else
dev_info(dev, "Registered iMON driver "
"(lirc minor: %d)\n", lirc_minor);
/* Needed while unregistering! */
driver->minor = lirc_minor;
context->usbdev = usbdev;
context->dev_present = 1;
context->rx_endpoint = rx_endpoint;
context->rx_urb = rx_urb;
/*
* tx is used to send characters to lcd/vfd, associate RF
* remotes, set IR protocol, and maybe more...
*/
context->tx_endpoint = tx_endpoint;
context->tx_urb = tx_urb;
if (display_ep_found)
context->display = 1;
usb_fill_int_urb(context->rx_urb, context->usbdev,
usb_rcvintpipe(context->usbdev,
context->rx_endpoint->bEndpointAddress),
context->usb_rx_buf, sizeof(context->usb_rx_buf),
usb_rx_callback, context,
context->rx_endpoint->bInterval);
retval = usb_submit_urb(context->rx_urb, GFP_KERNEL);
if (retval) {
err("%s: usb_submit_urb failed for intf0 (%d)",
__func__, retval);
mutex_unlock(&context->ctx_lock);
goto exit;
}
usb_set_intfdata(interface, context);
if (context->display && ifnum == 0) {
dev_dbg(dev, "%s: Registering iMON display with sysfs\n",
__func__);
if (usb_register_dev(interface, &imon_class)) {
/* Not a fatal error, so ignore */
dev_info(dev, "%s: could not get a minor number for "
"display\n", __func__);
}
}
dev_info(dev, "iMON device (%04x:%04x, intf%d) on "
"usb<%d:%d> initialized\n", vendor, product, ifnum,
usbdev->bus->busnum, usbdev->devnum);
unlock:
mutex_unlock(&context->ctx_lock);
alloc_status_switch:
switch (alloc_status) {
case 7:
usb_free_urb(tx_urb);
case 6:
usb_free_urb(rx_urb);
case 5:
if (rbuf)
lirc_buffer_free(rbuf);
case 4:
kfree(rbuf);
case 3:
kfree(driver);
case 2:
kfree(context);
context = NULL;
case 1:
if (retval != -ENODEV)
retval = -ENOMEM;
break;
case 0:
retval = 0;
}
exit:
mutex_unlock(&driver_lock);
return retval;
}
/**
* Callback function for USB core API: disconnect
*/
static void imon_disconnect(struct usb_interface *interface)
{
struct imon_context *context;
int ifnum;
/* prevent races with ir_open()/display_open() */
mutex_lock(&driver_lock);
context = usb_get_intfdata(interface);
ifnum = interface->cur_altsetting->desc.bInterfaceNumber;
mutex_lock(&context->ctx_lock);
usb_set_intfdata(interface, NULL);
/* Abort ongoing write */
if (atomic_read(&context->tx.busy)) {
usb_kill_urb(context->tx_urb);
complete_all(&context->tx.finished);
}
context->dev_present = 0;
usb_kill_urb(context->rx_urb);
if (context->display)
usb_deregister_dev(interface, &imon_class);
if (!context->ir_isopen && !context->dev_present) {
deregister_from_lirc(context);
mutex_unlock(&context->ctx_lock);
if (!context->display_isopen)
free_imon_context(context);
} else
mutex_unlock(&context->ctx_lock);
mutex_unlock(&driver_lock);
printk(KERN_INFO "%s: iMON device (intf%d) disconnected\n",
__func__, ifnum);
}
static int imon_suspend(struct usb_interface *intf, pm_message_t message)
{
struct imon_context *context = usb_get_intfdata(intf);
usb_kill_urb(context->rx_urb);
return 0;
}
static int imon_resume(struct usb_interface *intf)
{
int rc = 0;
struct imon_context *context = usb_get_intfdata(intf);
usb_fill_int_urb(context->rx_urb, context->usbdev,
usb_rcvintpipe(context->usbdev,
context->rx_endpoint->bEndpointAddress),
context->usb_rx_buf, sizeof(context->usb_rx_buf),
usb_rx_callback, context,
context->rx_endpoint->bInterval);
rc = usb_submit_urb(context->rx_urb, GFP_ATOMIC);
return rc;
}
module_usb_driver(imon_driver);
| gpl-2.0 |
aj700/nxzimg | drivers/staging/comedi/drivers/ke_counter.c | 4895 | 8308 | /*
comedi/drivers/ke_counter.c
Comedi driver for Kolter-Electronic PCI Counter 1 Card
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: ke_counter
Description: Driver for Kolter Electronic Counter Card
Devices: [Kolter Electronic] PCI Counter Card (ke_counter)
Author: Michael Hillmann
Updated: Mon, 14 Apr 2008 15:42:42 +0100
Status: tested
Configuration Options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
If bus/slot is not specified, the first supported
PCI device found will be used.
This driver is a simple driver to read the counter values from
Kolter Electronic PCI Counter Card.
*/
#include "../comedidev.h"
#include "comedi_pci.h"
#define CNT_DRIVER_NAME "ke_counter"
#define PCI_VENDOR_ID_KOLTER 0x1001
#define CNT_CARD_DEVICE_ID 0x0014
/*-- function prototypes ----------------------------------------------------*/
static int cnt_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int cnt_detach(struct comedi_device *dev);
static DEFINE_PCI_DEVICE_TABLE(cnt_pci_table) = {
{ PCI_DEVICE(PCI_VENDOR_ID_KOLTER, CNT_CARD_DEVICE_ID) },
{0}
};
MODULE_DEVICE_TABLE(pci, cnt_pci_table);
/*-- board specification structure ------------------------------------------*/
struct cnt_board_struct {
const char *name;
int device_id;
int cnt_channel_nbr;
int cnt_bits;
};
static const struct cnt_board_struct cnt_boards[] = {
{
.name = CNT_DRIVER_NAME,
.device_id = CNT_CARD_DEVICE_ID,
.cnt_channel_nbr = 3,
.cnt_bits = 24}
};
#define cnt_board_nbr (sizeof(cnt_boards)/sizeof(struct cnt_board_struct))
/*-- device private structure -----------------------------------------------*/
struct cnt_device_private {
struct pci_dev *pcidev;
};
#define devpriv ((struct cnt_device_private *)dev->private)
static struct comedi_driver cnt_driver = {
.driver_name = CNT_DRIVER_NAME,
.module = THIS_MODULE,
.attach = cnt_attach,
.detach = cnt_detach,
};
static int __devinit cnt_driver_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, cnt_driver.driver_name);
}
static void __devexit cnt_driver_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver cnt_driver_pci_driver = {
.id_table = cnt_pci_table,
.probe = &cnt_driver_pci_probe,
.remove = __devexit_p(&cnt_driver_pci_remove)
};
static int __init cnt_driver_init_module(void)
{
int retval;
retval = comedi_driver_register(&cnt_driver);
if (retval < 0)
return retval;
cnt_driver_pci_driver.name = (char *)cnt_driver.driver_name;
return pci_register_driver(&cnt_driver_pci_driver);
}
static void __exit cnt_driver_cleanup_module(void)
{
pci_unregister_driver(&cnt_driver_pci_driver);
comedi_driver_unregister(&cnt_driver);
}
module_init(cnt_driver_init_module);
module_exit(cnt_driver_cleanup_module);
/*-- counter write ----------------------------------------------------------*/
/* This should be used only for resetting the counters; maybe it is better
to make a special command 'reset'. */
static int cnt_winsn(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn,
unsigned int *data)
{
int chan = CR_CHAN(insn->chanspec);
outb((unsigned char)((data[0] >> 24) & 0xff),
dev->iobase + chan * 0x20 + 0x10);
outb((unsigned char)((data[0] >> 16) & 0xff),
dev->iobase + chan * 0x20 + 0x0c);
outb((unsigned char)((data[0] >> 8) & 0xff),
dev->iobase + chan * 0x20 + 0x08);
outb((unsigned char)((data[0] >> 0) & 0xff),
dev->iobase + chan * 0x20 + 0x04);
/* return the number of samples written */
return 1;
}
/*-- counter read -----------------------------------------------------------*/
static int cnt_rinsn(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn,
unsigned int *data)
{
unsigned char a0, a1, a2, a3, a4;
int chan = CR_CHAN(insn->chanspec);
int result;
a0 = inb(dev->iobase + chan * 0x20);
a1 = inb(dev->iobase + chan * 0x20 + 0x04);
a2 = inb(dev->iobase + chan * 0x20 + 0x08);
a3 = inb(dev->iobase + chan * 0x20 + 0x0c);
a4 = inb(dev->iobase + chan * 0x20 + 0x10);
result = (a1 + (a2 * 256) + (a3 * 65536));
if (a4 > 0)
result = result - s->maxdata;
*data = (unsigned int)result;
/* return the number of samples read */
return 1;
}
/*-- attach -----------------------------------------------------------------*/
static int cnt_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct comedi_subdevice *subdevice;
struct pci_dev *pci_device = NULL;
struct cnt_board_struct *board;
unsigned long io_base;
int error, i;
/* allocate device private structure */
error = alloc_private(dev, sizeof(struct cnt_device_private));
if (error < 0)
return error;
/* Probe the device to determine what device in the series it is. */
for_each_pci_dev(pci_device) {
if (pci_device->vendor == PCI_VENDOR_ID_KOLTER) {
for (i = 0; i < cnt_board_nbr; i++) {
if (cnt_boards[i].device_id ==
pci_device->device) {
/* was a particular bus/slot requested? */
if ((it->options[0] != 0)
|| (it->options[1] != 0)) {
/* are we on the wrong bus/slot? */
if (pci_device->bus->number !=
it->options[0]
||
PCI_SLOT(pci_device->devfn)
!= it->options[1]) {
continue;
}
}
dev->board_ptr = cnt_boards + i;
board =
(struct cnt_board_struct *)
dev->board_ptr;
goto found;
}
}
}
}
printk(KERN_WARNING
"comedi%d: no supported board found! (req. bus/slot: %d/%d)\n",
dev->minor, it->options[0], it->options[1]);
return -EIO;
found:
printk(KERN_INFO
"comedi%d: found %s at PCI bus %d, slot %d\n", dev->minor,
board->name, pci_device->bus->number,
PCI_SLOT(pci_device->devfn));
devpriv->pcidev = pci_device;
dev->board_name = board->name;
/* enable PCI device and request regions */
error = comedi_pci_enable(pci_device, CNT_DRIVER_NAME);
if (error < 0) {
printk(KERN_WARNING "comedi%d: "
"failed to enable PCI device and request regions!\n",
dev->minor);
return error;
}
/* read register base address [PCI_BASE_ADDRESS #0] */
io_base = pci_resource_start(pci_device, 0);
dev->iobase = io_base;
/* allocate the subdevice structures */
error = alloc_subdevices(dev, 1);
if (error < 0)
return error;
subdevice = dev->subdevices + 0;
dev->read_subdev = subdevice;
subdevice->type = COMEDI_SUBD_COUNTER;
subdevice->subdev_flags = SDF_READABLE /* | SDF_COMMON */ ;
subdevice->n_chan = board->cnt_channel_nbr;
subdevice->maxdata = (1 << board->cnt_bits) - 1;
subdevice->insn_read = cnt_rinsn;
subdevice->insn_write = cnt_winsn;
/* select 20MHz clock */
outb(3, dev->iobase + 248);
/* reset all counters */
outb(0, dev->iobase);
outb(0, dev->iobase + 0x20);
outb(0, dev->iobase + 0x40);
printk(KERN_INFO "comedi%d: " CNT_DRIVER_NAME " attached.\n",
dev->minor);
return 0;
}
/*-- detach -----------------------------------------------------------------*/
static int cnt_detach(struct comedi_device *dev)
{
if (devpriv && devpriv->pcidev) {
if (dev->iobase)
comedi_pci_disable(devpriv->pcidev);
pci_dev_put(devpriv->pcidev);
}
printk(KERN_INFO "comedi%d: " CNT_DRIVER_NAME " remove\n",
dev->minor);
return 0;
}
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
phenomx4/android_kernel_zte_nex | drivers/gpu/drm/nouveau/nv04_fb.c | 5407 | 1259 | #include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_drm.h"
int
nv04_fb_vram_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
u32 boot0 = nv_rd32(dev, NV04_PFB_BOOT_0);
if (boot0 & 0x00000100) {
dev_priv->vram_size = ((boot0 >> 12) & 0xf) * 2 + 2;
dev_priv->vram_size *= 1024 * 1024;
} else {
switch (boot0 & NV04_PFB_BOOT_0_RAM_AMOUNT) {
case NV04_PFB_BOOT_0_RAM_AMOUNT_32MB:
dev_priv->vram_size = 32 * 1024 * 1024;
break;
case NV04_PFB_BOOT_0_RAM_AMOUNT_16MB:
dev_priv->vram_size = 16 * 1024 * 1024;
break;
case NV04_PFB_BOOT_0_RAM_AMOUNT_8MB:
dev_priv->vram_size = 8 * 1024 * 1024;
break;
case NV04_PFB_BOOT_0_RAM_AMOUNT_4MB:
dev_priv->vram_size = 4 * 1024 * 1024;
break;
}
}
if ((boot0 & 0x00000038) <= 0x10)
dev_priv->vram_type = NV_MEM_TYPE_SGRAM;
else
dev_priv->vram_type = NV_MEM_TYPE_SDRAM;
return 0;
}
int
nv04_fb_init(struct drm_device *dev)
{
/* This is what the DDX did for NV_ARCH_04, but a mmio-trace shows
* nvidia reading PFB_CFG_0, then writing back its original value.
* (which was 0x701114 in this case)
*/
nv_wr32(dev, NV04_PFB_CFG0, 0x1114);
return 0;
}
void
nv04_fb_takedown(struct drm_device *dev)
{
}
| gpl-2.0 |
mifl/android_kernel_pantech_oscar | arch/arm/mach-s5p64x0/clock.c | 7711 | 5439 | /* linux/arch/arm/mach-s5p64x0/clock.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* S5P64X0 - Clock support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <plat/cpu-freq.h>
#include <plat/clock.h>
#include <plat/cpu.h>
#include <plat/pll.h>
#include <plat/s5p-clock.h>
#include <plat/clock-clksrc.h>
#include "common.h"
struct clksrc_clk clk_mout_apll = {
.clk = {
.name = "mout_apll",
.id = -1,
},
.sources = &clk_src_apll,
.reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 0, .size = 1 },
};
struct clksrc_clk clk_mout_mpll = {
.clk = {
.name = "mout_mpll",
.id = -1,
},
.sources = &clk_src_mpll,
.reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 1, .size = 1 },
};
struct clksrc_clk clk_mout_epll = {
.clk = {
.name = "mout_epll",
.id = -1,
},
.sources = &clk_src_epll,
.reg_src = { .reg = S5P64X0_CLK_SRC0, .shift = 2, .size = 1 },
};
enum perf_level {
L0 = 532*1000,
L1 = 266*1000,
L2 = 133*1000,
};
static const u32 clock_table[][3] = {
/*{ARM_CLK, DIVarm, DIVhclk}*/
{L0 * 1000, (0 << ARM_DIV_RATIO_SHIFT), (3 << S5P64X0_CLKDIV0_HCLK_SHIFT)},
{L1 * 1000, (1 << ARM_DIV_RATIO_SHIFT), (1 << S5P64X0_CLKDIV0_HCLK_SHIFT)},
{L2 * 1000, (3 << ARM_DIV_RATIO_SHIFT), (0 << S5P64X0_CLKDIV0_HCLK_SHIFT)},
};
static unsigned long s5p64x0_armclk_get_rate(struct clk *clk)
{
unsigned long rate = clk_get_rate(clk->parent);
u32 clkdiv;
/* divisor mask starts at bit0, so no need to shift */
clkdiv = __raw_readl(ARM_CLK_DIV) & ARM_DIV_MASK;
return rate / (clkdiv + 1);
}
static unsigned long s5p64x0_armclk_round_rate(struct clk *clk,
unsigned long rate)
{
u32 iter;
for (iter = 1 ; iter < ARRAY_SIZE(clock_table) ; iter++) {
if (rate > clock_table[iter][0])
return clock_table[iter-1][0];
}
return clock_table[ARRAY_SIZE(clock_table) - 1][0];
}
static int s5p64x0_armclk_set_rate(struct clk *clk, unsigned long rate)
{
u32 round_tmp;
u32 iter;
u32 clk_div0_tmp;
u32 cur_rate = clk->ops->get_rate(clk);
unsigned long flags;
round_tmp = clk->ops->round_rate(clk, rate);
if (round_tmp == cur_rate)
return 0;
for (iter = 0 ; iter < ARRAY_SIZE(clock_table) ; iter++) {
if (round_tmp == clock_table[iter][0])
break;
}
if (iter >= ARRAY_SIZE(clock_table))
iter = ARRAY_SIZE(clock_table) - 1;
local_irq_save(flags);
if (cur_rate > round_tmp) {
/* Frequency Down */
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) & ~(ARM_DIV_MASK);
clk_div0_tmp |= clock_table[iter][1];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) &
~(S5P64X0_CLKDIV0_HCLK_MASK);
clk_div0_tmp |= clock_table[iter][2];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
} else {
/* Frequency Up */
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) &
~(S5P64X0_CLKDIV0_HCLK_MASK);
clk_div0_tmp |= clock_table[iter][2];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
clk_div0_tmp = __raw_readl(ARM_CLK_DIV) & ~(ARM_DIV_MASK);
clk_div0_tmp |= clock_table[iter][1];
__raw_writel(clk_div0_tmp, ARM_CLK_DIV);
}
local_irq_restore(flags);
clk->rate = clock_table[iter][0];
return 0;
}
static struct clk_ops s5p64x0_clkarm_ops = {
.get_rate = s5p64x0_armclk_get_rate,
.set_rate = s5p64x0_armclk_set_rate,
.round_rate = s5p64x0_armclk_round_rate,
};
struct clksrc_clk clk_armclk = {
.clk = {
.name = "armclk",
.id = 1,
.parent = &clk_mout_apll.clk,
.ops = &s5p64x0_clkarm_ops,
},
.reg_div = { .reg = S5P64X0_CLK_DIV0, .shift = 0, .size = 4 },
};
struct clksrc_clk clk_dout_mpll = {
.clk = {
.name = "dout_mpll",
.id = -1,
.parent = &clk_mout_mpll.clk,
},
.reg_div = { .reg = S5P64X0_CLK_DIV0, .shift = 4, .size = 1 },
};
static struct clk *clkset_hclk_low_list[] = {
&clk_mout_apll.clk,
&clk_mout_mpll.clk,
};
struct clksrc_sources clkset_hclk_low = {
.sources = clkset_hclk_low_list,
.nr_sources = ARRAY_SIZE(clkset_hclk_low_list),
};
int s5p64x0_pclk_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_PCLK, clk, enable);
}
int s5p64x0_hclk0_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_HCLK0, clk, enable);
}
int s5p64x0_hclk1_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_HCLK1, clk, enable);
}
int s5p64x0_sclk_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_SCLK0, clk, enable);
}
int s5p64x0_sclk1_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_SCLK1, clk, enable);
}
int s5p64x0_mem_ctrl(struct clk *clk, int enable)
{
return s5p_gatectrl(S5P64X0_CLK_GATE_MEM0, clk, enable);
}
int s5p64x0_clk48m_ctrl(struct clk *clk, int enable)
{
unsigned long flags;
u32 val;
/* can't rely on clock lock, this register has other usages */
local_irq_save(flags);
val = __raw_readl(S5P64X0_OTHERS);
if (enable)
val |= S5P64X0_OTHERS_USB_SIG_MASK;
else
val &= ~S5P64X0_OTHERS_USB_SIG_MASK;
__raw_writel(val, S5P64X0_OTHERS);
local_irq_restore(flags);
return 0;
}
| gpl-2.0 |
CyanogenMod/android_kernel_oneplus_msm8974 | arch/arm/mm/copypage-xsc3.c | 9759 | 2882 | /*
* linux/arch/arm/mm/copypage-xsc3.S
*
* Copyright (C) 2004 Intel Corp.
*
* 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.
*
* Adapted for 3rd gen XScale core, no more mini-dcache
* Author: Matt Gilbert (matthew.m.gilbert@intel.com)
*/
#include <linux/init.h>
#include <linux/highmem.h>
/*
* General note:
* We don't really want write-allocate cache behaviour for these functions
* since that will just eat through 8K of the cache.
*/
/*
* XSC3 optimised copy_user_highpage
* r0 = destination
* r1 = source
*
* The source page may have some clean entries in the cache already, but we
* can safely ignore them - break_cow() will flush them out of the cache
* if we eventually end up using our copied page.
*
*/
static void __naked
xsc3_mc_copy_user_page(void *kto, const void *kfrom)
{
asm("\
stmfd sp!, {r4, r5, lr} \n\
mov lr, %2 \n\
\n\
pld [r1, #0] \n\
pld [r1, #32] \n\
1: pld [r1, #64] \n\
pld [r1, #96] \n\
\n\
2: ldrd r2, [r1], #8 \n\
mov ip, r0 \n\
ldrd r4, [r1], #8 \n\
mcr p15, 0, ip, c7, c6, 1 @ invalidate\n\
strd r2, [r0], #8 \n\
ldrd r2, [r1], #8 \n\
strd r4, [r0], #8 \n\
ldrd r4, [r1], #8 \n\
strd r2, [r0], #8 \n\
strd r4, [r0], #8 \n\
ldrd r2, [r1], #8 \n\
mov ip, r0 \n\
ldrd r4, [r1], #8 \n\
mcr p15, 0, ip, c7, c6, 1 @ invalidate\n\
strd r2, [r0], #8 \n\
ldrd r2, [r1], #8 \n\
subs lr, lr, #1 \n\
strd r4, [r0], #8 \n\
ldrd r4, [r1], #8 \n\
strd r2, [r0], #8 \n\
strd r4, [r0], #8 \n\
bgt 1b \n\
beq 2b \n\
\n\
ldmfd sp!, {r4, r5, pc}"
:
: "r" (kto), "r" (kfrom), "I" (PAGE_SIZE / 64 - 1));
}
void xsc3_mc_copy_user_highpage(struct page *to, struct page *from,
unsigned long vaddr, struct vm_area_struct *vma)
{
void *kto, *kfrom;
kto = kmap_atomic(to);
kfrom = kmap_atomic(from);
flush_cache_page(vma, vaddr, page_to_pfn(from));
xsc3_mc_copy_user_page(kto, kfrom);
kunmap_atomic(kfrom);
kunmap_atomic(kto);
}
/*
* XScale optimised clear_user_page
* r0 = destination
* r1 = virtual user address of ultimate destination page
*/
void xsc3_mc_clear_user_highpage(struct page *page, unsigned long vaddr)
{
void *ptr, *kaddr = kmap_atomic(page);
asm volatile ("\
mov r1, %2 \n\
mov r2, #0 \n\
mov r3, #0 \n\
1: mcr p15, 0, %0, c7, c6, 1 @ invalidate line\n\
strd r2, [%0], #8 \n\
strd r2, [%0], #8 \n\
strd r2, [%0], #8 \n\
strd r2, [%0], #8 \n\
subs r1, r1, #1 \n\
bne 1b"
: "=r" (ptr)
: "0" (kaddr), "I" (PAGE_SIZE / 32)
: "r1", "r2", "r3");
kunmap_atomic(kaddr);
}
struct cpu_user_fns xsc3_mc_user_fns __initdata = {
.cpu_clear_user_highpage = xsc3_mc_clear_user_highpage,
.cpu_copy_user_highpage = xsc3_mc_copy_user_highpage,
};
| gpl-2.0 |
Octane70/SGH-I337M_JB_4.2.2_Kernel_MG1 | arch/arm/mm/copypage-xsc3.c | 9759 | 2882 | /*
* linux/arch/arm/mm/copypage-xsc3.S
*
* Copyright (C) 2004 Intel Corp.
*
* 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.
*
* Adapted for 3rd gen XScale core, no more mini-dcache
* Author: Matt Gilbert (matthew.m.gilbert@intel.com)
*/
#include <linux/init.h>
#include <linux/highmem.h>
/*
* General note:
* We don't really want write-allocate cache behaviour for these functions
* since that will just eat through 8K of the cache.
*/
/*
* XSC3 optimised copy_user_highpage
* r0 = destination
* r1 = source
*
* The source page may have some clean entries in the cache already, but we
* can safely ignore them - break_cow() will flush them out of the cache
* if we eventually end up using our copied page.
*
*/
static void __naked
xsc3_mc_copy_user_page(void *kto, const void *kfrom)
{
asm("\
stmfd sp!, {r4, r5, lr} \n\
mov lr, %2 \n\
\n\
pld [r1, #0] \n\
pld [r1, #32] \n\
1: pld [r1, #64] \n\
pld [r1, #96] \n\
\n\
2: ldrd r2, [r1], #8 \n\
mov ip, r0 \n\
ldrd r4, [r1], #8 \n\
mcr p15, 0, ip, c7, c6, 1 @ invalidate\n\
strd r2, [r0], #8 \n\
ldrd r2, [r1], #8 \n\
strd r4, [r0], #8 \n\
ldrd r4, [r1], #8 \n\
strd r2, [r0], #8 \n\
strd r4, [r0], #8 \n\
ldrd r2, [r1], #8 \n\
mov ip, r0 \n\
ldrd r4, [r1], #8 \n\
mcr p15, 0, ip, c7, c6, 1 @ invalidate\n\
strd r2, [r0], #8 \n\
ldrd r2, [r1], #8 \n\
subs lr, lr, #1 \n\
strd r4, [r0], #8 \n\
ldrd r4, [r1], #8 \n\
strd r2, [r0], #8 \n\
strd r4, [r0], #8 \n\
bgt 1b \n\
beq 2b \n\
\n\
ldmfd sp!, {r4, r5, pc}"
:
: "r" (kto), "r" (kfrom), "I" (PAGE_SIZE / 64 - 1));
}
void xsc3_mc_copy_user_highpage(struct page *to, struct page *from,
unsigned long vaddr, struct vm_area_struct *vma)
{
void *kto, *kfrom;
kto = kmap_atomic(to);
kfrom = kmap_atomic(from);
flush_cache_page(vma, vaddr, page_to_pfn(from));
xsc3_mc_copy_user_page(kto, kfrom);
kunmap_atomic(kfrom);
kunmap_atomic(kto);
}
/*
* XScale optimised clear_user_page
* r0 = destination
* r1 = virtual user address of ultimate destination page
*/
void xsc3_mc_clear_user_highpage(struct page *page, unsigned long vaddr)
{
void *ptr, *kaddr = kmap_atomic(page);
asm volatile ("\
mov r1, %2 \n\
mov r2, #0 \n\
mov r3, #0 \n\
1: mcr p15, 0, %0, c7, c6, 1 @ invalidate line\n\
strd r2, [%0], #8 \n\
strd r2, [%0], #8 \n\
strd r2, [%0], #8 \n\
strd r2, [%0], #8 \n\
subs r1, r1, #1 \n\
bne 1b"
: "=r" (ptr)
: "0" (kaddr), "I" (PAGE_SIZE / 32)
: "r1", "r2", "r3");
kunmap_atomic(kaddr);
}
struct cpu_user_fns xsc3_mc_user_fns __initdata = {
.cpu_clear_user_highpage = xsc3_mc_clear_user_highpage,
.cpu_copy_user_highpage = xsc3_mc_copy_user_highpage,
};
| gpl-2.0 |
wkl/linux-509 | arch/mips/ath79/prom.c | 10783 | 1272 | /*
* Atheros AR71XX/AR724X/AR913X specific prom routines
*
* Copyright (C) 2008-2010 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/string.h>
#include <asm/bootinfo.h>
#include <asm/addrspace.h>
#include "common.h"
static inline int is_valid_ram_addr(void *addr)
{
if (((u32) addr > KSEG0) &&
((u32) addr < (KSEG0 + ATH79_MEM_SIZE_MAX)))
return 1;
if (((u32) addr > KSEG1) &&
((u32) addr < (KSEG1 + ATH79_MEM_SIZE_MAX)))
return 1;
return 0;
}
static __init void ath79_prom_init_cmdline(int argc, char **argv)
{
int i;
if (!is_valid_ram_addr(argv))
return;
for (i = 0; i < argc; i++)
if (is_valid_ram_addr(argv[i])) {
strlcat(arcs_cmdline, " ", sizeof(arcs_cmdline));
strlcat(arcs_cmdline, argv[i], sizeof(arcs_cmdline));
}
}
void __init prom_init(void)
{
ath79_prom_init_cmdline(fw_arg0, (char **)fw_arg1);
}
void __init prom_free_prom_memory(void)
{
/* We do not have to prom memory to free */
}
| gpl-2.0 |
Red--Code/android_kernel_sony_msm8974ac | arch/avr32/boards/merisc/flash.c | 13599 | 2832 | /*
* Merisc board-specific flash initialization
*
* Copyright (C) 2008 Martinsson Elektronik AB
*
* 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/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <mach/smc.h>
/* Will be translated to units of 14.3 ns, rounded up */
static struct smc_timing flash_timing __initdata = {
.ncs_read_setup = 1 * 14,
.nrd_setup = 5 * 14,
.ncs_write_setup = 1 * 14,
.nwe_setup = 2 * 14,
.ncs_read_pulse = 12 * 14,
.nrd_pulse = 7 * 14,
.ncs_write_pulse = 8 * 14,
.nwe_pulse = 4 * 14,
.read_cycle = 14 * 14,
.write_cycle = 10 * 14,
};
static struct smc_config flash_config __initdata = {
.bus_width = 2,
.nrd_controlled = 1,
.nwe_controlled = 1,
.byte_write = 1,
.tdf_cycles = 3,
};
static struct mtd_partition flash_0_parts[] = {
{
.name = "boot",
.offset = 0x00000000,
.size = 0x00060000,
.mask_flags = 0,
},
{
.name = "kernel",
.offset = 0x00060000,
.size = 0x00200000,
.mask_flags = 0,
},
{
.name = "root",
.offset = 0x00260000,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0,
},
};
static struct mtd_partition flash_1_parts[] = {
{
.name = "2ndflash",
.offset = 0x00000000,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0,
},
};
static struct physmap_flash_data flash_data[] = {
{
.width = 2,
.nr_parts = ARRAY_SIZE(flash_0_parts),
.parts = flash_0_parts,
},
{
.width = 2,
.nr_parts = ARRAY_SIZE(flash_1_parts),
.parts = flash_1_parts,
}
};
static struct resource flash_resource[] = {
{
.start = 0x00000000,
.end = 0x03ffffff,
.flags = IORESOURCE_MEM,
},
{
.start = 0x04000000,
.end = 0x07ffffff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device flash_device[] = {
{
.name = "physmap-flash",
.id = 0,
.resource = &flash_resource[0],
.num_resources = 1,
.dev = {
.platform_data = &flash_data[0],
},
},
{
.name = "physmap-flash",
.id = 1,
.resource = &flash_resource[1],
.num_resources = 1,
.dev = {
.platform_data = &flash_data[1],
},
},
};
static int __init merisc_flash_init(void)
{
int ret;
smc_set_timing(&flash_config, &flash_timing);
ret = smc_set_configuration(0, &flash_config);
if (ret < 0) {
printk(KERN_ERR "Merisc: failed to set NOR flash timing #0\n");
return ret;
}
ret = smc_set_configuration(4, &flash_config);
if (ret < 0) {
printk(KERN_ERR "Merisc: failed to set NOR flash timing #1\n");
return ret;
}
platform_device_register(&flash_device[0]);
platform_device_register(&flash_device[1]);
return 0;
}
device_initcall(merisc_flash_init);
| gpl-2.0 |
Alberto96/android_kernel_samsung_tassve | drivers/media/video/cx18/cx18-io.c | 13855 | 2814 | /*
* cx18 driver PCI memory mapped IO access routines
*
* Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl>
* Copyright (C) 2008 Andy Walls <awalls@md.metrocast.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
#include "cx18-driver.h"
#include "cx18-io.h"
#include "cx18-irq.h"
void cx18_memset_io(struct cx18 *cx, void __iomem *addr, int val, size_t count)
{
u8 __iomem *dst = addr;
u16 val2 = val | (val << 8);
u32 val4 = val2 | (val2 << 16);
/* Align writes on the CX23418's addresses */
if ((count > 0) && ((unsigned long)dst & 1)) {
cx18_writeb(cx, (u8) val, dst);
count--;
dst++;
}
if ((count > 1) && ((unsigned long)dst & 2)) {
cx18_writew(cx, val2, dst);
count -= 2;
dst += 2;
}
while (count > 3) {
cx18_writel(cx, val4, dst);
count -= 4;
dst += 4;
}
if (count > 1) {
cx18_writew(cx, val2, dst);
count -= 2;
dst += 2;
}
if (count > 0)
cx18_writeb(cx, (u8) val, dst);
}
void cx18_sw1_irq_enable(struct cx18 *cx, u32 val)
{
cx18_write_reg_expect(cx, val, SW1_INT_STATUS, ~val, val);
cx->sw1_irq_mask = cx18_read_reg(cx, SW1_INT_ENABLE_PCI) | val;
cx18_write_reg(cx, cx->sw1_irq_mask, SW1_INT_ENABLE_PCI);
}
void cx18_sw1_irq_disable(struct cx18 *cx, u32 val)
{
cx->sw1_irq_mask = cx18_read_reg(cx, SW1_INT_ENABLE_PCI) & ~val;
cx18_write_reg(cx, cx->sw1_irq_mask, SW1_INT_ENABLE_PCI);
}
void cx18_sw2_irq_enable(struct cx18 *cx, u32 val)
{
cx18_write_reg_expect(cx, val, SW2_INT_STATUS, ~val, val);
cx->sw2_irq_mask = cx18_read_reg(cx, SW2_INT_ENABLE_PCI) | val;
cx18_write_reg(cx, cx->sw2_irq_mask, SW2_INT_ENABLE_PCI);
}
void cx18_sw2_irq_disable(struct cx18 *cx, u32 val)
{
cx->sw2_irq_mask = cx18_read_reg(cx, SW2_INT_ENABLE_PCI) & ~val;
cx18_write_reg(cx, cx->sw2_irq_mask, SW2_INT_ENABLE_PCI);
}
void cx18_sw2_irq_disable_cpu(struct cx18 *cx, u32 val)
{
u32 r;
r = cx18_read_reg(cx, SW2_INT_ENABLE_CPU);
cx18_write_reg(cx, r & ~val, SW2_INT_ENABLE_CPU);
}
void cx18_setup_page(struct cx18 *cx, u32 addr)
{
u32 val;
val = cx18_read_reg(cx, 0xD000F8);
val = (val & ~0x1f00) | ((addr >> 17) & 0x1f00);
cx18_write_reg(cx, val, 0xD000F8);
}
| gpl-2.0 |
brymaster5000/Lunar_Max | drivers/media/video/msm/wfd/enc-subdev.c | 32 | 64075 | /* Copyright (c) 2012, 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 <media/v4l2-subdev.h>
#include <mach/iommu_domains.h>
#include "enc-subdev.h"
#include "wfd-util.h"
#include <media/msm/vcd_api.h>
#include <media/msm/vidc_init.h>
#include <media/msm/vcd_property.h>
#include <linux/time.h>
#include <linux/ktime.h>
#define VID_ENC_MAX_ENCODER_CLIENTS 1
#define MAX_NUM_CTRLS 20
static long venc_fill_outbuf(struct v4l2_subdev *sd, void *arg);
struct venc_inst {
struct video_client_ctx venc_client;
void *cbdata;
void (*op_buffer_done)(void *cookie, u32 status,
struct vb2_buffer *buf);
void (*ip_buffer_done)(void *cookie, u32 status,
struct mem_region *mregion);
u32 width;
u32 height;
int secure;
struct mem_region unqueued_op_bufs;
bool streaming;
enum venc_framerate_modes framerate_mode;
};
struct venc {
s32 device_handle;
void *virt_base;
struct venc_inst venc_clients[VID_ENC_MAX_ENCODER_CLIENTS];
struct mutex lock;
struct ion_client *iclient;
};
static struct venc venc_p;
static void *venc_map_dev_base_addr(void *device_name)
{
return venc_p.virt_base;
}
static void venc_interrupt_deregister(void)
{
}
static void venc_interrupt_register(void *device_name)
{
}
static void venc_interrupt_clear(void)
{
}
int venc_load_fw(struct v4l2_subdev *sd)
{
return !vidc_load_firmware();
}
static u32 venc_get_empty_client_index(void)
{
u32 i;
u32 found = false;
for (i = 0; i < VID_ENC_MAX_ENCODER_CLIENTS; i++) {
if (!venc_p.venc_clients[i].venc_client.vcd_handle) {
found = true;
break;
}
}
if (!found) {
WFD_MSG_ERR("%s():ERROR No space for new client\n",
__func__);
return -ENOMEM;
}
WFD_MSG_INFO("%s(): available client index = %u\n",
__func__, i);
return i;
}
int venc_init(struct v4l2_subdev *sd, u32 val)
{
struct vcd_init_config vcd_init_config;
mutex_init(&venc_p.lock);
venc_p.virt_base = vidc_get_ioaddr();
vcd_init_config.device_name = "VIDC";
vcd_init_config.map_dev_base_addr = venc_map_dev_base_addr;
vcd_init_config.interrupt_clr = venc_interrupt_clear;
vcd_init_config.register_isr = venc_interrupt_register;
vcd_init_config.deregister_isr = venc_interrupt_deregister;
vcd_init(&vcd_init_config, &venc_p.device_handle);
return 0;
}
static void venc_notify_client(struct video_client_ctx *client_ctx)
{
if (client_ctx)
complete(&client_ctx->event);
}
static void venc_open_done(struct video_client_ctx *client_ctx,
struct vcd_handle_container *handle_container)
{
if (client_ctx) {
if (handle_container)
client_ctx->vcd_handle = handle_container->handle;
else
WFD_MSG_ERR("handle_container is NULL\n");
venc_notify_client(client_ctx);
} else
WFD_MSG_ERR("ERROR. client_ctx is NULL");
}
static void venc_start_done(struct video_client_ctx *client_ctx, u32 status)
{
if (client_ctx)
venc_notify_client(client_ctx);
else
WFD_MSG_ERR("ERROR. client_ctx is NULL");
}
static void venc_stop_done(struct video_client_ctx *client_ctx, u32 status)
{
WFD_MSG_DBG("Inside venc_stop_done: E\n");
if (client_ctx)
venc_notify_client(client_ctx);
else
WFD_MSG_ERR("ERROR. client_ctx is NULL");
WFD_MSG_DBG("Inside venc_stop_done: X\n");
}
static void venc_cb(u32 event, u32 status, void *info, u32 size, void *handle,
void *const client_data)
{
struct venc_inst *inst = client_data;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct vb2_buffer *vbuf;
struct mem_region *mregion;
struct vcd_frame_data *frame_data = (struct vcd_frame_data *)info;
if (!client_ctx) {
WFD_MSG_ERR("Client context is NULL\n");
return;
}
client_ctx->event_status = status;
switch (event) {
case VCD_EVT_RESP_OPEN:
WFD_MSG_DBG("EVENT: open done = %d\n", event);
venc_open_done(client_ctx,
(struct vcd_handle_container *)info);
break;
case VCD_EVT_RESP_INPUT_DONE:
case VCD_EVT_RESP_INPUT_FLUSHED:
WFD_MSG_DBG("EVENT: input done = %d\n", event);
mregion = (struct mem_region *)
frame_data->frm_clnt_data;
inst->ip_buffer_done(inst->cbdata, status, mregion);
break;
case VCD_EVT_RESP_OUTPUT_DONE:
case VCD_EVT_RESP_OUTPUT_FLUSHED:
WFD_MSG_DBG("EVENT: output done = %d\n", event);
vbuf = (struct vb2_buffer *)
frame_data->frm_clnt_data;
vbuf->v4l2_planes[0].bytesused =
frame_data->data_len;
switch (frame_data->frame) {
case VCD_FRAME_I:
case VCD_FRAME_IDR:
vbuf->v4l2_buf.flags |= V4L2_BUF_FLAG_KEYFRAME;
break;
case VCD_FRAME_P:
vbuf->v4l2_buf.flags |= V4L2_BUF_FLAG_PFRAME;
break;
case VCD_FRAME_B:
vbuf->v4l2_buf.flags |= V4L2_BUF_FLAG_BFRAME;
break;
default:
break;
}
vbuf->v4l2_buf.timestamp =
ns_to_timeval(frame_data->time_stamp * NSEC_PER_USEC);
WFD_MSG_DBG("bytes used %d, ts: %d.%d, frame type is %d\n",
frame_data->data_len,
(int)vbuf->v4l2_buf.timestamp.tv_sec,
(int)vbuf->v4l2_buf.timestamp.tv_usec,
frame_data->frame);
{
unsigned long kvaddr, phys_addr;
s32 buffer_index = -1, ion_flags = 0;
struct ion_handle *ion_handle;
int pmem_fd;
struct file *filp;
bool rc;
rc = vidc_lookup_addr_table(client_ctx,
BUFFER_TYPE_OUTPUT, true,
(unsigned long *)&frame_data->
frm_clnt_data, &kvaddr, &phys_addr,
&pmem_fd, &filp, &buffer_index);
if (rc)
ion_flags = vidc_get_fd_info(client_ctx,
BUFFER_TYPE_OUTPUT, pmem_fd,
kvaddr, buffer_index, &ion_handle);
else
WFD_MSG_ERR("Got an output buffer that we "
"couldn't recognize!\n");
if (msm_ion_do_cache_op(client_ctx->user_ion_client,
ion_handle, &kvaddr, frame_data->data_len,
ION_IOC_CLEAN_INV_CACHES))
WFD_MSG_ERR("OP buffer flush failed\n");
}
inst->op_buffer_done(inst->cbdata, status, vbuf);
break;
case VCD_EVT_RESP_START:
WFD_MSG_DBG("EVENT: start done = %d\n", event);
venc_start_done(client_ctx, status);
break;
case VCD_EVT_RESP_STOP:
WFD_MSG_DBG("EVENT: not expected = %d\n", event);
venc_stop_done(client_ctx, status);
break;
case VCD_EVT_RESP_FLUSH_INPUT_DONE:
case VCD_EVT_RESP_FLUSH_OUTPUT_DONE:
venc_notify_client(client_ctx);
break;
case VCD_EVT_RESP_PAUSE:
case VCD_EVT_IND_OUTPUT_RECONFIG:
WFD_MSG_DBG("EVENT: not expected = %d\n", event);
break;
case VCD_EVT_IND_HWERRFATAL:
case VCD_EVT_IND_RESOURCES_LOST:
WFD_MSG_DBG("EVENT: error = %d\n", event);
break;
default:
WFD_MSG_ERR("Invalid event type = %u\n", event);
break;
}
}
static long venc_open(struct v4l2_subdev *sd, void *arg)
{
u32 client_index;
int rc = 0;
struct venc_inst *inst;
struct video_client_ctx *client_ctx;
struct venc_msg_ops *vmops = arg;
int flags = 0;
mutex_lock(&venc_p.lock);
client_index = venc_get_empty_client_index();
if ((s32)client_index < 0) {
WFD_MSG_ERR("No free clients, client_index = %d\n",
client_index);
rc = -ENODEV;
goto no_free_client;
}
inst = &venc_p.venc_clients[client_index];
client_ctx = &inst->venc_client;
init_completion(&client_ctx->event);
mutex_init(&client_ctx->msg_queue_lock);
mutex_init(&client_ctx->enrty_queue_lock);
INIT_LIST_HEAD(&client_ctx->msg_queue);
init_waitqueue_head(&client_ctx->msg_wait);
inst->op_buffer_done = vmops->op_buffer_done;
inst->ip_buffer_done = vmops->ip_buffer_done;
INIT_LIST_HEAD(&inst->unqueued_op_bufs.list);
inst->cbdata = vmops->cbdata;
inst->secure = vmops->secure;
inst->streaming = false;
inst->framerate_mode = VENC_MODE_VFR;
if (vmops->secure) {
WFD_MSG_ERR("OPENING SECURE SESSION\n");
flags |= VCD_CP_SESSION;
}
if (vcd_get_ion_status()) {
client_ctx->user_ion_client = vcd_get_ion_client();
if (!client_ctx->user_ion_client) {
WFD_MSG_ERR("vcd_open ion get client failed");
return -EFAULT;
}
}
rc = vcd_open(venc_p.device_handle, false, venc_cb,
inst, flags);
if (rc) {
WFD_MSG_ERR("vcd_open failed, rc = %d\n", rc);
rc = -ENODEV;
goto no_free_client;
}
wait_for_completion(&client_ctx->event);
if (client_ctx->event_status) {
WFD_MSG_ERR("callback for vcd_open returned error: %u",
client_ctx->event_status);
goto no_free_client;
}
WFD_MSG_ERR("NOTE: client_ctx = %p\n", client_ctx);
vmops->cookie = inst;
sd->dev_priv = inst;
no_free_client:
mutex_unlock(&venc_p.lock);
return rc;
}
static long venc_close(struct v4l2_subdev *sd, void *arg)
{
long rc = 0;
struct venc_inst *inst;
struct video_client_ctx *client_ctx = NULL;
mutex_lock(&venc_p.lock);
inst = sd->dev_priv;
client_ctx = &inst->venc_client;
if (!client_ctx || !client_ctx->vcd_handle) {
WFD_MSG_ERR("Invalid client context in close\n");
rc = -ENODEV;
goto end;
}
rc = vcd_close(client_ctx->vcd_handle);
if (rc) {
WFD_MSG_ERR("Failed to close encoder subdevice\n");
goto end;
}
memset((void *)client_ctx, 0,
sizeof(struct video_client_ctx));
end:
mutex_unlock(&venc_p.lock);
return rc;
}
static long venc_get_buffer_req(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct v4l2_requestbuffers *b = arg;
struct vcd_buffer_requirement buf_req;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
if (!client_ctx) {
WFD_MSG_ERR("Invalid client context");
rc = -EINVAL;
goto err;
}
rc = vcd_get_buffer_requirements(client_ctx->vcd_handle,
VCD_BUFFER_OUTPUT, &buf_req);
if (rc) {
WFD_MSG_ERR("Failed to get out buf reqs rc = %d", rc);
goto err;
}
buf_req.actual_count = b->count = max(buf_req.min_count, b->count);
rc = vcd_set_buffer_requirements(client_ctx->vcd_handle,
VCD_BUFFER_OUTPUT, &buf_req);
if (rc) {
WFD_MSG_ERR("Failed to set out buf reqs rc = %d", rc);
goto err;
}
err:
return rc;
}
static long venc_set_buffer_req(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct bufreq *b = arg;
struct vcd_buffer_requirement buf_req;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
int aligned_width, aligned_height;
if (!client_ctx) {
WFD_MSG_ERR("Invalid client context");
rc = -EINVAL;
goto err;
}
aligned_width = ALIGN(b->width, 16);
aligned_height = ALIGN(b->height, 16);
if (aligned_width != b->width) {
WFD_MSG_ERR("Width not 16 byte aligned\n");
rc = -EINVAL;
goto err;
}
buf_req.actual_count = b->count;
buf_req.min_count = b->count;
buf_req.max_count = b->count;
buf_req.sz = ALIGN(aligned_height * aligned_width, SZ_2K)
+ ALIGN(aligned_height * aligned_width * 1/2, SZ_2K);
buf_req.align = SZ_4K;
inst->width = b->width;
inst->height = b->height;
rc = vcd_set_buffer_requirements(client_ctx->vcd_handle,
VCD_BUFFER_INPUT, &buf_req);
if (rc) {
WFD_MSG_ERR("Failed to get out buf reqs rc = %d", rc);
goto err;
}
b->size = buf_req.sz;
err:
return rc;
}
static long venc_start(struct v4l2_subdev *sd)
{
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct mem_region *curr = NULL, *temp = NULL;
int rc;
if (!client_ctx) {
WFD_MSG_ERR("Client context is NULL");
return -EINVAL;
}
rc = vcd_encode_start(client_ctx->vcd_handle);
if (rc) {
WFD_MSG_ERR("vcd_encode_start failed, rc = %d\n", rc);
goto err;
}
wait_for_completion(&client_ctx->event);
if (client_ctx->event_status)
WFD_MSG_ERR("callback for vcd_encode_start returned error: %u",
client_ctx->event_status);
inst->streaming = true;
list_for_each_entry_safe(curr, temp,
&inst->unqueued_op_bufs.list, list) {
venc_fill_outbuf(sd, curr);
list_del(&curr->list);
kfree(curr);
}
err:
return rc;
}
static long venc_stop(struct v4l2_subdev *sd)
{
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct mem_region *curr = NULL, *temp = NULL;
int rc;
if (!client_ctx) {
WFD_MSG_ERR("Client context is NULL");
return -EINVAL;
}
rc = vcd_stop(client_ctx->vcd_handle);
wait_for_completion(&client_ctx->event);
inst->streaming = false;
list_for_each_entry_safe(curr, temp,
&inst->unqueued_op_bufs.list, list) {
inst->op_buffer_done(inst->cbdata, 0,
(struct vb2_buffer *)curr->cookie);
list_del(&curr->list);
kfree(curr);
}
return rc;
}
static long venc_set_codec(struct video_client_ctx *client_ctx, __s32 codec)
{
struct vcd_property_codec vcd_property_codec;
struct vcd_property_hdr vcd_property_hdr;
vcd_property_hdr.prop_id = VCD_I_CODEC;
vcd_property_hdr.sz = sizeof(struct vcd_property_codec);
vcd_property_codec.codec = VCD_CODEC_H264;
switch (codec) {
case V4L2_PIX_FMT_H264:
vcd_property_codec.codec = VCD_CODEC_H264;
break;
case V4L2_PIX_FMT_MPEG4:
vcd_property_codec.codec = VCD_CODEC_MPEG4;
break;
default:
WFD_MSG_ERR("Codec not supported, defaulting to h264\n");
break;
}
return vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_codec);
}
static long venc_set_codec_level(struct video_client_ctx *client_ctx,
__s32 codec, __s32 level)
{
struct vcd_property_level vcd_property_level;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_codec vcd_property_codec;
int rc = 0;
int mpeg4_base = VCD_LEVEL_MPEG4_0;
int h264_base = VCD_LEVEL_H264_1;
vcd_property_hdr.prop_id = VCD_I_CODEC;
vcd_property_hdr.sz = sizeof(struct vcd_property_codec);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_codec);
if (rc < 0) {
WFD_MSG_ERR("Error getting codec property");
rc = -EINVAL;
goto err;
}
if (!((vcd_property_codec.codec == VCD_CODEC_H264
&& codec == V4L2_CID_MPEG_VIDEO_H264_LEVEL) ||
(vcd_property_codec.codec == VCD_CODEC_MPEG4
&& codec == V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL))) {
WFD_MSG_ERR("Attempting to set %d for codec type %d",
codec, vcd_property_codec.codec);
rc = -EINVAL;
goto err;
}
vcd_property_hdr.prop_id = VCD_I_LEVEL;
vcd_property_hdr.sz = sizeof(struct vcd_property_level);
if (codec == V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL) {
vcd_property_level.level = mpeg4_base + level;
if (vcd_property_level.level < VCD_LEVEL_MPEG4_0
|| vcd_property_level.level > VCD_LEVEL_MPEG4_X) {
WFD_MSG_ERR("Level (%d) out of range"
"for codec (%d)\n", level, codec);
rc = -EINVAL;
goto err;
}
} else if (codec == V4L2_CID_MPEG_VIDEO_H264_LEVEL) {
vcd_property_level.level = h264_base + level;
if (vcd_property_level.level < VCD_LEVEL_H264_1
|| vcd_property_level.level > VCD_LEVEL_H264_5p1) {
WFD_MSG_ERR("Level (%d) out of range"
"for codec (%d)\n", level, codec);
rc = -EINVAL;
goto err;
}
} else {
WFD_MSG_ERR("Codec (%d) not supported, not setting level (%d)",
codec, level);
rc = -ENOTSUPP;
goto err;
}
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_level);
err:
return rc;
}
static long venc_get_codec_level(struct video_client_ctx *client_ctx,
__s32 codec, __s32 *level)
{
struct vcd_property_level vcd_property_level;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_codec vcd_property_codec;
int rc = 0;
int mpeg4_base = VCD_LEVEL_MPEG4_0;
int h264_base = VCD_LEVEL_H264_1;
vcd_property_hdr.prop_id = VCD_I_CODEC;
vcd_property_hdr.sz = sizeof(struct vcd_property_codec);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_codec);
if (rc < 0) {
WFD_MSG_ERR("Error getting codec property");
rc = -EINVAL;
goto err;
}
if (!((vcd_property_codec.codec == VCD_CODEC_H264
&& codec == V4L2_CID_MPEG_VIDEO_H264_LEVEL) ||
(vcd_property_codec.codec == VCD_CODEC_MPEG4
&& codec == V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL))) {
WFD_MSG_ERR("Attempting to get %d for codec type %d",
codec, vcd_property_codec.codec);
rc = -EINVAL;
goto err;
}
vcd_property_hdr.prop_id = VCD_I_LEVEL;
vcd_property_hdr.sz = sizeof(struct vcd_property_level);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_level);
if (rc < 0) {
rc = -EINVAL;
goto err;
}
if (codec == V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL) {
*level = vcd_property_level.level - mpeg4_base;
} else if (codec == V4L2_CID_MPEG_VIDEO_H264_LEVEL) {
*level = vcd_property_level.level - h264_base;
} else {
WFD_MSG_ERR("Codec (%d) not supported", codec);
rc = -ENOTSUPP;
goto err;
}
err:
return rc;
}
static long venc_set_codec_profile(struct video_client_ctx *client_ctx,
__s32 codec, __s32 profile)
{
struct vcd_property_profile vcd_property_profile;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_codec vcd_property_codec;
struct vcd_property_i_period vcd_property_i_period;
int rc = 0;
vcd_property_hdr.prop_id = VCD_I_CODEC;
vcd_property_hdr.sz = sizeof(struct vcd_property_codec);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_codec);
if (rc < 0) {
WFD_MSG_ERR("Error getting codec property");
rc = -EINVAL;
goto err_set_profile;
}
if (!((vcd_property_codec.codec == VCD_CODEC_H264
&& codec == V4L2_CID_MPEG_VIDEO_H264_PROFILE) ||
(vcd_property_codec.codec == VCD_CODEC_MPEG4
&& codec == V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE))) {
WFD_MSG_ERR("Attempting to set %d for codec type %d",
codec, vcd_property_codec.codec);
rc = -EINVAL;
goto err_set_profile;
}
vcd_property_hdr.prop_id = VCD_I_PROFILE;
vcd_property_hdr.sz = sizeof(struct vcd_property_profile);
if (codec == V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE) {
switch (profile) {
case V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE:
vcd_property_profile.profile = VCD_PROFILE_MPEG4_SP;
break;
case V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_SIMPLE:
vcd_property_profile.profile = VCD_PROFILE_MPEG4_ASP;
break;
default:
WFD_MSG_ERR("Profile %d not supported,"
"defaulting to simple (%d)",
profile, VCD_PROFILE_MPEG4_SP);
vcd_property_profile.profile = VCD_PROFILE_MPEG4_SP;
break;
}
} else if (codec == V4L2_CID_MPEG_VIDEO_H264_PROFILE) {
switch (profile) {
case V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE:
vcd_property_profile.profile =
VCD_PROFILE_H264_BASELINE;
break;
case V4L2_MPEG_VIDEO_H264_PROFILE_MAIN:
vcd_property_profile.profile = VCD_PROFILE_H264_MAIN;
break;
case V4L2_MPEG_VIDEO_H264_PROFILE_HIGH:
vcd_property_profile.profile = VCD_PROFILE_H264_HIGH;
break;
default:
WFD_MSG_ERR("Profile %d not supported,"
"defaulting to baseline (%d)",
profile, VCD_PROFILE_H264_BASELINE);
vcd_property_profile.profile =
VCD_PROFILE_H264_BASELINE;
break;
}
} else {
WFD_MSG_ERR("Codec (%d) not supported,"
"not setting profile (%d)",
codec, profile);
rc = -ENOTSUPP;
goto err_set_profile;
}
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_profile);
vcd_property_hdr.prop_id = VCD_I_INTRA_PERIOD;
vcd_property_hdr.sz = sizeof(struct vcd_property_i_period);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_i_period);
if (rc) {
WFD_MSG_ERR("Error getting I-period property");
goto err_set_profile;
}
vcd_property_i_period.b_frames = 0;
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_i_period);
if (rc) {
WFD_MSG_ERR("Error setting I-period property");
goto err_set_profile;
}
err_set_profile:
return rc;
}
static long venc_get_codec_profile(struct video_client_ctx *client_ctx,
__s32 codec, __s32 *profile)
{
struct vcd_property_profile vcd_property_profile;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_codec vcd_property_codec;
int rc = 0;
vcd_property_hdr.prop_id = VCD_I_CODEC;
vcd_property_hdr.sz = sizeof(struct vcd_property_codec);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_codec);
if (rc < 0) {
WFD_MSG_ERR("Error getting codec property");
rc = -EINVAL;
goto err;
}
if (!((vcd_property_codec.codec == VCD_CODEC_H264
&& codec == V4L2_CID_MPEG_VIDEO_H264_PROFILE) ||
(vcd_property_codec.codec == VCD_CODEC_MPEG4
&& codec == V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE))) {
WFD_MSG_ERR("Attempting to set %d for codec type %d",
codec, vcd_property_codec.codec);
rc = -EINVAL;
goto err;
}
vcd_property_hdr.prop_id = VCD_I_PROFILE;
vcd_property_hdr.sz = sizeof(struct vcd_property_profile);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_profile);
if (rc < 0) {
WFD_MSG_ERR("Unable to get property");
rc = -EINVAL;
goto err;
}
switch (vcd_property_profile.profile) {
case VCD_PROFILE_MPEG4_SP:
*profile = V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE;
break;
case VCD_PROFILE_MPEG4_ASP:
*profile = V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_SIMPLE;
break;
case VCD_PROFILE_H264_BASELINE:
*profile = V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE;
break;
case VCD_PROFILE_H264_MAIN:
*profile = V4L2_MPEG_VIDEO_H264_PROFILE_MAIN;
break;
case VCD_PROFILE_H264_HIGH:
*profile = V4L2_MPEG_VIDEO_H264_PROFILE_HIGH;
break;
default:
WFD_MSG_ERR("Unexpected profile");
rc = -EINVAL;
goto err;
break;
}
err:
return rc;
}
static long venc_set_h264_intra_period(struct video_client_ctx *client_ctx,
__s32 period)
{
struct vcd_property_i_period vcd_property_i_period;
struct vcd_property_codec vcd_property_codec;
struct vcd_property_hdr vcd_property_hdr;
int rc = 0;
vcd_property_hdr.prop_id = VCD_I_CODEC;
vcd_property_hdr.sz = sizeof(struct vcd_property_codec);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_codec);
if (rc < 0) {
WFD_MSG_ERR("Error getting codec property\n");
goto err;
}
if (vcd_property_codec.codec != VCD_CODEC_H264) {
rc = -ENOTSUPP;
WFD_MSG_ERR("Control not supported for non H264 codec\n");
goto err;
}
vcd_property_hdr.prop_id = VCD_I_INTRA_PERIOD;
vcd_property_hdr.sz = sizeof(struct vcd_property_i_period);
vcd_property_i_period.p_frames = period - 1;
vcd_property_i_period.b_frames = 0;
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_i_period);
if (rc < 0) {
WFD_MSG_ERR("Error setting intra period\n");
goto err;
}
err:
return rc;
}
static long venc_get_h264_intra_period(struct video_client_ctx *client_ctx,
__s32 *period)
{
struct vcd_property_i_period vcd_property_i_period;
struct vcd_property_codec vcd_property_codec;
struct vcd_property_hdr vcd_property_hdr;
int rc = 0;
vcd_property_hdr.prop_id = VCD_I_CODEC;
vcd_property_hdr.sz = sizeof(struct vcd_property_codec);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_codec);
if (rc < 0) {
WFD_MSG_ERR("Error getting codec property\n");
goto err;
}
if (vcd_property_codec.codec != VCD_CODEC_H264) {
rc = -ENOTSUPP;
WFD_MSG_ERR("Control not supported for non H264 codec\n");
goto err;
}
vcd_property_hdr.prop_id = VCD_I_INTRA_PERIOD;
vcd_property_hdr.sz = sizeof(struct vcd_property_i_period);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_i_period);
if (rc < 0) {
WFD_MSG_ERR("Error getting intra period\n");
goto err;
}
*period = vcd_property_i_period.p_frames + 1;
err:
return rc;
}
static long venc_request_frame(struct video_client_ctx *client_ctx, __s32 type)
{
struct vcd_property_req_i_frame vcd_property_req_i_frame;
struct vcd_property_hdr vcd_property_hdr;
int rc = 0;
switch (type) {
case V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_DISABLED:
break;
case V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME:
vcd_property_hdr.prop_id = VCD_I_REQ_IFRAME;
vcd_property_hdr.sz = sizeof(struct vcd_property_req_i_frame);
vcd_property_req_i_frame.req_i_frame = 1;
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_property_req_i_frame);
break;
case V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_NOT_CODED:
default:
rc = -ENOTSUPP;
}
return rc;
}
static long venc_set_bitrate(struct video_client_ctx *client_ctx,
__s32 bitrate)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_target_bitrate bit_rate;
if (!client_ctx || !bitrate)
return -EINVAL;
vcd_property_hdr.prop_id = VCD_I_TARGET_BITRATE;
vcd_property_hdr.sz =
sizeof(struct vcd_property_target_bitrate);
bit_rate.target_bitrate = bitrate;
return vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &bit_rate);
}
static long venc_get_bitrate(struct video_client_ctx *client_ctx,
__s32 *bitrate)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_target_bitrate bit_rate;
int rc = 0;
if (!client_ctx || !bitrate)
return -EINVAL;
vcd_property_hdr.prop_id = VCD_I_TARGET_BITRATE;
vcd_property_hdr.sz =
sizeof(struct vcd_property_target_bitrate);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &bit_rate);
if (rc < 0) {
WFD_MSG_ERR("Failed getting property for bitrate");
return rc;
}
*bitrate = bit_rate.target_bitrate;
return rc;
}
static long venc_set_bitrate_mode(struct video_client_ctx *client_ctx,
__s32 mode)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_rate_control rate_control;
int rc = 0;
if (!client_ctx) {
rc = -EINVAL;
goto err;
}
vcd_property_hdr.prop_id = VCD_I_RATE_CONTROL;
vcd_property_hdr.sz = sizeof(struct vcd_property_rate_control);
switch (mode) {
case V4L2_MPEG_VIDEO_BITRATE_MODE_VBR:
rate_control.rate_control = VCD_RATE_CONTROL_VBR_VFR;
break;
case V4L2_MPEG_VIDEO_BITRATE_MODE_CBR:
rate_control.rate_control = VCD_RATE_CONTROL_CBR_VFR;
break;
default:
WFD_MSG_ERR("unknown bitrate mode %d", mode);
rc = -EINVAL;
goto err;
}
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &rate_control);
err:
return rc;
}
static long venc_get_bitrate_mode(struct video_client_ctx *client_ctx,
__s32 *mode)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_rate_control rate_control;
int rc = 0;
if (!client_ctx)
return -EINVAL;
vcd_property_hdr.prop_id = VCD_I_RATE_CONTROL;
vcd_property_hdr.sz = sizeof(struct vcd_property_rate_control);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &rate_control);
switch (rate_control.rate_control) {
case VCD_RATE_CONTROL_CBR_VFR:
case VCD_RATE_CONTROL_CBR_CFR:
*mode = V4L2_MPEG_VIDEO_BITRATE_MODE_CBR;
break;
case VCD_RATE_CONTROL_VBR_VFR:
case VCD_RATE_CONTROL_VBR_CFR:
*mode = V4L2_MPEG_VIDEO_BITRATE_MODE_VBR;
break;
default:
WFD_MSG_ERR("unknown bitrate mode %d",
rate_control.rate_control);
return -EINVAL;
}
return 0;
}
static long venc_set_frame_size(struct video_client_ctx *client_ctx,
u32 height, u32 width)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_frame_size frame_size;
vcd_property_hdr.prop_id = VCD_I_FRAME_SIZE;
vcd_property_hdr.sz =
sizeof(struct vcd_property_frame_size);
frame_size.height = height;
frame_size.width = width;
return vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &frame_size);
}
static long venc_set_format(struct v4l2_subdev *sd, void *arg)
{
struct venc_inst *inst;
struct video_client_ctx *client_ctx;
struct v4l2_format *fmt = arg;
struct vcd_buffer_requirement buf_req;
int rc = 0;
inst = sd->dev_priv;
client_ctx = &inst->venc_client;
if (!inst || !client_ctx || !fmt) {
WFD_MSG_ERR("Invalid parameters\n");
return -EINVAL;
}
rc = venc_set_codec(client_ctx, fmt->fmt.pix.pixelformat);
if (rc) {
WFD_MSG_ERR("Failed to set codec, rc = %d\n", rc);
goto err;
}
rc = venc_set_frame_size(client_ctx, fmt->fmt.pix.height,
fmt->fmt.pix.width);
if (rc) {
WFD_MSG_ERR("Failed to set frame size, rc = %d\n", rc);
goto err;
}
rc = vcd_get_buffer_requirements(client_ctx->vcd_handle,
VCD_BUFFER_OUTPUT, &buf_req);
if (rc) {
WFD_MSG_ERR("Failed to get buf requrements, rc = %d\n", rc);
goto err;
}
fmt->fmt.pix.sizeimage = buf_req.sz;
err:
return rc;
}
static long venc_set_framerate(struct v4l2_subdev *sd,
void *arg)
{
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct v4l2_fract *frate = arg;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_frame_rate vcd_frame_rate;
struct vcd_property_vop_timing_constant_delta vcd_delta;
int rc;
vcd_property_hdr.prop_id = VCD_I_FRAME_RATE;
vcd_property_hdr.sz =
sizeof(struct vcd_property_frame_rate);
vcd_frame_rate.fps_denominator = frate->numerator;
vcd_frame_rate.fps_numerator = frate->denominator;
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_frame_rate);
if (rc) {
WFD_MSG_ERR("Failed to set frame rate, rc = %d\n", rc);
goto set_framerate_fail;
}
vcd_property_hdr.prop_id = VCD_I_VOP_TIMING_CONSTANT_DELTA;
vcd_property_hdr.sz = sizeof(vcd_delta);
vcd_delta.constant_delta = (frate->numerator * USEC_PER_SEC) /
frate->denominator;
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_delta);
if (rc) {
WFD_MSG_ERR("Failed to set frame delta, rc = %d", rc);
goto set_framerate_fail;
}
set_framerate_fail:
return rc;
}
static long venc_set_framerate_mode(struct v4l2_subdev *sd,
void *arg)
{
struct venc_inst *inst = sd->dev_priv;
inst->framerate_mode = *(enum venc_framerate_modes *)arg;
return 0;
}
static long venc_set_qp_value(struct video_client_ctx *client_ctx,
__s32 frametype, __s32 qp)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_session_qp vcd_property_session_qp;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
return -EINVAL;
}
vcd_property_hdr.prop_id = VCD_I_SESSION_QP;
vcd_property_hdr.sz = sizeof(vcd_property_session_qp);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_property_session_qp);
if (rc) {
WFD_MSG_ERR("Failed to get session qp\n");
goto err;
}
switch (frametype) {
case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
vcd_property_session_qp.i_frame_qp = qp;
break;
case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
vcd_property_session_qp.p_frame_qp = qp;
break;
case V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP:
vcd_property_session_qp.b_frame_qp = qp;
break;
case V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP:
rc = -ENOTSUPP;
goto err;
default:
rc = -EINVAL;
goto err;
}
rc = vcd_set_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_property_session_qp);
if (rc) {
WFD_MSG_ERR("Failed to set session qp\n");
goto err;
}
err:
return rc;
}
static long venc_get_qp_value(struct video_client_ctx *client_ctx,
__s32 frametype, __s32 *qp)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_session_qp vcd_property_session_qp;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
return -EINVAL;
}
vcd_property_hdr.prop_id = VCD_I_SESSION_QP;
vcd_property_hdr.sz = sizeof(vcd_property_session_qp);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_property_session_qp);
if (rc) {
WFD_MSG_ERR("Failed to get session qp\n");
goto err;
}
switch (frametype) {
case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
*qp = vcd_property_session_qp.i_frame_qp;
break;
case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
*qp = vcd_property_session_qp.p_frame_qp;
break;
case V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP:
*qp = vcd_property_session_qp.b_frame_qp;
break;
default:
rc = -EINVAL;
goto err;
}
err:
return rc;
}
static long venc_set_qp_range(struct video_client_ctx *client_ctx,
__s32 type, __s32 qp)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_qp_range vcd_property_qp_range;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
return -EINVAL;
}
vcd_property_hdr.prop_id = VCD_I_QP_RANGE;
vcd_property_hdr.sz = sizeof(vcd_property_qp_range);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_property_qp_range);
if (rc) {
WFD_MSG_ERR("Failed to get qp range\n");
goto err;
}
switch (type) {
case V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H263_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
vcd_property_qp_range.min_qp = qp;
break;
case V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H263_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
vcd_property_qp_range.max_qp = qp;
break;
default:
rc = -EINVAL;
goto err;
}
rc = vcd_set_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_property_qp_range);
if (rc) {
WFD_MSG_ERR("Failed to set qp range\n");
goto err;
}
err:
return rc;
}
static long venc_get_qp_range(struct video_client_ctx *client_ctx,
__s32 type, __s32 *qp)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_qp_range vcd_property_qp_range;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
return -EINVAL;
}
vcd_property_hdr.prop_id = VCD_I_QP_RANGE;
vcd_property_hdr.sz = sizeof(vcd_property_qp_range);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_property_qp_range);
if (rc) {
WFD_MSG_ERR("Failed to get qp range\n");
goto err;
}
switch (type) {
case V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H263_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
*qp = vcd_property_qp_range.min_qp;
break;
case V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H263_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
*qp = vcd_property_qp_range.max_qp;
break;
default:
rc = -EINVAL;
goto err;
}
rc = vcd_set_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_property_qp_range);
if (rc) {
WFD_MSG_ERR("Failed to set qp range\n");
goto err;
}
err:
return rc;
}
static long venc_set_max_perf_level(struct video_client_ctx *client_ctx,
__s32 value)
{
int rc = 0;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_perf_level perf;
int level = 0;
switch (value) {
case V4L2_CID_MPEG_QCOM_PERF_LEVEL_PERFORMANCE:
level = VCD_PERF_LEVEL2;
break;
case V4L2_CID_MPEG_QCOM_PERF_LEVEL_TURBO:
level = VCD_PERF_LEVEL_TURBO;
break;
default:
WFD_MSG_ERR("Unknown performance level: %d\n", value);
rc = -ENOTSUPP;
goto err_set_perf_level;
}
vcd_property_hdr.prop_id = VCD_REQ_PERF_LEVEL;
vcd_property_hdr.sz =
sizeof(struct vcd_property_perf_level);
perf.level = level;
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &perf);
err_set_perf_level:
return rc;
}
static long venc_set_avc_delimiter(struct video_client_ctx *client_ctx,
__s32 flag)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_avc_delimiter_enable delimiter_flag;
if (!client_ctx)
return -EINVAL;
vcd_property_hdr.prop_id = VCD_I_ENABLE_DELIMITER_FLAG;
vcd_property_hdr.sz =
sizeof(struct vcd_property_avc_delimiter_enable);
delimiter_flag.avc_delimiter_enable_flag = flag;
return vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &delimiter_flag);
}
static long venc_get_avc_delimiter(struct video_client_ctx *client_ctx,
__s32 *flag)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_avc_delimiter_enable delimiter_flag;
int rc = 0;
if (!client_ctx || !flag)
return -EINVAL;
vcd_property_hdr.prop_id = VCD_I_ENABLE_DELIMITER_FLAG;
vcd_property_hdr.sz =
sizeof(struct vcd_property_avc_delimiter_enable);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &delimiter_flag);
if (rc < 0) {
WFD_MSG_ERR("Failed getting property for delimiter");
return rc;
}
*flag = delimiter_flag.avc_delimiter_enable_flag;
return rc;
}
static long venc_set_vui_timing_info(struct video_client_ctx *client_ctx,
struct venc_inst *inst, __s32 flag)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_vui_timing_info_enable vui_timing_info_enable;
if (!client_ctx)
return -EINVAL;
if (inst->framerate_mode == VENC_MODE_VFR) {
WFD_MSG_ERR("VUI timing info not suported in VFR mode ");
return -EINVAL;
}
vcd_property_hdr.prop_id = VCD_I_ENABLE_VUI_TIMING_INFO;
vcd_property_hdr.sz =
sizeof(struct vcd_property_vui_timing_info_enable);
vui_timing_info_enable.vui_timing_info = flag;
return vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vui_timing_info_enable);
}
static long venc_get_vui_timing_info(struct video_client_ctx *client_ctx,
__s32 *flag)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_vui_timing_info_enable vui_timing_info_enable;
int rc = 0;
if (!client_ctx || !flag)
return -EINVAL;
vcd_property_hdr.prop_id = VCD_I_ENABLE_VUI_TIMING_INFO;
vcd_property_hdr.sz =
sizeof(struct vcd_property_vui_timing_info_enable);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vui_timing_info_enable);
if (rc < 0) {
WFD_MSG_ERR("Failed getting property for VUI timing info");
return rc;
}
*flag = vui_timing_info_enable.vui_timing_info;
return rc;
}
static long venc_set_header_mode(struct video_client_ctx *client_ctx,
__s32 mode)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_sps_pps_for_idr_enable sps_pps_for_idr_enable;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto err;
}
vcd_property_hdr.prop_id = VCD_I_ENABLE_SPS_PPS_FOR_IDR;
vcd_property_hdr.sz = sizeof(sps_pps_for_idr_enable);
switch (mode) {
case V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE:
sps_pps_for_idr_enable.sps_pps_for_idr_enable_flag = 0;
break;
case V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_I_FRAME:
sps_pps_for_idr_enable.sps_pps_for_idr_enable_flag = 1;
break;
case V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME:
default:
WFD_MSG_ERR("Video header mode %d not supported\n",
mode);
rc = -ENOTSUPP;
goto err;
}
rc = vcd_set_property(client_ctx->vcd_handle, &vcd_property_hdr,
&sps_pps_for_idr_enable);
if (rc) {
WFD_MSG_ERR("Failed to set enable_sps_pps_for_idr\n");
goto err;
}
err:
return rc;
}
static long venc_get_header_mode(struct video_client_ctx *client_ctx,
__s32 *mode)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_sps_pps_for_idr_enable sps_pps_for_idr_enable;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto err;
}
vcd_property_hdr.prop_id = VCD_I_ENABLE_SPS_PPS_FOR_IDR;
vcd_property_hdr.sz = sizeof(sps_pps_for_idr_enable);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&sps_pps_for_idr_enable);
if (rc) {
WFD_MSG_ERR("Failed to get sps/pps for idr enable\n");
goto err;
}
*mode = sps_pps_for_idr_enable.sps_pps_for_idr_enable_flag ?
V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_I_FRAME :
V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE;
err:
return rc;
}
static long venc_set_multislicing_mode(struct video_client_ctx *client_ctx,
__u32 control, __s32 value)
{
int rc = 0;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_frame_size vcd_frame_size;
struct vcd_buffer_requirement vcd_buf_req;
struct vcd_property_multi_slice vcd_multi_slice;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto set_multislicing_mode_fail;
}
vcd_property_hdr.prop_id = VCD_I_FRAME_SIZE;
vcd_property_hdr.sz =
sizeof(vcd_frame_size);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_frame_size);
if (rc) {
WFD_MSG_ERR("Failed to get frame size\n");
goto set_multislicing_mode_fail;
}
rc = vcd_get_buffer_requirements(client_ctx->vcd_handle,
VCD_BUFFER_OUTPUT, &vcd_buf_req);
if (rc) {
WFD_MSG_ERR("Failed to get buf reqs\n");
goto set_multislicing_mode_fail;
}
vcd_property_hdr.prop_id = VCD_I_MULTI_SLICE;
vcd_property_hdr.sz = sizeof(vcd_multi_slice);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_multi_slice);
if (rc) {
WFD_MSG_ERR("Failed to get multi slice\n");
goto set_multislicing_mode_fail;
}
switch (control) {
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
if (vcd_multi_slice.m_slice_sel !=
VCD_MSLICE_BY_BYTE_COUNT) {
WFD_MSG_ERR("Not in proper mode\n");
goto set_multislicing_mode_fail;
}
vcd_multi_slice.m_slice_size = value;
break;
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
if (vcd_multi_slice.m_slice_sel !=
VCD_MSLICE_BY_MB_COUNT) {
WFD_MSG_ERR("Not in proper mode\n");
goto set_multislicing_mode_fail;
}
vcd_multi_slice.m_slice_size = value;
break;
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
switch (value) {
case V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE:
vcd_multi_slice.m_slice_sel = VCD_MSLICE_OFF;
break;
case V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB:
vcd_multi_slice.m_slice_sel = VCD_MSLICE_BY_MB_COUNT;
vcd_multi_slice.m_slice_size =
(vcd_frame_size.stride / 16) *
(vcd_frame_size.scan_lines / 16);
break;
case V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES:
vcd_multi_slice.m_slice_sel = VCD_MSLICE_BY_BYTE_COUNT;
vcd_multi_slice.m_slice_size = vcd_buf_req.sz;
break;
default:
WFD_MSG_ERR("Unrecognized mode %d\n", value);
rc = -ENOTSUPP;
goto set_multislicing_mode_fail;
}
break;
default:
rc = -EINVAL;
goto set_multislicing_mode_fail;
}
rc = vcd_set_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_multi_slice);
if (rc) {
WFD_MSG_ERR("Failed to set multi slice\n");
goto set_multislicing_mode_fail;
}
set_multislicing_mode_fail:
return rc;
}
static long venc_get_multislicing_mode(struct video_client_ctx *client_ctx,
__u32 control, __s32 *value)
{
int rc = 0;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_frame_size vcd_frame_size;
struct vcd_buffer_requirement vcd_buf_req;
struct vcd_property_multi_slice vcd_multi_slice;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto get_multislicing_mode_fail;
}
vcd_property_hdr.prop_id = VCD_I_FRAME_SIZE;
vcd_property_hdr.sz =
sizeof(vcd_frame_size);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &vcd_frame_size);
if (rc) {
WFD_MSG_ERR("Failed to get frame size\n");
goto get_multislicing_mode_fail;
}
vcd_property_hdr.prop_id = VCD_I_MULTI_SLICE;
vcd_property_hdr.sz = sizeof(vcd_multi_slice);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&vcd_multi_slice);
if (rc) {
WFD_MSG_ERR("Failed to get multi slice\n");
goto get_multislicing_mode_fail;
}
rc = vcd_get_buffer_requirements(client_ctx->vcd_handle,
VCD_BUFFER_OUTPUT, &vcd_buf_req);
if (rc) {
WFD_MSG_ERR("Failed to get buf reqs\n");
goto get_multislicing_mode_fail;
}
switch (control) {
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
if (vcd_multi_slice.m_slice_sel == VCD_MSLICE_BY_BYTE_COUNT)
*value = vcd_multi_slice.m_slice_size;
else {
WFD_MSG_ERR("Invalid query when in slice mode %d\n",
vcd_multi_slice.m_slice_sel);
rc = -EINVAL;
goto get_multislicing_mode_fail;
}
break;
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
if (vcd_multi_slice.m_slice_sel == VCD_MSLICE_BY_MB_COUNT)
*value = vcd_multi_slice.m_slice_size;
else {
WFD_MSG_ERR("Invalid query when in slice mode %d\n",
vcd_multi_slice.m_slice_sel);
rc = -EINVAL;
goto get_multislicing_mode_fail;
}
break;
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
switch (vcd_multi_slice.m_slice_sel) {
case VCD_MSLICE_OFF:
*value = V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE;
break;
case VCD_MSLICE_BY_MB_COUNT:
*value = V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB;
break;
case VCD_MSLICE_BY_BYTE_COUNT:
*value = V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES;
break;
default:
WFD_MSG_ERR("Encoder in an unknown mode %d\n",
vcd_multi_slice.m_slice_sel);
rc = -ENOENT;
goto get_multislicing_mode_fail;
}
break;
default:
rc = -EINVAL;
goto get_multislicing_mode_fail;
}
get_multislicing_mode_fail:
return rc;
}
static long venc_set_entropy_mode(struct video_client_ctx *client_ctx,
__s32 value)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_entropy_control entropy_control;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto set_entropy_mode_fail;
}
vcd_property_hdr.prop_id = VCD_I_ENTROPY_CTRL;
vcd_property_hdr.sz = sizeof(entropy_control);
switch (value) {
case V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC:
entropy_control.entropy_sel = VCD_ENTROPY_SEL_CAVLC;
break;
case V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC:
entropy_control.entropy_sel = VCD_ENTROPY_SEL_CABAC;
entropy_control.cabac_model = VCD_CABAC_MODEL_NUMBER_0;
break;
default:
WFD_MSG_ERR("Entropy type %d not supported\n", value);
rc = -ENOTSUPP;
goto set_entropy_mode_fail;
}
rc = vcd_set_property(client_ctx->vcd_handle, &vcd_property_hdr,
&entropy_control);
if (rc) {
WFD_MSG_ERR("Failed to set entropy mode\n");
goto set_entropy_mode_fail;
}
set_entropy_mode_fail:
return rc;
}
static long venc_get_entropy_mode(struct video_client_ctx *client_ctx,
__s32 *value)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_entropy_control entropy_control;
int rc = 0;
if (!client_ctx || !value) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto get_entropy_mode_fail;
}
vcd_property_hdr.prop_id = VCD_I_ENTROPY_CTRL;
vcd_property_hdr.sz = sizeof(entropy_control);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&entropy_control);
if (rc) {
WFD_MSG_ERR("Failed to get entropy mode\n");
goto get_entropy_mode_fail;
}
switch (entropy_control.entropy_sel) {
case VCD_ENTROPY_SEL_CAVLC:
*value = V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC;
break;
case VCD_ENTROPY_SEL_CABAC:
*value = V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC;
break;
default:
WFD_MSG_ERR("Entropy type %d not known\n",
entropy_control.entropy_sel);
rc = -EINVAL;
goto get_entropy_mode_fail;
}
get_entropy_mode_fail:
return rc;
}
static long venc_set_cyclic_intra_refresh_mb(
struct video_client_ctx *client_ctx,
__s32 value)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_intra_refresh_mb_number cir_mb_num;
int rc = 0;
if (!client_ctx) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto set_cir_mbs_fail;
}
vcd_property_hdr.prop_id = VCD_I_INTRA_REFRESH;
vcd_property_hdr.sz = sizeof(cir_mb_num);
cir_mb_num.cir_mb_number = value;
rc = vcd_set_property(client_ctx->vcd_handle, &vcd_property_hdr,
&cir_mb_num);
if (rc) {
WFD_MSG_ERR("Failed to set CIR MBs\n");
goto set_cir_mbs_fail;
}
set_cir_mbs_fail:
return rc;
}
static long venc_get_cyclic_intra_refresh_mb(
struct video_client_ctx *client_ctx,
__s32 *value)
{
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_intra_refresh_mb_number cir_mb_num;
int rc = 0;
if (!client_ctx || !value) {
WFD_MSG_ERR("Invalid parameters\n");
rc = -EINVAL;
goto get_cir_mbs_fail;
}
vcd_property_hdr.prop_id = VCD_I_INTRA_REFRESH;
vcd_property_hdr.sz = sizeof(cir_mb_num);
rc = vcd_get_property(client_ctx->vcd_handle, &vcd_property_hdr,
&cir_mb_num);
if (rc) {
WFD_MSG_ERR("Failed to set CIR MBs\n");
goto get_cir_mbs_fail;
}
*value = cir_mb_num.cir_mb_number;
get_cir_mbs_fail:
return rc;
}
static long venc_set_input_buffer(struct v4l2_subdev *sd, void *arg)
{
struct mem_region *mregion = arg;
struct venc_inst *inst = sd->dev_priv;
unsigned long paddr, kvaddr, temp;
struct video_client_ctx *client_ctx = &inst->venc_client;
int rc = 0;
if (!client_ctx || !mregion) {
WFD_MSG_ERR("Invalid input\n");
rc = -EINVAL;
goto ins_table_fail;
}
kvaddr = (unsigned long)mregion->kvaddr;
paddr = (unsigned long)mregion->paddr;
if (!kvaddr || !paddr) {
WFD_MSG_ERR("Invalid addresses\n");
rc = -EINVAL;
goto ins_table_fail;
}
rc = vidc_insert_addr_table_kernel(client_ctx,
BUFFER_TYPE_INPUT, kvaddr, kvaddr,
paddr, 32, mregion->size);
if (rc == (u32)false) {
WFD_MSG_ERR("Failed to insert input buffer into table\n");
rc = -EFAULT;
goto ins_table_fail;
}
rc = vcd_set_buffer(client_ctx->vcd_handle,
VCD_BUFFER_INPUT, (u8 *)kvaddr,
mregion->size);
if (rc) {
WFD_MSG_ERR("Failed to set input buffer\n");
rc = -EFAULT;
goto set_input_buf_fail;
}
return rc;
set_input_buf_fail:
vidc_delete_addr_table(client_ctx, BUFFER_TYPE_INPUT,
kvaddr, &temp);
ins_table_fail:
return rc;
}
static long venc_set_output_buffer(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct mem_region *mregion = arg;
if (!client_ctx || !mregion) {
WFD_MSG_ERR("Invalid input\n");
return -EINVAL;
}
WFD_MSG_DBG("size = %u, offset = %u fd = %d\n", mregion->size,
mregion->offset, mregion->fd);
rc = vidc_insert_addr_table(client_ctx, BUFFER_TYPE_OUTPUT,
mregion->cookie,
(unsigned long *)&mregion->kvaddr,
mregion->fd,
mregion->offset,
32,
mregion->size);
if (rc == (u32)false) {
WFD_MSG_ERR("Failed to insert outbuf in table\n");
rc = -EINVAL;
goto err;
}
WFD_MSG_DBG("size = %u, %p\n", mregion->size, mregion->kvaddr);
rc = vcd_set_buffer(client_ctx->vcd_handle,
VCD_BUFFER_OUTPUT, (u8 *) mregion->kvaddr,
mregion->size);
if (rc)
WFD_MSG_ERR("Failed to set outbuf on encoder\n");
err:
return rc;
}
static long venc_fill_outbuf(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct mem_region *mregion = arg;
struct vcd_frame_data vcd_frame = {0};
unsigned long kernel_vaddr, phy_addr, user_vaddr;
int pmem_fd;
struct file *file;
s32 buffer_index = -1;
if (inst->streaming) {
user_vaddr = mregion->cookie;
rc = vidc_lookup_addr_table(client_ctx, BUFFER_TYPE_OUTPUT,
true, &user_vaddr,
&kernel_vaddr, &phy_addr, &pmem_fd, &file,
&buffer_index);
if (!rc) {
WFD_MSG_ERR("Address lookup failed\n");
goto err;
}
vcd_frame.virtual = (u8 *) kernel_vaddr;
vcd_frame.frm_clnt_data = mregion->cookie;
vcd_frame.alloc_len = mregion->size;
rc = vcd_fill_output_buffer(client_ctx->vcd_handle, &vcd_frame);
if (rc)
WFD_MSG_ERR("Failed to fill output buffer on encoder");
} else {
struct mem_region *temp = kzalloc(sizeof(*temp), GFP_KERNEL);
*temp = *mregion;
INIT_LIST_HEAD(&temp->list);
list_add_tail(&temp->list, &inst->unqueued_op_bufs.list);
}
err:
return rc;
}
static long venc_encode_frame(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct venc_buf_info *venc_buf = arg;
struct mem_region *mregion = venc_buf->mregion;
struct vcd_frame_data vcd_input_buffer = {0};
int64_t ts = 0;
ts = venc_buf->timestamp;
do_div(ts, NSEC_PER_USEC);
vcd_input_buffer.virtual = mregion->kvaddr;
vcd_input_buffer.frm_clnt_data = (u32)mregion;
vcd_input_buffer.ip_frm_tag = (u32)mregion;
vcd_input_buffer.data_len = mregion->size;
vcd_input_buffer.time_stamp = ts;
vcd_input_buffer.offset = 0;
rc = vcd_encode_frame(client_ctx->vcd_handle,
&vcd_input_buffer);
if (rc)
WFD_MSG_ERR("encode frame failed\n");
return rc;
}
static long venc_alloc_recon_buffers(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct vcd_property_hdr vcd_property_hdr;
struct vcd_property_buffer_size control;
struct vcd_property_enc_recon_buffer *ctrl = NULL;
unsigned long phy_addr;
int i = 0;
int flags = 0;
u32 len;
control.width = inst->width;
control.height = inst->height;
vcd_property_hdr.prop_id = VCD_I_GET_RECON_BUFFER_SIZE;
vcd_property_hdr.sz = sizeof(struct vcd_property_buffer_size);
rc = vcd_get_property(client_ctx->vcd_handle,
&vcd_property_hdr, &control);
if (rc) {
WFD_MSG_ERR("Failed to get recon buf size\n");
goto err;
}
flags = ION_HEAP(ION_CP_MM_HEAP_ID);
flags |= inst->secure ? ION_SECURE : ION_HEAP(ION_IOMMU_HEAP_ID);
if (vcd_get_ion_status()) {
for (i = 0; i < 4; ++i) {
ctrl = &client_ctx->recon_buffer[i];
ctrl->buffer_size = control.size;
ctrl->pmem_fd = 0;
ctrl->offset = 0;
ctrl->user_virtual_addr = (void *)i;
client_ctx->recon_buffer_ion_handle[i]
= ion_alloc(client_ctx->user_ion_client,
control.size, SZ_8K, flags);
ctrl->kernel_virtual_addr = ion_map_kernel(
client_ctx->user_ion_client,
client_ctx->recon_buffer_ion_handle[i], 0);
rc = ion_map_iommu(client_ctx->user_ion_client,
client_ctx->recon_buffer_ion_handle[i],
VIDEO_DOMAIN, VIDEO_MAIN_POOL, SZ_4K,
0, &phy_addr, (unsigned long *)&len, 0, 0);
if (rc) {
WFD_MSG_ERR("Failed to allo recon buffers\n");
break;
}
ctrl->physical_addr = (u8 *) phy_addr;
ctrl->dev_addr = ctrl->physical_addr;
vcd_property_hdr.prop_id = VCD_I_RECON_BUFFERS;
vcd_property_hdr.sz =
sizeof(struct vcd_property_enc_recon_buffer);
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, ctrl);
if (rc) {
WFD_MSG_ERR("Failed to set recon buffers\n");
break;
}
}
} else {
WFD_MSG_ERR("PMEM not suported\n");
return -ENOMEM;
}
err:
return rc;
}
static long venc_free_output_buffer(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct mem_region *mregion = arg;
unsigned long kernel_vaddr, user_vaddr;
if (!client_ctx || !mregion) {
WFD_MSG_ERR("Invalid input\n");
return -EINVAL;
}
user_vaddr = mregion->cookie;
rc = vidc_delete_addr_table(client_ctx, BUFFER_TYPE_OUTPUT,
user_vaddr,
&kernel_vaddr);
if (!rc) {
WFD_MSG_ERR("Failed to delete buf from address table\n");
return -EINVAL;
}
return vcd_free_buffer(client_ctx->vcd_handle, VCD_BUFFER_OUTPUT,
(u8 *)kernel_vaddr);
}
static long venc_flush_buffers(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
if (!client_ctx) {
WFD_MSG_ERR("Invalid input\n");
return -EINVAL;
}
rc = vcd_flush(client_ctx->vcd_handle, VCD_FLUSH_INPUT);
if (rc) {
WFD_MSG_ERR("Failed to flush input buffers\n");
rc = -EIO;
goto flush_failed;
}
wait_for_completion(&client_ctx->event);
if (client_ctx->event_status) {
WFD_MSG_ERR("callback for vcd_flush input returned error: %u",
client_ctx->event_status);
rc = -EIO;
goto flush_failed;
}
rc = vcd_flush(client_ctx->vcd_handle, VCD_FLUSH_OUTPUT);
if (rc) {
WFD_MSG_ERR("Failed to flush output buffers\n");
rc = -EIO;
goto flush_failed;
}
wait_for_completion(&client_ctx->event);
if (client_ctx->event_status) {
WFD_MSG_ERR("callback for vcd_flush output returned error: %u",
client_ctx->event_status);
rc = -EIO;
goto flush_failed;
}
flush_failed:
return rc;
}
static long venc_free_input_buffer(struct v4l2_subdev *sd, void *arg)
{
int del_rc = 0, free_rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct mem_region *mregion = arg;
unsigned long vidc_kvaddr;
if (!client_ctx || !mregion) {
WFD_MSG_ERR("Invalid input\n");
return -EINVAL;
}
del_rc = vidc_delete_addr_table(client_ctx, BUFFER_TYPE_INPUT,
(unsigned long)mregion->kvaddr,
&vidc_kvaddr);
if (del_rc == (u32)false) {
WFD_MSG_ERR("Failed to delete buf from address table\n");
del_rc = -ENOKEY;
} else if ((u8 *)vidc_kvaddr != mregion->kvaddr) {
WFD_MSG_ERR("Failed to find expected buffer\n");
del_rc = -EINVAL;
} else
del_rc = 0;
free_rc = vcd_free_buffer(client_ctx->vcd_handle, VCD_BUFFER_INPUT,
(u8 *)vidc_kvaddr);
if (free_rc) {
WFD_MSG_ERR("Failed to free buffer from encoder\n");
free_rc = -EINVAL;
}
return del_rc ? del_rc : free_rc;
}
static long venc_free_recon_buffers(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct video_client_ctx *client_ctx = &inst->venc_client;
struct vcd_property_hdr vcd_property_hdr;
int i;
if (vcd_get_ion_status()) {
for (i = 0; i < 4; i++) {
vcd_property_hdr.prop_id = VCD_I_FREE_RECON_BUFFERS;
vcd_property_hdr.sz =
sizeof(struct vcd_property_buffer_size);
rc = vcd_set_property(client_ctx->vcd_handle,
&vcd_property_hdr, &client_ctx->recon_buffer[i]);
if (rc)
WFD_MSG_ERR("Failed to free recon buffer\n");
if (client_ctx->recon_buffer_ion_handle[i]) {
ion_unmap_iommu(client_ctx->user_ion_client,
client_ctx->recon_buffer_ion_handle[i],
VIDEO_DOMAIN, VIDEO_MAIN_POOL);
ion_unmap_kernel(client_ctx->user_ion_client,
client_ctx->recon_buffer_ion_handle[i]);
ion_free(client_ctx->user_ion_client,
client_ctx->recon_buffer_ion_handle[i]);
client_ctx->recon_buffer_ion_handle[i] = NULL;
}
}
}
return rc;
}
static long venc_set_property(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct v4l2_control *ctrl = arg;
struct video_client_ctx *client_ctx = &inst->venc_client;
switch (ctrl->id) {
case V4L2_CID_MPEG_VIDEO_BITRATE:
rc = venc_set_bitrate(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
rc = venc_set_bitrate_mode(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_I_PERIOD:
rc = venc_set_h264_intra_period(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_LEVEL:
rc = venc_set_codec_level(client_ctx, ctrl->id, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_PROFILE:
rc = venc_set_codec_profile(client_ctx, ctrl->id, ctrl->value);
break;
case V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE:
rc = venc_request_frame(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP:
rc = venc_set_qp_value(client_ctx, ctrl->id, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H263_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H263_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
rc = venc_set_qp_range(client_ctx, ctrl->id, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
rc = venc_set_header_mode(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
rc = venc_set_multislicing_mode(client_ctx, ctrl->id,
ctrl->value);
break;
case V4L2_CID_MPEG_QCOM_SET_PERF_LEVEL:
rc = venc_set_max_perf_level(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDC_VIDEO_H264_AU_DELIMITER:
rc = venc_set_avc_delimiter(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO:
rc = venc_set_vui_timing_info(client_ctx, inst, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE:
rc = venc_set_entropy_mode(client_ctx, ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB:
rc = venc_set_cyclic_intra_refresh_mb(client_ctx, ctrl->value);
break;
default:
WFD_MSG_ERR("Set property not suported: %d\n", ctrl->id);
rc = -ENOTSUPP;
break;
}
return rc;
}
static long venc_get_property(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct venc_inst *inst = sd->dev_priv;
struct v4l2_control *ctrl = arg;
struct video_client_ctx *client_ctx = &inst->venc_client;
switch (ctrl->id) {
case V4L2_CID_MPEG_VIDEO_BITRATE:
rc = venc_get_bitrate(client_ctx, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
rc = venc_get_bitrate_mode(client_ctx, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_LEVEL:
rc = venc_get_codec_level(client_ctx, ctrl->id, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_PROFILE:
rc = venc_get_codec_profile(client_ctx, ctrl->id, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_I_PERIOD:
rc = venc_get_h264_intra_period(client_ctx, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP:
rc = venc_get_qp_value(client_ctx, ctrl->id, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP:
case V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H263_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H263_MAX_QP:
case V4L2_CID_MPEG_VIDEO_H264_MIN_QP:
case V4L2_CID_MPEG_VIDEO_H264_MAX_QP:
rc = venc_get_qp_range(client_ctx, ctrl->id, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_HEADER_MODE:
rc = venc_get_header_mode(client_ctx, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES:
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB:
case V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE:
rc = venc_get_multislicing_mode(client_ctx, ctrl->id,
&ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE:
rc = venc_get_entropy_mode(client_ctx, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB:
rc = venc_get_cyclic_intra_refresh_mb(client_ctx, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDC_VIDEO_H264_AU_DELIMITER:
rc = venc_get_avc_delimiter(client_ctx, &ctrl->value);
break;
case V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO:
rc = venc_get_vui_timing_info(client_ctx, &ctrl->value);
break;
default:
WFD_MSG_ERR("Get property not suported: %d\n", ctrl->id);
rc = -ENOTSUPP;
break;
}
return rc;
}
long venc_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
long rc = 0;
switch (cmd) {
case OPEN:
rc = venc_open(sd, arg);
break;
case CLOSE:
rc = venc_close(sd, arg);
break;
case ENCODE_START:
rc = venc_start(sd);
break;
case ENCODE_FRAME:
venc_encode_frame(sd, arg);
break;
case ENCODE_STOP:
rc = venc_stop(sd);
break;
case SET_PROP:
rc = venc_set_property(sd, arg);
break;
case GET_PROP:
rc = venc_get_property(sd, arg);
break;
case GET_BUFFER_REQ:
rc = venc_get_buffer_req(sd, arg);
break;
case SET_BUFFER_REQ:
rc = venc_set_buffer_req(sd, arg);
break;
case FREE_BUFFER:
break;
case FILL_OUTPUT_BUFFER:
rc = venc_fill_outbuf(sd, arg);
break;
case SET_FORMAT:
rc = venc_set_format(sd, arg);
break;
case SET_FRAMERATE:
rc = venc_set_framerate(sd, arg);
break;
case SET_INPUT_BUFFER:
rc = venc_set_input_buffer(sd, arg);
break;
case SET_OUTPUT_BUFFER:
rc = venc_set_output_buffer(sd, arg);
break;
case ALLOC_RECON_BUFFERS:
rc = venc_alloc_recon_buffers(sd, arg);
break;
case FREE_OUTPUT_BUFFER:
rc = venc_free_output_buffer(sd, arg);
break;
case FREE_INPUT_BUFFER:
rc = venc_free_input_buffer(sd, arg);
break;
case FREE_RECON_BUFFERS:
rc = venc_free_recon_buffers(sd, arg);
break;
case ENCODE_FLUSH:
rc = venc_flush_buffers(sd, arg);
break;
case SET_FRAMERATE_MODE:
rc = venc_set_framerate_mode(sd, arg);
break;
default:
rc = -1;
break;
}
return rc;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.