repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
speedbot/android_kernel_htc_golfu | drivers/net/mlx4/profile.c | 3097 | 7710 | /*
* Copyright (c) 2004, 2005 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
* Copyright (c) 2006, 2007 Cisco Systems, 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/slab.h>
#include "mlx4.h"
#include "fw.h"
enum {
MLX4_RES_QP,
MLX4_RES_RDMARC,
MLX4_RES_ALTC,
MLX4_RES_AUXC,
MLX4_RES_SRQ,
MLX4_RES_CQ,
MLX4_RES_EQ,
MLX4_RES_DMPT,
MLX4_RES_CMPT,
MLX4_RES_MTT,
MLX4_RES_MCG,
MLX4_RES_NUM
};
static const char *res_name[] = {
[MLX4_RES_QP] = "QP",
[MLX4_RES_RDMARC] = "RDMARC",
[MLX4_RES_ALTC] = "ALTC",
[MLX4_RES_AUXC] = "AUXC",
[MLX4_RES_SRQ] = "SRQ",
[MLX4_RES_CQ] = "CQ",
[MLX4_RES_EQ] = "EQ",
[MLX4_RES_DMPT] = "DMPT",
[MLX4_RES_CMPT] = "CMPT",
[MLX4_RES_MTT] = "MTT",
[MLX4_RES_MCG] = "MCG",
};
u64 mlx4_make_profile(struct mlx4_dev *dev,
struct mlx4_profile *request,
struct mlx4_dev_cap *dev_cap,
struct mlx4_init_hca_param *init_hca)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource {
u64 size;
u64 start;
int type;
int num;
int log_num;
};
u64 total_size = 0;
struct mlx4_resource *profile;
struct mlx4_resource tmp;
int i, j;
profile = kcalloc(MLX4_RES_NUM, sizeof(*profile), GFP_KERNEL);
if (!profile)
return -ENOMEM;
profile[MLX4_RES_QP].size = dev_cap->qpc_entry_sz;
profile[MLX4_RES_RDMARC].size = dev_cap->rdmarc_entry_sz;
profile[MLX4_RES_ALTC].size = dev_cap->altc_entry_sz;
profile[MLX4_RES_AUXC].size = dev_cap->aux_entry_sz;
profile[MLX4_RES_SRQ].size = dev_cap->srq_entry_sz;
profile[MLX4_RES_CQ].size = dev_cap->cqc_entry_sz;
profile[MLX4_RES_EQ].size = dev_cap->eqc_entry_sz;
profile[MLX4_RES_DMPT].size = dev_cap->dmpt_entry_sz;
profile[MLX4_RES_CMPT].size = dev_cap->cmpt_entry_sz;
profile[MLX4_RES_MTT].size = dev->caps.mtts_per_seg * dev_cap->mtt_entry_sz;
profile[MLX4_RES_MCG].size = MLX4_MGM_ENTRY_SIZE;
profile[MLX4_RES_QP].num = request->num_qp;
profile[MLX4_RES_RDMARC].num = request->num_qp * request->rdmarc_per_qp;
profile[MLX4_RES_ALTC].num = request->num_qp;
profile[MLX4_RES_AUXC].num = request->num_qp;
profile[MLX4_RES_SRQ].num = request->num_srq;
profile[MLX4_RES_CQ].num = request->num_cq;
profile[MLX4_RES_EQ].num = min_t(unsigned, dev_cap->max_eqs, MAX_MSIX);
profile[MLX4_RES_DMPT].num = request->num_mpt;
profile[MLX4_RES_CMPT].num = MLX4_NUM_CMPTS;
profile[MLX4_RES_MTT].num = request->num_mtt;
profile[MLX4_RES_MCG].num = request->num_mcg;
for (i = 0; i < MLX4_RES_NUM; ++i) {
profile[i].type = i;
profile[i].num = roundup_pow_of_two(profile[i].num);
profile[i].log_num = ilog2(profile[i].num);
profile[i].size *= profile[i].num;
profile[i].size = max(profile[i].size, (u64) PAGE_SIZE);
}
/*
* Sort the resources in decreasing order of size. Since they
* all have sizes that are powers of 2, we'll be able to keep
* resources aligned to their size and pack them without gaps
* using the sorted order.
*/
for (i = MLX4_RES_NUM; i > 0; --i)
for (j = 1; j < i; ++j) {
if (profile[j].size > profile[j - 1].size) {
tmp = profile[j];
profile[j] = profile[j - 1];
profile[j - 1] = tmp;
}
}
for (i = 0; i < MLX4_RES_NUM; ++i) {
if (profile[i].size) {
profile[i].start = total_size;
total_size += profile[i].size;
}
if (total_size > dev_cap->max_icm_sz) {
mlx4_err(dev, "Profile requires 0x%llx bytes; "
"won't fit in 0x%llx bytes of context memory.\n",
(unsigned long long) total_size,
(unsigned long long) dev_cap->max_icm_sz);
kfree(profile);
return -ENOMEM;
}
if (profile[i].size)
mlx4_dbg(dev, " profile[%2d] (%6s): 2^%02d entries @ 0x%10llx, "
"size 0x%10llx\n",
i, res_name[profile[i].type], profile[i].log_num,
(unsigned long long) profile[i].start,
(unsigned long long) profile[i].size);
}
mlx4_dbg(dev, "HCA context memory: reserving %d KB\n",
(int) (total_size >> 10));
for (i = 0; i < MLX4_RES_NUM; ++i) {
switch (profile[i].type) {
case MLX4_RES_QP:
dev->caps.num_qps = profile[i].num;
init_hca->qpc_base = profile[i].start;
init_hca->log_num_qps = profile[i].log_num;
break;
case MLX4_RES_RDMARC:
for (priv->qp_table.rdmarc_shift = 0;
request->num_qp << priv->qp_table.rdmarc_shift < profile[i].num;
++priv->qp_table.rdmarc_shift)
; /* nothing */
dev->caps.max_qp_dest_rdma = 1 << priv->qp_table.rdmarc_shift;
priv->qp_table.rdmarc_base = (u32) profile[i].start;
init_hca->rdmarc_base = profile[i].start;
init_hca->log_rd_per_qp = priv->qp_table.rdmarc_shift;
break;
case MLX4_RES_ALTC:
init_hca->altc_base = profile[i].start;
break;
case MLX4_RES_AUXC:
init_hca->auxc_base = profile[i].start;
break;
case MLX4_RES_SRQ:
dev->caps.num_srqs = profile[i].num;
init_hca->srqc_base = profile[i].start;
init_hca->log_num_srqs = profile[i].log_num;
break;
case MLX4_RES_CQ:
dev->caps.num_cqs = profile[i].num;
init_hca->cqc_base = profile[i].start;
init_hca->log_num_cqs = profile[i].log_num;
break;
case MLX4_RES_EQ:
dev->caps.num_eqs = profile[i].num;
init_hca->eqc_base = profile[i].start;
init_hca->log_num_eqs = profile[i].log_num;
break;
case MLX4_RES_DMPT:
dev->caps.num_mpts = profile[i].num;
priv->mr_table.mpt_base = profile[i].start;
init_hca->dmpt_base = profile[i].start;
init_hca->log_mpt_sz = profile[i].log_num;
break;
case MLX4_RES_CMPT:
init_hca->cmpt_base = profile[i].start;
break;
case MLX4_RES_MTT:
dev->caps.num_mtt_segs = profile[i].num;
priv->mr_table.mtt_base = profile[i].start;
init_hca->mtt_base = profile[i].start;
break;
case MLX4_RES_MCG:
dev->caps.num_mgms = profile[i].num >> 1;
dev->caps.num_amgms = profile[i].num >> 1;
init_hca->mc_base = profile[i].start;
init_hca->log_mc_entry_sz = ilog2(MLX4_MGM_ENTRY_SIZE);
init_hca->log_mc_table_sz = profile[i].log_num;
init_hca->log_mc_hash_sz = profile[i].log_num - 1;
break;
default:
break;
}
}
/*
* PDs don't take any HCA memory, but we assign them as part
* of the HCA profile anyway.
*/
dev->caps.num_pds = MLX4_NUM_PDS;
kfree(profile);
return total_size;
}
| gpl-2.0 |
crysehillmes/android_kernel_samsung_klimtlte | arch/arm/mach-omap2/board-omap4panda.c | 4633 | 16061 | /*
* Board support file for OMAP4430 based PandaBoard.
*
* Copyright (C) 2010 Texas Instruments
*
* Author: David Anders <x0132446@ti.com>
*
* Based on mach-omap2/board-4430sdp.c
*
* Author: Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* Based on mach-omap2/board-3430sdp.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/init.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/leds.h>
#include <linux/gpio.h>
#include <linux/usb/otg.h>
#include <linux/i2c/twl.h>
#include <linux/mfd/twl6040.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/wl12xx.h>
#include <linux/platform_data/omap-abe-twl6040.h>
#include <mach/hardware.h>
#include <asm/hardware/gic.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <video/omapdss.h>
#include <plat/board.h>
#include "common.h"
#include <plat/usb.h>
#include <plat/mmc.h>
#include <video/omap-panel-dvi.h>
#include "hsmmc.h"
#include "control.h"
#include "mux.h"
#include "common-board-devices.h"
#define GPIO_HUB_POWER 1
#define GPIO_HUB_NRESET 62
#define GPIO_WIFI_PMENA 43
#define GPIO_WIFI_IRQ 53
#define HDMI_GPIO_CT_CP_HPD 60 /* HPD mode enable/disable */
#define HDMI_GPIO_LS_OE 41 /* Level shifter for HDMI */
#define HDMI_GPIO_HPD 63 /* Hotplug detect */
/* wl127x BT, FM, GPS connectivity chip */
static int wl1271_gpios[] = {46, -1, -1};
static struct platform_device wl1271_device = {
.name = "kim",
.id = -1,
.dev = {
.platform_data = &wl1271_gpios,
},
};
static struct gpio_led gpio_leds[] = {
{
.name = "pandaboard::status1",
.default_trigger = "heartbeat",
.gpio = 7,
},
{
.name = "pandaboard::status2",
.default_trigger = "mmc0",
.gpio = 8,
},
};
static struct gpio_led_platform_data gpio_led_info = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
static struct platform_device leds_gpio = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &gpio_led_info,
},
};
static struct omap_abe_twl6040_data panda_abe_audio_data = {
/* Audio out */
.has_hs = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* HandsFree through expasion connector */
.has_hf = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* PandaBoard: FM TX, PandaBoardES: can be connected to audio out */
.has_aux = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* PandaBoard: FM RX, PandaBoardES: audio in */
.has_afm = ABE_TWL6040_LEFT | ABE_TWL6040_RIGHT,
/* No jack detection. */
.jack_detection = 0,
/* MCLK input is 38.4MHz */
.mclk_freq = 38400000,
};
static struct platform_device panda_abe_audio = {
.name = "omap-abe-twl6040",
.id = -1,
.dev = {
.platform_data = &panda_abe_audio_data,
},
};
static struct platform_device btwilink_device = {
.name = "btwilink",
.id = -1,
};
static struct platform_device *panda_devices[] __initdata = {
&leds_gpio,
&wl1271_device,
&panda_abe_audio,
&btwilink_device,
};
static const struct usbhs_omap_board_data usbhs_bdata __initconst = {
.port_mode[0] = OMAP_EHCI_PORT_MODE_PHY,
.port_mode[1] = OMAP_USBHS_PORT_MODE_UNUSED,
.port_mode[2] = OMAP_USBHS_PORT_MODE_UNUSED,
.phy_reset = false,
.reset_gpio_port[0] = -EINVAL,
.reset_gpio_port[1] = -EINVAL,
.reset_gpio_port[2] = -EINVAL
};
static struct gpio panda_ehci_gpios[] __initdata = {
{ GPIO_HUB_POWER, GPIOF_OUT_INIT_LOW, "hub_power" },
{ GPIO_HUB_NRESET, GPIOF_OUT_INIT_LOW, "hub_nreset" },
};
static void __init omap4_ehci_init(void)
{
int ret;
struct clk *phy_ref_clk;
/* FREF_CLK3 provides the 19.2 MHz reference clock to the PHY */
phy_ref_clk = clk_get(NULL, "auxclk3_ck");
if (IS_ERR(phy_ref_clk)) {
pr_err("Cannot request auxclk3\n");
return;
}
clk_set_rate(phy_ref_clk, 19200000);
clk_enable(phy_ref_clk);
/* disable the power to the usb hub prior to init and reset phy+hub */
ret = gpio_request_array(panda_ehci_gpios,
ARRAY_SIZE(panda_ehci_gpios));
if (ret) {
pr_err("Unable to initialize EHCI power/reset\n");
return;
}
gpio_export(GPIO_HUB_POWER, 0);
gpio_export(GPIO_HUB_NRESET, 0);
gpio_set_value(GPIO_HUB_NRESET, 1);
usbhs_init(&usbhs_bdata);
/* enable power to hub */
gpio_set_value(GPIO_HUB_POWER, 1);
}
static struct omap_musb_board_data musb_board_data = {
.interface_type = MUSB_INTERFACE_UTMI,
.mode = MUSB_OTG,
.power = 100,
};
static struct omap2_hsmmc_info mmc[] = {
{
.mmc = 1,
.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA,
.gpio_wp = -EINVAL,
.gpio_cd = -EINVAL,
},
{
.name = "wl1271",
.mmc = 5,
.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_POWER_OFF_CARD,
.gpio_wp = -EINVAL,
.gpio_cd = -EINVAL,
.ocr_mask = MMC_VDD_165_195,
.nonremovable = true,
},
{} /* Terminator */
};
static struct regulator_consumer_supply omap4_panda_vmmc5_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.4"),
};
static struct regulator_init_data panda_vmmc5 = {
.constraints = {
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_panda_vmmc5_supply),
.consumer_supplies = omap4_panda_vmmc5_supply,
};
static struct fixed_voltage_config panda_vwlan = {
.supply_name = "vwl1271",
.microvolts = 1800000, /* 1.8V */
.gpio = GPIO_WIFI_PMENA,
.startup_delay = 70000, /* 70msec */
.enable_high = 1,
.enabled_at_boot = 0,
.init_data = &panda_vmmc5,
};
static struct platform_device omap_vwlan_device = {
.name = "reg-fixed-voltage",
.id = 1,
.dev = {
.platform_data = &panda_vwlan,
},
};
struct wl12xx_platform_data omap_panda_wlan_data __initdata = {
/* PANDA ref clock is 38.4 MHz */
.board_ref_clock = 2,
};
static int omap4_twl6030_hsmmc_late_init(struct device *dev)
{
int irq = 0;
struct platform_device *pdev = container_of(dev,
struct platform_device, dev);
struct omap_mmc_platform_data *pdata = dev->platform_data;
if (!pdata) {
dev_err(dev, "%s: NULL platform data\n", __func__);
return -EINVAL;
}
/* Setting MMC1 Card detect Irq */
if (pdev->id == 0) {
irq = twl6030_mmc_card_detect_config();
if (irq < 0) {
dev_err(dev, "%s: Error card detect config(%d)\n",
__func__, irq);
return irq;
}
pdata->slots[0].card_detect = twl6030_mmc_card_detect;
}
return 0;
}
static __init void omap4_twl6030_hsmmc_set_late_init(struct device *dev)
{
struct omap_mmc_platform_data *pdata;
/* dev can be null if CONFIG_MMC_OMAP_HS is not set */
if (!dev) {
pr_err("Failed omap4_twl6030_hsmmc_set_late_init\n");
return;
}
pdata = dev->platform_data;
pdata->init = omap4_twl6030_hsmmc_late_init;
}
static int __init omap4_twl6030_hsmmc_init(struct omap2_hsmmc_info *controllers)
{
struct omap2_hsmmc_info *c;
omap_hsmmc_init(controllers);
for (c = controllers; c->mmc; c++)
omap4_twl6030_hsmmc_set_late_init(&c->pdev->dev);
return 0;
}
static struct twl6040_codec_data twl6040_codec = {
/* single-step ramp for headset and handsfree */
.hs_left_step = 0x0f,
.hs_right_step = 0x0f,
.hf_left_step = 0x1d,
.hf_right_step = 0x1d,
};
static struct twl6040_platform_data twl6040_data = {
.codec = &twl6040_codec,
.audpwron_gpio = 127,
.irq_base = TWL6040_CODEC_IRQ_BASE,
};
/* Panda board uses the common PMIC configuration */
static struct twl4030_platform_data omap4_panda_twldata;
/*
* Display monitor features are burnt in their EEPROM as EDID data. The EEPROM
* is connected as I2C slave device, and can be accessed at address 0x50
*/
static struct i2c_board_info __initdata panda_i2c_eeprom[] = {
{
I2C_BOARD_INFO("eeprom", 0x50),
},
};
static int __init omap4_panda_i2c_init(void)
{
omap4_pmic_get_config(&omap4_panda_twldata, TWL_COMMON_PDATA_USB,
TWL_COMMON_REGULATOR_VDAC |
TWL_COMMON_REGULATOR_VAUX2 |
TWL_COMMON_REGULATOR_VAUX3 |
TWL_COMMON_REGULATOR_VMMC |
TWL_COMMON_REGULATOR_VPP |
TWL_COMMON_REGULATOR_VANA |
TWL_COMMON_REGULATOR_VCXIO |
TWL_COMMON_REGULATOR_VUSB |
TWL_COMMON_REGULATOR_CLK32KG);
omap4_pmic_init("twl6030", &omap4_panda_twldata,
&twl6040_data, OMAP44XX_IRQ_SYS_2N);
omap_register_i2c_bus(2, 400, NULL, 0);
/*
* Bus 3 is attached to the DVI port where devices like the pico DLP
* projector don't work reliably with 400kHz
*/
omap_register_i2c_bus(3, 100, panda_i2c_eeprom,
ARRAY_SIZE(panda_i2c_eeprom));
omap_register_i2c_bus(4, 400, NULL, 0);
return 0;
}
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
/* WLAN IRQ - GPIO 53 */
OMAP4_MUX(GPMC_NCS3, OMAP_MUX_MODE3 | OMAP_PIN_INPUT),
/* WLAN POWER ENABLE - GPIO 43 */
OMAP4_MUX(GPMC_A19, OMAP_MUX_MODE3 | OMAP_PIN_OUTPUT),
/* WLAN SDIO: MMC5 CMD */
OMAP4_MUX(SDMMC5_CMD, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
/* WLAN SDIO: MMC5 CLK */
OMAP4_MUX(SDMMC5_CLK, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
/* WLAN SDIO: MMC5 DAT[0-3] */
OMAP4_MUX(SDMMC5_DAT0, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
OMAP4_MUX(SDMMC5_DAT1, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
OMAP4_MUX(SDMMC5_DAT2, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
OMAP4_MUX(SDMMC5_DAT3, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP),
/* gpio 0 - TFP410 PD */
OMAP4_MUX(KPD_COL1, OMAP_PIN_OUTPUT | OMAP_MUX_MODE3),
/* dispc2_data23 */
OMAP4_MUX(USBB2_ULPITLL_STP, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data22 */
OMAP4_MUX(USBB2_ULPITLL_DIR, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data21 */
OMAP4_MUX(USBB2_ULPITLL_NXT, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data20 */
OMAP4_MUX(USBB2_ULPITLL_DAT0, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data19 */
OMAP4_MUX(USBB2_ULPITLL_DAT1, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data18 */
OMAP4_MUX(USBB2_ULPITLL_DAT2, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data15 */
OMAP4_MUX(USBB2_ULPITLL_DAT3, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data14 */
OMAP4_MUX(USBB2_ULPITLL_DAT4, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data13 */
OMAP4_MUX(USBB2_ULPITLL_DAT5, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data12 */
OMAP4_MUX(USBB2_ULPITLL_DAT6, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data11 */
OMAP4_MUX(USBB2_ULPITLL_DAT7, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data10 */
OMAP4_MUX(DPM_EMU3, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data9 */
OMAP4_MUX(DPM_EMU4, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data16 */
OMAP4_MUX(DPM_EMU5, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data17 */
OMAP4_MUX(DPM_EMU6, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_hsync */
OMAP4_MUX(DPM_EMU7, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_pclk */
OMAP4_MUX(DPM_EMU8, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_vsync */
OMAP4_MUX(DPM_EMU9, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_de */
OMAP4_MUX(DPM_EMU10, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data8 */
OMAP4_MUX(DPM_EMU11, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data7 */
OMAP4_MUX(DPM_EMU12, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data6 */
OMAP4_MUX(DPM_EMU13, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data5 */
OMAP4_MUX(DPM_EMU14, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data4 */
OMAP4_MUX(DPM_EMU15, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data3 */
OMAP4_MUX(DPM_EMU16, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data2 */
OMAP4_MUX(DPM_EMU17, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data1 */
OMAP4_MUX(DPM_EMU18, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
/* dispc2_data0 */
OMAP4_MUX(DPM_EMU19, OMAP_PIN_OUTPUT | OMAP_MUX_MODE5),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#else
#define board_mux NULL
#endif
/* Display DVI */
#define PANDA_DVI_TFP410_POWER_DOWN_GPIO 0
static int omap4_panda_enable_dvi(struct omap_dss_device *dssdev)
{
gpio_set_value(dssdev->reset_gpio, 1);
return 0;
}
static void omap4_panda_disable_dvi(struct omap_dss_device *dssdev)
{
gpio_set_value(dssdev->reset_gpio, 0);
}
/* Using generic display panel */
static struct panel_dvi_platform_data omap4_dvi_panel = {
.platform_enable = omap4_panda_enable_dvi,
.platform_disable = omap4_panda_disable_dvi,
.i2c_bus_num = 3,
};
struct omap_dss_device omap4_panda_dvi_device = {
.type = OMAP_DISPLAY_TYPE_DPI,
.name = "dvi",
.driver_name = "dvi",
.data = &omap4_dvi_panel,
.phy.dpi.data_lines = 24,
.reset_gpio = PANDA_DVI_TFP410_POWER_DOWN_GPIO,
.channel = OMAP_DSS_CHANNEL_LCD2,
};
int __init omap4_panda_dvi_init(void)
{
int r;
/* Requesting TFP410 DVI GPIO and disabling it, at bootup */
r = gpio_request_one(omap4_panda_dvi_device.reset_gpio,
GPIOF_OUT_INIT_LOW, "DVI PD");
if (r)
pr_err("Failed to get DVI powerdown GPIO\n");
return r;
}
static struct gpio panda_hdmi_gpios[] = {
{ HDMI_GPIO_CT_CP_HPD, GPIOF_OUT_INIT_HIGH, "hdmi_gpio_ct_cp_hpd" },
{ HDMI_GPIO_LS_OE, GPIOF_OUT_INIT_HIGH, "hdmi_gpio_ls_oe" },
{ HDMI_GPIO_HPD, GPIOF_DIR_IN, "hdmi_gpio_hpd" },
};
static int omap4_panda_panel_enable_hdmi(struct omap_dss_device *dssdev)
{
int status;
status = gpio_request_array(panda_hdmi_gpios,
ARRAY_SIZE(panda_hdmi_gpios));
if (status)
pr_err("Cannot request HDMI GPIOs\n");
return status;
}
static void omap4_panda_panel_disable_hdmi(struct omap_dss_device *dssdev)
{
gpio_free_array(panda_hdmi_gpios, ARRAY_SIZE(panda_hdmi_gpios));
}
static struct omap_dss_hdmi_data omap4_panda_hdmi_data = {
.hpd_gpio = HDMI_GPIO_HPD,
};
static struct omap_dss_device omap4_panda_hdmi_device = {
.name = "hdmi",
.driver_name = "hdmi_panel",
.type = OMAP_DISPLAY_TYPE_HDMI,
.platform_enable = omap4_panda_panel_enable_hdmi,
.platform_disable = omap4_panda_panel_disable_hdmi,
.channel = OMAP_DSS_CHANNEL_DIGIT,
.data = &omap4_panda_hdmi_data,
};
static struct omap_dss_device *omap4_panda_dss_devices[] = {
&omap4_panda_dvi_device,
&omap4_panda_hdmi_device,
};
static struct omap_dss_board_info omap4_panda_dss_data = {
.num_devices = ARRAY_SIZE(omap4_panda_dss_devices),
.devices = omap4_panda_dss_devices,
.default_device = &omap4_panda_dvi_device,
};
void __init omap4_panda_display_init(void)
{
int r;
r = omap4_panda_dvi_init();
if (r)
pr_err("error initializing panda DVI\n");
omap_display_init(&omap4_panda_dss_data);
/*
* OMAP4460SDP/Blaze and OMAP4430 ES2.3 SDP/Blaze boards and
* later have external pull up on the HDMI I2C lines
*/
if (cpu_is_omap446x() || omap_rev() > OMAP4430_REV_ES2_2)
omap_hdmi_init(OMAP_HDMI_SDA_SCL_EXTERNAL_PULLUP);
else
omap_hdmi_init(0);
omap_mux_init_gpio(HDMI_GPIO_LS_OE, OMAP_PIN_OUTPUT);
omap_mux_init_gpio(HDMI_GPIO_CT_CP_HPD, OMAP_PIN_OUTPUT);
omap_mux_init_gpio(HDMI_GPIO_HPD, OMAP_PIN_INPUT_PULLDOWN);
}
static void omap4_panda_init_rev(void)
{
if (cpu_is_omap443x()) {
/* PandaBoard 4430 */
/* ASoC audio configuration */
panda_abe_audio_data.card_name = "PandaBoard";
panda_abe_audio_data.has_hsmic = 1;
} else {
/* PandaBoard ES */
/* ASoC audio configuration */
panda_abe_audio_data.card_name = "PandaBoardES";
}
}
static void __init omap4_panda_init(void)
{
int package = OMAP_PACKAGE_CBS;
int ret;
if (omap_rev() == OMAP4430_REV_ES1_0)
package = OMAP_PACKAGE_CBL;
omap4_mux_init(board_mux, NULL, package);
omap_panda_wlan_data.irq = gpio_to_irq(GPIO_WIFI_IRQ);
ret = wl12xx_set_platform_data(&omap_panda_wlan_data);
if (ret)
pr_err("error setting wl12xx data: %d\n", ret);
omap4_panda_init_rev();
omap4_panda_i2c_init();
platform_add_devices(panda_devices, ARRAY_SIZE(panda_devices));
platform_device_register(&omap_vwlan_device);
omap_serial_init();
omap_sdrc_init(NULL, NULL);
omap4_twl6030_hsmmc_init(mmc);
omap4_ehci_init();
usb_musb_init(&musb_board_data);
omap4_panda_display_init();
}
MACHINE_START(OMAP4_PANDA, "OMAP4 Panda board")
/* Maintainer: David Anders - Texas Instruments Inc */
.atag_offset = 0x100,
.reserve = omap_reserve,
.map_io = omap4_map_io,
.init_early = omap4430_init_early,
.init_irq = gic_init_irq,
.handle_irq = gic_handle_irq,
.init_machine = omap4_panda_init,
.timer = &omap4_timer,
.restart = omap_prcm_restart,
MACHINE_END
| gpl-2.0 |
tweezy23/kernel-msm | drivers/i2c/busses/i2c-ixp2000.c | 4889 | 4165 | /*
* drivers/i2c/busses/i2c-ixp2000.c
*
* I2C adapter for IXP2000 systems using GPIOs for I2C bus
*
* Author: Deepak Saxena <dsaxena@plexity.net>
* Based on IXDP2400 code by: Naeem M. Afzal <naeem.m.afzal@intel.com>
* Made generic by: Jeff Daly <jeffrey.daly@intel.com>
*
* Copyright (c) 2003-2004 MontaVista Software Inc.
*
* 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.
*
* From Jeff Daly:
*
* I2C adapter driver for Intel IXDP2xxx platforms. This should work for any
* IXP2000 platform if it uses the HW GPIO in the same manner. Basically,
* SDA and SCL GPIOs have external pullups. Setting the respective GPIO to
* an input will make the signal a '1' via the pullup. Setting them to
* outputs will pull them down.
*
* The GPIOs are open drain signals and are used as configuration strap inputs
* during power-up so there's generally a buffer on the board that needs to be
* 'enabled' to drive the GPIOs.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/slab.h>
#include <mach/hardware.h> /* Pick up IXP2000-specific bits */
#include <mach/gpio-ixp2000.h>
static inline int ixp2000_scl_pin(void *data)
{
return ((struct ixp2000_i2c_pins*)data)->scl_pin;
}
static inline int ixp2000_sda_pin(void *data)
{
return ((struct ixp2000_i2c_pins*)data)->sda_pin;
}
static void ixp2000_bit_setscl(void *data, int val)
{
int i = 5000;
if (val) {
gpio_line_config(ixp2000_scl_pin(data), GPIO_IN);
while(!gpio_line_get(ixp2000_scl_pin(data)) && i--);
} else {
gpio_line_config(ixp2000_scl_pin(data), GPIO_OUT);
}
}
static void ixp2000_bit_setsda(void *data, int val)
{
if (val) {
gpio_line_config(ixp2000_sda_pin(data), GPIO_IN);
} else {
gpio_line_config(ixp2000_sda_pin(data), GPIO_OUT);
}
}
static int ixp2000_bit_getscl(void *data)
{
return gpio_line_get(ixp2000_scl_pin(data));
}
static int ixp2000_bit_getsda(void *data)
{
return gpio_line_get(ixp2000_sda_pin(data));
}
struct ixp2000_i2c_data {
struct ixp2000_i2c_pins *gpio_pins;
struct i2c_adapter adapter;
struct i2c_algo_bit_data algo_data;
};
static int ixp2000_i2c_remove(struct platform_device *plat_dev)
{
struct ixp2000_i2c_data *drv_data = platform_get_drvdata(plat_dev);
platform_set_drvdata(plat_dev, NULL);
i2c_del_adapter(&drv_data->adapter);
kfree(drv_data);
return 0;
}
static int ixp2000_i2c_probe(struct platform_device *plat_dev)
{
int err;
struct ixp2000_i2c_pins *gpio = plat_dev->dev.platform_data;
struct ixp2000_i2c_data *drv_data =
kzalloc(sizeof(struct ixp2000_i2c_data), GFP_KERNEL);
if (!drv_data)
return -ENOMEM;
drv_data->gpio_pins = gpio;
drv_data->algo_data.data = gpio;
drv_data->algo_data.setsda = ixp2000_bit_setsda;
drv_data->algo_data.setscl = ixp2000_bit_setscl;
drv_data->algo_data.getsda = ixp2000_bit_getsda;
drv_data->algo_data.getscl = ixp2000_bit_getscl;
drv_data->algo_data.udelay = 6;
drv_data->algo_data.timeout = HZ;
strlcpy(drv_data->adapter.name, plat_dev->dev.driver->name,
sizeof(drv_data->adapter.name));
drv_data->adapter.algo_data = &drv_data->algo_data,
drv_data->adapter.dev.parent = &plat_dev->dev;
gpio_line_config(gpio->sda_pin, GPIO_IN);
gpio_line_config(gpio->scl_pin, GPIO_IN);
gpio_line_set(gpio->scl_pin, 0);
gpio_line_set(gpio->sda_pin, 0);
if ((err = i2c_bit_add_bus(&drv_data->adapter)) != 0) {
dev_err(&plat_dev->dev, "Could not install, error %d\n", err);
kfree(drv_data);
return err;
}
platform_set_drvdata(plat_dev, drv_data);
return 0;
}
static struct platform_driver ixp2000_i2c_driver = {
.probe = ixp2000_i2c_probe,
.remove = ixp2000_i2c_remove,
.driver = {
.name = "IXP2000-I2C",
.owner = THIS_MODULE,
},
};
module_platform_driver(ixp2000_i2c_driver);
MODULE_AUTHOR ("Deepak Saxena <dsaxena@plexity.net>");
MODULE_DESCRIPTION("IXP2000 GPIO-based I2C bus driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:IXP2000-I2C");
| gpl-2.0 |
alexandru-g/kernel_htc_m8_gpe | arch/arm/mach-rpc/irq.c | 6425 | 3512 | #include <linux/init.h>
#include <linux/list.h>
#include <linux/io.h>
#include <asm/mach/irq.h>
#include <asm/hardware/iomd.h>
#include <asm/irq.h>
#include <asm/fiq.h>
static void iomd_ack_irq_a(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << d->irq;
val = iomd_readb(IOMD_IRQMASKA);
iomd_writeb(val & ~mask, IOMD_IRQMASKA);
iomd_writeb(mask, IOMD_IRQCLRA);
}
static void iomd_mask_irq_a(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << d->irq;
val = iomd_readb(IOMD_IRQMASKA);
iomd_writeb(val & ~mask, IOMD_IRQMASKA);
}
static void iomd_unmask_irq_a(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << d->irq;
val = iomd_readb(IOMD_IRQMASKA);
iomd_writeb(val | mask, IOMD_IRQMASKA);
}
static struct irq_chip iomd_a_chip = {
.irq_ack = iomd_ack_irq_a,
.irq_mask = iomd_mask_irq_a,
.irq_unmask = iomd_unmask_irq_a,
};
static void iomd_mask_irq_b(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << (d->irq & 7);
val = iomd_readb(IOMD_IRQMASKB);
iomd_writeb(val & ~mask, IOMD_IRQMASKB);
}
static void iomd_unmask_irq_b(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << (d->irq & 7);
val = iomd_readb(IOMD_IRQMASKB);
iomd_writeb(val | mask, IOMD_IRQMASKB);
}
static struct irq_chip iomd_b_chip = {
.irq_ack = iomd_mask_irq_b,
.irq_mask = iomd_mask_irq_b,
.irq_unmask = iomd_unmask_irq_b,
};
static void iomd_mask_irq_dma(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << (d->irq & 7);
val = iomd_readb(IOMD_DMAMASK);
iomd_writeb(val & ~mask, IOMD_DMAMASK);
}
static void iomd_unmask_irq_dma(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << (d->irq & 7);
val = iomd_readb(IOMD_DMAMASK);
iomd_writeb(val | mask, IOMD_DMAMASK);
}
static struct irq_chip iomd_dma_chip = {
.irq_ack = iomd_mask_irq_dma,
.irq_mask = iomd_mask_irq_dma,
.irq_unmask = iomd_unmask_irq_dma,
};
static void iomd_mask_irq_fiq(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << (d->irq & 7);
val = iomd_readb(IOMD_FIQMASK);
iomd_writeb(val & ~mask, IOMD_FIQMASK);
}
static void iomd_unmask_irq_fiq(struct irq_data *d)
{
unsigned int val, mask;
mask = 1 << (d->irq & 7);
val = iomd_readb(IOMD_FIQMASK);
iomd_writeb(val | mask, IOMD_FIQMASK);
}
static struct irq_chip iomd_fiq_chip = {
.irq_ack = iomd_mask_irq_fiq,
.irq_mask = iomd_mask_irq_fiq,
.irq_unmask = iomd_unmask_irq_fiq,
};
extern unsigned char rpc_default_fiq_start, rpc_default_fiq_end;
void __init rpc_init_irq(void)
{
unsigned int irq, flags;
iomd_writeb(0, IOMD_IRQMASKA);
iomd_writeb(0, IOMD_IRQMASKB);
iomd_writeb(0, IOMD_FIQMASK);
iomd_writeb(0, IOMD_DMAMASK);
set_fiq_handler(&rpc_default_fiq_start,
&rpc_default_fiq_end - &rpc_default_fiq_start);
for (irq = 0; irq < NR_IRQS; irq++) {
flags = IRQF_VALID;
if (irq <= 6 || (irq >= 9 && irq <= 15))
flags |= IRQF_PROBE;
if (irq == 21 || (irq >= 16 && irq <= 19) ||
irq == IRQ_KEYBOARDTX)
flags |= IRQF_NOAUTOEN;
switch (irq) {
case 0 ... 7:
irq_set_chip_and_handler(irq, &iomd_a_chip,
handle_level_irq);
set_irq_flags(irq, flags);
break;
case 8 ... 15:
irq_set_chip_and_handler(irq, &iomd_b_chip,
handle_level_irq);
set_irq_flags(irq, flags);
break;
case 16 ... 21:
irq_set_chip_and_handler(irq, &iomd_dma_chip,
handle_level_irq);
set_irq_flags(irq, flags);
break;
case 64 ... 71:
irq_set_chip(irq, &iomd_fiq_chip);
set_irq_flags(irq, IRQF_VALID);
break;
}
}
init_FIQ(FIQ_START);
}
| gpl-2.0 |
emceethemouth/kernel_androidone | arch/powerpc/platforms/pseries/io_event_irq.c | 6681 | 5201 | /*
* Copyright 2010 2011 Mark Nelson and Tseng-Hui (Frank) Lin, IBM Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/of.h>
#include <linux/list.h>
#include <linux/notifier.h>
#include <asm/machdep.h>
#include <asm/rtas.h>
#include <asm/irq.h>
#include <asm/io_event_irq.h>
#include "pseries.h"
/*
* IO event interrupt is a mechanism provided by RTAS to return
* information about hardware error and non-error events. Device
* drivers can register their event handlers to receive events.
* Device drivers are expected to use atomic_notifier_chain_register()
* and atomic_notifier_chain_unregister() to register and unregister
* their event handlers. Since multiple IO event types and scopes
* share an IO event interrupt, the event handlers are called one
* by one until the IO event is claimed by one of the handlers.
* The event handlers are expected to return NOTIFY_OK if the
* event is handled by the event handler or NOTIFY_DONE if the
* event does not belong to the handler.
*
* Usage:
*
* Notifier function:
* #include <asm/io_event_irq.h>
* int event_handler(struct notifier_block *nb, unsigned long val, void *data) {
* p = (struct pseries_io_event_sect_data *) data;
* if (! is_my_event(p->scope, p->event_type)) return NOTIFY_DONE;
* :
* :
* return NOTIFY_OK;
* }
* struct notifier_block event_nb = {
* .notifier_call = event_handler,
* }
*
* Registration:
* atomic_notifier_chain_register(&pseries_ioei_notifier_list, &event_nb);
*
* Unregistration:
* atomic_notifier_chain_unregister(&pseries_ioei_notifier_list, &event_nb);
*/
ATOMIC_NOTIFIER_HEAD(pseries_ioei_notifier_list);
EXPORT_SYMBOL_GPL(pseries_ioei_notifier_list);
static int ioei_check_exception_token;
static char ioei_rtas_buf[RTAS_DATA_BUF_SIZE] __cacheline_aligned;
/**
* Find the data portion of an IO Event section from event log.
* @elog: RTAS error/event log.
*
* Return:
* pointer to a valid IO event section data. NULL if not found.
*/
static struct pseries_io_event * ioei_find_event(struct rtas_error_log *elog)
{
struct pseries_errorlog *sect;
/* We should only ever get called for io-event interrupts, but if
* we do get called for another type then something went wrong so
* make some noise about it.
* RTAS_TYPE_IO only exists in extended event log version 6 or later.
* No need to check event log version.
*/
if (unlikely(elog->type != RTAS_TYPE_IO)) {
printk_once(KERN_WARNING "io_event_irq: Unexpected event type %d",
elog->type);
return NULL;
}
sect = get_pseries_errorlog(elog, PSERIES_ELOG_SECT_ID_IO_EVENT);
if (unlikely(!sect)) {
printk_once(KERN_WARNING "io_event_irq: RTAS extended event "
"log does not contain an IO Event section. "
"Could be a bug in system firmware!\n");
return NULL;
}
return (struct pseries_io_event *) §->data;
}
/*
* PAPR:
* - check-exception returns the first found error or event and clear that
* error or event so it is reported once.
* - Each interrupt returns one event. If a plateform chooses to report
* multiple events through a single interrupt, it must ensure that the
* interrupt remains asserted until check-exception has been used to
* process all out-standing events for that interrupt.
*
* Implementation notes:
* - Events must be processed in the order they are returned. Hence,
* sequential in nature.
* - The owner of an event is determined by combinations of scope,
* event type, and sub-type. There is no easy way to pre-sort clients
* by scope or event type alone. For example, Torrent ISR route change
* event is reported with scope 0x00 (Not Applicatable) rather than
* 0x3B (Torrent-hub). It is better to let the clients to identify
* who owns the the event.
*/
static irqreturn_t ioei_interrupt(int irq, void *dev_id)
{
struct pseries_io_event *event;
int rtas_rc;
for (;;) {
rtas_rc = rtas_call(ioei_check_exception_token, 6, 1, NULL,
RTAS_VECTOR_EXTERNAL_INTERRUPT,
virq_to_hw(irq),
RTAS_IO_EVENTS, 1 /* Time Critical */,
__pa(ioei_rtas_buf),
RTAS_DATA_BUF_SIZE);
if (rtas_rc != 0)
break;
event = ioei_find_event((struct rtas_error_log *)ioei_rtas_buf);
if (!event)
continue;
atomic_notifier_call_chain(&pseries_ioei_notifier_list,
0, event);
}
return IRQ_HANDLED;
}
static int __init ioei_init(void)
{
struct device_node *np;
ioei_check_exception_token = rtas_token("check-exception");
if (ioei_check_exception_token == RTAS_UNKNOWN_SERVICE)
return -ENODEV;
np = of_find_node_by_path("/event-sources/ibm,io-events");
if (np) {
request_event_sources_irqs(np, ioei_interrupt, "IO_EVENT");
pr_info("IBM I/O event interrupts enabled\n");
of_node_put(np);
} else {
return -ENODEV;
}
return 0;
}
machine_subsys_initcall(pseries, ioei_init);
| gpl-2.0 |
sleshepic/Note_2_l900 | arch/x86/kernel/cpu/perfctr-watchdog.c | 7961 | 3980 | /*
* local apic based NMI watchdog for various CPUs.
*
* This file also handles reservation of performance counters for coordination
* with other users (like oprofile).
*
* Note that these events normally don't tick when the CPU idles. This means
* the frequency varies with CPU load.
*
* Original code for K7/P6 written by Keith Owens
*
*/
#include <linux/percpu.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/bitops.h>
#include <linux/smp.h>
#include <asm/nmi.h>
#include <linux/kprobes.h>
#include <asm/apic.h>
#include <asm/perf_event.h>
/*
* this number is calculated from Intel's MSR_P4_CRU_ESCR5 register and it's
* offset from MSR_P4_BSU_ESCR0.
*
* It will be the max for all platforms (for now)
*/
#define NMI_MAX_COUNTER_BITS 66
/*
* perfctr_nmi_owner tracks the ownership of the perfctr registers:
* evtsel_nmi_owner tracks the ownership of the event selection
* - different performance counters/ event selection may be reserved for
* different subsystems this reservation system just tries to coordinate
* things a little
*/
static DECLARE_BITMAP(perfctr_nmi_owner, NMI_MAX_COUNTER_BITS);
static DECLARE_BITMAP(evntsel_nmi_owner, NMI_MAX_COUNTER_BITS);
/* converts an msr to an appropriate reservation bit */
static inline unsigned int nmi_perfctr_msr_to_bit(unsigned int msr)
{
/* returns the bit offset of the performance counter register */
switch (boot_cpu_data.x86_vendor) {
case X86_VENDOR_AMD:
if (msr >= MSR_F15H_PERF_CTR)
return (msr - MSR_F15H_PERF_CTR) >> 1;
return msr - MSR_K7_PERFCTR0;
case X86_VENDOR_INTEL:
if (cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON))
return msr - MSR_ARCH_PERFMON_PERFCTR0;
switch (boot_cpu_data.x86) {
case 6:
return msr - MSR_P6_PERFCTR0;
case 15:
return msr - MSR_P4_BPU_PERFCTR0;
}
}
return 0;
}
/*
* converts an msr to an appropriate reservation bit
* returns the bit offset of the event selection register
*/
static inline unsigned int nmi_evntsel_msr_to_bit(unsigned int msr)
{
/* returns the bit offset of the event selection register */
switch (boot_cpu_data.x86_vendor) {
case X86_VENDOR_AMD:
if (msr >= MSR_F15H_PERF_CTL)
return (msr - MSR_F15H_PERF_CTL) >> 1;
return msr - MSR_K7_EVNTSEL0;
case X86_VENDOR_INTEL:
if (cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON))
return msr - MSR_ARCH_PERFMON_EVENTSEL0;
switch (boot_cpu_data.x86) {
case 6:
return msr - MSR_P6_EVNTSEL0;
case 15:
return msr - MSR_P4_BSU_ESCR0;
}
}
return 0;
}
/* checks for a bit availability (hack for oprofile) */
int avail_to_resrv_perfctr_nmi_bit(unsigned int counter)
{
BUG_ON(counter > NMI_MAX_COUNTER_BITS);
return !test_bit(counter, perfctr_nmi_owner);
}
EXPORT_SYMBOL(avail_to_resrv_perfctr_nmi_bit);
int reserve_perfctr_nmi(unsigned int msr)
{
unsigned int counter;
counter = nmi_perfctr_msr_to_bit(msr);
/* register not managed by the allocator? */
if (counter > NMI_MAX_COUNTER_BITS)
return 1;
if (!test_and_set_bit(counter, perfctr_nmi_owner))
return 1;
return 0;
}
EXPORT_SYMBOL(reserve_perfctr_nmi);
void release_perfctr_nmi(unsigned int msr)
{
unsigned int counter;
counter = nmi_perfctr_msr_to_bit(msr);
/* register not managed by the allocator? */
if (counter > NMI_MAX_COUNTER_BITS)
return;
clear_bit(counter, perfctr_nmi_owner);
}
EXPORT_SYMBOL(release_perfctr_nmi);
int reserve_evntsel_nmi(unsigned int msr)
{
unsigned int counter;
counter = nmi_evntsel_msr_to_bit(msr);
/* register not managed by the allocator? */
if (counter > NMI_MAX_COUNTER_BITS)
return 1;
if (!test_and_set_bit(counter, evntsel_nmi_owner))
return 1;
return 0;
}
EXPORT_SYMBOL(reserve_evntsel_nmi);
void release_evntsel_nmi(unsigned int msr)
{
unsigned int counter;
counter = nmi_evntsel_msr_to_bit(msr);
/* register not managed by the allocator? */
if (counter > NMI_MAX_COUNTER_BITS)
return;
clear_bit(counter, evntsel_nmi_owner);
}
EXPORT_SYMBOL(release_evntsel_nmi);
| gpl-2.0 |
laufersteppenwolf/android_kernel_lge_d680 | drivers/ide/ide-floppy.c | 8473 | 14731 | /*
* IDE ATAPI floppy driver.
*
* Copyright (C) 1996-1999 Gadi Oxman <gadio@netvision.net.il>
* Copyright (C) 2000-2002 Paul Bristow <paul@paulbristow.net>
* Copyright (C) 2005 Bartlomiej Zolnierkiewicz
*
* This driver supports the following IDE floppy drives:
*
* LS-120/240 SuperDisk
* Iomega Zip 100/250
* Iomega PC Card Clik!/PocketZip
*
* For a historical changelog see
* Documentation/ide/ChangeLog.ide-floppy.1996-2002
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/genhd.h>
#include <linux/cdrom.h>
#include <linux/ide.h>
#include <linux/hdreg.h>
#include <linux/bitops.h>
#include <linux/mutex.h>
#include <linux/scatterlist.h>
#include <scsi/scsi_ioctl.h>
#include <asm/byteorder.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <asm/unaligned.h>
#include "ide-floppy.h"
/*
* After each failed packet command we issue a request sense command and retry
* the packet command IDEFLOPPY_MAX_PC_RETRIES times.
*/
#define IDEFLOPPY_MAX_PC_RETRIES 3
/* format capacities descriptor codes */
#define CAPACITY_INVALID 0x00
#define CAPACITY_UNFORMATTED 0x01
#define CAPACITY_CURRENT 0x02
#define CAPACITY_NO_CARTRIDGE 0x03
/*
* The following delay solves a problem with ATAPI Zip 100 drive where BSY bit
* was apparently being deasserted before the unit was ready to receive data.
*/
#define IDEFLOPPY_PC_DELAY (HZ/20) /* default delay for ZIP 100 (50ms) */
static int ide_floppy_callback(ide_drive_t *drive, int dsc)
{
struct ide_disk_obj *floppy = drive->driver_data;
struct ide_atapi_pc *pc = drive->pc;
struct request *rq = pc->rq;
int uptodate = pc->error ? 0 : 1;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (drive->failed_pc == pc)
drive->failed_pc = NULL;
if (pc->c[0] == GPCMD_READ_10 || pc->c[0] == GPCMD_WRITE_10 ||
rq->cmd_type == REQ_TYPE_BLOCK_PC)
uptodate = 1; /* FIXME */
else if (pc->c[0] == GPCMD_REQUEST_SENSE) {
u8 *buf = bio_data(rq->bio);
if (!pc->error) {
floppy->sense_key = buf[2] & 0x0F;
floppy->asc = buf[12];
floppy->ascq = buf[13];
floppy->progress_indication = buf[15] & 0x80 ?
(u16)get_unaligned((u16 *)&buf[16]) : 0x10000;
if (drive->failed_pc)
ide_debug_log(IDE_DBG_PC, "pc = %x",
drive->failed_pc->c[0]);
ide_debug_log(IDE_DBG_SENSE, "sense key = %x, asc = %x,"
"ascq = %x", floppy->sense_key,
floppy->asc, floppy->ascq);
} else
printk(KERN_ERR PFX "Error in REQUEST SENSE itself - "
"Aborting request!\n");
}
if (rq->cmd_type == REQ_TYPE_SPECIAL)
rq->errors = uptodate ? 0 : IDE_DRV_ERROR_GENERAL;
return uptodate;
}
static void ide_floppy_report_error(struct ide_disk_obj *floppy,
struct ide_atapi_pc *pc)
{
/* suppress error messages resulting from Medium not present */
if (floppy->sense_key == 0x02 &&
floppy->asc == 0x3a &&
floppy->ascq == 0x00)
return;
printk(KERN_ERR PFX "%s: I/O error, pc = %2x, key = %2x, "
"asc = %2x, ascq = %2x\n",
floppy->drive->name, pc->c[0], floppy->sense_key,
floppy->asc, floppy->ascq);
}
static ide_startstop_t ide_floppy_issue_pc(ide_drive_t *drive,
struct ide_cmd *cmd,
struct ide_atapi_pc *pc)
{
struct ide_disk_obj *floppy = drive->driver_data;
if (drive->failed_pc == NULL &&
pc->c[0] != GPCMD_REQUEST_SENSE)
drive->failed_pc = pc;
/* Set the current packet command */
drive->pc = pc;
if (pc->retries > IDEFLOPPY_MAX_PC_RETRIES) {
unsigned int done = blk_rq_bytes(drive->hwif->rq);
if (!(pc->flags & PC_FLAG_SUPPRESS_ERROR))
ide_floppy_report_error(floppy, pc);
/* Giving up */
pc->error = IDE_DRV_ERROR_GENERAL;
drive->failed_pc = NULL;
drive->pc_callback(drive, 0);
ide_complete_rq(drive, -EIO, done);
return ide_stopped;
}
ide_debug_log(IDE_DBG_FUNC, "retry #%d", pc->retries);
pc->retries++;
return ide_issue_pc(drive, cmd);
}
void ide_floppy_create_read_capacity_cmd(struct ide_atapi_pc *pc)
{
ide_init_pc(pc);
pc->c[0] = GPCMD_READ_FORMAT_CAPACITIES;
pc->c[7] = 255;
pc->c[8] = 255;
pc->req_xfer = 255;
}
/* A mode sense command is used to "sense" floppy parameters. */
void ide_floppy_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
{
u16 length = 8; /* sizeof(Mode Parameter Header) = 8 Bytes */
ide_init_pc(pc);
pc->c[0] = GPCMD_MODE_SENSE_10;
pc->c[1] = 0;
pc->c[2] = page_code;
switch (page_code) {
case IDEFLOPPY_CAPABILITIES_PAGE:
length += 12;
break;
case IDEFLOPPY_FLEXIBLE_DISK_PAGE:
length += 32;
break;
default:
printk(KERN_ERR PFX "unsupported page code in %s\n", __func__);
}
put_unaligned(cpu_to_be16(length), (u16 *) &pc->c[7]);
pc->req_xfer = length;
}
static void idefloppy_create_rw_cmd(ide_drive_t *drive,
struct ide_atapi_pc *pc, struct request *rq,
unsigned long sector)
{
struct ide_disk_obj *floppy = drive->driver_data;
int block = sector / floppy->bs_factor;
int blocks = blk_rq_sectors(rq) / floppy->bs_factor;
int cmd = rq_data_dir(rq);
ide_debug_log(IDE_DBG_FUNC, "block: %d, blocks: %d", block, blocks);
ide_init_pc(pc);
pc->c[0] = cmd == READ ? GPCMD_READ_10 : GPCMD_WRITE_10;
put_unaligned(cpu_to_be16(blocks), (unsigned short *)&pc->c[7]);
put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[2]);
memcpy(rq->cmd, pc->c, 12);
pc->rq = rq;
if (rq->cmd_flags & REQ_WRITE)
pc->flags |= PC_FLAG_WRITING;
pc->flags |= PC_FLAG_DMA_OK;
}
static void idefloppy_blockpc_cmd(struct ide_disk_obj *floppy,
struct ide_atapi_pc *pc, struct request *rq)
{
ide_init_pc(pc);
memcpy(pc->c, rq->cmd, sizeof(pc->c));
pc->rq = rq;
if (blk_rq_bytes(rq)) {
pc->flags |= PC_FLAG_DMA_OK;
if (rq_data_dir(rq) == WRITE)
pc->flags |= PC_FLAG_WRITING;
}
}
static ide_startstop_t ide_floppy_do_request(ide_drive_t *drive,
struct request *rq, sector_t block)
{
struct ide_disk_obj *floppy = drive->driver_data;
struct ide_cmd cmd;
struct ide_atapi_pc *pc;
ide_debug_log(IDE_DBG_FUNC, "enter, cmd: 0x%x\n", rq->cmd[0]);
if (drive->debug_mask & IDE_DBG_RQ)
blk_dump_rq_flags(rq, (rq->rq_disk
? rq->rq_disk->disk_name
: "dev?"));
if (rq->errors >= ERROR_MAX) {
if (drive->failed_pc) {
ide_floppy_report_error(floppy, drive->failed_pc);
drive->failed_pc = NULL;
} else
printk(KERN_ERR PFX "%s: I/O error\n", drive->name);
if (rq->cmd_type == REQ_TYPE_SPECIAL) {
rq->errors = 0;
ide_complete_rq(drive, 0, blk_rq_bytes(rq));
return ide_stopped;
} else
goto out_end;
}
switch (rq->cmd_type) {
case REQ_TYPE_FS:
if (((long)blk_rq_pos(rq) % floppy->bs_factor) ||
(blk_rq_sectors(rq) % floppy->bs_factor)) {
printk(KERN_ERR PFX "%s: unsupported r/w rq size\n",
drive->name);
goto out_end;
}
pc = &floppy->queued_pc;
idefloppy_create_rw_cmd(drive, pc, rq, (unsigned long)block);
break;
case REQ_TYPE_SPECIAL:
case REQ_TYPE_SENSE:
pc = (struct ide_atapi_pc *)rq->special;
break;
case REQ_TYPE_BLOCK_PC:
pc = &floppy->queued_pc;
idefloppy_blockpc_cmd(floppy, pc, rq);
break;
default:
BUG();
}
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);
}
pc->rq = rq;
return ide_floppy_issue_pc(drive, &cmd, pc);
out_end:
drive->failed_pc = NULL;
if (rq->cmd_type != REQ_TYPE_FS && rq->errors == 0)
rq->errors = -EIO;
ide_complete_rq(drive, -EIO, blk_rq_bytes(rq));
return ide_stopped;
}
/*
* Look at the flexible disk page parameters. We ignore the CHS capacity
* parameters and use the LBA parameters instead.
*/
static int ide_floppy_get_flexible_disk_page(ide_drive_t *drive,
struct ide_atapi_pc *pc)
{
struct ide_disk_obj *floppy = drive->driver_data;
struct gendisk *disk = floppy->disk;
u8 *page, buf[40];
int capacity, lba_capacity;
u16 transfer_rate, sector_size, cyls, rpm;
u8 heads, sectors;
ide_floppy_create_mode_sense_cmd(pc, IDEFLOPPY_FLEXIBLE_DISK_PAGE);
if (ide_queue_pc_tail(drive, disk, pc, buf, pc->req_xfer)) {
printk(KERN_ERR PFX "Can't get flexible disk page params\n");
return 1;
}
if (buf[3] & 0x80)
drive->dev_flags |= IDE_DFLAG_WP;
else
drive->dev_flags &= ~IDE_DFLAG_WP;
set_disk_ro(disk, !!(drive->dev_flags & IDE_DFLAG_WP));
page = &buf[8];
transfer_rate = be16_to_cpup((__be16 *)&buf[8 + 2]);
sector_size = be16_to_cpup((__be16 *)&buf[8 + 6]);
cyls = be16_to_cpup((__be16 *)&buf[8 + 8]);
rpm = be16_to_cpup((__be16 *)&buf[8 + 28]);
heads = buf[8 + 4];
sectors = buf[8 + 5];
capacity = cyls * heads * sectors * sector_size;
if (memcmp(page, &floppy->flexible_disk_page, 32))
printk(KERN_INFO PFX "%s: %dkB, %d/%d/%d CHS, %d kBps, "
"%d sector size, %d rpm\n",
drive->name, capacity / 1024, cyls, heads,
sectors, transfer_rate / 8, sector_size, rpm);
memcpy(&floppy->flexible_disk_page, page, 32);
drive->bios_cyl = cyls;
drive->bios_head = heads;
drive->bios_sect = sectors;
lba_capacity = floppy->blocks * floppy->block_size;
if (capacity < lba_capacity) {
printk(KERN_NOTICE PFX "%s: The disk reports a capacity of %d "
"bytes, but the drive only handles %d\n",
drive->name, lba_capacity, capacity);
floppy->blocks = floppy->block_size ?
capacity / floppy->block_size : 0;
drive->capacity64 = floppy->blocks * floppy->bs_factor;
}
return 0;
}
/*
* Determine if a media is present in the floppy drive, and if so, its LBA
* capacity.
*/
static int ide_floppy_get_capacity(ide_drive_t *drive)
{
struct ide_disk_obj *floppy = drive->driver_data;
struct gendisk *disk = floppy->disk;
struct ide_atapi_pc pc;
u8 *cap_desc;
u8 pc_buf[256], header_len, desc_cnt;
int i, rc = 1, blocks, length;
ide_debug_log(IDE_DBG_FUNC, "enter");
drive->bios_cyl = 0;
drive->bios_head = drive->bios_sect = 0;
floppy->blocks = 0;
floppy->bs_factor = 1;
drive->capacity64 = 0;
ide_floppy_create_read_capacity_cmd(&pc);
if (ide_queue_pc_tail(drive, disk, &pc, pc_buf, pc.req_xfer)) {
printk(KERN_ERR PFX "Can't get floppy parameters\n");
return 1;
}
header_len = pc_buf[3];
cap_desc = &pc_buf[4];
desc_cnt = header_len / 8; /* capacity descriptor of 8 bytes */
for (i = 0; i < desc_cnt; i++) {
unsigned int desc_start = 4 + i*8;
blocks = be32_to_cpup((__be32 *)&pc_buf[desc_start]);
length = be16_to_cpup((__be16 *)&pc_buf[desc_start + 6]);
ide_debug_log(IDE_DBG_PROBE, "Descriptor %d: %dkB, %d blocks, "
"%d sector size",
i, blocks * length / 1024,
blocks, length);
if (i)
continue;
/*
* the code below is valid only for the 1st descriptor, ie i=0
*/
switch (pc_buf[desc_start + 4] & 0x03) {
/* Clik! drive returns this instead of CAPACITY_CURRENT */
case CAPACITY_UNFORMATTED:
if (!(drive->atapi_flags & IDE_AFLAG_CLIK_DRIVE))
/*
* If it is not a clik drive, break out
* (maintains previous driver behaviour)
*/
break;
case CAPACITY_CURRENT:
/* Normal Zip/LS-120 disks */
if (memcmp(cap_desc, &floppy->cap_desc, 8))
printk(KERN_INFO PFX "%s: %dkB, %d blocks, %d "
"sector size\n",
drive->name, blocks * length / 1024,
blocks, length);
memcpy(&floppy->cap_desc, cap_desc, 8);
if (!length || length % 512) {
printk(KERN_NOTICE PFX "%s: %d bytes block size"
" not supported\n", drive->name, length);
} else {
floppy->blocks = blocks;
floppy->block_size = length;
floppy->bs_factor = length / 512;
if (floppy->bs_factor != 1)
printk(KERN_NOTICE PFX "%s: Warning: "
"non 512 bytes block size not "
"fully supported\n",
drive->name);
drive->capacity64 =
floppy->blocks * floppy->bs_factor;
rc = 0;
}
break;
case CAPACITY_NO_CARTRIDGE:
/*
* This is a KERN_ERR so it appears on screen
* for the user to see
*/
printk(KERN_ERR PFX "%s: No disk in drive\n",
drive->name);
break;
case CAPACITY_INVALID:
printk(KERN_ERR PFX "%s: Invalid capacity for disk "
"in drive\n", drive->name);
break;
}
ide_debug_log(IDE_DBG_PROBE, "Descriptor 0 Code: %d",
pc_buf[desc_start + 4] & 0x03);
}
/* Clik! disk does not support get_flexible_disk_page */
if (!(drive->atapi_flags & IDE_AFLAG_CLIK_DRIVE))
(void) ide_floppy_get_flexible_disk_page(drive, &pc);
return rc;
}
static void ide_floppy_setup(ide_drive_t *drive)
{
struct ide_disk_obj *floppy = drive->driver_data;
u16 *id = drive->id;
drive->pc_callback = ide_floppy_callback;
/*
* We used to check revisions here. At this point however I'm giving up.
* Just assume they are all broken, its easier.
*
* The actual reason for the workarounds was likely a driver bug after
* all rather than a firmware bug, and the workaround below used to hide
* it. It should be fixed as of version 1.9, but to be on the safe side
* we'll leave the limitation below for the 2.2.x tree.
*/
if (!strncmp((char *)&id[ATA_ID_PROD], "IOMEGA ZIP 100 ATAPI", 20)) {
drive->atapi_flags |= IDE_AFLAG_ZIP_DRIVE;
/* This value will be visible in the /proc/ide/hdx/settings */
drive->pc_delay = IDEFLOPPY_PC_DELAY;
blk_queue_max_hw_sectors(drive->queue, 64);
}
/*
* Guess what? The IOMEGA Clik! drive also needs the above fix. It makes
* nasty clicking noises without it, so please don't remove this.
*/
if (strncmp((char *)&id[ATA_ID_PROD], "IOMEGA Clik!", 11) == 0) {
blk_queue_max_hw_sectors(drive->queue, 64);
drive->atapi_flags |= IDE_AFLAG_CLIK_DRIVE;
/* IOMEGA Clik! drives do not support lock/unlock commands */
drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
}
(void) ide_floppy_get_capacity(drive);
ide_proc_register_driver(drive, floppy->driver);
drive->dev_flags |= IDE_DFLAG_ATTACH;
}
static void ide_floppy_flush(ide_drive_t *drive)
{
}
static int ide_floppy_init_media(ide_drive_t *drive, struct gendisk *disk)
{
int ret = 0;
if (ide_do_test_unit_ready(drive, disk))
ide_do_start_stop(drive, disk, 1);
ret = ide_floppy_get_capacity(drive);
set_capacity(disk, ide_gd_capacity(drive));
return ret;
}
const struct ide_disk_ops ide_atapi_disk_ops = {
.check = ide_check_atapi_device,
.get_capacity = ide_floppy_get_capacity,
.setup = ide_floppy_setup,
.flush = ide_floppy_flush,
.init_media = ide_floppy_init_media,
.set_doorlock = ide_set_media_lock,
.do_request = ide_floppy_do_request,
.ioctl = ide_floppy_ioctl,
};
| gpl-2.0 |
sbryan12144/BLACKOUT_ICS_MSM7x30 | fs/nls/nls_cp850.c | 12569 | 13400 | /*
* linux/fs/nls/nls_cp850.c
*
* Charset cp850 translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x00c7, 0x00fc, 0x00e9, 0x00e2,
0x00e4, 0x00e0, 0x00e5, 0x00e7,
0x00ea, 0x00eb, 0x00e8, 0x00ef,
0x00ee, 0x00ec, 0x00c4, 0x00c5,
/* 0x90*/
0x00c9, 0x00e6, 0x00c6, 0x00f4,
0x00f6, 0x00f2, 0x00fb, 0x00f9,
0x00ff, 0x00d6, 0x00dc, 0x00f8,
0x00a3, 0x00d8, 0x00d7, 0x0192,
/* 0xa0*/
0x00e1, 0x00ed, 0x00f3, 0x00fa,
0x00f1, 0x00d1, 0x00aa, 0x00ba,
0x00bf, 0x00ae, 0x00ac, 0x00bd,
0x00bc, 0x00a1, 0x00ab, 0x00bb,
/* 0xb0*/
0x2591, 0x2592, 0x2593, 0x2502,
0x2524, 0x00c1, 0x00c2, 0x00c0,
0x00a9, 0x2563, 0x2551, 0x2557,
0x255d, 0x00a2, 0x00a5, 0x2510,
/* 0xc0*/
0x2514, 0x2534, 0x252c, 0x251c,
0x2500, 0x253c, 0x00e3, 0x00c3,
0x255a, 0x2554, 0x2569, 0x2566,
0x2560, 0x2550, 0x256c, 0x00a4,
/* 0xd0*/
0x00f0, 0x00d0, 0x00ca, 0x00cb,
0x00c8, 0x0131, 0x00cd, 0x00ce,
0x00cf, 0x2518, 0x250c, 0x2588,
0x2584, 0x00a6, 0x00cc, 0x2580,
/* 0xe0*/
0x00d3, 0x00df, 0x00d4, 0x00d2,
0x00f5, 0x00d5, 0x00b5, 0x00fe,
0x00de, 0x00da, 0x00db, 0x00d9,
0x00fd, 0x00dd, 0x00af, 0x00b4,
/* 0xf0*/
0x00ad, 0x00b1, 0x2017, 0x00be,
0x00b6, 0x00a7, 0x00f7, 0x00b8,
0x00b0, 0x00a8, 0x00b7, 0x00b9,
0x00b3, 0x00b2, 0x25a0, 0x00a0,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xff, 0xad, 0xbd, 0x9c, 0xcf, 0xbe, 0xdd, 0xf5, /* 0xa0-0xa7 */
0xf9, 0xb8, 0xa6, 0xae, 0xaa, 0xf0, 0xa9, 0xee, /* 0xa8-0xaf */
0xf8, 0xf1, 0xfd, 0xfc, 0xef, 0xe6, 0xf4, 0xfa, /* 0xb0-0xb7 */
0xf7, 0xfb, 0xa7, 0xaf, 0xac, 0xab, 0xf3, 0xa8, /* 0xb8-0xbf */
0xb7, 0xb5, 0xb6, 0xc7, 0x8e, 0x8f, 0x92, 0x80, /* 0xc0-0xc7 */
0xd4, 0x90, 0xd2, 0xd3, 0xde, 0xd6, 0xd7, 0xd8, /* 0xc8-0xcf */
0xd1, 0xa5, 0xe3, 0xe0, 0xe2, 0xe5, 0x99, 0x9e, /* 0xd0-0xd7 */
0x9d, 0xeb, 0xe9, 0xea, 0x9a, 0xed, 0xe8, 0xe1, /* 0xd8-0xdf */
0x85, 0xa0, 0x83, 0xc6, 0x84, 0x86, 0x91, 0x87, /* 0xe0-0xe7 */
0x8a, 0x82, 0x88, 0x89, 0x8d, 0xa1, 0x8c, 0x8b, /* 0xe8-0xef */
0xd0, 0xa4, 0x95, 0xa2, 0x93, 0xe4, 0x94, 0xf6, /* 0xf0-0xf7 */
0x9b, 0x97, 0xa3, 0x96, 0x81, 0xec, 0xe7, 0x98, /* 0xf8-0xff */
};
static const unsigned char page01[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
};
static const unsigned char page20[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, /* 0x10-0x17 */
};
static const unsigned char page25[256] = {
0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0xcd, 0xba, 0x00, 0x00, 0xc9, 0x00, 0x00, 0xbb, /* 0x50-0x57 */
0x00, 0x00, 0xc8, 0x00, 0x00, 0xbc, 0x00, 0x00, /* 0x58-0x5f */
0xcc, 0x00, 0x00, 0xb9, 0x00, 0x00, 0xcb, 0x00, /* 0x60-0x67 */
0x00, 0xca, 0x00, 0x00, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0xdb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
};
static const unsigned char *const page_uni2charset[256] = {
page00, page01, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
page20, NULL, NULL, NULL, NULL, page25, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x87, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x84, 0x86, /* 0x88-0x8f */
0x82, 0x91, 0x91, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x94, 0x81, 0x9b, 0x9c, 0x9b, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa4, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xa0, 0x83, 0x85, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd0, 0x88, 0x89, 0x8a, 0xd5, 0xa1, 0x8c, /* 0xd0-0xd7 */
0x8b, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0x8d, 0xdf, /* 0xd8-0xdf */
0xa2, 0xe1, 0x93, 0x95, 0xe4, 0xe4, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe7, 0xa3, 0x96, 0x97, 0xec, 0xec, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x9a, 0x90, 0xb6, 0x8e, 0xb7, 0x8f, 0x80, /* 0x80-0x87 */
0xd2, 0xd3, 0xd4, 0xd8, 0xd7, 0xde, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x92, 0x92, 0xe2, 0x99, 0xe3, 0xea, 0xeb, /* 0x90-0x97 */
0x00, 0x99, 0x9a, 0x9d, 0x9c, 0x9d, 0x9e, 0x00, /* 0x98-0x9f */
0xb5, 0xd6, 0xe0, 0xe9, 0xa5, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc7, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd1, 0xd1, 0xd2, 0xd3, 0xd4, 0x49, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe5, 0xe5, 0x00, 0xe8, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xed, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "cp850",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_cp850(void)
{
return register_nls(&table);
}
static void __exit exit_nls_cp850(void)
{
unregister_nls(&table);
}
module_init(init_nls_cp850)
module_exit(exit_nls_cp850)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
hoalamha/android_kernel_lge_apq8084 | sound/isa/gus/gus_irq.c | 14617 | 4770 | /*
* Routine for IRQ handling from GF1/InterWave chip
* 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 <sound/core.h>
#include <sound/info.h>
#include <sound/gus.h>
#ifdef CONFIG_SND_DEBUG
#define STAT_ADD(x) ((x)++)
#else
#define STAT_ADD(x) while (0) { ; }
#endif
irqreturn_t snd_gus_interrupt(int irq, void *dev_id)
{
struct snd_gus_card * gus = dev_id;
unsigned char status;
int loop = 100;
int handled = 0;
__again:
status = inb(gus->gf1.reg_irqstat);
if (status == 0)
return IRQ_RETVAL(handled);
handled = 1;
/* snd_printk(KERN_DEBUG "IRQ: status = 0x%x\n", status); */
if (status & 0x02) {
STAT_ADD(gus->gf1.interrupt_stat_midi_in);
if (gus->gf1.interrupt_handler_midi_in)
gus->gf1.interrupt_handler_midi_in(gus);
}
if (status & 0x01) {
STAT_ADD(gus->gf1.interrupt_stat_midi_out);
if (gus->gf1.interrupt_handler_midi_out)
gus->gf1.interrupt_handler_midi_out(gus);
}
if (status & (0x20 | 0x40)) {
unsigned int already, _current_;
unsigned char voice_status, voice;
struct snd_gus_voice *pvoice;
already = 0;
while (((voice_status = snd_gf1_i_read8(gus, SNDRV_GF1_GB_VOICES_IRQ)) & 0xc0) != 0xc0) {
voice = voice_status & 0x1f;
_current_ = 1 << voice;
if (already & _current_)
continue; /* multi request */
already |= _current_; /* mark request */
#if 0
printk(KERN_DEBUG "voice = %i, voice_status = 0x%x, "
"voice_verify = %i\n",
voice, voice_status, inb(GUSP(gus, GF1PAGE)));
#endif
pvoice = &gus->gf1.voices[voice];
if (pvoice->use) {
if (!(voice_status & 0x80)) { /* voice position IRQ */
STAT_ADD(pvoice->interrupt_stat_wave);
pvoice->handler_wave(gus, pvoice);
}
if (!(voice_status & 0x40)) { /* volume ramp IRQ */
STAT_ADD(pvoice->interrupt_stat_volume);
pvoice->handler_volume(gus, pvoice);
}
} else {
STAT_ADD(gus->gf1.interrupt_stat_voice_lost);
snd_gf1_i_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL);
snd_gf1_i_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL);
}
}
}
if (status & 0x04) {
STAT_ADD(gus->gf1.interrupt_stat_timer1);
if (gus->gf1.interrupt_handler_timer1)
gus->gf1.interrupt_handler_timer1(gus);
}
if (status & 0x08) {
STAT_ADD(gus->gf1.interrupt_stat_timer2);
if (gus->gf1.interrupt_handler_timer2)
gus->gf1.interrupt_handler_timer2(gus);
}
if (status & 0x80) {
if (snd_gf1_i_look8(gus, SNDRV_GF1_GB_DRAM_DMA_CONTROL) & 0x40) {
STAT_ADD(gus->gf1.interrupt_stat_dma_write);
if (gus->gf1.interrupt_handler_dma_write)
gus->gf1.interrupt_handler_dma_write(gus);
}
if (snd_gf1_i_look8(gus, SNDRV_GF1_GB_REC_DMA_CONTROL) & 0x40) {
STAT_ADD(gus->gf1.interrupt_stat_dma_read);
if (gus->gf1.interrupt_handler_dma_read)
gus->gf1.interrupt_handler_dma_read(gus);
}
}
if (--loop > 0)
goto __again;
return IRQ_NONE;
}
#ifdef CONFIG_SND_DEBUG
static void snd_gus_irq_info_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_gus_card *gus;
struct snd_gus_voice *pvoice;
int idx;
gus = entry->private_data;
snd_iprintf(buffer, "midi out = %u\n", gus->gf1.interrupt_stat_midi_out);
snd_iprintf(buffer, "midi in = %u\n", gus->gf1.interrupt_stat_midi_in);
snd_iprintf(buffer, "timer1 = %u\n", gus->gf1.interrupt_stat_timer1);
snd_iprintf(buffer, "timer2 = %u\n", gus->gf1.interrupt_stat_timer2);
snd_iprintf(buffer, "dma write = %u\n", gus->gf1.interrupt_stat_dma_write);
snd_iprintf(buffer, "dma read = %u\n", gus->gf1.interrupt_stat_dma_read);
snd_iprintf(buffer, "voice lost = %u\n", gus->gf1.interrupt_stat_voice_lost);
for (idx = 0; idx < 32; idx++) {
pvoice = &gus->gf1.voices[idx];
snd_iprintf(buffer, "voice %i: wave = %u, volume = %u\n",
idx,
pvoice->interrupt_stat_wave,
pvoice->interrupt_stat_volume);
}
}
void snd_gus_irq_profile_init(struct snd_gus_card *gus)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(gus->card, "gusirq", &entry))
snd_info_set_text_ops(entry, gus, snd_gus_irq_info_read);
}
#endif
| gpl-2.0 |
MIPS/karma-linux-mti | sound/isa/gus/gus_irq.c | 14617 | 4770 | /*
* Routine for IRQ handling from GF1/InterWave chip
* 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 <sound/core.h>
#include <sound/info.h>
#include <sound/gus.h>
#ifdef CONFIG_SND_DEBUG
#define STAT_ADD(x) ((x)++)
#else
#define STAT_ADD(x) while (0) { ; }
#endif
irqreturn_t snd_gus_interrupt(int irq, void *dev_id)
{
struct snd_gus_card * gus = dev_id;
unsigned char status;
int loop = 100;
int handled = 0;
__again:
status = inb(gus->gf1.reg_irqstat);
if (status == 0)
return IRQ_RETVAL(handled);
handled = 1;
/* snd_printk(KERN_DEBUG "IRQ: status = 0x%x\n", status); */
if (status & 0x02) {
STAT_ADD(gus->gf1.interrupt_stat_midi_in);
if (gus->gf1.interrupt_handler_midi_in)
gus->gf1.interrupt_handler_midi_in(gus);
}
if (status & 0x01) {
STAT_ADD(gus->gf1.interrupt_stat_midi_out);
if (gus->gf1.interrupt_handler_midi_out)
gus->gf1.interrupt_handler_midi_out(gus);
}
if (status & (0x20 | 0x40)) {
unsigned int already, _current_;
unsigned char voice_status, voice;
struct snd_gus_voice *pvoice;
already = 0;
while (((voice_status = snd_gf1_i_read8(gus, SNDRV_GF1_GB_VOICES_IRQ)) & 0xc0) != 0xc0) {
voice = voice_status & 0x1f;
_current_ = 1 << voice;
if (already & _current_)
continue; /* multi request */
already |= _current_; /* mark request */
#if 0
printk(KERN_DEBUG "voice = %i, voice_status = 0x%x, "
"voice_verify = %i\n",
voice, voice_status, inb(GUSP(gus, GF1PAGE)));
#endif
pvoice = &gus->gf1.voices[voice];
if (pvoice->use) {
if (!(voice_status & 0x80)) { /* voice position IRQ */
STAT_ADD(pvoice->interrupt_stat_wave);
pvoice->handler_wave(gus, pvoice);
}
if (!(voice_status & 0x40)) { /* volume ramp IRQ */
STAT_ADD(pvoice->interrupt_stat_volume);
pvoice->handler_volume(gus, pvoice);
}
} else {
STAT_ADD(gus->gf1.interrupt_stat_voice_lost);
snd_gf1_i_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL);
snd_gf1_i_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL);
}
}
}
if (status & 0x04) {
STAT_ADD(gus->gf1.interrupt_stat_timer1);
if (gus->gf1.interrupt_handler_timer1)
gus->gf1.interrupt_handler_timer1(gus);
}
if (status & 0x08) {
STAT_ADD(gus->gf1.interrupt_stat_timer2);
if (gus->gf1.interrupt_handler_timer2)
gus->gf1.interrupt_handler_timer2(gus);
}
if (status & 0x80) {
if (snd_gf1_i_look8(gus, SNDRV_GF1_GB_DRAM_DMA_CONTROL) & 0x40) {
STAT_ADD(gus->gf1.interrupt_stat_dma_write);
if (gus->gf1.interrupt_handler_dma_write)
gus->gf1.interrupt_handler_dma_write(gus);
}
if (snd_gf1_i_look8(gus, SNDRV_GF1_GB_REC_DMA_CONTROL) & 0x40) {
STAT_ADD(gus->gf1.interrupt_stat_dma_read);
if (gus->gf1.interrupt_handler_dma_read)
gus->gf1.interrupt_handler_dma_read(gus);
}
}
if (--loop > 0)
goto __again;
return IRQ_NONE;
}
#ifdef CONFIG_SND_DEBUG
static void snd_gus_irq_info_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_gus_card *gus;
struct snd_gus_voice *pvoice;
int idx;
gus = entry->private_data;
snd_iprintf(buffer, "midi out = %u\n", gus->gf1.interrupt_stat_midi_out);
snd_iprintf(buffer, "midi in = %u\n", gus->gf1.interrupt_stat_midi_in);
snd_iprintf(buffer, "timer1 = %u\n", gus->gf1.interrupt_stat_timer1);
snd_iprintf(buffer, "timer2 = %u\n", gus->gf1.interrupt_stat_timer2);
snd_iprintf(buffer, "dma write = %u\n", gus->gf1.interrupt_stat_dma_write);
snd_iprintf(buffer, "dma read = %u\n", gus->gf1.interrupt_stat_dma_read);
snd_iprintf(buffer, "voice lost = %u\n", gus->gf1.interrupt_stat_voice_lost);
for (idx = 0; idx < 32; idx++) {
pvoice = &gus->gf1.voices[idx];
snd_iprintf(buffer, "voice %i: wave = %u, volume = %u\n",
idx,
pvoice->interrupt_stat_wave,
pvoice->interrupt_stat_volume);
}
}
void snd_gus_irq_profile_init(struct snd_gus_card *gus)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(gus->card, "gusirq", &entry))
snd_info_set_text_ops(entry, gus, snd_gus_irq_info_read);
}
#endif
| gpl-2.0 |
EZchip/gcc | libgfortran/generated/_atan_r4.F90 | 26 | 1473 | ! Copyright (C) 2002-2013 Free Software Foundation, Inc.
! Contributed by Paul Brook <paul@nowt.org>
!
!This file is part of the GNU Fortran 95 runtime library (libgfortran).
!
!GNU libgfortran 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 3 of the License, or (at your option) any later version.
!GNU libgfortran 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.
!
!Under Section 7 of GPL version 3, you are granted additional
!permissions described in the GCC Runtime Library Exception, version
!3.1, as published by the Free Software Foundation.
!
!You should have received a copy of the GNU General Public License and
!a copy of the GCC Runtime Library Exception along with this program;
!see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
!<http://www.gnu.org/licenses/>.
!
!This file is machine generated.
#include "config.h"
#include "kinds.inc"
#include "c99_protos.inc"
#if defined (HAVE_GFC_REAL_4)
#ifdef HAVE_ATANF
elemental function _gfortran_specific__atan_r4 (parm)
real (kind=4), intent (in) :: parm
real (kind=4) :: _gfortran_specific__atan_r4
_gfortran_specific__atan_r4 = atan (parm)
end function
#endif
#endif
| gpl-2.0 |
skristiansson/eco32-gcc | libgfortran/generated/_abs_i16.F90 | 26 | 1461 | ! Copyright (C) 2002-2013 Free Software Foundation, Inc.
! Contributed by Paul Brook <paul@nowt.org>
!
!This file is part of the GNU Fortran 95 runtime library (libgfortran).
!
!GNU libgfortran 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 3 of the License, or (at your option) any later version.
!GNU libgfortran 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.
!
!Under Section 7 of GPL version 3, you are granted additional
!permissions described in the GCC Runtime Library Exception, version
!3.1, as published by the Free Software Foundation.
!
!You should have received a copy of the GNU General Public License and
!a copy of the GCC Runtime Library Exception along with this program;
!see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
!<http://www.gnu.org/licenses/>.
!
!This file is machine generated.
#include "config.h"
#include "kinds.inc"
#include "c99_protos.inc"
#if defined (HAVE_GFC_INTEGER_16)
elemental function _gfortran_specific__abs_i16 (parm)
integer (kind=16), intent (in) :: parm
integer (kind=16) :: _gfortran_specific__abs_i16
_gfortran_specific__abs_i16 = abs (parm)
end function
#endif
| gpl-2.0 |
prpplague/RCA-DSB772WE | sound/soc/omap/osk5912.c | 26 | 5838 | /*
* osk5912.c -- SoC audio for OSK 5912
*
* Copyright (C) 2008 Mistral Solutions
*
* Contact: Arun KS <arunks@mistralsolutions.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <linux/gpio.h>
#include <mach/mcbsp.h>
#include "omap-mcbsp.h"
#include "omap-pcm.h"
#include "../codecs/tlv320aic23.h"
#define CODEC_CLOCK 12000000
static struct clk *tlv320aic23_mclk;
static int osk_startup(struct snd_pcm_substream *substream)
{
return clk_enable(tlv320aic23_mclk);
}
static void osk_shutdown(struct snd_pcm_substream *substream)
{
clk_disable(tlv320aic23_mclk);
}
static int osk_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->dai->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai;
int err;
/* Set codec DAI configuration */
err = snd_soc_dai_set_fmt(codec_dai,
SND_SOC_DAIFMT_DSP_A |
SND_SOC_DAIFMT_NB_IF |
SND_SOC_DAIFMT_CBM_CFM);
if (err < 0) {
printk(KERN_ERR "can't set codec DAI configuration\n");
return err;
}
/* Set cpu DAI configuration */
err = snd_soc_dai_set_fmt(cpu_dai,
SND_SOC_DAIFMT_DSP_A |
SND_SOC_DAIFMT_NB_IF |
SND_SOC_DAIFMT_CBM_CFM);
if (err < 0) {
printk(KERN_ERR "can't set cpu DAI configuration\n");
return err;
}
/* Set the codec system clock for DAC and ADC */
err =
snd_soc_dai_set_sysclk(codec_dai, 0, CODEC_CLOCK, SND_SOC_CLOCK_IN);
if (err < 0) {
printk(KERN_ERR "can't set codec system clock\n");
return err;
}
return err;
}
static struct snd_soc_ops osk_ops = {
.startup = osk_startup,
.hw_params = osk_hw_params,
.shutdown = osk_shutdown,
};
static const struct snd_soc_dapm_widget tlv320aic23_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_LINE("Line In", NULL),
SND_SOC_DAPM_MIC("Mic Jack", NULL),
};
static const struct snd_soc_dapm_route audio_map[] = {
{"Headphone Jack", NULL, "LHPOUT"},
{"Headphone Jack", NULL, "RHPOUT"},
{"LLINEIN", NULL, "Line In"},
{"RLINEIN", NULL, "Line In"},
{"MICIN", NULL, "Mic Jack"},
};
static int osk_tlv320aic23_init(struct snd_soc_codec *codec)
{
/* Add osk5912 specific widgets */
snd_soc_dapm_new_controls(codec, tlv320aic23_dapm_widgets,
ARRAY_SIZE(tlv320aic23_dapm_widgets));
/* Set up osk5912 specific audio path audio_map */
snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map));
snd_soc_dapm_enable_pin(codec, "Headphone Jack");
snd_soc_dapm_enable_pin(codec, "Line In");
snd_soc_dapm_enable_pin(codec, "Mic Jack");
snd_soc_dapm_sync(codec);
return 0;
}
/* Digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link osk_dai = {
.name = "TLV320AIC23",
.stream_name = "AIC23",
.cpu_dai = &omap_mcbsp_dai[0],
.codec_dai = &tlv320aic23_dai,
.init = osk_tlv320aic23_init,
.ops = &osk_ops,
};
/* Audio machine driver */
static struct snd_soc_machine snd_soc_machine_osk = {
.name = "OSK5912",
.dai_link = &osk_dai,
.num_links = 1,
};
/* Audio subsystem */
static struct snd_soc_device osk_snd_devdata = {
.machine = &snd_soc_machine_osk,
.platform = &omap_soc_platform,
.codec_dev = &soc_codec_dev_tlv320aic23,
};
static struct platform_device *osk_snd_device;
static int __init osk_soc_init(void)
{
int err;
u32 curRate;
struct device *dev;
if (!(machine_is_omap_osk()))
return -ENODEV;
osk_snd_device = platform_device_alloc("soc-audio", -1);
if (!osk_snd_device)
return -ENOMEM;
platform_set_drvdata(osk_snd_device, &osk_snd_devdata);
osk_snd_devdata.dev = &osk_snd_device->dev;
*(unsigned int *)osk_dai.cpu_dai->private_data = 0; /* McBSP1 */
err = platform_device_add(osk_snd_device);
if (err)
goto err1;
dev = &osk_snd_device->dev;
tlv320aic23_mclk = clk_get(dev, "mclk");
if (IS_ERR(tlv320aic23_mclk)) {
printk(KERN_ERR "Could not get mclk clock\n");
return -ENODEV;
}
if (clk_get_usecount(tlv320aic23_mclk) > 0) {
/* MCLK is already in use */
printk(KERN_WARNING
"MCLK in use at %d Hz. We change it to %d Hz\n",
(uint) clk_get_rate(tlv320aic23_mclk), CODEC_CLOCK);
}
/*
* Configure 12 MHz output on MCLK.
*/
curRate = (uint) clk_get_rate(tlv320aic23_mclk);
if (curRate != CODEC_CLOCK) {
if (clk_set_rate(tlv320aic23_mclk, CODEC_CLOCK)) {
printk(KERN_ERR "Cannot set MCLK for AIC23 CODEC\n");
err = -ECANCELED;
goto err1;
}
}
printk(KERN_INFO "MCLK = %d [%d], usecount = %d\n",
(uint) clk_get_rate(tlv320aic23_mclk), CODEC_CLOCK,
clk_get_usecount(tlv320aic23_mclk));
return 0;
err1:
clk_put(tlv320aic23_mclk);
platform_device_del(osk_snd_device);
platform_device_put(osk_snd_device);
return err;
}
static void __exit osk_soc_exit(void)
{
platform_device_unregister(osk_snd_device);
}
module_init(osk_soc_init);
module_exit(osk_soc_exit);
MODULE_AUTHOR("Arun KS <arunks@mistralsolutions.com>");
MODULE_DESCRIPTION("ALSA SoC OSK 5912");
MODULE_LICENSE("GPL");
| gpl-2.0 |
clearwater/chumby-linux | kernel/smp.c | 26 | 10977 | /*
* Generic helpers for smp ipi calls
*
* (C) Jens Axboe <jens.axboe@oracle.com> 2008
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/percpu.h>
#include <linux/rcupdate.h>
#include <linux/rculist.h>
#include <linux/smp.h>
static DEFINE_PER_CPU(struct call_single_queue, call_single_queue);
static LIST_HEAD(call_function_queue);
__cacheline_aligned_in_smp DEFINE_SPINLOCK(call_function_lock);
enum {
CSD_FLAG_WAIT = 0x01,
CSD_FLAG_ALLOC = 0x02,
};
struct call_function_data {
struct call_single_data csd;
spinlock_t lock;
unsigned int refs;
cpumask_t cpumask;
struct rcu_head rcu_head;
};
struct call_single_queue {
struct list_head list;
spinlock_t lock;
};
static int __cpuinit init_call_single_data(void)
{
int i;
for_each_possible_cpu(i) {
struct call_single_queue *q = &per_cpu(call_single_queue, i);
spin_lock_init(&q->lock);
INIT_LIST_HEAD(&q->list);
}
return 0;
}
early_initcall(init_call_single_data);
static void csd_flag_wait(struct call_single_data *data)
{
/* Wait for response */
do {
if (!(data->flags & CSD_FLAG_WAIT))
break;
cpu_relax();
} while (1);
}
/*
* Insert a previously allocated call_single_data element for execution
* on the given CPU. data must already have ->func, ->info, and ->flags set.
*/
static void generic_exec_single(int cpu, struct call_single_data *data)
{
struct call_single_queue *dst = &per_cpu(call_single_queue, cpu);
int wait = data->flags & CSD_FLAG_WAIT, ipi;
unsigned long flags;
spin_lock_irqsave(&dst->lock, flags);
ipi = list_empty(&dst->list);
list_add_tail(&data->list, &dst->list);
spin_unlock_irqrestore(&dst->lock, flags);
/*
* Make the list addition visible before sending the ipi.
*/
smp_mb();
if (ipi)
arch_send_call_function_single_ipi(cpu);
if (wait)
csd_flag_wait(data);
}
static void rcu_free_call_data(struct rcu_head *head)
{
struct call_function_data *data;
data = container_of(head, struct call_function_data, rcu_head);
kfree(data);
}
/*
* Invoked by arch to handle an IPI for call function. Must be called with
* interrupts disabled.
*/
void generic_smp_call_function_interrupt(void)
{
struct call_function_data *data;
int cpu = get_cpu();
/*
* It's ok to use list_for_each_rcu() here even though we may delete
* 'pos', since list_del_rcu() doesn't clear ->next
*/
rcu_read_lock();
list_for_each_entry_rcu(data, &call_function_queue, csd.list) {
int refs;
if (!cpu_isset(cpu, data->cpumask))
continue;
data->csd.func(data->csd.info);
spin_lock(&data->lock);
cpu_clear(cpu, data->cpumask);
WARN_ON(data->refs == 0);
data->refs--;
refs = data->refs;
spin_unlock(&data->lock);
if (refs)
continue;
spin_lock(&call_function_lock);
list_del_rcu(&data->csd.list);
spin_unlock(&call_function_lock);
if (data->csd.flags & CSD_FLAG_WAIT) {
/*
* serialize stores to data with the flag clear
* and wakeup
*/
smp_wmb();
data->csd.flags &= ~CSD_FLAG_WAIT;
}
if (data->csd.flags & CSD_FLAG_ALLOC)
call_rcu(&data->rcu_head, rcu_free_call_data);
}
rcu_read_unlock();
put_cpu();
}
/*
* Invoked by arch to handle an IPI for call function single. Must be called
* from the arch with interrupts disabled.
*/
void generic_smp_call_function_single_interrupt(void)
{
struct call_single_queue *q = &__get_cpu_var(call_single_queue);
LIST_HEAD(list);
/*
* Need to see other stores to list head for checking whether
* list is empty without holding q->lock
*/
smp_read_barrier_depends();
while (!list_empty(&q->list)) {
unsigned int data_flags;
spin_lock(&q->lock);
list_replace_init(&q->list, &list);
spin_unlock(&q->lock);
while (!list_empty(&list)) {
struct call_single_data *data;
data = list_entry(list.next, struct call_single_data,
list);
list_del(&data->list);
/*
* 'data' can be invalid after this call if
* flags == 0 (when called through
* generic_exec_single(), so save them away before
* making the call.
*/
data_flags = data->flags;
data->func(data->info);
if (data_flags & CSD_FLAG_WAIT) {
smp_wmb();
data->flags &= ~CSD_FLAG_WAIT;
} else if (data_flags & CSD_FLAG_ALLOC)
kfree(data);
}
/*
* See comment on outer loop
*/
smp_read_barrier_depends();
}
}
/*
* smp_call_function_single - Run a function on a specific CPU
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait until function has completed on other CPUs.
*
* Returns 0 on success, else a negative status code. Note that @wait
* will be implicitly turned on in case of allocation failures, since
* we fall back to on-stack allocation.
*/
int smp_call_function_single(int cpu, void (*func) (void *info), void *info,
int wait)
{
struct call_single_data d;
unsigned long flags;
/* prevent preemption and reschedule on another processor,
as well as CPU removal */
int me = get_cpu();
int err = 0;
/* Can deadlock when called with interrupts disabled */
WARN_ON(irqs_disabled());
if (cpu == me) {
local_irq_save(flags);
func(info);
local_irq_restore(flags);
} else if ((unsigned)cpu < NR_CPUS && cpu_online(cpu)) {
struct call_single_data *data = NULL;
if (!wait) {
data = kmalloc(sizeof(*data), GFP_ATOMIC);
if (data)
data->flags = CSD_FLAG_ALLOC;
}
if (!data) {
data = &d;
data->flags = CSD_FLAG_WAIT;
}
data->func = func;
data->info = info;
generic_exec_single(cpu, data);
} else {
err = -ENXIO; /* CPU not online */
}
put_cpu();
return err;
}
EXPORT_SYMBOL(smp_call_function_single);
/**
* __smp_call_function_single(): Run a function on another CPU
* @cpu: The CPU to run on.
* @data: Pre-allocated and setup data structure
*
* Like smp_call_function_single(), but allow caller to pass in a pre-allocated
* data structure. Useful for embedding @data inside other structures, for
* instance.
*
*/
void __smp_call_function_single(int cpu, struct call_single_data *data)
{
/* Can deadlock when called with interrupts disabled */
WARN_ON((data->flags & CSD_FLAG_WAIT) && irqs_disabled());
generic_exec_single(cpu, data);
}
/* Dummy function */
static void quiesce_dummy(void *unused)
{
}
/*
* Ensure stack based data used in call function mask is safe to free.
*
* This is needed by smp_call_function_mask when using on-stack data, because
* a single call function queue is shared by all CPUs, and any CPU may pick up
* the data item on the queue at any time before it is deleted. So we need to
* ensure that all CPUs have transitioned through a quiescent state after
* this call.
*
* This is a very slow function, implemented by sending synchronous IPIs to
* all possible CPUs. For this reason, we have to alloc data rather than use
* stack based data even in the case of synchronous calls. The stack based
* data is then just used for deadlock/oom fallback which will be very rare.
*
* If a faster scheme can be made, we could go back to preferring stack based
* data -- the data allocation/free is non-zero cost.
*/
static void smp_call_function_mask_quiesce_stack(cpumask_t mask)
{
struct call_single_data data;
int cpu;
data.func = quiesce_dummy;
data.info = NULL;
for_each_cpu_mask(cpu, mask) {
data.flags = CSD_FLAG_WAIT;
generic_exec_single(cpu, &data);
}
}
/**
* smp_call_function_mask(): Run a function on a set of other CPUs.
* @mask: The set of cpus to run on.
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed on other CPUs.
*
* Returns 0 on success, else a negative status code.
*
* If @wait is true, then returns once @func has returned. Note that @wait
* will be implicitly turned on in case of allocation failures, since
* we fall back to on-stack allocation.
*
* You must not call this function with disabled interrupts or from a
* hardware interrupt handler or from a bottom half handler. Preemption
* must be disabled when calling this function.
*/
int smp_call_function_mask(cpumask_t mask, void (*func)(void *), void *info,
int wait)
{
struct call_function_data d;
struct call_function_data *data = NULL;
cpumask_t allbutself;
unsigned long flags;
int cpu, num_cpus;
int slowpath = 0;
/* Can deadlock when called with interrupts disabled */
WARN_ON(irqs_disabled());
cpu = smp_processor_id();
allbutself = cpu_online_map;
cpu_clear(cpu, allbutself);
cpus_and(mask, mask, allbutself);
num_cpus = cpus_weight(mask);
/*
* If zero CPUs, return. If just a single CPU, turn this request
* into a targetted single call instead since it's faster.
*/
if (!num_cpus)
return 0;
else if (num_cpus == 1) {
cpu = first_cpu(mask);
return smp_call_function_single(cpu, func, info, wait);
}
data = kmalloc(sizeof(*data), GFP_ATOMIC);
if (data) {
data->csd.flags = CSD_FLAG_ALLOC;
if (wait)
data->csd.flags |= CSD_FLAG_WAIT;
} else {
data = &d;
data->csd.flags = CSD_FLAG_WAIT;
wait = 1;
slowpath = 1;
}
spin_lock_init(&data->lock);
data->csd.func = func;
data->csd.info = info;
data->refs = num_cpus;
data->cpumask = mask;
spin_lock_irqsave(&call_function_lock, flags);
list_add_tail_rcu(&data->csd.list, &call_function_queue);
spin_unlock_irqrestore(&call_function_lock, flags);
/*
* Make the list addition visible before sending the ipi.
*/
smp_mb();
/* Send a message to all CPUs in the map */
arch_send_call_function_ipi(mask);
/* optionally wait for the CPUs to complete */
if (wait) {
csd_flag_wait(&data->csd);
if (unlikely(slowpath))
smp_call_function_mask_quiesce_stack(mask);
}
return 0;
}
EXPORT_SYMBOL(smp_call_function_mask);
/**
* smp_call_function(): Run a function on all other CPUs.
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed on other CPUs.
*
* Returns 0 on success, else a negative status code.
*
* If @wait is true, then returns once @func has returned; otherwise
* it returns just before the target cpu calls @func. In case of allocation
* failure, @wait will be implicitly turned on.
*
* You must not call this function with disabled interrupts or from a
* hardware interrupt handler or from a bottom half handler.
*/
int smp_call_function(void (*func)(void *), void *info, int wait)
{
int ret;
preempt_disable();
ret = smp_call_function_mask(cpu_online_map, func, info, wait);
preempt_enable();
return ret;
}
EXPORT_SYMBOL(smp_call_function);
void ipi_call_lock(void)
{
spin_lock(&call_function_lock);
}
void ipi_call_unlock(void)
{
spin_unlock(&call_function_lock);
}
void ipi_call_lock_irq(void)
{
spin_lock_irq(&call_function_lock);
}
void ipi_call_unlock_irq(void)
{
spin_unlock_irq(&call_function_lock);
}
| gpl-2.0 |
SlimRoms/kernel_htc_msm8994 | fs/sdcardfs/derived_perm.c | 26 | 8103 | /*
* fs/sdcardfs/derived_perm.c
*
* Copyright (c) 2013 Samsung Electronics Co. Ltd
* Authors: Daeho Jeong, Woojoong Lee, Seunghwan Hyun,
* Sunghwan Yun, Sungjong Seo
*
* This program has been developed as a stackable file system based on
* the WrapFS which written by
*
* Copyright (c) 1998-2011 Erez Zadok
* Copyright (c) 2009 Shrikar Archak
* Copyright (c) 2003-2011 Stony Brook University
* Copyright (c) 2003-2011 The Research Foundation of SUNY
*
* This file is dual licensed. It may be redistributed and/or modified
* under the terms of the Apache 2.0 License OR version 2 of the GNU
* General Public License.
*/
#include "sdcardfs.h"
/* copy derived state from parent inode */
static void inherit_derived_state(struct inode *parent, struct inode *child)
{
struct sdcardfs_inode_info *pi = SDCARDFS_I(parent);
struct sdcardfs_inode_info *ci = SDCARDFS_I(child);
ci->perm = PERM_INHERIT;
ci->userid = pi->userid;
ci->d_uid = pi->d_uid;
ci->under_android = pi->under_android;
}
/* helper function for derived state */
void setup_derived_state(struct inode *inode, perm_t perm,
userid_t userid, uid_t uid, bool under_android)
{
struct sdcardfs_inode_info *info = SDCARDFS_I(inode);
info->perm = perm;
info->userid = userid;
info->d_uid = uid;
info->under_android = under_android;
}
/* While renaming, there is a point where we want the path from dentry, but the name from newdentry */
void get_derived_permission_new(struct dentry *parent, struct dentry *dentry, struct dentry *newdentry)
{
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb);
struct sdcardfs_inode_info *info = SDCARDFS_I(dentry->d_inode);
struct sdcardfs_inode_info *parent_info= SDCARDFS_I(parent->d_inode);
appid_t appid;
/* By default, each inode inherits from its parent.
* the properties are maintained on its private fields
* because the inode attributes will be modified with that of
* its lower inode.
* The derived state will be updated on the last
* stage of each system call by fix_derived_permission(inode).
*/
inherit_derived_state(parent->d_inode, dentry->d_inode);
/* Derive custom permissions based on parent and current node */
switch (parent_info->perm) {
case PERM_INHERIT:
/* Already inherited above */
break;
case PERM_PRE_ROOT:
/* Legacy internal layout places users at top level */
info->perm = PERM_ROOT;
info->userid = simple_strtoul(newdentry->d_name.name, NULL, 10);
break;
case PERM_ROOT:
/* Assume masked off by default. */
if (!strcasecmp(newdentry->d_name.name, "Android")) {
/* App-specific directories inside; let anyone traverse */
info->perm = PERM_ANDROID;
info->under_android = true;
}
break;
case PERM_ANDROID:
if (!strcasecmp(newdentry->d_name.name, "data")) {
/* App-specific directories inside; let anyone traverse */
info->perm = PERM_ANDROID_DATA;
} else if (!strcasecmp(newdentry->d_name.name, "obb")) {
/* App-specific directories inside; let anyone traverse */
info->perm = PERM_ANDROID_OBB;
/* Single OBB directory is always shared */
} else if (!strcasecmp(newdentry->d_name.name, "media")) {
/* App-specific directories inside; let anyone traverse */
info->perm = PERM_ANDROID_MEDIA;
}
break;
case PERM_ANDROID_DATA:
case PERM_ANDROID_OBB:
case PERM_ANDROID_MEDIA:
appid = get_appid(sbi->pkgl_id, newdentry->d_name.name);
if (appid != 0) {
info->d_uid = multiuser_get_uid(parent_info->userid, appid);
}
break;
}
}
void get_derived_permission(struct dentry *parent, struct dentry *dentry)
{
get_derived_permission_new(parent, dentry, dentry);
}
void get_derive_permissions_recursive(struct dentry *parent) {
struct dentry *dentry;
list_for_each_entry(dentry, &parent->d_subdirs, d_child) {
if (dentry->d_inode) {
mutex_lock(&dentry->d_inode->i_mutex);
get_derived_permission(parent, dentry);
fix_derived_permission(dentry->d_inode);
get_derive_permissions_recursive(dentry);
mutex_unlock(&dentry->d_inode->i_mutex);
}
}
}
/* main function for updating derived permission */
inline void update_derived_permission_lock(struct dentry *dentry)
{
struct dentry *parent;
if(!dentry || !dentry->d_inode) {
printk(KERN_ERR "sdcardfs: %s: invalid dentry\n", __func__);
return;
}
/* FIXME:
* 1. need to check whether the dentry is updated or not
* 2. remove the root dentry update
*/
mutex_lock(&dentry->d_inode->i_mutex);
if(IS_ROOT(dentry)) {
//setup_default_pre_root_state(dentry->d_inode);
} else {
parent = dget_parent(dentry);
if(parent) {
get_derived_permission(parent, dentry);
dput(parent);
}
}
fix_derived_permission(dentry->d_inode);
mutex_unlock(&dentry->d_inode->i_mutex);
}
int need_graft_path(struct dentry *dentry)
{
int ret = 0;
struct dentry *parent = dget_parent(dentry);
struct sdcardfs_inode_info *parent_info= SDCARDFS_I(parent->d_inode);
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb);
if(parent_info->perm == PERM_ANDROID &&
!strcasecmp(dentry->d_name.name, "obb")) {
/* /Android/obb is the base obbpath of DERIVED_UNIFIED */
if(!(sbi->options.multiuser == false
&& parent_info->userid == 0)) {
ret = 1;
}
}
dput(parent);
return ret;
}
int is_obbpath_invalid(struct dentry *dent)
{
int ret = 0;
struct sdcardfs_dentry_info *di = SDCARDFS_D(dent);
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dent->d_sb);
char *path_buf, *obbpath_s;
/* check the base obbpath has been changed.
* this routine can check an uninitialized obb dentry as well.
* regarding the uninitialized obb, refer to the sdcardfs_mkdir() */
spin_lock(&di->lock);
if(di->orig_path.dentry) {
if(!di->lower_path.dentry) {
ret = 1;
} else {
path_get(&di->lower_path);
//lower_parent = lock_parent(lower_path->dentry);
path_buf = kmalloc(PATH_MAX, GFP_ATOMIC);
if(!path_buf) {
ret = 1;
printk(KERN_ERR "sdcardfs: fail to allocate path_buf in %s.\n", __func__);
} else {
obbpath_s = d_path(&di->lower_path, path_buf, PATH_MAX);
if (d_unhashed(di->lower_path.dentry) ||
strcasecmp(sbi->obbpath_s, obbpath_s)) {
ret = 1;
}
kfree(path_buf);
}
//unlock_dir(lower_parent);
path_put(&di->lower_path);
}
}
spin_unlock(&di->lock);
return ret;
}
int is_base_obbpath(struct dentry *dentry)
{
int ret = 0;
struct dentry *parent = dget_parent(dentry);
struct sdcardfs_inode_info *parent_info= SDCARDFS_I(parent->d_inode);
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb);
spin_lock(&SDCARDFS_D(dentry)->lock);
if (sbi->options.multiuser) {
if(parent_info->perm == PERM_PRE_ROOT &&
!strcasecmp(dentry->d_name.name, "obb")) {
ret = 1;
}
} else if (parent_info->perm == PERM_ANDROID &&
!strcasecmp(dentry->d_name.name, "obb")) {
ret = 1;
}
spin_unlock(&SDCARDFS_D(dentry)->lock);
return ret;
}
/* The lower_path will be stored to the dentry's orig_path
* and the base obbpath will be copyed to the lower_path variable.
* if an error returned, there's no change in the lower_path
* returns: -ERRNO if error (0: no error) */
int setup_obb_dentry(struct dentry *dentry, struct path *lower_path)
{
int err = 0;
struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb);
struct path obbpath;
/* A local obb dentry must have its own orig_path to support rmdir
* and mkdir of itself. Usually, we expect that the sbi->obbpath
* is avaiable on this stage. */
sdcardfs_set_orig_path(dentry, lower_path);
err = kern_path(sbi->obbpath_s,
LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &obbpath);
if(!err) {
/* the obbpath base has been found */
printk(KERN_INFO "sdcardfs: the sbi->obbpath is found\n");
pathcpy(lower_path, &obbpath);
} else {
/* if the sbi->obbpath is not available, we can optionally
* setup the lower_path with its orig_path.
* but, the current implementation just returns an error
* because the sdcard daemon also regards this case as
* a lookup fail. */
printk(KERN_INFO "sdcardfs: the sbi->obbpath is not available\n");
}
return err;
}
| gpl-2.0 |
CyanogenMod/htc-kernel-pyramid | drivers/video/msm_8x60/mipi_himax_cmd_720p_pt.c | 26 | 4330 | /* Copyright (c) 2010, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
#include <mach/panel_id.h>
#include "msm_fb.h"
#include "mipi_dsi.h"
#include "mipi_himax.h"
static struct msm_panel_info pinfo;
static struct mipi_dsi_phy_ctrl dsi_cmd_mode_phy_db = {
#if 0
/* two lane work */
/* DSI_BIT_CLK at 400MHz, 2 lane, RGB888 */
{0x03, 0x01, 0x01, 0x00}, /* regulator */
/* timing */
//{0x96, 0x26, 0x23, 0x0, 0x50, 0x4B, 0x1e,
//0x28, 0x28, 0x03, 0x04},
{0xAD, 0x8B, 0x19, 0x00, 0x1C, 0x92, 0x1C, 0x8D,
0x1C, 0x03, 0x04},
{0x7f, 0x00, 0x00, 0x00}, /* phy ctrl */
{0xee, 0x02, 0x86, 0x00}, /* strength */
/* pll control */
{0x41, 0x4A, 0xb1, 0xd9, 0x00, 0x50, 0x48, 0x63,
0x01, 0x0f, 0x07,
0x05, 0x14, 0x03, 0x03, 0x03, 0x54, 0x06, 0x10, 0x04, 0x03 },
};
#endif
#if 0 //device will hung when unlock, frame rate is about 42fps
/* DSI_BIT_CLK at 482MHz, 2 lane, RGB888 */
{0x03, 0x01, 0x01, 0x00}, /* regulator */
/* timing */
//{0x96, 0x26, 0x23, 0x0, 0x50, 0x4B, 0x1e,
//0x28, 0x28, 0x03, 0x04},
{0x96, 0x1E, 0x1E, 0x00, 0x3C, 0x3C, 0x1E, 0x28,
0x0b, 0x13, 0x04},
{0x7f, 0x00, 0x00, 0x00}, /* phy ctrl */
{0xee, 0x02, 0x86, 0x00}, /* strength */
/* pll control */
{0x41, 0x9c, 0xb9, 0xd6, 0x00, 0x50, 0x48, 0x63,
#ifdef THREE_LANES
0x01, 0x0f, 0x01,
#else
0x01, 0x0f, 0x07,
#endif
0x05, 0x14, 0x03, 0x03, 0x03, 0x54, 0x06, 0x10, 0x04, 0x03 },
};
#else
//frame rate is about 32fps
/* DSI_BIT_CLK at 500MHz, 2 lane, RGB888 */
{0x03, 0x01, 0x01, 0x00}, /* regulator */
/* timing */
{0xB9, 0x8E, 0x20, 0x00, 0x24, 0x96, 0x23,
0x90, 0x24, 0x03, 0x04},
{0x7f, 0x00, 0x00, 0x00}, /* phy ctrl */
{0xee, 0x02, 0x86, 0x00}, /* strength */
/* pll control */
{0x40, 0xf9, 0xb0, 0xda, 0x00, 0x50, 0x48, 0x63,
0x01, 0x0f, 0x07,
0x05, 0x14, 0x03, 0x0, 0x0, 0x54, 0x06, 0x10, 0x04, 0x0},
};
#endif
static int __init mipi_cmd_himax_720p_pt_init(void)
{
int ret;
#ifdef CONFIG_FB_MSM_MIPI_PANEL_DETECT
if (msm_fb_detect_client("mipi_cmd_himax_720p"))
return 0;
#endif
pr_info("Daniel:%s:", __func__);
pinfo.xres = 720;
pinfo.yres = 1280;
pinfo.type = MIPI_CMD_PANEL;
pinfo.pdest = DISPLAY_1;
pinfo.wait_cycle = 0;
pinfo.bpp = 24;
pinfo.lcdc.h_back_porch = 5;
pinfo.lcdc.h_front_porch = 5;
pinfo.lcdc.h_pulse_width = 5;
pinfo.lcdc.v_back_porch = 4;
pinfo.lcdc.v_front_porch = 14;
pinfo.lcdc.v_pulse_width = 2;
pinfo.lcdc.border_clr = 0; /* blk */
pinfo.lcdc.underflow_clr = 0xff; /* blue */
pinfo.lcdc.hsync_skew = 0;
pinfo.bl_max = 255;
pinfo.bl_min = 1;
pinfo.fb_num = 2;
pinfo.clk_rate = 482000000;
pinfo.lcd.vsync_enable = TRUE;
pinfo.lcd.hw_vsync_mode = TRUE;
pinfo.lcd.refx100 = 6096; /* adjust refx100 to prevent tearing */
pinfo.mipi.mode = DSI_CMD_MODE;
pinfo.mipi.dst_format = DSI_CMD_DST_FORMAT_RGB888;
pinfo.mipi.vc = 0;
pinfo.mipi.rgb_swap = DSI_RGB_SWAP_BGR;
pinfo.mipi.data_lane0 = TRUE;
pinfo.mipi.data_lane1 = TRUE;
#ifdef THREE_LANES
pinfo.mipi.data_lane2 = TRUE;
#endif
pinfo.mipi.t_clk_post = 0x0a;
pinfo.mipi.t_clk_pre = 0x1e;
pinfo.mipi.stream = 0; /* dma_p */
pinfo.mipi.mdp_trigger = DSI_CMD_TRIGGER_SW;
pinfo.mipi.dma_trigger = DSI_CMD_TRIGGER_SW;
pinfo.mipi.te_sel = 1; /* TE from vsycn gpio */
pinfo.mipi.interleave_max = 1;
pinfo.mipi.insert_dcs_cmd = TRUE;
pinfo.mipi.wr_mem_continue = 0x3c;
pinfo.mipi.wr_mem_start = 0x2c;
pinfo.mipi.dsi_phy_db = &dsi_cmd_mode_phy_db;
ret = mipi_himax_device_register(&pinfo, MIPI_DSI_PRIM, MIPI_DSI_PANEL_WVGA_PT);
pr_info("Daniel:%s:end.", __func__);
if (ret)
pr_err("%s: failed to register device!\n", __func__);
return ret;
}
module_init(mipi_cmd_himax_720p_pt_init);
| gpl-2.0 |
tmatsuya/milkymist-linux | drivers/char/hvc_rtas.c | 26 | 3659 | /*
* IBM RTAS driver interface to hvc_console.c
*
* (C) Copyright IBM Corporation 2001-2005
* (C) Copyright Red Hat, Inc. 2005
*
* Author(s): Maximino Augilar <IBM STI Design Center>
* : Ryan S. Arnold <rsa@us.ibm.com>
* : Utz Bacher <utz.bacher@de.ibm.com>
* : David Woodhouse <dwmw2@infradead.org>
*
* inspired by drivers/char/hvc_console.c
* written by Anton Blanchard and Paul Mackerras
*
* 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/console.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <asm/irq.h>
#include <asm/rtas.h>
#include "hvc_console.h"
#define hvc_rtas_cookie 0x67781e15
struct hvc_struct *hvc_rtas_dev;
static int rtascons_put_char_token = RTAS_UNKNOWN_SERVICE;
static int rtascons_get_char_token = RTAS_UNKNOWN_SERVICE;
static inline int hvc_rtas_write_console(uint32_t vtermno, const char *buf,
int count)
{
int i;
for (i = 0; i < count; i++) {
if (rtas_call(rtascons_put_char_token, 1, 1, NULL, buf[i]))
break;
}
return i;
}
static int hvc_rtas_read_console(uint32_t vtermno, char *buf, int count)
{
int i, c;
for (i = 0; i < count; i++) {
if (rtas_call(rtascons_get_char_token, 0, 2, &c))
break;
buf[i] = c;
}
return i;
}
static struct hv_ops hvc_rtas_get_put_ops = {
.get_chars = hvc_rtas_read_console,
.put_chars = hvc_rtas_write_console,
};
static int hvc_rtas_init(void)
{
struct hvc_struct *hp;
if (rtascons_put_char_token == RTAS_UNKNOWN_SERVICE)
rtascons_put_char_token = rtas_token("put-term-char");
if (rtascons_put_char_token == RTAS_UNKNOWN_SERVICE)
return -EIO;
if (rtascons_get_char_token == RTAS_UNKNOWN_SERVICE)
rtascons_get_char_token = rtas_token("get-term-char");
if (rtascons_get_char_token == RTAS_UNKNOWN_SERVICE)
return -EIO;
BUG_ON(hvc_rtas_dev);
/* Allocate an hvc_struct for the console device we instantiated
* earlier. Save off hp so that we can return it on exit */
hp = hvc_alloc(hvc_rtas_cookie, NO_IRQ, &hvc_rtas_get_put_ops, 16);
if (IS_ERR(hp))
return PTR_ERR(hp);
hvc_rtas_dev = hp;
return 0;
}
module_init(hvc_rtas_init);
/* This will tear down the tty portion of the driver */
static void __exit hvc_rtas_exit(void)
{
/* Really the fun isn't over until the worker thread breaks down and
* the tty cleans up */
if (hvc_rtas_dev)
hvc_remove(hvc_rtas_dev);
}
module_exit(hvc_rtas_exit);
/* This will happen prior to module init. There is no tty at this time? */
static int __init hvc_rtas_console_init(void)
{
rtascons_put_char_token = rtas_token("put-term-char");
if (rtascons_put_char_token == RTAS_UNKNOWN_SERVICE)
return -EIO;
rtascons_get_char_token = rtas_token("get-term-char");
if (rtascons_get_char_token == RTAS_UNKNOWN_SERVICE)
return -EIO;
hvc_instantiate(hvc_rtas_cookie, 0, &hvc_rtas_get_put_ops);
add_preferred_console("hvc", 0, NULL);
return 0;
}
console_initcall(hvc_rtas_console_init);
| gpl-2.0 |
Max-Coin/cpuminer | keccak.c | 26 | 54976 | /* $Id: keccak.c 259 2011-07-19 22:11:27Z tp $ */
/*
* Keccak implementation.
*
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* 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.
*
* ===========================(LICENSE END)=============================
*
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
#include <stddef.h>
#include <string.h>
#include "sph_keccak.h"
#ifdef __cplusplus
extern "C"{
#endif
/*
* Parameters:
*
* SPH_KECCAK_64 use a 64-bit type
* SPH_KECCAK_UNROLL number of loops to unroll (0/undef for full unroll)
* SPH_KECCAK_INTERLEAVE use bit-interleaving (32-bit type only)
* SPH_KECCAK_NOCOPY do not copy the state into local variables
*
* If there is no usable 64-bit type, the code automatically switches
* back to the 32-bit implementation.
*
* Some tests on an Intel Core2 Q6600 (both 64-bit and 32-bit, 32 kB L1
* code cache), a PowerPC (G3, 32 kB L1 code cache), an ARM920T core
* (16 kB L1 code cache), and a small MIPS-compatible CPU (Broadcom BCM3302,
* 8 kB L1 code cache), seem to show that the following are optimal:
*
* -- x86, 64-bit: use the 64-bit implementation, unroll 8 rounds,
* do not copy the state; unrolling 2, 6 or all rounds also provides
* near-optimal performance.
* -- x86, 32-bit: use the 32-bit implementation, unroll 6 rounds,
* interleave, do not copy the state. Unrolling 1, 2, 4 or 8 rounds
* also provides near-optimal performance.
* -- PowerPC: use the 64-bit implementation, unroll 8 rounds,
* copy the state. Unrolling 4 or 6 rounds is near-optimal.
* -- ARM: use the 64-bit implementation, unroll 2 or 4 rounds,
* copy the state.
* -- MIPS: use the 64-bit implementation, unroll 2 rounds, copy
* the state. Unrolling only 1 round is also near-optimal.
*
* Also, interleaving does not always yield actual improvements when
* using a 32-bit implementation; in particular when the architecture
* does not offer a native rotation opcode (interleaving replaces one
* 64-bit rotation with two 32-bit rotations, which is a gain only if
* there is a native 32-bit rotation opcode and not a native 64-bit
* rotation opcode; also, interleaving implies a small overhead when
* processing input words).
*
* To sum up:
* -- when possible, use the 64-bit code
* -- exception: on 32-bit x86, use 32-bit code
* -- when using 32-bit code, use interleaving
* -- copy the state, except on x86
* -- unroll 8 rounds on "big" machine, 2 rounds on "small" machines
*/
#if SPH_SMALL_FOOTPRINT && !defined SPH_SMALL_FOOTPRINT_KECCAK
#define SPH_SMALL_FOOTPRINT_KECCAK 1
#endif
/*
* By default, we select the 64-bit implementation if a 64-bit type
* is available, unless a 32-bit x86 is detected.
*/
#if !defined SPH_KECCAK_64 && SPH_64 \
&& !(defined __i386__ || SPH_I386_GCC || SPH_I386_MSVC)
#define SPH_KECCAK_64 1
#endif
/*
* If using a 32-bit implementation, we prefer to interleave.
*/
#if !SPH_KECCAK_64 && !defined SPH_KECCAK_INTERLEAVE
#define SPH_KECCAK_INTERLEAVE 1
#endif
/*
* Unroll 8 rounds on big systems, 2 rounds on small systems.
*/
#ifndef SPH_KECCAK_UNROLL
#if SPH_SMALL_FOOTPRINT_KECCAK
#define SPH_KECCAK_UNROLL 2
#else
#define SPH_KECCAK_UNROLL 8
#endif
#endif
/*
* We do not want to copy the state to local variables on x86 (32-bit
* and 64-bit alike).
*/
#ifndef SPH_KECCAK_NOCOPY
#if defined __i386__ || defined __x86_64 || SPH_I386_MSVC || SPH_I386_GCC
#define SPH_KECCAK_NOCOPY 1
#else
#define SPH_KECCAK_NOCOPY 0
#endif
#endif
#ifdef _MSC_VER
#pragma warning (disable: 4146)
#endif
#if SPH_KECCAK_64
static const sph_u64 RC[] = {
SPH_C64(0x0000000000000001), SPH_C64(0x0000000000008082),
SPH_C64(0x800000000000808A), SPH_C64(0x8000000080008000),
SPH_C64(0x000000000000808B), SPH_C64(0x0000000080000001),
SPH_C64(0x8000000080008081), SPH_C64(0x8000000000008009),
SPH_C64(0x000000000000008A), SPH_C64(0x0000000000000088),
SPH_C64(0x0000000080008009), SPH_C64(0x000000008000000A),
SPH_C64(0x000000008000808B), SPH_C64(0x800000000000008B),
SPH_C64(0x8000000000008089), SPH_C64(0x8000000000008003),
SPH_C64(0x8000000000008002), SPH_C64(0x8000000000000080),
SPH_C64(0x000000000000800A), SPH_C64(0x800000008000000A),
SPH_C64(0x8000000080008081), SPH_C64(0x8000000000008080),
SPH_C64(0x0000000080000001), SPH_C64(0x8000000080008008)
};
#if SPH_KECCAK_NOCOPY
#define a00 (kc->u.wide[ 0])
#define a10 (kc->u.wide[ 1])
#define a20 (kc->u.wide[ 2])
#define a30 (kc->u.wide[ 3])
#define a40 (kc->u.wide[ 4])
#define a01 (kc->u.wide[ 5])
#define a11 (kc->u.wide[ 6])
#define a21 (kc->u.wide[ 7])
#define a31 (kc->u.wide[ 8])
#define a41 (kc->u.wide[ 9])
#define a02 (kc->u.wide[10])
#define a12 (kc->u.wide[11])
#define a22 (kc->u.wide[12])
#define a32 (kc->u.wide[13])
#define a42 (kc->u.wide[14])
#define a03 (kc->u.wide[15])
#define a13 (kc->u.wide[16])
#define a23 (kc->u.wide[17])
#define a33 (kc->u.wide[18])
#define a43 (kc->u.wide[19])
#define a04 (kc->u.wide[20])
#define a14 (kc->u.wide[21])
#define a24 (kc->u.wide[22])
#define a34 (kc->u.wide[23])
#define a44 (kc->u.wide[24])
#define DECL_STATE
#define READ_STATE(sc)
#define WRITE_STATE(sc)
#define INPUT_BUF(size) do { \
size_t j; \
for (j = 0; j < (size); j += 8) { \
kc->u.wide[j >> 3] ^= sph_dec64le_aligned(buf + j); \
} \
} while (0)
#define INPUT_BUF144 INPUT_BUF(144)
#define INPUT_BUF136 INPUT_BUF(136)
#define INPUT_BUF104 INPUT_BUF(104)
#define INPUT_BUF72 INPUT_BUF(72)
#else
#define DECL_STATE \
sph_u64 a00, a01, a02, a03, a04; \
sph_u64 a10, a11, a12, a13, a14; \
sph_u64 a20, a21, a22, a23, a24; \
sph_u64 a30, a31, a32, a33, a34; \
sph_u64 a40, a41, a42, a43, a44;
#define READ_STATE(state) do { \
a00 = (state)->u.wide[ 0]; \
a10 = (state)->u.wide[ 1]; \
a20 = (state)->u.wide[ 2]; \
a30 = (state)->u.wide[ 3]; \
a40 = (state)->u.wide[ 4]; \
a01 = (state)->u.wide[ 5]; \
a11 = (state)->u.wide[ 6]; \
a21 = (state)->u.wide[ 7]; \
a31 = (state)->u.wide[ 8]; \
a41 = (state)->u.wide[ 9]; \
a02 = (state)->u.wide[10]; \
a12 = (state)->u.wide[11]; \
a22 = (state)->u.wide[12]; \
a32 = (state)->u.wide[13]; \
a42 = (state)->u.wide[14]; \
a03 = (state)->u.wide[15]; \
a13 = (state)->u.wide[16]; \
a23 = (state)->u.wide[17]; \
a33 = (state)->u.wide[18]; \
a43 = (state)->u.wide[19]; \
a04 = (state)->u.wide[20]; \
a14 = (state)->u.wide[21]; \
a24 = (state)->u.wide[22]; \
a34 = (state)->u.wide[23]; \
a44 = (state)->u.wide[24]; \
} while (0)
#define WRITE_STATE(state) do { \
(state)->u.wide[ 0] = a00; \
(state)->u.wide[ 1] = a10; \
(state)->u.wide[ 2] = a20; \
(state)->u.wide[ 3] = a30; \
(state)->u.wide[ 4] = a40; \
(state)->u.wide[ 5] = a01; \
(state)->u.wide[ 6] = a11; \
(state)->u.wide[ 7] = a21; \
(state)->u.wide[ 8] = a31; \
(state)->u.wide[ 9] = a41; \
(state)->u.wide[10] = a02; \
(state)->u.wide[11] = a12; \
(state)->u.wide[12] = a22; \
(state)->u.wide[13] = a32; \
(state)->u.wide[14] = a42; \
(state)->u.wide[15] = a03; \
(state)->u.wide[16] = a13; \
(state)->u.wide[17] = a23; \
(state)->u.wide[18] = a33; \
(state)->u.wide[19] = a43; \
(state)->u.wide[20] = a04; \
(state)->u.wide[21] = a14; \
(state)->u.wide[22] = a24; \
(state)->u.wide[23] = a34; \
(state)->u.wide[24] = a44; \
} while (0)
#define INPUT_BUF144 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
a32 ^= sph_dec64le_aligned(buf + 104); \
a42 ^= sph_dec64le_aligned(buf + 112); \
a03 ^= sph_dec64le_aligned(buf + 120); \
a13 ^= sph_dec64le_aligned(buf + 128); \
a23 ^= sph_dec64le_aligned(buf + 136); \
} while (0)
#define INPUT_BUF136 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
a32 ^= sph_dec64le_aligned(buf + 104); \
a42 ^= sph_dec64le_aligned(buf + 112); \
a03 ^= sph_dec64le_aligned(buf + 120); \
a13 ^= sph_dec64le_aligned(buf + 128); \
} while (0)
#define INPUT_BUF104 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
} while (0)
#define INPUT_BUF72 do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
} while (0)
#define INPUT_BUF(lim) do { \
a00 ^= sph_dec64le_aligned(buf + 0); \
a10 ^= sph_dec64le_aligned(buf + 8); \
a20 ^= sph_dec64le_aligned(buf + 16); \
a30 ^= sph_dec64le_aligned(buf + 24); \
a40 ^= sph_dec64le_aligned(buf + 32); \
a01 ^= sph_dec64le_aligned(buf + 40); \
a11 ^= sph_dec64le_aligned(buf + 48); \
a21 ^= sph_dec64le_aligned(buf + 56); \
a31 ^= sph_dec64le_aligned(buf + 64); \
if ((lim) == 72) \
break; \
a41 ^= sph_dec64le_aligned(buf + 72); \
a02 ^= sph_dec64le_aligned(buf + 80); \
a12 ^= sph_dec64le_aligned(buf + 88); \
a22 ^= sph_dec64le_aligned(buf + 96); \
if ((lim) == 104) \
break; \
a32 ^= sph_dec64le_aligned(buf + 104); \
a42 ^= sph_dec64le_aligned(buf + 112); \
a03 ^= sph_dec64le_aligned(buf + 120); \
a13 ^= sph_dec64le_aligned(buf + 128); \
if ((lim) == 136) \
break; \
a23 ^= sph_dec64le_aligned(buf + 136); \
} while (0)
#endif
#define DECL64(x) sph_u64 x
#define MOV64(d, s) (d = s)
#define XOR64(d, a, b) (d = a ^ b)
#define AND64(d, a, b) (d = a & b)
#define OR64(d, a, b) (d = a | b)
#define NOT64(d, s) (d = SPH_T64(~s))
#define ROL64(d, v, n) (d = SPH_ROTL64(v, n))
#define XOR64_IOTA XOR64
#else
static const struct {
sph_u32 high, low;
} RC[] = {
#if SPH_KECCAK_INTERLEAVE
{ SPH_C32(0x00000000), SPH_C32(0x00000001) },
{ SPH_C32(0x00000089), SPH_C32(0x00000000) },
{ SPH_C32(0x8000008B), SPH_C32(0x00000000) },
{ SPH_C32(0x80008080), SPH_C32(0x00000000) },
{ SPH_C32(0x0000008B), SPH_C32(0x00000001) },
{ SPH_C32(0x00008000), SPH_C32(0x00000001) },
{ SPH_C32(0x80008088), SPH_C32(0x00000001) },
{ SPH_C32(0x80000082), SPH_C32(0x00000001) },
{ SPH_C32(0x0000000B), SPH_C32(0x00000000) },
{ SPH_C32(0x0000000A), SPH_C32(0x00000000) },
{ SPH_C32(0x00008082), SPH_C32(0x00000001) },
{ SPH_C32(0x00008003), SPH_C32(0x00000000) },
{ SPH_C32(0x0000808B), SPH_C32(0x00000001) },
{ SPH_C32(0x8000000B), SPH_C32(0x00000001) },
{ SPH_C32(0x8000008A), SPH_C32(0x00000001) },
{ SPH_C32(0x80000081), SPH_C32(0x00000001) },
{ SPH_C32(0x80000081), SPH_C32(0x00000000) },
{ SPH_C32(0x80000008), SPH_C32(0x00000000) },
{ SPH_C32(0x00000083), SPH_C32(0x00000000) },
{ SPH_C32(0x80008003), SPH_C32(0x00000000) },
{ SPH_C32(0x80008088), SPH_C32(0x00000001) },
{ SPH_C32(0x80000088), SPH_C32(0x00000000) },
{ SPH_C32(0x00008000), SPH_C32(0x00000001) },
{ SPH_C32(0x80008082), SPH_C32(0x00000000) }
#else
{ SPH_C32(0x00000000), SPH_C32(0x00000001) },
{ SPH_C32(0x00000000), SPH_C32(0x00008082) },
{ SPH_C32(0x80000000), SPH_C32(0x0000808A) },
{ SPH_C32(0x80000000), SPH_C32(0x80008000) },
{ SPH_C32(0x00000000), SPH_C32(0x0000808B) },
{ SPH_C32(0x00000000), SPH_C32(0x80000001) },
{ SPH_C32(0x80000000), SPH_C32(0x80008081) },
{ SPH_C32(0x80000000), SPH_C32(0x00008009) },
{ SPH_C32(0x00000000), SPH_C32(0x0000008A) },
{ SPH_C32(0x00000000), SPH_C32(0x00000088) },
{ SPH_C32(0x00000000), SPH_C32(0x80008009) },
{ SPH_C32(0x00000000), SPH_C32(0x8000000A) },
{ SPH_C32(0x00000000), SPH_C32(0x8000808B) },
{ SPH_C32(0x80000000), SPH_C32(0x0000008B) },
{ SPH_C32(0x80000000), SPH_C32(0x00008089) },
{ SPH_C32(0x80000000), SPH_C32(0x00008003) },
{ SPH_C32(0x80000000), SPH_C32(0x00008002) },
{ SPH_C32(0x80000000), SPH_C32(0x00000080) },
{ SPH_C32(0x00000000), SPH_C32(0x0000800A) },
{ SPH_C32(0x80000000), SPH_C32(0x8000000A) },
{ SPH_C32(0x80000000), SPH_C32(0x80008081) },
{ SPH_C32(0x80000000), SPH_C32(0x00008080) },
{ SPH_C32(0x00000000), SPH_C32(0x80000001) },
{ SPH_C32(0x80000000), SPH_C32(0x80008008) }
#endif
};
#if SPH_KECCAK_INTERLEAVE
#define INTERLEAVE(xl, xh) do { \
sph_u32 l, h, t; \
l = (xl); h = (xh); \
t = (l ^ (l >> 1)) & SPH_C32(0x22222222); l ^= t ^ (t << 1); \
t = (h ^ (h >> 1)) & SPH_C32(0x22222222); h ^= t ^ (t << 1); \
t = (l ^ (l >> 2)) & SPH_C32(0x0C0C0C0C); l ^= t ^ (t << 2); \
t = (h ^ (h >> 2)) & SPH_C32(0x0C0C0C0C); h ^= t ^ (t << 2); \
t = (l ^ (l >> 4)) & SPH_C32(0x00F000F0); l ^= t ^ (t << 4); \
t = (h ^ (h >> 4)) & SPH_C32(0x00F000F0); h ^= t ^ (t << 4); \
t = (l ^ (l >> 8)) & SPH_C32(0x0000FF00); l ^= t ^ (t << 8); \
t = (h ^ (h >> 8)) & SPH_C32(0x0000FF00); h ^= t ^ (t << 8); \
t = (l ^ SPH_T32(h << 16)) & SPH_C32(0xFFFF0000); \
l ^= t; h ^= t >> 16; \
(xl) = l; (xh) = h; \
} while (0)
#define UNINTERLEAVE(xl, xh) do { \
sph_u32 l, h, t; \
l = (xl); h = (xh); \
t = (l ^ SPH_T32(h << 16)) & SPH_C32(0xFFFF0000); \
l ^= t; h ^= t >> 16; \
t = (l ^ (l >> 8)) & SPH_C32(0x0000FF00); l ^= t ^ (t << 8); \
t = (h ^ (h >> 8)) & SPH_C32(0x0000FF00); h ^= t ^ (t << 8); \
t = (l ^ (l >> 4)) & SPH_C32(0x00F000F0); l ^= t ^ (t << 4); \
t = (h ^ (h >> 4)) & SPH_C32(0x00F000F0); h ^= t ^ (t << 4); \
t = (l ^ (l >> 2)) & SPH_C32(0x0C0C0C0C); l ^= t ^ (t << 2); \
t = (h ^ (h >> 2)) & SPH_C32(0x0C0C0C0C); h ^= t ^ (t << 2); \
t = (l ^ (l >> 1)) & SPH_C32(0x22222222); l ^= t ^ (t << 1); \
t = (h ^ (h >> 1)) & SPH_C32(0x22222222); h ^= t ^ (t << 1); \
(xl) = l; (xh) = h; \
} while (0)
#else
#define INTERLEAVE(l, h)
#define UNINTERLEAVE(l, h)
#endif
#if SPH_KECCAK_NOCOPY
#define a00l (kc->u.narrow[2 * 0 + 0])
#define a00h (kc->u.narrow[2 * 0 + 1])
#define a10l (kc->u.narrow[2 * 1 + 0])
#define a10h (kc->u.narrow[2 * 1 + 1])
#define a20l (kc->u.narrow[2 * 2 + 0])
#define a20h (kc->u.narrow[2 * 2 + 1])
#define a30l (kc->u.narrow[2 * 3 + 0])
#define a30h (kc->u.narrow[2 * 3 + 1])
#define a40l (kc->u.narrow[2 * 4 + 0])
#define a40h (kc->u.narrow[2 * 4 + 1])
#define a01l (kc->u.narrow[2 * 5 + 0])
#define a01h (kc->u.narrow[2 * 5 + 1])
#define a11l (kc->u.narrow[2 * 6 + 0])
#define a11h (kc->u.narrow[2 * 6 + 1])
#define a21l (kc->u.narrow[2 * 7 + 0])
#define a21h (kc->u.narrow[2 * 7 + 1])
#define a31l (kc->u.narrow[2 * 8 + 0])
#define a31h (kc->u.narrow[2 * 8 + 1])
#define a41l (kc->u.narrow[2 * 9 + 0])
#define a41h (kc->u.narrow[2 * 9 + 1])
#define a02l (kc->u.narrow[2 * 10 + 0])
#define a02h (kc->u.narrow[2 * 10 + 1])
#define a12l (kc->u.narrow[2 * 11 + 0])
#define a12h (kc->u.narrow[2 * 11 + 1])
#define a22l (kc->u.narrow[2 * 12 + 0])
#define a22h (kc->u.narrow[2 * 12 + 1])
#define a32l (kc->u.narrow[2 * 13 + 0])
#define a32h (kc->u.narrow[2 * 13 + 1])
#define a42l (kc->u.narrow[2 * 14 + 0])
#define a42h (kc->u.narrow[2 * 14 + 1])
#define a03l (kc->u.narrow[2 * 15 + 0])
#define a03h (kc->u.narrow[2 * 15 + 1])
#define a13l (kc->u.narrow[2 * 16 + 0])
#define a13h (kc->u.narrow[2 * 16 + 1])
#define a23l (kc->u.narrow[2 * 17 + 0])
#define a23h (kc->u.narrow[2 * 17 + 1])
#define a33l (kc->u.narrow[2 * 18 + 0])
#define a33h (kc->u.narrow[2 * 18 + 1])
#define a43l (kc->u.narrow[2 * 19 + 0])
#define a43h (kc->u.narrow[2 * 19 + 1])
#define a04l (kc->u.narrow[2 * 20 + 0])
#define a04h (kc->u.narrow[2 * 20 + 1])
#define a14l (kc->u.narrow[2 * 21 + 0])
#define a14h (kc->u.narrow[2 * 21 + 1])
#define a24l (kc->u.narrow[2 * 22 + 0])
#define a24h (kc->u.narrow[2 * 22 + 1])
#define a34l (kc->u.narrow[2 * 23 + 0])
#define a34h (kc->u.narrow[2 * 23 + 1])
#define a44l (kc->u.narrow[2 * 24 + 0])
#define a44h (kc->u.narrow[2 * 24 + 1])
#define DECL_STATE
#define READ_STATE(state)
#define WRITE_STATE(state)
#define INPUT_BUF(size) do { \
size_t j; \
for (j = 0; j < (size); j += 8) { \
sph_u32 tl, th; \
tl = sph_dec32le_aligned(buf + j + 0); \
th = sph_dec32le_aligned(buf + j + 4); \
INTERLEAVE(tl, th); \
kc->u.narrow[(j >> 2) + 0] ^= tl; \
kc->u.narrow[(j >> 2) + 1] ^= th; \
} \
} while (0)
#define INPUT_BUF144 INPUT_BUF(144)
#define INPUT_BUF136 INPUT_BUF(136)
#define INPUT_BUF104 INPUT_BUF(104)
#define INPUT_BUF72 INPUT_BUF(72)
#else
#define DECL_STATE \
sph_u32 a00l, a00h, a01l, a01h, a02l, a02h, a03l, a03h, a04l, a04h; \
sph_u32 a10l, a10h, a11l, a11h, a12l, a12h, a13l, a13h, a14l, a14h; \
sph_u32 a20l, a20h, a21l, a21h, a22l, a22h, a23l, a23h, a24l, a24h; \
sph_u32 a30l, a30h, a31l, a31h, a32l, a32h, a33l, a33h, a34l, a34h; \
sph_u32 a40l, a40h, a41l, a41h, a42l, a42h, a43l, a43h, a44l, a44h;
#define READ_STATE(state) do { \
a00l = (state)->u.narrow[2 * 0 + 0]; \
a00h = (state)->u.narrow[2 * 0 + 1]; \
a10l = (state)->u.narrow[2 * 1 + 0]; \
a10h = (state)->u.narrow[2 * 1 + 1]; \
a20l = (state)->u.narrow[2 * 2 + 0]; \
a20h = (state)->u.narrow[2 * 2 + 1]; \
a30l = (state)->u.narrow[2 * 3 + 0]; \
a30h = (state)->u.narrow[2 * 3 + 1]; \
a40l = (state)->u.narrow[2 * 4 + 0]; \
a40h = (state)->u.narrow[2 * 4 + 1]; \
a01l = (state)->u.narrow[2 * 5 + 0]; \
a01h = (state)->u.narrow[2 * 5 + 1]; \
a11l = (state)->u.narrow[2 * 6 + 0]; \
a11h = (state)->u.narrow[2 * 6 + 1]; \
a21l = (state)->u.narrow[2 * 7 + 0]; \
a21h = (state)->u.narrow[2 * 7 + 1]; \
a31l = (state)->u.narrow[2 * 8 + 0]; \
a31h = (state)->u.narrow[2 * 8 + 1]; \
a41l = (state)->u.narrow[2 * 9 + 0]; \
a41h = (state)->u.narrow[2 * 9 + 1]; \
a02l = (state)->u.narrow[2 * 10 + 0]; \
a02h = (state)->u.narrow[2 * 10 + 1]; \
a12l = (state)->u.narrow[2 * 11 + 0]; \
a12h = (state)->u.narrow[2 * 11 + 1]; \
a22l = (state)->u.narrow[2 * 12 + 0]; \
a22h = (state)->u.narrow[2 * 12 + 1]; \
a32l = (state)->u.narrow[2 * 13 + 0]; \
a32h = (state)->u.narrow[2 * 13 + 1]; \
a42l = (state)->u.narrow[2 * 14 + 0]; \
a42h = (state)->u.narrow[2 * 14 + 1]; \
a03l = (state)->u.narrow[2 * 15 + 0]; \
a03h = (state)->u.narrow[2 * 15 + 1]; \
a13l = (state)->u.narrow[2 * 16 + 0]; \
a13h = (state)->u.narrow[2 * 16 + 1]; \
a23l = (state)->u.narrow[2 * 17 + 0]; \
a23h = (state)->u.narrow[2 * 17 + 1]; \
a33l = (state)->u.narrow[2 * 18 + 0]; \
a33h = (state)->u.narrow[2 * 18 + 1]; \
a43l = (state)->u.narrow[2 * 19 + 0]; \
a43h = (state)->u.narrow[2 * 19 + 1]; \
a04l = (state)->u.narrow[2 * 20 + 0]; \
a04h = (state)->u.narrow[2 * 20 + 1]; \
a14l = (state)->u.narrow[2 * 21 + 0]; \
a14h = (state)->u.narrow[2 * 21 + 1]; \
a24l = (state)->u.narrow[2 * 22 + 0]; \
a24h = (state)->u.narrow[2 * 22 + 1]; \
a34l = (state)->u.narrow[2 * 23 + 0]; \
a34h = (state)->u.narrow[2 * 23 + 1]; \
a44l = (state)->u.narrow[2 * 24 + 0]; \
a44h = (state)->u.narrow[2 * 24 + 1]; \
} while (0)
#define WRITE_STATE(state) do { \
(state)->u.narrow[2 * 0 + 0] = a00l; \
(state)->u.narrow[2 * 0 + 1] = a00h; \
(state)->u.narrow[2 * 1 + 0] = a10l; \
(state)->u.narrow[2 * 1 + 1] = a10h; \
(state)->u.narrow[2 * 2 + 0] = a20l; \
(state)->u.narrow[2 * 2 + 1] = a20h; \
(state)->u.narrow[2 * 3 + 0] = a30l; \
(state)->u.narrow[2 * 3 + 1] = a30h; \
(state)->u.narrow[2 * 4 + 0] = a40l; \
(state)->u.narrow[2 * 4 + 1] = a40h; \
(state)->u.narrow[2 * 5 + 0] = a01l; \
(state)->u.narrow[2 * 5 + 1] = a01h; \
(state)->u.narrow[2 * 6 + 0] = a11l; \
(state)->u.narrow[2 * 6 + 1] = a11h; \
(state)->u.narrow[2 * 7 + 0] = a21l; \
(state)->u.narrow[2 * 7 + 1] = a21h; \
(state)->u.narrow[2 * 8 + 0] = a31l; \
(state)->u.narrow[2 * 8 + 1] = a31h; \
(state)->u.narrow[2 * 9 + 0] = a41l; \
(state)->u.narrow[2 * 9 + 1] = a41h; \
(state)->u.narrow[2 * 10 + 0] = a02l; \
(state)->u.narrow[2 * 10 + 1] = a02h; \
(state)->u.narrow[2 * 11 + 0] = a12l; \
(state)->u.narrow[2 * 11 + 1] = a12h; \
(state)->u.narrow[2 * 12 + 0] = a22l; \
(state)->u.narrow[2 * 12 + 1] = a22h; \
(state)->u.narrow[2 * 13 + 0] = a32l; \
(state)->u.narrow[2 * 13 + 1] = a32h; \
(state)->u.narrow[2 * 14 + 0] = a42l; \
(state)->u.narrow[2 * 14 + 1] = a42h; \
(state)->u.narrow[2 * 15 + 0] = a03l; \
(state)->u.narrow[2 * 15 + 1] = a03h; \
(state)->u.narrow[2 * 16 + 0] = a13l; \
(state)->u.narrow[2 * 16 + 1] = a13h; \
(state)->u.narrow[2 * 17 + 0] = a23l; \
(state)->u.narrow[2 * 17 + 1] = a23h; \
(state)->u.narrow[2 * 18 + 0] = a33l; \
(state)->u.narrow[2 * 18 + 1] = a33h; \
(state)->u.narrow[2 * 19 + 0] = a43l; \
(state)->u.narrow[2 * 19 + 1] = a43h; \
(state)->u.narrow[2 * 20 + 0] = a04l; \
(state)->u.narrow[2 * 20 + 1] = a04h; \
(state)->u.narrow[2 * 21 + 0] = a14l; \
(state)->u.narrow[2 * 21 + 1] = a14h; \
(state)->u.narrow[2 * 22 + 0] = a24l; \
(state)->u.narrow[2 * 22 + 1] = a24h; \
(state)->u.narrow[2 * 23 + 0] = a34l; \
(state)->u.narrow[2 * 23 + 1] = a34h; \
(state)->u.narrow[2 * 24 + 0] = a44l; \
(state)->u.narrow[2 * 24 + 1] = a44h; \
} while (0)
#define READ64(d, off) do { \
sph_u32 tl, th; \
tl = sph_dec32le_aligned(buf + (off)); \
th = sph_dec32le_aligned(buf + (off) + 4); \
INTERLEAVE(tl, th); \
d ## l ^= tl; \
d ## h ^= th; \
} while (0)
#define INPUT_BUF144 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
READ64(a32, 104); \
READ64(a42, 112); \
READ64(a03, 120); \
READ64(a13, 128); \
READ64(a23, 136); \
} while (0)
#define INPUT_BUF136 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
READ64(a32, 104); \
READ64(a42, 112); \
READ64(a03, 120); \
READ64(a13, 128); \
} while (0)
#define INPUT_BUF104 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
} while (0)
#define INPUT_BUF72 do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
} while (0)
#define INPUT_BUF(lim) do { \
READ64(a00, 0); \
READ64(a10, 8); \
READ64(a20, 16); \
READ64(a30, 24); \
READ64(a40, 32); \
READ64(a01, 40); \
READ64(a11, 48); \
READ64(a21, 56); \
READ64(a31, 64); \
if ((lim) == 72) \
break; \
READ64(a41, 72); \
READ64(a02, 80); \
READ64(a12, 88); \
READ64(a22, 96); \
if ((lim) == 104) \
break; \
READ64(a32, 104); \
READ64(a42, 112); \
READ64(a03, 120); \
READ64(a13, 128); \
if ((lim) == 136) \
break; \
READ64(a23, 136); \
} while (0)
#endif
#define DECL64(x) sph_u64 x ## l, x ## h
#define MOV64(d, s) (d ## l = s ## l, d ## h = s ## h)
#define XOR64(d, a, b) (d ## l = a ## l ^ b ## l, d ## h = a ## h ^ b ## h)
#define AND64(d, a, b) (d ## l = a ## l & b ## l, d ## h = a ## h & b ## h)
#define OR64(d, a, b) (d ## l = a ## l | b ## l, d ## h = a ## h | b ## h)
#define NOT64(d, s) (d ## l = SPH_T32(~s ## l), d ## h = SPH_T32(~s ## h))
#define ROL64(d, v, n) ROL64_ ## n(d, v)
#if SPH_KECCAK_INTERLEAVE
#define ROL64_odd1(d, v) do { \
sph_u32 tmp; \
tmp = v ## l; \
d ## l = SPH_T32(v ## h << 1) | (v ## h >> 31); \
d ## h = tmp; \
} while (0)
#define ROL64_odd63(d, v) do { \
sph_u32 tmp; \
tmp = SPH_T32(v ## l << 31) | (v ## l >> 1); \
d ## l = v ## h; \
d ## h = tmp; \
} while (0)
#define ROL64_odd(d, v, n) do { \
sph_u32 tmp; \
tmp = SPH_T32(v ## l << (n - 1)) | (v ## l >> (33 - n)); \
d ## l = SPH_T32(v ## h << n) | (v ## h >> (32 - n)); \
d ## h = tmp; \
} while (0)
#define ROL64_even(d, v, n) do { \
d ## l = SPH_T32(v ## l << n) | (v ## l >> (32 - n)); \
d ## h = SPH_T32(v ## h << n) | (v ## h >> (32 - n)); \
} while (0)
#define ROL64_0(d, v)
#define ROL64_1(d, v) ROL64_odd1(d, v)
#define ROL64_2(d, v) ROL64_even(d, v, 1)
#define ROL64_3(d, v) ROL64_odd( d, v, 2)
#define ROL64_4(d, v) ROL64_even(d, v, 2)
#define ROL64_5(d, v) ROL64_odd( d, v, 3)
#define ROL64_6(d, v) ROL64_even(d, v, 3)
#define ROL64_7(d, v) ROL64_odd( d, v, 4)
#define ROL64_8(d, v) ROL64_even(d, v, 4)
#define ROL64_9(d, v) ROL64_odd( d, v, 5)
#define ROL64_10(d, v) ROL64_even(d, v, 5)
#define ROL64_11(d, v) ROL64_odd( d, v, 6)
#define ROL64_12(d, v) ROL64_even(d, v, 6)
#define ROL64_13(d, v) ROL64_odd( d, v, 7)
#define ROL64_14(d, v) ROL64_even(d, v, 7)
#define ROL64_15(d, v) ROL64_odd( d, v, 8)
#define ROL64_16(d, v) ROL64_even(d, v, 8)
#define ROL64_17(d, v) ROL64_odd( d, v, 9)
#define ROL64_18(d, v) ROL64_even(d, v, 9)
#define ROL64_19(d, v) ROL64_odd( d, v, 10)
#define ROL64_20(d, v) ROL64_even(d, v, 10)
#define ROL64_21(d, v) ROL64_odd( d, v, 11)
#define ROL64_22(d, v) ROL64_even(d, v, 11)
#define ROL64_23(d, v) ROL64_odd( d, v, 12)
#define ROL64_24(d, v) ROL64_even(d, v, 12)
#define ROL64_25(d, v) ROL64_odd( d, v, 13)
#define ROL64_26(d, v) ROL64_even(d, v, 13)
#define ROL64_27(d, v) ROL64_odd( d, v, 14)
#define ROL64_28(d, v) ROL64_even(d, v, 14)
#define ROL64_29(d, v) ROL64_odd( d, v, 15)
#define ROL64_30(d, v) ROL64_even(d, v, 15)
#define ROL64_31(d, v) ROL64_odd( d, v, 16)
#define ROL64_32(d, v) ROL64_even(d, v, 16)
#define ROL64_33(d, v) ROL64_odd( d, v, 17)
#define ROL64_34(d, v) ROL64_even(d, v, 17)
#define ROL64_35(d, v) ROL64_odd( d, v, 18)
#define ROL64_36(d, v) ROL64_even(d, v, 18)
#define ROL64_37(d, v) ROL64_odd( d, v, 19)
#define ROL64_38(d, v) ROL64_even(d, v, 19)
#define ROL64_39(d, v) ROL64_odd( d, v, 20)
#define ROL64_40(d, v) ROL64_even(d, v, 20)
#define ROL64_41(d, v) ROL64_odd( d, v, 21)
#define ROL64_42(d, v) ROL64_even(d, v, 21)
#define ROL64_43(d, v) ROL64_odd( d, v, 22)
#define ROL64_44(d, v) ROL64_even(d, v, 22)
#define ROL64_45(d, v) ROL64_odd( d, v, 23)
#define ROL64_46(d, v) ROL64_even(d, v, 23)
#define ROL64_47(d, v) ROL64_odd( d, v, 24)
#define ROL64_48(d, v) ROL64_even(d, v, 24)
#define ROL64_49(d, v) ROL64_odd( d, v, 25)
#define ROL64_50(d, v) ROL64_even(d, v, 25)
#define ROL64_51(d, v) ROL64_odd( d, v, 26)
#define ROL64_52(d, v) ROL64_even(d, v, 26)
#define ROL64_53(d, v) ROL64_odd( d, v, 27)
#define ROL64_54(d, v) ROL64_even(d, v, 27)
#define ROL64_55(d, v) ROL64_odd( d, v, 28)
#define ROL64_56(d, v) ROL64_even(d, v, 28)
#define ROL64_57(d, v) ROL64_odd( d, v, 29)
#define ROL64_58(d, v) ROL64_even(d, v, 29)
#define ROL64_59(d, v) ROL64_odd( d, v, 30)
#define ROL64_60(d, v) ROL64_even(d, v, 30)
#define ROL64_61(d, v) ROL64_odd( d, v, 31)
#define ROL64_62(d, v) ROL64_even(d, v, 31)
#define ROL64_63(d, v) ROL64_odd63(d, v)
#else
#define ROL64_small(d, v, n) do { \
sph_u32 tmp; \
tmp = SPH_T32(v ## l << n) | (v ## h >> (32 - n)); \
d ## h = SPH_T32(v ## h << n) | (v ## l >> (32 - n)); \
d ## l = tmp; \
} while (0)
#define ROL64_0(d, v) 0
#define ROL64_1(d, v) ROL64_small(d, v, 1)
#define ROL64_2(d, v) ROL64_small(d, v, 2)
#define ROL64_3(d, v) ROL64_small(d, v, 3)
#define ROL64_4(d, v) ROL64_small(d, v, 4)
#define ROL64_5(d, v) ROL64_small(d, v, 5)
#define ROL64_6(d, v) ROL64_small(d, v, 6)
#define ROL64_7(d, v) ROL64_small(d, v, 7)
#define ROL64_8(d, v) ROL64_small(d, v, 8)
#define ROL64_9(d, v) ROL64_small(d, v, 9)
#define ROL64_10(d, v) ROL64_small(d, v, 10)
#define ROL64_11(d, v) ROL64_small(d, v, 11)
#define ROL64_12(d, v) ROL64_small(d, v, 12)
#define ROL64_13(d, v) ROL64_small(d, v, 13)
#define ROL64_14(d, v) ROL64_small(d, v, 14)
#define ROL64_15(d, v) ROL64_small(d, v, 15)
#define ROL64_16(d, v) ROL64_small(d, v, 16)
#define ROL64_17(d, v) ROL64_small(d, v, 17)
#define ROL64_18(d, v) ROL64_small(d, v, 18)
#define ROL64_19(d, v) ROL64_small(d, v, 19)
#define ROL64_20(d, v) ROL64_small(d, v, 20)
#define ROL64_21(d, v) ROL64_small(d, v, 21)
#define ROL64_22(d, v) ROL64_small(d, v, 22)
#define ROL64_23(d, v) ROL64_small(d, v, 23)
#define ROL64_24(d, v) ROL64_small(d, v, 24)
#define ROL64_25(d, v) ROL64_small(d, v, 25)
#define ROL64_26(d, v) ROL64_small(d, v, 26)
#define ROL64_27(d, v) ROL64_small(d, v, 27)
#define ROL64_28(d, v) ROL64_small(d, v, 28)
#define ROL64_29(d, v) ROL64_small(d, v, 29)
#define ROL64_30(d, v) ROL64_small(d, v, 30)
#define ROL64_31(d, v) ROL64_small(d, v, 31)
#define ROL64_32(d, v) do { \
sph_u32 tmp; \
tmp = v ## l; \
d ## l = v ## h; \
d ## h = tmp; \
} while (0)
#define ROL64_big(d, v, n) do { \
sph_u32 trl, trh; \
ROL64_small(tr, v, n); \
d ## h = trl; \
d ## l = trh; \
} while (0)
#define ROL64_33(d, v) ROL64_big(d, v, 1)
#define ROL64_34(d, v) ROL64_big(d, v, 2)
#define ROL64_35(d, v) ROL64_big(d, v, 3)
#define ROL64_36(d, v) ROL64_big(d, v, 4)
#define ROL64_37(d, v) ROL64_big(d, v, 5)
#define ROL64_38(d, v) ROL64_big(d, v, 6)
#define ROL64_39(d, v) ROL64_big(d, v, 7)
#define ROL64_40(d, v) ROL64_big(d, v, 8)
#define ROL64_41(d, v) ROL64_big(d, v, 9)
#define ROL64_42(d, v) ROL64_big(d, v, 10)
#define ROL64_43(d, v) ROL64_big(d, v, 11)
#define ROL64_44(d, v) ROL64_big(d, v, 12)
#define ROL64_45(d, v) ROL64_big(d, v, 13)
#define ROL64_46(d, v) ROL64_big(d, v, 14)
#define ROL64_47(d, v) ROL64_big(d, v, 15)
#define ROL64_48(d, v) ROL64_big(d, v, 16)
#define ROL64_49(d, v) ROL64_big(d, v, 17)
#define ROL64_50(d, v) ROL64_big(d, v, 18)
#define ROL64_51(d, v) ROL64_big(d, v, 19)
#define ROL64_52(d, v) ROL64_big(d, v, 20)
#define ROL64_53(d, v) ROL64_big(d, v, 21)
#define ROL64_54(d, v) ROL64_big(d, v, 22)
#define ROL64_55(d, v) ROL64_big(d, v, 23)
#define ROL64_56(d, v) ROL64_big(d, v, 24)
#define ROL64_57(d, v) ROL64_big(d, v, 25)
#define ROL64_58(d, v) ROL64_big(d, v, 26)
#define ROL64_59(d, v) ROL64_big(d, v, 27)
#define ROL64_60(d, v) ROL64_big(d, v, 28)
#define ROL64_61(d, v) ROL64_big(d, v, 29)
#define ROL64_62(d, v) ROL64_big(d, v, 30)
#define ROL64_63(d, v) ROL64_big(d, v, 31)
#endif
#define XOR64_IOTA(d, s, k) \
(d ## l = s ## l ^ k.low, d ## h = s ## h ^ k.high)
#endif
#define TH_ELT(t, c0, c1, c2, c3, c4, d0, d1, d2, d3, d4) do { \
DECL64(tt0); \
DECL64(tt1); \
DECL64(tt2); \
DECL64(tt3); \
XOR64(tt0, d0, d1); \
XOR64(tt1, d2, d3); \
XOR64(tt0, tt0, d4); \
XOR64(tt0, tt0, tt1); \
ROL64(tt0, tt0, 1); \
XOR64(tt2, c0, c1); \
XOR64(tt3, c2, c3); \
XOR64(tt0, tt0, c4); \
XOR64(tt2, tt2, tt3); \
XOR64(t, tt0, tt2); \
} while (0)
#define THETA(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \
b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \
b40, b41, b42, b43, b44) \
do { \
DECL64(t0); \
DECL64(t1); \
DECL64(t2); \
DECL64(t3); \
DECL64(t4); \
TH_ELT(t0, b40, b41, b42, b43, b44, b10, b11, b12, b13, b14); \
TH_ELT(t1, b00, b01, b02, b03, b04, b20, b21, b22, b23, b24); \
TH_ELT(t2, b10, b11, b12, b13, b14, b30, b31, b32, b33, b34); \
TH_ELT(t3, b20, b21, b22, b23, b24, b40, b41, b42, b43, b44); \
TH_ELT(t4, b30, b31, b32, b33, b34, b00, b01, b02, b03, b04); \
XOR64(b00, b00, t0); \
XOR64(b01, b01, t0); \
XOR64(b02, b02, t0); \
XOR64(b03, b03, t0); \
XOR64(b04, b04, t0); \
XOR64(b10, b10, t1); \
XOR64(b11, b11, t1); \
XOR64(b12, b12, t1); \
XOR64(b13, b13, t1); \
XOR64(b14, b14, t1); \
XOR64(b20, b20, t2); \
XOR64(b21, b21, t2); \
XOR64(b22, b22, t2); \
XOR64(b23, b23, t2); \
XOR64(b24, b24, t2); \
XOR64(b30, b30, t3); \
XOR64(b31, b31, t3); \
XOR64(b32, b32, t3); \
XOR64(b33, b33, t3); \
XOR64(b34, b34, t3); \
XOR64(b40, b40, t4); \
XOR64(b41, b41, t4); \
XOR64(b42, b42, t4); \
XOR64(b43, b43, t4); \
XOR64(b44, b44, t4); \
} while (0)
#define RHO(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \
b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \
b40, b41, b42, b43, b44) \
do { \
/* ROL64(b00, b00, 0); */ \
ROL64(b01, b01, 36); \
ROL64(b02, b02, 3); \
ROL64(b03, b03, 41); \
ROL64(b04, b04, 18); \
ROL64(b10, b10, 1); \
ROL64(b11, b11, 44); \
ROL64(b12, b12, 10); \
ROL64(b13, b13, 45); \
ROL64(b14, b14, 2); \
ROL64(b20, b20, 62); \
ROL64(b21, b21, 6); \
ROL64(b22, b22, 43); \
ROL64(b23, b23, 15); \
ROL64(b24, b24, 61); \
ROL64(b30, b30, 28); \
ROL64(b31, b31, 55); \
ROL64(b32, b32, 25); \
ROL64(b33, b33, 21); \
ROL64(b34, b34, 56); \
ROL64(b40, b40, 27); \
ROL64(b41, b41, 20); \
ROL64(b42, b42, 39); \
ROL64(b43, b43, 8); \
ROL64(b44, b44, 14); \
} while (0)
/*
* The KHI macro integrates the "lane complement" optimization. On input,
* some words are complemented:
* a00 a01 a02 a04 a13 a20 a21 a22 a30 a33 a34 a43
* On output, the following words are complemented:
* a04 a10 a20 a22 a23 a31
*
* The (implicit) permutation and the theta expansion will bring back
* the input mask for the next round.
*/
#define KHI_XO(d, a, b, c) do { \
DECL64(kt); \
OR64(kt, b, c); \
XOR64(d, a, kt); \
} while (0)
#define KHI_XA(d, a, b, c) do { \
DECL64(kt); \
AND64(kt, b, c); \
XOR64(d, a, kt); \
} while (0)
#define KHI(b00, b01, b02, b03, b04, b10, b11, b12, b13, b14, \
b20, b21, b22, b23, b24, b30, b31, b32, b33, b34, \
b40, b41, b42, b43, b44) \
do { \
DECL64(c0); \
DECL64(c1); \
DECL64(c2); \
DECL64(c3); \
DECL64(c4); \
DECL64(bnn); \
NOT64(bnn, b20); \
KHI_XO(c0, b00, b10, b20); \
KHI_XO(c1, b10, bnn, b30); \
KHI_XA(c2, b20, b30, b40); \
KHI_XO(c3, b30, b40, b00); \
KHI_XA(c4, b40, b00, b10); \
MOV64(b00, c0); \
MOV64(b10, c1); \
MOV64(b20, c2); \
MOV64(b30, c3); \
MOV64(b40, c4); \
NOT64(bnn, b41); \
KHI_XO(c0, b01, b11, b21); \
KHI_XA(c1, b11, b21, b31); \
KHI_XO(c2, b21, b31, bnn); \
KHI_XO(c3, b31, b41, b01); \
KHI_XA(c4, b41, b01, b11); \
MOV64(b01, c0); \
MOV64(b11, c1); \
MOV64(b21, c2); \
MOV64(b31, c3); \
MOV64(b41, c4); \
NOT64(bnn, b32); \
KHI_XO(c0, b02, b12, b22); \
KHI_XA(c1, b12, b22, b32); \
KHI_XA(c2, b22, bnn, b42); \
KHI_XO(c3, bnn, b42, b02); \
KHI_XA(c4, b42, b02, b12); \
MOV64(b02, c0); \
MOV64(b12, c1); \
MOV64(b22, c2); \
MOV64(b32, c3); \
MOV64(b42, c4); \
NOT64(bnn, b33); \
KHI_XA(c0, b03, b13, b23); \
KHI_XO(c1, b13, b23, b33); \
KHI_XO(c2, b23, bnn, b43); \
KHI_XA(c3, bnn, b43, b03); \
KHI_XO(c4, b43, b03, b13); \
MOV64(b03, c0); \
MOV64(b13, c1); \
MOV64(b23, c2); \
MOV64(b33, c3); \
MOV64(b43, c4); \
NOT64(bnn, b14); \
KHI_XA(c0, b04, bnn, b24); \
KHI_XO(c1, bnn, b24, b34); \
KHI_XA(c2, b24, b34, b44); \
KHI_XO(c3, b34, b44, b04); \
KHI_XA(c4, b44, b04, b14); \
MOV64(b04, c0); \
MOV64(b14, c1); \
MOV64(b24, c2); \
MOV64(b34, c3); \
MOV64(b44, c4); \
} while (0)
#define IOTA(r) XOR64_IOTA(a00, a00, r)
#define P0 a00, a01, a02, a03, a04, a10, a11, a12, a13, a14, a20, a21, \
a22, a23, a24, a30, a31, a32, a33, a34, a40, a41, a42, a43, a44
#define P1 a00, a30, a10, a40, a20, a11, a41, a21, a01, a31, a22, a02, \
a32, a12, a42, a33, a13, a43, a23, a03, a44, a24, a04, a34, a14
#define P2 a00, a33, a11, a44, a22, a41, a24, a02, a30, a13, a32, a10, \
a43, a21, a04, a23, a01, a34, a12, a40, a14, a42, a20, a03, a31
#define P3 a00, a23, a41, a14, a32, a24, a42, a10, a33, a01, a43, a11, \
a34, a02, a20, a12, a30, a03, a21, a44, a31, a04, a22, a40, a13
#define P4 a00, a12, a24, a31, a43, a42, a04, a11, a23, a30, a34, a41, \
a03, a10, a22, a21, a33, a40, a02, a14, a13, a20, a32, a44, a01
#define P5 a00, a21, a42, a13, a34, a04, a20, a41, a12, a33, a03, a24, \
a40, a11, a32, a02, a23, a44, a10, a31, a01, a22, a43, a14, a30
#define P6 a00, a02, a04, a01, a03, a20, a22, a24, a21, a23, a40, a42, \
a44, a41, a43, a10, a12, a14, a11, a13, a30, a32, a34, a31, a33
#define P7 a00, a10, a20, a30, a40, a22, a32, a42, a02, a12, a44, a04, \
a14, a24, a34, a11, a21, a31, a41, a01, a33, a43, a03, a13, a23
#define P8 a00, a11, a22, a33, a44, a32, a43, a04, a10, a21, a14, a20, \
a31, a42, a03, a41, a02, a13, a24, a30, a23, a34, a40, a01, a12
#define P9 a00, a41, a32, a23, a14, a43, a34, a20, a11, a02, a31, a22, \
a13, a04, a40, a24, a10, a01, a42, a33, a12, a03, a44, a30, a21
#define P10 a00, a24, a43, a12, a31, a34, a03, a22, a41, a10, a13, a32, \
a01, a20, a44, a42, a11, a30, a04, a23, a21, a40, a14, a33, a02
#define P11 a00, a42, a34, a21, a13, a03, a40, a32, a24, a11, a01, a43, \
a30, a22, a14, a04, a41, a33, a20, a12, a02, a44, a31, a23, a10
#define P12 a00, a04, a03, a02, a01, a40, a44, a43, a42, a41, a30, a34, \
a33, a32, a31, a20, a24, a23, a22, a21, a10, a14, a13, a12, a11
#define P13 a00, a20, a40, a10, a30, a44, a14, a34, a04, a24, a33, a03, \
a23, a43, a13, a22, a42, a12, a32, a02, a11, a31, a01, a21, a41
#define P14 a00, a22, a44, a11, a33, a14, a31, a03, a20, a42, a23, a40, \
a12, a34, a01, a32, a04, a21, a43, a10, a41, a13, a30, a02, a24
#define P15 a00, a32, a14, a41, a23, a31, a13, a40, a22, a04, a12, a44, \
a21, a03, a30, a43, a20, a02, a34, a11, a24, a01, a33, a10, a42
#define P16 a00, a43, a31, a24, a12, a13, a01, a44, a32, a20, a21, a14, \
a02, a40, a33, a34, a22, a10, a03, a41, a42, a30, a23, a11, a04
#define P17 a00, a34, a13, a42, a21, a01, a30, a14, a43, a22, a02, a31, \
a10, a44, a23, a03, a32, a11, a40, a24, a04, a33, a12, a41, a20
#define P18 a00, a03, a01, a04, a02, a30, a33, a31, a34, a32, a10, a13, \
a11, a14, a12, a40, a43, a41, a44, a42, a20, a23, a21, a24, a22
#define P19 a00, a40, a30, a20, a10, a33, a23, a13, a03, a43, a11, a01, \
a41, a31, a21, a44, a34, a24, a14, a04, a22, a12, a02, a42, a32
#define P20 a00, a44, a33, a22, a11, a23, a12, a01, a40, a34, a41, a30, \
a24, a13, a02, a14, a03, a42, a31, a20, a32, a21, a10, a04, a43
#define P21 a00, a14, a23, a32, a41, a12, a21, a30, a44, a03, a24, a33, \
a42, a01, a10, a31, a40, a04, a13, a22, a43, a02, a11, a20, a34
#define P22 a00, a31, a12, a43, a24, a21, a02, a33, a14, a40, a42, a23, \
a04, a30, a11, a13, a44, a20, a01, a32, a34, a10, a41, a22, a03
#define P23 a00, a13, a21, a34, a42, a02, a10, a23, a31, a44, a04, a12, \
a20, a33, a41, a01, a14, a22, a30, a43, a03, a11, a24, a32, a40
#define P1_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a30); \
MOV64(a30, a33); \
MOV64(a33, a23); \
MOV64(a23, a12); \
MOV64(a12, a21); \
MOV64(a21, a02); \
MOV64(a02, a10); \
MOV64(a10, a11); \
MOV64(a11, a41); \
MOV64(a41, a24); \
MOV64(a24, a42); \
MOV64(a42, a04); \
MOV64(a04, a20); \
MOV64(a20, a22); \
MOV64(a22, a32); \
MOV64(a32, a43); \
MOV64(a43, a34); \
MOV64(a34, a03); \
MOV64(a03, a40); \
MOV64(a40, a44); \
MOV64(a44, a14); \
MOV64(a14, a31); \
MOV64(a31, a13); \
MOV64(a13, t); \
} while (0)
#define P2_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a33); \
MOV64(a33, a12); \
MOV64(a12, a02); \
MOV64(a02, a11); \
MOV64(a11, a24); \
MOV64(a24, a04); \
MOV64(a04, a22); \
MOV64(a22, a43); \
MOV64(a43, a03); \
MOV64(a03, a44); \
MOV64(a44, a31); \
MOV64(a31, t); \
MOV64(t, a10); \
MOV64(a10, a41); \
MOV64(a41, a42); \
MOV64(a42, a20); \
MOV64(a20, a32); \
MOV64(a32, a34); \
MOV64(a34, a40); \
MOV64(a40, a14); \
MOV64(a14, a13); \
MOV64(a13, a30); \
MOV64(a30, a23); \
MOV64(a23, a21); \
MOV64(a21, t); \
} while (0)
#define P4_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a12); \
MOV64(a12, a11); \
MOV64(a11, a04); \
MOV64(a04, a43); \
MOV64(a43, a44); \
MOV64(a44, t); \
MOV64(t, a02); \
MOV64(a02, a24); \
MOV64(a24, a22); \
MOV64(a22, a03); \
MOV64(a03, a31); \
MOV64(a31, a33); \
MOV64(a33, t); \
MOV64(t, a10); \
MOV64(a10, a42); \
MOV64(a42, a32); \
MOV64(a32, a40); \
MOV64(a40, a13); \
MOV64(a13, a23); \
MOV64(a23, t); \
MOV64(t, a14); \
MOV64(a14, a30); \
MOV64(a30, a21); \
MOV64(a21, a41); \
MOV64(a41, a20); \
MOV64(a20, a34); \
MOV64(a34, t); \
} while (0)
#define P6_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a02); \
MOV64(a02, a04); \
MOV64(a04, a03); \
MOV64(a03, t); \
MOV64(t, a10); \
MOV64(a10, a20); \
MOV64(a20, a40); \
MOV64(a40, a30); \
MOV64(a30, t); \
MOV64(t, a11); \
MOV64(a11, a22); \
MOV64(a22, a44); \
MOV64(a44, a33); \
MOV64(a33, t); \
MOV64(t, a12); \
MOV64(a12, a24); \
MOV64(a24, a43); \
MOV64(a43, a31); \
MOV64(a31, t); \
MOV64(t, a13); \
MOV64(a13, a21); \
MOV64(a21, a42); \
MOV64(a42, a34); \
MOV64(a34, t); \
MOV64(t, a14); \
MOV64(a14, a23); \
MOV64(a23, a41); \
MOV64(a41, a32); \
MOV64(a32, t); \
} while (0)
#define P8_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a11); \
MOV64(a11, a43); \
MOV64(a43, t); \
MOV64(t, a02); \
MOV64(a02, a22); \
MOV64(a22, a31); \
MOV64(a31, t); \
MOV64(t, a03); \
MOV64(a03, a33); \
MOV64(a33, a24); \
MOV64(a24, t); \
MOV64(t, a04); \
MOV64(a04, a44); \
MOV64(a44, a12); \
MOV64(a12, t); \
MOV64(t, a10); \
MOV64(a10, a32); \
MOV64(a32, a13); \
MOV64(a13, t); \
MOV64(t, a14); \
MOV64(a14, a21); \
MOV64(a21, a20); \
MOV64(a20, t); \
MOV64(t, a23); \
MOV64(a23, a42); \
MOV64(a42, a40); \
MOV64(a40, t); \
MOV64(t, a30); \
MOV64(a30, a41); \
MOV64(a41, a34); \
MOV64(a34, t); \
} while (0)
#define P12_TO_P0 do { \
DECL64(t); \
MOV64(t, a01); \
MOV64(a01, a04); \
MOV64(a04, t); \
MOV64(t, a02); \
MOV64(a02, a03); \
MOV64(a03, t); \
MOV64(t, a10); \
MOV64(a10, a40); \
MOV64(a40, t); \
MOV64(t, a11); \
MOV64(a11, a44); \
MOV64(a44, t); \
MOV64(t, a12); \
MOV64(a12, a43); \
MOV64(a43, t); \
MOV64(t, a13); \
MOV64(a13, a42); \
MOV64(a42, t); \
MOV64(t, a14); \
MOV64(a14, a41); \
MOV64(a41, t); \
MOV64(t, a20); \
MOV64(a20, a30); \
MOV64(a30, t); \
MOV64(t, a21); \
MOV64(a21, a34); \
MOV64(a34, t); \
MOV64(t, a22); \
MOV64(a22, a33); \
MOV64(a33, t); \
MOV64(t, a23); \
MOV64(a23, a32); \
MOV64(a32, t); \
MOV64(t, a24); \
MOV64(a24, a31); \
MOV64(a31, t); \
} while (0)
#define LPAR (
#define RPAR )
#define KF_ELT(r, s, k) do { \
THETA LPAR P ## r RPAR; \
RHO LPAR P ## r RPAR; \
KHI LPAR P ## s RPAR; \
IOTA(k); \
} while (0)
#define DO(x) x
#define KECCAK_F_1600 DO(KECCAK_F_1600_)
#if SPH_KECCAK_UNROLL == 1
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j ++) { \
KF_ELT( 0, 1, RC[j + 0]); \
P1_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 2
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 2) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
P2_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 4
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 4) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
P4_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 6
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 6) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
KF_ELT( 4, 5, RC[j + 4]); \
KF_ELT( 5, 6, RC[j + 5]); \
P6_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 8
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 8) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
KF_ELT( 4, 5, RC[j + 4]); \
KF_ELT( 5, 6, RC[j + 5]); \
KF_ELT( 6, 7, RC[j + 6]); \
KF_ELT( 7, 8, RC[j + 7]); \
P8_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 12
#define KECCAK_F_1600_ do { \
int j; \
for (j = 0; j < 24; j += 12) { \
KF_ELT( 0, 1, RC[j + 0]); \
KF_ELT( 1, 2, RC[j + 1]); \
KF_ELT( 2, 3, RC[j + 2]); \
KF_ELT( 3, 4, RC[j + 3]); \
KF_ELT( 4, 5, RC[j + 4]); \
KF_ELT( 5, 6, RC[j + 5]); \
KF_ELT( 6, 7, RC[j + 6]); \
KF_ELT( 7, 8, RC[j + 7]); \
KF_ELT( 8, 9, RC[j + 8]); \
KF_ELT( 9, 10, RC[j + 9]); \
KF_ELT(10, 11, RC[j + 10]); \
KF_ELT(11, 12, RC[j + 11]); \
P12_TO_P0; \
} \
} while (0)
#elif SPH_KECCAK_UNROLL == 0
#define KECCAK_F_1600_ do { \
KF_ELT( 0, 1, RC[ 0]); \
KF_ELT( 1, 2, RC[ 1]); \
KF_ELT( 2, 3, RC[ 2]); \
KF_ELT( 3, 4, RC[ 3]); \
KF_ELT( 4, 5, RC[ 4]); \
KF_ELT( 5, 6, RC[ 5]); \
KF_ELT( 6, 7, RC[ 6]); \
KF_ELT( 7, 8, RC[ 7]); \
KF_ELT( 8, 9, RC[ 8]); \
KF_ELT( 9, 10, RC[ 9]); \
KF_ELT(10, 11, RC[10]); \
KF_ELT(11, 12, RC[11]); \
KF_ELT(12, 13, RC[12]); \
KF_ELT(13, 14, RC[13]); \
KF_ELT(14, 15, RC[14]); \
KF_ELT(15, 16, RC[15]); \
KF_ELT(16, 17, RC[16]); \
KF_ELT(17, 18, RC[17]); \
KF_ELT(18, 19, RC[18]); \
KF_ELT(19, 20, RC[19]); \
KF_ELT(20, 21, RC[20]); \
KF_ELT(21, 22, RC[21]); \
KF_ELT(22, 23, RC[22]); \
KF_ELT(23, 0, RC[23]); \
} while (0)
#else
#error Unimplemented unroll count for Keccak.
#endif
static void
keccak_init(sph_keccak_context *kc, unsigned out_size)
{
int i;
#if SPH_KECCAK_64
for (i = 0; i < 25; i ++)
kc->u.wide[i] = 0;
/*
* Initialization for the "lane complement".
*/
kc->u.wide[ 1] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[ 2] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[ 8] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[12] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[17] = SPH_C64(0xFFFFFFFFFFFFFFFF);
kc->u.wide[20] = SPH_C64(0xFFFFFFFFFFFFFFFF);
#else
for (i = 0; i < 50; i ++)
kc->u.narrow[i] = 0;
/*
* Initialization for the "lane complement".
* Note: since we set to all-one full 64-bit words,
* interleaving (if applicable) is a no-op.
*/
kc->u.narrow[ 2] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[ 3] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[ 4] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[ 5] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[16] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[17] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[24] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[25] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[34] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[35] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[40] = SPH_C32(0xFFFFFFFF);
kc->u.narrow[41] = SPH_C32(0xFFFFFFFF);
#endif
kc->ptr = 0;
kc->lim = 200 - (out_size >> 2);
}
static void
keccak_core(sph_keccak_context *kc, const void *data, size_t len, size_t lim)
{
unsigned char *buf;
size_t ptr;
DECL_STATE
buf = kc->buf;
ptr = kc->ptr;
if (len < (lim - ptr)) {
memcpy(buf + ptr, data, len);
kc->ptr = ptr + len;
return;
}
READ_STATE(kc);
while (len > 0) {
size_t clen;
clen = (lim - ptr);
if (clen > len)
clen = len;
memcpy(buf + ptr, data, clen);
ptr += clen;
data = (const unsigned char *)data + clen;
len -= clen;
if (ptr == lim) {
INPUT_BUF(lim);
KECCAK_F_1600;
ptr = 0;
}
}
WRITE_STATE(kc);
kc->ptr = ptr;
}
#if SPH_KECCAK_64
#define DEFCLOSE(d, lim) \
static void keccak_close ## d( \
sph_keccak_context *kc, unsigned ub, unsigned n, void *dst) \
{ \
unsigned eb; \
union { \
unsigned char tmp[lim + 1]; \
sph_u64 dummy; /* for alignment */ \
} u; \
size_t j; \
\
eb = (0x100 | (ub & 0xFF)) >> (8 - n); \
if (kc->ptr == (lim - 1)) { \
if (n == 7) { \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, lim - 1); \
u.tmp[lim] = 0x80; \
j = 1 + lim; \
} else { \
u.tmp[0] = eb | 0x80; \
j = 1; \
} \
} else { \
j = lim - kc->ptr; \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, j - 2); \
u.tmp[j - 1] = 0x80; \
} \
keccak_core(kc, u.tmp, j, lim); \
/* Finalize the "lane complement" */ \
kc->u.wide[ 1] = ~kc->u.wide[ 1]; \
kc->u.wide[ 2] = ~kc->u.wide[ 2]; \
kc->u.wide[ 8] = ~kc->u.wide[ 8]; \
kc->u.wide[12] = ~kc->u.wide[12]; \
kc->u.wide[17] = ~kc->u.wide[17]; \
kc->u.wide[20] = ~kc->u.wide[20]; \
for (j = 0; j < d; j += 8) \
sph_enc64le_aligned(u.tmp + j, kc->u.wide[j >> 3]); \
memcpy(dst, u.tmp, d); \
keccak_init(kc, (unsigned)d << 3); \
} \
#else
#define DEFCLOSE(d, lim) \
static void keccak_close ## d( \
sph_keccak_context *kc, unsigned ub, unsigned n, void *dst) \
{ \
unsigned eb; \
union { \
unsigned char tmp[lim + 1]; \
sph_u64 dummy; /* for alignment */ \
} u; \
size_t j; \
\
eb = (0x100 | (ub & 0xFF)) >> (8 - n); \
if (kc->ptr == (lim - 1)) { \
if (n == 7) { \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, lim - 1); \
u.tmp[lim] = 0x80; \
j = 1 + lim; \
} else { \
u.tmp[0] = eb | 0x80; \
j = 1; \
} \
} else { \
j = lim - kc->ptr; \
u.tmp[0] = eb; \
memset(u.tmp + 1, 0, j - 2); \
u.tmp[j - 1] = 0x80; \
} \
keccak_core(kc, u.tmp, j, lim); \
/* Finalize the "lane complement" */ \
kc->u.narrow[ 2] = ~kc->u.narrow[ 2]; \
kc->u.narrow[ 3] = ~kc->u.narrow[ 3]; \
kc->u.narrow[ 4] = ~kc->u.narrow[ 4]; \
kc->u.narrow[ 5] = ~kc->u.narrow[ 5]; \
kc->u.narrow[16] = ~kc->u.narrow[16]; \
kc->u.narrow[17] = ~kc->u.narrow[17]; \
kc->u.narrow[24] = ~kc->u.narrow[24]; \
kc->u.narrow[25] = ~kc->u.narrow[25]; \
kc->u.narrow[34] = ~kc->u.narrow[34]; \
kc->u.narrow[35] = ~kc->u.narrow[35]; \
kc->u.narrow[40] = ~kc->u.narrow[40]; \
kc->u.narrow[41] = ~kc->u.narrow[41]; \
/* un-interleave */ \
for (j = 0; j < 50; j += 2) \
UNINTERLEAVE(kc->u.narrow[j], kc->u.narrow[j + 1]); \
for (j = 0; j < d; j += 4) \
sph_enc32le_aligned(u.tmp + j, kc->u.narrow[j >> 2]); \
memcpy(dst, u.tmp, d); \
keccak_init(kc, (unsigned)d << 3); \
} \
#endif
DEFCLOSE(28, 144)
DEFCLOSE(32, 136)
DEFCLOSE(48, 104)
DEFCLOSE(64, 72)
/* see sph_keccak.h */
void
sph_keccak224_init(void *cc)
{
keccak_init(cc, 224);
}
/* see sph_keccak.h */
void
sph_keccak224(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 144);
}
/* see sph_keccak.h */
void
sph_keccak224_close(void *cc, void *dst)
{
sph_keccak224_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak224_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close28(cc, ub, n, dst);
}
/* see sph_keccak.h */
void
sph_keccak256_init(void *cc)
{
keccak_init(cc, 256);
}
/* see sph_keccak.h */
void
sph_keccak256(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 136);
}
/* see sph_keccak.h */
void
sph_keccak256_close(void *cc, void *dst)
{
sph_keccak256_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak256_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close32(cc, ub, n, dst);
}
/* see sph_keccak.h */
void
sph_keccak384_init(void *cc)
{
keccak_init(cc, 384);
}
/* see sph_keccak.h */
void
sph_keccak384(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 104);
}
/* see sph_keccak.h */
void
sph_keccak384_close(void *cc, void *dst)
{
sph_keccak384_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak384_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close48(cc, ub, n, dst);
}
/* see sph_keccak.h */
void
sph_keccak512_init(void *cc)
{
keccak_init(cc, 512);
}
/* see sph_keccak.h */
void
sph_keccak512(void *cc, const void *data, size_t len)
{
keccak_core(cc, data, len, 72);
}
/* see sph_keccak.h */
void
sph_keccak512_close(void *cc, void *dst)
{
sph_keccak512_addbits_and_close(cc, 0, 0, dst);
}
/* see sph_keccak.h */
void
sph_keccak512_addbits_and_close(void *cc, unsigned ub, unsigned n, void *dst)
{
keccak_close64(cc, ub, n, dst);
}
#ifdef __cplusplus
}
#endif | gpl-2.0 |
jiangliu/linux | drivers/thermal/thermal_core.c | 282 | 48212 | /*
* thermal.c - Generic Thermal Management Sysfs support.
*
* Copyright (C) 2008 Intel Corp
* Copyright (C) 2008 Zhang Rui <rui.zhang@intel.com>
* Copyright (C) 2008 Sujith Thomas <sujith.thomas@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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 pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/kdev_t.h>
#include <linux/idr.h>
#include <linux/thermal.h>
#include <linux/reboot.h>
#include <linux/string.h>
#include <linux/of.h>
#include <net/netlink.h>
#include <net/genetlink.h>
#include "thermal_core.h"
#include "thermal_hwmon.h"
MODULE_AUTHOR("Zhang Rui");
MODULE_DESCRIPTION("Generic thermal management sysfs support");
MODULE_LICENSE("GPL v2");
static DEFINE_IDR(thermal_tz_idr);
static DEFINE_IDR(thermal_cdev_idr);
static DEFINE_MUTEX(thermal_idr_lock);
static LIST_HEAD(thermal_tz_list);
static LIST_HEAD(thermal_cdev_list);
static LIST_HEAD(thermal_governor_list);
static DEFINE_MUTEX(thermal_list_lock);
static DEFINE_MUTEX(thermal_governor_lock);
static struct thermal_governor *def_governor;
static struct thermal_governor *__find_governor(const char *name)
{
struct thermal_governor *pos;
if (!name || !name[0])
return def_governor;
list_for_each_entry(pos, &thermal_governor_list, governor_list)
if (!strnicmp(name, pos->name, THERMAL_NAME_LENGTH))
return pos;
return NULL;
}
int thermal_register_governor(struct thermal_governor *governor)
{
int err;
const char *name;
struct thermal_zone_device *pos;
if (!governor)
return -EINVAL;
mutex_lock(&thermal_governor_lock);
err = -EBUSY;
if (__find_governor(governor->name) == NULL) {
err = 0;
list_add(&governor->governor_list, &thermal_governor_list);
if (!def_governor && !strncmp(governor->name,
DEFAULT_THERMAL_GOVERNOR, THERMAL_NAME_LENGTH))
def_governor = governor;
}
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_tz_list, node) {
/*
* only thermal zones with specified tz->tzp->governor_name
* may run with tz->govenor unset
*/
if (pos->governor)
continue;
name = pos->tzp->governor_name;
if (!strnicmp(name, governor->name, THERMAL_NAME_LENGTH))
pos->governor = governor;
}
mutex_unlock(&thermal_list_lock);
mutex_unlock(&thermal_governor_lock);
return err;
}
void thermal_unregister_governor(struct thermal_governor *governor)
{
struct thermal_zone_device *pos;
if (!governor)
return;
mutex_lock(&thermal_governor_lock);
if (__find_governor(governor->name) == NULL)
goto exit;
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_tz_list, node) {
if (!strnicmp(pos->governor->name, governor->name,
THERMAL_NAME_LENGTH))
pos->governor = NULL;
}
mutex_unlock(&thermal_list_lock);
list_del(&governor->governor_list);
exit:
mutex_unlock(&thermal_governor_lock);
return;
}
static int get_idr(struct idr *idr, struct mutex *lock, int *id)
{
int ret;
if (lock)
mutex_lock(lock);
ret = idr_alloc(idr, NULL, 0, 0, GFP_KERNEL);
if (lock)
mutex_unlock(lock);
if (unlikely(ret < 0))
return ret;
*id = ret;
return 0;
}
static void release_idr(struct idr *idr, struct mutex *lock, int id)
{
if (lock)
mutex_lock(lock);
idr_remove(idr, id);
if (lock)
mutex_unlock(lock);
}
int get_tz_trend(struct thermal_zone_device *tz, int trip)
{
enum thermal_trend trend;
if (tz->emul_temperature || !tz->ops->get_trend ||
tz->ops->get_trend(tz, trip, &trend)) {
if (tz->temperature > tz->last_temperature)
trend = THERMAL_TREND_RAISING;
else if (tz->temperature < tz->last_temperature)
trend = THERMAL_TREND_DROPPING;
else
trend = THERMAL_TREND_STABLE;
}
return trend;
}
EXPORT_SYMBOL(get_tz_trend);
struct thermal_instance *get_thermal_instance(struct thermal_zone_device *tz,
struct thermal_cooling_device *cdev, int trip)
{
struct thermal_instance *pos = NULL;
struct thermal_instance *target_instance = NULL;
mutex_lock(&tz->lock);
mutex_lock(&cdev->lock);
list_for_each_entry(pos, &tz->thermal_instances, tz_node) {
if (pos->tz == tz && pos->trip == trip && pos->cdev == cdev) {
target_instance = pos;
break;
}
}
mutex_unlock(&cdev->lock);
mutex_unlock(&tz->lock);
return target_instance;
}
EXPORT_SYMBOL(get_thermal_instance);
static void print_bind_err_msg(struct thermal_zone_device *tz,
struct thermal_cooling_device *cdev, int ret)
{
dev_err(&tz->device, "binding zone %s with cdev %s failed:%d\n",
tz->type, cdev->type, ret);
}
static void __bind(struct thermal_zone_device *tz, int mask,
struct thermal_cooling_device *cdev,
unsigned long *limits)
{
int i, ret;
for (i = 0; i < tz->trips; i++) {
if (mask & (1 << i)) {
unsigned long upper, lower;
upper = THERMAL_NO_LIMIT;
lower = THERMAL_NO_LIMIT;
if (limits) {
lower = limits[i * 2];
upper = limits[i * 2 + 1];
}
ret = thermal_zone_bind_cooling_device(tz, i, cdev,
upper, lower);
if (ret)
print_bind_err_msg(tz, cdev, ret);
}
}
}
static void __unbind(struct thermal_zone_device *tz, int mask,
struct thermal_cooling_device *cdev)
{
int i;
for (i = 0; i < tz->trips; i++)
if (mask & (1 << i))
thermal_zone_unbind_cooling_device(tz, i, cdev);
}
static void bind_cdev(struct thermal_cooling_device *cdev)
{
int i, ret;
const struct thermal_zone_params *tzp;
struct thermal_zone_device *pos = NULL;
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_tz_list, node) {
if (!pos->tzp && !pos->ops->bind)
continue;
if (pos->ops->bind) {
ret = pos->ops->bind(pos, cdev);
if (ret)
print_bind_err_msg(pos, cdev, ret);
continue;
}
tzp = pos->tzp;
if (!tzp || !tzp->tbp)
continue;
for (i = 0; i < tzp->num_tbps; i++) {
if (tzp->tbp[i].cdev || !tzp->tbp[i].match)
continue;
if (tzp->tbp[i].match(pos, cdev))
continue;
tzp->tbp[i].cdev = cdev;
__bind(pos, tzp->tbp[i].trip_mask, cdev,
tzp->tbp[i].binding_limits);
}
}
mutex_unlock(&thermal_list_lock);
}
static void bind_tz(struct thermal_zone_device *tz)
{
int i, ret;
struct thermal_cooling_device *pos = NULL;
const struct thermal_zone_params *tzp = tz->tzp;
if (!tzp && !tz->ops->bind)
return;
mutex_lock(&thermal_list_lock);
/* If there is ops->bind, try to use ops->bind */
if (tz->ops->bind) {
list_for_each_entry(pos, &thermal_cdev_list, node) {
ret = tz->ops->bind(tz, pos);
if (ret)
print_bind_err_msg(tz, pos, ret);
}
goto exit;
}
if (!tzp || !tzp->tbp)
goto exit;
list_for_each_entry(pos, &thermal_cdev_list, node) {
for (i = 0; i < tzp->num_tbps; i++) {
if (tzp->tbp[i].cdev || !tzp->tbp[i].match)
continue;
if (tzp->tbp[i].match(tz, pos))
continue;
tzp->tbp[i].cdev = pos;
__bind(tz, tzp->tbp[i].trip_mask, pos,
tzp->tbp[i].binding_limits);
}
}
exit:
mutex_unlock(&thermal_list_lock);
}
static void thermal_zone_device_set_polling(struct thermal_zone_device *tz,
int delay)
{
if (delay > 1000)
mod_delayed_work(system_freezable_wq, &tz->poll_queue,
round_jiffies(msecs_to_jiffies(delay)));
else if (delay)
mod_delayed_work(system_freezable_wq, &tz->poll_queue,
msecs_to_jiffies(delay));
else
cancel_delayed_work(&tz->poll_queue);
}
static void monitor_thermal_zone(struct thermal_zone_device *tz)
{
mutex_lock(&tz->lock);
if (tz->passive)
thermal_zone_device_set_polling(tz, tz->passive_delay);
else if (tz->polling_delay)
thermal_zone_device_set_polling(tz, tz->polling_delay);
else
thermal_zone_device_set_polling(tz, 0);
mutex_unlock(&tz->lock);
}
static void handle_non_critical_trips(struct thermal_zone_device *tz,
int trip, enum thermal_trip_type trip_type)
{
tz->governor ? tz->governor->throttle(tz, trip) :
def_governor->throttle(tz, trip);
}
static void handle_critical_trips(struct thermal_zone_device *tz,
int trip, enum thermal_trip_type trip_type)
{
long trip_temp;
tz->ops->get_trip_temp(tz, trip, &trip_temp);
/* If we have not crossed the trip_temp, we do not care. */
if (tz->temperature < trip_temp)
return;
if (tz->ops->notify)
tz->ops->notify(tz, trip, trip_type);
if (trip_type == THERMAL_TRIP_CRITICAL) {
dev_emerg(&tz->device,
"critical temperature reached(%d C),shutting down\n",
tz->temperature / 1000);
orderly_poweroff(true);
}
}
static void handle_thermal_trip(struct thermal_zone_device *tz, int trip)
{
enum thermal_trip_type type;
tz->ops->get_trip_type(tz, trip, &type);
if (type == THERMAL_TRIP_CRITICAL || type == THERMAL_TRIP_HOT)
handle_critical_trips(tz, trip, type);
else
handle_non_critical_trips(tz, trip, type);
/*
* Alright, we handled this trip successfully.
* So, start monitoring again.
*/
monitor_thermal_zone(tz);
}
/**
* thermal_zone_get_temp() - returns its the temperature of thermal zone
* @tz: a valid pointer to a struct thermal_zone_device
* @temp: a valid pointer to where to store the resulting temperature.
*
* When a valid thermal zone reference is passed, it will fetch its
* temperature and fill @temp.
*
* Return: On success returns 0, an error code otherwise
*/
int thermal_zone_get_temp(struct thermal_zone_device *tz, unsigned long *temp)
{
int ret = -EINVAL;
#ifdef CONFIG_THERMAL_EMULATION
int count;
unsigned long crit_temp = -1UL;
enum thermal_trip_type type;
#endif
if (!tz || IS_ERR(tz) || !tz->ops->get_temp)
goto exit;
mutex_lock(&tz->lock);
ret = tz->ops->get_temp(tz, temp);
#ifdef CONFIG_THERMAL_EMULATION
if (!tz->emul_temperature)
goto skip_emul;
for (count = 0; count < tz->trips; count++) {
ret = tz->ops->get_trip_type(tz, count, &type);
if (!ret && type == THERMAL_TRIP_CRITICAL) {
ret = tz->ops->get_trip_temp(tz, count, &crit_temp);
break;
}
}
if (ret)
goto skip_emul;
if (*temp < crit_temp)
*temp = tz->emul_temperature;
skip_emul:
#endif
mutex_unlock(&tz->lock);
exit:
return ret;
}
EXPORT_SYMBOL_GPL(thermal_zone_get_temp);
static void update_temperature(struct thermal_zone_device *tz)
{
long temp;
int ret;
ret = thermal_zone_get_temp(tz, &temp);
if (ret) {
dev_warn(&tz->device, "failed to read out thermal zone %d\n",
tz->id);
return;
}
mutex_lock(&tz->lock);
tz->last_temperature = tz->temperature;
tz->temperature = temp;
mutex_unlock(&tz->lock);
dev_dbg(&tz->device, "last_temperature=%d, current_temperature=%d\n",
tz->last_temperature, tz->temperature);
}
void thermal_zone_device_update(struct thermal_zone_device *tz)
{
int count;
if (!tz->ops->get_temp)
return;
update_temperature(tz);
for (count = 0; count < tz->trips; count++)
handle_thermal_trip(tz, count);
}
EXPORT_SYMBOL_GPL(thermal_zone_device_update);
static void thermal_zone_device_check(struct work_struct *work)
{
struct thermal_zone_device *tz = container_of(work, struct
thermal_zone_device,
poll_queue.work);
thermal_zone_device_update(tz);
}
/* sys I/F for thermal zone */
#define to_thermal_zone(_dev) \
container_of(_dev, struct thermal_zone_device, device)
static ssize_t
type_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
return sprintf(buf, "%s\n", tz->type);
}
static ssize_t
temp_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
long temperature;
int ret;
ret = thermal_zone_get_temp(tz, &temperature);
if (ret)
return ret;
return sprintf(buf, "%ld\n", temperature);
}
static ssize_t
mode_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
enum thermal_device_mode mode;
int result;
if (!tz->ops->get_mode)
return -EPERM;
result = tz->ops->get_mode(tz, &mode);
if (result)
return result;
return sprintf(buf, "%s\n", mode == THERMAL_DEVICE_ENABLED ? "enabled"
: "disabled");
}
static ssize_t
mode_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int result;
if (!tz->ops->set_mode)
return -EPERM;
if (!strncmp(buf, "enabled", sizeof("enabled") - 1))
result = tz->ops->set_mode(tz, THERMAL_DEVICE_ENABLED);
else if (!strncmp(buf, "disabled", sizeof("disabled") - 1))
result = tz->ops->set_mode(tz, THERMAL_DEVICE_DISABLED);
else
result = -EINVAL;
if (result)
return result;
return count;
}
static ssize_t
trip_point_type_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
enum thermal_trip_type type;
int trip, result;
if (!tz->ops->get_trip_type)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_type", &trip))
return -EINVAL;
result = tz->ops->get_trip_type(tz, trip, &type);
if (result)
return result;
switch (type) {
case THERMAL_TRIP_CRITICAL:
return sprintf(buf, "critical\n");
case THERMAL_TRIP_HOT:
return sprintf(buf, "hot\n");
case THERMAL_TRIP_PASSIVE:
return sprintf(buf, "passive\n");
case THERMAL_TRIP_ACTIVE:
return sprintf(buf, "active\n");
default:
return sprintf(buf, "unknown\n");
}
}
static ssize_t
trip_point_temp_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int trip, ret;
unsigned long temperature;
if (!tz->ops->set_trip_temp)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_temp", &trip))
return -EINVAL;
if (kstrtoul(buf, 10, &temperature))
return -EINVAL;
ret = tz->ops->set_trip_temp(tz, trip, temperature);
return ret ? ret : count;
}
static ssize_t
trip_point_temp_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int trip, ret;
long temperature;
if (!tz->ops->get_trip_temp)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_temp", &trip))
return -EINVAL;
ret = tz->ops->get_trip_temp(tz, trip, &temperature);
if (ret)
return ret;
return sprintf(buf, "%ld\n", temperature);
}
static ssize_t
trip_point_hyst_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int trip, ret;
unsigned long temperature;
if (!tz->ops->set_trip_hyst)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_hyst", &trip))
return -EINVAL;
if (kstrtoul(buf, 10, &temperature))
return -EINVAL;
/*
* We are not doing any check on the 'temperature' value
* here. The driver implementing 'set_trip_hyst' has to
* take care of this.
*/
ret = tz->ops->set_trip_hyst(tz, trip, temperature);
return ret ? ret : count;
}
static ssize_t
trip_point_hyst_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int trip, ret;
unsigned long temperature;
if (!tz->ops->get_trip_hyst)
return -EPERM;
if (!sscanf(attr->attr.name, "trip_point_%d_hyst", &trip))
return -EINVAL;
ret = tz->ops->get_trip_hyst(tz, trip, &temperature);
return ret ? ret : sprintf(buf, "%ld\n", temperature);
}
static ssize_t
passive_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
struct thermal_cooling_device *cdev = NULL;
int state;
if (!sscanf(buf, "%d\n", &state))
return -EINVAL;
/* sanity check: values below 1000 millicelcius don't make sense
* and can cause the system to go into a thermal heart attack
*/
if (state && state < 1000)
return -EINVAL;
if (state && !tz->forced_passive) {
mutex_lock(&thermal_list_lock);
list_for_each_entry(cdev, &thermal_cdev_list, node) {
if (!strncmp("Processor", cdev->type,
sizeof("Processor")))
thermal_zone_bind_cooling_device(tz,
THERMAL_TRIPS_NONE, cdev,
THERMAL_NO_LIMIT,
THERMAL_NO_LIMIT);
}
mutex_unlock(&thermal_list_lock);
if (!tz->passive_delay)
tz->passive_delay = 1000;
} else if (!state && tz->forced_passive) {
mutex_lock(&thermal_list_lock);
list_for_each_entry(cdev, &thermal_cdev_list, node) {
if (!strncmp("Processor", cdev->type,
sizeof("Processor")))
thermal_zone_unbind_cooling_device(tz,
THERMAL_TRIPS_NONE,
cdev);
}
mutex_unlock(&thermal_list_lock);
tz->passive_delay = 0;
}
tz->forced_passive = state;
thermal_zone_device_update(tz);
return count;
}
static ssize_t
passive_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
return sprintf(buf, "%d\n", tz->forced_passive);
}
static ssize_t
policy_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret = -EINVAL;
struct thermal_zone_device *tz = to_thermal_zone(dev);
struct thermal_governor *gov;
char name[THERMAL_NAME_LENGTH];
snprintf(name, sizeof(name), "%s", buf);
mutex_lock(&thermal_governor_lock);
gov = __find_governor(strim(name));
if (!gov)
goto exit;
tz->governor = gov;
ret = count;
exit:
mutex_unlock(&thermal_governor_lock);
return ret;
}
static ssize_t
policy_show(struct device *dev, struct device_attribute *devattr, char *buf)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
return sprintf(buf, "%s\n", tz->governor->name);
}
#ifdef CONFIG_THERMAL_EMULATION
static ssize_t
emul_temp_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_zone_device *tz = to_thermal_zone(dev);
int ret = 0;
unsigned long temperature;
if (kstrtoul(buf, 10, &temperature))
return -EINVAL;
if (!tz->ops->set_emul_temp) {
mutex_lock(&tz->lock);
tz->emul_temperature = temperature;
mutex_unlock(&tz->lock);
} else {
ret = tz->ops->set_emul_temp(tz, temperature);
}
if (!ret)
thermal_zone_device_update(tz);
return ret ? ret : count;
}
static DEVICE_ATTR(emul_temp, S_IWUSR, NULL, emul_temp_store);
#endif/*CONFIG_THERMAL_EMULATION*/
static DEVICE_ATTR(type, 0444, type_show, NULL);
static DEVICE_ATTR(temp, 0444, temp_show, NULL);
static DEVICE_ATTR(mode, 0644, mode_show, mode_store);
static DEVICE_ATTR(passive, S_IRUGO | S_IWUSR, passive_show, passive_store);
static DEVICE_ATTR(policy, S_IRUGO | S_IWUSR, policy_show, policy_store);
/* sys I/F for cooling device */
#define to_cooling_device(_dev) \
container_of(_dev, struct thermal_cooling_device, device)
static ssize_t
thermal_cooling_device_type_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
return sprintf(buf, "%s\n", cdev->type);
}
static ssize_t
thermal_cooling_device_max_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
unsigned long state;
int ret;
ret = cdev->ops->get_max_state(cdev, &state);
if (ret)
return ret;
return sprintf(buf, "%ld\n", state);
}
static ssize_t
thermal_cooling_device_cur_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
unsigned long state;
int ret;
ret = cdev->ops->get_cur_state(cdev, &state);
if (ret)
return ret;
return sprintf(buf, "%ld\n", state);
}
static ssize_t
thermal_cooling_device_cur_state_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct thermal_cooling_device *cdev = to_cooling_device(dev);
unsigned long state;
int result;
if (!sscanf(buf, "%ld\n", &state))
return -EINVAL;
if ((long)state < 0)
return -EINVAL;
result = cdev->ops->set_cur_state(cdev, state);
if (result)
return result;
return count;
}
static struct device_attribute dev_attr_cdev_type =
__ATTR(type, 0444, thermal_cooling_device_type_show, NULL);
static DEVICE_ATTR(max_state, 0444,
thermal_cooling_device_max_state_show, NULL);
static DEVICE_ATTR(cur_state, 0644,
thermal_cooling_device_cur_state_show,
thermal_cooling_device_cur_state_store);
static ssize_t
thermal_cooling_device_trip_point_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct thermal_instance *instance;
instance =
container_of(attr, struct thermal_instance, attr);
if (instance->trip == THERMAL_TRIPS_NONE)
return sprintf(buf, "-1\n");
else
return sprintf(buf, "%d\n", instance->trip);
}
/* Device management */
/**
* thermal_zone_bind_cooling_device() - bind a cooling device to a thermal zone
* @tz: pointer to struct thermal_zone_device
* @trip: indicates which trip point the cooling devices is
* associated with in this thermal zone.
* @cdev: pointer to struct thermal_cooling_device
* @upper: the Maximum cooling state for this trip point.
* THERMAL_NO_LIMIT means no upper limit,
* and the cooling device can be in max_state.
* @lower: the Minimum cooling state can be used for this trip point.
* THERMAL_NO_LIMIT means no lower limit,
* and the cooling device can be in cooling state 0.
*
* This interface function bind a thermal cooling device to the certain trip
* point of a thermal zone device.
* This function is usually called in the thermal zone device .bind callback.
*
* Return: 0 on success, the proper error value otherwise.
*/
int thermal_zone_bind_cooling_device(struct thermal_zone_device *tz,
int trip,
struct thermal_cooling_device *cdev,
unsigned long upper, unsigned long lower)
{
struct thermal_instance *dev;
struct thermal_instance *pos;
struct thermal_zone_device *pos1;
struct thermal_cooling_device *pos2;
unsigned long max_state;
int result;
if (trip >= tz->trips || (trip < 0 && trip != THERMAL_TRIPS_NONE))
return -EINVAL;
list_for_each_entry(pos1, &thermal_tz_list, node) {
if (pos1 == tz)
break;
}
list_for_each_entry(pos2, &thermal_cdev_list, node) {
if (pos2 == cdev)
break;
}
if (tz != pos1 || cdev != pos2)
return -EINVAL;
cdev->ops->get_max_state(cdev, &max_state);
/* lower default 0, upper default max_state */
lower = lower == THERMAL_NO_LIMIT ? 0 : lower;
upper = upper == THERMAL_NO_LIMIT ? max_state : upper;
if (lower > upper || upper > max_state)
return -EINVAL;
dev =
kzalloc(sizeof(struct thermal_instance), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->tz = tz;
dev->cdev = cdev;
dev->trip = trip;
dev->upper = upper;
dev->lower = lower;
dev->target = THERMAL_NO_TARGET;
result = get_idr(&tz->idr, &tz->lock, &dev->id);
if (result)
goto free_mem;
sprintf(dev->name, "cdev%d", dev->id);
result =
sysfs_create_link(&tz->device.kobj, &cdev->device.kobj, dev->name);
if (result)
goto release_idr;
sprintf(dev->attr_name, "cdev%d_trip_point", dev->id);
sysfs_attr_init(&dev->attr.attr);
dev->attr.attr.name = dev->attr_name;
dev->attr.attr.mode = 0444;
dev->attr.show = thermal_cooling_device_trip_point_show;
result = device_create_file(&tz->device, &dev->attr);
if (result)
goto remove_symbol_link;
mutex_lock(&tz->lock);
mutex_lock(&cdev->lock);
list_for_each_entry(pos, &tz->thermal_instances, tz_node)
if (pos->tz == tz && pos->trip == trip && pos->cdev == cdev) {
result = -EEXIST;
break;
}
if (!result) {
list_add_tail(&dev->tz_node, &tz->thermal_instances);
list_add_tail(&dev->cdev_node, &cdev->thermal_instances);
}
mutex_unlock(&cdev->lock);
mutex_unlock(&tz->lock);
if (!result)
return 0;
device_remove_file(&tz->device, &dev->attr);
remove_symbol_link:
sysfs_remove_link(&tz->device.kobj, dev->name);
release_idr:
release_idr(&tz->idr, &tz->lock, dev->id);
free_mem:
kfree(dev);
return result;
}
EXPORT_SYMBOL_GPL(thermal_zone_bind_cooling_device);
/**
* thermal_zone_unbind_cooling_device() - unbind a cooling device from a
* thermal zone.
* @tz: pointer to a struct thermal_zone_device.
* @trip: indicates which trip point the cooling devices is
* associated with in this thermal zone.
* @cdev: pointer to a struct thermal_cooling_device.
*
* This interface function unbind a thermal cooling device from the certain
* trip point of a thermal zone device.
* This function is usually called in the thermal zone device .unbind callback.
*
* Return: 0 on success, the proper error value otherwise.
*/
int thermal_zone_unbind_cooling_device(struct thermal_zone_device *tz,
int trip,
struct thermal_cooling_device *cdev)
{
struct thermal_instance *pos, *next;
mutex_lock(&tz->lock);
mutex_lock(&cdev->lock);
list_for_each_entry_safe(pos, next, &tz->thermal_instances, tz_node) {
if (pos->tz == tz && pos->trip == trip && pos->cdev == cdev) {
list_del(&pos->tz_node);
list_del(&pos->cdev_node);
mutex_unlock(&cdev->lock);
mutex_unlock(&tz->lock);
goto unbind;
}
}
mutex_unlock(&cdev->lock);
mutex_unlock(&tz->lock);
return -ENODEV;
unbind:
device_remove_file(&tz->device, &pos->attr);
sysfs_remove_link(&tz->device.kobj, pos->name);
release_idr(&tz->idr, &tz->lock, pos->id);
kfree(pos);
return 0;
}
EXPORT_SYMBOL_GPL(thermal_zone_unbind_cooling_device);
static void thermal_release(struct device *dev)
{
struct thermal_zone_device *tz;
struct thermal_cooling_device *cdev;
if (!strncmp(dev_name(dev), "thermal_zone",
sizeof("thermal_zone") - 1)) {
tz = to_thermal_zone(dev);
kfree(tz);
} else if(!strncmp(dev_name(dev), "cooling_device",
sizeof("cooling_device") - 1)){
cdev = to_cooling_device(dev);
kfree(cdev);
}
}
static struct class thermal_class = {
.name = "thermal",
.dev_release = thermal_release,
};
/**
* __thermal_cooling_device_register() - register a new thermal cooling device
* @np: a pointer to a device tree node.
* @type: the thermal cooling device type.
* @devdata: device private data.
* @ops: standard thermal cooling devices callbacks.
*
* This interface function adds a new thermal cooling device (fan/processor/...)
* to /sys/class/thermal/ folder as cooling_device[0-*]. It tries to bind itself
* to all the thermal zone devices registered at the same time.
* It also gives the opportunity to link the cooling device to a device tree
* node, so that it can be bound to a thermal zone created out of device tree.
*
* Return: a pointer to the created struct thermal_cooling_device or an
* ERR_PTR. Caller must check return value with IS_ERR*() helpers.
*/
static struct thermal_cooling_device *
__thermal_cooling_device_register(struct device_node *np,
char *type, void *devdata,
const struct thermal_cooling_device_ops *ops)
{
struct thermal_cooling_device *cdev;
int result;
if (type && strlen(type) >= THERMAL_NAME_LENGTH)
return ERR_PTR(-EINVAL);
if (!ops || !ops->get_max_state || !ops->get_cur_state ||
!ops->set_cur_state)
return ERR_PTR(-EINVAL);
cdev = kzalloc(sizeof(struct thermal_cooling_device), GFP_KERNEL);
if (!cdev)
return ERR_PTR(-ENOMEM);
result = get_idr(&thermal_cdev_idr, &thermal_idr_lock, &cdev->id);
if (result) {
kfree(cdev);
return ERR_PTR(result);
}
strlcpy(cdev->type, type ? : "", sizeof(cdev->type));
mutex_init(&cdev->lock);
INIT_LIST_HEAD(&cdev->thermal_instances);
cdev->np = np;
cdev->ops = ops;
cdev->updated = false;
cdev->device.class = &thermal_class;
cdev->devdata = devdata;
dev_set_name(&cdev->device, "cooling_device%d", cdev->id);
result = device_register(&cdev->device);
if (result) {
release_idr(&thermal_cdev_idr, &thermal_idr_lock, cdev->id);
kfree(cdev);
return ERR_PTR(result);
}
/* sys I/F */
if (type) {
result = device_create_file(&cdev->device, &dev_attr_cdev_type);
if (result)
goto unregister;
}
result = device_create_file(&cdev->device, &dev_attr_max_state);
if (result)
goto unregister;
result = device_create_file(&cdev->device, &dev_attr_cur_state);
if (result)
goto unregister;
/* Add 'this' new cdev to the global cdev list */
mutex_lock(&thermal_list_lock);
list_add(&cdev->node, &thermal_cdev_list);
mutex_unlock(&thermal_list_lock);
/* Update binding information for 'this' new cdev */
bind_cdev(cdev);
return cdev;
unregister:
release_idr(&thermal_cdev_idr, &thermal_idr_lock, cdev->id);
device_unregister(&cdev->device);
return ERR_PTR(result);
}
/**
* thermal_cooling_device_register() - register a new thermal cooling device
* @type: the thermal cooling device type.
* @devdata: device private data.
* @ops: standard thermal cooling devices callbacks.
*
* This interface function adds a new thermal cooling device (fan/processor/...)
* to /sys/class/thermal/ folder as cooling_device[0-*]. It tries to bind itself
* to all the thermal zone devices registered at the same time.
*
* Return: a pointer to the created struct thermal_cooling_device or an
* ERR_PTR. Caller must check return value with IS_ERR*() helpers.
*/
struct thermal_cooling_device *
thermal_cooling_device_register(char *type, void *devdata,
const struct thermal_cooling_device_ops *ops)
{
return __thermal_cooling_device_register(NULL, type, devdata, ops);
}
EXPORT_SYMBOL_GPL(thermal_cooling_device_register);
/**
* thermal_of_cooling_device_register() - register an OF thermal cooling device
* @np: a pointer to a device tree node.
* @type: the thermal cooling device type.
* @devdata: device private data.
* @ops: standard thermal cooling devices callbacks.
*
* This function will register a cooling device with device tree node reference.
* This interface function adds a new thermal cooling device (fan/processor/...)
* to /sys/class/thermal/ folder as cooling_device[0-*]. It tries to bind itself
* to all the thermal zone devices registered at the same time.
*
* Return: a pointer to the created struct thermal_cooling_device or an
* ERR_PTR. Caller must check return value with IS_ERR*() helpers.
*/
struct thermal_cooling_device *
thermal_of_cooling_device_register(struct device_node *np,
char *type, void *devdata,
const struct thermal_cooling_device_ops *ops)
{
return __thermal_cooling_device_register(np, type, devdata, ops);
}
EXPORT_SYMBOL_GPL(thermal_of_cooling_device_register);
/**
* thermal_cooling_device_unregister - removes the registered thermal cooling device
* @cdev: the thermal cooling device to remove.
*
* thermal_cooling_device_unregister() must be called when the device is no
* longer needed.
*/
void thermal_cooling_device_unregister(struct thermal_cooling_device *cdev)
{
int i;
const struct thermal_zone_params *tzp;
struct thermal_zone_device *tz;
struct thermal_cooling_device *pos = NULL;
if (!cdev)
return;
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_cdev_list, node)
if (pos == cdev)
break;
if (pos != cdev) {
/* thermal cooling device not found */
mutex_unlock(&thermal_list_lock);
return;
}
list_del(&cdev->node);
/* Unbind all thermal zones associated with 'this' cdev */
list_for_each_entry(tz, &thermal_tz_list, node) {
if (tz->ops->unbind) {
tz->ops->unbind(tz, cdev);
continue;
}
if (!tz->tzp || !tz->tzp->tbp)
continue;
tzp = tz->tzp;
for (i = 0; i < tzp->num_tbps; i++) {
if (tzp->tbp[i].cdev == cdev) {
__unbind(tz, tzp->tbp[i].trip_mask, cdev);
tzp->tbp[i].cdev = NULL;
}
}
}
mutex_unlock(&thermal_list_lock);
if (cdev->type[0])
device_remove_file(&cdev->device, &dev_attr_cdev_type);
device_remove_file(&cdev->device, &dev_attr_max_state);
device_remove_file(&cdev->device, &dev_attr_cur_state);
release_idr(&thermal_cdev_idr, &thermal_idr_lock, cdev->id);
device_unregister(&cdev->device);
return;
}
EXPORT_SYMBOL_GPL(thermal_cooling_device_unregister);
void thermal_cdev_update(struct thermal_cooling_device *cdev)
{
struct thermal_instance *instance;
unsigned long target = 0;
/* cooling device is updated*/
if (cdev->updated)
return;
mutex_lock(&cdev->lock);
/* Make sure cdev enters the deepest cooling state */
list_for_each_entry(instance, &cdev->thermal_instances, cdev_node) {
dev_dbg(&cdev->device, "zone%d->target=%lu\n",
instance->tz->id, instance->target);
if (instance->target == THERMAL_NO_TARGET)
continue;
if (instance->target > target)
target = instance->target;
}
mutex_unlock(&cdev->lock);
cdev->ops->set_cur_state(cdev, target);
cdev->updated = true;
dev_dbg(&cdev->device, "set to state %lu\n", target);
}
EXPORT_SYMBOL(thermal_cdev_update);
/**
* thermal_notify_framework - Sensor drivers use this API to notify framework
* @tz: thermal zone device
* @trip: indicates which trip point has been crossed
*
* This function handles the trip events from sensor drivers. It starts
* throttling the cooling devices according to the policy configured.
* For CRITICAL and HOT trip points, this notifies the respective drivers,
* and does actual throttling for other trip points i.e ACTIVE and PASSIVE.
* The throttling policy is based on the configured platform data; if no
* platform data is provided, this uses the step_wise throttling policy.
*/
void thermal_notify_framework(struct thermal_zone_device *tz, int trip)
{
handle_thermal_trip(tz, trip);
}
EXPORT_SYMBOL_GPL(thermal_notify_framework);
/**
* create_trip_attrs() - create attributes for trip points
* @tz: the thermal zone device
* @mask: Writeable trip point bitmap.
*
* helper function to instantiate sysfs entries for every trip
* point and its properties of a struct thermal_zone_device.
*
* Return: 0 on success, the proper error value otherwise.
*/
static int create_trip_attrs(struct thermal_zone_device *tz, int mask)
{
int indx;
int size = sizeof(struct thermal_attr) * tz->trips;
tz->trip_type_attrs = kzalloc(size, GFP_KERNEL);
if (!tz->trip_type_attrs)
return -ENOMEM;
tz->trip_temp_attrs = kzalloc(size, GFP_KERNEL);
if (!tz->trip_temp_attrs) {
kfree(tz->trip_type_attrs);
return -ENOMEM;
}
if (tz->ops->get_trip_hyst) {
tz->trip_hyst_attrs = kzalloc(size, GFP_KERNEL);
if (!tz->trip_hyst_attrs) {
kfree(tz->trip_type_attrs);
kfree(tz->trip_temp_attrs);
return -ENOMEM;
}
}
for (indx = 0; indx < tz->trips; indx++) {
/* create trip type attribute */
snprintf(tz->trip_type_attrs[indx].name, THERMAL_NAME_LENGTH,
"trip_point_%d_type", indx);
sysfs_attr_init(&tz->trip_type_attrs[indx].attr.attr);
tz->trip_type_attrs[indx].attr.attr.name =
tz->trip_type_attrs[indx].name;
tz->trip_type_attrs[indx].attr.attr.mode = S_IRUGO;
tz->trip_type_attrs[indx].attr.show = trip_point_type_show;
device_create_file(&tz->device,
&tz->trip_type_attrs[indx].attr);
/* create trip temp attribute */
snprintf(tz->trip_temp_attrs[indx].name, THERMAL_NAME_LENGTH,
"trip_point_%d_temp", indx);
sysfs_attr_init(&tz->trip_temp_attrs[indx].attr.attr);
tz->trip_temp_attrs[indx].attr.attr.name =
tz->trip_temp_attrs[indx].name;
tz->trip_temp_attrs[indx].attr.attr.mode = S_IRUGO;
tz->trip_temp_attrs[indx].attr.show = trip_point_temp_show;
if (mask & (1 << indx)) {
tz->trip_temp_attrs[indx].attr.attr.mode |= S_IWUSR;
tz->trip_temp_attrs[indx].attr.store =
trip_point_temp_store;
}
device_create_file(&tz->device,
&tz->trip_temp_attrs[indx].attr);
/* create Optional trip hyst attribute */
if (!tz->ops->get_trip_hyst)
continue;
snprintf(tz->trip_hyst_attrs[indx].name, THERMAL_NAME_LENGTH,
"trip_point_%d_hyst", indx);
sysfs_attr_init(&tz->trip_hyst_attrs[indx].attr.attr);
tz->trip_hyst_attrs[indx].attr.attr.name =
tz->trip_hyst_attrs[indx].name;
tz->trip_hyst_attrs[indx].attr.attr.mode = S_IRUGO;
tz->trip_hyst_attrs[indx].attr.show = trip_point_hyst_show;
if (tz->ops->set_trip_hyst) {
tz->trip_hyst_attrs[indx].attr.attr.mode |= S_IWUSR;
tz->trip_hyst_attrs[indx].attr.store =
trip_point_hyst_store;
}
device_create_file(&tz->device,
&tz->trip_hyst_attrs[indx].attr);
}
return 0;
}
static void remove_trip_attrs(struct thermal_zone_device *tz)
{
int indx;
for (indx = 0; indx < tz->trips; indx++) {
device_remove_file(&tz->device,
&tz->trip_type_attrs[indx].attr);
device_remove_file(&tz->device,
&tz->trip_temp_attrs[indx].attr);
if (tz->ops->get_trip_hyst)
device_remove_file(&tz->device,
&tz->trip_hyst_attrs[indx].attr);
}
kfree(tz->trip_type_attrs);
kfree(tz->trip_temp_attrs);
kfree(tz->trip_hyst_attrs);
}
/**
* thermal_zone_device_register() - register a new thermal zone device
* @type: the thermal zone device type
* @trips: the number of trip points the thermal zone support
* @mask: a bit string indicating the writeablility of trip points
* @devdata: private device data
* @ops: standard thermal zone device callbacks
* @tzp: thermal zone platform parameters
* @passive_delay: number of milliseconds to wait between polls when
* performing passive cooling
* @polling_delay: number of milliseconds to wait between polls when checking
* whether trip points have been crossed (0 for interrupt
* driven systems)
*
* This interface function adds a new thermal zone device (sensor) to
* /sys/class/thermal folder as thermal_zone[0-*]. It tries to bind all the
* thermal cooling devices registered at the same time.
* thermal_zone_device_unregister() must be called when the device is no
* longer needed. The passive cooling depends on the .get_trend() return value.
*
* Return: a pointer to the created struct thermal_zone_device or an
* in case of error, an ERR_PTR. Caller must check return value with
* IS_ERR*() helpers.
*/
struct thermal_zone_device *thermal_zone_device_register(const char *type,
int trips, int mask, void *devdata,
struct thermal_zone_device_ops *ops,
const struct thermal_zone_params *tzp,
int passive_delay, int polling_delay)
{
struct thermal_zone_device *tz;
enum thermal_trip_type trip_type;
int result;
int count;
int passive = 0;
if (type && strlen(type) >= THERMAL_NAME_LENGTH)
return ERR_PTR(-EINVAL);
if (trips > THERMAL_MAX_TRIPS || trips < 0 || mask >> trips)
return ERR_PTR(-EINVAL);
if (!ops)
return ERR_PTR(-EINVAL);
if (trips > 0 && (!ops->get_trip_type || !ops->get_trip_temp))
return ERR_PTR(-EINVAL);
tz = kzalloc(sizeof(struct thermal_zone_device), GFP_KERNEL);
if (!tz)
return ERR_PTR(-ENOMEM);
INIT_LIST_HEAD(&tz->thermal_instances);
idr_init(&tz->idr);
mutex_init(&tz->lock);
result = get_idr(&thermal_tz_idr, &thermal_idr_lock, &tz->id);
if (result) {
kfree(tz);
return ERR_PTR(result);
}
strlcpy(tz->type, type ? : "", sizeof(tz->type));
tz->ops = ops;
tz->tzp = tzp;
tz->device.class = &thermal_class;
tz->devdata = devdata;
tz->trips = trips;
tz->passive_delay = passive_delay;
tz->polling_delay = polling_delay;
dev_set_name(&tz->device, "thermal_zone%d", tz->id);
result = device_register(&tz->device);
if (result) {
release_idr(&thermal_tz_idr, &thermal_idr_lock, tz->id);
kfree(tz);
return ERR_PTR(result);
}
/* sys I/F */
if (type) {
result = device_create_file(&tz->device, &dev_attr_type);
if (result)
goto unregister;
}
result = device_create_file(&tz->device, &dev_attr_temp);
if (result)
goto unregister;
if (ops->get_mode) {
result = device_create_file(&tz->device, &dev_attr_mode);
if (result)
goto unregister;
}
result = create_trip_attrs(tz, mask);
if (result)
goto unregister;
for (count = 0; count < trips; count++) {
tz->ops->get_trip_type(tz, count, &trip_type);
if (trip_type == THERMAL_TRIP_PASSIVE)
passive = 1;
}
if (!passive) {
result = device_create_file(&tz->device, &dev_attr_passive);
if (result)
goto unregister;
}
#ifdef CONFIG_THERMAL_EMULATION
result = device_create_file(&tz->device, &dev_attr_emul_temp);
if (result)
goto unregister;
#endif
/* Create policy attribute */
result = device_create_file(&tz->device, &dev_attr_policy);
if (result)
goto unregister;
/* Update 'this' zone's governor information */
mutex_lock(&thermal_governor_lock);
if (tz->tzp)
tz->governor = __find_governor(tz->tzp->governor_name);
else
tz->governor = def_governor;
mutex_unlock(&thermal_governor_lock);
if (!tz->tzp || !tz->tzp->no_hwmon) {
result = thermal_add_hwmon_sysfs(tz);
if (result)
goto unregister;
}
mutex_lock(&thermal_list_lock);
list_add_tail(&tz->node, &thermal_tz_list);
mutex_unlock(&thermal_list_lock);
/* Bind cooling devices for this zone */
bind_tz(tz);
INIT_DELAYED_WORK(&(tz->poll_queue), thermal_zone_device_check);
if (!tz->ops->get_temp)
thermal_zone_device_set_polling(tz, 0);
thermal_zone_device_update(tz);
if (!result)
return tz;
unregister:
release_idr(&thermal_tz_idr, &thermal_idr_lock, tz->id);
device_unregister(&tz->device);
return ERR_PTR(result);
}
EXPORT_SYMBOL_GPL(thermal_zone_device_register);
/**
* thermal_device_unregister - removes the registered thermal zone device
* @tz: the thermal zone device to remove
*/
void thermal_zone_device_unregister(struct thermal_zone_device *tz)
{
int i;
const struct thermal_zone_params *tzp;
struct thermal_cooling_device *cdev;
struct thermal_zone_device *pos = NULL;
if (!tz)
return;
tzp = tz->tzp;
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_tz_list, node)
if (pos == tz)
break;
if (pos != tz) {
/* thermal zone device not found */
mutex_unlock(&thermal_list_lock);
return;
}
list_del(&tz->node);
/* Unbind all cdevs associated with 'this' thermal zone */
list_for_each_entry(cdev, &thermal_cdev_list, node) {
if (tz->ops->unbind) {
tz->ops->unbind(tz, cdev);
continue;
}
if (!tzp || !tzp->tbp)
break;
for (i = 0; i < tzp->num_tbps; i++) {
if (tzp->tbp[i].cdev == cdev) {
__unbind(tz, tzp->tbp[i].trip_mask, cdev);
tzp->tbp[i].cdev = NULL;
}
}
}
mutex_unlock(&thermal_list_lock);
thermal_zone_device_set_polling(tz, 0);
if (tz->type[0])
device_remove_file(&tz->device, &dev_attr_type);
device_remove_file(&tz->device, &dev_attr_temp);
if (tz->ops->get_mode)
device_remove_file(&tz->device, &dev_attr_mode);
device_remove_file(&tz->device, &dev_attr_policy);
remove_trip_attrs(tz);
tz->governor = NULL;
thermal_remove_hwmon_sysfs(tz);
release_idr(&thermal_tz_idr, &thermal_idr_lock, tz->id);
idr_destroy(&tz->idr);
mutex_destroy(&tz->lock);
device_unregister(&tz->device);
return;
}
EXPORT_SYMBOL_GPL(thermal_zone_device_unregister);
/**
* thermal_zone_get_zone_by_name() - search for a zone and returns its ref
* @name: thermal zone name to fetch the temperature
*
* When only one zone is found with the passed name, returns a reference to it.
*
* Return: On success returns a reference to an unique thermal zone with
* matching name equals to @name, an ERR_PTR otherwise (-EINVAL for invalid
* paramenters, -ENODEV for not found and -EEXIST for multiple matches).
*/
struct thermal_zone_device *thermal_zone_get_zone_by_name(const char *name)
{
struct thermal_zone_device *pos = NULL, *ref = ERR_PTR(-EINVAL);
unsigned int found = 0;
if (!name)
goto exit;
mutex_lock(&thermal_list_lock);
list_for_each_entry(pos, &thermal_tz_list, node)
if (!strnicmp(name, pos->type, THERMAL_NAME_LENGTH)) {
found++;
ref = pos;
}
mutex_unlock(&thermal_list_lock);
/* nothing has been found, thus an error code for it */
if (found == 0)
ref = ERR_PTR(-ENODEV);
else if (found > 1)
/* Success only when an unique zone is found */
ref = ERR_PTR(-EEXIST);
exit:
return ref;
}
EXPORT_SYMBOL_GPL(thermal_zone_get_zone_by_name);
#ifdef CONFIG_NET
static const struct genl_multicast_group thermal_event_mcgrps[] = {
{ .name = THERMAL_GENL_MCAST_GROUP_NAME, },
};
static struct genl_family thermal_event_genl_family = {
.id = GENL_ID_GENERATE,
.name = THERMAL_GENL_FAMILY_NAME,
.version = THERMAL_GENL_VERSION,
.maxattr = THERMAL_GENL_ATTR_MAX,
.mcgrps = thermal_event_mcgrps,
.n_mcgrps = ARRAY_SIZE(thermal_event_mcgrps),
};
int thermal_generate_netlink_event(struct thermal_zone_device *tz,
enum events event)
{
struct sk_buff *skb;
struct nlattr *attr;
struct thermal_genl_event *thermal_event;
void *msg_header;
int size;
int result;
static unsigned int thermal_event_seqnum;
if (!tz)
return -EINVAL;
/* allocate memory */
size = nla_total_size(sizeof(struct thermal_genl_event)) +
nla_total_size(0);
skb = genlmsg_new(size, GFP_ATOMIC);
if (!skb)
return -ENOMEM;
/* add the genetlink message header */
msg_header = genlmsg_put(skb, 0, thermal_event_seqnum++,
&thermal_event_genl_family, 0,
THERMAL_GENL_CMD_EVENT);
if (!msg_header) {
nlmsg_free(skb);
return -ENOMEM;
}
/* fill the data */
attr = nla_reserve(skb, THERMAL_GENL_ATTR_EVENT,
sizeof(struct thermal_genl_event));
if (!attr) {
nlmsg_free(skb);
return -EINVAL;
}
thermal_event = nla_data(attr);
if (!thermal_event) {
nlmsg_free(skb);
return -EINVAL;
}
memset(thermal_event, 0, sizeof(struct thermal_genl_event));
thermal_event->orig = tz->id;
thermal_event->event = event;
/* send multicast genetlink message */
result = genlmsg_end(skb, msg_header);
if (result < 0) {
nlmsg_free(skb);
return result;
}
result = genlmsg_multicast(&thermal_event_genl_family, skb, 0,
0, GFP_ATOMIC);
if (result)
dev_err(&tz->device, "Failed to send netlink event:%d", result);
return result;
}
EXPORT_SYMBOL_GPL(thermal_generate_netlink_event);
static int genetlink_init(void)
{
return genl_register_family(&thermal_event_genl_family);
}
static void genetlink_exit(void)
{
genl_unregister_family(&thermal_event_genl_family);
}
#else /* !CONFIG_NET */
static inline int genetlink_init(void) { return 0; }
static inline void genetlink_exit(void) {}
#endif /* !CONFIG_NET */
static int __init thermal_register_governors(void)
{
int result;
result = thermal_gov_step_wise_register();
if (result)
return result;
result = thermal_gov_fair_share_register();
if (result)
return result;
return thermal_gov_user_space_register();
}
static void thermal_unregister_governors(void)
{
thermal_gov_step_wise_unregister();
thermal_gov_fair_share_unregister();
thermal_gov_user_space_unregister();
}
static int __init thermal_init(void)
{
int result;
result = thermal_register_governors();
if (result)
goto error;
result = class_register(&thermal_class);
if (result)
goto unregister_governors;
result = genetlink_init();
if (result)
goto unregister_class;
result = of_parse_thermal_zones();
if (result)
goto exit_netlink;
return 0;
exit_netlink:
genetlink_exit();
unregister_governors:
thermal_unregister_governors();
unregister_class:
class_unregister(&thermal_class);
error:
idr_destroy(&thermal_tz_idr);
idr_destroy(&thermal_cdev_idr);
mutex_destroy(&thermal_idr_lock);
mutex_destroy(&thermal_list_lock);
mutex_destroy(&thermal_governor_lock);
return result;
}
static void __exit thermal_exit(void)
{
of_thermal_destroy_zones();
genetlink_exit();
class_unregister(&thermal_class);
thermal_unregister_governors();
idr_destroy(&thermal_tz_idr);
idr_destroy(&thermal_cdev_idr);
mutex_destroy(&thermal_idr_lock);
mutex_destroy(&thermal_list_lock);
mutex_destroy(&thermal_governor_lock);
}
fs_initcall(thermal_init);
module_exit(thermal_exit);
| gpl-2.0 |
male-puppies/linux-3.18.pps | arch/x86/lib/hash.c | 538 | 2843 | /*
* Some portions derived from code covered by the following notice:
*
* Copyright (c) 2010-2013 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/hash.h>
#include <linux/init.h>
#include <asm/processor.h>
#include <asm/cpufeature.h>
#include <asm/hash.h>
static inline u32 crc32_u32(u32 crc, u32 val)
{
#ifdef CONFIG_AS_CRC32
asm ("crc32l %1,%0\n" : "+r" (crc) : "rm" (val));
#else
asm (".byte 0xf2, 0x0f, 0x38, 0xf1, 0xc1" : "+a" (crc) : "c" (val));
#endif
return crc;
}
static u32 intel_crc4_2_hash(const void *data, u32 len, u32 seed)
{
const u32 *p32 = (const u32 *) data;
u32 i, tmp = 0;
for (i = 0; i < len / 4; i++)
seed = crc32_u32(seed, *p32++);
switch (len & 3) {
case 3:
tmp |= *((const u8 *) p32 + 2) << 16;
/* fallthrough */
case 2:
tmp |= *((const u8 *) p32 + 1) << 8;
/* fallthrough */
case 1:
tmp |= *((const u8 *) p32);
seed = crc32_u32(seed, tmp);
break;
}
return seed;
}
static u32 intel_crc4_2_hash2(const u32 *data, u32 len, u32 seed)
{
const u32 *p32 = (const u32 *) data;
u32 i;
for (i = 0; i < len; i++)
seed = crc32_u32(seed, *p32++);
return seed;
}
void __init setup_arch_fast_hash(struct fast_hash_ops *ops)
{
if (cpu_has_xmm4_2) {
ops->hash = intel_crc4_2_hash;
ops->hash2 = intel_crc4_2_hash2;
}
}
| gpl-2.0 |
gablg1/ubuntu-vivid-docker-cr | fs/cifs/xattr.c | 538 | 12358 | /*
* fs/cifs/xattr.c
*
* Copyright (c) International Business Machines Corp., 2003, 2007
* Author(s): Steve French (sfrench@us.ibm.com)
*
* This 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.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; 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/posix_acl_xattr.h>
#include <linux/slab.h>
#include <linux/xattr.h>
#include "cifsfs.h"
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"
#include "cifs_fs_sb.h"
#include "cifs_unicode.h"
#define MAX_EA_VALUE_SIZE 65535
#define CIFS_XATTR_DOS_ATTRIB "user.DosAttrib"
#define CIFS_XATTR_CIFS_ACL "system.cifs_acl"
/* BB need to add server (Samba e.g) support for security and trusted prefix */
int cifs_removexattr(struct dentry *direntry, const char *ea_name)
{
int rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path = NULL;
if (direntry == NULL)
return -EIO;
if (direntry->d_inode == NULL)
return -EIO;
sb = direntry->d_inode->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto remove_ea_exit;
}
if (ea_name == NULL) {
cifs_dbg(FYI, "Null xattr names not supported\n");
} else if (strncmp(ea_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)
&& (strncmp(ea_name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN))) {
cifs_dbg(FYI,
"illegal xattr request %s (only user namespace supported)\n",
ea_name);
/* BB what if no namespace prefix? */
/* Should we just pass them to server, except for
system and perhaps security prefixes? */
} else {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto remove_ea_exit;
ea_name += XATTR_USER_PREFIX_LEN; /* skip past user. prefix */
if (pTcon->ses->server->ops->set_EA)
rc = pTcon->ses->server->ops->set_EA(xid, pTcon,
full_path, ea_name, NULL, (__u16)0,
cifs_sb->local_nls, cifs_remap(cifs_sb));
}
remove_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
int cifs_setxattr(struct dentry *direntry, const char *ea_name,
const void *ea_value, size_t value_size, int flags)
{
int rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path;
if (direntry == NULL)
return -EIO;
if (direntry->d_inode == NULL)
return -EIO;
sb = direntry->d_inode->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto set_ea_exit;
}
/* return dos attributes as pseudo xattr */
/* return alt name if available as pseudo attr */
/* if proc/fs/cifs/streamstoxattr is set then
search server for EAs or streams to
returns as xattrs */
if (value_size > MAX_EA_VALUE_SIZE) {
cifs_dbg(FYI, "size of EA value too large\n");
rc = -EOPNOTSUPP;
goto set_ea_exit;
}
if (ea_name == NULL) {
cifs_dbg(FYI, "Null xattr names not supported\n");
} else if (strncmp(ea_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)
== 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto set_ea_exit;
if (strncmp(ea_name, CIFS_XATTR_DOS_ATTRIB, 14) == 0)
cifs_dbg(FYI, "attempt to set cifs inode metadata\n");
ea_name += XATTR_USER_PREFIX_LEN; /* skip past user. prefix */
if (pTcon->ses->server->ops->set_EA)
rc = pTcon->ses->server->ops->set_EA(xid, pTcon,
full_path, ea_name, ea_value, (__u16)value_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN)
== 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto set_ea_exit;
ea_name += XATTR_OS2_PREFIX_LEN; /* skip past os2. prefix */
if (pTcon->ses->server->ops->set_EA)
rc = pTcon->ses->server->ops->set_EA(xid, pTcon,
full_path, ea_name, ea_value, (__u16)value_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, CIFS_XATTR_CIFS_ACL,
strlen(CIFS_XATTR_CIFS_ACL)) == 0) {
#ifdef CONFIG_CIFS_ACL
struct cifs_ntsd *pacl;
pacl = kmalloc(value_size, GFP_KERNEL);
if (!pacl) {
rc = -ENOMEM;
} else {
memcpy(pacl, ea_value, value_size);
if (pTcon->ses->server->ops->set_acl)
rc = pTcon->ses->server->ops->set_acl(pacl,
value_size, direntry->d_inode,
full_path, CIFS_ACL_DACL);
else
rc = -EOPNOTSUPP;
if (rc == 0) /* force revalidate of the inode */
CIFS_I(direntry->d_inode)->time = 0;
kfree(pacl);
}
#else
cifs_dbg(FYI, "Set CIFS ACL not supported yet\n");
#endif /* CONFIG_CIFS_ACL */
} else {
int temp;
temp = strncmp(ea_name, POSIX_ACL_XATTR_ACCESS,
strlen(POSIX_ACL_XATTR_ACCESS));
if (temp == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBSetPosixACL(xid, pTcon, full_path,
ea_value, (const int)value_size,
ACL_TYPE_ACCESS, cifs_sb->local_nls,
cifs_remap(cifs_sb));
cifs_dbg(FYI, "set POSIX ACL rc %d\n", rc);
#else
cifs_dbg(FYI, "set POSIX ACL not supported\n");
#endif
} else if (strncmp(ea_name, POSIX_ACL_XATTR_DEFAULT,
strlen(POSIX_ACL_XATTR_DEFAULT)) == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBSetPosixACL(xid, pTcon, full_path,
ea_value, (const int)value_size,
ACL_TYPE_DEFAULT, cifs_sb->local_nls,
cifs_remap(cifs_sb));
cifs_dbg(FYI, "set POSIX default ACL rc %d\n", rc);
#else
cifs_dbg(FYI, "set default POSIX ACL not supported\n");
#endif
} else {
cifs_dbg(FYI, "illegal xattr request %s (only user namespace supported)\n",
ea_name);
/* BB what if no namespace prefix? */
/* Should we just pass them to server, except for
system and perhaps security prefixes? */
}
}
set_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
ssize_t cifs_getxattr(struct dentry *direntry, const char *ea_name,
void *ea_value, size_t buf_size)
{
ssize_t rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path;
if (direntry == NULL)
return -EIO;
if (direntry->d_inode == NULL)
return -EIO;
sb = direntry->d_inode->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto get_ea_exit;
}
/* return dos attributes as pseudo xattr */
/* return alt name if available as pseudo attr */
if (ea_name == NULL) {
cifs_dbg(FYI, "Null xattr names not supported\n");
} else if (strncmp(ea_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)
== 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto get_ea_exit;
if (strncmp(ea_name, CIFS_XATTR_DOS_ATTRIB, 14) == 0) {
cifs_dbg(FYI, "attempt to query cifs inode metadata\n");
/* revalidate/getattr then populate from inode */
} /* BB add else when above is implemented */
ea_name += XATTR_USER_PREFIX_LEN; /* skip past user. prefix */
if (pTcon->ses->server->ops->query_all_EAs)
rc = pTcon->ses->server->ops->query_all_EAs(xid, pTcon,
full_path, ea_name, ea_value, buf_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN) == 0) {
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
goto get_ea_exit;
ea_name += XATTR_OS2_PREFIX_LEN; /* skip past os2. prefix */
if (pTcon->ses->server->ops->query_all_EAs)
rc = pTcon->ses->server->ops->query_all_EAs(xid, pTcon,
full_path, ea_name, ea_value, buf_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
} else if (strncmp(ea_name, POSIX_ACL_XATTR_ACCESS,
strlen(POSIX_ACL_XATTR_ACCESS)) == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBGetPosixACL(xid, pTcon, full_path,
ea_value, buf_size, ACL_TYPE_ACCESS,
cifs_sb->local_nls,
cifs_remap(cifs_sb));
#else
cifs_dbg(FYI, "Query POSIX ACL not supported yet\n");
#endif /* CONFIG_CIFS_POSIX */
} else if (strncmp(ea_name, POSIX_ACL_XATTR_DEFAULT,
strlen(POSIX_ACL_XATTR_DEFAULT)) == 0) {
#ifdef CONFIG_CIFS_POSIX
if (sb->s_flags & MS_POSIXACL)
rc = CIFSSMBGetPosixACL(xid, pTcon, full_path,
ea_value, buf_size, ACL_TYPE_DEFAULT,
cifs_sb->local_nls,
cifs_remap(cifs_sb));
#else
cifs_dbg(FYI, "Query POSIX default ACL not supported yet\n");
#endif /* CONFIG_CIFS_POSIX */
} else if (strncmp(ea_name, CIFS_XATTR_CIFS_ACL,
strlen(CIFS_XATTR_CIFS_ACL)) == 0) {
#ifdef CONFIG_CIFS_ACL
u32 acllen;
struct cifs_ntsd *pacl;
if (pTcon->ses->server->ops->get_acl == NULL)
goto get_ea_exit; /* rc already EOPNOTSUPP */
pacl = pTcon->ses->server->ops->get_acl(cifs_sb,
direntry->d_inode, full_path, &acllen);
if (IS_ERR(pacl)) {
rc = PTR_ERR(pacl);
cifs_dbg(VFS, "%s: error %zd getting sec desc\n",
__func__, rc);
} else {
if (ea_value) {
if (acllen > buf_size)
acllen = -ERANGE;
else
memcpy(ea_value, pacl, acllen);
}
rc = acllen;
kfree(pacl);
}
#else
cifs_dbg(FYI, "Query CIFS ACL not supported yet\n");
#endif /* CONFIG_CIFS_ACL */
} else if (strncmp(ea_name,
XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) == 0) {
cifs_dbg(FYI, "Trusted xattr namespace not supported yet\n");
} else if (strncmp(ea_name,
XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN) == 0) {
cifs_dbg(FYI, "Security xattr namespace not supported yet\n");
} else
cifs_dbg(FYI,
"illegal xattr request %s (only user namespace supported)\n",
ea_name);
/* We could add an additional check for streams ie
if proc/fs/cifs/streamstoxattr is set then
search server for EAs or streams to
returns as xattrs */
if (rc == -EINVAL)
rc = -EOPNOTSUPP;
get_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
ssize_t cifs_listxattr(struct dentry *direntry, char *data, size_t buf_size)
{
ssize_t rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
unsigned int xid;
struct cifs_sb_info *cifs_sb;
struct tcon_link *tlink;
struct cifs_tcon *pTcon;
struct super_block *sb;
char *full_path;
if (direntry == NULL)
return -EIO;
if (direntry->d_inode == NULL)
return -EIO;
sb = direntry->d_inode->i_sb;
if (sb == NULL)
return -EIO;
cifs_sb = CIFS_SB(sb);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
return -EOPNOTSUPP;
tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
pTcon = tlink_tcon(tlink);
xid = get_xid();
full_path = build_path_from_dentry(direntry);
if (full_path == NULL) {
rc = -ENOMEM;
goto list_ea_exit;
}
/* return dos attributes as pseudo xattr */
/* return alt name if available as pseudo attr */
/* if proc/fs/cifs/streamstoxattr is set then
search server for EAs or streams to
returns as xattrs */
if (pTcon->ses->server->ops->query_all_EAs)
rc = pTcon->ses->server->ops->query_all_EAs(xid, pTcon,
full_path, NULL, data, buf_size,
cifs_sb->local_nls, cifs_remap(cifs_sb));
list_ea_exit:
kfree(full_path);
free_xid(xid);
cifs_put_tlink(tlink);
#endif
return rc;
}
| gpl-2.0 |
Edgar86/boston-2.6.32.x | drivers/mtd/devices/doc2000.c | 1818 | 32664 |
/*
* Linux driver for Disk-On-Chip 2000 and Millennium
* (c) 1999 Machine Vision Holdings, Inc.
* (c) 1999, 2000 David Woodhouse <dwmw2@infradead.org>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/errno.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/bitops.h>
#include <linux/mutex.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/doc2000.h>
#define DOC_SUPPORT_2000
#define DOC_SUPPORT_2000TSOP
#define DOC_SUPPORT_MILLENNIUM
#ifdef DOC_SUPPORT_2000
#define DoC_is_2000(doc) (doc->ChipID == DOC_ChipID_Doc2k)
#else
#define DoC_is_2000(doc) (0)
#endif
#if defined(DOC_SUPPORT_2000TSOP) || defined(DOC_SUPPORT_MILLENNIUM)
#define DoC_is_Millennium(doc) (doc->ChipID == DOC_ChipID_DocMil)
#else
#define DoC_is_Millennium(doc) (0)
#endif
/* #define ECC_DEBUG */
/* I have no idea why some DoC chips can not use memcpy_from|to_io().
* This may be due to the different revisions of the ASIC controller built-in or
* simplily a QA/Bug issue. Who knows ?? If you have trouble, please uncomment
* this:
#undef USE_MEMCPY
*/
static int doc_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char *buf);
static int doc_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t *retlen, const u_char *buf);
static int doc_read_oob(struct mtd_info *mtd, loff_t ofs,
struct mtd_oob_ops *ops);
static int doc_write_oob(struct mtd_info *mtd, loff_t ofs,
struct mtd_oob_ops *ops);
static int doc_write_oob_nolock(struct mtd_info *mtd, loff_t ofs, size_t len,
size_t *retlen, const u_char *buf);
static int doc_erase (struct mtd_info *mtd, struct erase_info *instr);
static struct mtd_info *doc2klist = NULL;
/* Perform the required delay cycles by reading from the appropriate register */
static void DoC_Delay(struct DiskOnChip *doc, unsigned short cycles)
{
volatile char dummy;
int i;
for (i = 0; i < cycles; i++) {
if (DoC_is_Millennium(doc))
dummy = ReadDOC(doc->virtadr, NOP);
else
dummy = ReadDOC(doc->virtadr, DOCStatus);
}
}
/* DOC_WaitReady: Wait for RDY line to be asserted by the flash chip */
static int _DoC_WaitReady(struct DiskOnChip *doc)
{
void __iomem *docptr = doc->virtadr;
unsigned long timeo = jiffies + (HZ * 10);
DEBUG(MTD_DEBUG_LEVEL3,
"_DoC_WaitReady called for out-of-line wait\n");
/* Out-of-line routine to wait for chip response */
while (!(ReadDOC(docptr, CDSNControl) & CDSN_CTRL_FR_B)) {
/* issue 2 read from NOP register after reading from CDSNControl register
see Software Requirement 11.4 item 2. */
DoC_Delay(doc, 2);
if (time_after(jiffies, timeo)) {
DEBUG(MTD_DEBUG_LEVEL2, "_DoC_WaitReady timed out.\n");
return -EIO;
}
udelay(1);
cond_resched();
}
return 0;
}
static inline int DoC_WaitReady(struct DiskOnChip *doc)
{
void __iomem *docptr = doc->virtadr;
/* This is inline, to optimise the common case, where it's ready instantly */
int ret = 0;
/* 4 read form NOP register should be issued in prior to the read from CDSNControl
see Software Requirement 11.4 item 2. */
DoC_Delay(doc, 4);
if (!(ReadDOC(docptr, CDSNControl) & CDSN_CTRL_FR_B))
/* Call the out-of-line routine to wait */
ret = _DoC_WaitReady(doc);
/* issue 2 read from NOP register after reading from CDSNControl register
see Software Requirement 11.4 item 2. */
DoC_Delay(doc, 2);
return ret;
}
/* DoC_Command: Send a flash command to the flash chip through the CDSN Slow IO register to
bypass the internal pipeline. Each of 4 delay cycles (read from the NOP register) is
required after writing to CDSN Control register, see Software Requirement 11.4 item 3. */
static int DoC_Command(struct DiskOnChip *doc, unsigned char command,
unsigned char xtraflags)
{
void __iomem *docptr = doc->virtadr;
if (DoC_is_2000(doc))
xtraflags |= CDSN_CTRL_FLASH_IO;
/* Assert the CLE (Command Latch Enable) line to the flash chip */
WriteDOC(xtraflags | CDSN_CTRL_CLE | CDSN_CTRL_CE, docptr, CDSNControl);
DoC_Delay(doc, 4); /* Software requirement 11.4.3 for Millennium */
if (DoC_is_Millennium(doc))
WriteDOC(command, docptr, CDSNSlowIO);
/* Send the command */
WriteDOC_(command, docptr, doc->ioreg);
if (DoC_is_Millennium(doc))
WriteDOC(command, docptr, WritePipeTerm);
/* Lower the CLE line */
WriteDOC(xtraflags | CDSN_CTRL_CE, docptr, CDSNControl);
DoC_Delay(doc, 4); /* Software requirement 11.4.3 for Millennium */
/* Wait for the chip to respond - Software requirement 11.4.1 (extended for any command) */
return DoC_WaitReady(doc);
}
/* DoC_Address: Set the current address for the flash chip through the CDSN Slow IO register to
bypass the internal pipeline. Each of 4 delay cycles (read from the NOP register) is
required after writing to CDSN Control register, see Software Requirement 11.4 item 3. */
static int DoC_Address(struct DiskOnChip *doc, int numbytes, unsigned long ofs,
unsigned char xtraflags1, unsigned char xtraflags2)
{
int i;
void __iomem *docptr = doc->virtadr;
if (DoC_is_2000(doc))
xtraflags1 |= CDSN_CTRL_FLASH_IO;
/* Assert the ALE (Address Latch Enable) line to the flash chip */
WriteDOC(xtraflags1 | CDSN_CTRL_ALE | CDSN_CTRL_CE, docptr, CDSNControl);
DoC_Delay(doc, 4); /* Software requirement 11.4.3 for Millennium */
/* Send the address */
/* Devices with 256-byte page are addressed as:
Column (bits 0-7), Page (bits 8-15, 16-23, 24-31)
* there is no device on the market with page256
and more than 24 bits.
Devices with 512-byte page are addressed as:
Column (bits 0-7), Page (bits 9-16, 17-24, 25-31)
* 25-31 is sent only if the chip support it.
* bit 8 changes the read command to be sent
(NAND_CMD_READ0 or NAND_CMD_READ1).
*/
if (numbytes == ADDR_COLUMN || numbytes == ADDR_COLUMN_PAGE) {
if (DoC_is_Millennium(doc))
WriteDOC(ofs & 0xff, docptr, CDSNSlowIO);
WriteDOC_(ofs & 0xff, docptr, doc->ioreg);
}
if (doc->page256) {
ofs = ofs >> 8;
} else {
ofs = ofs >> 9;
}
if (numbytes == ADDR_PAGE || numbytes == ADDR_COLUMN_PAGE) {
for (i = 0; i < doc->pageadrlen; i++, ofs = ofs >> 8) {
if (DoC_is_Millennium(doc))
WriteDOC(ofs & 0xff, docptr, CDSNSlowIO);
WriteDOC_(ofs & 0xff, docptr, doc->ioreg);
}
}
if (DoC_is_Millennium(doc))
WriteDOC(ofs & 0xff, docptr, WritePipeTerm);
DoC_Delay(doc, 2); /* Needed for some slow flash chips. mf. */
/* FIXME: The SlowIO's for millennium could be replaced by
a single WritePipeTerm here. mf. */
/* Lower the ALE line */
WriteDOC(xtraflags1 | xtraflags2 | CDSN_CTRL_CE, docptr,
CDSNControl);
DoC_Delay(doc, 4); /* Software requirement 11.4.3 for Millennium */
/* Wait for the chip to respond - Software requirement 11.4.1 */
return DoC_WaitReady(doc);
}
/* Read a buffer from DoC, taking care of Millennium odditys */
static void DoC_ReadBuf(struct DiskOnChip *doc, u_char * buf, int len)
{
volatile int dummy;
int modulus = 0xffff;
void __iomem *docptr = doc->virtadr;
int i;
if (len <= 0)
return;
if (DoC_is_Millennium(doc)) {
/* Read the data via the internal pipeline through CDSN IO register,
see Pipelined Read Operations 11.3 */
dummy = ReadDOC(docptr, ReadPipeInit);
/* Millennium should use the LastDataRead register - Pipeline Reads */
len--;
/* This is needed for correctly ECC calculation */
modulus = 0xff;
}
for (i = 0; i < len; i++)
buf[i] = ReadDOC_(docptr, doc->ioreg + (i & modulus));
if (DoC_is_Millennium(doc)) {
buf[i] = ReadDOC(docptr, LastDataRead);
}
}
/* Write a buffer to DoC, taking care of Millennium odditys */
static void DoC_WriteBuf(struct DiskOnChip *doc, const u_char * buf, int len)
{
void __iomem *docptr = doc->virtadr;
int i;
if (len <= 0)
return;
for (i = 0; i < len; i++)
WriteDOC_(buf[i], docptr, doc->ioreg + i);
if (DoC_is_Millennium(doc)) {
WriteDOC(0x00, docptr, WritePipeTerm);
}
}
/* DoC_SelectChip: Select a given flash chip within the current floor */
static inline int DoC_SelectChip(struct DiskOnChip *doc, int chip)
{
void __iomem *docptr = doc->virtadr;
/* Software requirement 11.4.4 before writing DeviceSelect */
/* Deassert the CE line to eliminate glitches on the FCE# outputs */
WriteDOC(CDSN_CTRL_WP, docptr, CDSNControl);
DoC_Delay(doc, 4); /* Software requirement 11.4.3 for Millennium */
/* Select the individual flash chip requested */
WriteDOC(chip, docptr, CDSNDeviceSelect);
DoC_Delay(doc, 4);
/* Reassert the CE line */
WriteDOC(CDSN_CTRL_CE | CDSN_CTRL_FLASH_IO | CDSN_CTRL_WP, docptr,
CDSNControl);
DoC_Delay(doc, 4); /* Software requirement 11.4.3 for Millennium */
/* Wait for it to be ready */
return DoC_WaitReady(doc);
}
/* DoC_SelectFloor: Select a given floor (bank of flash chips) */
static inline int DoC_SelectFloor(struct DiskOnChip *doc, int floor)
{
void __iomem *docptr = doc->virtadr;
/* Select the floor (bank) of chips required */
WriteDOC(floor, docptr, FloorSelect);
/* Wait for the chip to be ready */
return DoC_WaitReady(doc);
}
/* DoC_IdentChip: Identify a given NAND chip given {floor,chip} */
static int DoC_IdentChip(struct DiskOnChip *doc, int floor, int chip)
{
int mfr, id, i, j;
volatile char dummy;
/* Page in the required floor/chip */
DoC_SelectFloor(doc, floor);
DoC_SelectChip(doc, chip);
/* Reset the chip */
if (DoC_Command(doc, NAND_CMD_RESET, CDSN_CTRL_WP)) {
DEBUG(MTD_DEBUG_LEVEL2,
"DoC_Command (reset) for %d,%d returned true\n",
floor, chip);
return 0;
}
/* Read the NAND chip ID: 1. Send ReadID command */
if (DoC_Command(doc, NAND_CMD_READID, CDSN_CTRL_WP)) {
DEBUG(MTD_DEBUG_LEVEL2,
"DoC_Command (ReadID) for %d,%d returned true\n",
floor, chip);
return 0;
}
/* Read the NAND chip ID: 2. Send address byte zero */
DoC_Address(doc, ADDR_COLUMN, 0, CDSN_CTRL_WP, 0);
/* Read the manufacturer and device id codes from the device */
if (DoC_is_Millennium(doc)) {
DoC_Delay(doc, 2);
dummy = ReadDOC(doc->virtadr, ReadPipeInit);
mfr = ReadDOC(doc->virtadr, LastDataRead);
DoC_Delay(doc, 2);
dummy = ReadDOC(doc->virtadr, ReadPipeInit);
id = ReadDOC(doc->virtadr, LastDataRead);
} else {
/* CDSN Slow IO register see Software Req 11.4 item 5. */
dummy = ReadDOC(doc->virtadr, CDSNSlowIO);
DoC_Delay(doc, 2);
mfr = ReadDOC_(doc->virtadr, doc->ioreg);
/* CDSN Slow IO register see Software Req 11.4 item 5. */
dummy = ReadDOC(doc->virtadr, CDSNSlowIO);
DoC_Delay(doc, 2);
id = ReadDOC_(doc->virtadr, doc->ioreg);
}
/* No response - return failure */
if (mfr == 0xff || mfr == 0)
return 0;
/* Check it's the same as the first chip we identified.
* M-Systems say that any given DiskOnChip device should only
* contain _one_ type of flash part, although that's not a
* hardware restriction. */
if (doc->mfr) {
if (doc->mfr == mfr && doc->id == id)
return 1; /* This is the same as the first */
else
printk(KERN_WARNING
"Flash chip at floor %d, chip %d is different:\n",
floor, chip);
}
/* Print and store the manufacturer and ID codes. */
for (i = 0; nand_flash_ids[i].name != NULL; i++) {
if (id == nand_flash_ids[i].id) {
/* Try to identify manufacturer */
for (j = 0; nand_manuf_ids[j].id != 0x0; j++) {
if (nand_manuf_ids[j].id == mfr)
break;
}
printk(KERN_INFO
"Flash chip found: Manufacturer ID: %2.2X, "
"Chip ID: %2.2X (%s:%s)\n", mfr, id,
nand_manuf_ids[j].name, nand_flash_ids[i].name);
if (!doc->mfr) {
doc->mfr = mfr;
doc->id = id;
doc->chipshift =
ffs((nand_flash_ids[i].chipsize << 20)) - 1;
doc->page256 = (nand_flash_ids[i].pagesize == 256) ? 1 : 0;
doc->pageadrlen = doc->chipshift > 25 ? 3 : 2;
doc->erasesize =
nand_flash_ids[i].erasesize;
return 1;
}
return 0;
}
}
/* We haven't fully identified the chip. Print as much as we know. */
printk(KERN_WARNING "Unknown flash chip found: %2.2X %2.2X\n",
id, mfr);
printk(KERN_WARNING "Please report to dwmw2@infradead.org\n");
return 0;
}
/* DoC_ScanChips: Find all NAND chips present in a DiskOnChip, and identify them */
static void DoC_ScanChips(struct DiskOnChip *this, int maxchips)
{
int floor, chip;
int numchips[MAX_FLOORS];
int ret = 1;
this->numchips = 0;
this->mfr = 0;
this->id = 0;
/* For each floor, find the number of valid chips it contains */
for (floor = 0; floor < MAX_FLOORS; floor++) {
ret = 1;
numchips[floor] = 0;
for (chip = 0; chip < maxchips && ret != 0; chip++) {
ret = DoC_IdentChip(this, floor, chip);
if (ret) {
numchips[floor]++;
this->numchips++;
}
}
}
/* If there are none at all that we recognise, bail */
if (!this->numchips) {
printk(KERN_NOTICE "No flash chips recognised.\n");
return;
}
/* Allocate an array to hold the information for each chip */
this->chips = kmalloc(sizeof(struct Nand) * this->numchips, GFP_KERNEL);
if (!this->chips) {
printk(KERN_NOTICE "No memory for allocating chip info structures\n");
return;
}
ret = 0;
/* Fill out the chip array with {floor, chipno} for each
* detected chip in the device. */
for (floor = 0; floor < MAX_FLOORS; floor++) {
for (chip = 0; chip < numchips[floor]; chip++) {
this->chips[ret].floor = floor;
this->chips[ret].chip = chip;
this->chips[ret].curadr = 0;
this->chips[ret].curmode = 0x50;
ret++;
}
}
/* Calculate and print the total size of the device */
this->totlen = this->numchips * (1 << this->chipshift);
printk(KERN_INFO "%d flash chips found. Total DiskOnChip size: %ld MiB\n",
this->numchips, this->totlen >> 20);
}
static int DoC2k_is_alias(struct DiskOnChip *doc1, struct DiskOnChip *doc2)
{
int tmp1, tmp2, retval;
if (doc1->physadr == doc2->physadr)
return 1;
/* Use the alias resolution register which was set aside for this
* purpose. If it's value is the same on both chips, they might
* be the same chip, and we write to one and check for a change in
* the other. It's unclear if this register is usuable in the
* DoC 2000 (it's in the Millennium docs), but it seems to work. */
tmp1 = ReadDOC(doc1->virtadr, AliasResolution);
tmp2 = ReadDOC(doc2->virtadr, AliasResolution);
if (tmp1 != tmp2)
return 0;
WriteDOC((tmp1 + 1) % 0xff, doc1->virtadr, AliasResolution);
tmp2 = ReadDOC(doc2->virtadr, AliasResolution);
if (tmp2 == (tmp1 + 1) % 0xff)
retval = 1;
else
retval = 0;
/* Restore register contents. May not be necessary, but do it just to
* be safe. */
WriteDOC(tmp1, doc1->virtadr, AliasResolution);
return retval;
}
/* This routine is found from the docprobe code by symbol_get(),
* which will bump the use count of this module. */
void DoC2k_init(struct mtd_info *mtd)
{
struct DiskOnChip *this = mtd->priv;
struct DiskOnChip *old = NULL;
int maxchips;
/* We must avoid being called twice for the same device. */
if (doc2klist)
old = doc2klist->priv;
while (old) {
if (DoC2k_is_alias(old, this)) {
printk(KERN_NOTICE
"Ignoring DiskOnChip 2000 at 0x%lX - already configured\n",
this->physadr);
iounmap(this->virtadr);
kfree(mtd);
return;
}
if (old->nextdoc)
old = old->nextdoc->priv;
else
old = NULL;
}
switch (this->ChipID) {
case DOC_ChipID_Doc2kTSOP:
mtd->name = "DiskOnChip 2000 TSOP";
this->ioreg = DoC_Mil_CDSN_IO;
/* Pretend it's a Millennium */
this->ChipID = DOC_ChipID_DocMil;
maxchips = MAX_CHIPS;
break;
case DOC_ChipID_Doc2k:
mtd->name = "DiskOnChip 2000";
this->ioreg = DoC_2k_CDSN_IO;
maxchips = MAX_CHIPS;
break;
case DOC_ChipID_DocMil:
mtd->name = "DiskOnChip Millennium";
this->ioreg = DoC_Mil_CDSN_IO;
maxchips = MAX_CHIPS_MIL;
break;
default:
printk("Unknown ChipID 0x%02x\n", this->ChipID);
kfree(mtd);
iounmap(this->virtadr);
return;
}
printk(KERN_NOTICE "%s found at address 0x%lX\n", mtd->name,
this->physadr);
mtd->type = MTD_NANDFLASH;
mtd->flags = MTD_CAP_NANDFLASH;
mtd->size = 0;
mtd->erasesize = 0;
mtd->writesize = 512;
mtd->oobsize = 16;
mtd->owner = THIS_MODULE;
mtd->erase = doc_erase;
mtd->point = NULL;
mtd->unpoint = NULL;
mtd->read = doc_read;
mtd->write = doc_write;
mtd->read_oob = doc_read_oob;
mtd->write_oob = doc_write_oob;
mtd->sync = NULL;
this->totlen = 0;
this->numchips = 0;
this->curfloor = -1;
this->curchip = -1;
mutex_init(&this->lock);
/* Ident all the chips present. */
DoC_ScanChips(this, maxchips);
if (!this->totlen) {
kfree(mtd);
iounmap(this->virtadr);
} else {
this->nextdoc = doc2klist;
doc2klist = mtd;
mtd->size = this->totlen;
mtd->erasesize = this->erasesize;
add_mtd_device(mtd);
return;
}
}
EXPORT_SYMBOL_GPL(DoC2k_init);
static int doc_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t * retlen, u_char * buf)
{
struct DiskOnChip *this = mtd->priv;
void __iomem *docptr = this->virtadr;
struct Nand *mychip;
unsigned char syndrome[6], eccbuf[6];
volatile char dummy;
int i, len256 = 0, ret=0;
size_t left = len;
/* Don't allow read past end of device */
if (from >= this->totlen)
return -EINVAL;
mutex_lock(&this->lock);
*retlen = 0;
while (left) {
len = left;
/* Don't allow a single read to cross a 512-byte block boundary */
if (from + len > ((from | 0x1ff) + 1))
len = ((from | 0x1ff) + 1) - from;
/* The ECC will not be calculated correctly if less than 512 is read */
if (len != 0x200)
printk(KERN_WARNING
"ECC needs a full sector read (adr: %lx size %lx)\n",
(long) from, (long) len);
/* printk("DoC_Read (adr: %lx size %lx)\n", (long) from, (long) len); */
/* Find the chip which is to be used and select it */
mychip = &this->chips[from >> (this->chipshift)];
if (this->curfloor != mychip->floor) {
DoC_SelectFloor(this, mychip->floor);
DoC_SelectChip(this, mychip->chip);
} else if (this->curchip != mychip->chip) {
DoC_SelectChip(this, mychip->chip);
}
this->curfloor = mychip->floor;
this->curchip = mychip->chip;
DoC_Command(this,
(!this->page256
&& (from & 0x100)) ? NAND_CMD_READ1 : NAND_CMD_READ0,
CDSN_CTRL_WP);
DoC_Address(this, ADDR_COLUMN_PAGE, from, CDSN_CTRL_WP,
CDSN_CTRL_ECC_IO);
/* Prime the ECC engine */
WriteDOC(DOC_ECC_RESET, docptr, ECCConf);
WriteDOC(DOC_ECC_EN, docptr, ECCConf);
/* treat crossing 256-byte sector for 2M x 8bits devices */
if (this->page256 && from + len > (from | 0xff) + 1) {
len256 = (from | 0xff) + 1 - from;
DoC_ReadBuf(this, buf, len256);
DoC_Command(this, NAND_CMD_READ0, CDSN_CTRL_WP);
DoC_Address(this, ADDR_COLUMN_PAGE, from + len256,
CDSN_CTRL_WP, CDSN_CTRL_ECC_IO);
}
DoC_ReadBuf(this, &buf[len256], len - len256);
/* Let the caller know we completed it */
*retlen += len;
/* Read the ECC data through the DiskOnChip ECC logic */
/* Note: this will work even with 2M x 8bit devices as */
/* they have 8 bytes of OOB per 256 page. mf. */
DoC_ReadBuf(this, eccbuf, 6);
/* Flush the pipeline */
if (DoC_is_Millennium(this)) {
dummy = ReadDOC(docptr, ECCConf);
dummy = ReadDOC(docptr, ECCConf);
i = ReadDOC(docptr, ECCConf);
} else {
dummy = ReadDOC(docptr, 2k_ECCStatus);
dummy = ReadDOC(docptr, 2k_ECCStatus);
i = ReadDOC(docptr, 2k_ECCStatus);
}
/* Check the ECC Status */
if (i & 0x80) {
int nb_errors;
/* There was an ECC error */
#ifdef ECC_DEBUG
printk(KERN_ERR "DiskOnChip ECC Error: Read at %lx\n", (long)from);
#endif
/* Read the ECC syndrom through the DiskOnChip ECC
logic. These syndrome will be all ZERO when there
is no error */
for (i = 0; i < 6; i++) {
syndrome[i] =
ReadDOC(docptr, ECCSyndrome0 + i);
}
nb_errors = doc_decode_ecc(buf, syndrome);
#ifdef ECC_DEBUG
printk(KERN_ERR "Errors corrected: %x\n", nb_errors);
#endif
if (nb_errors < 0) {
/* We return error, but have actually done the
read. Not that this can be told to
user-space, via sys_read(), but at least
MTD-aware stuff can know about it by
checking *retlen */
ret = -EIO;
}
}
#ifdef PSYCHO_DEBUG
printk(KERN_DEBUG "ECC DATA at %lxB: %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X\n",
(long)from, eccbuf[0], eccbuf[1], eccbuf[2],
eccbuf[3], eccbuf[4], eccbuf[5]);
#endif
/* disable the ECC engine */
WriteDOC(DOC_ECC_DIS, docptr , ECCConf);
/* according to 11.4.1, we need to wait for the busy line
* drop if we read to the end of the page. */
if(0 == ((from + len) & 0x1ff))
{
DoC_WaitReady(this);
}
from += len;
left -= len;
buf += len;
}
mutex_unlock(&this->lock);
return ret;
}
static int doc_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t * retlen, const u_char * buf)
{
struct DiskOnChip *this = mtd->priv;
int di; /* Yes, DI is a hangover from when I was disassembling the binary driver */
void __iomem *docptr = this->virtadr;
unsigned char eccbuf[6];
volatile char dummy;
int len256 = 0;
struct Nand *mychip;
size_t left = len;
int status;
/* Don't allow write past end of device */
if (to >= this->totlen)
return -EINVAL;
mutex_lock(&this->lock);
*retlen = 0;
while (left) {
len = left;
/* Don't allow a single write to cross a 512-byte block boundary */
if (to + len > ((to | 0x1ff) + 1))
len = ((to | 0x1ff) + 1) - to;
/* The ECC will not be calculated correctly if less than 512 is written */
/* DBB-
if (len != 0x200 && eccbuf)
printk(KERN_WARNING
"ECC needs a full sector write (adr: %lx size %lx)\n",
(long) to, (long) len);
-DBB */
/* printk("DoC_Write (adr: %lx size %lx)\n", (long) to, (long) len); */
/* Find the chip which is to be used and select it */
mychip = &this->chips[to >> (this->chipshift)];
if (this->curfloor != mychip->floor) {
DoC_SelectFloor(this, mychip->floor);
DoC_SelectChip(this, mychip->chip);
} else if (this->curchip != mychip->chip) {
DoC_SelectChip(this, mychip->chip);
}
this->curfloor = mychip->floor;
this->curchip = mychip->chip;
/* Set device to main plane of flash */
DoC_Command(this, NAND_CMD_RESET, CDSN_CTRL_WP);
DoC_Command(this,
(!this->page256
&& (to & 0x100)) ? NAND_CMD_READ1 : NAND_CMD_READ0,
CDSN_CTRL_WP);
DoC_Command(this, NAND_CMD_SEQIN, 0);
DoC_Address(this, ADDR_COLUMN_PAGE, to, 0, CDSN_CTRL_ECC_IO);
/* Prime the ECC engine */
WriteDOC(DOC_ECC_RESET, docptr, ECCConf);
WriteDOC(DOC_ECC_EN | DOC_ECC_RW, docptr, ECCConf);
/* treat crossing 256-byte sector for 2M x 8bits devices */
if (this->page256 && to + len > (to | 0xff) + 1) {
len256 = (to | 0xff) + 1 - to;
DoC_WriteBuf(this, buf, len256);
DoC_Command(this, NAND_CMD_PAGEPROG, 0);
DoC_Command(this, NAND_CMD_STATUS, CDSN_CTRL_WP);
/* There's an implicit DoC_WaitReady() in DoC_Command */
dummy = ReadDOC(docptr, CDSNSlowIO);
DoC_Delay(this, 2);
if (ReadDOC_(docptr, this->ioreg) & 1) {
printk(KERN_ERR "Error programming flash\n");
/* Error in programming */
*retlen = 0;
mutex_unlock(&this->lock);
return -EIO;
}
DoC_Command(this, NAND_CMD_SEQIN, 0);
DoC_Address(this, ADDR_COLUMN_PAGE, to + len256, 0,
CDSN_CTRL_ECC_IO);
}
DoC_WriteBuf(this, &buf[len256], len - len256);
WriteDOC(CDSN_CTRL_ECC_IO | CDSN_CTRL_CE, docptr, CDSNControl);
if (DoC_is_Millennium(this)) {
WriteDOC(0, docptr, NOP);
WriteDOC(0, docptr, NOP);
WriteDOC(0, docptr, NOP);
} else {
WriteDOC_(0, docptr, this->ioreg);
WriteDOC_(0, docptr, this->ioreg);
WriteDOC_(0, docptr, this->ioreg);
}
WriteDOC(CDSN_CTRL_ECC_IO | CDSN_CTRL_FLASH_IO | CDSN_CTRL_CE, docptr,
CDSNControl);
/* Read the ECC data through the DiskOnChip ECC logic */
for (di = 0; di < 6; di++) {
eccbuf[di] = ReadDOC(docptr, ECCSyndrome0 + di);
}
/* Reset the ECC engine */
WriteDOC(DOC_ECC_DIS, docptr, ECCConf);
#ifdef PSYCHO_DEBUG
printk
("OOB data at %lx is %2.2X %2.2X %2.2X %2.2X %2.2X %2.2X\n",
(long) to, eccbuf[0], eccbuf[1], eccbuf[2], eccbuf[3],
eccbuf[4], eccbuf[5]);
#endif
DoC_Command(this, NAND_CMD_PAGEPROG, 0);
DoC_Command(this, NAND_CMD_STATUS, CDSN_CTRL_WP);
/* There's an implicit DoC_WaitReady() in DoC_Command */
if (DoC_is_Millennium(this)) {
ReadDOC(docptr, ReadPipeInit);
status = ReadDOC(docptr, LastDataRead);
} else {
dummy = ReadDOC(docptr, CDSNSlowIO);
DoC_Delay(this, 2);
status = ReadDOC_(docptr, this->ioreg);
}
if (status & 1) {
printk(KERN_ERR "Error programming flash\n");
/* Error in programming */
*retlen = 0;
mutex_unlock(&this->lock);
return -EIO;
}
/* Let the caller know we completed it */
*retlen += len;
{
unsigned char x[8];
size_t dummy;
int ret;
/* Write the ECC data to flash */
for (di=0; di<6; di++)
x[di] = eccbuf[di];
x[6]=0x55;
x[7]=0x55;
ret = doc_write_oob_nolock(mtd, to, 8, &dummy, x);
if (ret) {
mutex_unlock(&this->lock);
return ret;
}
}
to += len;
left -= len;
buf += len;
}
mutex_unlock(&this->lock);
return 0;
}
static int doc_read_oob(struct mtd_info *mtd, loff_t ofs,
struct mtd_oob_ops *ops)
{
struct DiskOnChip *this = mtd->priv;
int len256 = 0, ret;
struct Nand *mychip;
uint8_t *buf = ops->oobbuf;
size_t len = ops->len;
BUG_ON(ops->mode != MTD_OOB_PLACE);
ofs += ops->ooboffs;
mutex_lock(&this->lock);
mychip = &this->chips[ofs >> this->chipshift];
if (this->curfloor != mychip->floor) {
DoC_SelectFloor(this, mychip->floor);
DoC_SelectChip(this, mychip->chip);
} else if (this->curchip != mychip->chip) {
DoC_SelectChip(this, mychip->chip);
}
this->curfloor = mychip->floor;
this->curchip = mychip->chip;
/* update address for 2M x 8bit devices. OOB starts on the second */
/* page to maintain compatibility with doc_read_ecc. */
if (this->page256) {
if (!(ofs & 0x8))
ofs += 0x100;
else
ofs -= 0x8;
}
DoC_Command(this, NAND_CMD_READOOB, CDSN_CTRL_WP);
DoC_Address(this, ADDR_COLUMN_PAGE, ofs, CDSN_CTRL_WP, 0);
/* treat crossing 8-byte OOB data for 2M x 8bit devices */
/* Note: datasheet says it should automaticaly wrap to the */
/* next OOB block, but it didn't work here. mf. */
if (this->page256 && ofs + len > (ofs | 0x7) + 1) {
len256 = (ofs | 0x7) + 1 - ofs;
DoC_ReadBuf(this, buf, len256);
DoC_Command(this, NAND_CMD_READOOB, CDSN_CTRL_WP);
DoC_Address(this, ADDR_COLUMN_PAGE, ofs & (~0x1ff),
CDSN_CTRL_WP, 0);
}
DoC_ReadBuf(this, &buf[len256], len - len256);
ops->retlen = len;
/* Reading the full OOB data drops us off of the end of the page,
* causing the flash device to go into busy mode, so we need
* to wait until ready 11.4.1 and Toshiba TC58256FT docs */
ret = DoC_WaitReady(this);
mutex_unlock(&this->lock);
return ret;
}
static int doc_write_oob_nolock(struct mtd_info *mtd, loff_t ofs, size_t len,
size_t * retlen, const u_char * buf)
{
struct DiskOnChip *this = mtd->priv;
int len256 = 0;
void __iomem *docptr = this->virtadr;
struct Nand *mychip = &this->chips[ofs >> this->chipshift];
volatile int dummy;
int status;
// printk("doc_write_oob(%lx, %d): %2.2X %2.2X %2.2X %2.2X ... %2.2X %2.2X .. %2.2X %2.2X\n",(long)ofs, len,
// buf[0], buf[1], buf[2], buf[3], buf[8], buf[9], buf[14],buf[15]);
/* Find the chip which is to be used and select it */
if (this->curfloor != mychip->floor) {
DoC_SelectFloor(this, mychip->floor);
DoC_SelectChip(this, mychip->chip);
} else if (this->curchip != mychip->chip) {
DoC_SelectChip(this, mychip->chip);
}
this->curfloor = mychip->floor;
this->curchip = mychip->chip;
/* disable the ECC engine */
WriteDOC (DOC_ECC_RESET, docptr, ECCConf);
WriteDOC (DOC_ECC_DIS, docptr, ECCConf);
/* Reset the chip, see Software Requirement 11.4 item 1. */
DoC_Command(this, NAND_CMD_RESET, CDSN_CTRL_WP);
/* issue the Read2 command to set the pointer to the Spare Data Area. */
DoC_Command(this, NAND_CMD_READOOB, CDSN_CTRL_WP);
/* update address for 2M x 8bit devices. OOB starts on the second */
/* page to maintain compatibility with doc_read_ecc. */
if (this->page256) {
if (!(ofs & 0x8))
ofs += 0x100;
else
ofs -= 0x8;
}
/* issue the Serial Data In command to initial the Page Program process */
DoC_Command(this, NAND_CMD_SEQIN, 0);
DoC_Address(this, ADDR_COLUMN_PAGE, ofs, 0, 0);
/* treat crossing 8-byte OOB data for 2M x 8bit devices */
/* Note: datasheet says it should automaticaly wrap to the */
/* next OOB block, but it didn't work here. mf. */
if (this->page256 && ofs + len > (ofs | 0x7) + 1) {
len256 = (ofs | 0x7) + 1 - ofs;
DoC_WriteBuf(this, buf, len256);
DoC_Command(this, NAND_CMD_PAGEPROG, 0);
DoC_Command(this, NAND_CMD_STATUS, 0);
/* DoC_WaitReady() is implicit in DoC_Command */
if (DoC_is_Millennium(this)) {
ReadDOC(docptr, ReadPipeInit);
status = ReadDOC(docptr, LastDataRead);
} else {
dummy = ReadDOC(docptr, CDSNSlowIO);
DoC_Delay(this, 2);
status = ReadDOC_(docptr, this->ioreg);
}
if (status & 1) {
printk(KERN_ERR "Error programming oob data\n");
/* There was an error */
*retlen = 0;
return -EIO;
}
DoC_Command(this, NAND_CMD_SEQIN, 0);
DoC_Address(this, ADDR_COLUMN_PAGE, ofs & (~0x1ff), 0, 0);
}
DoC_WriteBuf(this, &buf[len256], len - len256);
DoC_Command(this, NAND_CMD_PAGEPROG, 0);
DoC_Command(this, NAND_CMD_STATUS, 0);
/* DoC_WaitReady() is implicit in DoC_Command */
if (DoC_is_Millennium(this)) {
ReadDOC(docptr, ReadPipeInit);
status = ReadDOC(docptr, LastDataRead);
} else {
dummy = ReadDOC(docptr, CDSNSlowIO);
DoC_Delay(this, 2);
status = ReadDOC_(docptr, this->ioreg);
}
if (status & 1) {
printk(KERN_ERR "Error programming oob data\n");
/* There was an error */
*retlen = 0;
return -EIO;
}
*retlen = len;
return 0;
}
static int doc_write_oob(struct mtd_info *mtd, loff_t ofs,
struct mtd_oob_ops *ops)
{
struct DiskOnChip *this = mtd->priv;
int ret;
BUG_ON(ops->mode != MTD_OOB_PLACE);
mutex_lock(&this->lock);
ret = doc_write_oob_nolock(mtd, ofs + ops->ooboffs, ops->len,
&ops->retlen, ops->oobbuf);
mutex_unlock(&this->lock);
return ret;
}
static int doc_erase(struct mtd_info *mtd, struct erase_info *instr)
{
struct DiskOnChip *this = mtd->priv;
__u32 ofs = instr->addr;
__u32 len = instr->len;
volatile int dummy;
void __iomem *docptr = this->virtadr;
struct Nand *mychip;
int status;
mutex_lock(&this->lock);
if (ofs & (mtd->erasesize-1) || len & (mtd->erasesize-1)) {
mutex_unlock(&this->lock);
return -EINVAL;
}
instr->state = MTD_ERASING;
/* FIXME: Do this in the background. Use timers or schedule_task() */
while(len) {
mychip = &this->chips[ofs >> this->chipshift];
if (this->curfloor != mychip->floor) {
DoC_SelectFloor(this, mychip->floor);
DoC_SelectChip(this, mychip->chip);
} else if (this->curchip != mychip->chip) {
DoC_SelectChip(this, mychip->chip);
}
this->curfloor = mychip->floor;
this->curchip = mychip->chip;
DoC_Command(this, NAND_CMD_ERASE1, 0);
DoC_Address(this, ADDR_PAGE, ofs, 0, 0);
DoC_Command(this, NAND_CMD_ERASE2, 0);
DoC_Command(this, NAND_CMD_STATUS, CDSN_CTRL_WP);
if (DoC_is_Millennium(this)) {
ReadDOC(docptr, ReadPipeInit);
status = ReadDOC(docptr, LastDataRead);
} else {
dummy = ReadDOC(docptr, CDSNSlowIO);
DoC_Delay(this, 2);
status = ReadDOC_(docptr, this->ioreg);
}
if (status & 1) {
printk(KERN_ERR "Error erasing at 0x%x\n", ofs);
/* There was an error */
instr->state = MTD_ERASE_FAILED;
goto callback;
}
ofs += mtd->erasesize;
len -= mtd->erasesize;
}
instr->state = MTD_ERASE_DONE;
callback:
mtd_erase_callback(instr);
mutex_unlock(&this->lock);
return 0;
}
/****************************************************************************
*
* Module stuff
*
****************************************************************************/
static void __exit cleanup_doc2000(void)
{
struct mtd_info *mtd;
struct DiskOnChip *this;
while ((mtd = doc2klist)) {
this = mtd->priv;
doc2klist = this->nextdoc;
del_mtd_device(mtd);
iounmap(this->virtadr);
kfree(this->chips);
kfree(mtd);
}
}
module_exit(cleanup_doc2000);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org> et al.");
MODULE_DESCRIPTION("MTD driver for DiskOnChip 2000 and Millennium");
| gpl-2.0 |
AudioGod/Gods_kernel_YU | drivers/input/serio/hp_sdc.c | 2842 | 29156 | /*
* HP i8042-based System Device Controller driver.
*
* Copyright (c) 2001 Brian S. Julin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL").
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
*
* References:
* System Device Controller Microprocessor Firmware Theory of Operation
* for Part Number 1820-4784 Revision B. Dwg No. A-1820-4784-2
* Helge Deller's original hilkbd.c port for PA-RISC.
*
*
* Driver theory of operation:
*
* hp_sdc_put does all writing to the SDC. ISR can run on a different
* CPU than hp_sdc_put, but only one CPU runs hp_sdc_put at a time
* (it cannot really benefit from SMP anyway.) A tasket fit this perfectly.
*
* All data coming back from the SDC is sent via interrupt and can be read
* fully in the ISR, so there are no latency/throughput problems there.
* The problem is with output, due to the slow clock speed of the SDC
* compared to the CPU. This should not be too horrible most of the time,
* but if used with HIL devices that support the multibyte transfer command,
* keeping outbound throughput flowing at the 6500KBps that the HIL is
* capable of is more than can be done at HZ=100.
*
* Busy polling for IBF clear wastes CPU cycles and bus cycles. hp_sdc.ibf
* is set to 0 when the IBF flag in the status register has cleared. ISR
* may do this, and may also access the parts of queued transactions related
* to reading data back from the SDC, but otherwise will not touch the
* hp_sdc state. Whenever a register is written hp_sdc.ibf is set to 1.
*
* The i8042 write index and the values in the 4-byte input buffer
* starting at 0x70 are kept track of in hp_sdc.wi, and .r7[], respectively,
* to minimize the amount of IO needed to the SDC. However these values
* do not need to be locked since they are only ever accessed by hp_sdc_put.
*
* A timer task schedules the tasklet once per second just to make
* sure it doesn't freeze up and to allow for bad reads to time out.
*/
#include <linux/hp_sdc.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/time.h>
#include <linux/semaphore.h>
#include <linux/slab.h>
#include <linux/hil.h>
#include <asm/io.h>
/* Machine-specific abstraction */
#if defined(__hppa__)
# include <asm/parisc-device.h>
# define sdc_readb(p) gsc_readb(p)
# define sdc_writeb(v,p) gsc_writeb((v),(p))
#elif defined(__mc68000__)
# include <asm/uaccess.h>
# define sdc_readb(p) in_8(p)
# define sdc_writeb(v,p) out_8((p),(v))
#else
# error "HIL is not supported on this platform"
#endif
#define PREFIX "HP SDC: "
MODULE_AUTHOR("Brian S. Julin <bri@calyx.com>");
MODULE_DESCRIPTION("HP i8042-based SDC Driver");
MODULE_LICENSE("Dual BSD/GPL");
EXPORT_SYMBOL(hp_sdc_request_timer_irq);
EXPORT_SYMBOL(hp_sdc_request_hil_irq);
EXPORT_SYMBOL(hp_sdc_request_cooked_irq);
EXPORT_SYMBOL(hp_sdc_release_timer_irq);
EXPORT_SYMBOL(hp_sdc_release_hil_irq);
EXPORT_SYMBOL(hp_sdc_release_cooked_irq);
EXPORT_SYMBOL(__hp_sdc_enqueue_transaction);
EXPORT_SYMBOL(hp_sdc_enqueue_transaction);
EXPORT_SYMBOL(hp_sdc_dequeue_transaction);
static bool hp_sdc_disabled;
module_param_named(no_hpsdc, hp_sdc_disabled, bool, 0);
MODULE_PARM_DESC(no_hpsdc, "Do not enable HP SDC driver.");
static hp_i8042_sdc hp_sdc; /* All driver state is kept in here. */
/*************** primitives for use in any context *********************/
static inline uint8_t hp_sdc_status_in8(void)
{
uint8_t status;
unsigned long flags;
write_lock_irqsave(&hp_sdc.ibf_lock, flags);
status = sdc_readb(hp_sdc.status_io);
if (!(status & HP_SDC_STATUS_IBF))
hp_sdc.ibf = 0;
write_unlock_irqrestore(&hp_sdc.ibf_lock, flags);
return status;
}
static inline uint8_t hp_sdc_data_in8(void)
{
return sdc_readb(hp_sdc.data_io);
}
static inline void hp_sdc_status_out8(uint8_t val)
{
unsigned long flags;
write_lock_irqsave(&hp_sdc.ibf_lock, flags);
hp_sdc.ibf = 1;
if ((val & 0xf0) == 0xe0)
hp_sdc.wi = 0xff;
sdc_writeb(val, hp_sdc.status_io);
write_unlock_irqrestore(&hp_sdc.ibf_lock, flags);
}
static inline void hp_sdc_data_out8(uint8_t val)
{
unsigned long flags;
write_lock_irqsave(&hp_sdc.ibf_lock, flags);
hp_sdc.ibf = 1;
sdc_writeb(val, hp_sdc.data_io);
write_unlock_irqrestore(&hp_sdc.ibf_lock, flags);
}
/* Care must be taken to only invoke hp_sdc_spin_ibf when
* absolutely needed, or in rarely invoked subroutines.
* Not only does it waste CPU cycles, it also wastes bus cycles.
*/
static inline void hp_sdc_spin_ibf(void)
{
unsigned long flags;
rwlock_t *lock;
lock = &hp_sdc.ibf_lock;
read_lock_irqsave(lock, flags);
if (!hp_sdc.ibf) {
read_unlock_irqrestore(lock, flags);
return;
}
read_unlock(lock);
write_lock(lock);
while (sdc_readb(hp_sdc.status_io) & HP_SDC_STATUS_IBF)
{ }
hp_sdc.ibf = 0;
write_unlock_irqrestore(lock, flags);
}
/************************ Interrupt context functions ************************/
static void hp_sdc_take(int irq, void *dev_id, uint8_t status, uint8_t data)
{
hp_sdc_transaction *curr;
read_lock(&hp_sdc.rtq_lock);
if (hp_sdc.rcurr < 0) {
read_unlock(&hp_sdc.rtq_lock);
return;
}
curr = hp_sdc.tq[hp_sdc.rcurr];
read_unlock(&hp_sdc.rtq_lock);
curr->seq[curr->idx++] = status;
curr->seq[curr->idx++] = data;
hp_sdc.rqty -= 2;
do_gettimeofday(&hp_sdc.rtv);
if (hp_sdc.rqty <= 0) {
/* All data has been gathered. */
if (curr->seq[curr->actidx] & HP_SDC_ACT_SEMAPHORE)
if (curr->act.semaphore)
up(curr->act.semaphore);
if (curr->seq[curr->actidx] & HP_SDC_ACT_CALLBACK)
if (curr->act.irqhook)
curr->act.irqhook(irq, dev_id, status, data);
curr->actidx = curr->idx;
curr->idx++;
/* Return control of this transaction */
write_lock(&hp_sdc.rtq_lock);
hp_sdc.rcurr = -1;
hp_sdc.rqty = 0;
write_unlock(&hp_sdc.rtq_lock);
tasklet_schedule(&hp_sdc.task);
}
}
static irqreturn_t hp_sdc_isr(int irq, void *dev_id)
{
uint8_t status, data;
status = hp_sdc_status_in8();
/* Read data unconditionally to advance i8042. */
data = hp_sdc_data_in8();
/* For now we are ignoring these until we get the SDC to behave. */
if (((status & 0xf1) == 0x51) && data == 0x82)
return IRQ_HANDLED;
switch (status & HP_SDC_STATUS_IRQMASK) {
case 0: /* This case is not documented. */
break;
case HP_SDC_STATUS_USERTIMER:
case HP_SDC_STATUS_PERIODIC:
case HP_SDC_STATUS_TIMER:
read_lock(&hp_sdc.hook_lock);
if (hp_sdc.timer != NULL)
hp_sdc.timer(irq, dev_id, status, data);
read_unlock(&hp_sdc.hook_lock);
break;
case HP_SDC_STATUS_REG:
hp_sdc_take(irq, dev_id, status, data);
break;
case HP_SDC_STATUS_HILCMD:
case HP_SDC_STATUS_HILDATA:
read_lock(&hp_sdc.hook_lock);
if (hp_sdc.hil != NULL)
hp_sdc.hil(irq, dev_id, status, data);
read_unlock(&hp_sdc.hook_lock);
break;
case HP_SDC_STATUS_PUP:
read_lock(&hp_sdc.hook_lock);
if (hp_sdc.pup != NULL)
hp_sdc.pup(irq, dev_id, status, data);
else
printk(KERN_INFO PREFIX "HP SDC reports successful PUP.\n");
read_unlock(&hp_sdc.hook_lock);
break;
default:
read_lock(&hp_sdc.hook_lock);
if (hp_sdc.cooked != NULL)
hp_sdc.cooked(irq, dev_id, status, data);
read_unlock(&hp_sdc.hook_lock);
break;
}
return IRQ_HANDLED;
}
static irqreturn_t hp_sdc_nmisr(int irq, void *dev_id)
{
int status;
status = hp_sdc_status_in8();
printk(KERN_WARNING PREFIX "NMI !\n");
#if 0
if (status & HP_SDC_NMISTATUS_FHS) {
read_lock(&hp_sdc.hook_lock);
if (hp_sdc.timer != NULL)
hp_sdc.timer(irq, dev_id, status, 0);
read_unlock(&hp_sdc.hook_lock);
} else {
/* TODO: pass this on to the HIL handler, or do SAK here? */
printk(KERN_WARNING PREFIX "HIL NMI\n");
}
#endif
return IRQ_HANDLED;
}
/***************** Kernel (tasklet) context functions ****************/
unsigned long hp_sdc_put(void);
static void hp_sdc_tasklet(unsigned long foo)
{
write_lock_irq(&hp_sdc.rtq_lock);
if (hp_sdc.rcurr >= 0) {
struct timeval tv;
do_gettimeofday(&tv);
if (tv.tv_sec > hp_sdc.rtv.tv_sec)
tv.tv_usec += USEC_PER_SEC;
if (tv.tv_usec - hp_sdc.rtv.tv_usec > HP_SDC_MAX_REG_DELAY) {
hp_sdc_transaction *curr;
uint8_t tmp;
curr = hp_sdc.tq[hp_sdc.rcurr];
/* If this turns out to be a normal failure mode
* we'll need to figure out a way to communicate
* it back to the application. and be less verbose.
*/
printk(KERN_WARNING PREFIX "read timeout (%ius)!\n",
(int)(tv.tv_usec - hp_sdc.rtv.tv_usec));
curr->idx += hp_sdc.rqty;
hp_sdc.rqty = 0;
tmp = curr->seq[curr->actidx];
curr->seq[curr->actidx] |= HP_SDC_ACT_DEAD;
if (tmp & HP_SDC_ACT_SEMAPHORE)
if (curr->act.semaphore)
up(curr->act.semaphore);
if (tmp & HP_SDC_ACT_CALLBACK) {
/* Note this means that irqhooks may be called
* in tasklet/bh context.
*/
if (curr->act.irqhook)
curr->act.irqhook(0, NULL, 0, 0);
}
curr->actidx = curr->idx;
curr->idx++;
hp_sdc.rcurr = -1;
}
}
write_unlock_irq(&hp_sdc.rtq_lock);
hp_sdc_put();
}
unsigned long hp_sdc_put(void)
{
hp_sdc_transaction *curr;
uint8_t act;
int idx, curridx;
int limit = 0;
write_lock(&hp_sdc.lock);
/* If i8042 buffers are full, we cannot do anything that
requires output, so we skip to the administrativa. */
if (hp_sdc.ibf) {
hp_sdc_status_in8();
if (hp_sdc.ibf)
goto finish;
}
anew:
/* See if we are in the middle of a sequence. */
if (hp_sdc.wcurr < 0)
hp_sdc.wcurr = 0;
read_lock_irq(&hp_sdc.rtq_lock);
if (hp_sdc.rcurr == hp_sdc.wcurr)
hp_sdc.wcurr++;
read_unlock_irq(&hp_sdc.rtq_lock);
if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN)
hp_sdc.wcurr = 0;
curridx = hp_sdc.wcurr;
if (hp_sdc.tq[curridx] != NULL)
goto start;
while (++curridx != hp_sdc.wcurr) {
if (curridx >= HP_SDC_QUEUE_LEN) {
curridx = -1; /* Wrap to top */
continue;
}
read_lock_irq(&hp_sdc.rtq_lock);
if (hp_sdc.rcurr == curridx) {
read_unlock_irq(&hp_sdc.rtq_lock);
continue;
}
read_unlock_irq(&hp_sdc.rtq_lock);
if (hp_sdc.tq[curridx] != NULL)
break; /* Found one. */
}
if (curridx == hp_sdc.wcurr) { /* There's nothing queued to do. */
curridx = -1;
}
hp_sdc.wcurr = curridx;
start:
/* Check to see if the interrupt mask needs to be set. */
if (hp_sdc.set_im) {
hp_sdc_status_out8(hp_sdc.im | HP_SDC_CMD_SET_IM);
hp_sdc.set_im = 0;
goto finish;
}
if (hp_sdc.wcurr == -1)
goto done;
curr = hp_sdc.tq[curridx];
idx = curr->actidx;
if (curr->actidx >= curr->endidx) {
hp_sdc.tq[curridx] = NULL;
/* Interleave outbound data between the transactions. */
hp_sdc.wcurr++;
if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN)
hp_sdc.wcurr = 0;
goto finish;
}
act = curr->seq[idx];
idx++;
if (curr->idx >= curr->endidx) {
if (act & HP_SDC_ACT_DEALLOC)
kfree(curr);
hp_sdc.tq[curridx] = NULL;
/* Interleave outbound data between the transactions. */
hp_sdc.wcurr++;
if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN)
hp_sdc.wcurr = 0;
goto finish;
}
while (act & HP_SDC_ACT_PRECMD) {
if (curr->idx != idx) {
idx++;
act &= ~HP_SDC_ACT_PRECMD;
break;
}
hp_sdc_status_out8(curr->seq[idx]);
curr->idx++;
/* act finished? */
if ((act & HP_SDC_ACT_DURING) == HP_SDC_ACT_PRECMD)
goto actdone;
/* skip quantity field if data-out sequence follows. */
if (act & HP_SDC_ACT_DATAOUT)
curr->idx++;
goto finish;
}
if (act & HP_SDC_ACT_DATAOUT) {
int qty;
qty = curr->seq[idx];
idx++;
if (curr->idx - idx < qty) {
hp_sdc_data_out8(curr->seq[curr->idx]);
curr->idx++;
/* act finished? */
if (curr->idx - idx >= qty &&
(act & HP_SDC_ACT_DURING) == HP_SDC_ACT_DATAOUT)
goto actdone;
goto finish;
}
idx += qty;
act &= ~HP_SDC_ACT_DATAOUT;
} else
while (act & HP_SDC_ACT_DATAREG) {
int mask;
uint8_t w7[4];
mask = curr->seq[idx];
if (idx != curr->idx) {
idx++;
idx += !!(mask & 1);
idx += !!(mask & 2);
idx += !!(mask & 4);
idx += !!(mask & 8);
act &= ~HP_SDC_ACT_DATAREG;
break;
}
w7[0] = (mask & 1) ? curr->seq[++idx] : hp_sdc.r7[0];
w7[1] = (mask & 2) ? curr->seq[++idx] : hp_sdc.r7[1];
w7[2] = (mask & 4) ? curr->seq[++idx] : hp_sdc.r7[2];
w7[3] = (mask & 8) ? curr->seq[++idx] : hp_sdc.r7[3];
if (hp_sdc.wi > 0x73 || hp_sdc.wi < 0x70 ||
w7[hp_sdc.wi - 0x70] == hp_sdc.r7[hp_sdc.wi - 0x70]) {
int i = 0;
/* Need to point the write index register */
while (i < 4 && w7[i] == hp_sdc.r7[i])
i++;
if (i < 4) {
hp_sdc_status_out8(HP_SDC_CMD_SET_D0 + i);
hp_sdc.wi = 0x70 + i;
goto finish;
}
idx++;
if ((act & HP_SDC_ACT_DURING) == HP_SDC_ACT_DATAREG)
goto actdone;
curr->idx = idx;
act &= ~HP_SDC_ACT_DATAREG;
break;
}
hp_sdc_data_out8(w7[hp_sdc.wi - 0x70]);
hp_sdc.r7[hp_sdc.wi - 0x70] = w7[hp_sdc.wi - 0x70];
hp_sdc.wi++; /* write index register autoincrements */
{
int i = 0;
while ((i < 4) && w7[i] == hp_sdc.r7[i])
i++;
if (i >= 4) {
curr->idx = idx + 1;
if ((act & HP_SDC_ACT_DURING) ==
HP_SDC_ACT_DATAREG)
goto actdone;
}
}
goto finish;
}
/* We don't go any further in the command if there is a pending read,
because we don't want interleaved results. */
read_lock_irq(&hp_sdc.rtq_lock);
if (hp_sdc.rcurr >= 0) {
read_unlock_irq(&hp_sdc.rtq_lock);
goto finish;
}
read_unlock_irq(&hp_sdc.rtq_lock);
if (act & HP_SDC_ACT_POSTCMD) {
uint8_t postcmd;
/* curr->idx should == idx at this point. */
postcmd = curr->seq[idx];
curr->idx++;
if (act & HP_SDC_ACT_DATAIN) {
/* Start a new read */
hp_sdc.rqty = curr->seq[curr->idx];
do_gettimeofday(&hp_sdc.rtv);
curr->idx++;
/* Still need to lock here in case of spurious irq. */
write_lock_irq(&hp_sdc.rtq_lock);
hp_sdc.rcurr = curridx;
write_unlock_irq(&hp_sdc.rtq_lock);
hp_sdc_status_out8(postcmd);
goto finish;
}
hp_sdc_status_out8(postcmd);
goto actdone;
}
actdone:
if (act & HP_SDC_ACT_SEMAPHORE)
up(curr->act.semaphore);
else if (act & HP_SDC_ACT_CALLBACK)
curr->act.irqhook(0,NULL,0,0);
if (curr->idx >= curr->endidx) { /* This transaction is over. */
if (act & HP_SDC_ACT_DEALLOC)
kfree(curr);
hp_sdc.tq[curridx] = NULL;
} else {
curr->actidx = idx + 1;
curr->idx = idx + 2;
}
/* Interleave outbound data between the transactions. */
hp_sdc.wcurr++;
if (hp_sdc.wcurr >= HP_SDC_QUEUE_LEN)
hp_sdc.wcurr = 0;
finish:
/* If by some quirk IBF has cleared and our ISR has run to
see that that has happened, do it all again. */
if (!hp_sdc.ibf && limit++ < 20)
goto anew;
done:
if (hp_sdc.wcurr >= 0)
tasklet_schedule(&hp_sdc.task);
write_unlock(&hp_sdc.lock);
return 0;
}
/******* Functions called in either user or kernel context ****/
int __hp_sdc_enqueue_transaction(hp_sdc_transaction *this)
{
int i;
if (this == NULL) {
BUG();
return -EINVAL;
}
/* Can't have same transaction on queue twice */
for (i = 0; i < HP_SDC_QUEUE_LEN; i++)
if (hp_sdc.tq[i] == this)
goto fail;
this->actidx = 0;
this->idx = 1;
/* Search for empty slot */
for (i = 0; i < HP_SDC_QUEUE_LEN; i++)
if (hp_sdc.tq[i] == NULL) {
hp_sdc.tq[i] = this;
tasklet_schedule(&hp_sdc.task);
return 0;
}
printk(KERN_WARNING PREFIX "No free slot to add transaction.\n");
return -EBUSY;
fail:
printk(KERN_WARNING PREFIX "Transaction add failed: transaction already queued?\n");
return -EINVAL;
}
int hp_sdc_enqueue_transaction(hp_sdc_transaction *this) {
unsigned long flags;
int ret;
write_lock_irqsave(&hp_sdc.lock, flags);
ret = __hp_sdc_enqueue_transaction(this);
write_unlock_irqrestore(&hp_sdc.lock,flags);
return ret;
}
int hp_sdc_dequeue_transaction(hp_sdc_transaction *this)
{
unsigned long flags;
int i;
write_lock_irqsave(&hp_sdc.lock, flags);
/* TODO: don't remove it if it's not done. */
for (i = 0; i < HP_SDC_QUEUE_LEN; i++)
if (hp_sdc.tq[i] == this)
hp_sdc.tq[i] = NULL;
write_unlock_irqrestore(&hp_sdc.lock, flags);
return 0;
}
/********************** User context functions **************************/
int hp_sdc_request_timer_irq(hp_sdc_irqhook *callback)
{
if (callback == NULL || hp_sdc.dev == NULL)
return -EINVAL;
write_lock_irq(&hp_sdc.hook_lock);
if (hp_sdc.timer != NULL) {
write_unlock_irq(&hp_sdc.hook_lock);
return -EBUSY;
}
hp_sdc.timer = callback;
/* Enable interrupts from the timers */
hp_sdc.im &= ~HP_SDC_IM_FH;
hp_sdc.im &= ~HP_SDC_IM_PT;
hp_sdc.im &= ~HP_SDC_IM_TIMERS;
hp_sdc.set_im = 1;
write_unlock_irq(&hp_sdc.hook_lock);
tasklet_schedule(&hp_sdc.task);
return 0;
}
int hp_sdc_request_hil_irq(hp_sdc_irqhook *callback)
{
if (callback == NULL || hp_sdc.dev == NULL)
return -EINVAL;
write_lock_irq(&hp_sdc.hook_lock);
if (hp_sdc.hil != NULL) {
write_unlock_irq(&hp_sdc.hook_lock);
return -EBUSY;
}
hp_sdc.hil = callback;
hp_sdc.im &= ~(HP_SDC_IM_HIL | HP_SDC_IM_RESET);
hp_sdc.set_im = 1;
write_unlock_irq(&hp_sdc.hook_lock);
tasklet_schedule(&hp_sdc.task);
return 0;
}
int hp_sdc_request_cooked_irq(hp_sdc_irqhook *callback)
{
if (callback == NULL || hp_sdc.dev == NULL)
return -EINVAL;
write_lock_irq(&hp_sdc.hook_lock);
if (hp_sdc.cooked != NULL) {
write_unlock_irq(&hp_sdc.hook_lock);
return -EBUSY;
}
/* Enable interrupts from the HIL MLC */
hp_sdc.cooked = callback;
hp_sdc.im &= ~(HP_SDC_IM_HIL | HP_SDC_IM_RESET);
hp_sdc.set_im = 1;
write_unlock_irq(&hp_sdc.hook_lock);
tasklet_schedule(&hp_sdc.task);
return 0;
}
int hp_sdc_release_timer_irq(hp_sdc_irqhook *callback)
{
write_lock_irq(&hp_sdc.hook_lock);
if ((callback != hp_sdc.timer) ||
(hp_sdc.timer == NULL)) {
write_unlock_irq(&hp_sdc.hook_lock);
return -EINVAL;
}
/* Disable interrupts from the timers */
hp_sdc.timer = NULL;
hp_sdc.im |= HP_SDC_IM_TIMERS;
hp_sdc.im |= HP_SDC_IM_FH;
hp_sdc.im |= HP_SDC_IM_PT;
hp_sdc.set_im = 1;
write_unlock_irq(&hp_sdc.hook_lock);
tasklet_schedule(&hp_sdc.task);
return 0;
}
int hp_sdc_release_hil_irq(hp_sdc_irqhook *callback)
{
write_lock_irq(&hp_sdc.hook_lock);
if ((callback != hp_sdc.hil) ||
(hp_sdc.hil == NULL)) {
write_unlock_irq(&hp_sdc.hook_lock);
return -EINVAL;
}
hp_sdc.hil = NULL;
/* Disable interrupts from HIL only if there is no cooked driver. */
if(hp_sdc.cooked == NULL) {
hp_sdc.im |= (HP_SDC_IM_HIL | HP_SDC_IM_RESET);
hp_sdc.set_im = 1;
}
write_unlock_irq(&hp_sdc.hook_lock);
tasklet_schedule(&hp_sdc.task);
return 0;
}
int hp_sdc_release_cooked_irq(hp_sdc_irqhook *callback)
{
write_lock_irq(&hp_sdc.hook_lock);
if ((callback != hp_sdc.cooked) ||
(hp_sdc.cooked == NULL)) {
write_unlock_irq(&hp_sdc.hook_lock);
return -EINVAL;
}
hp_sdc.cooked = NULL;
/* Disable interrupts from HIL only if there is no raw HIL driver. */
if(hp_sdc.hil == NULL) {
hp_sdc.im |= (HP_SDC_IM_HIL | HP_SDC_IM_RESET);
hp_sdc.set_im = 1;
}
write_unlock_irq(&hp_sdc.hook_lock);
tasklet_schedule(&hp_sdc.task);
return 0;
}
/************************* Keepalive timer task *********************/
static void hp_sdc_kicker(unsigned long data)
{
tasklet_schedule(&hp_sdc.task);
/* Re-insert the periodic task. */
mod_timer(&hp_sdc.kicker, jiffies + HZ);
}
/************************** Module Initialization ***************************/
#if defined(__hppa__)
static const struct parisc_device_id hp_sdc_tbl[] = {
{
.hw_type = HPHW_FIO,
.hversion_rev = HVERSION_REV_ANY_ID,
.hversion = HVERSION_ANY_ID,
.sversion = 0x73,
},
{ 0, }
};
MODULE_DEVICE_TABLE(parisc, hp_sdc_tbl);
static int __init hp_sdc_init_hppa(struct parisc_device *d);
static struct delayed_work moduleloader_work;
static struct parisc_driver hp_sdc_driver = {
.name = "hp_sdc",
.id_table = hp_sdc_tbl,
.probe = hp_sdc_init_hppa,
};
#endif /* __hppa__ */
static int __init hp_sdc_init(void)
{
char *errstr;
hp_sdc_transaction t_sync;
uint8_t ts_sync[6];
struct semaphore s_sync;
rwlock_init(&hp_sdc.lock);
rwlock_init(&hp_sdc.ibf_lock);
rwlock_init(&hp_sdc.rtq_lock);
rwlock_init(&hp_sdc.hook_lock);
hp_sdc.timer = NULL;
hp_sdc.hil = NULL;
hp_sdc.pup = NULL;
hp_sdc.cooked = NULL;
hp_sdc.im = HP_SDC_IM_MASK; /* Mask maskable irqs */
hp_sdc.set_im = 1;
hp_sdc.wi = 0xff;
hp_sdc.r7[0] = 0xff;
hp_sdc.r7[1] = 0xff;
hp_sdc.r7[2] = 0xff;
hp_sdc.r7[3] = 0xff;
hp_sdc.ibf = 1;
memset(&hp_sdc.tq, 0, sizeof(hp_sdc.tq));
hp_sdc.wcurr = -1;
hp_sdc.rcurr = -1;
hp_sdc.rqty = 0;
hp_sdc.dev_err = -ENODEV;
errstr = "IO not found for";
if (!hp_sdc.base_io)
goto err0;
errstr = "IRQ not found for";
if (!hp_sdc.irq)
goto err0;
hp_sdc.dev_err = -EBUSY;
#if defined(__hppa__)
errstr = "IO not available for";
if (request_region(hp_sdc.data_io, 2, hp_sdc_driver.name))
goto err0;
#endif
errstr = "IRQ not available for";
if (request_irq(hp_sdc.irq, &hp_sdc_isr, IRQF_SHARED,
"HP SDC", &hp_sdc))
goto err1;
errstr = "NMI not available for";
if (request_irq(hp_sdc.nmi, &hp_sdc_nmisr, IRQF_SHARED,
"HP SDC NMI", &hp_sdc))
goto err2;
printk(KERN_INFO PREFIX "HP SDC at 0x%p, IRQ %d (NMI IRQ %d)\n",
(void *)hp_sdc.base_io, hp_sdc.irq, hp_sdc.nmi);
hp_sdc_status_in8();
hp_sdc_data_in8();
tasklet_init(&hp_sdc.task, hp_sdc_tasklet, 0);
/* Sync the output buffer registers, thus scheduling hp_sdc_tasklet. */
t_sync.actidx = 0;
t_sync.idx = 1;
t_sync.endidx = 6;
t_sync.seq = ts_sync;
ts_sync[0] = HP_SDC_ACT_DATAREG | HP_SDC_ACT_SEMAPHORE;
ts_sync[1] = 0x0f;
ts_sync[2] = ts_sync[3] = ts_sync[4] = ts_sync[5] = 0;
t_sync.act.semaphore = &s_sync;
sema_init(&s_sync, 0);
hp_sdc_enqueue_transaction(&t_sync);
down(&s_sync); /* Wait for t_sync to complete */
/* Create the keepalive task */
init_timer(&hp_sdc.kicker);
hp_sdc.kicker.expires = jiffies + HZ;
hp_sdc.kicker.function = &hp_sdc_kicker;
add_timer(&hp_sdc.kicker);
hp_sdc.dev_err = 0;
return 0;
err2:
free_irq(hp_sdc.irq, &hp_sdc);
err1:
release_region(hp_sdc.data_io, 2);
err0:
printk(KERN_WARNING PREFIX ": %s SDC IO=0x%p IRQ=0x%x NMI=0x%x\n",
errstr, (void *)hp_sdc.base_io, hp_sdc.irq, hp_sdc.nmi);
hp_sdc.dev = NULL;
return hp_sdc.dev_err;
}
#if defined(__hppa__)
static void request_module_delayed(struct work_struct *work)
{
request_module("hp_sdc_mlc");
}
static int __init hp_sdc_init_hppa(struct parisc_device *d)
{
int ret;
if (!d)
return 1;
if (hp_sdc.dev != NULL)
return 1; /* We only expect one SDC */
hp_sdc.dev = d;
hp_sdc.irq = d->irq;
hp_sdc.nmi = d->aux_irq;
hp_sdc.base_io = d->hpa.start;
hp_sdc.data_io = d->hpa.start + 0x800;
hp_sdc.status_io = d->hpa.start + 0x801;
INIT_DELAYED_WORK(&moduleloader_work, request_module_delayed);
ret = hp_sdc_init();
/* after successful initialization give SDC some time to settle
* and then load the hp_sdc_mlc upper layer driver */
if (!ret)
schedule_delayed_work(&moduleloader_work,
msecs_to_jiffies(2000));
return ret;
}
#endif /* __hppa__ */
static void hp_sdc_exit(void)
{
/* do nothing if we don't have a SDC */
if (!hp_sdc.dev)
return;
write_lock_irq(&hp_sdc.lock);
/* Turn off all maskable "sub-function" irq's. */
hp_sdc_spin_ibf();
sdc_writeb(HP_SDC_CMD_SET_IM | HP_SDC_IM_MASK, hp_sdc.status_io);
/* Wait until we know this has been processed by the i8042 */
hp_sdc_spin_ibf();
free_irq(hp_sdc.nmi, &hp_sdc);
free_irq(hp_sdc.irq, &hp_sdc);
write_unlock_irq(&hp_sdc.lock);
del_timer(&hp_sdc.kicker);
tasklet_kill(&hp_sdc.task);
#if defined(__hppa__)
cancel_delayed_work_sync(&moduleloader_work);
if (unregister_parisc_driver(&hp_sdc_driver))
printk(KERN_WARNING PREFIX "Error unregistering HP SDC");
#endif
}
static int __init hp_sdc_register(void)
{
hp_sdc_transaction tq_init;
uint8_t tq_init_seq[5];
struct semaphore tq_init_sem;
#if defined(__mc68000__)
mm_segment_t fs;
unsigned char i;
#endif
if (hp_sdc_disabled) {
printk(KERN_WARNING PREFIX "HP SDC driver disabled by no_hpsdc=1.\n");
return -ENODEV;
}
hp_sdc.dev = NULL;
hp_sdc.dev_err = 0;
#if defined(__hppa__)
if (register_parisc_driver(&hp_sdc_driver)) {
printk(KERN_WARNING PREFIX "Error registering SDC with system bus tree.\n");
return -ENODEV;
}
#elif defined(__mc68000__)
if (!MACH_IS_HP300)
return -ENODEV;
hp_sdc.irq = 1;
hp_sdc.nmi = 7;
hp_sdc.base_io = (unsigned long) 0xf0428000;
hp_sdc.data_io = (unsigned long) hp_sdc.base_io + 1;
hp_sdc.status_io = (unsigned long) hp_sdc.base_io + 3;
fs = get_fs();
set_fs(KERNEL_DS);
if (!get_user(i, (unsigned char *)hp_sdc.data_io))
hp_sdc.dev = (void *)1;
set_fs(fs);
hp_sdc.dev_err = hp_sdc_init();
#endif
if (hp_sdc.dev == NULL) {
printk(KERN_WARNING PREFIX "No SDC found.\n");
return hp_sdc.dev_err;
}
sema_init(&tq_init_sem, 0);
tq_init.actidx = 0;
tq_init.idx = 1;
tq_init.endidx = 5;
tq_init.seq = tq_init_seq;
tq_init.act.semaphore = &tq_init_sem;
tq_init_seq[0] =
HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN | HP_SDC_ACT_SEMAPHORE;
tq_init_seq[1] = HP_SDC_CMD_READ_KCC;
tq_init_seq[2] = 1;
tq_init_seq[3] = 0;
tq_init_seq[4] = 0;
hp_sdc_enqueue_transaction(&tq_init);
down(&tq_init_sem);
up(&tq_init_sem);
if ((tq_init_seq[0] & HP_SDC_ACT_DEAD) == HP_SDC_ACT_DEAD) {
printk(KERN_WARNING PREFIX "Error reading config byte.\n");
hp_sdc_exit();
return -ENODEV;
}
hp_sdc.r11 = tq_init_seq[4];
if (hp_sdc.r11 & HP_SDC_CFG_NEW) {
const char *str;
printk(KERN_INFO PREFIX "New style SDC\n");
tq_init_seq[1] = HP_SDC_CMD_READ_XTD;
tq_init.actidx = 0;
tq_init.idx = 1;
down(&tq_init_sem);
hp_sdc_enqueue_transaction(&tq_init);
down(&tq_init_sem);
up(&tq_init_sem);
if ((tq_init_seq[0] & HP_SDC_ACT_DEAD) == HP_SDC_ACT_DEAD) {
printk(KERN_WARNING PREFIX "Error reading extended config byte.\n");
return -ENODEV;
}
hp_sdc.r7e = tq_init_seq[4];
HP_SDC_XTD_REV_STRINGS(hp_sdc.r7e & HP_SDC_XTD_REV, str)
printk(KERN_INFO PREFIX "Revision: %s\n", str);
if (hp_sdc.r7e & HP_SDC_XTD_BEEPER)
printk(KERN_INFO PREFIX "TI SN76494 beeper present\n");
if (hp_sdc.r7e & HP_SDC_XTD_BBRTC)
printk(KERN_INFO PREFIX "OKI MSM-58321 BBRTC present\n");
printk(KERN_INFO PREFIX "Spunking the self test register to force PUP "
"on next firmware reset.\n");
tq_init_seq[0] = HP_SDC_ACT_PRECMD |
HP_SDC_ACT_DATAOUT | HP_SDC_ACT_SEMAPHORE;
tq_init_seq[1] = HP_SDC_CMD_SET_STR;
tq_init_seq[2] = 1;
tq_init_seq[3] = 0;
tq_init.actidx = 0;
tq_init.idx = 1;
tq_init.endidx = 4;
down(&tq_init_sem);
hp_sdc_enqueue_transaction(&tq_init);
down(&tq_init_sem);
up(&tq_init_sem);
} else
printk(KERN_INFO PREFIX "Old style SDC (1820-%s).\n",
(hp_sdc.r11 & HP_SDC_CFG_REV) ? "3300" : "2564/3087");
return 0;
}
module_init(hp_sdc_register);
module_exit(hp_sdc_exit);
/* Timing notes: These measurements taken on my 64MHz 7100-LC (715/64)
* cycles cycles-adj time
* between two consecutive mfctl(16)'s: 4 n/a 63ns
* hp_sdc_spin_ibf when idle: 119 115 1.7us
* gsc_writeb status register: 83 79 1.2us
* IBF to clear after sending SET_IM: 6204 6006 93us
* IBF to clear after sending LOAD_RT: 4467 4352 68us
* IBF to clear after sending two LOAD_RTs: 18974 18859 295us
* READ_T1, read status/data, IRQ, call handler: 35564 n/a 556us
* cmd to ~IBF READ_T1 2nd time right after: 5158403 n/a 81ms
* between IRQ received and ~IBF for above: 2578877 n/a 40ms
*
* Performance stats after a run of this module configuring HIL and
* receiving a few mouse events:
*
* status in8 282508 cycles 7128 calls
* status out8 8404 cycles 341 calls
* data out8 1734 cycles 78 calls
* isr 174324 cycles 617 calls (includes take)
* take 1241 cycles 2 calls
* put 1411504 cycles 6937 calls
* task 1655209 cycles 6937 calls (includes put)
*
*/
| gpl-2.0 |
syshack/KVMGT-kernel | drivers/media/usb/pwc/pwc-v4l.c | 2842 | 29833 | /* Linux driver for Philips webcam
USB and Video4Linux interface part.
(C) 1999-2004 Nemosoft Unv.
(C) 2004-2006 Luc Saillard (luc@saillard.org)
(C) 2011 Hans de Goede <hdegoede@redhat.com>
NOTE: this version of pwc is an unofficial (modified) release of pwc & pcwx
driver and thus may have bugs that are not present in the original version.
Please send bug reports and support requests to <luc@saillard.org>.
The decompression routines have been implemented by reverse-engineering the
Nemosoft binary pwcx module. Caveat emptor.
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/errno.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/vmalloc.h>
#include <linux/jiffies.h>
#include <asm/io.h>
#include "pwc.h"
#define PWC_CID_CUSTOM(ctrl) ((V4L2_CID_USER_BASE | 0xf000) + custom_ ## ctrl)
static int pwc_g_volatile_ctrl(struct v4l2_ctrl *ctrl);
static int pwc_s_ctrl(struct v4l2_ctrl *ctrl);
static const struct v4l2_ctrl_ops pwc_ctrl_ops = {
.g_volatile_ctrl = pwc_g_volatile_ctrl,
.s_ctrl = pwc_s_ctrl,
};
enum { awb_indoor, awb_outdoor, awb_fl, awb_manual, awb_auto };
enum { custom_autocontour, custom_contour, custom_noise_reduction,
custom_awb_speed, custom_awb_delay,
custom_save_user, custom_restore_user, custom_restore_factory };
const char * const pwc_auto_whitebal_qmenu[] = {
"Indoor (Incandescant Lighting) Mode",
"Outdoor (Sunlight) Mode",
"Indoor (Fluorescent Lighting) Mode",
"Manual Mode",
"Auto Mode",
NULL
};
static const struct v4l2_ctrl_config pwc_auto_white_balance_cfg = {
.ops = &pwc_ctrl_ops,
.id = V4L2_CID_AUTO_WHITE_BALANCE,
.type = V4L2_CTRL_TYPE_MENU,
.max = awb_auto,
.qmenu = pwc_auto_whitebal_qmenu,
};
static const struct v4l2_ctrl_config pwc_autocontour_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(autocontour),
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Auto contour",
.min = 0,
.max = 1,
.step = 1,
};
static const struct v4l2_ctrl_config pwc_contour_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(contour),
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contour",
.flags = V4L2_CTRL_FLAG_SLIDER,
.min = 0,
.max = 63,
.step = 1,
};
static const struct v4l2_ctrl_config pwc_backlight_cfg = {
.ops = &pwc_ctrl_ops,
.id = V4L2_CID_BACKLIGHT_COMPENSATION,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.min = 0,
.max = 1,
.step = 1,
};
static const struct v4l2_ctrl_config pwc_flicker_cfg = {
.ops = &pwc_ctrl_ops,
.id = V4L2_CID_BAND_STOP_FILTER,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.min = 0,
.max = 1,
.step = 1,
};
static const struct v4l2_ctrl_config pwc_noise_reduction_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(noise_reduction),
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Dynamic Noise Reduction",
.min = 0,
.max = 3,
.step = 1,
};
static const struct v4l2_ctrl_config pwc_save_user_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(save_user),
.type = V4L2_CTRL_TYPE_BUTTON,
.name = "Save User Settings",
};
static const struct v4l2_ctrl_config pwc_restore_user_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(restore_user),
.type = V4L2_CTRL_TYPE_BUTTON,
.name = "Restore User Settings",
};
static const struct v4l2_ctrl_config pwc_restore_factory_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(restore_factory),
.type = V4L2_CTRL_TYPE_BUTTON,
.name = "Restore Factory Settings",
};
static const struct v4l2_ctrl_config pwc_awb_speed_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(awb_speed),
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Auto White Balance Speed",
.min = 1,
.max = 32,
.step = 1,
};
static const struct v4l2_ctrl_config pwc_awb_delay_cfg = {
.ops = &pwc_ctrl_ops,
.id = PWC_CID_CUSTOM(awb_delay),
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Auto White Balance Delay",
.min = 0,
.max = 63,
.step = 1,
};
int pwc_init_controls(struct pwc_device *pdev)
{
struct v4l2_ctrl_handler *hdl;
struct v4l2_ctrl_config cfg;
int r, def;
hdl = &pdev->ctrl_handler;
r = v4l2_ctrl_handler_init(hdl, 20);
if (r)
return r;
/* Brightness, contrast, saturation, gamma */
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, BRIGHTNESS_FORMATTER, &def);
if (r || def > 127)
def = 63;
pdev->brightness = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0, 127, 1, def);
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, CONTRAST_FORMATTER, &def);
if (r || def > 63)
def = 31;
pdev->contrast = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_CONTRAST, 0, 63, 1, def);
if (pdev->type >= 675) {
if (pdev->type < 730)
pdev->saturation_fmt = SATURATION_MODE_FORMATTER2;
else
pdev->saturation_fmt = SATURATION_MODE_FORMATTER1;
r = pwc_get_s8_ctrl(pdev, GET_CHROM_CTL, pdev->saturation_fmt,
&def);
if (r || def < -100 || def > 100)
def = 0;
pdev->saturation = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_SATURATION, -100, 100, 1, def);
}
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, GAMMA_FORMATTER, &def);
if (r || def > 31)
def = 15;
pdev->gamma = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_GAMMA, 0, 31, 1, def);
/* auto white balance, red gain, blue gain */
r = pwc_get_u8_ctrl(pdev, GET_CHROM_CTL, WB_MODE_FORMATTER, &def);
if (r || def > awb_auto)
def = awb_auto;
cfg = pwc_auto_white_balance_cfg;
cfg.name = v4l2_ctrl_get_name(cfg.id);
cfg.def = def;
pdev->auto_white_balance = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
/* check auto controls to avoid NULL deref in v4l2_ctrl_auto_cluster */
if (!pdev->auto_white_balance)
return hdl->error;
r = pwc_get_u8_ctrl(pdev, GET_CHROM_CTL,
PRESET_MANUAL_RED_GAIN_FORMATTER, &def);
if (r)
def = 127;
pdev->red_balance = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_RED_BALANCE, 0, 255, 1, def);
r = pwc_get_u8_ctrl(pdev, GET_CHROM_CTL,
PRESET_MANUAL_BLUE_GAIN_FORMATTER, &def);
if (r)
def = 127;
pdev->blue_balance = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_BLUE_BALANCE, 0, 255, 1, def);
v4l2_ctrl_auto_cluster(3, &pdev->auto_white_balance, awb_manual, true);
/* autogain, gain */
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, AGC_MODE_FORMATTER, &def);
if (r || (def != 0 && def != 0xff))
def = 0;
/* Note a register value if 0 means auto gain is on */
pdev->autogain = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, def == 0);
if (!pdev->autogain)
return hdl->error;
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, PRESET_AGC_FORMATTER, &def);
if (r || def > 63)
def = 31;
pdev->gain = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_GAIN, 0, 63, 1, def);
/* auto exposure, exposure */
if (DEVICE_USE_CODEC2(pdev->type)) {
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, SHUTTER_MODE_FORMATTER,
&def);
if (r || (def != 0 && def != 0xff))
def = 0;
/*
* def = 0 auto, def = ff manual
* menu idx 0 = auto, idx 1 = manual
*/
pdev->exposure_auto = v4l2_ctrl_new_std_menu(hdl,
&pwc_ctrl_ops,
V4L2_CID_EXPOSURE_AUTO,
1, 0, def != 0);
if (!pdev->exposure_auto)
return hdl->error;
/* GET_LUM_CTL, PRESET_SHUTTER_FORMATTER is unreliable */
r = pwc_get_u16_ctrl(pdev, GET_STATUS_CTL,
READ_SHUTTER_FORMATTER, &def);
if (r || def > 655)
def = 655;
pdev->exposure = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_EXPOSURE, 0, 655, 1, def);
/* CODEC2: separate auto gain & auto exposure */
v4l2_ctrl_auto_cluster(2, &pdev->autogain, 0, true);
v4l2_ctrl_auto_cluster(2, &pdev->exposure_auto,
V4L2_EXPOSURE_MANUAL, true);
} else if (DEVICE_USE_CODEC3(pdev->type)) {
/* GET_LUM_CTL, PRESET_SHUTTER_FORMATTER is unreliable */
r = pwc_get_u16_ctrl(pdev, GET_STATUS_CTL,
READ_SHUTTER_FORMATTER, &def);
if (r || def > 255)
def = 255;
pdev->exposure = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_EXPOSURE, 0, 255, 1, def);
/* CODEC3: both gain and exposure controlled by autogain */
pdev->autogain_expo_cluster[0] = pdev->autogain;
pdev->autogain_expo_cluster[1] = pdev->gain;
pdev->autogain_expo_cluster[2] = pdev->exposure;
v4l2_ctrl_auto_cluster(3, pdev->autogain_expo_cluster,
0, true);
}
/* color / bw setting */
r = pwc_get_u8_ctrl(pdev, GET_CHROM_CTL, COLOUR_MODE_FORMATTER,
&def);
if (r || (def != 0 && def != 0xff))
def = 0xff;
/* def = 0 bw, def = ff color, menu idx 0 = color, idx 1 = bw */
pdev->colorfx = v4l2_ctrl_new_std_menu(hdl, &pwc_ctrl_ops,
V4L2_CID_COLORFX, 1, 0, def == 0);
/* autocontour, contour */
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, AUTO_CONTOUR_FORMATTER, &def);
if (r || (def != 0 && def != 0xff))
def = 0;
cfg = pwc_autocontour_cfg;
cfg.def = def == 0;
pdev->autocontour = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
if (!pdev->autocontour)
return hdl->error;
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL, PRESET_CONTOUR_FORMATTER, &def);
if (r || def > 63)
def = 31;
cfg = pwc_contour_cfg;
cfg.def = def;
pdev->contour = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
v4l2_ctrl_auto_cluster(2, &pdev->autocontour, 0, false);
/* backlight */
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL,
BACK_LIGHT_COMPENSATION_FORMATTER, &def);
if (r || (def != 0 && def != 0xff))
def = 0;
cfg = pwc_backlight_cfg;
cfg.name = v4l2_ctrl_get_name(cfg.id);
cfg.def = def == 0;
pdev->backlight = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
/* flikker rediction */
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL,
FLICKERLESS_MODE_FORMATTER, &def);
if (r || (def != 0 && def != 0xff))
def = 0;
cfg = pwc_flicker_cfg;
cfg.name = v4l2_ctrl_get_name(cfg.id);
cfg.def = def == 0;
pdev->flicker = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
/* Dynamic noise reduction */
r = pwc_get_u8_ctrl(pdev, GET_LUM_CTL,
DYNAMIC_NOISE_CONTROL_FORMATTER, &def);
if (r || def > 3)
def = 2;
cfg = pwc_noise_reduction_cfg;
cfg.def = def;
pdev->noise_reduction = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
/* Save / Restore User / Factory Settings */
pdev->save_user = v4l2_ctrl_new_custom(hdl, &pwc_save_user_cfg, NULL);
pdev->restore_user = v4l2_ctrl_new_custom(hdl, &pwc_restore_user_cfg,
NULL);
if (pdev->restore_user)
pdev->restore_user->flags |= V4L2_CTRL_FLAG_UPDATE;
pdev->restore_factory = v4l2_ctrl_new_custom(hdl,
&pwc_restore_factory_cfg,
NULL);
if (pdev->restore_factory)
pdev->restore_factory->flags |= V4L2_CTRL_FLAG_UPDATE;
/* Auto White Balance speed & delay */
r = pwc_get_u8_ctrl(pdev, GET_CHROM_CTL,
AWB_CONTROL_SPEED_FORMATTER, &def);
if (r || def < 1 || def > 32)
def = 1;
cfg = pwc_awb_speed_cfg;
cfg.def = def;
pdev->awb_speed = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
r = pwc_get_u8_ctrl(pdev, GET_CHROM_CTL,
AWB_CONTROL_DELAY_FORMATTER, &def);
if (r || def > 63)
def = 0;
cfg = pwc_awb_delay_cfg;
cfg.def = def;
pdev->awb_delay = v4l2_ctrl_new_custom(hdl, &cfg, NULL);
if (!(pdev->features & FEATURE_MOTOR_PANTILT))
return hdl->error;
/* Motor pan / tilt / reset */
pdev->motor_pan = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_PAN_RELATIVE, -4480, 4480, 64, 0);
if (!pdev->motor_pan)
return hdl->error;
pdev->motor_tilt = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_TILT_RELATIVE, -1920, 1920, 64, 0);
pdev->motor_pan_reset = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_PAN_RESET, 0, 0, 0, 0);
pdev->motor_tilt_reset = v4l2_ctrl_new_std(hdl, &pwc_ctrl_ops,
V4L2_CID_TILT_RESET, 0, 0, 0, 0);
v4l2_ctrl_cluster(4, &pdev->motor_pan);
return hdl->error;
}
static void pwc_vidioc_fill_fmt(struct v4l2_format *f,
int width, int height, u32 pixfmt)
{
memset(&f->fmt.pix, 0, sizeof(struct v4l2_pix_format));
f->fmt.pix.width = width;
f->fmt.pix.height = height;
f->fmt.pix.field = V4L2_FIELD_NONE;
f->fmt.pix.pixelformat = pixfmt;
f->fmt.pix.bytesperline = f->fmt.pix.width;
f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.width * 3 / 2;
f->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
PWC_DEBUG_IOCTL("pwc_vidioc_fill_fmt() "
"width=%d, height=%d, bytesperline=%d, sizeimage=%d, pixelformat=%c%c%c%c\n",
f->fmt.pix.width,
f->fmt.pix.height,
f->fmt.pix.bytesperline,
f->fmt.pix.sizeimage,
(f->fmt.pix.pixelformat)&255,
(f->fmt.pix.pixelformat>>8)&255,
(f->fmt.pix.pixelformat>>16)&255,
(f->fmt.pix.pixelformat>>24)&255);
}
/* ioctl(VIDIOC_TRY_FMT) */
static int pwc_vidioc_try_fmt(struct pwc_device *pdev, struct v4l2_format *f)
{
int size;
if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
PWC_DEBUG_IOCTL("Bad video type must be V4L2_BUF_TYPE_VIDEO_CAPTURE\n");
return -EINVAL;
}
switch (f->fmt.pix.pixelformat) {
case V4L2_PIX_FMT_YUV420:
break;
case V4L2_PIX_FMT_PWC1:
if (DEVICE_USE_CODEC23(pdev->type)) {
PWC_DEBUG_IOCTL("codec1 is only supported for old pwc webcam\n");
f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;
}
break;
case V4L2_PIX_FMT_PWC2:
if (DEVICE_USE_CODEC1(pdev->type)) {
PWC_DEBUG_IOCTL("codec23 is only supported for new pwc webcam\n");
f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;
}
break;
default:
PWC_DEBUG_IOCTL("Unsupported pixel format\n");
f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;
}
size = pwc_get_size(pdev, f->fmt.pix.width, f->fmt.pix.height);
pwc_vidioc_fill_fmt(f,
pwc_image_sizes[size][0],
pwc_image_sizes[size][1],
f->fmt.pix.pixelformat);
return 0;
}
/* ioctl(VIDIOC_SET_FMT) */
static int pwc_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *f)
{
struct pwc_device *pdev = video_drvdata(file);
int ret, pixelformat, compression = 0;
ret = pwc_vidioc_try_fmt(pdev, f);
if (ret < 0)
return ret;
if (vb2_is_busy(&pdev->vb_queue))
return -EBUSY;
pixelformat = f->fmt.pix.pixelformat;
PWC_DEBUG_IOCTL("Trying to set format to: width=%d height=%d fps=%d "
"format=%c%c%c%c\n",
f->fmt.pix.width, f->fmt.pix.height, pdev->vframes,
(pixelformat)&255,
(pixelformat>>8)&255,
(pixelformat>>16)&255,
(pixelformat>>24)&255);
ret = pwc_set_video_mode(pdev, f->fmt.pix.width, f->fmt.pix.height,
pixelformat, 30, &compression, 0);
PWC_DEBUG_IOCTL("pwc_set_video_mode(), return=%d\n", ret);
pwc_vidioc_fill_fmt(f, pdev->width, pdev->height, pdev->pixfmt);
return ret;
}
static int pwc_querycap(struct file *file, void *fh, struct v4l2_capability *cap)
{
struct pwc_device *pdev = video_drvdata(file);
strcpy(cap->driver, PWC_NAME);
strlcpy(cap->card, pdev->vdev.name, sizeof(cap->card));
usb_make_path(pdev->udev, cap->bus_info, sizeof(cap->bus_info));
cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
V4L2_CAP_READWRITE;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int pwc_enum_input(struct file *file, void *fh, struct v4l2_input *i)
{
if (i->index) /* Only one INPUT is supported */
return -EINVAL;
strlcpy(i->name, "Camera", sizeof(i->name));
i->type = V4L2_INPUT_TYPE_CAMERA;
return 0;
}
static int pwc_g_input(struct file *file, void *fh, unsigned int *i)
{
*i = 0;
return 0;
}
static int pwc_s_input(struct file *file, void *fh, unsigned int i)
{
return i ? -EINVAL : 0;
}
static int pwc_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
struct pwc_device *pdev =
container_of(ctrl->handler, struct pwc_device, ctrl_handler);
int ret = 0;
switch (ctrl->id) {
case V4L2_CID_AUTO_WHITE_BALANCE:
if (pdev->color_bal_valid &&
(pdev->auto_white_balance->val != awb_auto ||
time_before(jiffies,
pdev->last_color_bal_update + HZ / 4))) {
pdev->red_balance->val = pdev->last_red_balance;
pdev->blue_balance->val = pdev->last_blue_balance;
break;
}
ret = pwc_get_u8_ctrl(pdev, GET_STATUS_CTL,
READ_RED_GAIN_FORMATTER,
&pdev->red_balance->val);
if (ret)
break;
ret = pwc_get_u8_ctrl(pdev, GET_STATUS_CTL,
READ_BLUE_GAIN_FORMATTER,
&pdev->blue_balance->val);
if (ret)
break;
pdev->last_red_balance = pdev->red_balance->val;
pdev->last_blue_balance = pdev->blue_balance->val;
pdev->last_color_bal_update = jiffies;
pdev->color_bal_valid = true;
break;
case V4L2_CID_AUTOGAIN:
if (pdev->gain_valid && time_before(jiffies,
pdev->last_gain_update + HZ / 4)) {
pdev->gain->val = pdev->last_gain;
break;
}
ret = pwc_get_u8_ctrl(pdev, GET_STATUS_CTL,
READ_AGC_FORMATTER, &pdev->gain->val);
if (ret)
break;
pdev->last_gain = pdev->gain->val;
pdev->last_gain_update = jiffies;
pdev->gain_valid = true;
if (!DEVICE_USE_CODEC3(pdev->type))
break;
/* Fall through for CODEC3 where autogain also controls expo */
case V4L2_CID_EXPOSURE_AUTO:
if (pdev->exposure_valid && time_before(jiffies,
pdev->last_exposure_update + HZ / 4)) {
pdev->exposure->val = pdev->last_exposure;
break;
}
ret = pwc_get_u16_ctrl(pdev, GET_STATUS_CTL,
READ_SHUTTER_FORMATTER,
&pdev->exposure->val);
if (ret)
break;
pdev->last_exposure = pdev->exposure->val;
pdev->last_exposure_update = jiffies;
pdev->exposure_valid = true;
break;
default:
ret = -EINVAL;
}
if (ret)
PWC_ERROR("g_ctrl %s error %d\n", ctrl->name, ret);
return ret;
}
static int pwc_set_awb(struct pwc_device *pdev)
{
int ret;
if (pdev->auto_white_balance->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_CHROM_CTL,
WB_MODE_FORMATTER,
pdev->auto_white_balance->val);
if (ret)
return ret;
if (pdev->auto_white_balance->val != awb_manual)
pdev->color_bal_valid = false; /* Force cache update */
/*
* If this is a preset, update our red / blue balance values
* so that events get generated for the new preset values
*/
if (pdev->auto_white_balance->val == awb_indoor ||
pdev->auto_white_balance->val == awb_outdoor ||
pdev->auto_white_balance->val == awb_fl)
pwc_g_volatile_ctrl(pdev->auto_white_balance);
}
if (pdev->auto_white_balance->val != awb_manual)
return 0;
if (pdev->red_balance->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_CHROM_CTL,
PRESET_MANUAL_RED_GAIN_FORMATTER,
pdev->red_balance->val);
if (ret)
return ret;
}
if (pdev->blue_balance->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_CHROM_CTL,
PRESET_MANUAL_BLUE_GAIN_FORMATTER,
pdev->blue_balance->val);
if (ret)
return ret;
}
return 0;
}
/* For CODEC2 models which have separate autogain and auto exposure */
static int pwc_set_autogain(struct pwc_device *pdev)
{
int ret;
if (pdev->autogain->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
AGC_MODE_FORMATTER,
pdev->autogain->val ? 0 : 0xff);
if (ret)
return ret;
if (pdev->autogain->val)
pdev->gain_valid = false; /* Force cache update */
}
if (pdev->autogain->val)
return 0;
if (pdev->gain->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
PRESET_AGC_FORMATTER,
pdev->gain->val);
if (ret)
return ret;
}
return 0;
}
/* For CODEC2 models which have separate autogain and auto exposure */
static int pwc_set_exposure_auto(struct pwc_device *pdev)
{
int ret;
int is_auto = pdev->exposure_auto->val == V4L2_EXPOSURE_AUTO;
if (pdev->exposure_auto->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
SHUTTER_MODE_FORMATTER,
is_auto ? 0 : 0xff);
if (ret)
return ret;
if (is_auto)
pdev->exposure_valid = false; /* Force cache update */
}
if (is_auto)
return 0;
if (pdev->exposure->is_new) {
ret = pwc_set_u16_ctrl(pdev, SET_LUM_CTL,
PRESET_SHUTTER_FORMATTER,
pdev->exposure->val);
if (ret)
return ret;
}
return 0;
}
/* For CODEC3 models which have autogain controlling both gain and exposure */
static int pwc_set_autogain_expo(struct pwc_device *pdev)
{
int ret;
if (pdev->autogain->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
AGC_MODE_FORMATTER,
pdev->autogain->val ? 0 : 0xff);
if (ret)
return ret;
if (pdev->autogain->val) {
pdev->gain_valid = false; /* Force cache update */
pdev->exposure_valid = false; /* Force cache update */
}
}
if (pdev->autogain->val)
return 0;
if (pdev->gain->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
PRESET_AGC_FORMATTER,
pdev->gain->val);
if (ret)
return ret;
}
if (pdev->exposure->is_new) {
ret = pwc_set_u16_ctrl(pdev, SET_LUM_CTL,
PRESET_SHUTTER_FORMATTER,
pdev->exposure->val);
if (ret)
return ret;
}
return 0;
}
static int pwc_set_motor(struct pwc_device *pdev)
{
int ret;
pdev->ctrl_buf[0] = 0;
if (pdev->motor_pan_reset->is_new)
pdev->ctrl_buf[0] |= 0x01;
if (pdev->motor_tilt_reset->is_new)
pdev->ctrl_buf[0] |= 0x02;
if (pdev->motor_pan_reset->is_new || pdev->motor_tilt_reset->is_new) {
ret = send_control_msg(pdev, SET_MPT_CTL,
PT_RESET_CONTROL_FORMATTER,
pdev->ctrl_buf, 1);
if (ret < 0)
return ret;
}
memset(pdev->ctrl_buf, 0, 4);
if (pdev->motor_pan->is_new) {
pdev->ctrl_buf[0] = pdev->motor_pan->val & 0xFF;
pdev->ctrl_buf[1] = (pdev->motor_pan->val >> 8);
}
if (pdev->motor_tilt->is_new) {
pdev->ctrl_buf[2] = pdev->motor_tilt->val & 0xFF;
pdev->ctrl_buf[3] = (pdev->motor_tilt->val >> 8);
}
if (pdev->motor_pan->is_new || pdev->motor_tilt->is_new) {
ret = send_control_msg(pdev, SET_MPT_CTL,
PT_RELATIVE_CONTROL_FORMATTER,
pdev->ctrl_buf, 4);
if (ret < 0)
return ret;
}
return 0;
}
static int pwc_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct pwc_device *pdev =
container_of(ctrl->handler, struct pwc_device, ctrl_handler);
int ret = 0;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
BRIGHTNESS_FORMATTER, ctrl->val);
break;
case V4L2_CID_CONTRAST:
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
CONTRAST_FORMATTER, ctrl->val);
break;
case V4L2_CID_SATURATION:
ret = pwc_set_s8_ctrl(pdev, SET_CHROM_CTL,
pdev->saturation_fmt, ctrl->val);
break;
case V4L2_CID_GAMMA:
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
GAMMA_FORMATTER, ctrl->val);
break;
case V4L2_CID_AUTO_WHITE_BALANCE:
ret = pwc_set_awb(pdev);
break;
case V4L2_CID_AUTOGAIN:
if (DEVICE_USE_CODEC2(pdev->type))
ret = pwc_set_autogain(pdev);
else if (DEVICE_USE_CODEC3(pdev->type))
ret = pwc_set_autogain_expo(pdev);
else
ret = -EINVAL;
break;
case V4L2_CID_EXPOSURE_AUTO:
if (DEVICE_USE_CODEC2(pdev->type))
ret = pwc_set_exposure_auto(pdev);
else
ret = -EINVAL;
break;
case V4L2_CID_COLORFX:
ret = pwc_set_u8_ctrl(pdev, SET_CHROM_CTL,
COLOUR_MODE_FORMATTER,
ctrl->val ? 0 : 0xff);
break;
case PWC_CID_CUSTOM(autocontour):
if (pdev->autocontour->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
AUTO_CONTOUR_FORMATTER,
pdev->autocontour->val ? 0 : 0xff);
}
if (ret == 0 && pdev->contour->is_new) {
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
PRESET_CONTOUR_FORMATTER,
pdev->contour->val);
}
break;
case V4L2_CID_BACKLIGHT_COMPENSATION:
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
BACK_LIGHT_COMPENSATION_FORMATTER,
ctrl->val ? 0 : 0xff);
break;
case V4L2_CID_BAND_STOP_FILTER:
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
FLICKERLESS_MODE_FORMATTER,
ctrl->val ? 0 : 0xff);
break;
case PWC_CID_CUSTOM(noise_reduction):
ret = pwc_set_u8_ctrl(pdev, SET_LUM_CTL,
DYNAMIC_NOISE_CONTROL_FORMATTER,
ctrl->val);
break;
case PWC_CID_CUSTOM(save_user):
ret = pwc_button_ctrl(pdev, SAVE_USER_DEFAULTS_FORMATTER);
break;
case PWC_CID_CUSTOM(restore_user):
ret = pwc_button_ctrl(pdev, RESTORE_USER_DEFAULTS_FORMATTER);
break;
case PWC_CID_CUSTOM(restore_factory):
ret = pwc_button_ctrl(pdev,
RESTORE_FACTORY_DEFAULTS_FORMATTER);
break;
case PWC_CID_CUSTOM(awb_speed):
ret = pwc_set_u8_ctrl(pdev, SET_CHROM_CTL,
AWB_CONTROL_SPEED_FORMATTER,
ctrl->val);
break;
case PWC_CID_CUSTOM(awb_delay):
ret = pwc_set_u8_ctrl(pdev, SET_CHROM_CTL,
AWB_CONTROL_DELAY_FORMATTER,
ctrl->val);
break;
case V4L2_CID_PAN_RELATIVE:
ret = pwc_set_motor(pdev);
break;
default:
ret = -EINVAL;
}
if (ret)
PWC_ERROR("s_ctrl %s error %d\n", ctrl->name, ret);
return ret;
}
static int pwc_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *f)
{
struct pwc_device *pdev = video_drvdata(file);
/* We only support two format: the raw format, and YUV */
switch (f->index) {
case 0:
/* RAW format */
f->pixelformat = pdev->type <= 646 ? V4L2_PIX_FMT_PWC1 : V4L2_PIX_FMT_PWC2;
f->flags = V4L2_FMT_FLAG_COMPRESSED;
strlcpy(f->description, "Raw Philips Webcam", sizeof(f->description));
break;
case 1:
f->pixelformat = V4L2_PIX_FMT_YUV420;
strlcpy(f->description, "4:2:0, planar, Y-Cb-Cr", sizeof(f->description));
break;
default:
return -EINVAL;
}
return 0;
}
static int pwc_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *f)
{
struct pwc_device *pdev = video_drvdata(file);
if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
PWC_DEBUG_IOCTL("ioctl(VIDIOC_G_FMT) return size %dx%d\n",
pdev->width, pdev->height);
pwc_vidioc_fill_fmt(f, pdev->width, pdev->height, pdev->pixfmt);
return 0;
}
static int pwc_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *f)
{
struct pwc_device *pdev = video_drvdata(file);
return pwc_vidioc_try_fmt(pdev, f);
}
static int pwc_enum_framesizes(struct file *file, void *fh,
struct v4l2_frmsizeenum *fsize)
{
struct pwc_device *pdev = video_drvdata(file);
unsigned int i = 0, index = fsize->index;
if (fsize->pixel_format == V4L2_PIX_FMT_YUV420 ||
(fsize->pixel_format == V4L2_PIX_FMT_PWC1 &&
DEVICE_USE_CODEC1(pdev->type)) ||
(fsize->pixel_format == V4L2_PIX_FMT_PWC2 &&
DEVICE_USE_CODEC23(pdev->type))) {
for (i = 0; i < PSZ_MAX; i++) {
if (!(pdev->image_mask & (1UL << i)))
continue;
if (!index--) {
fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
fsize->discrete.width = pwc_image_sizes[i][0];
fsize->discrete.height = pwc_image_sizes[i][1];
return 0;
}
}
}
return -EINVAL;
}
static int pwc_enum_frameintervals(struct file *file, void *fh,
struct v4l2_frmivalenum *fival)
{
struct pwc_device *pdev = video_drvdata(file);
int size = -1;
unsigned int i;
for (i = 0; i < PSZ_MAX; i++) {
if (pwc_image_sizes[i][0] == fival->width &&
pwc_image_sizes[i][1] == fival->height) {
size = i;
break;
}
}
/* TODO: Support raw format */
if (size < 0 || fival->pixel_format != V4L2_PIX_FMT_YUV420)
return -EINVAL;
i = pwc_get_fps(pdev, fival->index, size);
if (!i)
return -EINVAL;
fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
fival->discrete.numerator = 1;
fival->discrete.denominator = i;
return 0;
}
static int pwc_g_parm(struct file *file, void *fh,
struct v4l2_streamparm *parm)
{
struct pwc_device *pdev = video_drvdata(file);
if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
memset(parm, 0, sizeof(*parm));
parm->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
parm->parm.capture.readbuffers = MIN_FRAMES;
parm->parm.capture.capability |= V4L2_CAP_TIMEPERFRAME;
parm->parm.capture.timeperframe.denominator = pdev->vframes;
parm->parm.capture.timeperframe.numerator = 1;
return 0;
}
static int pwc_s_parm(struct file *file, void *fh,
struct v4l2_streamparm *parm)
{
struct pwc_device *pdev = video_drvdata(file);
int compression = 0;
int ret, fps;
if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
/* If timeperframe == 0, then reset the framerate to the nominal value.
We pick a high framerate here, and let pwc_set_video_mode() figure
out the best match. */
if (parm->parm.capture.timeperframe.numerator == 0 ||
parm->parm.capture.timeperframe.denominator == 0)
fps = 30;
else
fps = parm->parm.capture.timeperframe.denominator /
parm->parm.capture.timeperframe.numerator;
if (vb2_is_busy(&pdev->vb_queue))
return -EBUSY;
ret = pwc_set_video_mode(pdev, pdev->width, pdev->height, pdev->pixfmt,
fps, &compression, 0);
pwc_g_parm(file, fh, parm);
return ret;
}
const struct v4l2_ioctl_ops pwc_ioctl_ops = {
.vidioc_querycap = pwc_querycap,
.vidioc_enum_input = pwc_enum_input,
.vidioc_g_input = pwc_g_input,
.vidioc_s_input = pwc_s_input,
.vidioc_enum_fmt_vid_cap = pwc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = pwc_g_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = pwc_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = pwc_try_fmt_vid_cap,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_enum_framesizes = pwc_enum_framesizes,
.vidioc_enum_frameintervals = pwc_enum_frameintervals,
.vidioc_g_parm = pwc_g_parm,
.vidioc_s_parm = pwc_s_parm,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
| gpl-2.0 |
ea4862/boeffla_cm12.1 | net/ipv4/udplite.c | 3098 | 3293 | /*
* UDPLITE An implementation of the UDP-Lite protocol (RFC 3828).
*
* Authors: Gerrit Renker <gerrit@erg.abdn.ac.uk>
*
* Changes:
* Fixes:
* 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 "udp_impl.h"
struct udp_table udplite_table __read_mostly;
EXPORT_SYMBOL(udplite_table);
static int udplite_rcv(struct sk_buff *skb)
{
return __udp4_lib_rcv(skb, &udplite_table, IPPROTO_UDPLITE);
}
static void udplite_err(struct sk_buff *skb, u32 info)
{
__udp4_lib_err(skb, info, &udplite_table);
}
static const struct net_protocol udplite_protocol = {
.handler = udplite_rcv,
.err_handler = udplite_err,
.no_policy = 1,
.netns_ok = 1,
};
struct proto udplite_prot = {
.name = "UDP-Lite",
.owner = THIS_MODULE,
.close = udp_lib_close,
.connect = ip4_datagram_connect,
.disconnect = udp_disconnect,
.ioctl = udp_ioctl,
.init = udplite_sk_init,
.destroy = udp_destroy_sock,
.setsockopt = udp_setsockopt,
.getsockopt = udp_getsockopt,
.sendmsg = udp_sendmsg,
.recvmsg = udp_recvmsg,
.sendpage = udp_sendpage,
.backlog_rcv = udp_queue_rcv_skb,
.hash = udp_lib_hash,
.unhash = udp_lib_unhash,
.get_port = udp_v4_get_port,
.obj_size = sizeof(struct udp_sock),
.slab_flags = SLAB_DESTROY_BY_RCU,
.h.udp_table = &udplite_table,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_udp_setsockopt,
.compat_getsockopt = compat_udp_getsockopt,
#endif
.clear_sk = sk_prot_clear_portaddr_nulls,
};
EXPORT_SYMBOL(udplite_prot);
static struct inet_protosw udplite4_protosw = {
.type = SOCK_DGRAM,
.protocol = IPPROTO_UDPLITE,
.prot = &udplite_prot,
.ops = &inet_dgram_ops,
.no_check = 0, /* must checksum (RFC 3828) */
.flags = INET_PROTOSW_PERMANENT,
};
#ifdef CONFIG_PROC_FS
static struct udp_seq_afinfo udplite4_seq_afinfo = {
.name = "udplite",
.family = AF_INET,
.udp_table = &udplite_table,
.seq_fops = {
.owner = THIS_MODULE,
},
.seq_ops = {
.show = udp4_seq_show,
},
};
static int __net_init udplite4_proc_init_net(struct net *net)
{
return udp_proc_register(net, &udplite4_seq_afinfo);
}
static void __net_exit udplite4_proc_exit_net(struct net *net)
{
udp_proc_unregister(net, &udplite4_seq_afinfo);
}
static struct pernet_operations udplite4_net_ops = {
.init = udplite4_proc_init_net,
.exit = udplite4_proc_exit_net,
};
static __init int udplite4_proc_init(void)
{
return register_pernet_subsys(&udplite4_net_ops);
}
#else
static inline int udplite4_proc_init(void)
{
return 0;
}
#endif
void __init udplite4_register(void)
{
udp_table_init(&udplite_table, "UDP-Lite");
if (proto_register(&udplite_prot, 1))
goto out_register_err;
if (inet_add_protocol(&udplite_protocol, IPPROTO_UDPLITE) < 0)
goto out_unregister_proto;
inet_register_protosw(&udplite4_protosw);
if (udplite4_proc_init())
printk(KERN_ERR "%s: Cannot register /proc!\n", __func__);
return;
out_unregister_proto:
proto_unregister(&udplite_prot);
out_register_err:
printk(KERN_CRIT "%s: Cannot add UDP-Lite protocol.\n", __func__);
}
| gpl-2.0 |
Troj80/T.J.T-Kernel-vivo | sound/core/seq/oss/seq_oss.c | 3098 | 7459 | /*
* OSS compatible sequencer driver
*
* registration of device and proc
*
* Copyright (C) 1998,99 Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/minors.h>
#include <sound/initval.h>
#include "seq_oss_device.h"
#include "seq_oss_synth.h"
/*
* module option
*/
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("OSS-compatible sequencer module");
MODULE_LICENSE("GPL");
/* Takashi says this is really only for sound-service-0-, but this is OK. */
MODULE_ALIAS_SNDRV_MINOR(SNDRV_MINOR_OSS_SEQUENCER);
MODULE_ALIAS_SNDRV_MINOR(SNDRV_MINOR_OSS_MUSIC);
#ifdef SNDRV_SEQ_OSS_DEBUG
module_param(seq_oss_debug, int, 0644);
MODULE_PARM_DESC(seq_oss_debug, "debug option");
int seq_oss_debug = 0;
#endif
/*
* prototypes
*/
static int register_device(void);
static void unregister_device(void);
#ifdef CONFIG_PROC_FS
static int register_proc(void);
static void unregister_proc(void);
#else
static inline int register_proc(void) { return 0; }
static inline void unregister_proc(void) {}
#endif
static int odev_open(struct inode *inode, struct file *file);
static int odev_release(struct inode *inode, struct file *file);
static ssize_t odev_read(struct file *file, char __user *buf, size_t count, loff_t *offset);
static ssize_t odev_write(struct file *file, const char __user *buf, size_t count, loff_t *offset);
static long odev_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
static unsigned int odev_poll(struct file *file, poll_table * wait);
/*
* module interface
*/
static int __init alsa_seq_oss_init(void)
{
int rc;
static struct snd_seq_dev_ops ops = {
snd_seq_oss_synth_register,
snd_seq_oss_synth_unregister,
};
snd_seq_autoload_lock();
if ((rc = register_device()) < 0)
goto error;
if ((rc = register_proc()) < 0) {
unregister_device();
goto error;
}
if ((rc = snd_seq_oss_create_client()) < 0) {
unregister_proc();
unregister_device();
goto error;
}
if ((rc = snd_seq_device_register_driver(SNDRV_SEQ_DEV_ID_OSS, &ops,
sizeof(struct snd_seq_oss_reg))) < 0) {
snd_seq_oss_delete_client();
unregister_proc();
unregister_device();
goto error;
}
/* success */
snd_seq_oss_synth_init();
error:
snd_seq_autoload_unlock();
return rc;
}
static void __exit alsa_seq_oss_exit(void)
{
snd_seq_device_unregister_driver(SNDRV_SEQ_DEV_ID_OSS);
snd_seq_oss_delete_client();
unregister_proc();
unregister_device();
}
module_init(alsa_seq_oss_init)
module_exit(alsa_seq_oss_exit)
/*
* ALSA minor device interface
*/
static DEFINE_MUTEX(register_mutex);
static int
odev_open(struct inode *inode, struct file *file)
{
int level, rc;
if (iminor(inode) == SNDRV_MINOR_OSS_MUSIC)
level = SNDRV_SEQ_OSS_MODE_MUSIC;
else
level = SNDRV_SEQ_OSS_MODE_SYNTH;
mutex_lock(®ister_mutex);
rc = snd_seq_oss_open(file, level);
mutex_unlock(®ister_mutex);
return rc;
}
static int
odev_release(struct inode *inode, struct file *file)
{
struct seq_oss_devinfo *dp;
if ((dp = file->private_data) == NULL)
return 0;
snd_seq_oss_drain_write(dp);
mutex_lock(®ister_mutex);
snd_seq_oss_release(dp);
mutex_unlock(®ister_mutex);
return 0;
}
static ssize_t
odev_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
{
struct seq_oss_devinfo *dp;
dp = file->private_data;
if (snd_BUG_ON(!dp))
return -ENXIO;
return snd_seq_oss_read(dp, buf, count);
}
static ssize_t
odev_write(struct file *file, const char __user *buf, size_t count, loff_t *offset)
{
struct seq_oss_devinfo *dp;
dp = file->private_data;
if (snd_BUG_ON(!dp))
return -ENXIO;
return snd_seq_oss_write(dp, buf, count, file);
}
static long
odev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct seq_oss_devinfo *dp;
dp = file->private_data;
if (snd_BUG_ON(!dp))
return -ENXIO;
return snd_seq_oss_ioctl(dp, cmd, arg);
}
#ifdef CONFIG_COMPAT
#define odev_ioctl_compat odev_ioctl
#else
#define odev_ioctl_compat NULL
#endif
static unsigned int
odev_poll(struct file *file, poll_table * wait)
{
struct seq_oss_devinfo *dp;
dp = file->private_data;
if (snd_BUG_ON(!dp))
return -ENXIO;
return snd_seq_oss_poll(dp, file, wait);
}
/*
* registration of sequencer minor device
*/
static const struct file_operations seq_oss_f_ops =
{
.owner = THIS_MODULE,
.read = odev_read,
.write = odev_write,
.open = odev_open,
.release = odev_release,
.poll = odev_poll,
.unlocked_ioctl = odev_ioctl,
.compat_ioctl = odev_ioctl_compat,
.llseek = noop_llseek,
};
static int __init
register_device(void)
{
int rc;
mutex_lock(®ister_mutex);
if ((rc = snd_register_oss_device(SNDRV_OSS_DEVICE_TYPE_SEQUENCER,
NULL, 0,
&seq_oss_f_ops, NULL,
SNDRV_SEQ_OSS_DEVNAME)) < 0) {
snd_printk(KERN_ERR "can't register device seq\n");
mutex_unlock(®ister_mutex);
return rc;
}
if ((rc = snd_register_oss_device(SNDRV_OSS_DEVICE_TYPE_MUSIC,
NULL, 0,
&seq_oss_f_ops, NULL,
SNDRV_SEQ_OSS_DEVNAME)) < 0) {
snd_printk(KERN_ERR "can't register device music\n");
snd_unregister_oss_device(SNDRV_OSS_DEVICE_TYPE_SEQUENCER, NULL, 0);
mutex_unlock(®ister_mutex);
return rc;
}
debug_printk(("device registered\n"));
mutex_unlock(®ister_mutex);
return 0;
}
static void
unregister_device(void)
{
mutex_lock(®ister_mutex);
debug_printk(("device unregistered\n"));
if (snd_unregister_oss_device(SNDRV_OSS_DEVICE_TYPE_MUSIC, NULL, 0) < 0)
snd_printk(KERN_ERR "error unregister device music\n");
if (snd_unregister_oss_device(SNDRV_OSS_DEVICE_TYPE_SEQUENCER, NULL, 0) < 0)
snd_printk(KERN_ERR "error unregister device seq\n");
mutex_unlock(®ister_mutex);
}
/*
* /proc interface
*/
#ifdef CONFIG_PROC_FS
static struct snd_info_entry *info_entry;
static void
info_read(struct snd_info_entry *entry, struct snd_info_buffer *buf)
{
mutex_lock(®ister_mutex);
snd_iprintf(buf, "OSS sequencer emulation version %s\n", SNDRV_SEQ_OSS_VERSION_STR);
snd_seq_oss_system_info_read(buf);
snd_seq_oss_synth_info_read(buf);
snd_seq_oss_midi_info_read(buf);
mutex_unlock(®ister_mutex);
}
static int __init
register_proc(void)
{
struct snd_info_entry *entry;
entry = snd_info_create_module_entry(THIS_MODULE, SNDRV_SEQ_OSS_PROCNAME, snd_seq_root);
if (entry == NULL)
return -ENOMEM;
entry->content = SNDRV_INFO_CONTENT_TEXT;
entry->private_data = NULL;
entry->c.text.read = info_read;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
return -ENOMEM;
}
info_entry = entry;
return 0;
}
static void
unregister_proc(void)
{
snd_info_free_entry(info_entry);
info_entry = NULL;
}
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
thornbirdblue/MI3_kernel_code | fs/xattr.c | 4378 | 18107 | /*
File: fs/xattr.c
Extended attribute handling.
Copyright (C) 2001 by Andreas Gruenbacher <a.gruenbacher@computer.org>
Copyright (C) 2001 SGI - Silicon Graphics, Inc <linux-xfs@oss.sgi.com>
Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
*/
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/xattr.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/security.h>
#include <linux/evm.h>
#include <linux/syscalls.h>
#include <linux/export.h>
#include <linux/fsnotify.h>
#include <linux/audit.h>
#include <linux/vmalloc.h>
#include <asm/uaccess.h>
/*
* Check permissions for extended attribute access. This is a bit complicated
* because different namespaces have very different rules.
*/
static int
xattr_permission(struct inode *inode, const char *name, int mask)
{
/*
* We can never set or remove an extended attribute on a read-only
* filesystem or on an immutable / append-only inode.
*/
if (mask & MAY_WRITE) {
if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
return -EPERM;
}
/*
* No restriction for security.* and system.* from the VFS. Decision
* on these is left to the underlying filesystem / security module.
*/
if (!strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN) ||
!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
return 0;
/*
* The trusted.* namespace can only be accessed by privileged users.
*/
if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN)) {
if (!capable(CAP_SYS_ADMIN))
return (mask & MAY_WRITE) ? -EPERM : -ENODATA;
return 0;
}
/*
* In the user.* namespace, only regular files and directories can have
* extended attributes. For sticky directories, only the owner and
* privileged users can write attributes.
*/
if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN)) {
if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode))
return (mask & MAY_WRITE) ? -EPERM : -ENODATA;
if (S_ISDIR(inode->i_mode) && (inode->i_mode & S_ISVTX) &&
(mask & MAY_WRITE) && !inode_owner_or_capable(inode))
return -EPERM;
}
return inode_permission(inode, mask);
}
/**
* __vfs_setxattr_noperm - perform setxattr operation without performing
* permission checks.
*
* @dentry - object to perform setxattr on
* @name - xattr name to set
* @value - value to set @name to
* @size - size of @value
* @flags - flags to pass into filesystem operations
*
* returns the result of the internal setxattr or setsecurity operations.
*
* This function requires the caller to lock the inode's i_mutex before it
* is executed. It also assumes that the caller will make the appropriate
* permission checks.
*/
int __vfs_setxattr_noperm(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
struct inode *inode = dentry->d_inode;
int error = -EOPNOTSUPP;
int issec = !strncmp(name, XATTR_SECURITY_PREFIX,
XATTR_SECURITY_PREFIX_LEN);
if (issec)
inode->i_flags &= ~S_NOSEC;
if (inode->i_op->setxattr) {
error = inode->i_op->setxattr(dentry, name, value, size, flags);
if (!error) {
fsnotify_xattr(dentry);
security_inode_post_setxattr(dentry, name, value,
size, flags);
}
} else if (issec) {
const char *suffix = name + XATTR_SECURITY_PREFIX_LEN;
error = security_inode_setsecurity(inode, suffix, value,
size, flags);
if (!error)
fsnotify_xattr(dentry);
}
return error;
}
int
vfs_setxattr(struct dentry *dentry, const char *name, const void *value,
size_t size, int flags)
{
struct inode *inode = dentry->d_inode;
int error;
error = xattr_permission(inode, name, MAY_WRITE);
if (error)
return error;
mutex_lock(&inode->i_mutex);
error = security_inode_setxattr(dentry, name, value, size, flags);
if (error)
goto out;
error = __vfs_setxattr_noperm(dentry, name, value, size, flags);
out:
mutex_unlock(&inode->i_mutex);
return error;
}
EXPORT_SYMBOL_GPL(vfs_setxattr);
ssize_t
xattr_getsecurity(struct inode *inode, const char *name, void *value,
size_t size)
{
void *buffer = NULL;
ssize_t len;
if (!value || !size) {
len = security_inode_getsecurity(inode, name, &buffer, false);
goto out_noalloc;
}
len = security_inode_getsecurity(inode, name, &buffer, true);
if (len < 0)
return len;
if (size < len) {
len = -ERANGE;
goto out;
}
memcpy(value, buffer, len);
out:
security_release_secctx(buffer, len);
out_noalloc:
return len;
}
EXPORT_SYMBOL_GPL(xattr_getsecurity);
/*
* vfs_getxattr_alloc - allocate memory, if necessary, before calling getxattr
*
* Allocate memory, if not already allocated, or re-allocate correct size,
* before retrieving the extended attribute.
*
* Returns the result of alloc, if failed, or the getxattr operation.
*/
ssize_t
vfs_getxattr_alloc(struct dentry *dentry, const char *name, char **xattr_value,
size_t xattr_size, gfp_t flags)
{
struct inode *inode = dentry->d_inode;
char *value = *xattr_value;
int error;
error = xattr_permission(inode, name, MAY_READ);
if (error)
return error;
if (!inode->i_op->getxattr)
return -EOPNOTSUPP;
error = inode->i_op->getxattr(dentry, name, NULL, 0);
if (error < 0)
return error;
if (!value || (error > xattr_size)) {
value = krealloc(*xattr_value, error + 1, flags);
if (!value)
return -ENOMEM;
memset(value, 0, error + 1);
}
error = inode->i_op->getxattr(dentry, name, value, error);
*xattr_value = value;
return error;
}
/* Compare an extended attribute value with the given value */
int vfs_xattr_cmp(struct dentry *dentry, const char *xattr_name,
const char *value, size_t size, gfp_t flags)
{
char *xattr_value = NULL;
int rc;
rc = vfs_getxattr_alloc(dentry, xattr_name, &xattr_value, 0, flags);
if (rc < 0)
return rc;
if ((rc != size) || (memcmp(xattr_value, value, rc) != 0))
rc = -EINVAL;
else
rc = 0;
kfree(xattr_value);
return rc;
}
ssize_t
vfs_getxattr(struct dentry *dentry, const char *name, void *value, size_t size)
{
struct inode *inode = dentry->d_inode;
int error;
error = xattr_permission(inode, name, MAY_READ);
if (error)
return error;
error = security_inode_getxattr(dentry, name);
if (error)
return error;
if (!strncmp(name, XATTR_SECURITY_PREFIX,
XATTR_SECURITY_PREFIX_LEN)) {
const char *suffix = name + XATTR_SECURITY_PREFIX_LEN;
int ret = xattr_getsecurity(inode, suffix, value, size);
/*
* Only overwrite the return value if a security module
* is actually active.
*/
if (ret == -EOPNOTSUPP)
goto nolsm;
return ret;
}
nolsm:
if (inode->i_op->getxattr)
error = inode->i_op->getxattr(dentry, name, value, size);
else
error = -EOPNOTSUPP;
return error;
}
EXPORT_SYMBOL_GPL(vfs_getxattr);
ssize_t
vfs_listxattr(struct dentry *d, char *list, size_t size)
{
ssize_t error;
error = security_inode_listxattr(d);
if (error)
return error;
error = -EOPNOTSUPP;
if (d->d_inode->i_op->listxattr) {
error = d->d_inode->i_op->listxattr(d, list, size);
} else {
error = security_inode_listsecurity(d->d_inode, list, size);
if (size && error > size)
error = -ERANGE;
}
return error;
}
EXPORT_SYMBOL_GPL(vfs_listxattr);
int
vfs_removexattr(struct dentry *dentry, const char *name)
{
struct inode *inode = dentry->d_inode;
int error;
if (!inode->i_op->removexattr)
return -EOPNOTSUPP;
error = xattr_permission(inode, name, MAY_WRITE);
if (error)
return error;
error = security_inode_removexattr(dentry, name);
if (error)
return error;
mutex_lock(&inode->i_mutex);
error = inode->i_op->removexattr(dentry, name);
mutex_unlock(&inode->i_mutex);
if (!error) {
fsnotify_xattr(dentry);
evm_inode_post_removexattr(dentry, name);
}
return error;
}
EXPORT_SYMBOL_GPL(vfs_removexattr);
/*
* Extended attribute SET operations
*/
static long
setxattr(struct dentry *d, const char __user *name, const void __user *value,
size_t size, int flags)
{
int error;
void *kvalue = NULL;
void *vvalue = NULL; /* If non-NULL, we used vmalloc() */
char kname[XATTR_NAME_MAX + 1];
if (flags & ~(XATTR_CREATE|XATTR_REPLACE))
return -EINVAL;
error = strncpy_from_user(kname, name, sizeof(kname));
if (error == 0 || error == sizeof(kname))
error = -ERANGE;
if (error < 0)
return error;
if (size) {
if (size > XATTR_SIZE_MAX)
return -E2BIG;
kvalue = kmalloc(size, GFP_KERNEL | __GFP_NOWARN);
if (!kvalue) {
vvalue = vmalloc(size);
if (!vvalue)
return -ENOMEM;
kvalue = vvalue;
}
if (copy_from_user(kvalue, value, size)) {
error = -EFAULT;
goto out;
}
}
error = vfs_setxattr(d, kname, kvalue, size, flags);
out:
if (vvalue)
vfree(vvalue);
else
kfree(kvalue);
return error;
}
SYSCALL_DEFINE5(setxattr, const char __user *, pathname,
const char __user *, name, const void __user *, value,
size_t, size, int, flags)
{
struct path path;
int error;
error = user_path(pathname, &path);
if (error)
return error;
error = mnt_want_write(path.mnt);
if (!error) {
error = setxattr(path.dentry, name, value, size, flags);
mnt_drop_write(path.mnt);
}
path_put(&path);
return error;
}
SYSCALL_DEFINE5(lsetxattr, const char __user *, pathname,
const char __user *, name, const void __user *, value,
size_t, size, int, flags)
{
struct path path;
int error;
error = user_lpath(pathname, &path);
if (error)
return error;
error = mnt_want_write(path.mnt);
if (!error) {
error = setxattr(path.dentry, name, value, size, flags);
mnt_drop_write(path.mnt);
}
path_put(&path);
return error;
}
SYSCALL_DEFINE5(fsetxattr, int, fd, const char __user *, name,
const void __user *,value, size_t, size, int, flags)
{
struct file *f;
struct dentry *dentry;
int error = -EBADF;
f = fget(fd);
if (!f)
return error;
dentry = f->f_path.dentry;
audit_inode(NULL, dentry);
error = mnt_want_write_file(f);
if (!error) {
error = setxattr(dentry, name, value, size, flags);
mnt_drop_write_file(f);
}
fput(f);
return error;
}
/*
* Extended attribute GET operations
*/
static ssize_t
getxattr(struct dentry *d, const char __user *name, void __user *value,
size_t size)
{
ssize_t error;
void *kvalue = NULL;
char kname[XATTR_NAME_MAX + 1];
error = strncpy_from_user(kname, name, sizeof(kname));
if (error == 0 || error == sizeof(kname))
error = -ERANGE;
if (error < 0)
return error;
if (size) {
if (size > XATTR_SIZE_MAX)
size = XATTR_SIZE_MAX;
kvalue = kzalloc(size, GFP_KERNEL);
if (!kvalue)
return -ENOMEM;
}
error = vfs_getxattr(d, kname, kvalue, size);
if (error > 0) {
if (size && copy_to_user(value, kvalue, error))
error = -EFAULT;
} else if (error == -ERANGE && size >= XATTR_SIZE_MAX) {
/* The file system tried to returned a value bigger
than XATTR_SIZE_MAX bytes. Not possible. */
error = -E2BIG;
}
kfree(kvalue);
return error;
}
SYSCALL_DEFINE4(getxattr, const char __user *, pathname,
const char __user *, name, void __user *, value, size_t, size)
{
struct path path;
ssize_t error;
error = user_path(pathname, &path);
if (error)
return error;
error = getxattr(path.dentry, name, value, size);
path_put(&path);
return error;
}
SYSCALL_DEFINE4(lgetxattr, const char __user *, pathname,
const char __user *, name, void __user *, value, size_t, size)
{
struct path path;
ssize_t error;
error = user_lpath(pathname, &path);
if (error)
return error;
error = getxattr(path.dentry, name, value, size);
path_put(&path);
return error;
}
SYSCALL_DEFINE4(fgetxattr, int, fd, const char __user *, name,
void __user *, value, size_t, size)
{
struct file *f;
ssize_t error = -EBADF;
f = fget(fd);
if (!f)
return error;
audit_inode(NULL, f->f_path.dentry);
error = getxattr(f->f_path.dentry, name, value, size);
fput(f);
return error;
}
/*
* Extended attribute LIST operations
*/
static ssize_t
listxattr(struct dentry *d, char __user *list, size_t size)
{
ssize_t error;
char *klist = NULL;
char *vlist = NULL; /* If non-NULL, we used vmalloc() */
if (size) {
if (size > XATTR_LIST_MAX)
size = XATTR_LIST_MAX;
klist = kmalloc(size, __GFP_NOWARN | GFP_KERNEL);
if (!klist) {
vlist = vmalloc(size);
if (!vlist)
return -ENOMEM;
klist = vlist;
}
}
error = vfs_listxattr(d, klist, size);
if (error > 0) {
if (size && copy_to_user(list, klist, error))
error = -EFAULT;
} else if (error == -ERANGE && size >= XATTR_LIST_MAX) {
/* The file system tried to returned a list bigger
than XATTR_LIST_MAX bytes. Not possible. */
error = -E2BIG;
}
if (vlist)
vfree(vlist);
else
kfree(klist);
return error;
}
SYSCALL_DEFINE3(listxattr, const char __user *, pathname, char __user *, list,
size_t, size)
{
struct path path;
ssize_t error;
error = user_path(pathname, &path);
if (error)
return error;
error = listxattr(path.dentry, list, size);
path_put(&path);
return error;
}
SYSCALL_DEFINE3(llistxattr, const char __user *, pathname, char __user *, list,
size_t, size)
{
struct path path;
ssize_t error;
error = user_lpath(pathname, &path);
if (error)
return error;
error = listxattr(path.dentry, list, size);
path_put(&path);
return error;
}
SYSCALL_DEFINE3(flistxattr, int, fd, char __user *, list, size_t, size)
{
struct file *f;
ssize_t error = -EBADF;
f = fget(fd);
if (!f)
return error;
audit_inode(NULL, f->f_path.dentry);
error = listxattr(f->f_path.dentry, list, size);
fput(f);
return error;
}
/*
* Extended attribute REMOVE operations
*/
static long
removexattr(struct dentry *d, const char __user *name)
{
int error;
char kname[XATTR_NAME_MAX + 1];
error = strncpy_from_user(kname, name, sizeof(kname));
if (error == 0 || error == sizeof(kname))
error = -ERANGE;
if (error < 0)
return error;
return vfs_removexattr(d, kname);
}
SYSCALL_DEFINE2(removexattr, const char __user *, pathname,
const char __user *, name)
{
struct path path;
int error;
error = user_path(pathname, &path);
if (error)
return error;
error = mnt_want_write(path.mnt);
if (!error) {
error = removexattr(path.dentry, name);
mnt_drop_write(path.mnt);
}
path_put(&path);
return error;
}
SYSCALL_DEFINE2(lremovexattr, const char __user *, pathname,
const char __user *, name)
{
struct path path;
int error;
error = user_lpath(pathname, &path);
if (error)
return error;
error = mnt_want_write(path.mnt);
if (!error) {
error = removexattr(path.dentry, name);
mnt_drop_write(path.mnt);
}
path_put(&path);
return error;
}
SYSCALL_DEFINE2(fremovexattr, int, fd, const char __user *, name)
{
struct file *f;
struct dentry *dentry;
int error = -EBADF;
f = fget(fd);
if (!f)
return error;
dentry = f->f_path.dentry;
audit_inode(NULL, dentry);
error = mnt_want_write_file(f);
if (!error) {
error = removexattr(dentry, name);
mnt_drop_write_file(f);
}
fput(f);
return error;
}
static const char *
strcmp_prefix(const char *a, const char *a_prefix)
{
while (*a_prefix && *a == *a_prefix) {
a++;
a_prefix++;
}
return *a_prefix ? NULL : a;
}
/*
* In order to implement different sets of xattr operations for each xattr
* prefix with the generic xattr API, a filesystem should create a
* null-terminated array of struct xattr_handler (one for each prefix) and
* hang a pointer to it off of the s_xattr field of the superblock.
*
* The generic_fooxattr() functions will use this list to dispatch xattr
* operations to the correct xattr_handler.
*/
#define for_each_xattr_handler(handlers, handler) \
for ((handler) = *(handlers)++; \
(handler) != NULL; \
(handler) = *(handlers)++)
/*
* Find the xattr_handler with the matching prefix.
*/
static const struct xattr_handler *
xattr_resolve_name(const struct xattr_handler **handlers, const char **name)
{
const struct xattr_handler *handler;
if (!*name)
return NULL;
for_each_xattr_handler(handlers, handler) {
const char *n = strcmp_prefix(*name, handler->prefix);
if (n) {
*name = n;
break;
}
}
return handler;
}
/*
* Find the handler for the prefix and dispatch its get() operation.
*/
ssize_t
generic_getxattr(struct dentry *dentry, const char *name, void *buffer, size_t size)
{
const struct xattr_handler *handler;
handler = xattr_resolve_name(dentry->d_sb->s_xattr, &name);
if (!handler)
return -EOPNOTSUPP;
return handler->get(dentry, name, buffer, size, handler->flags);
}
/*
* Combine the results of the list() operation from every xattr_handler in the
* list.
*/
ssize_t
generic_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size)
{
const struct xattr_handler *handler, **handlers = dentry->d_sb->s_xattr;
unsigned int size = 0;
if (!buffer) {
for_each_xattr_handler(handlers, handler) {
size += handler->list(dentry, NULL, 0, NULL, 0,
handler->flags);
}
} else {
char *buf = buffer;
for_each_xattr_handler(handlers, handler) {
size = handler->list(dentry, buf, buffer_size,
NULL, 0, handler->flags);
if (size > buffer_size)
return -ERANGE;
buf += size;
buffer_size -= size;
}
size = buf - buffer;
}
return size;
}
/*
* Find the handler for the prefix and dispatch its set() operation.
*/
int
generic_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags)
{
const struct xattr_handler *handler;
if (size == 0)
value = ""; /* empty EA, do not remove */
handler = xattr_resolve_name(dentry->d_sb->s_xattr, &name);
if (!handler)
return -EOPNOTSUPP;
return handler->set(dentry, name, value, size, flags, handler->flags);
}
/*
* Find the handler for the prefix and dispatch its set() operation to remove
* any associated extended attribute.
*/
int
generic_removexattr(struct dentry *dentry, const char *name)
{
const struct xattr_handler *handler;
handler = xattr_resolve_name(dentry->d_sb->s_xattr, &name);
if (!handler)
return -EOPNOTSUPP;
return handler->set(dentry, name, NULL, 0,
XATTR_REPLACE, handler->flags);
}
EXPORT_SYMBOL(generic_getxattr);
EXPORT_SYMBOL(generic_listxattr);
EXPORT_SYMBOL(generic_setxattr);
EXPORT_SYMBOL(generic_removexattr);
| gpl-2.0 |
chirayudesai/laughing-cyril | drivers/mtd/nand/ppchameleonevb.c | 5146 | 11904 | /*
* drivers/mtd/nand/ppchameleonevb.c
*
* Copyright (C) 2003 DAVE Srl (info@wawnet.biz)
*
* Derived from drivers/mtd/nand/edb7312.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.
*
* Overview:
* This is a device driver for the NAND flash devices found on the
* PPChameleon/PPChameleonEVB system.
* PPChameleon options (autodetected):
* - BA model: no NAND
* - ME model: 32MB (Samsung K9F5608U0B)
* - HI model: 128MB (Samsung K9F1G08UOM)
* PPChameleonEVB options:
* - 32MB (Samsung K9F5608U0B)
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <asm/io.h>
#include <platforms/PPChameleonEVB.h>
#undef USE_READY_BUSY_PIN
#define USE_READY_BUSY_PIN
/* see datasheets (tR) */
#define NAND_BIG_DELAY_US 25
#define NAND_SMALL_DELAY_US 10
/* handy sizes */
#define SZ_4M 0x00400000
#define NAND_SMALL_SIZE 0x02000000
#define NAND_MTD_NAME "ppchameleon-nand"
#define NAND_EVB_MTD_NAME "ppchameleonevb-nand"
/* GPIO pins used to drive NAND chip mounted on processor module */
#define NAND_nCE_GPIO_PIN (0x80000000 >> 1)
#define NAND_CLE_GPIO_PIN (0x80000000 >> 2)
#define NAND_ALE_GPIO_PIN (0x80000000 >> 3)
#define NAND_RB_GPIO_PIN (0x80000000 >> 4)
/* GPIO pins used to drive NAND chip mounted on EVB */
#define NAND_EVB_nCE_GPIO_PIN (0x80000000 >> 14)
#define NAND_EVB_CLE_GPIO_PIN (0x80000000 >> 15)
#define NAND_EVB_ALE_GPIO_PIN (0x80000000 >> 16)
#define NAND_EVB_RB_GPIO_PIN (0x80000000 >> 31)
/*
* MTD structure for PPChameleonEVB board
*/
static struct mtd_info *ppchameleon_mtd = NULL;
static struct mtd_info *ppchameleonevb_mtd = NULL;
/*
* Module stuff
*/
static unsigned long ppchameleon_fio_pbase = CFG_NAND0_PADDR;
static unsigned long ppchameleonevb_fio_pbase = CFG_NAND1_PADDR;
#ifdef MODULE
module_param(ppchameleon_fio_pbase, ulong, 0);
module_param(ppchameleonevb_fio_pbase, ulong, 0);
#else
__setup("ppchameleon_fio_pbase=", ppchameleon_fio_pbase);
__setup("ppchameleonevb_fio_pbase=", ppchameleonevb_fio_pbase);
#endif
/*
* Define static partitions for flash devices
*/
static struct mtd_partition partition_info_hi[] = {
{ .name = "PPChameleon HI Nand Flash",
.offset = 0,
.size = 128 * 1024 * 1024
}
};
static struct mtd_partition partition_info_me[] = {
{ .name = "PPChameleon ME Nand Flash",
.offset = 0,
.size = 32 * 1024 * 1024
}
};
static struct mtd_partition partition_info_evb[] = {
{ .name = "PPChameleonEVB Nand Flash",
.offset = 0,
.size = 32 * 1024 * 1024
}
};
#define NUM_PARTITIONS 1
/*
* hardware specific access to control-lines
*/
static void ppchameleon_hwcontrol(struct mtd_info *mtdinfo, int cmd,
unsigned int ctrl)
{
struct nand_chip *chip = mtd->priv;
if (ctrl & NAND_CTRL_CHANGE) {
#error Missing headerfiles. No way to fix this. -tglx
switch (cmd) {
case NAND_CTL_SETCLE:
MACRO_NAND_CTL_SETCLE((unsigned long)CFG_NAND0_PADDR);
break;
case NAND_CTL_CLRCLE:
MACRO_NAND_CTL_CLRCLE((unsigned long)CFG_NAND0_PADDR);
break;
case NAND_CTL_SETALE:
MACRO_NAND_CTL_SETALE((unsigned long)CFG_NAND0_PADDR);
break;
case NAND_CTL_CLRALE:
MACRO_NAND_CTL_CLRALE((unsigned long)CFG_NAND0_PADDR);
break;
case NAND_CTL_SETNCE:
MACRO_NAND_ENABLE_CE((unsigned long)CFG_NAND0_PADDR);
break;
case NAND_CTL_CLRNCE:
MACRO_NAND_DISABLE_CE((unsigned long)CFG_NAND0_PADDR);
break;
}
}
if (cmd != NAND_CMD_NONE)
writeb(cmd, chip->IO_ADDR_W);
}
static void ppchameleonevb_hwcontrol(struct mtd_info *mtdinfo, int cmd,
unsigned int ctrl)
{
struct nand_chip *chip = mtd->priv;
if (ctrl & NAND_CTRL_CHANGE) {
#error Missing headerfiles. No way to fix this. -tglx
switch (cmd) {
case NAND_CTL_SETCLE:
MACRO_NAND_CTL_SETCLE((unsigned long)CFG_NAND1_PADDR);
break;
case NAND_CTL_CLRCLE:
MACRO_NAND_CTL_CLRCLE((unsigned long)CFG_NAND1_PADDR);
break;
case NAND_CTL_SETALE:
MACRO_NAND_CTL_SETALE((unsigned long)CFG_NAND1_PADDR);
break;
case NAND_CTL_CLRALE:
MACRO_NAND_CTL_CLRALE((unsigned long)CFG_NAND1_PADDR);
break;
case NAND_CTL_SETNCE:
MACRO_NAND_ENABLE_CE((unsigned long)CFG_NAND1_PADDR);
break;
case NAND_CTL_CLRNCE:
MACRO_NAND_DISABLE_CE((unsigned long)CFG_NAND1_PADDR);
break;
}
}
if (cmd != NAND_CMD_NONE)
writeb(cmd, chip->IO_ADDR_W);
}
#ifdef USE_READY_BUSY_PIN
/*
* read device ready pin
*/
static int ppchameleon_device_ready(struct mtd_info *minfo)
{
if (in_be32((volatile unsigned *)GPIO0_IR) & NAND_RB_GPIO_PIN)
return 1;
return 0;
}
static int ppchameleonevb_device_ready(struct mtd_info *minfo)
{
if (in_be32((volatile unsigned *)GPIO0_IR) & NAND_EVB_RB_GPIO_PIN)
return 1;
return 0;
}
#endif
/*
* Main initialization routine
*/
static int __init ppchameleonevb_init(void)
{
struct nand_chip *this;
void __iomem *ppchameleon_fio_base;
void __iomem *ppchameleonevb_fio_base;
/*********************************
* Processor module NAND (if any) *
*********************************/
/* Allocate memory for MTD device structure and private data */
ppchameleon_mtd = kmalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip), GFP_KERNEL);
if (!ppchameleon_mtd) {
printk("Unable to allocate PPChameleon NAND MTD device structure.\n");
return -ENOMEM;
}
/* map physical address */
ppchameleon_fio_base = ioremap(ppchameleon_fio_pbase, SZ_4M);
if (!ppchameleon_fio_base) {
printk("ioremap PPChameleon NAND flash failed\n");
kfree(ppchameleon_mtd);
return -EIO;
}
/* Get pointer to private data */
this = (struct nand_chip *)(&ppchameleon_mtd[1]);
/* Initialize structures */
memset(ppchameleon_mtd, 0, sizeof(struct mtd_info));
memset(this, 0, sizeof(struct nand_chip));
/* Link the private data with the MTD structure */
ppchameleon_mtd->priv = this;
ppchameleon_mtd->owner = THIS_MODULE;
/* Initialize GPIOs */
/* Pin mapping for NAND chip */
/*
CE GPIO_01
CLE GPIO_02
ALE GPIO_03
R/B GPIO_04
*/
/* output select */
out_be32((volatile unsigned *)GPIO0_OSRH, in_be32((volatile unsigned *)GPIO0_OSRH) & 0xC0FFFFFF);
/* three-state select */
out_be32((volatile unsigned *)GPIO0_TSRH, in_be32((volatile unsigned *)GPIO0_TSRH) & 0xC0FFFFFF);
/* enable output driver */
out_be32((volatile unsigned *)GPIO0_TCR,
in_be32((volatile unsigned *)GPIO0_TCR) | NAND_nCE_GPIO_PIN | NAND_CLE_GPIO_PIN | NAND_ALE_GPIO_PIN);
#ifdef USE_READY_BUSY_PIN
/* three-state select */
out_be32((volatile unsigned *)GPIO0_TSRH, in_be32((volatile unsigned *)GPIO0_TSRH) & 0xFF3FFFFF);
/* high-impedecence */
out_be32((volatile unsigned *)GPIO0_TCR, in_be32((volatile unsigned *)GPIO0_TCR) & (~NAND_RB_GPIO_PIN));
/* input select */
out_be32((volatile unsigned *)GPIO0_ISR1H,
(in_be32((volatile unsigned *)GPIO0_ISR1H) & 0xFF3FFFFF) | 0x00400000);
#endif
/* insert callbacks */
this->IO_ADDR_R = ppchameleon_fio_base;
this->IO_ADDR_W = ppchameleon_fio_base;
this->cmd_ctrl = ppchameleon_hwcontrol;
#ifdef USE_READY_BUSY_PIN
this->dev_ready = ppchameleon_device_ready;
#endif
this->chip_delay = NAND_BIG_DELAY_US;
/* ECC mode */
this->ecc.mode = NAND_ECC_SOFT;
/* Scan to find existence of the device (it could not be mounted) */
if (nand_scan(ppchameleon_mtd, 1)) {
iounmap((void *)ppchameleon_fio_base);
ppchameleon_fio_base = NULL;
kfree(ppchameleon_mtd);
goto nand_evb_init;
}
#ifndef USE_READY_BUSY_PIN
/* Adjust delay if necessary */
if (ppchameleon_mtd->size == NAND_SMALL_SIZE)
this->chip_delay = NAND_SMALL_DELAY_US;
#endif
ppchameleon_mtd->name = "ppchameleon-nand";
/* Register the partitions */
mtd_device_parse_register(ppchameleon_mtd, NULL, NULL,
ppchameleon_mtd->size == NAND_SMALL_SIZE ?
partition_info_me : partition_info_hi,
NUM_PARTITIONS);
nand_evb_init:
/****************************
* EVB NAND (always present) *
****************************/
/* Allocate memory for MTD device structure and private data */
ppchameleonevb_mtd = kmalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip), GFP_KERNEL);
if (!ppchameleonevb_mtd) {
printk("Unable to allocate PPChameleonEVB NAND MTD device structure.\n");
if (ppchameleon_fio_base)
iounmap(ppchameleon_fio_base);
return -ENOMEM;
}
/* map physical address */
ppchameleonevb_fio_base = ioremap(ppchameleonevb_fio_pbase, SZ_4M);
if (!ppchameleonevb_fio_base) {
printk("ioremap PPChameleonEVB NAND flash failed\n");
kfree(ppchameleonevb_mtd);
if (ppchameleon_fio_base)
iounmap(ppchameleon_fio_base);
return -EIO;
}
/* Get pointer to private data */
this = (struct nand_chip *)(&ppchameleonevb_mtd[1]);
/* Initialize structures */
memset(ppchameleonevb_mtd, 0, sizeof(struct mtd_info));
memset(this, 0, sizeof(struct nand_chip));
/* Link the private data with the MTD structure */
ppchameleonevb_mtd->priv = this;
/* Initialize GPIOs */
/* Pin mapping for NAND chip */
/*
CE GPIO_14
CLE GPIO_15
ALE GPIO_16
R/B GPIO_31
*/
/* output select */
out_be32((volatile unsigned *)GPIO0_OSRH, in_be32((volatile unsigned *)GPIO0_OSRH) & 0xFFFFFFF0);
out_be32((volatile unsigned *)GPIO0_OSRL, in_be32((volatile unsigned *)GPIO0_OSRL) & 0x3FFFFFFF);
/* three-state select */
out_be32((volatile unsigned *)GPIO0_TSRH, in_be32((volatile unsigned *)GPIO0_TSRH) & 0xFFFFFFF0);
out_be32((volatile unsigned *)GPIO0_TSRL, in_be32((volatile unsigned *)GPIO0_TSRL) & 0x3FFFFFFF);
/* enable output driver */
out_be32((volatile unsigned *)GPIO0_TCR, in_be32((volatile unsigned *)GPIO0_TCR) | NAND_EVB_nCE_GPIO_PIN |
NAND_EVB_CLE_GPIO_PIN | NAND_EVB_ALE_GPIO_PIN);
#ifdef USE_READY_BUSY_PIN
/* three-state select */
out_be32((volatile unsigned *)GPIO0_TSRL, in_be32((volatile unsigned *)GPIO0_TSRL) & 0xFFFFFFFC);
/* high-impedecence */
out_be32((volatile unsigned *)GPIO0_TCR, in_be32((volatile unsigned *)GPIO0_TCR) & (~NAND_EVB_RB_GPIO_PIN));
/* input select */
out_be32((volatile unsigned *)GPIO0_ISR1L,
(in_be32((volatile unsigned *)GPIO0_ISR1L) & 0xFFFFFFFC) | 0x00000001);
#endif
/* insert callbacks */
this->IO_ADDR_R = ppchameleonevb_fio_base;
this->IO_ADDR_W = ppchameleonevb_fio_base;
this->cmd_ctrl = ppchameleonevb_hwcontrol;
#ifdef USE_READY_BUSY_PIN
this->dev_ready = ppchameleonevb_device_ready;
#endif
this->chip_delay = NAND_SMALL_DELAY_US;
/* ECC mode */
this->ecc.mode = NAND_ECC_SOFT;
/* Scan to find existence of the device */
if (nand_scan(ppchameleonevb_mtd, 1)) {
iounmap((void *)ppchameleonevb_fio_base);
kfree(ppchameleonevb_mtd);
if (ppchameleon_fio_base)
iounmap(ppchameleon_fio_base);
return -ENXIO;
}
ppchameleonevb_mtd->name = NAND_EVB_MTD_NAME;
/* Register the partitions */
mtd_device_parse_register(ppchameleonevb_mtd, NULL, NULL,
ppchameleon_mtd->size == NAND_SMALL_SIZE ?
partition_info_me : partition_info_hi,
NUM_PARTITIONS);
/* Return happy */
return 0;
}
module_init(ppchameleonevb_init);
/*
* Clean up routine
*/
static void __exit ppchameleonevb_cleanup(void)
{
struct nand_chip *this;
/* Release resources, unregister device(s) */
nand_release(ppchameleon_mtd);
nand_release(ppchameleonevb_mtd);
/* Release iomaps */
this = (struct nand_chip *) &ppchameleon_mtd[1];
iounmap((void *) this->IO_ADDR_R);
this = (struct nand_chip *) &ppchameleonevb_mtd[1];
iounmap((void *) this->IO_ADDR_R);
/* Free the MTD device structure */
kfree (ppchameleon_mtd);
kfree (ppchameleonevb_mtd);
}
module_exit(ppchameleonevb_cleanup);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("DAVE Srl <support-ppchameleon@dave-tech.it>");
MODULE_DESCRIPTION("MTD map driver for DAVE Srl PPChameleonEVB board");
| gpl-2.0 |
pedestre/Kernel-Apolo-ICS-4.0.4 | drivers/gpu/drm/ttm/ttm_object.c | 5402 | 11815 | /**************************************************************************
*
* Copyright (c) 2009 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>
*/
/** @file ttm_ref_object.c
*
* Base- and reference object implementation for the various
* ttm objects. Implements reference counting, minimal security checks
* and release on file close.
*/
/**
* struct ttm_object_file
*
* @tdev: Pointer to the ttm_object_device.
*
* @lock: Lock that protects the ref_list list and the
* ref_hash hash tables.
*
* @ref_list: List of ttm_ref_objects to be destroyed at
* file release.
*
* @ref_hash: Hash tables of ref objects, one per ttm_ref_type,
* for fast lookup of ref objects given a base object.
*/
#define pr_fmt(fmt) "[TTM] " fmt
#include "ttm/ttm_object.h"
#include "ttm/ttm_module.h"
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/atomic.h>
struct ttm_object_file {
struct ttm_object_device *tdev;
rwlock_t lock;
struct list_head ref_list;
struct drm_open_hash ref_hash[TTM_REF_NUM];
struct kref refcount;
};
/**
* struct ttm_object_device
*
* @object_lock: lock that protects the object_hash hash table.
*
* @object_hash: hash table for fast lookup of object global names.
*
* @object_count: Per device object count.
*
* This is the per-device data structure needed for ttm object management.
*/
struct ttm_object_device {
rwlock_t object_lock;
struct drm_open_hash object_hash;
atomic_t object_count;
struct ttm_mem_global *mem_glob;
};
/**
* struct ttm_ref_object
*
* @hash: Hash entry for the per-file object reference hash.
*
* @head: List entry for the per-file list of ref-objects.
*
* @kref: Ref count.
*
* @obj: Base object this ref object is referencing.
*
* @ref_type: Type of ref object.
*
* This is similar to an idr object, but it also has a hash table entry
* that allows lookup with a pointer to the referenced object as a key. In
* that way, one can easily detect whether a base object is referenced by
* a particular ttm_object_file. It also carries a ref count to avoid creating
* multiple ref objects if a ttm_object_file references the same base
* object more than once.
*/
struct ttm_ref_object {
struct drm_hash_item hash;
struct list_head head;
struct kref kref;
enum ttm_ref_type ref_type;
struct ttm_base_object *obj;
struct ttm_object_file *tfile;
};
static inline struct ttm_object_file *
ttm_object_file_ref(struct ttm_object_file *tfile)
{
kref_get(&tfile->refcount);
return tfile;
}
static void ttm_object_file_destroy(struct kref *kref)
{
struct ttm_object_file *tfile =
container_of(kref, struct ttm_object_file, refcount);
kfree(tfile);
}
static inline void ttm_object_file_unref(struct ttm_object_file **p_tfile)
{
struct ttm_object_file *tfile = *p_tfile;
*p_tfile = NULL;
kref_put(&tfile->refcount, ttm_object_file_destroy);
}
int ttm_base_object_init(struct ttm_object_file *tfile,
struct ttm_base_object *base,
bool shareable,
enum ttm_object_type object_type,
void (*refcount_release) (struct ttm_base_object **),
void (*ref_obj_release) (struct ttm_base_object *,
enum ttm_ref_type ref_type))
{
struct ttm_object_device *tdev = tfile->tdev;
int ret;
base->shareable = shareable;
base->tfile = ttm_object_file_ref(tfile);
base->refcount_release = refcount_release;
base->ref_obj_release = ref_obj_release;
base->object_type = object_type;
write_lock(&tdev->object_lock);
kref_init(&base->refcount);
ret = drm_ht_just_insert_please(&tdev->object_hash,
&base->hash,
(unsigned long)base, 31, 0, 0);
write_unlock(&tdev->object_lock);
if (unlikely(ret != 0))
goto out_err0;
ret = ttm_ref_object_add(tfile, base, TTM_REF_USAGE, NULL);
if (unlikely(ret != 0))
goto out_err1;
ttm_base_object_unref(&base);
return 0;
out_err1:
(void)drm_ht_remove_item(&tdev->object_hash, &base->hash);
out_err0:
return ret;
}
EXPORT_SYMBOL(ttm_base_object_init);
static void ttm_release_base(struct kref *kref)
{
struct ttm_base_object *base =
container_of(kref, struct ttm_base_object, refcount);
struct ttm_object_device *tdev = base->tfile->tdev;
(void)drm_ht_remove_item(&tdev->object_hash, &base->hash);
write_unlock(&tdev->object_lock);
if (base->refcount_release) {
ttm_object_file_unref(&base->tfile);
base->refcount_release(&base);
}
write_lock(&tdev->object_lock);
}
void ttm_base_object_unref(struct ttm_base_object **p_base)
{
struct ttm_base_object *base = *p_base;
struct ttm_object_device *tdev = base->tfile->tdev;
*p_base = NULL;
/*
* Need to take the lock here to avoid racing with
* users trying to look up the object.
*/
write_lock(&tdev->object_lock);
kref_put(&base->refcount, ttm_release_base);
write_unlock(&tdev->object_lock);
}
EXPORT_SYMBOL(ttm_base_object_unref);
struct ttm_base_object *ttm_base_object_lookup(struct ttm_object_file *tfile,
uint32_t key)
{
struct ttm_object_device *tdev = tfile->tdev;
struct ttm_base_object *base;
struct drm_hash_item *hash;
int ret;
read_lock(&tdev->object_lock);
ret = drm_ht_find_item(&tdev->object_hash, key, &hash);
if (likely(ret == 0)) {
base = drm_hash_entry(hash, struct ttm_base_object, hash);
kref_get(&base->refcount);
}
read_unlock(&tdev->object_lock);
if (unlikely(ret != 0))
return NULL;
if (tfile != base->tfile && !base->shareable) {
pr_err("Attempted access of non-shareable object\n");
ttm_base_object_unref(&base);
return NULL;
}
return base;
}
EXPORT_SYMBOL(ttm_base_object_lookup);
int ttm_ref_object_add(struct ttm_object_file *tfile,
struct ttm_base_object *base,
enum ttm_ref_type ref_type, bool *existed)
{
struct drm_open_hash *ht = &tfile->ref_hash[ref_type];
struct ttm_ref_object *ref;
struct drm_hash_item *hash;
struct ttm_mem_global *mem_glob = tfile->tdev->mem_glob;
int ret = -EINVAL;
if (existed != NULL)
*existed = true;
while (ret == -EINVAL) {
read_lock(&tfile->lock);
ret = drm_ht_find_item(ht, base->hash.key, &hash);
if (ret == 0) {
ref = drm_hash_entry(hash, struct ttm_ref_object, hash);
kref_get(&ref->kref);
read_unlock(&tfile->lock);
break;
}
read_unlock(&tfile->lock);
ret = ttm_mem_global_alloc(mem_glob, sizeof(*ref),
false, false);
if (unlikely(ret != 0))
return ret;
ref = kmalloc(sizeof(*ref), GFP_KERNEL);
if (unlikely(ref == NULL)) {
ttm_mem_global_free(mem_glob, sizeof(*ref));
return -ENOMEM;
}
ref->hash.key = base->hash.key;
ref->obj = base;
ref->tfile = tfile;
ref->ref_type = ref_type;
kref_init(&ref->kref);
write_lock(&tfile->lock);
ret = drm_ht_insert_item(ht, &ref->hash);
if (likely(ret == 0)) {
list_add_tail(&ref->head, &tfile->ref_list);
kref_get(&base->refcount);
write_unlock(&tfile->lock);
if (existed != NULL)
*existed = false;
break;
}
write_unlock(&tfile->lock);
BUG_ON(ret != -EINVAL);
ttm_mem_global_free(mem_glob, sizeof(*ref));
kfree(ref);
}
return ret;
}
EXPORT_SYMBOL(ttm_ref_object_add);
static void ttm_ref_object_release(struct kref *kref)
{
struct ttm_ref_object *ref =
container_of(kref, struct ttm_ref_object, kref);
struct ttm_base_object *base = ref->obj;
struct ttm_object_file *tfile = ref->tfile;
struct drm_open_hash *ht;
struct ttm_mem_global *mem_glob = tfile->tdev->mem_glob;
ht = &tfile->ref_hash[ref->ref_type];
(void)drm_ht_remove_item(ht, &ref->hash);
list_del(&ref->head);
write_unlock(&tfile->lock);
if (ref->ref_type != TTM_REF_USAGE && base->ref_obj_release)
base->ref_obj_release(base, ref->ref_type);
ttm_base_object_unref(&ref->obj);
ttm_mem_global_free(mem_glob, sizeof(*ref));
kfree(ref);
write_lock(&tfile->lock);
}
int ttm_ref_object_base_unref(struct ttm_object_file *tfile,
unsigned long key, enum ttm_ref_type ref_type)
{
struct drm_open_hash *ht = &tfile->ref_hash[ref_type];
struct ttm_ref_object *ref;
struct drm_hash_item *hash;
int ret;
write_lock(&tfile->lock);
ret = drm_ht_find_item(ht, key, &hash);
if (unlikely(ret != 0)) {
write_unlock(&tfile->lock);
return -EINVAL;
}
ref = drm_hash_entry(hash, struct ttm_ref_object, hash);
kref_put(&ref->kref, ttm_ref_object_release);
write_unlock(&tfile->lock);
return 0;
}
EXPORT_SYMBOL(ttm_ref_object_base_unref);
void ttm_object_file_release(struct ttm_object_file **p_tfile)
{
struct ttm_ref_object *ref;
struct list_head *list;
unsigned int i;
struct ttm_object_file *tfile = *p_tfile;
*p_tfile = NULL;
write_lock(&tfile->lock);
/*
* Since we release the lock within the loop, we have to
* restart it from the beginning each time.
*/
while (!list_empty(&tfile->ref_list)) {
list = tfile->ref_list.next;
ref = list_entry(list, struct ttm_ref_object, head);
ttm_ref_object_release(&ref->kref);
}
for (i = 0; i < TTM_REF_NUM; ++i)
drm_ht_remove(&tfile->ref_hash[i]);
write_unlock(&tfile->lock);
ttm_object_file_unref(&tfile);
}
EXPORT_SYMBOL(ttm_object_file_release);
struct ttm_object_file *ttm_object_file_init(struct ttm_object_device *tdev,
unsigned int hash_order)
{
struct ttm_object_file *tfile = kmalloc(sizeof(*tfile), GFP_KERNEL);
unsigned int i;
unsigned int j = 0;
int ret;
if (unlikely(tfile == NULL))
return NULL;
rwlock_init(&tfile->lock);
tfile->tdev = tdev;
kref_init(&tfile->refcount);
INIT_LIST_HEAD(&tfile->ref_list);
for (i = 0; i < TTM_REF_NUM; ++i) {
ret = drm_ht_create(&tfile->ref_hash[i], hash_order);
if (ret) {
j = i;
goto out_err;
}
}
return tfile;
out_err:
for (i = 0; i < j; ++i)
drm_ht_remove(&tfile->ref_hash[i]);
kfree(tfile);
return NULL;
}
EXPORT_SYMBOL(ttm_object_file_init);
struct ttm_object_device *ttm_object_device_init(struct ttm_mem_global
*mem_glob,
unsigned int hash_order)
{
struct ttm_object_device *tdev = kmalloc(sizeof(*tdev), GFP_KERNEL);
int ret;
if (unlikely(tdev == NULL))
return NULL;
tdev->mem_glob = mem_glob;
rwlock_init(&tdev->object_lock);
atomic_set(&tdev->object_count, 0);
ret = drm_ht_create(&tdev->object_hash, hash_order);
if (likely(ret == 0))
return tdev;
kfree(tdev);
return NULL;
}
EXPORT_SYMBOL(ttm_object_device_init);
void ttm_object_device_release(struct ttm_object_device **p_tdev)
{
struct ttm_object_device *tdev = *p_tdev;
*p_tdev = NULL;
write_lock(&tdev->object_lock);
drm_ht_remove(&tdev->object_hash);
write_unlock(&tdev->object_lock);
kfree(tdev);
}
EXPORT_SYMBOL(ttm_object_device_release);
| gpl-2.0 |
Ca1ne/Underworld-Sense-Kernel | sound/pci/ctxfi/ctimap.c | 14618 | 2516 | /**
* Copyright (C) 2008, Creative Technology Ltd. All Rights Reserved.
*
* This source file is released under GPL v2 license (no other versions).
* See the COPYING file included in the main directory of this source
* distribution for the license terms and conditions.
*
* @File ctimap.c
*
* @Brief
* This file contains the implementation of generic input mapper operations
* for input mapper management.
*
* @Author Liu Chun
* @Date May 23 2008
*
*/
#include "ctimap.h"
#include <linux/slab.h>
int input_mapper_add(struct list_head *mappers, struct imapper *entry,
int (*map_op)(void *, struct imapper *), void *data)
{
struct list_head *pos, *pre, *head;
struct imapper *pre_ent, *pos_ent;
head = mappers;
if (list_empty(head)) {
entry->next = entry->addr;
map_op(data, entry);
list_add(&entry->list, head);
return 0;
}
list_for_each(pos, head) {
pos_ent = list_entry(pos, struct imapper, list);
if (pos_ent->slot > entry->slot) {
/* found a position in list */
break;
}
}
if (pos != head) {
pre = pos->prev;
if (pre == head)
pre = head->prev;
__list_add(&entry->list, pos->prev, pos);
} else {
pre = head->prev;
pos = head->next;
list_add_tail(&entry->list, head);
}
pre_ent = list_entry(pre, struct imapper, list);
pos_ent = list_entry(pos, struct imapper, list);
entry->next = pos_ent->addr;
map_op(data, entry);
pre_ent->next = entry->addr;
map_op(data, pre_ent);
return 0;
}
int input_mapper_delete(struct list_head *mappers, struct imapper *entry,
int (*map_op)(void *, struct imapper *), void *data)
{
struct list_head *next, *pre, *head;
struct imapper *pre_ent, *next_ent;
head = mappers;
if (list_empty(head))
return 0;
pre = (entry->list.prev == head) ? head->prev : entry->list.prev;
next = (entry->list.next == head) ? head->next : entry->list.next;
if (pre == &entry->list) {
/* entry is the only one node in mappers list */
entry->next = entry->addr = entry->user = entry->slot = 0;
map_op(data, entry);
list_del(&entry->list);
return 0;
}
pre_ent = list_entry(pre, struct imapper, list);
next_ent = list_entry(next, struct imapper, list);
pre_ent->next = next_ent->addr;
map_op(data, pre_ent);
list_del(&entry->list);
return 0;
}
void free_input_mapper_list(struct list_head *head)
{
struct imapper *entry;
struct list_head *pos;
while (!list_empty(head)) {
pos = head->next;
list_del(pos);
entry = list_entry(pos, struct imapper, list);
kfree(entry);
}
}
| gpl-2.0 |
linuxium/ubuntu-yakkety | lib/iov_iter.c | 27 | 19341 | #include <linux/export.h>
#include <linux/uio.h>
#include <linux/pagemap.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <net/checksum.h>
#define iterate_iovec(i, n, __v, __p, skip, STEP) { \
size_t left; \
size_t wanted = n; \
__p = i->iov; \
__v.iov_len = min(n, __p->iov_len - skip); \
if (likely(__v.iov_len)) { \
__v.iov_base = __p->iov_base + skip; \
left = (STEP); \
__v.iov_len -= left; \
skip += __v.iov_len; \
n -= __v.iov_len; \
} else { \
left = 0; \
} \
while (unlikely(!left && n)) { \
__p++; \
__v.iov_len = min(n, __p->iov_len); \
if (unlikely(!__v.iov_len)) \
continue; \
__v.iov_base = __p->iov_base; \
left = (STEP); \
__v.iov_len -= left; \
skip = __v.iov_len; \
n -= __v.iov_len; \
} \
n = wanted - n; \
}
#define iterate_kvec(i, n, __v, __p, skip, STEP) { \
size_t wanted = n; \
__p = i->kvec; \
__v.iov_len = min(n, __p->iov_len - skip); \
if (likely(__v.iov_len)) { \
__v.iov_base = __p->iov_base + skip; \
(void)(STEP); \
skip += __v.iov_len; \
n -= __v.iov_len; \
} \
while (unlikely(n)) { \
__p++; \
__v.iov_len = min(n, __p->iov_len); \
if (unlikely(!__v.iov_len)) \
continue; \
__v.iov_base = __p->iov_base; \
(void)(STEP); \
skip = __v.iov_len; \
n -= __v.iov_len; \
} \
n = wanted; \
}
#define iterate_bvec(i, n, __v, __bi, skip, STEP) { \
struct bvec_iter __start; \
__start.bi_size = n; \
__start.bi_bvec_done = skip; \
__start.bi_idx = 0; \
for_each_bvec(__v, i->bvec, __bi, __start) { \
if (!__v.bv_len) \
continue; \
(void)(STEP); \
} \
}
#define iterate_all_kinds(i, n, v, I, B, K) { \
size_t skip = i->iov_offset; \
if (unlikely(i->type & ITER_BVEC)) { \
struct bio_vec v; \
struct bvec_iter __bi; \
iterate_bvec(i, n, v, __bi, skip, (B)) \
} else if (unlikely(i->type & ITER_KVEC)) { \
const struct kvec *kvec; \
struct kvec v; \
iterate_kvec(i, n, v, kvec, skip, (K)) \
} else { \
const struct iovec *iov; \
struct iovec v; \
iterate_iovec(i, n, v, iov, skip, (I)) \
} \
}
#define iterate_and_advance(i, n, v, I, B, K) { \
if (unlikely(i->count < n)) \
n = i->count; \
if (i->count) { \
size_t skip = i->iov_offset; \
if (unlikely(i->type & ITER_BVEC)) { \
const struct bio_vec *bvec = i->bvec; \
struct bio_vec v; \
struct bvec_iter __bi; \
iterate_bvec(i, n, v, __bi, skip, (B)) \
i->bvec = __bvec_iter_bvec(i->bvec, __bi); \
i->nr_segs -= i->bvec - bvec; \
skip = __bi.bi_bvec_done; \
} else if (unlikely(i->type & ITER_KVEC)) { \
const struct kvec *kvec; \
struct kvec v; \
iterate_kvec(i, n, v, kvec, skip, (K)) \
if (skip == kvec->iov_len) { \
kvec++; \
skip = 0; \
} \
i->nr_segs -= kvec - i->kvec; \
i->kvec = kvec; \
} else { \
const struct iovec *iov; \
struct iovec v; \
iterate_iovec(i, n, v, iov, skip, (I)) \
if (skip == iov->iov_len) { \
iov++; \
skip = 0; \
} \
i->nr_segs -= iov - i->iov; \
i->iov = iov; \
} \
i->count -= n; \
i->iov_offset = skip; \
} \
}
static size_t copy_page_to_iter_iovec(struct page *page, size_t offset, size_t bytes,
struct iov_iter *i)
{
size_t skip, copy, left, wanted;
const struct iovec *iov;
char __user *buf;
void *kaddr, *from;
if (unlikely(bytes > i->count))
bytes = i->count;
if (unlikely(!bytes))
return 0;
wanted = bytes;
iov = i->iov;
skip = i->iov_offset;
buf = iov->iov_base + skip;
copy = min(bytes, iov->iov_len - skip);
if (IS_ENABLED(CONFIG_HIGHMEM) && !fault_in_pages_writeable(buf, copy)) {
kaddr = kmap_atomic(page);
from = kaddr + offset;
/* first chunk, usually the only one */
left = __copy_to_user_inatomic(buf, from, copy);
copy -= left;
skip += copy;
from += copy;
bytes -= copy;
while (unlikely(!left && bytes)) {
iov++;
buf = iov->iov_base;
copy = min(bytes, iov->iov_len);
left = __copy_to_user_inatomic(buf, from, copy);
copy -= left;
skip = copy;
from += copy;
bytes -= copy;
}
if (likely(!bytes)) {
kunmap_atomic(kaddr);
goto done;
}
offset = from - kaddr;
buf += copy;
kunmap_atomic(kaddr);
copy = min(bytes, iov->iov_len - skip);
}
/* Too bad - revert to non-atomic kmap */
kaddr = kmap(page);
from = kaddr + offset;
left = __copy_to_user(buf, from, copy);
copy -= left;
skip += copy;
from += copy;
bytes -= copy;
while (unlikely(!left && bytes)) {
iov++;
buf = iov->iov_base;
copy = min(bytes, iov->iov_len);
left = __copy_to_user(buf, from, copy);
copy -= left;
skip = copy;
from += copy;
bytes -= copy;
}
kunmap(page);
done:
if (skip == iov->iov_len) {
iov++;
skip = 0;
}
i->count -= wanted - bytes;
i->nr_segs -= iov - i->iov;
i->iov = iov;
i->iov_offset = skip;
return wanted - bytes;
}
static size_t copy_page_from_iter_iovec(struct page *page, size_t offset, size_t bytes,
struct iov_iter *i)
{
size_t skip, copy, left, wanted;
const struct iovec *iov;
char __user *buf;
void *kaddr, *to;
if (unlikely(bytes > i->count))
bytes = i->count;
if (unlikely(!bytes))
return 0;
wanted = bytes;
iov = i->iov;
skip = i->iov_offset;
buf = iov->iov_base + skip;
copy = min(bytes, iov->iov_len - skip);
if (IS_ENABLED(CONFIG_HIGHMEM) && !fault_in_pages_readable(buf, copy)) {
kaddr = kmap_atomic(page);
to = kaddr + offset;
/* first chunk, usually the only one */
left = __copy_from_user_inatomic(to, buf, copy);
copy -= left;
skip += copy;
to += copy;
bytes -= copy;
while (unlikely(!left && bytes)) {
iov++;
buf = iov->iov_base;
copy = min(bytes, iov->iov_len);
left = __copy_from_user_inatomic(to, buf, copy);
copy -= left;
skip = copy;
to += copy;
bytes -= copy;
}
if (likely(!bytes)) {
kunmap_atomic(kaddr);
goto done;
}
offset = to - kaddr;
buf += copy;
kunmap_atomic(kaddr);
copy = min(bytes, iov->iov_len - skip);
}
/* Too bad - revert to non-atomic kmap */
kaddr = kmap(page);
to = kaddr + offset;
left = __copy_from_user(to, buf, copy);
copy -= left;
skip += copy;
to += copy;
bytes -= copy;
while (unlikely(!left && bytes)) {
iov++;
buf = iov->iov_base;
copy = min(bytes, iov->iov_len);
left = __copy_from_user(to, buf, copy);
copy -= left;
skip = copy;
to += copy;
bytes -= copy;
}
kunmap(page);
done:
if (skip == iov->iov_len) {
iov++;
skip = 0;
}
i->count -= wanted - bytes;
i->nr_segs -= iov - i->iov;
i->iov = iov;
i->iov_offset = skip;
return wanted - bytes;
}
/*
* Fault in one or more iovecs of the given iov_iter, to a maximum length of
* bytes. For each iovec, fault in each page that constitutes the iovec.
*
* Return 0 on success, or non-zero if the memory could not be accessed (i.e.
* because it is an invalid address).
*/
int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
{
size_t skip = i->iov_offset;
const struct iovec *iov;
int err;
struct iovec v;
if (!(i->type & (ITER_BVEC|ITER_KVEC))) {
iterate_iovec(i, bytes, v, iov, skip, ({
err = fault_in_multipages_readable(v.iov_base,
v.iov_len);
if (unlikely(err))
return err;
0;}))
}
return 0;
}
EXPORT_SYMBOL(iov_iter_fault_in_readable);
void iov_iter_init(struct iov_iter *i, int direction,
const struct iovec *iov, unsigned long nr_segs,
size_t count)
{
/* It will get better. Eventually... */
if (segment_eq(get_fs(), KERNEL_DS)) {
direction |= ITER_KVEC;
i->type = direction;
i->kvec = (struct kvec *)iov;
} else {
i->type = direction;
i->iov = iov;
}
i->nr_segs = nr_segs;
i->iov_offset = 0;
i->count = count;
}
EXPORT_SYMBOL(iov_iter_init);
static void memcpy_from_page(char *to, struct page *page, size_t offset, size_t len)
{
char *from = kmap_atomic(page);
memcpy(to, from + offset, len);
kunmap_atomic(from);
}
static void memcpy_to_page(struct page *page, size_t offset, const char *from, size_t len)
{
char *to = kmap_atomic(page);
memcpy(to + offset, from, len);
kunmap_atomic(to);
}
static void memzero_page(struct page *page, size_t offset, size_t len)
{
char *addr = kmap_atomic(page);
memset(addr + offset, 0, len);
kunmap_atomic(addr);
}
size_t copy_to_iter(const void *addr, size_t bytes, struct iov_iter *i)
{
const char *from = addr;
iterate_and_advance(i, bytes, v,
__copy_to_user(v.iov_base, (from += v.iov_len) - v.iov_len,
v.iov_len),
memcpy_to_page(v.bv_page, v.bv_offset,
(from += v.bv_len) - v.bv_len, v.bv_len),
memcpy(v.iov_base, (from += v.iov_len) - v.iov_len, v.iov_len)
)
return bytes;
}
EXPORT_SYMBOL(copy_to_iter);
size_t copy_from_iter(void *addr, size_t bytes, struct iov_iter *i)
{
char *to = addr;
iterate_and_advance(i, bytes, v,
__copy_from_user((to += v.iov_len) - v.iov_len, v.iov_base,
v.iov_len),
memcpy_from_page((to += v.bv_len) - v.bv_len, v.bv_page,
v.bv_offset, v.bv_len),
memcpy((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len)
)
return bytes;
}
EXPORT_SYMBOL(copy_from_iter);
size_t copy_from_iter_nocache(void *addr, size_t bytes, struct iov_iter *i)
{
char *to = addr;
iterate_and_advance(i, bytes, v,
__copy_from_user_nocache((to += v.iov_len) - v.iov_len,
v.iov_base, v.iov_len),
memcpy_from_page((to += v.bv_len) - v.bv_len, v.bv_page,
v.bv_offset, v.bv_len),
memcpy((to += v.iov_len) - v.iov_len, v.iov_base, v.iov_len)
)
return bytes;
}
EXPORT_SYMBOL(copy_from_iter_nocache);
size_t copy_page_to_iter(struct page *page, size_t offset, size_t bytes,
struct iov_iter *i)
{
if (i->type & (ITER_BVEC|ITER_KVEC)) {
void *kaddr = kmap_atomic(page);
size_t wanted = copy_to_iter(kaddr + offset, bytes, i);
kunmap_atomic(kaddr);
return wanted;
} else
return copy_page_to_iter_iovec(page, offset, bytes, i);
}
EXPORT_SYMBOL(copy_page_to_iter);
size_t copy_page_from_iter(struct page *page, size_t offset, size_t bytes,
struct iov_iter *i)
{
if (i->type & (ITER_BVEC|ITER_KVEC)) {
void *kaddr = kmap_atomic(page);
size_t wanted = copy_from_iter(kaddr + offset, bytes, i);
kunmap_atomic(kaddr);
return wanted;
} else
return copy_page_from_iter_iovec(page, offset, bytes, i);
}
EXPORT_SYMBOL(copy_page_from_iter);
size_t iov_iter_zero(size_t bytes, struct iov_iter *i)
{
iterate_and_advance(i, bytes, v,
__clear_user(v.iov_base, v.iov_len),
memzero_page(v.bv_page, v.bv_offset, v.bv_len),
memset(v.iov_base, 0, v.iov_len)
)
return bytes;
}
EXPORT_SYMBOL(iov_iter_zero);
size_t iov_iter_copy_from_user_atomic(struct page *page,
struct iov_iter *i, unsigned long offset, size_t bytes)
{
char *kaddr = kmap_atomic(page), *p = kaddr + offset;
iterate_all_kinds(i, bytes, v,
__copy_from_user_inatomic((p += v.iov_len) - v.iov_len,
v.iov_base, v.iov_len),
memcpy_from_page((p += v.bv_len) - v.bv_len, v.bv_page,
v.bv_offset, v.bv_len),
memcpy((p += v.iov_len) - v.iov_len, v.iov_base, v.iov_len)
)
kunmap_atomic(kaddr);
return bytes;
}
EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
void iov_iter_advance(struct iov_iter *i, size_t size)
{
iterate_and_advance(i, size, v, 0, 0, 0)
}
EXPORT_SYMBOL(iov_iter_advance);
/*
* Return the count of just the current iov_iter segment.
*/
size_t iov_iter_single_seg_count(const struct iov_iter *i)
{
if (i->nr_segs == 1)
return i->count;
else if (i->type & ITER_BVEC)
return min(i->count, i->bvec->bv_len - i->iov_offset);
else
return min(i->count, i->iov->iov_len - i->iov_offset);
}
EXPORT_SYMBOL(iov_iter_single_seg_count);
void iov_iter_kvec(struct iov_iter *i, int direction,
const struct kvec *kvec, unsigned long nr_segs,
size_t count)
{
BUG_ON(!(direction & ITER_KVEC));
i->type = direction;
i->kvec = kvec;
i->nr_segs = nr_segs;
i->iov_offset = 0;
i->count = count;
}
EXPORT_SYMBOL(iov_iter_kvec);
void iov_iter_bvec(struct iov_iter *i, int direction,
const struct bio_vec *bvec, unsigned long nr_segs,
size_t count)
{
BUG_ON(!(direction & ITER_BVEC));
i->type = direction;
i->bvec = bvec;
i->nr_segs = nr_segs;
i->iov_offset = 0;
i->count = count;
}
EXPORT_SYMBOL(iov_iter_bvec);
unsigned long iov_iter_alignment(const struct iov_iter *i)
{
unsigned long res = 0;
size_t size = i->count;
if (!size)
return 0;
iterate_all_kinds(i, size, v,
(res |= (unsigned long)v.iov_base | v.iov_len, 0),
res |= v.bv_offset | v.bv_len,
res |= (unsigned long)v.iov_base | v.iov_len
)
return res;
}
EXPORT_SYMBOL(iov_iter_alignment);
unsigned long iov_iter_gap_alignment(const struct iov_iter *i)
{
unsigned long res = 0;
size_t size = i->count;
if (!size)
return 0;
iterate_all_kinds(i, size, v,
(res |= (!res ? 0 : (unsigned long)v.iov_base) |
(size != v.iov_len ? size : 0), 0),
(res |= (!res ? 0 : (unsigned long)v.bv_offset) |
(size != v.bv_len ? size : 0)),
(res |= (!res ? 0 : (unsigned long)v.iov_base) |
(size != v.iov_len ? size : 0))
);
return res;
}
EXPORT_SYMBOL(iov_iter_gap_alignment);
ssize_t iov_iter_get_pages(struct iov_iter *i,
struct page **pages, size_t maxsize, unsigned maxpages,
size_t *start)
{
if (maxsize > i->count)
maxsize = i->count;
if (!maxsize)
return 0;
iterate_all_kinds(i, maxsize, v, ({
unsigned long addr = (unsigned long)v.iov_base;
size_t len = v.iov_len + (*start = addr & (PAGE_SIZE - 1));
int n;
int res;
if (len > maxpages * PAGE_SIZE)
len = maxpages * PAGE_SIZE;
addr &= ~(PAGE_SIZE - 1);
n = DIV_ROUND_UP(len, PAGE_SIZE);
res = get_user_pages_fast(addr, n, (i->type & WRITE) != WRITE, pages);
if (unlikely(res < 0))
return res;
return (res == n ? len : res * PAGE_SIZE) - *start;
0;}),({
/* can't be more than PAGE_SIZE */
*start = v.bv_offset;
get_page(*pages = v.bv_page);
return v.bv_len;
}),({
return -EFAULT;
})
)
return 0;
}
EXPORT_SYMBOL(iov_iter_get_pages);
static struct page **get_pages_array(size_t n)
{
struct page **p = kmalloc(n * sizeof(struct page *), GFP_KERNEL);
if (!p)
p = vmalloc(n * sizeof(struct page *));
return p;
}
ssize_t iov_iter_get_pages_alloc(struct iov_iter *i,
struct page ***pages, size_t maxsize,
size_t *start)
{
struct page **p;
if (maxsize > i->count)
maxsize = i->count;
if (!maxsize)
return 0;
iterate_all_kinds(i, maxsize, v, ({
unsigned long addr = (unsigned long)v.iov_base;
size_t len = v.iov_len + (*start = addr & (PAGE_SIZE - 1));
int n;
int res;
addr &= ~(PAGE_SIZE - 1);
n = DIV_ROUND_UP(len, PAGE_SIZE);
p = get_pages_array(n);
if (!p)
return -ENOMEM;
res = get_user_pages_fast(addr, n, (i->type & WRITE) != WRITE, p);
if (unlikely(res < 0)) {
kvfree(p);
return res;
}
*pages = p;
return (res == n ? len : res * PAGE_SIZE) - *start;
0;}),({
/* can't be more than PAGE_SIZE */
*start = v.bv_offset;
*pages = p = get_pages_array(1);
if (!p)
return -ENOMEM;
get_page(*p = v.bv_page);
return v.bv_len;
}),({
return -EFAULT;
})
)
return 0;
}
EXPORT_SYMBOL(iov_iter_get_pages_alloc);
size_t csum_and_copy_from_iter(void *addr, size_t bytes, __wsum *csum,
struct iov_iter *i)
{
char *to = addr;
__wsum sum, next;
size_t off = 0;
sum = *csum;
iterate_and_advance(i, bytes, v, ({
int err = 0;
next = csum_and_copy_from_user(v.iov_base,
(to += v.iov_len) - v.iov_len,
v.iov_len, 0, &err);
if (!err) {
sum = csum_block_add(sum, next, off);
off += v.iov_len;
}
err ? v.iov_len : 0;
}), ({
char *p = kmap_atomic(v.bv_page);
next = csum_partial_copy_nocheck(p + v.bv_offset,
(to += v.bv_len) - v.bv_len,
v.bv_len, 0);
kunmap_atomic(p);
sum = csum_block_add(sum, next, off);
off += v.bv_len;
}),({
next = csum_partial_copy_nocheck(v.iov_base,
(to += v.iov_len) - v.iov_len,
v.iov_len, 0);
sum = csum_block_add(sum, next, off);
off += v.iov_len;
})
)
*csum = sum;
return bytes;
}
EXPORT_SYMBOL(csum_and_copy_from_iter);
size_t csum_and_copy_to_iter(const void *addr, size_t bytes, __wsum *csum,
struct iov_iter *i)
{
const char *from = addr;
__wsum sum, next;
size_t off = 0;
sum = *csum;
iterate_and_advance(i, bytes, v, ({
int err = 0;
next = csum_and_copy_to_user((from += v.iov_len) - v.iov_len,
v.iov_base,
v.iov_len, 0, &err);
if (!err) {
sum = csum_block_add(sum, next, off);
off += v.iov_len;
}
err ? v.iov_len : 0;
}), ({
char *p = kmap_atomic(v.bv_page);
next = csum_partial_copy_nocheck((from += v.bv_len) - v.bv_len,
p + v.bv_offset,
v.bv_len, 0);
kunmap_atomic(p);
sum = csum_block_add(sum, next, off);
off += v.bv_len;
}),({
next = csum_partial_copy_nocheck((from += v.iov_len) - v.iov_len,
v.iov_base,
v.iov_len, 0);
sum = csum_block_add(sum, next, off);
off += v.iov_len;
})
)
*csum = sum;
return bytes;
}
EXPORT_SYMBOL(csum_and_copy_to_iter);
int iov_iter_npages(const struct iov_iter *i, int maxpages)
{
size_t size = i->count;
int npages = 0;
if (!size)
return 0;
iterate_all_kinds(i, size, v, ({
unsigned long p = (unsigned long)v.iov_base;
npages += DIV_ROUND_UP(p + v.iov_len, PAGE_SIZE)
- p / PAGE_SIZE;
if (npages >= maxpages)
return maxpages;
0;}),({
npages++;
if (npages >= maxpages)
return maxpages;
}),({
unsigned long p = (unsigned long)v.iov_base;
npages += DIV_ROUND_UP(p + v.iov_len, PAGE_SIZE)
- p / PAGE_SIZE;
if (npages >= maxpages)
return maxpages;
})
)
return npages;
}
EXPORT_SYMBOL(iov_iter_npages);
const void *dup_iter(struct iov_iter *new, struct iov_iter *old, gfp_t flags)
{
*new = *old;
if (new->type & ITER_BVEC)
return new->bvec = kmemdup(new->bvec,
new->nr_segs * sizeof(struct bio_vec),
flags);
else
/* iovec and kvec have identical layout */
return new->iov = kmemdup(new->iov,
new->nr_segs * sizeof(struct iovec),
flags);
}
EXPORT_SYMBOL(dup_iter);
int import_iovec(int type, const struct iovec __user * uvector,
unsigned nr_segs, unsigned fast_segs,
struct iovec **iov, struct iov_iter *i)
{
ssize_t n;
struct iovec *p;
n = rw_copy_check_uvector(type, uvector, nr_segs, fast_segs,
*iov, &p);
if (n < 0) {
if (p != *iov)
kfree(p);
*iov = NULL;
return n;
}
iov_iter_init(i, type, p, nr_segs, n);
*iov = p == *iov ? NULL : p;
return 0;
}
EXPORT_SYMBOL(import_iovec);
#ifdef CONFIG_COMPAT
#include <linux/compat.h>
int compat_import_iovec(int type, const struct compat_iovec __user * uvector,
unsigned nr_segs, unsigned fast_segs,
struct iovec **iov, struct iov_iter *i)
{
ssize_t n;
struct iovec *p;
n = compat_rw_copy_check_uvector(type, uvector, nr_segs, fast_segs,
*iov, &p);
if (n < 0) {
if (p != *iov)
kfree(p);
*iov = NULL;
return n;
}
iov_iter_init(i, type, p, nr_segs, n);
*iov = p == *iov ? NULL : p;
return 0;
}
#endif
int import_single_range(int rw, void __user *buf, size_t len,
struct iovec *iov, struct iov_iter *i)
{
if (len > MAX_RW_COUNT)
len = MAX_RW_COUNT;
if (unlikely(!access_ok(!rw, buf, len)))
return -EFAULT;
iov->iov_base = buf;
iov->iov_len = len;
iov_iter_init(i, rw, iov, 1, len);
return 0;
}
EXPORT_SYMBOL(import_single_range);
| gpl-2.0 |
mikewadsten/asuswrt | release/src/router/samba3/source/modules/vfs_hpuxacl.c | 27 | 31917 | /*
* Unix SMB/Netbios implementation.
* VFS module to get and set HP-UX ACLs
* Copyright (C) Michael Adam 2006
*
* 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.
*/
/*
* This module supports JFS (POSIX) ACLs on VxFS (Veritas * Filesystem).
* These are available on HP-UX 11.00 if JFS 3.3 is installed.
* On HP-UX 11i (11.11 and above) these ACLs are supported out of
* the box.
*
* There is another form of ACLs on HFS. These ACLs have a
* completely different API and their own set of userland tools.
* Since HFS seems to be considered deprecated, HFS acls
* are not supported. (They could be supported through a separate
* vfs-module if there is demand.)
*/
/* =================================================================
* NOTE:
*
* The original hpux-acl code in lib/sysacls.c was based upon the
* solaris acl code in the same file. Now for the new modularized
* acl implementation, I have taken the code from vfs_solarisacls.c
* and did similar adaptations as were done before, essentially
* reusing the original internal aclsort functions.
* The check for the presence of the acl() call has been adopted, and
* a check for the presence of the aclsort() call has been added.
*
* Michael Adam <obnox@samba.org>
*
* ================================================================= */
#include "includes.h"
/*
* including standard header <sys/aclv.h>
*
* included here as a quick hack for the special HP-UX-situation:
*
* The problem is that, on HP-UX, jfs/posix acls are
* defined in <sys/aclv.h>, while the deprecated hfs acls
* are defined inside <sys/acl.h>.
*
*/
/* GROUP is defined somewhere else so undef it here... */
#undef GROUP
#include <sys/aclv.h>
/* dl.h: needed to check for acl call via shl_findsym */
#include <dl.h>
typedef struct acl HPUX_ACE_T;
typedef struct acl *HPUX_ACL_T;
typedef int HPUX_ACL_TAG_T; /* the type of an ACL entry */
typedef ushort HPUX_PERM_T;
/* Structure to capture the count for each type of ACE.
* (for hpux_internal_aclsort */
struct hpux_acl_types {
int n_user;
int n_def_user;
int n_user_obj;
int n_def_user_obj;
int n_group;
int n_def_group;
int n_group_obj;
int n_def_group_obj;
int n_other;
int n_other_obj;
int n_def_other_obj;
int n_class_obj;
int n_def_class_obj;
int n_illegal_obj;
};
/* for convenience: check if hpux acl entry is a default entry? */
#define _IS_DEFAULT(ace) ((ace).a_type & ACL_DEFAULT)
#define _IS_OF_TYPE(ace, type) ( \
(((type) == SMB_ACL_TYPE_ACCESS) && !_IS_DEFAULT(ace)) \
|| \
(((type) == SMB_ACL_TYPE_DEFAULT) && _IS_DEFAULT(ace)) \
)
/* prototypes for private functions */
static HPUX_ACL_T hpux_acl_init(int count);
static BOOL smb_acl_to_hpux_acl(SMB_ACL_T smb_acl,
HPUX_ACL_T *solariacl, int *count,
SMB_ACL_TYPE_T type);
static SMB_ACL_T hpux_acl_to_smb_acl(HPUX_ACL_T hpuxacl, int count,
SMB_ACL_TYPE_T type);
static HPUX_ACL_TAG_T smb_tag_to_hpux_tag(SMB_ACL_TAG_T smb_tag);
static SMB_ACL_TAG_T hpux_tag_to_smb_tag(HPUX_ACL_TAG_T hpux_tag);
static BOOL hpux_add_to_acl(HPUX_ACL_T *hpux_acl, int *count,
HPUX_ACL_T add_acl, int add_count, SMB_ACL_TYPE_T type);
static BOOL hpux_acl_get_file(const char *name, HPUX_ACL_T *hpuxacl,
int *count);
static SMB_ACL_PERM_T hpux_perm_to_smb_perm(const HPUX_PERM_T perm);
static HPUX_PERM_T smb_perm_to_hpux_perm(const SMB_ACL_PERM_T perm);
#if 0
static BOOL hpux_acl_check(HPUX_ACL_T hpux_acl, int count);
#endif
/* aclsort (internal) and helpers: */
static BOOL hpux_acl_sort(HPUX_ACL_T acl, int count);
static int hpux_internal_aclsort(int acl_count, int calclass, HPUX_ACL_T aclp);
static void hpux_count_obj(int acl_count, HPUX_ACL_T aclp,
struct hpux_acl_types *acl_type_count);
static void hpux_swap_acl_entries(HPUX_ACE_T *aclp0, HPUX_ACE_T *aclp1);
static BOOL hpux_prohibited_duplicate_type(int acl_type);
static BOOL hpux_acl_call_present(void);
static BOOL hpux_aclsort_call_present(void);
/* public functions - the api */
SMB_ACL_T hpuxacl_sys_acl_get_file(vfs_handle_struct *handle,
const char *path_p,
SMB_ACL_TYPE_T type)
{
SMB_ACL_T result = NULL;
int count;
HPUX_ACL_T hpux_acl = NULL;
DEBUG(10, ("hpuxacl_sys_acl_get_file called for file '%s'.\n",
path_p));
if(hpux_acl_call_present() == False) {
/* Looks like we don't have the acl() system call on HPUX.
* May be the system doesn't have the latest version of JFS.
*/
goto done;
}
if (type != SMB_ACL_TYPE_ACCESS && type != SMB_ACL_TYPE_DEFAULT) {
DEBUG(10, ("invalid SMB_ACL_TYPE given (%d)\n", type));
errno = EINVAL;
goto done;
}
DEBUGADD(10, ("getting %s acl\n",
((type == SMB_ACL_TYPE_ACCESS) ? "access" : "default")));
if (!hpux_acl_get_file(path_p, &hpux_acl, &count)) {
goto done;
}
result = hpux_acl_to_smb_acl(hpux_acl, count, type);
if (result == NULL) {
DEBUG(10, ("conversion hpux_acl -> smb_acl failed (%s).\n",
strerror(errno)));
}
done:
DEBUG(10, ("hpuxacl_sys_acl_get_file %s.\n",
((result == NULL) ? "failed" : "succeeded" )));
SAFE_FREE(hpux_acl);
return result;
}
/*
* get the access ACL of a file referred to by a fd
*/
SMB_ACL_T hpuxacl_sys_acl_get_fd(vfs_handle_struct *handle,
files_struct *fsp,
int fd)
{
/*
* HPUX doesn't have the facl call. Fake it using the path.... JRA.
*/
/* For all I see, the info should already be in the fsp
* parameter, but get it again to be safe --- necessary? */
files_struct *file_struct_p = file_find_fd(fd);
if (file_struct_p == NULL) {
errno = EBADF;
return NULL;
}
/*
* We know we're in the same conn context. So we
* can use the relative path.
*/
DEBUG(10, ("redirecting call of hpuxacl_sys_acl_get_fd to "
"hpuxacl_sys_acl_get_file (no facl syscall on HPUX).\n"));
return hpuxacl_sys_acl_get_file(handle, file_struct_p->fsp_name,
SMB_ACL_TYPE_ACCESS);
}
int hpuxacl_sys_acl_set_file(vfs_handle_struct *handle,
const char *name,
SMB_ACL_TYPE_T type,
SMB_ACL_T theacl)
{
int ret = -1;
SMB_STRUCT_STAT s;
HPUX_ACL_T hpux_acl = NULL;
int count;
DEBUG(10, ("hpuxacl_sys_acl_set_file called for file '%s'\n",
name));
if(hpux_acl_call_present() == False) {
/* Looks like we don't have the acl() system call on HPUX.
* May be the system doesn't have the latest version of JFS.
*/
goto done;
}
if ((type != SMB_ACL_TYPE_ACCESS) && (type != SMB_ACL_TYPE_DEFAULT)) {
errno = EINVAL;
DEBUG(10, ("invalid smb acl type given (%d).\n", type));
goto done;
}
DEBUGADD(10, ("setting %s acl\n",
((type == SMB_ACL_TYPE_ACCESS) ? "access" : "default")));
if(!smb_acl_to_hpux_acl(theacl, &hpux_acl, &count, type)) {
DEBUG(10, ("conversion smb_acl -> hpux_acl failed (%s).\n",
strerror(errno)));
goto done;
}
/*
* if the file is a directory, there is extra work to do:
* since the hpux acl call stores both the access acl and
* the default acl as provided, we have to get the acl part
* that has _not_ been specified in "type" from the file first
* and concatenate it with the acl provided.
*/
if (SMB_VFS_STAT(handle->conn, name, &s) != 0) {
DEBUG(10, ("Error in stat call: %s\n", strerror(errno)));
goto done;
}
if (S_ISDIR(s.st_mode)) {
HPUX_ACL_T other_acl;
int other_count;
SMB_ACL_TYPE_T other_type;
other_type = (type == SMB_ACL_TYPE_ACCESS)
? SMB_ACL_TYPE_DEFAULT
: SMB_ACL_TYPE_ACCESS;
DEBUGADD(10, ("getting acl from filesystem\n"));
if (!hpux_acl_get_file(name, &other_acl, &other_count)) {
DEBUG(10, ("error getting acl from directory\n"));
goto done;
}
DEBUG(10, ("adding %s part of fs acl to given acl\n",
((other_type == SMB_ACL_TYPE_ACCESS)
? "access"
: "default")));
if (!hpux_add_to_acl(&hpux_acl, &count, other_acl,
other_count, other_type))
{
DEBUG(10, ("error adding other acl.\n"));
SAFE_FREE(other_acl);
goto done;
}
SAFE_FREE(other_acl);
}
else if (type != SMB_ACL_TYPE_ACCESS) {
errno = EINVAL;
goto done;
}
if (!hpux_acl_sort(hpux_acl, count)) {
DEBUG(10, ("resulting acl is not valid!\n"));
goto done;
}
DEBUG(10, ("resulting acl is valid.\n"));
ret = acl(CONST_DISCARD(char *, name), ACL_SET, count, hpux_acl);
if (ret != 0) {
DEBUG(0, ("ERROR calling acl: %s\n", strerror(errno)));
}
done:
DEBUG(10, ("hpuxacl_sys_acl_set_file %s.\n",
((ret != 0) ? "failed" : "succeeded")));
SAFE_FREE(hpux_acl);
return ret;
}
/*
* set the access ACL on the file referred to by a fd
*/
int hpuxacl_sys_acl_set_fd(vfs_handle_struct *handle,
files_struct *fsp,
int fd, SMB_ACL_T theacl)
{
/*
* HPUX doesn't have the facl call. Fake it using the path.... JRA.
*/
/* For all I see, the info should already be in the fsp
* parameter, but get it again to be safe --- necessary? */
files_struct *file_struct_p = file_find_fd(fd);
if (file_struct_p == NULL) {
errno = EBADF;
return -1;
}
/*
* We know we're in the same conn context. So we
* can use the relative path.
*/
DEBUG(10, ("redirecting call of hpuxacl_sys_acl_set_fd to "
"hpuxacl_sys_acl_set_file (no facl syscall on HPUX)\n"));
return hpuxacl_sys_acl_set_file(handle, file_struct_p->fsp_name,
SMB_ACL_TYPE_ACCESS, theacl);
}
/*
* delete the default ACL of a directory
*
* This is achieved by fetching the access ACL and rewriting it
* directly, via the hpux system call: the ACL_SET call on
* directories writes both the access and the default ACL as provided.
*
* XXX: posix acl_delete_def_file returns an error if
* the file referred to by path is not a directory.
* this function does not complain but the actions
* have no effect on a file other than a directory.
* But sys_acl_delete_default_file is only called in
* smbd/posixacls.c after having checked that the file
* is a directory, anyways. So implementing the extra
* check is considered unnecessary. --- Agreed? XXX
*/
int hpuxacl_sys_acl_delete_def_file(vfs_handle_struct *handle,
const char *path)
{
SMB_ACL_T smb_acl;
int ret = -1;
HPUX_ACL_T hpux_acl;
int count;
DEBUG(10, ("entering hpuxacl_sys_acl_delete_def_file.\n"));
smb_acl = hpuxacl_sys_acl_get_file(handle, path,
SMB_ACL_TYPE_ACCESS);
if (smb_acl == NULL) {
DEBUG(10, ("getting file acl failed!\n"));
goto done;
}
if (!smb_acl_to_hpux_acl(smb_acl, &hpux_acl, &count,
SMB_ACL_TYPE_ACCESS))
{
DEBUG(10, ("conversion smb_acl -> hpux_acl failed.\n"));
goto done;
}
if (!hpux_acl_sort(hpux_acl, count)) {
DEBUG(10, ("resulting acl is not valid!\n"));
goto done;
}
ret = acl(CONST_DISCARD(char *, path), ACL_SET, count, hpux_acl);
if (ret != 0) {
DEBUG(10, ("settinge file acl failed!\n"));
}
done:
DEBUG(10, ("hpuxacl_sys_acl_delete_def_file %s.\n",
((ret != 0) ? "failed" : "succeeded" )));
SAFE_FREE(smb_acl);
return ret;
}
/*
* private functions
*/
static HPUX_ACL_T hpux_acl_init(int count)
{
HPUX_ACL_T hpux_acl =
(HPUX_ACL_T)SMB_MALLOC(sizeof(HPUX_ACE_T) * count);
if (hpux_acl == NULL) {
errno = ENOMEM;
}
return hpux_acl;
}
/*
* Convert the SMB acl to the ACCESS or DEFAULT part of a
* hpux ACL, as desired.
*/
static BOOL smb_acl_to_hpux_acl(SMB_ACL_T smb_acl,
HPUX_ACL_T *hpux_acl, int *count,
SMB_ACL_TYPE_T type)
{
BOOL ret = False;
int i;
int check_which, check_rc;
DEBUG(10, ("entering smb_acl_to_hpux_acl\n"));
*hpux_acl = NULL;
*count = 0;
for (i = 0; i < smb_acl->count; i++) {
const struct smb_acl_entry *smb_entry = &(smb_acl->acl[i]);
HPUX_ACE_T hpux_entry;
ZERO_STRUCT(hpux_entry);
hpux_entry.a_type = smb_tag_to_hpux_tag(smb_entry->a_type);
if (hpux_entry.a_type == 0) {
DEBUG(10, ("smb_tag to hpux_tag failed\n"));
goto fail;
}
switch(hpux_entry.a_type) {
case USER:
DEBUG(10, ("got tag type USER with uid %d\n",
smb_entry->uid));
hpux_entry.a_id = (uid_t)smb_entry->uid;
break;
case GROUP:
DEBUG(10, ("got tag type GROUP with gid %d\n",
smb_entry->gid));
hpux_entry.a_id = (uid_t)smb_entry->gid;
break;
default:
break;
}
if (type == SMB_ACL_TYPE_DEFAULT) {
DEBUG(10, ("adding default bit to hpux ace\n"));
hpux_entry.a_type |= ACL_DEFAULT;
}
hpux_entry.a_perm =
smb_perm_to_hpux_perm(smb_entry->a_perm);
DEBUG(10, ("assembled the following hpux ace:\n"));
DEBUGADD(10, (" - type: 0x%04x\n", hpux_entry.a_type));
DEBUGADD(10, (" - id: %d\n", hpux_entry.a_id));
DEBUGADD(10, (" - perm: o%o\n", hpux_entry.a_perm));
if (!hpux_add_to_acl(hpux_acl, count, &hpux_entry,
1, type))
{
DEBUG(10, ("error adding acl entry\n"));
goto fail;
}
DEBUG(10, ("count after adding: %d (i: %d)\n", *count, i));
DEBUG(10, ("test, if entry has been copied into acl:\n"));
DEBUGADD(10, (" - type: 0x%04x\n",
(*hpux_acl)[(*count)-1].a_type));
DEBUGADD(10, (" - id: %d\n",
(*hpux_acl)[(*count)-1].a_id));
DEBUGADD(10, (" - perm: o%o\n",
(*hpux_acl)[(*count)-1].a_perm));
}
ret = True;
goto done;
fail:
SAFE_FREE(*hpux_acl);
done:
DEBUG(10, ("smb_acl_to_hpux_acl %s\n",
((ret == True) ? "succeeded" : "failed")));
return ret;
}
/*
* convert either the access or the default part of a
* soaris acl to the SMB_ACL format.
*/
static SMB_ACL_T hpux_acl_to_smb_acl(HPUX_ACL_T hpux_acl, int count,
SMB_ACL_TYPE_T type)
{
SMB_ACL_T result;
int i;
if ((result = sys_acl_init(0)) == NULL) {
DEBUG(10, ("error allocating memory for SMB_ACL\n"));
goto fail;
}
for (i = 0; i < count; i++) {
SMB_ACL_ENTRY_T smb_entry;
SMB_ACL_PERM_T smb_perm;
if (!_IS_OF_TYPE(hpux_acl[i], type)) {
continue;
}
result = SMB_REALLOC(result,
sizeof(struct smb_acl_t) +
(sizeof(struct smb_acl_entry) *
(result->count + 1)));
if (result == NULL) {
DEBUG(10, ("error reallocating memory for SMB_ACL\n"));
goto fail;
}
smb_entry = &result->acl[result->count];
if (sys_acl_set_tag_type(smb_entry,
hpux_tag_to_smb_tag(hpux_acl[i].a_type)) != 0)
{
DEBUG(10, ("invalid tag type given: 0x%04x\n",
hpux_acl[i].a_type));
goto fail;
}
/* intentionally not checking return code here: */
sys_acl_set_qualifier(smb_entry, (void *)&hpux_acl[i].a_id);
smb_perm = hpux_perm_to_smb_perm(hpux_acl[i].a_perm);
if (sys_acl_set_permset(smb_entry, &smb_perm) != 0) {
DEBUG(10, ("invalid permset given: %d\n",
hpux_acl[i].a_perm));
goto fail;
}
result->count += 1;
}
goto done;
fail:
SAFE_FREE(result);
done:
DEBUG(10, ("hpux_acl_to_smb_acl %s\n",
((result == NULL) ? "failed" : "succeeded")));
return result;
}
static HPUX_ACL_TAG_T smb_tag_to_hpux_tag(SMB_ACL_TAG_T smb_tag)
{
HPUX_ACL_TAG_T hpux_tag = 0;
DEBUG(10, ("smb_tag_to_hpux_tag\n"));
DEBUGADD(10, (" --> got smb tag 0x%04x\n", smb_tag));
switch (smb_tag) {
case SMB_ACL_USER:
hpux_tag = USER;
break;
case SMB_ACL_USER_OBJ:
hpux_tag = USER_OBJ;
break;
case SMB_ACL_GROUP:
hpux_tag = GROUP;
break;
case SMB_ACL_GROUP_OBJ:
hpux_tag = GROUP_OBJ;
break;
case SMB_ACL_OTHER:
hpux_tag = OTHER_OBJ;
break;
case SMB_ACL_MASK:
hpux_tag = CLASS_OBJ;
break;
default:
DEBUGADD(10, (" !!! unknown smb tag type 0x%04x\n", smb_tag));
break;
}
DEBUGADD(10, (" --> determined hpux tag 0x%04x\n", hpux_tag));
return hpux_tag;
}
static SMB_ACL_TAG_T hpux_tag_to_smb_tag(HPUX_ACL_TAG_T hpux_tag)
{
SMB_ACL_TAG_T smb_tag = 0;
DEBUG(10, ("hpux_tag_to_smb_tag:\n"));
DEBUGADD(10, (" --> got hpux tag 0x%04x\n", hpux_tag));
hpux_tag &= ~ACL_DEFAULT;
switch (hpux_tag) {
case USER:
smb_tag = SMB_ACL_USER;
break;
case USER_OBJ:
smb_tag = SMB_ACL_USER_OBJ;
break;
case GROUP:
smb_tag = SMB_ACL_GROUP;
break;
case GROUP_OBJ:
smb_tag = SMB_ACL_GROUP_OBJ;
break;
case OTHER_OBJ:
smb_tag = SMB_ACL_OTHER;
break;
case CLASS_OBJ:
smb_tag = SMB_ACL_MASK;
break;
default:
DEBUGADD(10, (" !!! unknown hpux tag type: 0x%04x\n",
hpux_tag));
break;
}
DEBUGADD(10, (" --> determined smb tag 0x%04x\n", smb_tag));
return smb_tag;
}
/*
* The permission bits used in the following two permission conversion
* functions are same, but the functions make us independent of the concrete
* permission data types.
*/
static SMB_ACL_PERM_T hpux_perm_to_smb_perm(const HPUX_PERM_T perm)
{
SMB_ACL_PERM_T smb_perm = 0;
smb_perm |= ((perm & SMB_ACL_READ) ? SMB_ACL_READ : 0);
smb_perm |= ((perm & SMB_ACL_WRITE) ? SMB_ACL_WRITE : 0);
smb_perm |= ((perm & SMB_ACL_EXECUTE) ? SMB_ACL_EXECUTE : 0);
return smb_perm;
}
static HPUX_PERM_T smb_perm_to_hpux_perm(const SMB_ACL_PERM_T perm)
{
HPUX_PERM_T hpux_perm = 0;
hpux_perm |= ((perm & SMB_ACL_READ) ? SMB_ACL_READ : 0);
hpux_perm |= ((perm & SMB_ACL_WRITE) ? SMB_ACL_WRITE : 0);
hpux_perm |= ((perm & SMB_ACL_EXECUTE) ? SMB_ACL_EXECUTE : 0);
return hpux_perm;
}
static BOOL hpux_acl_get_file(const char *name, HPUX_ACL_T *hpux_acl,
int *count)
{
BOOL result = False;
static HPUX_ACE_T dummy_ace;
DEBUG(10, ("hpux_acl_get_file called for file '%s'\n", name));
/*
* The original code tries some INITIAL_ACL_SIZE
* and only did the ACL_CNT call upon failure
* (for performance reasons).
* For the sake of simplicity, I skip this for now.
*
* NOTE: There is a catch here on HP-UX: acl with cmd parameter
* ACL_CNT fails with errno EINVAL when called with a NULL
* pointer as last argument. So we need to use a dummy acl
* struct here (we make it static so it does not need to be
* instantiated or malloced each time this function is
* called). Btw: the count parameter does not seem to matter...
*/
*count = acl(CONST_DISCARD(char *, name), ACL_CNT, 0, &dummy_ace);
if (*count < 0) {
DEBUG(10, ("acl ACL_CNT failed: %s\n", strerror(errno)));
goto done;
}
*hpux_acl = hpux_acl_init(*count);
if (*hpux_acl == NULL) {
DEBUG(10, ("error allocating memory for hpux acl...\n"));
goto done;
}
*count = acl(CONST_DISCARD(char *, name), ACL_GET, *count, *hpux_acl);
if (*count < 0) {
DEBUG(10, ("acl ACL_GET failed: %s\n", strerror(errno)));
goto done;
}
result = True;
done:
DEBUG(10, ("hpux_acl_get_file %s.\n",
((result == True) ? "succeeded" : "failed" )));
return result;
}
/*
* Add entries to a hpux ACL.
*
* Entries are directly added to the hpuxacl parameter.
* if memory allocation fails, this may result in hpuxacl
* being NULL. if the resulting acl is to be checked and is
* not valid, it is kept in hpuxacl but False is returned.
*
* The type of ACEs (access/default) to be added to the ACL can
* be selected via the type parameter.
* I use the SMB_ACL_TYPE_T type here. Since SMB_ACL_TYPE_ACCESS
* is defined as "0", this means that one can only add either
* access or default ACEs from the given ACL, not both at the same
* time. If it should become necessary to add all of an ACL, one
* would have to replace this parameter by another type.
*/
static BOOL hpux_add_to_acl(HPUX_ACL_T *hpux_acl, int *count,
HPUX_ACL_T add_acl, int add_count,
SMB_ACL_TYPE_T type)
{
int i;
if ((type != SMB_ACL_TYPE_ACCESS) && (type != SMB_ACL_TYPE_DEFAULT))
{
DEBUG(10, ("invalid acl type given: %d\n", type));
errno = EINVAL;
return False;
}
for (i = 0; i < add_count; i++) {
if (!_IS_OF_TYPE(add_acl[i], type)) {
continue;
}
ADD_TO_ARRAY(NULL, HPUX_ACE_T, add_acl[i],
hpux_acl, count);
if (hpux_acl == NULL) {
DEBUG(10, ("error enlarging acl.\n"));
errno = ENOMEM;
return False;
}
}
return True;
}
/*
* sort the ACL and check it for validity
*
* [original comment from lib/sysacls.c:]
*
* if it's a minimal ACL with only 4 entries then we
* need to recalculate the mask permissions to make
* sure that they are the same as the GROUP_OBJ
* permissions as required by the UnixWare acl() system call.
*
* (note: since POSIX allows minimal ACLs which only contain
* 3 entries - ie there is no mask entry - we should, in theory,
* check for this and add a mask entry if necessary - however
* we "know" that the caller of this interface always specifies
* a mask, so in practice "this never happens" (tm) - if it *does*
* happen aclsort() will fail and return an error and someone will
* have to fix it...)
*/
static BOOL hpux_acl_sort(HPUX_ACL_T hpux_acl, int count)
{
int fixmask = (count <= 4);
if (hpux_internal_aclsort(count, fixmask, hpux_acl) != 0) {
errno = EINVAL;
return False;
}
return True;
}
/*
* Helpers for hpux_internal_aclsort:
* - hpux_count_obj
* - hpux_swap_acl_entries
* - hpux_prohibited_duplicate_type
* - hpux_get_needed_class_perm
*/
/* hpux_count_obj:
* Counts the different number of objects in a given array of ACL
* structures.
* Inputs:
*
* acl_count - Count of ACLs in the array of ACL strucutres.
* aclp - Array of ACL structures.
* acl_type_count - Pointer to acl_types structure. Should already be
* allocated.
* Output:
*
* acl_type_count - This structure is filled up with counts of various
* acl types.
*/
static void hpux_count_obj(int acl_count, HPUX_ACL_T aclp, struct hpux_acl_types *acl_type_count)
{
int i;
memset(acl_type_count, 0, sizeof(struct hpux_acl_types));
for(i=0;i<acl_count;i++) {
switch(aclp[i].a_type) {
case USER:
acl_type_count->n_user++;
break;
case USER_OBJ:
acl_type_count->n_user_obj++;
break;
case DEF_USER_OBJ:
acl_type_count->n_def_user_obj++;
break;
case GROUP:
acl_type_count->n_group++;
break;
case GROUP_OBJ:
acl_type_count->n_group_obj++;
break;
case DEF_GROUP_OBJ:
acl_type_count->n_def_group_obj++;
break;
case OTHER_OBJ:
acl_type_count->n_other_obj++;
break;
case DEF_OTHER_OBJ:
acl_type_count->n_def_other_obj++;
break;
case CLASS_OBJ:
acl_type_count->n_class_obj++;
break;
case DEF_CLASS_OBJ:
acl_type_count->n_def_class_obj++;
break;
case DEF_USER:
acl_type_count->n_def_user++;
break;
case DEF_GROUP:
acl_type_count->n_def_group++;
break;
default:
acl_type_count->n_illegal_obj++;
break;
}
}
}
/* hpux_swap_acl_entries: Swaps two ACL entries.
*
* Inputs: aclp0, aclp1 - ACL entries to be swapped.
*/
static void hpux_swap_acl_entries(HPUX_ACE_T *aclp0, HPUX_ACE_T *aclp1)
{
HPUX_ACE_T temp_acl;
temp_acl.a_type = aclp0->a_type;
temp_acl.a_id = aclp0->a_id;
temp_acl.a_perm = aclp0->a_perm;
aclp0->a_type = aclp1->a_type;
aclp0->a_id = aclp1->a_id;
aclp0->a_perm = aclp1->a_perm;
aclp1->a_type = temp_acl.a_type;
aclp1->a_id = temp_acl.a_id;
aclp1->a_perm = temp_acl.a_perm;
}
/* hpux_prohibited_duplicate_type
* Identifies if given ACL type can have duplicate entries or
* not.
*
* Inputs: acl_type - ACL Type.
*
* Outputs:
*
* Return..
*
* True - If the ACL type matches any of the prohibited types.
* False - If the ACL type doesn't match any of the prohibited types.
*/
static BOOL hpux_prohibited_duplicate_type(int acl_type)
{
switch(acl_type) {
case USER:
case GROUP:
case DEF_USER:
case DEF_GROUP:
return True;
default:
return False;
}
}
/* hpux_get_needed_class_perm
* Returns the permissions of a ACL structure only if the ACL
* type matches one of the pre-determined types for computing
* CLASS_OBJ permissions.
*
* Inputs: aclp - Pointer to ACL structure.
*/
static int hpux_get_needed_class_perm(struct acl *aclp)
{
switch(aclp->a_type) {
case USER:
case GROUP_OBJ:
case GROUP:
case DEF_USER_OBJ:
case DEF_USER:
case DEF_GROUP_OBJ:
case DEF_GROUP:
case DEF_CLASS_OBJ:
case DEF_OTHER_OBJ:
return aclp->a_perm;
default:
return 0;
}
}
/* hpux_internal_aclsort: aclsort for HPUX.
*
* -> The aclsort() system call is availabe on the latest HPUX General
* -> Patch Bundles. So for HPUX, we developed our version of aclsort
* -> function. Because, we don't want to update to a new
* -> HPUX GR bundle just for aclsort() call.
*
* aclsort sorts the array of ACL structures as per the description in
* aclsort man page. Refer to aclsort man page for more details
*
* Inputs:
*
* acl_count - Count of ACLs in the array of ACL structures.
* calclass - If this is not zero, then we compute the CLASS_OBJ
* permissions.
* aclp - Array of ACL structures.
*
* Outputs:
*
* aclp - Sorted array of ACL structures.
*
* Outputs:
*
* Returns 0 for success -1 for failure. Prints a message to the Samba
* debug log in case of failure.
*/
static int hpux_internal_aclsort(int acl_count, int calclass, HPUX_ACL_T aclp)
{
struct hpux_acl_types acl_obj_count;
int n_class_obj_perm = 0;
int i, j;
DEBUG(10,("Entering hpux_internal_aclsort. (calclass = %d)\n", calclass));
if (hpux_aclsort_call_present()) {
DEBUG(10, ("calling hpux aclsort\n"));
return aclsort(acl_count, calclass, aclp);
}
DEBUG(10, ("using internal aclsort\n"));
if(!acl_count) {
DEBUG(10,("Zero acl count passed. Returning Success\n"));
return 0;
}
if(aclp == NULL) {
DEBUG(0,("Null ACL pointer in hpux_acl_sort. Returning Failure. \n"));
return -1;
}
/* Count different types of ACLs in the ACLs array */
hpux_count_obj(acl_count, aclp, &acl_obj_count);
/* There should be only one entry each of type USER_OBJ, GROUP_OBJ,
* CLASS_OBJ and OTHER_OBJ
*/
if ( (acl_obj_count.n_user_obj != 1) ||
(acl_obj_count.n_group_obj != 1) ||
(acl_obj_count.n_class_obj != 1) ||
(acl_obj_count.n_other_obj != 1) )
{
DEBUG(0,("hpux_internal_aclsort: More than one entry or no entries for \
USER OBJ or GROUP_OBJ or OTHER_OBJ or CLASS_OBJ\n"));
return -1;
}
/* If any of the default objects are present, there should be only
* one of them each.
*/
if ( (acl_obj_count.n_def_user_obj > 1) ||
(acl_obj_count.n_def_group_obj > 1) ||
(acl_obj_count.n_def_other_obj > 1) ||
(acl_obj_count.n_def_class_obj > 1) )
{
DEBUG(0,("hpux_internal_aclsort: More than one entry for DEF_CLASS_OBJ \
or DEF_USER_OBJ or DEF_GROUP_OBJ or DEF_OTHER_OBJ\n"));
return -1;
}
/* We now have proper number of OBJ and DEF_OBJ entries. Now sort the acl
* structures.
*
* Sorting crieteria - First sort by ACL type. If there are multiple entries of
* same ACL type, sort by ACL id.
*
* I am using the trival kind of sorting method here because, performance isn't
* really effected by the ACLs feature. More over there aren't going to be more
* than 17 entries on HPUX.
*/
for(i=0; i<acl_count;i++) {
for (j=i+1; j<acl_count; j++) {
if( aclp[i].a_type > aclp[j].a_type ) {
/* ACL entries out of order, swap them */
hpux_swap_acl_entries((aclp+i), (aclp+j));
} else if ( aclp[i].a_type == aclp[j].a_type ) {
/* ACL entries of same type, sort by id */
if(aclp[i].a_id > aclp[j].a_id) {
hpux_swap_acl_entries((aclp+i), (aclp+j));
} else if (aclp[i].a_id == aclp[j].a_id) {
/* We have a duplicate entry. */
if(hpux_prohibited_duplicate_type(aclp[i].a_type)) {
DEBUG(0, ("hpux_internal_aclsort: Duplicate entry: Type(hex): %x Id: %d\n",
aclp[i].a_type, aclp[i].a_id));
return -1;
}
}
}
}
}
/* set the class obj permissions to the computed one. */
if(calclass) {
int n_class_obj_index = -1;
for(i=0;i<acl_count;i++) {
n_class_obj_perm |= hpux_get_needed_class_perm((aclp+i));
if(aclp[i].a_type == CLASS_OBJ)
n_class_obj_index = i;
}
aclp[n_class_obj_index].a_perm = n_class_obj_perm;
}
return 0;
}
/*
* hpux_acl_call_present:
*
* This checks if the POSIX ACL system call is defined
* which basically corresponds to whether JFS 3.3 or
* higher is installed. If acl() was called when it
* isn't defined, it causes the process to core dump
* so it is important to check this and avoid acl()
* calls if it isn't there.
*/
static BOOL hpux_acl_call_present(void)
{
shl_t handle = NULL;
void *value;
int ret_val=0;
static BOOL already_checked = False;
if(already_checked)
return True;
errno = 0;
ret_val = shl_findsym(&handle, "acl", TYPE_PROCEDURE, &value);
if(ret_val != 0) {
DEBUG(5, ("hpux_acl_call_present: shl_findsym() returned %d, errno = %d, error %s\n",
ret_val, errno, strerror(errno)));
DEBUG(5,("hpux_acl_call_present: acl() system call is not present. Check if you have JFS 3.3 and above?\n"));
errno = ENOSYS;
return False;
}
DEBUG(10,("hpux_acl_call_present: acl() system call is present. We have JFS 3.3 or above \n"));
already_checked = True;
return True;
}
/*
* runtime check for presence of aclsort library call.
* same code as for acl call. if there are more of these,
* a dispatcher function could be handy...
*/
static BOOL hpux_aclsort_call_present(void)
{
shl_t handle = NULL;
void *value;
int ret_val = 0;
static BOOL already_checked = False;
if (already_checked) {
return True;
}
errno = 0;
ret_val = shl_findsym(&handle, "aclsort", TYPE_PROCEDURE, &value);
if (ret_val != 0) {
DEBUG(5, ("hpux_aclsort_call_present: shl_findsym "
"returned %d, errno = %d, error %s",
ret_val, errno, strerror(errno)));
DEBUG(5, ("hpux_aclsort_call_present: "
"aclsort() function not available.\n"));
return False;
}
DEBUG(10,("hpux_aclsort_call_present: aclsort() function present.\n"));
already_checked = True;
return True;
}
#if 0
/*
* acl check function:
* unused at the moment but could be used to get more
* concrete error messages for debugging...
* (acl sort just says that the acl is invalid...)
*/
static BOOL hpux_acl_check(HPUX_ACL_T hpux_acl, int count)
{
int check_rc;
int check_which;
check_rc = aclcheck(hpux_acl, count, &check_which);
if (check_rc != 0) {
DEBUG(10, ("acl is not valid:\n"));
DEBUGADD(10, (" - return code: %d\n", check_rc));
DEBUGADD(10, (" - which: %d\n", check_which));
if (check_which != -1) {
DEBUGADD(10, (" - invalid entry:\n"));
DEBUGADD(10, (" * type: %d:\n",
hpux_acl[check_which].a_type));
DEBUGADD(10, (" * id: %d\n",
hpux_acl[check_which].a_id));
DEBUGADD(10, (" * perm: 0o%o\n",
hpux_acl[check_which].a_perm));
}
return False;
}
return True;
}
#endif
/* VFS operations structure */
static vfs_op_tuple hpuxacl_op_tuples[] = {
/* Disk operations */
{SMB_VFS_OP(hpuxacl_sys_acl_get_file),
SMB_VFS_OP_SYS_ACL_GET_FILE,
SMB_VFS_LAYER_TRANSPARENT},
{SMB_VFS_OP(hpuxacl_sys_acl_get_fd),
SMB_VFS_OP_SYS_ACL_GET_FD,
SMB_VFS_LAYER_TRANSPARENT},
{SMB_VFS_OP(hpuxacl_sys_acl_set_file),
SMB_VFS_OP_SYS_ACL_SET_FILE,
SMB_VFS_LAYER_TRANSPARENT},
{SMB_VFS_OP(hpuxacl_sys_acl_set_fd),
SMB_VFS_OP_SYS_ACL_SET_FD,
SMB_VFS_LAYER_TRANSPARENT},
{SMB_VFS_OP(hpuxacl_sys_acl_delete_def_file),
SMB_VFS_OP_SYS_ACL_DELETE_DEF_FILE,
SMB_VFS_LAYER_TRANSPARENT},
{SMB_VFS_OP(NULL),
SMB_VFS_OP_NOOP,
SMB_VFS_LAYER_NOOP}
};
NTSTATUS vfs_hpuxacl_init(void)
{
return smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "hpuxacl",
hpuxacl_op_tuples);
}
/* ENTE */
| gpl-2.0 |
hejiann/android_kernel_huawei_u8860 | sound/soc/msm/msm-dai-q6.c | 27 | 29381 | /* Copyright (c) 2011-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/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mfd/wcd9310/core.h>
#include <linux/bitops.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/apr_audio.h>
#include <sound/q6afe.h>
#include <sound/msm-dai-q6.h>
#include <mach/clk.h>
enum {
STATUS_PORT_STARTED, /* track if AFE port has started */
STATUS_MAX
};
struct msm_dai_q6_dai_data {
DECLARE_BITMAP(status_mask, STATUS_MAX);
u32 rate;
u32 channels;
union afe_port_config port_config;
};
static struct clk *pcm_clk;
static u8 num_of_bits_set(u8 sd_line_mask)
{
u8 num_bits_set = 0;
while (sd_line_mask) {
num_bits_set++;
sd_line_mask = sd_line_mask & (sd_line_mask - 1);
}
return num_bits_set;
}
static int msm_dai_q6_cdc_hw_params(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai, int stream)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
dai_data->channels = params_channels(params);
switch (dai_data->channels) {
case 2:
dai_data->port_config.mi2s.channel = MSM_AFE_STEREO;
break;
case 1:
dai_data->port_config.mi2s.channel = MSM_AFE_MONO;
break;
default:
return -EINVAL;
break;
}
dai_data->rate = params_rate(params);
dev_dbg(dai->dev, " channel %d sample rate %d entered\n",
dai_data->channels, dai_data->rate);
/* Q6 only supports 16 as now */
dai_data->port_config.mi2s.bitwidth = 16;
dai_data->port_config.mi2s.line = 1;
return 0;
}
static int msm_dai_q6_mi2s_hw_params(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai, int stream)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
struct msm_mi2s_data *mi2s_pdata =
(struct msm_mi2s_data *) dai->dev->platform_data;
dai_data->channels = params_channels(params);
if (num_of_bits_set(mi2s_pdata->sd_lines) == 1) {
switch (dai_data->channels) {
case 2:
dai_data->port_config.mi2s.channel = MSM_AFE_STEREO;
break;
case 1:
dai_data->port_config.mi2s.channel = MSM_AFE_MONO;
break;
default:
pr_warn("greater than stereo has not been validated");
break;
}
}
/* Q6 only supports 16 as now */
dai_data->port_config.mi2s.bitwidth = 16;
return 0;
}
static int msm_dai_q6_mi2s_platform_data_validation(
struct snd_soc_dai *dai)
{
u8 num_of_sd_lines;
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
struct msm_mi2s_data *mi2s_pdata =
(struct msm_mi2s_data *)dai->dev->platform_data;
struct snd_soc_dai_driver *dai_driver =
(struct snd_soc_dai_driver *)dai->driver;
num_of_sd_lines = num_of_bits_set(mi2s_pdata->sd_lines);
switch (num_of_sd_lines) {
case 1:
switch (mi2s_pdata->sd_lines) {
case MSM_MI2S_SD0:
dai_data->port_config.mi2s.line = AFE_I2S_SD0;
break;
case MSM_MI2S_SD1:
dai_data->port_config.mi2s.line = AFE_I2S_SD1;
break;
case MSM_MI2S_SD2:
dai_data->port_config.mi2s.line = AFE_I2S_SD2;
break;
case MSM_MI2S_SD3:
dai_data->port_config.mi2s.line = AFE_I2S_SD3;
break;
default:
pr_err("%s: invalid SD line\n",
__func__);
goto error_invalid_data;
}
break;
case 2:
switch (mi2s_pdata->sd_lines) {
case MSM_MI2S_SD0 | MSM_MI2S_SD1:
dai_data->port_config.mi2s.line = AFE_I2S_QUAD01;
break;
case MSM_MI2S_SD2 | MSM_MI2S_SD3:
dai_data->port_config.mi2s.line = AFE_I2S_QUAD23;
break;
default:
pr_err("%s: invalid SD line\n",
__func__);
goto error_invalid_data;
}
break;
case 3:
switch (mi2s_pdata->sd_lines) {
case MSM_MI2S_SD0 | MSM_MI2S_SD1 | MSM_MI2S_SD2:
dai_data->port_config.mi2s.line = AFE_I2S_6CHS;
break;
default:
pr_err("%s: invalid SD lines\n",
__func__);
goto error_invalid_data;
}
break;
case 4:
switch (mi2s_pdata->sd_lines) {
case MSM_MI2S_SD0 | MSM_MI2S_SD1 | MSM_MI2S_SD2 | MSM_MI2S_SD3:
dai_data->port_config.mi2s.line = AFE_I2S_8CHS;
break;
default:
pr_err("%s: invalid SD lines\n",
__func__);
goto error_invalid_data;
}
break;
default:
pr_err("%s: invalid SD lines\n", __func__);
goto error_invalid_data;
}
if (mi2s_pdata->capability == MSM_MI2S_CAP_RX)
dai_driver->playback.channels_max = num_of_sd_lines << 1;
return 0;
error_invalid_data:
return -EINVAL;
}
static int msm_dai_q6_cdc_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
dai_data->port_config.mi2s.ws = 1; /* CPU is master */
break;
case SND_SOC_DAIFMT_CBM_CFM:
dai_data->port_config.mi2s.ws = 0; /* CPU is slave */
break;
default:
return -EINVAL;
}
return 0;
}
static int msm_dai_q6_slim_bus_hw_params(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai, int stream)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
u8 pgd_la, inf_la;
u16 *slave_port_mapping;
memset(dai_data->port_config.slimbus.slave_port_mapping, 0,
sizeof(dai_data->port_config.slimbus.slave_port_mapping));
dai_data->channels = params_channels(params);
slave_port_mapping = dai_data->port_config.slimbus.slave_port_mapping;
switch (dai_data->channels) {
case 4:
if (dai->id == SLIMBUS_0_TX) {
slave_port_mapping[0] = 7;
slave_port_mapping[1] = 8;
slave_port_mapping[2] = 9;
slave_port_mapping[3] = 10;
} else {
return -EINVAL;
}
break;
case 3:
if (dai->id == SLIMBUS_0_TX) {
slave_port_mapping[0] = 7;
slave_port_mapping[1] = 8;
slave_port_mapping[2] = 9;
} else {
return -EINVAL;
}
break;
case 2:
if (dai->id == SLIMBUS_0_RX) {
slave_port_mapping[0] = 1;
slave_port_mapping[1] = 2;
} else {
slave_port_mapping[0] = 7;
slave_port_mapping[1] = 8;
}
break;
case 1:
if (dai->id == SLIMBUS_0_RX)
slave_port_mapping[0] = 1;
else
slave_port_mapping[0] = 7;
break;
default:
return -EINVAL;
break;
}
dai_data->rate = params_rate(params);
tabla_get_logical_addresses(&pgd_la, &inf_la);
dai_data->port_config.slimbus.slimbus_dev_id = AFE_SLIMBUS_DEVICE_1;
dai_data->port_config.slimbus.slave_dev_pgd_la = pgd_la;
dai_data->port_config.slimbus.slave_dev_intfdev_la = inf_la;
/* Q6 only supports 16 as now */
dai_data->port_config.slimbus.bit_width = 16;
dai_data->port_config.slimbus.data_format = 0;
dai_data->port_config.slimbus.num_channels = dai_data->channels;
dai_data->port_config.slimbus.reserved = 0;
dev_dbg(dai->dev, "slimbus_dev_id %hu slave_dev_pgd_la 0x%hx\n"
"slave_dev_intfdev_la 0x%hx bit_width %hu data_format %hu\n"
"num_channel %hu slave_port_mapping[0] %hu\n"
"slave_port_mapping[1] %hu slave_port_mapping[2] %hu\n"
"sample_rate %d\n",
dai_data->port_config.slimbus.slimbus_dev_id,
dai_data->port_config.slimbus.slave_dev_pgd_la,
dai_data->port_config.slimbus.slave_dev_intfdev_la,
dai_data->port_config.slimbus.bit_width,
dai_data->port_config.slimbus.data_format,
dai_data->port_config.slimbus.num_channels,
dai_data->port_config.slimbus.slave_port_mapping[0],
dai_data->port_config.slimbus.slave_port_mapping[1],
dai_data->port_config.slimbus.slave_port_mapping[2],
dai_data->rate);
return 0;
}
static int msm_dai_q6_bt_fm_hw_params(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai, int stream)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
dai_data->channels = params_channels(params);
dai_data->rate = params_rate(params);
dev_dbg(dai->dev, "channels %d sample rate %d entered\n",
dai_data->channels, dai_data->rate);
memset(&dai_data->port_config, 0, sizeof(dai_data->port_config));
return 0;
}
static int msm_dai_q6_auxpcm_hw_params(
struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
struct msm_dai_auxpcm_pdata *auxpcm_pdata =
(struct msm_dai_auxpcm_pdata *) dai->dev->platform_data;
if (params_channels(params) != 1) {
dev_err(dai->dev, "AUX PCM supports only mono stream\n");
return -EINVAL;
}
dai_data->channels = params_channels(params);
if (params_rate(params) != 8000) {
dev_err(dai->dev, "AUX PCM supports only 8KHz sampling rate\n");
return -EINVAL;
}
dai_data->rate = params_rate(params);
dai_data->port_config.pcm.mode = auxpcm_pdata->mode;
dai_data->port_config.pcm.sync = auxpcm_pdata->sync;
dai_data->port_config.pcm.frame = auxpcm_pdata->frame;
dai_data->port_config.pcm.quant = auxpcm_pdata->quant;
dai_data->port_config.pcm.slot = auxpcm_pdata->slot;
dai_data->port_config.pcm.data = auxpcm_pdata->data;
return 0;
}
static int get_frame_size(u16 rate, u16 ch)
{
if (rate == 8000) {
if (ch == 1)
return 128 * 2;
else
return 128 * 2 * 2;
} else if (rate == 16000) {
if (ch == 1)
return 128 * 2 * 2;
else
return 128 * 2 * 4;
} else if (rate == 48000) {
if (ch == 1)
return 128 * 2 * 6;
else
return 128 * 2 * 12;
} else
return 128 * 2 * 12;
}
static int msm_dai_q6_afe_rtproxy_hw_params(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
dai_data->rate = params_rate(params);
dai_data->port_config.rtproxy.num_ch =
params_channels(params);
pr_debug("channel %d entered,dai_id: %d,rate: %d\n",
dai_data->port_config.rtproxy.num_ch, dai->id, dai_data->rate);
dai_data->port_config.rtproxy.bitwidth = 16; /* Q6 only supports 16 */
dai_data->port_config.rtproxy.interleaved = 1;
dai_data->port_config.rtproxy.frame_sz = get_frame_size(dai_data->rate,
dai_data->port_config.rtproxy.num_ch);
dai_data->port_config.rtproxy.jitter =
dai_data->port_config.rtproxy.frame_sz/2;
dai_data->port_config.rtproxy.lw_mark = 0;
dai_data->port_config.rtproxy.hw_mark = 0;
dai_data->port_config.rtproxy.rsvd = 0;
return 0;
}
/* Current implementation assumes hw_param is called once
* This may not be the case but what to do when ADM and AFE
* port are already opened and parameter changes
*/
static int msm_dai_q6_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
int rc = 0;
switch (dai->id) {
case PRIMARY_I2S_TX:
case PRIMARY_I2S_RX:
case SECONDARY_I2S_RX:
rc = msm_dai_q6_cdc_hw_params(params, dai, substream->stream);
break;
case MI2S_RX:
rc = msm_dai_q6_mi2s_hw_params(params, dai, substream->stream);
break;
case SLIMBUS_0_RX:
case SLIMBUS_0_TX:
rc = msm_dai_q6_slim_bus_hw_params(params, dai,
substream->stream);
break;
case INT_BT_SCO_RX:
case INT_BT_SCO_TX:
case INT_FM_RX:
case INT_FM_TX:
rc = msm_dai_q6_bt_fm_hw_params(params, dai, substream->stream);
break;
case RT_PROXY_DAI_001_TX:
case RT_PROXY_DAI_001_RX:
case RT_PROXY_DAI_002_TX:
case RT_PROXY_DAI_002_RX:
rc = msm_dai_q6_afe_rtproxy_hw_params(params, dai);
break;
case VOICE_PLAYBACK_TX:
case VOICE_RECORD_RX:
case VOICE_RECORD_TX:
rc = 0;
break;
default:
dev_err(dai->dev, "invalid AFE port ID\n");
rc = -EINVAL;
break;
}
return rc;
}
static void msm_dai_q6_auxpcm_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
int rc = 0;
pr_debug("%s: dai->id = %d", __func__, dai->id);
if (test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
clk_disable(pcm_clk);
rc = afe_close(dai->id); /* can block */
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to close AFE port\n");
pr_debug("%s: dai_data->status_mask = %ld\n", __func__,
*dai_data->status_mask);
clear_bit(STATUS_PORT_STARTED, dai_data->status_mask);
rc = afe_close(PCM_TX);
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to close AUX PCM TX port\n");
}
}
static void msm_dai_q6_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
int rc = 0;
if (test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
switch (dai->id) {
case VOICE_PLAYBACK_TX:
case VOICE_RECORD_TX:
case VOICE_RECORD_RX:
pr_debug("%s, stop pseudo port:%d\n",
__func__, dai->id);
rc = afe_stop_pseudo_port(dai->id);
break;
default:
rc = afe_close(dai->id); /* can block */
break;
}
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to close AFE port\n");
pr_debug("%s: dai_data->status_mask = %ld\n", __func__,
*dai_data->status_mask);
clear_bit(STATUS_PORT_STARTED, dai_data->status_mask);
}
}
static int msm_dai_q6_auxpcm_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
int rc = 0;
struct msm_dai_auxpcm_pdata *auxpcm_pdata =
(struct msm_dai_auxpcm_pdata *) dai->dev->platform_data;
if (!test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
rc = afe_q6_interface_prepare();
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to open AFE APR\n");
rc = afe_q6_interface_prepare();
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to open AFE APR\n");
pr_debug("%s:dai->id:%d dai_data->status_mask = %ld\n",
__func__, dai->id, *dai_data->status_mask);
/*
* For AUX PCM Interface the below sequence of clk
* settings and afe_open is a strict requirement.
*
* Also using afe_open instead of afe_port_start_nowait
* to make sure the port is open before deasserting the
* clock line. This is required because pcm register is
* not written before clock deassert. Hence the hw does
* not get updated with new setting if the below clock
* assert/deasset and afe_open sequence is not followed.
*/
clk_reset(pcm_clk, CLK_RESET_ASSERT);
afe_open(dai->id, &dai_data->port_config,
dai_data->rate);
set_bit(STATUS_PORT_STARTED,
dai_data->status_mask);
afe_open(PCM_TX, &dai_data->port_config, dai_data->rate);
rc = clk_set_rate(pcm_clk, auxpcm_pdata->pcm_clk_rate);
if (rc < 0) {
pr_err("%s: clk_set_rate failed\n", __func__);
return rc;
}
clk_enable(pcm_clk);
clk_reset(pcm_clk, CLK_RESET_DEASSERT);
}
return rc;
}
static int msm_dai_q6_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
int rc = 0;
if (!test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
/* PORT START should be set if prepare called in active state */
rc = afe_q6_interface_prepare();
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to open AFE APR\n");
}
return rc;
}
static int msm_dai_q6_auxpcm_trigger(struct snd_pcm_substream *substream,
int cmd, struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
int rc = 0;
pr_debug("%s:port:%d cmd:%d dai_data->status_mask = %ld",
__func__, dai->id, cmd, *dai_data->status_mask);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
/* afe_open will be called from prepare */
return 0;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
if (test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
clk_disable(pcm_clk);
afe_port_stop_nowait(dai->id);
clear_bit(STATUS_PORT_STARTED,
dai_data->status_mask);
afe_port_stop_nowait(PCM_TX);
}
break;
default:
rc = -EINVAL;
}
return rc;
}
static int msm_dai_q6_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);
int rc = 0;
/* Start/stop port without waiting for Q6 AFE response. Need to have
* native q6 AFE driver propagates AFE response in order to handle
* port start/stop command error properly if error does arise.
*/
pr_debug("%s:port:%d cmd:%d dai_data->status_mask = %ld",
__func__, dai->id, cmd, *dai_data->status_mask);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
if (!test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
switch (dai->id) {
case VOICE_PLAYBACK_TX:
case VOICE_RECORD_TX:
case VOICE_RECORD_RX:
afe_pseudo_port_start_nowait(dai->id);
break;
default:
afe_port_start_nowait(dai->id,
&dai_data->port_config, dai_data->rate);
break;
}
set_bit(STATUS_PORT_STARTED,
dai_data->status_mask);
}
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
if (test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
switch (dai->id) {
case VOICE_PLAYBACK_TX:
case VOICE_RECORD_TX:
case VOICE_RECORD_RX:
afe_pseudo_port_stop_nowait(dai->id);
break;
default:
afe_port_stop_nowait(dai->id);
break;
}
clear_bit(STATUS_PORT_STARTED,
dai_data->status_mask);
}
break;
default:
rc = -EINVAL;
}
return rc;
}
static int msm_dai_q6_dai_auxpcm_probe(struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data;
int rc = 0;
struct msm_dai_auxpcm_pdata *auxpcm_pdata =
(struct msm_dai_auxpcm_pdata *) dai->dev->platform_data;
dai_data = kzalloc(sizeof(struct msm_dai_q6_dai_data),
GFP_KERNEL);
if (!dai_data) {
dev_err(dai->dev, "DAI-%d: fail to allocate dai data\n",
dai->id);
rc = -ENOMEM;
} else
dev_set_drvdata(dai->dev, dai_data);
/*
* The clk name for AUX PCM operation is passed as platform
* data to the cpu driver, since cpu drive is unaware of any
* boarc specific configuration.
*/
pcm_clk = clk_get(NULL, auxpcm_pdata->clk);
if (IS_ERR(pcm_clk)) {
pr_err("%s: could not get pcm_clk\n", __func__);
return PTR_ERR(pcm_clk);
kfree(dai_data);
}
return rc;
}
static int msm_dai_q6_dai_auxpcm_remove(struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data;
int rc;
dai_data = dev_get_drvdata(dai->dev);
/* If AFE port is still up, close it */
if (test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
rc = afe_close(dai->id); /* can block */
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to close AFE port\n");
clear_bit(STATUS_PORT_STARTED, dai_data->status_mask);
rc = afe_close(PCM_TX);
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to close AUX PCM TX port\n");
}
kfree(dai_data);
snd_soc_unregister_dai(dai->dev);
return 0;
}
static int msm_dai_q6_dai_mi2s_probe(struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data;
int rc = 0;
dai_data = kzalloc(sizeof(struct msm_dai_q6_dai_data),
GFP_KERNEL);
if (!dai_data) {
dev_err(dai->dev, "DAI-%d: fail to allocate dai data\n",
dai->id);
rc = -ENOMEM;
goto rtn;
} else
dev_set_drvdata(dai->dev, dai_data);
rc = msm_dai_q6_mi2s_platform_data_validation(dai);
if (rc != 0) {
pr_err("%s: The msm_dai_q6_mi2s_platform_data_validation failed\n",
__func__);
kfree(dai_data);
}
rtn:
return rc;
}
static int msm_dai_q6_dai_probe(struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data;
int rc = 0;
dai_data = kzalloc(sizeof(struct msm_dai_q6_dai_data),
GFP_KERNEL);
if (!dai_data) {
dev_err(dai->dev, "DAI-%d: fail to allocate dai data\n",
dai->id);
rc = -ENOMEM;
} else
dev_set_drvdata(dai->dev, dai_data);
return rc;
}
static int msm_dai_q6_dai_remove(struct snd_soc_dai *dai)
{
struct msm_dai_q6_dai_data *dai_data;
int rc;
dai_data = dev_get_drvdata(dai->dev);
/* If AFE port is still up, close it */
if (test_bit(STATUS_PORT_STARTED, dai_data->status_mask)) {
switch (dai->id) {
case VOICE_PLAYBACK_TX:
case VOICE_RECORD_TX:
case VOICE_RECORD_RX:
pr_debug("%s, stop pseudo port:%d\n",
__func__, dai->id);
rc = afe_stop_pseudo_port(dai->id);
break;
default:
rc = afe_close(dai->id); /* can block */
}
if (IS_ERR_VALUE(rc))
dev_err(dai->dev, "fail to close AFE port\n");
clear_bit(STATUS_PORT_STARTED, dai_data->status_mask);
}
kfree(dai_data);
snd_soc_unregister_dai(dai->dev);
return 0;
}
static int msm_dai_q6_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
int rc = 0;
dev_dbg(dai->dev, "enter %s, id = %d\n", __func__, dai->id);
switch (dai->id) {
case PRIMARY_I2S_TX:
case PRIMARY_I2S_RX:
case MI2S_RX:
case SECONDARY_I2S_RX:
rc = msm_dai_q6_cdc_set_fmt(dai, fmt);
break;
default:
dev_err(dai->dev, "invalid cpu_dai set_fmt\n");
rc = -EINVAL;
break;
}
return rc;
}
static struct snd_soc_dai_ops msm_dai_q6_ops = {
.prepare = msm_dai_q6_prepare,
.trigger = msm_dai_q6_trigger,
.hw_params = msm_dai_q6_hw_params,
.shutdown = msm_dai_q6_shutdown,
.set_fmt = msm_dai_q6_set_fmt,
};
static struct snd_soc_dai_ops msm_dai_q6_auxpcm_ops = {
.prepare = msm_dai_q6_auxpcm_prepare,
.trigger = msm_dai_q6_auxpcm_trigger,
.hw_params = msm_dai_q6_auxpcm_hw_params,
.shutdown = msm_dai_q6_auxpcm_shutdown,
};
static struct snd_soc_dai_driver msm_dai_q6_i2s_rx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 4,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_i2s_tx_dai = {
.capture = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_afe_rx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_afe_tx_dai = {
.capture = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_voice_playback_tx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_max = 48000,
.rate_min = 8000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_slimbus_rx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_slimbus_tx_dai = {
.capture = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_incall_record_dai = {
.capture = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_bt_sco_rx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 1,
.rate_max = 16000,
.rate_min = 8000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_bt_sco_tx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 1,
.rate_max = 16000,
.rate_min = 8000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_fm_rx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 2,
.channels_max = 2,
.rate_max = 48000,
.rate_min = 8000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_fm_tx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 2,
.channels_max = 2,
.rate_max = 48000,
.rate_min = 8000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_aux_pcm_rx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_8000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 1,
.rate_max = 8000,
.rate_min = 8000,
},
.ops = &msm_dai_q6_auxpcm_ops,
.probe = msm_dai_q6_dai_auxpcm_probe,
.remove = msm_dai_q6_dai_auxpcm_remove,
};
static struct snd_soc_dai_driver msm_dai_q6_aux_pcm_tx_dai = {
.capture = {
.rates = SNDRV_PCM_RATE_8000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 1,
.rate_max = 8000,
.rate_min = 8000,
},
};
static struct snd_soc_dai_driver msm_dai_q6_mi2s_rx_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_q6_ops,
.probe = msm_dai_q6_dai_mi2s_probe,
.remove = msm_dai_q6_dai_probe,
};
/* To do: change to register DAIs as batch */
static __devinit int msm_dai_q6_dev_probe(struct platform_device *pdev)
{
int rc = 0;
dev_dbg(&pdev->dev, "dev name %s\n", dev_name(&pdev->dev));
switch (pdev->id) {
case PRIMARY_I2S_RX:
case SECONDARY_I2S_RX:
rc = snd_soc_register_dai(&pdev->dev, &msm_dai_q6_i2s_rx_dai);
break;
case PRIMARY_I2S_TX:
rc = snd_soc_register_dai(&pdev->dev, &msm_dai_q6_i2s_tx_dai);
break;
case PCM_RX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_aux_pcm_rx_dai);
break;
case PCM_TX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_aux_pcm_tx_dai);
break;
case MI2S_RX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_mi2s_rx_dai);
break;
case SLIMBUS_0_RX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_slimbus_rx_dai);
break;
case SLIMBUS_0_TX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_slimbus_tx_dai);
case INT_BT_SCO_RX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_bt_sco_rx_dai);
break;
case INT_BT_SCO_TX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_bt_sco_tx_dai);
break;
case INT_FM_RX:
rc = snd_soc_register_dai(&pdev->dev, &msm_dai_q6_fm_rx_dai);
break;
case INT_FM_TX:
rc = snd_soc_register_dai(&pdev->dev, &msm_dai_q6_fm_tx_dai);
break;
case RT_PROXY_DAI_001_RX:
case RT_PROXY_DAI_002_RX:
rc = snd_soc_register_dai(&pdev->dev, &msm_dai_q6_afe_rx_dai);
break;
case RT_PROXY_DAI_001_TX:
case RT_PROXY_DAI_002_TX:
rc = snd_soc_register_dai(&pdev->dev, &msm_dai_q6_afe_tx_dai);
break;
case VOICE_PLAYBACK_TX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_voice_playback_tx_dai);
break;
case VOICE_RECORD_RX:
case VOICE_RECORD_TX:
rc = snd_soc_register_dai(&pdev->dev,
&msm_dai_q6_incall_record_dai);
break;
default:
rc = -ENODEV;
break;
}
return rc;
}
static __devexit int msm_dai_q6_dev_remove(struct platform_device *pdev)
{
snd_soc_unregister_dai(&pdev->dev);
return 0;
}
static struct platform_driver msm_dai_q6_driver = {
.probe = msm_dai_q6_dev_probe,
.remove = msm_dai_q6_dev_remove,
.driver = {
.name = "msm-dai-q6",
.owner = THIS_MODULE,
},
};
static int __init msm_dai_q6_init(void)
{
return platform_driver_register(&msm_dai_q6_driver);
}
module_init(msm_dai_q6_init);
static void __exit msm_dai_q6_exit(void)
{
platform_driver_unregister(&msm_dai_q6_driver);
}
module_exit(msm_dai_q6_exit);
/* Module information */
MODULE_DESCRIPTION("MSM DSP DAI driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
mv0/tip | drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 27 | 85415 | /*******************************************************************************
This is the driver for the ST MAC 10/100/1000 on-chip Ethernet controllers.
ST Ethernet IPs are built around a Synopsys IP Core.
Copyright(C) 2007-2011 STMicroelectronics Ltd
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Author: Giuseppe Cavallaro <peppe.cavallaro@st.com>
Documentation available at:
http://www.stlinux.com
Support available at:
https://bugzilla.stlinux.com/
*******************************************************************************/
#include <linux/clk.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <linux/if_ether.h>
#include <linux/crc32.h>
#include <linux/mii.h>
#include <linux/if.h>
#include <linux/if_vlan.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/prefetch.h>
#include <linux/pinctrl/consumer.h>
#ifdef CONFIG_STMMAC_DEBUG_FS
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#endif /* CONFIG_STMMAC_DEBUG_FS */
#include <linux/net_tstamp.h>
#include "stmmac_ptp.h"
#include "stmmac.h"
#include <linux/reset.h>
#define STMMAC_ALIGN(x) L1_CACHE_ALIGN(x)
/* Module parameters */
#define TX_TIMEO 5000
static int watchdog = TX_TIMEO;
module_param(watchdog, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(watchdog, "Transmit timeout in milliseconds (default 5s)");
static int debug = -1;
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Message Level (-1: default, 0: no output, 16: all)");
static int phyaddr = -1;
module_param(phyaddr, int, S_IRUGO);
MODULE_PARM_DESC(phyaddr, "Physical device address");
#define DMA_TX_SIZE 256
static int dma_txsize = DMA_TX_SIZE;
module_param(dma_txsize, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(dma_txsize, "Number of descriptors in the TX list");
#define DMA_RX_SIZE 256
static int dma_rxsize = DMA_RX_SIZE;
module_param(dma_rxsize, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(dma_rxsize, "Number of descriptors in the RX list");
static int flow_ctrl = FLOW_OFF;
module_param(flow_ctrl, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(flow_ctrl, "Flow control ability [on/off]");
static int pause = PAUSE_TIME;
module_param(pause, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(pause, "Flow Control Pause Time");
#define TC_DEFAULT 64
static int tc = TC_DEFAULT;
module_param(tc, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(tc, "DMA threshold control value");
#define DMA_BUFFER_SIZE BUF_SIZE_4KiB
static int buf_sz = DMA_BUFFER_SIZE;
module_param(buf_sz, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(buf_sz, "DMA buffer size");
static const u32 default_msg_level = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFUP |
NETIF_MSG_IFDOWN | NETIF_MSG_TIMER);
#define STMMAC_DEFAULT_LPI_TIMER 1000
static int eee_timer = STMMAC_DEFAULT_LPI_TIMER;
module_param(eee_timer, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(eee_timer, "LPI tx expiration time in msec");
#define STMMAC_LPI_T(x) (jiffies + msecs_to_jiffies(x))
/* By default the driver will use the ring mode to manage tx and rx descriptors
* but passing this value so user can force to use the chain instead of the ring
*/
static unsigned int chain_mode;
module_param(chain_mode, int, S_IRUGO);
MODULE_PARM_DESC(chain_mode, "To use chain instead of ring mode");
static irqreturn_t stmmac_interrupt(int irq, void *dev_id);
#ifdef CONFIG_STMMAC_DEBUG_FS
static int stmmac_init_fs(struct net_device *dev);
static void stmmac_exit_fs(void);
#endif
#define STMMAC_COAL_TIMER(x) (jiffies + usecs_to_jiffies(x))
/**
* stmmac_verify_args - verify the driver parameters.
* Description: it verifies if some wrong parameter is passed to the driver.
* Note that wrong parameters are replaced with the default values.
*/
static void stmmac_verify_args(void)
{
if (unlikely(watchdog < 0))
watchdog = TX_TIMEO;
if (unlikely(dma_rxsize < 0))
dma_rxsize = DMA_RX_SIZE;
if (unlikely(dma_txsize < 0))
dma_txsize = DMA_TX_SIZE;
if (unlikely((buf_sz < DMA_BUFFER_SIZE) || (buf_sz > BUF_SIZE_16KiB)))
buf_sz = DMA_BUFFER_SIZE;
if (unlikely(flow_ctrl > 1))
flow_ctrl = FLOW_AUTO;
else if (likely(flow_ctrl < 0))
flow_ctrl = FLOW_OFF;
if (unlikely((pause < 0) || (pause > 0xffff)))
pause = PAUSE_TIME;
if (eee_timer < 0)
eee_timer = STMMAC_DEFAULT_LPI_TIMER;
}
/**
* stmmac_clk_csr_set - dynamically set the MDC clock
* @priv: driver private structure
* Description: this is to dynamically set the MDC clock according to the csr
* clock input.
* Note:
* If a specific clk_csr value is passed from the platform
* this means that the CSR Clock Range selection cannot be
* changed at run-time and it is fixed (as reported in the driver
* documentation). Viceversa the driver will try to set the MDC
* clock dynamically according to the actual clock input.
*/
static void stmmac_clk_csr_set(struct stmmac_priv *priv)
{
u32 clk_rate;
clk_rate = clk_get_rate(priv->stmmac_clk);
/* Platform provided default clk_csr would be assumed valid
* for all other cases except for the below mentioned ones.
* For values higher than the IEEE 802.3 specified frequency
* we can not estimate the proper divider as it is not known
* the frequency of clk_csr_i. So we do not change the default
* divider.
*/
if (!(priv->clk_csr & MAC_CSR_H_FRQ_MASK)) {
if (clk_rate < CSR_F_35M)
priv->clk_csr = STMMAC_CSR_20_35M;
else if ((clk_rate >= CSR_F_35M) && (clk_rate < CSR_F_60M))
priv->clk_csr = STMMAC_CSR_35_60M;
else if ((clk_rate >= CSR_F_60M) && (clk_rate < CSR_F_100M))
priv->clk_csr = STMMAC_CSR_60_100M;
else if ((clk_rate >= CSR_F_100M) && (clk_rate < CSR_F_150M))
priv->clk_csr = STMMAC_CSR_100_150M;
else if ((clk_rate >= CSR_F_150M) && (clk_rate < CSR_F_250M))
priv->clk_csr = STMMAC_CSR_150_250M;
else if ((clk_rate >= CSR_F_250M) && (clk_rate < CSR_F_300M))
priv->clk_csr = STMMAC_CSR_250_300M;
}
}
static void print_pkt(unsigned char *buf, int len)
{
int j;
pr_debug("len = %d byte, buf addr: 0x%p", len, buf);
for (j = 0; j < len; j++) {
if ((j % 16) == 0)
pr_debug("\n %03x:", j);
pr_debug(" %02x", buf[j]);
}
pr_debug("\n");
}
/* minimum number of free TX descriptors required to wake up TX process */
#define STMMAC_TX_THRESH(x) (x->dma_tx_size/4)
static inline u32 stmmac_tx_avail(struct stmmac_priv *priv)
{
return priv->dirty_tx + priv->dma_tx_size - priv->cur_tx - 1;
}
/**
* stmmac_hw_fix_mac_speed: callback for speed selection
* @priv: driver private structure
* Description: on some platforms (e.g. ST), some HW system configuraton
* registers have to be set according to the link speed negotiated.
*/
static inline void stmmac_hw_fix_mac_speed(struct stmmac_priv *priv)
{
struct phy_device *phydev = priv->phydev;
if (likely(priv->plat->fix_mac_speed))
priv->plat->fix_mac_speed(priv->plat->bsp_priv, phydev->speed);
}
/**
* stmmac_enable_eee_mode: Check and enter in LPI mode
* @priv: driver private structure
* Description: this function is to verify and enter in LPI mode for EEE.
*/
static void stmmac_enable_eee_mode(struct stmmac_priv *priv)
{
/* Check and enter in LPI mode */
if ((priv->dirty_tx == priv->cur_tx) &&
(priv->tx_path_in_lpi_mode == false))
priv->hw->mac->set_eee_mode(priv->ioaddr);
}
/**
* stmmac_disable_eee_mode: disable/exit from EEE
* @priv: driver private structure
* Description: this function is to exit and disable EEE in case of
* LPI state is true. This is called by the xmit.
*/
void stmmac_disable_eee_mode(struct stmmac_priv *priv)
{
priv->hw->mac->reset_eee_mode(priv->ioaddr);
del_timer_sync(&priv->eee_ctrl_timer);
priv->tx_path_in_lpi_mode = false;
}
/**
* stmmac_eee_ctrl_timer: EEE TX SW timer.
* @arg : data hook
* Description:
* if there is no data transfer and if we are not in LPI state,
* then MAC Transmitter can be moved to LPI state.
*/
static void stmmac_eee_ctrl_timer(unsigned long arg)
{
struct stmmac_priv *priv = (struct stmmac_priv *)arg;
stmmac_enable_eee_mode(priv);
mod_timer(&priv->eee_ctrl_timer, STMMAC_LPI_T(eee_timer));
}
/**
* stmmac_eee_init: init EEE
* @priv: driver private structure
* Description:
* If the EEE support has been enabled while configuring the driver,
* if the GMAC actually supports the EEE (from the HW cap reg) and the
* phy can also manage EEE, so enable the LPI state and start the timer
* to verify if the tx path can enter in LPI state.
*/
bool stmmac_eee_init(struct stmmac_priv *priv)
{
bool ret = false;
/* Using PCS we cannot dial with the phy registers at this stage
* so we do not support extra feature like EEE.
*/
if ((priv->pcs == STMMAC_PCS_RGMII) || (priv->pcs == STMMAC_PCS_TBI) ||
(priv->pcs == STMMAC_PCS_RTBI))
goto out;
/* MAC core supports the EEE feature. */
if (priv->dma_cap.eee) {
/* Check if the PHY supports EEE */
if (phy_init_eee(priv->phydev, 1))
goto out;
if (!priv->eee_active) {
priv->eee_active = 1;
init_timer(&priv->eee_ctrl_timer);
priv->eee_ctrl_timer.function = stmmac_eee_ctrl_timer;
priv->eee_ctrl_timer.data = (unsigned long)priv;
priv->eee_ctrl_timer.expires = STMMAC_LPI_T(eee_timer);
add_timer(&priv->eee_ctrl_timer);
priv->hw->mac->set_eee_timer(priv->ioaddr,
STMMAC_DEFAULT_LIT_LS,
priv->tx_lpi_timer);
} else
/* Set HW EEE according to the speed */
priv->hw->mac->set_eee_pls(priv->ioaddr,
priv->phydev->link);
pr_info("stmmac: Energy-Efficient Ethernet initialized\n");
ret = true;
}
out:
return ret;
}
/* stmmac_get_tx_hwtstamp: get HW TX timestamps
* @priv: driver private structure
* @entry : descriptor index to be used.
* @skb : the socket buffer
* Description :
* This function will read timestamp from the descriptor & pass it to stack.
* and also perform some sanity checks.
*/
static void stmmac_get_tx_hwtstamp(struct stmmac_priv *priv,
unsigned int entry, struct sk_buff *skb)
{
struct skb_shared_hwtstamps shhwtstamp;
u64 ns;
void *desc = NULL;
if (!priv->hwts_tx_en)
return;
/* exit if skb doesn't support hw tstamp */
if (likely(!skb || !(skb_shinfo(skb)->tx_flags & SKBTX_IN_PROGRESS)))
return;
if (priv->adv_ts)
desc = (priv->dma_etx + entry);
else
desc = (priv->dma_tx + entry);
/* check tx tstamp status */
if (!priv->hw->desc->get_tx_timestamp_status((struct dma_desc *)desc))
return;
/* get the valid tstamp */
ns = priv->hw->desc->get_timestamp(desc, priv->adv_ts);
memset(&shhwtstamp, 0, sizeof(struct skb_shared_hwtstamps));
shhwtstamp.hwtstamp = ns_to_ktime(ns);
/* pass tstamp to stack */
skb_tstamp_tx(skb, &shhwtstamp);
return;
}
/* stmmac_get_rx_hwtstamp: get HW RX timestamps
* @priv: driver private structure
* @entry : descriptor index to be used.
* @skb : the socket buffer
* Description :
* This function will read received packet's timestamp from the descriptor
* and pass it to stack. It also perform some sanity checks.
*/
static void stmmac_get_rx_hwtstamp(struct stmmac_priv *priv,
unsigned int entry, struct sk_buff *skb)
{
struct skb_shared_hwtstamps *shhwtstamp = NULL;
u64 ns;
void *desc = NULL;
if (!priv->hwts_rx_en)
return;
if (priv->adv_ts)
desc = (priv->dma_erx + entry);
else
desc = (priv->dma_rx + entry);
/* exit if rx tstamp is not valid */
if (!priv->hw->desc->get_rx_timestamp_status(desc, priv->adv_ts))
return;
/* get valid tstamp */
ns = priv->hw->desc->get_timestamp(desc, priv->adv_ts);
shhwtstamp = skb_hwtstamps(skb);
memset(shhwtstamp, 0, sizeof(struct skb_shared_hwtstamps));
shhwtstamp->hwtstamp = ns_to_ktime(ns);
}
/**
* stmmac_hwtstamp_ioctl - control hardware timestamping.
* @dev: device pointer.
* @ifr: An IOCTL specefic structure, that can contain a pointer to
* a proprietary structure used to pass information to the driver.
* Description:
* This function configures the MAC to enable/disable both outgoing(TX)
* and incoming(RX) packets time stamping based on user input.
* Return Value:
* 0 on success and an appropriate -ve integer on failure.
*/
static int stmmac_hwtstamp_ioctl(struct net_device *dev, struct ifreq *ifr)
{
struct stmmac_priv *priv = netdev_priv(dev);
struct hwtstamp_config config;
struct timespec now;
u64 temp = 0;
u32 ptp_v2 = 0;
u32 tstamp_all = 0;
u32 ptp_over_ipv4_udp = 0;
u32 ptp_over_ipv6_udp = 0;
u32 ptp_over_ethernet = 0;
u32 snap_type_sel = 0;
u32 ts_master_en = 0;
u32 ts_event_en = 0;
u32 value = 0;
if (!(priv->dma_cap.time_stamp || priv->adv_ts)) {
netdev_alert(priv->dev, "No support for HW time stamping\n");
priv->hwts_tx_en = 0;
priv->hwts_rx_en = 0;
return -EOPNOTSUPP;
}
if (copy_from_user(&config, ifr->ifr_data,
sizeof(struct hwtstamp_config)))
return -EFAULT;
pr_debug("%s config flags:0x%x, tx_type:0x%x, rx_filter:0x%x\n",
__func__, config.flags, config.tx_type, config.rx_filter);
/* reserved for future extensions */
if (config.flags)
return -EINVAL;
if (config.tx_type != HWTSTAMP_TX_OFF &&
config.tx_type != HWTSTAMP_TX_ON)
return -ERANGE;
if (priv->adv_ts) {
switch (config.rx_filter) {
case HWTSTAMP_FILTER_NONE:
/* time stamp no incoming packet at all */
config.rx_filter = HWTSTAMP_FILTER_NONE;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
/* PTP v1, UDP, any kind of event packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_EVENT;
/* take time stamp for all event messages */
snap_type_sel = PTP_TCR_SNAPTYPSEL_1;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
/* PTP v1, UDP, Sync packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_SYNC;
/* take time stamp for SYNC messages only */
ts_event_en = PTP_TCR_TSEVNTENA;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
/* PTP v1, UDP, Delay_req packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ;
/* take time stamp for Delay_Req messages only */
ts_master_en = PTP_TCR_TSMSTRENA;
ts_event_en = PTP_TCR_TSEVNTENA;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
break;
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
/* PTP v2, UDP, any kind of event packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_EVENT;
ptp_v2 = PTP_TCR_TSVER2ENA;
/* take time stamp for all event messages */
snap_type_sel = PTP_TCR_SNAPTYPSEL_1;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
break;
case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
/* PTP v2, UDP, Sync packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_SYNC;
ptp_v2 = PTP_TCR_TSVER2ENA;
/* take time stamp for SYNC messages only */
ts_event_en = PTP_TCR_TSEVNTENA;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
break;
case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
/* PTP v2, UDP, Delay_req packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ;
ptp_v2 = PTP_TCR_TSVER2ENA;
/* take time stamp for Delay_Req messages only */
ts_master_en = PTP_TCR_TSMSTRENA;
ts_event_en = PTP_TCR_TSEVNTENA;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
break;
case HWTSTAMP_FILTER_PTP_V2_EVENT:
/* PTP v2/802.AS1 any layer, any kind of event packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT;
ptp_v2 = PTP_TCR_TSVER2ENA;
/* take time stamp for all event messages */
snap_type_sel = PTP_TCR_SNAPTYPSEL_1;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
ptp_over_ethernet = PTP_TCR_TSIPENA;
break;
case HWTSTAMP_FILTER_PTP_V2_SYNC:
/* PTP v2/802.AS1, any layer, Sync packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V2_SYNC;
ptp_v2 = PTP_TCR_TSVER2ENA;
/* take time stamp for SYNC messages only */
ts_event_en = PTP_TCR_TSEVNTENA;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
ptp_over_ethernet = PTP_TCR_TSIPENA;
break;
case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
/* PTP v2/802.AS1, any layer, Delay_req packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V2_DELAY_REQ;
ptp_v2 = PTP_TCR_TSVER2ENA;
/* take time stamp for Delay_Req messages only */
ts_master_en = PTP_TCR_TSMSTRENA;
ts_event_en = PTP_TCR_TSEVNTENA;
ptp_over_ipv4_udp = PTP_TCR_TSIPV4ENA;
ptp_over_ipv6_udp = PTP_TCR_TSIPV6ENA;
ptp_over_ethernet = PTP_TCR_TSIPENA;
break;
case HWTSTAMP_FILTER_ALL:
/* time stamp any incoming packet */
config.rx_filter = HWTSTAMP_FILTER_ALL;
tstamp_all = PTP_TCR_TSENALL;
break;
default:
return -ERANGE;
}
} else {
switch (config.rx_filter) {
case HWTSTAMP_FILTER_NONE:
config.rx_filter = HWTSTAMP_FILTER_NONE;
break;
default:
/* PTP v1, UDP, any kind of event packet */
config.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_EVENT;
break;
}
}
priv->hwts_rx_en = ((config.rx_filter == HWTSTAMP_FILTER_NONE) ? 0 : 1);
priv->hwts_tx_en = config.tx_type == HWTSTAMP_TX_ON;
if (!priv->hwts_tx_en && !priv->hwts_rx_en)
priv->hw->ptp->config_hw_tstamping(priv->ioaddr, 0);
else {
value = (PTP_TCR_TSENA | PTP_TCR_TSCFUPDT | PTP_TCR_TSCTRLSSR |
tstamp_all | ptp_v2 | ptp_over_ethernet |
ptp_over_ipv6_udp | ptp_over_ipv4_udp | ts_event_en |
ts_master_en | snap_type_sel);
priv->hw->ptp->config_hw_tstamping(priv->ioaddr, value);
/* program Sub Second Increment reg */
priv->hw->ptp->config_sub_second_increment(priv->ioaddr);
/* calculate default added value:
* formula is :
* addend = (2^32)/freq_div_ratio;
* where, freq_div_ratio = STMMAC_SYSCLOCK/50MHz
* hence, addend = ((2^32) * 50MHz)/STMMAC_SYSCLOCK;
* NOTE: STMMAC_SYSCLOCK should be >= 50MHz to
* achive 20ns accuracy.
*
* 2^x * y == (y << x), hence
* 2^32 * 50000000 ==> (50000000 << 32)
*/
temp = (u64) (50000000ULL << 32);
priv->default_addend = div_u64(temp, STMMAC_SYSCLOCK);
priv->hw->ptp->config_addend(priv->ioaddr,
priv->default_addend);
/* initialize system time */
getnstimeofday(&now);
priv->hw->ptp->init_systime(priv->ioaddr, now.tv_sec,
now.tv_nsec);
}
return copy_to_user(ifr->ifr_data, &config,
sizeof(struct hwtstamp_config)) ? -EFAULT : 0;
}
/**
* stmmac_init_ptp: init PTP
* @priv: driver private structure
* Description: this is to verify if the HW supports the PTPv1 or v2.
* This is done by looking at the HW cap. register.
* Also it registers the ptp driver.
*/
static int stmmac_init_ptp(struct stmmac_priv *priv)
{
if (!(priv->dma_cap.time_stamp || priv->dma_cap.atime_stamp))
return -EOPNOTSUPP;
priv->adv_ts = 0;
if (priv->dma_cap.atime_stamp && priv->extend_desc)
priv->adv_ts = 1;
if (netif_msg_hw(priv) && priv->dma_cap.time_stamp)
pr_debug("IEEE 1588-2002 Time Stamp supported\n");
if (netif_msg_hw(priv) && priv->adv_ts)
pr_debug("IEEE 1588-2008 Advanced Time Stamp supported\n");
priv->hw->ptp = &stmmac_ptp;
priv->hwts_tx_en = 0;
priv->hwts_rx_en = 0;
return stmmac_ptp_register(priv);
}
static void stmmac_release_ptp(struct stmmac_priv *priv)
{
stmmac_ptp_unregister(priv);
}
/**
* stmmac_adjust_link
* @dev: net device structure
* Description: it adjusts the link parameters.
*/
static void stmmac_adjust_link(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
struct phy_device *phydev = priv->phydev;
unsigned long flags;
int new_state = 0;
unsigned int fc = priv->flow_ctrl, pause_time = priv->pause;
if (phydev == NULL)
return;
spin_lock_irqsave(&priv->lock, flags);
if (phydev->link) {
u32 ctrl = readl(priv->ioaddr + MAC_CTRL_REG);
/* Now we make sure that we can be in full duplex mode.
* If not, we operate in half-duplex mode. */
if (phydev->duplex != priv->oldduplex) {
new_state = 1;
if (!(phydev->duplex))
ctrl &= ~priv->hw->link.duplex;
else
ctrl |= priv->hw->link.duplex;
priv->oldduplex = phydev->duplex;
}
/* Flow Control operation */
if (phydev->pause)
priv->hw->mac->flow_ctrl(priv->ioaddr, phydev->duplex,
fc, pause_time);
if (phydev->speed != priv->speed) {
new_state = 1;
switch (phydev->speed) {
case 1000:
if (likely(priv->plat->has_gmac))
ctrl &= ~priv->hw->link.port;
stmmac_hw_fix_mac_speed(priv);
break;
case 100:
case 10:
if (priv->plat->has_gmac) {
ctrl |= priv->hw->link.port;
if (phydev->speed == SPEED_100) {
ctrl |= priv->hw->link.speed;
} else {
ctrl &= ~(priv->hw->link.speed);
}
} else {
ctrl &= ~priv->hw->link.port;
}
stmmac_hw_fix_mac_speed(priv);
break;
default:
if (netif_msg_link(priv))
pr_warn("%s: Speed (%d) not 10/100\n",
dev->name, phydev->speed);
break;
}
priv->speed = phydev->speed;
}
writel(ctrl, priv->ioaddr + MAC_CTRL_REG);
if (!priv->oldlink) {
new_state = 1;
priv->oldlink = 1;
}
} else if (priv->oldlink) {
new_state = 1;
priv->oldlink = 0;
priv->speed = 0;
priv->oldduplex = -1;
}
if (new_state && netif_msg_link(priv))
phy_print_status(phydev);
/* At this stage, it could be needed to setup the EEE or adjust some
* MAC related HW registers.
*/
priv->eee_enabled = stmmac_eee_init(priv);
spin_unlock_irqrestore(&priv->lock, flags);
}
/**
* stmmac_check_pcs_mode: verify if RGMII/SGMII is supported
* @priv: driver private structure
* Description: this is to verify if the HW supports the PCS.
* Physical Coding Sublayer (PCS) interface that can be used when the MAC is
* configured for the TBI, RTBI, or SGMII PHY interface.
*/
static void stmmac_check_pcs_mode(struct stmmac_priv *priv)
{
int interface = priv->plat->interface;
if (priv->dma_cap.pcs) {
if ((interface == PHY_INTERFACE_MODE_RGMII) ||
(interface == PHY_INTERFACE_MODE_RGMII_ID) ||
(interface == PHY_INTERFACE_MODE_RGMII_RXID) ||
(interface == PHY_INTERFACE_MODE_RGMII_TXID)) {
pr_debug("STMMAC: PCS RGMII support enable\n");
priv->pcs = STMMAC_PCS_RGMII;
} else if (interface == PHY_INTERFACE_MODE_SGMII) {
pr_debug("STMMAC: PCS SGMII support enable\n");
priv->pcs = STMMAC_PCS_SGMII;
}
}
}
/**
* stmmac_init_phy - PHY initialization
* @dev: net device structure
* Description: it initializes the driver's PHY state, and attaches the PHY
* to the mac driver.
* Return value:
* 0 on success
*/
static int stmmac_init_phy(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
struct phy_device *phydev;
char phy_id_fmt[MII_BUS_ID_SIZE + 3];
char bus_id[MII_BUS_ID_SIZE];
int interface = priv->plat->interface;
int max_speed = priv->plat->max_speed;
priv->oldlink = 0;
priv->speed = 0;
priv->oldduplex = -1;
if (priv->plat->phy_bus_name)
snprintf(bus_id, MII_BUS_ID_SIZE, "%s-%x",
priv->plat->phy_bus_name, priv->plat->bus_id);
else
snprintf(bus_id, MII_BUS_ID_SIZE, "stmmac-%x",
priv->plat->bus_id);
snprintf(phy_id_fmt, MII_BUS_ID_SIZE + 3, PHY_ID_FMT, bus_id,
priv->plat->phy_addr);
pr_debug("stmmac_init_phy: trying to attach to %s\n", phy_id_fmt);
phydev = phy_connect(dev, phy_id_fmt, &stmmac_adjust_link, interface);
if (IS_ERR(phydev)) {
pr_err("%s: Could not attach to PHY\n", dev->name);
return PTR_ERR(phydev);
}
/* Stop Advertising 1000BASE Capability if interface is not GMII */
if ((interface == PHY_INTERFACE_MODE_MII) ||
(interface == PHY_INTERFACE_MODE_RMII) ||
(max_speed < 1000 && max_speed > 0))
phydev->advertising &= ~(SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full);
/*
* Broken HW is sometimes missing the pull-up resistor on the
* MDIO line, which results in reads to non-existent devices returning
* 0 rather than 0xffff. Catch this here and treat 0 as a non-existent
* device as well.
* Note: phydev->phy_id is the result of reading the UID PHY registers.
*/
if (phydev->phy_id == 0) {
phy_disconnect(phydev);
return -ENODEV;
}
pr_debug("stmmac_init_phy: %s: attached to PHY (UID 0x%x)"
" Link = %d\n", dev->name, phydev->phy_id, phydev->link);
priv->phydev = phydev;
return 0;
}
/**
* stmmac_display_ring: display ring
* @head: pointer to the head of the ring passed.
* @size: size of the ring.
* @extend_desc: to verify if extended descriptors are used.
* Description: display the control/status and buffer descriptors.
*/
static void stmmac_display_ring(void *head, int size, int extend_desc)
{
int i;
struct dma_extended_desc *ep = (struct dma_extended_desc *)head;
struct dma_desc *p = (struct dma_desc *)head;
for (i = 0; i < size; i++) {
u64 x;
if (extend_desc) {
x = *(u64 *) ep;
pr_info("%d [0x%x]: 0x%x 0x%x 0x%x 0x%x\n",
i, (unsigned int)virt_to_phys(ep),
(unsigned int)x, (unsigned int)(x >> 32),
ep->basic.des2, ep->basic.des3);
ep++;
} else {
x = *(u64 *) p;
pr_info("%d [0x%x]: 0x%x 0x%x 0x%x 0x%x",
i, (unsigned int)virt_to_phys(p),
(unsigned int)x, (unsigned int)(x >> 32),
p->des2, p->des3);
p++;
}
pr_info("\n");
}
}
static void stmmac_display_rings(struct stmmac_priv *priv)
{
unsigned int txsize = priv->dma_tx_size;
unsigned int rxsize = priv->dma_rx_size;
if (priv->extend_desc) {
pr_info("Extended RX descriptor ring:\n");
stmmac_display_ring((void *)priv->dma_erx, rxsize, 1);
pr_info("Extended TX descriptor ring:\n");
stmmac_display_ring((void *)priv->dma_etx, txsize, 1);
} else {
pr_info("RX descriptor ring:\n");
stmmac_display_ring((void *)priv->dma_rx, rxsize, 0);
pr_info("TX descriptor ring:\n");
stmmac_display_ring((void *)priv->dma_tx, txsize, 0);
}
}
static int stmmac_set_bfsize(int mtu, int bufsize)
{
int ret = bufsize;
if (mtu >= BUF_SIZE_4KiB)
ret = BUF_SIZE_8KiB;
else if (mtu >= BUF_SIZE_2KiB)
ret = BUF_SIZE_4KiB;
else if (mtu >= DMA_BUFFER_SIZE)
ret = BUF_SIZE_2KiB;
else
ret = DMA_BUFFER_SIZE;
return ret;
}
/**
* stmmac_clear_descriptors: clear descriptors
* @priv: driver private structure
* Description: this function is called to clear the tx and rx descriptors
* in case of both basic and extended descriptors are used.
*/
static void stmmac_clear_descriptors(struct stmmac_priv *priv)
{
int i;
unsigned int txsize = priv->dma_tx_size;
unsigned int rxsize = priv->dma_rx_size;
/* Clear the Rx/Tx descriptors */
for (i = 0; i < rxsize; i++)
if (priv->extend_desc)
priv->hw->desc->init_rx_desc(&priv->dma_erx[i].basic,
priv->use_riwt, priv->mode,
(i == rxsize - 1));
else
priv->hw->desc->init_rx_desc(&priv->dma_rx[i],
priv->use_riwt, priv->mode,
(i == rxsize - 1));
for (i = 0; i < txsize; i++)
if (priv->extend_desc)
priv->hw->desc->init_tx_desc(&priv->dma_etx[i].basic,
priv->mode,
(i == txsize - 1));
else
priv->hw->desc->init_tx_desc(&priv->dma_tx[i],
priv->mode,
(i == txsize - 1));
}
static int stmmac_init_rx_buffers(struct stmmac_priv *priv, struct dma_desc *p,
int i)
{
struct sk_buff *skb;
skb = __netdev_alloc_skb(priv->dev, priv->dma_buf_sz + NET_IP_ALIGN,
GFP_KERNEL);
if (!skb) {
pr_err("%s: Rx init fails; skb is NULL\n", __func__);
return -ENOMEM;
}
skb_reserve(skb, NET_IP_ALIGN);
priv->rx_skbuff[i] = skb;
priv->rx_skbuff_dma[i] = dma_map_single(priv->device, skb->data,
priv->dma_buf_sz,
DMA_FROM_DEVICE);
if (dma_mapping_error(priv->device, priv->rx_skbuff_dma[i])) {
pr_err("%s: DMA mapping error\n", __func__);
dev_kfree_skb_any(skb);
return -EINVAL;
}
p->des2 = priv->rx_skbuff_dma[i];
if ((priv->mode == STMMAC_RING_MODE) &&
(priv->dma_buf_sz == BUF_SIZE_16KiB))
priv->hw->ring->init_desc3(p);
return 0;
}
static void stmmac_free_rx_buffers(struct stmmac_priv *priv, int i)
{
if (priv->rx_skbuff[i]) {
dma_unmap_single(priv->device, priv->rx_skbuff_dma[i],
priv->dma_buf_sz, DMA_FROM_DEVICE);
dev_kfree_skb_any(priv->rx_skbuff[i]);
}
priv->rx_skbuff[i] = NULL;
}
/**
* init_dma_desc_rings - init the RX/TX descriptor rings
* @dev: net device structure
* Description: this function initializes the DMA RX/TX descriptors
* and allocates the socket buffers. It suppors the chained and ring
* modes.
*/
static int init_dma_desc_rings(struct net_device *dev)
{
int i;
struct stmmac_priv *priv = netdev_priv(dev);
unsigned int txsize = priv->dma_tx_size;
unsigned int rxsize = priv->dma_rx_size;
unsigned int bfsize = 0;
int ret = -ENOMEM;
/* Set the max buffer size according to the DESC mode
* and the MTU. Note that RING mode allows 16KiB bsize.
*/
if (priv->mode == STMMAC_RING_MODE)
bfsize = priv->hw->ring->set_16kib_bfsize(dev->mtu);
if (bfsize < BUF_SIZE_16KiB)
bfsize = stmmac_set_bfsize(dev->mtu, priv->dma_buf_sz);
priv->dma_buf_sz = bfsize;
if (netif_msg_probe(priv))
pr_debug("%s: txsize %d, rxsize %d, bfsize %d\n", __func__,
txsize, rxsize, bfsize);
if (netif_msg_probe(priv)) {
pr_debug("(%s) dma_rx_phy=0x%08x dma_tx_phy=0x%08x\n", __func__,
(u32) priv->dma_rx_phy, (u32) priv->dma_tx_phy);
/* RX INITIALIZATION */
pr_debug("\tSKB addresses:\nskb\t\tskb data\tdma data\n");
}
for (i = 0; i < rxsize; i++) {
struct dma_desc *p;
if (priv->extend_desc)
p = &((priv->dma_erx + i)->basic);
else
p = priv->dma_rx + i;
ret = stmmac_init_rx_buffers(priv, p, i);
if (ret)
goto err_init_rx_buffers;
if (netif_msg_probe(priv))
pr_debug("[%p]\t[%p]\t[%x]\n", priv->rx_skbuff[i],
priv->rx_skbuff[i]->data,
(unsigned int)priv->rx_skbuff_dma[i]);
}
priv->cur_rx = 0;
priv->dirty_rx = (unsigned int)(i - rxsize);
buf_sz = bfsize;
/* Setup the chained descriptor addresses */
if (priv->mode == STMMAC_CHAIN_MODE) {
if (priv->extend_desc) {
priv->hw->chain->init(priv->dma_erx, priv->dma_rx_phy,
rxsize, 1);
priv->hw->chain->init(priv->dma_etx, priv->dma_tx_phy,
txsize, 1);
} else {
priv->hw->chain->init(priv->dma_rx, priv->dma_rx_phy,
rxsize, 0);
priv->hw->chain->init(priv->dma_tx, priv->dma_tx_phy,
txsize, 0);
}
}
/* TX INITIALIZATION */
for (i = 0; i < txsize; i++) {
struct dma_desc *p;
if (priv->extend_desc)
p = &((priv->dma_etx + i)->basic);
else
p = priv->dma_tx + i;
p->des2 = 0;
priv->tx_skbuff_dma[i] = 0;
priv->tx_skbuff[i] = NULL;
}
priv->dirty_tx = 0;
priv->cur_tx = 0;
stmmac_clear_descriptors(priv);
if (netif_msg_hw(priv))
stmmac_display_rings(priv);
return 0;
err_init_rx_buffers:
while (--i >= 0)
stmmac_free_rx_buffers(priv, i);
return ret;
}
static void dma_free_rx_skbufs(struct stmmac_priv *priv)
{
int i;
for (i = 0; i < priv->dma_rx_size; i++)
stmmac_free_rx_buffers(priv, i);
}
static void dma_free_tx_skbufs(struct stmmac_priv *priv)
{
int i;
for (i = 0; i < priv->dma_tx_size; i++) {
struct dma_desc *p;
if (priv->extend_desc)
p = &((priv->dma_etx + i)->basic);
else
p = priv->dma_tx + i;
if (priv->tx_skbuff_dma[i]) {
dma_unmap_single(priv->device,
priv->tx_skbuff_dma[i],
priv->hw->desc->get_tx_len(p),
DMA_TO_DEVICE);
priv->tx_skbuff_dma[i] = 0;
}
if (priv->tx_skbuff[i] != NULL) {
dev_kfree_skb_any(priv->tx_skbuff[i]);
priv->tx_skbuff[i] = NULL;
}
}
}
static int alloc_dma_desc_resources(struct stmmac_priv *priv)
{
unsigned int txsize = priv->dma_tx_size;
unsigned int rxsize = priv->dma_rx_size;
int ret = -ENOMEM;
priv->rx_skbuff_dma = kmalloc_array(rxsize, sizeof(dma_addr_t),
GFP_KERNEL);
if (!priv->rx_skbuff_dma)
return -ENOMEM;
priv->rx_skbuff = kmalloc_array(rxsize, sizeof(struct sk_buff *),
GFP_KERNEL);
if (!priv->rx_skbuff)
goto err_rx_skbuff;
priv->tx_skbuff_dma = kmalloc_array(txsize, sizeof(dma_addr_t),
GFP_KERNEL);
if (!priv->tx_skbuff_dma)
goto err_tx_skbuff_dma;
priv->tx_skbuff = kmalloc_array(txsize, sizeof(struct sk_buff *),
GFP_KERNEL);
if (!priv->tx_skbuff)
goto err_tx_skbuff;
if (priv->extend_desc) {
priv->dma_erx = dma_alloc_coherent(priv->device, rxsize *
sizeof(struct
dma_extended_desc),
&priv->dma_rx_phy,
GFP_KERNEL);
if (!priv->dma_erx)
goto err_dma;
priv->dma_etx = dma_alloc_coherent(priv->device, txsize *
sizeof(struct
dma_extended_desc),
&priv->dma_tx_phy,
GFP_KERNEL);
if (!priv->dma_etx) {
dma_free_coherent(priv->device, priv->dma_rx_size *
sizeof(struct dma_extended_desc),
priv->dma_erx, priv->dma_rx_phy);
goto err_dma;
}
} else {
priv->dma_rx = dma_alloc_coherent(priv->device, rxsize *
sizeof(struct dma_desc),
&priv->dma_rx_phy,
GFP_KERNEL);
if (!priv->dma_rx)
goto err_dma;
priv->dma_tx = dma_alloc_coherent(priv->device, txsize *
sizeof(struct dma_desc),
&priv->dma_tx_phy,
GFP_KERNEL);
if (!priv->dma_tx) {
dma_free_coherent(priv->device, priv->dma_rx_size *
sizeof(struct dma_desc),
priv->dma_rx, priv->dma_rx_phy);
goto err_dma;
}
}
return 0;
err_dma:
kfree(priv->tx_skbuff);
err_tx_skbuff:
kfree(priv->tx_skbuff_dma);
err_tx_skbuff_dma:
kfree(priv->rx_skbuff);
err_rx_skbuff:
kfree(priv->rx_skbuff_dma);
return ret;
}
static void free_dma_desc_resources(struct stmmac_priv *priv)
{
/* Release the DMA TX/RX socket buffers */
dma_free_rx_skbufs(priv);
dma_free_tx_skbufs(priv);
/* Free DMA regions of consistent memory previously allocated */
if (!priv->extend_desc) {
dma_free_coherent(priv->device,
priv->dma_tx_size * sizeof(struct dma_desc),
priv->dma_tx, priv->dma_tx_phy);
dma_free_coherent(priv->device,
priv->dma_rx_size * sizeof(struct dma_desc),
priv->dma_rx, priv->dma_rx_phy);
} else {
dma_free_coherent(priv->device, priv->dma_tx_size *
sizeof(struct dma_extended_desc),
priv->dma_etx, priv->dma_tx_phy);
dma_free_coherent(priv->device, priv->dma_rx_size *
sizeof(struct dma_extended_desc),
priv->dma_erx, priv->dma_rx_phy);
}
kfree(priv->rx_skbuff_dma);
kfree(priv->rx_skbuff);
kfree(priv->tx_skbuff_dma);
kfree(priv->tx_skbuff);
}
/**
* stmmac_dma_operation_mode - HW DMA operation mode
* @priv: driver private structure
* Description: it sets the DMA operation mode: tx/rx DMA thresholds
* or Store-And-Forward capability.
*/
static void stmmac_dma_operation_mode(struct stmmac_priv *priv)
{
if (priv->plat->force_thresh_dma_mode)
priv->hw->dma->dma_mode(priv->ioaddr, tc, tc);
else if (priv->plat->force_sf_dma_mode || priv->plat->tx_coe) {
/*
* In case of GMAC, SF mode can be enabled
* to perform the TX COE in HW. This depends on:
* 1) TX COE if actually supported
* 2) There is no bugged Jumbo frame support
* that needs to not insert csum in the TDES.
*/
priv->hw->dma->dma_mode(priv->ioaddr, SF_DMA_MODE, SF_DMA_MODE);
tc = SF_DMA_MODE;
} else
priv->hw->dma->dma_mode(priv->ioaddr, tc, SF_DMA_MODE);
}
/**
* stmmac_tx_clean:
* @priv: driver private structure
* Description: it reclaims resources after transmission completes.
*/
static void stmmac_tx_clean(struct stmmac_priv *priv)
{
unsigned int txsize = priv->dma_tx_size;
spin_lock(&priv->tx_lock);
priv->xstats.tx_clean++;
while (priv->dirty_tx != priv->cur_tx) {
int last;
unsigned int entry = priv->dirty_tx % txsize;
struct sk_buff *skb = priv->tx_skbuff[entry];
struct dma_desc *p;
if (priv->extend_desc)
p = (struct dma_desc *)(priv->dma_etx + entry);
else
p = priv->dma_tx + entry;
/* Check if the descriptor is owned by the DMA. */
if (priv->hw->desc->get_tx_owner(p))
break;
/* Verify tx error by looking at the last segment. */
last = priv->hw->desc->get_tx_ls(p);
if (likely(last)) {
int tx_error =
priv->hw->desc->tx_status(&priv->dev->stats,
&priv->xstats, p,
priv->ioaddr);
if (likely(tx_error == 0)) {
priv->dev->stats.tx_packets++;
priv->xstats.tx_pkt_n++;
} else
priv->dev->stats.tx_errors++;
stmmac_get_tx_hwtstamp(priv, entry, skb);
}
if (netif_msg_tx_done(priv))
pr_debug("%s: curr %d, dirty %d\n", __func__,
priv->cur_tx, priv->dirty_tx);
if (likely(priv->tx_skbuff_dma[entry])) {
dma_unmap_single(priv->device,
priv->tx_skbuff_dma[entry],
priv->hw->desc->get_tx_len(p),
DMA_TO_DEVICE);
priv->tx_skbuff_dma[entry] = 0;
}
priv->hw->ring->clean_desc3(priv, p);
if (likely(skb != NULL)) {
dev_kfree_skb(skb);
priv->tx_skbuff[entry] = NULL;
}
priv->hw->desc->release_tx_desc(p, priv->mode);
priv->dirty_tx++;
}
if (unlikely(netif_queue_stopped(priv->dev) &&
stmmac_tx_avail(priv) > STMMAC_TX_THRESH(priv))) {
netif_tx_lock(priv->dev);
if (netif_queue_stopped(priv->dev) &&
stmmac_tx_avail(priv) > STMMAC_TX_THRESH(priv)) {
if (netif_msg_tx_done(priv))
pr_debug("%s: restart transmit\n", __func__);
netif_wake_queue(priv->dev);
}
netif_tx_unlock(priv->dev);
}
if ((priv->eee_enabled) && (!priv->tx_path_in_lpi_mode)) {
stmmac_enable_eee_mode(priv);
mod_timer(&priv->eee_ctrl_timer, STMMAC_LPI_T(eee_timer));
}
spin_unlock(&priv->tx_lock);
}
static inline void stmmac_enable_dma_irq(struct stmmac_priv *priv)
{
priv->hw->dma->enable_dma_irq(priv->ioaddr);
}
static inline void stmmac_disable_dma_irq(struct stmmac_priv *priv)
{
priv->hw->dma->disable_dma_irq(priv->ioaddr);
}
/**
* stmmac_tx_err: irq tx error mng function
* @priv: driver private structure
* Description: it cleans the descriptors and restarts the transmission
* in case of errors.
*/
static void stmmac_tx_err(struct stmmac_priv *priv)
{
int i;
int txsize = priv->dma_tx_size;
netif_stop_queue(priv->dev);
priv->hw->dma->stop_tx(priv->ioaddr);
dma_free_tx_skbufs(priv);
for (i = 0; i < txsize; i++)
if (priv->extend_desc)
priv->hw->desc->init_tx_desc(&priv->dma_etx[i].basic,
priv->mode,
(i == txsize - 1));
else
priv->hw->desc->init_tx_desc(&priv->dma_tx[i],
priv->mode,
(i == txsize - 1));
priv->dirty_tx = 0;
priv->cur_tx = 0;
priv->hw->dma->start_tx(priv->ioaddr);
priv->dev->stats.tx_errors++;
netif_wake_queue(priv->dev);
}
/**
* stmmac_dma_interrupt: DMA ISR
* @priv: driver private structure
* Description: this is the DMA ISR. It is called by the main ISR.
* It calls the dwmac dma routine to understand which type of interrupt
* happened. In case of there is a Normal interrupt and either TX or RX
* interrupt happened so the NAPI is scheduled.
*/
static void stmmac_dma_interrupt(struct stmmac_priv *priv)
{
int status;
status = priv->hw->dma->dma_interrupt(priv->ioaddr, &priv->xstats);
if (likely((status & handle_rx)) || (status & handle_tx)) {
if (likely(napi_schedule_prep(&priv->napi))) {
stmmac_disable_dma_irq(priv);
__napi_schedule(&priv->napi);
}
}
if (unlikely(status & tx_hard_error_bump_tc)) {
/* Try to bump up the dma threshold on this failure */
if (unlikely(tc != SF_DMA_MODE) && (tc <= 256)) {
tc += 64;
priv->hw->dma->dma_mode(priv->ioaddr, tc, SF_DMA_MODE);
priv->xstats.threshold = tc;
}
} else if (unlikely(status == tx_hard_error))
stmmac_tx_err(priv);
}
/**
* stmmac_mmc_setup: setup the Mac Management Counters (MMC)
* @priv: driver private structure
* Description: this masks the MMC irq, in fact, the counters are managed in SW.
*/
static void stmmac_mmc_setup(struct stmmac_priv *priv)
{
unsigned int mode = MMC_CNTRL_RESET_ON_READ | MMC_CNTRL_COUNTER_RESET |
MMC_CNTRL_PRESET | MMC_CNTRL_FULL_HALF_PRESET;
dwmac_mmc_intr_all_mask(priv->ioaddr);
if (priv->dma_cap.rmon) {
dwmac_mmc_ctrl(priv->ioaddr, mode);
memset(&priv->mmc, 0, sizeof(struct stmmac_counters));
} else
pr_info(" No MAC Management Counters available\n");
}
static u32 stmmac_get_synopsys_id(struct stmmac_priv *priv)
{
u32 hwid = priv->hw->synopsys_uid;
/* Check Synopsys Id (not available on old chips) */
if (likely(hwid)) {
u32 uid = ((hwid & 0x0000ff00) >> 8);
u32 synid = (hwid & 0x000000ff);
pr_info("stmmac - user ID: 0x%x, Synopsys ID: 0x%x\n",
uid, synid);
return synid;
}
return 0;
}
/**
* stmmac_selec_desc_mode: to select among: normal/alternate/extend descriptors
* @priv: driver private structure
* Description: select the Enhanced/Alternate or Normal descriptors.
* In case of Enhanced/Alternate, it looks at the extended descriptors are
* supported by the HW cap. register.
*/
static void stmmac_selec_desc_mode(struct stmmac_priv *priv)
{
if (priv->plat->enh_desc) {
pr_info(" Enhanced/Alternate descriptors\n");
/* GMAC older than 3.50 has no extended descriptors */
if (priv->synopsys_id >= DWMAC_CORE_3_50) {
pr_info("\tEnabled extended descriptors\n");
priv->extend_desc = 1;
} else
pr_warn("Extended descriptors not supported\n");
priv->hw->desc = &enh_desc_ops;
} else {
pr_info(" Normal descriptors\n");
priv->hw->desc = &ndesc_ops;
}
}
/**
* stmmac_get_hw_features: get MAC capabilities from the HW cap. register.
* @priv: driver private structure
* Description:
* new GMAC chip generations have a new register to indicate the
* presence of the optional feature/functions.
* This can be also used to override the value passed through the
* platform and necessary for old MAC10/100 and GMAC chips.
*/
static int stmmac_get_hw_features(struct stmmac_priv *priv)
{
u32 hw_cap = 0;
if (priv->hw->dma->get_hw_feature) {
hw_cap = priv->hw->dma->get_hw_feature(priv->ioaddr);
priv->dma_cap.mbps_10_100 = (hw_cap & DMA_HW_FEAT_MIISEL);
priv->dma_cap.mbps_1000 = (hw_cap & DMA_HW_FEAT_GMIISEL) >> 1;
priv->dma_cap.half_duplex = (hw_cap & DMA_HW_FEAT_HDSEL) >> 2;
priv->dma_cap.hash_filter = (hw_cap & DMA_HW_FEAT_HASHSEL) >> 4;
priv->dma_cap.multi_addr = (hw_cap & DMA_HW_FEAT_ADDMAC) >> 5;
priv->dma_cap.pcs = (hw_cap & DMA_HW_FEAT_PCSSEL) >> 6;
priv->dma_cap.sma_mdio = (hw_cap & DMA_HW_FEAT_SMASEL) >> 8;
priv->dma_cap.pmt_remote_wake_up =
(hw_cap & DMA_HW_FEAT_RWKSEL) >> 9;
priv->dma_cap.pmt_magic_frame =
(hw_cap & DMA_HW_FEAT_MGKSEL) >> 10;
/* MMC */
priv->dma_cap.rmon = (hw_cap & DMA_HW_FEAT_MMCSEL) >> 11;
/* IEEE 1588-2002 */
priv->dma_cap.time_stamp =
(hw_cap & DMA_HW_FEAT_TSVER1SEL) >> 12;
/* IEEE 1588-2008 */
priv->dma_cap.atime_stamp =
(hw_cap & DMA_HW_FEAT_TSVER2SEL) >> 13;
/* 802.3az - Energy-Efficient Ethernet (EEE) */
priv->dma_cap.eee = (hw_cap & DMA_HW_FEAT_EEESEL) >> 14;
priv->dma_cap.av = (hw_cap & DMA_HW_FEAT_AVSEL) >> 15;
/* TX and RX csum */
priv->dma_cap.tx_coe = (hw_cap & DMA_HW_FEAT_TXCOESEL) >> 16;
priv->dma_cap.rx_coe_type1 =
(hw_cap & DMA_HW_FEAT_RXTYP1COE) >> 17;
priv->dma_cap.rx_coe_type2 =
(hw_cap & DMA_HW_FEAT_RXTYP2COE) >> 18;
priv->dma_cap.rxfifo_over_2048 =
(hw_cap & DMA_HW_FEAT_RXFIFOSIZE) >> 19;
/* TX and RX number of channels */
priv->dma_cap.number_rx_channel =
(hw_cap & DMA_HW_FEAT_RXCHCNT) >> 20;
priv->dma_cap.number_tx_channel =
(hw_cap & DMA_HW_FEAT_TXCHCNT) >> 22;
/* Alternate (enhanced) DESC mode */
priv->dma_cap.enh_desc = (hw_cap & DMA_HW_FEAT_ENHDESSEL) >> 24;
}
return hw_cap;
}
/**
* stmmac_check_ether_addr: check if the MAC addr is valid
* @priv: driver private structure
* Description:
* it is to verify if the MAC address is valid, in case of failures it
* generates a random MAC address
*/
static void stmmac_check_ether_addr(struct stmmac_priv *priv)
{
if (!is_valid_ether_addr(priv->dev->dev_addr)) {
priv->hw->mac->get_umac_addr((void __iomem *)
priv->dev->base_addr,
priv->dev->dev_addr, 0);
if (!is_valid_ether_addr(priv->dev->dev_addr))
eth_hw_addr_random(priv->dev);
pr_info("%s: device MAC address %pM\n", priv->dev->name,
priv->dev->dev_addr);
}
}
/**
* stmmac_init_dma_engine: DMA init.
* @priv: driver private structure
* Description:
* It inits the DMA invoking the specific MAC/GMAC callback.
* Some DMA parameters can be passed from the platform;
* in case of these are not passed a default is kept for the MAC or GMAC.
*/
static int stmmac_init_dma_engine(struct stmmac_priv *priv)
{
int pbl = DEFAULT_DMA_PBL, fixed_burst = 0, burst_len = 0;
int mixed_burst = 0;
int atds = 0;
if (priv->plat->dma_cfg) {
pbl = priv->plat->dma_cfg->pbl;
fixed_burst = priv->plat->dma_cfg->fixed_burst;
mixed_burst = priv->plat->dma_cfg->mixed_burst;
burst_len = priv->plat->dma_cfg->burst_len;
}
if (priv->extend_desc && (priv->mode == STMMAC_RING_MODE))
atds = 1;
return priv->hw->dma->init(priv->ioaddr, pbl, fixed_burst, mixed_burst,
burst_len, priv->dma_tx_phy,
priv->dma_rx_phy, atds);
}
/**
* stmmac_tx_timer: mitigation sw timer for tx.
* @data: data pointer
* Description:
* This is the timer handler to directly invoke the stmmac_tx_clean.
*/
static void stmmac_tx_timer(unsigned long data)
{
struct stmmac_priv *priv = (struct stmmac_priv *)data;
stmmac_tx_clean(priv);
}
/**
* stmmac_init_tx_coalesce: init tx mitigation options.
* @priv: driver private structure
* Description:
* This inits the transmit coalesce parameters: i.e. timer rate,
* timer handler and default threshold used for enabling the
* interrupt on completion bit.
*/
static void stmmac_init_tx_coalesce(struct stmmac_priv *priv)
{
priv->tx_coal_frames = STMMAC_TX_FRAMES;
priv->tx_coal_timer = STMMAC_COAL_TX_TIMER;
init_timer(&priv->txtimer);
priv->txtimer.expires = STMMAC_COAL_TIMER(priv->tx_coal_timer);
priv->txtimer.data = (unsigned long)priv;
priv->txtimer.function = stmmac_tx_timer;
add_timer(&priv->txtimer);
}
/**
* stmmac_hw_setup: setup mac in a usable state.
* @dev : pointer to the device structure.
* Description:
* This function sets up the ip in a usable state.
* Return value:
* 0 on success and an appropriate (-)ve integer as defined in errno.h
* file on failure.
*/
static int stmmac_hw_setup(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
int ret;
ret = init_dma_desc_rings(dev);
if (ret < 0) {
pr_err("%s: DMA descriptors initialization failed\n", __func__);
return ret;
}
/* DMA initialization and SW reset */
ret = stmmac_init_dma_engine(priv);
if (ret < 0) {
pr_err("%s: DMA engine initialization failed\n", __func__);
return ret;
}
/* Copy the MAC addr into the HW */
priv->hw->mac->set_umac_addr(priv->ioaddr, dev->dev_addr, 0);
/* If required, perform hw setup of the bus. */
if (priv->plat->bus_setup)
priv->plat->bus_setup(priv->ioaddr);
/* Initialize the MAC Core */
priv->hw->mac->core_init(priv->ioaddr, dev->mtu);
/* Enable the MAC Rx/Tx */
stmmac_set_mac(priv->ioaddr, true);
/* Set the HW DMA mode and the COE */
stmmac_dma_operation_mode(priv);
stmmac_mmc_setup(priv);
ret = stmmac_init_ptp(priv);
if (ret && ret != -EOPNOTSUPP)
pr_warn("%s: failed PTP initialisation\n", __func__);
#ifdef CONFIG_STMMAC_DEBUG_FS
ret = stmmac_init_fs(dev);
if (ret < 0)
pr_warn("%s: failed debugFS registration\n", __func__);
#endif
/* Start the ball rolling... */
pr_debug("%s: DMA RX/TX processes started...\n", dev->name);
priv->hw->dma->start_tx(priv->ioaddr);
priv->hw->dma->start_rx(priv->ioaddr);
/* Dump DMA/MAC registers */
if (netif_msg_hw(priv)) {
priv->hw->mac->dump_regs(priv->ioaddr);
priv->hw->dma->dump_regs(priv->ioaddr);
}
priv->tx_lpi_timer = STMMAC_DEFAULT_TWT_LS;
priv->eee_enabled = stmmac_eee_init(priv);
stmmac_init_tx_coalesce(priv);
if ((priv->use_riwt) && (priv->hw->dma->rx_watchdog)) {
priv->rx_riwt = MAX_DMA_RIWT;
priv->hw->dma->rx_watchdog(priv->ioaddr, MAX_DMA_RIWT);
}
if (priv->pcs && priv->hw->mac->ctrl_ane)
priv->hw->mac->ctrl_ane(priv->ioaddr, 0);
return 0;
}
/**
* stmmac_open - open entry point of the driver
* @dev : pointer to the device structure.
* Description:
* This function is the open entry point of the driver.
* Return value:
* 0 on success and an appropriate (-)ve integer as defined in errno.h
* file on failure.
*/
static int stmmac_open(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
int ret;
stmmac_check_ether_addr(priv);
if (priv->pcs != STMMAC_PCS_RGMII && priv->pcs != STMMAC_PCS_TBI &&
priv->pcs != STMMAC_PCS_RTBI) {
ret = stmmac_init_phy(dev);
if (ret) {
pr_err("%s: Cannot attach to PHY (error: %d)\n",
__func__, ret);
goto phy_error;
}
}
/* Extra statistics */
memset(&priv->xstats, 0, sizeof(struct stmmac_extra_stats));
priv->xstats.threshold = tc;
/* Create and initialize the TX/RX descriptors chains. */
priv->dma_tx_size = STMMAC_ALIGN(dma_txsize);
priv->dma_rx_size = STMMAC_ALIGN(dma_rxsize);
priv->dma_buf_sz = STMMAC_ALIGN(buf_sz);
alloc_dma_desc_resources(priv);
if (ret < 0) {
pr_err("%s: DMA descriptors allocation failed\n", __func__);
goto dma_desc_error;
}
ret = stmmac_hw_setup(dev);
if (ret < 0) {
pr_err("%s: Hw setup failed\n", __func__);
goto init_error;
}
if (priv->phydev)
phy_start(priv->phydev);
/* Request the IRQ lines */
ret = request_irq(dev->irq, stmmac_interrupt,
IRQF_SHARED, dev->name, dev);
if (unlikely(ret < 0)) {
pr_err("%s: ERROR: allocating the IRQ %d (error: %d)\n",
__func__, dev->irq, ret);
goto init_error;
}
/* Request the Wake IRQ in case of another line is used for WoL */
if (priv->wol_irq != dev->irq) {
ret = request_irq(priv->wol_irq, stmmac_interrupt,
IRQF_SHARED, dev->name, dev);
if (unlikely(ret < 0)) {
pr_err("%s: ERROR: allocating the WoL IRQ %d (%d)\n",
__func__, priv->wol_irq, ret);
goto wolirq_error;
}
}
/* Request the IRQ lines */
if (priv->lpi_irq != -ENXIO) {
ret = request_irq(priv->lpi_irq, stmmac_interrupt, IRQF_SHARED,
dev->name, dev);
if (unlikely(ret < 0)) {
pr_err("%s: ERROR: allocating the LPI IRQ %d (%d)\n",
__func__, priv->lpi_irq, ret);
goto lpiirq_error;
}
}
napi_enable(&priv->napi);
netif_start_queue(dev);
return 0;
lpiirq_error:
if (priv->wol_irq != dev->irq)
free_irq(priv->wol_irq, dev);
wolirq_error:
free_irq(dev->irq, dev);
init_error:
free_dma_desc_resources(priv);
dma_desc_error:
if (priv->phydev)
phy_disconnect(priv->phydev);
phy_error:
clk_disable_unprepare(priv->stmmac_clk);
return ret;
}
/**
* stmmac_release - close entry point of the driver
* @dev : device pointer.
* Description:
* This is the stop entry point of the driver.
*/
static int stmmac_release(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
if (priv->eee_enabled)
del_timer_sync(&priv->eee_ctrl_timer);
/* Stop and disconnect the PHY */
if (priv->phydev) {
phy_stop(priv->phydev);
phy_disconnect(priv->phydev);
priv->phydev = NULL;
}
netif_stop_queue(dev);
napi_disable(&priv->napi);
del_timer_sync(&priv->txtimer);
/* Free the IRQ lines */
free_irq(dev->irq, dev);
if (priv->wol_irq != dev->irq)
free_irq(priv->wol_irq, dev);
if (priv->lpi_irq != -ENXIO)
free_irq(priv->lpi_irq, dev);
/* Stop TX/RX DMA and clear the descriptors */
priv->hw->dma->stop_tx(priv->ioaddr);
priv->hw->dma->stop_rx(priv->ioaddr);
/* Release and free the Rx/Tx resources */
free_dma_desc_resources(priv);
/* Disable the MAC Rx/Tx */
stmmac_set_mac(priv->ioaddr, false);
netif_carrier_off(dev);
#ifdef CONFIG_STMMAC_DEBUG_FS
stmmac_exit_fs();
#endif
stmmac_release_ptp(priv);
return 0;
}
/**
* stmmac_xmit: Tx entry point of the driver
* @skb : the socket buffer
* @dev : device pointer
* Description : this is the tx entry point of the driver.
* It programs the chain or the ring and supports oversized frames
* and SG feature.
*/
static netdev_tx_t stmmac_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
unsigned int txsize = priv->dma_tx_size;
unsigned int entry;
int i, csum_insertion = 0, is_jumbo = 0;
int nfrags = skb_shinfo(skb)->nr_frags;
struct dma_desc *desc, *first;
unsigned int nopaged_len = skb_headlen(skb);
if (unlikely(stmmac_tx_avail(priv) < nfrags + 1)) {
if (!netif_queue_stopped(dev)) {
netif_stop_queue(dev);
/* This is a hard error, log it. */
pr_err("%s: Tx Ring full when queue awake\n", __func__);
}
return NETDEV_TX_BUSY;
}
spin_lock(&priv->tx_lock);
if (priv->tx_path_in_lpi_mode)
stmmac_disable_eee_mode(priv);
entry = priv->cur_tx % txsize;
csum_insertion = (skb->ip_summed == CHECKSUM_PARTIAL);
if (priv->extend_desc)
desc = (struct dma_desc *)(priv->dma_etx + entry);
else
desc = priv->dma_tx + entry;
first = desc;
/* To program the descriptors according to the size of the frame */
if (priv->mode == STMMAC_RING_MODE) {
is_jumbo = priv->hw->ring->is_jumbo_frm(skb->len,
priv->plat->enh_desc);
if (unlikely(is_jumbo))
entry = priv->hw->ring->jumbo_frm(priv, skb,
csum_insertion);
} else {
is_jumbo = priv->hw->chain->is_jumbo_frm(skb->len,
priv->plat->enh_desc);
if (unlikely(is_jumbo))
entry = priv->hw->chain->jumbo_frm(priv, skb,
csum_insertion);
}
if (likely(!is_jumbo)) {
desc->des2 = dma_map_single(priv->device, skb->data,
nopaged_len, DMA_TO_DEVICE);
priv->tx_skbuff_dma[entry] = desc->des2;
priv->hw->desc->prepare_tx_desc(desc, 1, nopaged_len,
csum_insertion, priv->mode);
} else
desc = first;
for (i = 0; i < nfrags; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
int len = skb_frag_size(frag);
priv->tx_skbuff[entry] = NULL;
entry = (++priv->cur_tx) % txsize;
if (priv->extend_desc)
desc = (struct dma_desc *)(priv->dma_etx + entry);
else
desc = priv->dma_tx + entry;
desc->des2 = skb_frag_dma_map(priv->device, frag, 0, len,
DMA_TO_DEVICE);
priv->tx_skbuff_dma[entry] = desc->des2;
priv->hw->desc->prepare_tx_desc(desc, 0, len, csum_insertion,
priv->mode);
wmb();
priv->hw->desc->set_tx_owner(desc);
wmb();
}
priv->tx_skbuff[entry] = skb;
/* Finalize the latest segment. */
priv->hw->desc->close_tx_desc(desc);
wmb();
/* According to the coalesce parameter the IC bit for the latest
* segment could be reset and the timer re-started to invoke the
* stmmac_tx function. This approach takes care about the fragments.
*/
priv->tx_count_frames += nfrags + 1;
if (priv->tx_coal_frames > priv->tx_count_frames) {
priv->hw->desc->clear_tx_ic(desc);
priv->xstats.tx_reset_ic_bit++;
mod_timer(&priv->txtimer,
STMMAC_COAL_TIMER(priv->tx_coal_timer));
} else
priv->tx_count_frames = 0;
/* To avoid raise condition */
priv->hw->desc->set_tx_owner(first);
wmb();
priv->cur_tx++;
if (netif_msg_pktdata(priv)) {
pr_debug("%s: curr %d dirty=%d entry=%d, first=%p, nfrags=%d",
__func__, (priv->cur_tx % txsize),
(priv->dirty_tx % txsize), entry, first, nfrags);
if (priv->extend_desc)
stmmac_display_ring((void *)priv->dma_etx, txsize, 1);
else
stmmac_display_ring((void *)priv->dma_tx, txsize, 0);
pr_debug(">>> frame to be transmitted: ");
print_pkt(skb->data, skb->len);
}
if (unlikely(stmmac_tx_avail(priv) <= (MAX_SKB_FRAGS + 1))) {
if (netif_msg_hw(priv))
pr_debug("%s: stop transmitted packets\n", __func__);
netif_stop_queue(dev);
}
dev->stats.tx_bytes += skb->len;
if (unlikely((skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP) &&
priv->hwts_tx_en)) {
/* declare that device is doing timestamping */
skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
priv->hw->desc->enable_tx_timestamp(first);
}
if (!priv->hwts_tx_en)
skb_tx_timestamp(skb);
priv->hw->dma->enable_dma_transmission(priv->ioaddr);
spin_unlock(&priv->tx_lock);
return NETDEV_TX_OK;
}
static void stmmac_rx_vlan(struct net_device *dev, struct sk_buff *skb)
{
struct ethhdr *ehdr;
u16 vlanid;
if ((dev->features & NETIF_F_HW_VLAN_CTAG_RX) ==
NETIF_F_HW_VLAN_CTAG_RX &&
!__vlan_get_tag(skb, &vlanid)) {
/* pop the vlan tag */
ehdr = (struct ethhdr *)skb->data;
memmove(skb->data + VLAN_HLEN, ehdr, ETH_ALEN * 2);
skb_pull(skb, VLAN_HLEN);
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vlanid);
}
}
/**
* stmmac_rx_refill: refill used skb preallocated buffers
* @priv: driver private structure
* Description : this is to reallocate the skb for the reception process
* that is based on zero-copy.
*/
static inline void stmmac_rx_refill(struct stmmac_priv *priv)
{
unsigned int rxsize = priv->dma_rx_size;
int bfsize = priv->dma_buf_sz;
for (; priv->cur_rx - priv->dirty_rx > 0; priv->dirty_rx++) {
unsigned int entry = priv->dirty_rx % rxsize;
struct dma_desc *p;
if (priv->extend_desc)
p = (struct dma_desc *)(priv->dma_erx + entry);
else
p = priv->dma_rx + entry;
if (likely(priv->rx_skbuff[entry] == NULL)) {
struct sk_buff *skb;
skb = netdev_alloc_skb_ip_align(priv->dev, bfsize);
if (unlikely(skb == NULL))
break;
priv->rx_skbuff[entry] = skb;
priv->rx_skbuff_dma[entry] =
dma_map_single(priv->device, skb->data, bfsize,
DMA_FROM_DEVICE);
p->des2 = priv->rx_skbuff_dma[entry];
priv->hw->ring->refill_desc3(priv, p);
if (netif_msg_rx_status(priv))
pr_debug("\trefill entry #%d\n", entry);
}
wmb();
priv->hw->desc->set_rx_owner(p);
wmb();
}
}
/**
* stmmac_rx_refill: refill used skb preallocated buffers
* @priv: driver private structure
* @limit: napi bugget.
* Description : this the function called by the napi poll method.
* It gets all the frames inside the ring.
*/
static int stmmac_rx(struct stmmac_priv *priv, int limit)
{
unsigned int rxsize = priv->dma_rx_size;
unsigned int entry = priv->cur_rx % rxsize;
unsigned int next_entry;
unsigned int count = 0;
int coe = priv->plat->rx_coe;
if (netif_msg_rx_status(priv)) {
pr_debug("%s: descriptor ring:\n", __func__);
if (priv->extend_desc)
stmmac_display_ring((void *)priv->dma_erx, rxsize, 1);
else
stmmac_display_ring((void *)priv->dma_rx, rxsize, 0);
}
while (count < limit) {
int status;
struct dma_desc *p;
if (priv->extend_desc)
p = (struct dma_desc *)(priv->dma_erx + entry);
else
p = priv->dma_rx + entry;
if (priv->hw->desc->get_rx_owner(p))
break;
count++;
next_entry = (++priv->cur_rx) % rxsize;
if (priv->extend_desc)
prefetch(priv->dma_erx + next_entry);
else
prefetch(priv->dma_rx + next_entry);
/* read the status of the incoming frame */
status = priv->hw->desc->rx_status(&priv->dev->stats,
&priv->xstats, p);
if ((priv->extend_desc) && (priv->hw->desc->rx_extended_status))
priv->hw->desc->rx_extended_status(&priv->dev->stats,
&priv->xstats,
priv->dma_erx +
entry);
if (unlikely(status == discard_frame)) {
priv->dev->stats.rx_errors++;
if (priv->hwts_rx_en && !priv->extend_desc) {
/* DESC2 & DESC3 will be overwitten by device
* with timestamp value, hence reinitialize
* them in stmmac_rx_refill() function so that
* device can reuse it.
*/
priv->rx_skbuff[entry] = NULL;
dma_unmap_single(priv->device,
priv->rx_skbuff_dma[entry],
priv->dma_buf_sz,
DMA_FROM_DEVICE);
}
} else {
struct sk_buff *skb;
int frame_len;
frame_len = priv->hw->desc->get_rx_frame_len(p, coe);
/* ACS is set; GMAC core strips PAD/FCS for IEEE 802.3
* Type frames (LLC/LLC-SNAP)
*/
if (unlikely(status != llc_snap))
frame_len -= ETH_FCS_LEN;
if (netif_msg_rx_status(priv)) {
pr_debug("\tdesc: %p [entry %d] buff=0x%x\n",
p, entry, p->des2);
if (frame_len > ETH_FRAME_LEN)
pr_debug("\tframe size %d, COE: %d\n",
frame_len, status);
}
skb = priv->rx_skbuff[entry];
if (unlikely(!skb)) {
pr_err("%s: Inconsistent Rx descriptor chain\n",
priv->dev->name);
priv->dev->stats.rx_dropped++;
break;
}
prefetch(skb->data - NET_IP_ALIGN);
priv->rx_skbuff[entry] = NULL;
stmmac_get_rx_hwtstamp(priv, entry, skb);
skb_put(skb, frame_len);
dma_unmap_single(priv->device,
priv->rx_skbuff_dma[entry],
priv->dma_buf_sz, DMA_FROM_DEVICE);
if (netif_msg_pktdata(priv)) {
pr_debug("frame received (%dbytes)", frame_len);
print_pkt(skb->data, frame_len);
}
stmmac_rx_vlan(priv->dev, skb);
skb->protocol = eth_type_trans(skb, priv->dev);
if (unlikely(!coe))
skb_checksum_none_assert(skb);
else
skb->ip_summed = CHECKSUM_UNNECESSARY;
napi_gro_receive(&priv->napi, skb);
priv->dev->stats.rx_packets++;
priv->dev->stats.rx_bytes += frame_len;
}
entry = next_entry;
}
stmmac_rx_refill(priv);
priv->xstats.rx_pkt_n += count;
return count;
}
/**
* stmmac_poll - stmmac poll method (NAPI)
* @napi : pointer to the napi structure.
* @budget : maximum number of packets that the current CPU can receive from
* all interfaces.
* Description :
* To look at the incoming frames and clear the tx resources.
*/
static int stmmac_poll(struct napi_struct *napi, int budget)
{
struct stmmac_priv *priv = container_of(napi, struct stmmac_priv, napi);
int work_done = 0;
priv->xstats.napi_poll++;
stmmac_tx_clean(priv);
work_done = stmmac_rx(priv, budget);
if (work_done < budget) {
napi_complete(napi);
stmmac_enable_dma_irq(priv);
}
return work_done;
}
/**
* stmmac_tx_timeout
* @dev : Pointer to net device structure
* Description: this function is called when a packet transmission fails to
* complete within a reasonable time. The driver will mark the error in the
* netdev structure and arrange for the device to be reset to a sane state
* in order to transmit a new packet.
*/
static void stmmac_tx_timeout(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
/* Clear Tx resources and restart transmitting again */
stmmac_tx_err(priv);
}
/* Configuration changes (passed on by ifconfig) */
static int stmmac_config(struct net_device *dev, struct ifmap *map)
{
if (dev->flags & IFF_UP) /* can't act on a running interface */
return -EBUSY;
/* Don't allow changing the I/O address */
if (map->base_addr != dev->base_addr) {
pr_warn("%s: can't change I/O address\n", dev->name);
return -EOPNOTSUPP;
}
/* Don't allow changing the IRQ */
if (map->irq != dev->irq) {
pr_warn("%s: not change IRQ number %d\n", dev->name, dev->irq);
return -EOPNOTSUPP;
}
return 0;
}
/**
* stmmac_set_rx_mode - entry point for multicast addressing
* @dev : pointer to the device structure
* Description:
* This function is a driver entry point which gets called by the kernel
* whenever multicast addresses must be enabled/disabled.
* Return value:
* void.
*/
static void stmmac_set_rx_mode(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
spin_lock(&priv->lock);
priv->hw->mac->set_filter(dev, priv->synopsys_id);
spin_unlock(&priv->lock);
}
/**
* stmmac_change_mtu - entry point to change MTU size for the device.
* @dev : device pointer.
* @new_mtu : the new MTU size for the device.
* Description: the Maximum Transfer Unit (MTU) is used by the network layer
* to drive packet transmission. Ethernet has an MTU of 1500 octets
* (ETH_DATA_LEN). This value can be changed with ifconfig.
* Return value:
* 0 on success and an appropriate (-)ve integer as defined in errno.h
* file on failure.
*/
static int stmmac_change_mtu(struct net_device *dev, int new_mtu)
{
struct stmmac_priv *priv = netdev_priv(dev);
int max_mtu;
if (netif_running(dev)) {
pr_err("%s: must be stopped to change its MTU\n", dev->name);
return -EBUSY;
}
if (priv->plat->enh_desc)
max_mtu = JUMBO_LEN;
else
max_mtu = SKB_MAX_HEAD(NET_SKB_PAD + NET_IP_ALIGN);
if (priv->plat->maxmtu < max_mtu)
max_mtu = priv->plat->maxmtu;
if ((new_mtu < 46) || (new_mtu > max_mtu)) {
pr_err("%s: invalid MTU, max MTU is: %d\n", dev->name, max_mtu);
return -EINVAL;
}
dev->mtu = new_mtu;
netdev_update_features(dev);
return 0;
}
static netdev_features_t stmmac_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct stmmac_priv *priv = netdev_priv(dev);
if (priv->plat->rx_coe == STMMAC_RX_COE_NONE)
features &= ~NETIF_F_RXCSUM;
else if (priv->plat->rx_coe == STMMAC_RX_COE_TYPE1)
features &= ~NETIF_F_IPV6_CSUM;
if (!priv->plat->tx_coe)
features &= ~NETIF_F_ALL_CSUM;
/* Some GMAC devices have a bugged Jumbo frame support that
* needs to have the Tx COE disabled for oversized frames
* (due to limited buffer sizes). In this case we disable
* the TX csum insertionin the TDES and not use SF.
*/
if (priv->plat->bugged_jumbo && (dev->mtu > ETH_DATA_LEN))
features &= ~NETIF_F_ALL_CSUM;
return features;
}
/**
* stmmac_interrupt - main ISR
* @irq: interrupt number.
* @dev_id: to pass the net device pointer.
* Description: this is the main driver interrupt service routine.
* It calls the DMA ISR and also the core ISR to manage PMT, MMC, LPI
* interrupts.
*/
static irqreturn_t stmmac_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *)dev_id;
struct stmmac_priv *priv = netdev_priv(dev);
if (priv->irq_wake)
pm_wakeup_event(priv->device, 0);
if (unlikely(!dev)) {
pr_err("%s: invalid dev pointer\n", __func__);
return IRQ_NONE;
}
/* To handle GMAC own interrupts */
if (priv->plat->has_gmac) {
int status = priv->hw->mac->host_irq_status((void __iomem *)
dev->base_addr,
&priv->xstats);
if (unlikely(status)) {
/* For LPI we need to save the tx status */
if (status & CORE_IRQ_TX_PATH_IN_LPI_MODE)
priv->tx_path_in_lpi_mode = true;
if (status & CORE_IRQ_TX_PATH_EXIT_LPI_MODE)
priv->tx_path_in_lpi_mode = false;
}
}
/* To handle DMA interrupts */
stmmac_dma_interrupt(priv);
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/* Polling receive - used by NETCONSOLE and other diagnostic tools
* to allow network I/O with interrupts disabled.
*/
static void stmmac_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
stmmac_interrupt(dev->irq, dev);
enable_irq(dev->irq);
}
#endif
/**
* stmmac_ioctl - Entry point for the Ioctl
* @dev: Device pointer.
* @rq: An IOCTL specefic structure, that can contain a pointer to
* a proprietary structure used to pass information to the driver.
* @cmd: IOCTL command
* Description:
* Currently it supports the phy_mii_ioctl(...) and HW time stamping.
*/
static int stmmac_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct stmmac_priv *priv = netdev_priv(dev);
int ret = -EOPNOTSUPP;
if (!netif_running(dev))
return -EINVAL;
switch (cmd) {
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
if (!priv->phydev)
return -EINVAL;
ret = phy_mii_ioctl(priv->phydev, rq, cmd);
break;
case SIOCSHWTSTAMP:
ret = stmmac_hwtstamp_ioctl(dev, rq);
break;
default:
break;
}
return ret;
}
#ifdef CONFIG_STMMAC_DEBUG_FS
static struct dentry *stmmac_fs_dir;
static struct dentry *stmmac_rings_status;
static struct dentry *stmmac_dma_cap;
static void sysfs_display_ring(void *head, int size, int extend_desc,
struct seq_file *seq)
{
int i;
struct dma_extended_desc *ep = (struct dma_extended_desc *)head;
struct dma_desc *p = (struct dma_desc *)head;
for (i = 0; i < size; i++) {
u64 x;
if (extend_desc) {
x = *(u64 *) ep;
seq_printf(seq, "%d [0x%x]: 0x%x 0x%x 0x%x 0x%x\n",
i, (unsigned int)virt_to_phys(ep),
(unsigned int)x, (unsigned int)(x >> 32),
ep->basic.des2, ep->basic.des3);
ep++;
} else {
x = *(u64 *) p;
seq_printf(seq, "%d [0x%x]: 0x%x 0x%x 0x%x 0x%x\n",
i, (unsigned int)virt_to_phys(ep),
(unsigned int)x, (unsigned int)(x >> 32),
p->des2, p->des3);
p++;
}
seq_printf(seq, "\n");
}
}
static int stmmac_sysfs_ring_read(struct seq_file *seq, void *v)
{
struct net_device *dev = seq->private;
struct stmmac_priv *priv = netdev_priv(dev);
unsigned int txsize = priv->dma_tx_size;
unsigned int rxsize = priv->dma_rx_size;
if (priv->extend_desc) {
seq_printf(seq, "Extended RX descriptor ring:\n");
sysfs_display_ring((void *)priv->dma_erx, rxsize, 1, seq);
seq_printf(seq, "Extended TX descriptor ring:\n");
sysfs_display_ring((void *)priv->dma_etx, txsize, 1, seq);
} else {
seq_printf(seq, "RX descriptor ring:\n");
sysfs_display_ring((void *)priv->dma_rx, rxsize, 0, seq);
seq_printf(seq, "TX descriptor ring:\n");
sysfs_display_ring((void *)priv->dma_tx, txsize, 0, seq);
}
return 0;
}
static int stmmac_sysfs_ring_open(struct inode *inode, struct file *file)
{
return single_open(file, stmmac_sysfs_ring_read, inode->i_private);
}
static const struct file_operations stmmac_rings_status_fops = {
.owner = THIS_MODULE,
.open = stmmac_sysfs_ring_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int stmmac_sysfs_dma_cap_read(struct seq_file *seq, void *v)
{
struct net_device *dev = seq->private;
struct stmmac_priv *priv = netdev_priv(dev);
if (!priv->hw_cap_support) {
seq_printf(seq, "DMA HW features not supported\n");
return 0;
}
seq_printf(seq, "==============================\n");
seq_printf(seq, "\tDMA HW features\n");
seq_printf(seq, "==============================\n");
seq_printf(seq, "\t10/100 Mbps %s\n",
(priv->dma_cap.mbps_10_100) ? "Y" : "N");
seq_printf(seq, "\t1000 Mbps %s\n",
(priv->dma_cap.mbps_1000) ? "Y" : "N");
seq_printf(seq, "\tHalf duple %s\n",
(priv->dma_cap.half_duplex) ? "Y" : "N");
seq_printf(seq, "\tHash Filter: %s\n",
(priv->dma_cap.hash_filter) ? "Y" : "N");
seq_printf(seq, "\tMultiple MAC address registers: %s\n",
(priv->dma_cap.multi_addr) ? "Y" : "N");
seq_printf(seq, "\tPCS (TBI/SGMII/RTBI PHY interfatces): %s\n",
(priv->dma_cap.pcs) ? "Y" : "N");
seq_printf(seq, "\tSMA (MDIO) Interface: %s\n",
(priv->dma_cap.sma_mdio) ? "Y" : "N");
seq_printf(seq, "\tPMT Remote wake up: %s\n",
(priv->dma_cap.pmt_remote_wake_up) ? "Y" : "N");
seq_printf(seq, "\tPMT Magic Frame: %s\n",
(priv->dma_cap.pmt_magic_frame) ? "Y" : "N");
seq_printf(seq, "\tRMON module: %s\n",
(priv->dma_cap.rmon) ? "Y" : "N");
seq_printf(seq, "\tIEEE 1588-2002 Time Stamp: %s\n",
(priv->dma_cap.time_stamp) ? "Y" : "N");
seq_printf(seq, "\tIEEE 1588-2008 Advanced Time Stamp:%s\n",
(priv->dma_cap.atime_stamp) ? "Y" : "N");
seq_printf(seq, "\t802.3az - Energy-Efficient Ethernet (EEE) %s\n",
(priv->dma_cap.eee) ? "Y" : "N");
seq_printf(seq, "\tAV features: %s\n", (priv->dma_cap.av) ? "Y" : "N");
seq_printf(seq, "\tChecksum Offload in TX: %s\n",
(priv->dma_cap.tx_coe) ? "Y" : "N");
seq_printf(seq, "\tIP Checksum Offload (type1) in RX: %s\n",
(priv->dma_cap.rx_coe_type1) ? "Y" : "N");
seq_printf(seq, "\tIP Checksum Offload (type2) in RX: %s\n",
(priv->dma_cap.rx_coe_type2) ? "Y" : "N");
seq_printf(seq, "\tRXFIFO > 2048bytes: %s\n",
(priv->dma_cap.rxfifo_over_2048) ? "Y" : "N");
seq_printf(seq, "\tNumber of Additional RX channel: %d\n",
priv->dma_cap.number_rx_channel);
seq_printf(seq, "\tNumber of Additional TX channel: %d\n",
priv->dma_cap.number_tx_channel);
seq_printf(seq, "\tEnhanced descriptors: %s\n",
(priv->dma_cap.enh_desc) ? "Y" : "N");
return 0;
}
static int stmmac_sysfs_dma_cap_open(struct inode *inode, struct file *file)
{
return single_open(file, stmmac_sysfs_dma_cap_read, inode->i_private);
}
static const struct file_operations stmmac_dma_cap_fops = {
.owner = THIS_MODULE,
.open = stmmac_sysfs_dma_cap_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int stmmac_init_fs(struct net_device *dev)
{
/* Create debugfs entries */
stmmac_fs_dir = debugfs_create_dir(STMMAC_RESOURCE_NAME, NULL);
if (!stmmac_fs_dir || IS_ERR(stmmac_fs_dir)) {
pr_err("ERROR %s, debugfs create directory failed\n",
STMMAC_RESOURCE_NAME);
return -ENOMEM;
}
/* Entry to report DMA RX/TX rings */
stmmac_rings_status = debugfs_create_file("descriptors_status",
S_IRUGO, stmmac_fs_dir, dev,
&stmmac_rings_status_fops);
if (!stmmac_rings_status || IS_ERR(stmmac_rings_status)) {
pr_info("ERROR creating stmmac ring debugfs file\n");
debugfs_remove(stmmac_fs_dir);
return -ENOMEM;
}
/* Entry to report the DMA HW features */
stmmac_dma_cap = debugfs_create_file("dma_cap", S_IRUGO, stmmac_fs_dir,
dev, &stmmac_dma_cap_fops);
if (!stmmac_dma_cap || IS_ERR(stmmac_dma_cap)) {
pr_info("ERROR creating stmmac MMC debugfs file\n");
debugfs_remove(stmmac_rings_status);
debugfs_remove(stmmac_fs_dir);
return -ENOMEM;
}
return 0;
}
static void stmmac_exit_fs(void)
{
debugfs_remove(stmmac_rings_status);
debugfs_remove(stmmac_dma_cap);
debugfs_remove(stmmac_fs_dir);
}
#endif /* CONFIG_STMMAC_DEBUG_FS */
static const struct net_device_ops stmmac_netdev_ops = {
.ndo_open = stmmac_open,
.ndo_start_xmit = stmmac_xmit,
.ndo_stop = stmmac_release,
.ndo_change_mtu = stmmac_change_mtu,
.ndo_fix_features = stmmac_fix_features,
.ndo_set_rx_mode = stmmac_set_rx_mode,
.ndo_tx_timeout = stmmac_tx_timeout,
.ndo_do_ioctl = stmmac_ioctl,
.ndo_set_config = stmmac_config,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = stmmac_poll_controller,
#endif
.ndo_set_mac_address = eth_mac_addr,
};
/**
* stmmac_hw_init - Init the MAC device
* @priv: driver private structure
* Description: this function detects which MAC device
* (GMAC/MAC10-100) has to attached, checks the HW capability
* (if supported) and sets the driver's features (for example
* to use the ring or chaine mode or support the normal/enh
* descriptor structure).
*/
static int stmmac_hw_init(struct stmmac_priv *priv)
{
int ret;
struct mac_device_info *mac;
/* Identify the MAC HW device */
if (priv->plat->has_gmac) {
priv->dev->priv_flags |= IFF_UNICAST_FLT;
mac = dwmac1000_setup(priv->ioaddr);
} else {
mac = dwmac100_setup(priv->ioaddr);
}
if (!mac)
return -ENOMEM;
priv->hw = mac;
/* Get and dump the chip ID */
priv->synopsys_id = stmmac_get_synopsys_id(priv);
/* To use the chained or ring mode */
if (chain_mode) {
priv->hw->chain = &chain_mode_ops;
pr_info(" Chain mode enabled\n");
priv->mode = STMMAC_CHAIN_MODE;
} else {
priv->hw->ring = &ring_mode_ops;
pr_info(" Ring mode enabled\n");
priv->mode = STMMAC_RING_MODE;
}
/* Get the HW capability (new GMAC newer than 3.50a) */
priv->hw_cap_support = stmmac_get_hw_features(priv);
if (priv->hw_cap_support) {
pr_info(" DMA HW capability register supported");
/* We can override some gmac/dma configuration fields: e.g.
* enh_desc, tx_coe (e.g. that are passed through the
* platform) with the values from the HW capability
* register (if supported).
*/
priv->plat->enh_desc = priv->dma_cap.enh_desc;
priv->plat->pmt = priv->dma_cap.pmt_remote_wake_up;
priv->plat->tx_coe = priv->dma_cap.tx_coe;
if (priv->dma_cap.rx_coe_type2)
priv->plat->rx_coe = STMMAC_RX_COE_TYPE2;
else if (priv->dma_cap.rx_coe_type1)
priv->plat->rx_coe = STMMAC_RX_COE_TYPE1;
} else
pr_info(" No HW DMA feature register supported");
/* To use alternate (extended) or normal descriptor structures */
stmmac_selec_desc_mode(priv);
ret = priv->hw->mac->rx_ipc(priv->ioaddr);
if (!ret) {
pr_warn(" RX IPC Checksum Offload not configured.\n");
priv->plat->rx_coe = STMMAC_RX_COE_NONE;
}
if (priv->plat->rx_coe)
pr_info(" RX Checksum Offload Engine supported (type %d)\n",
priv->plat->rx_coe);
if (priv->plat->tx_coe)
pr_info(" TX Checksum insertion supported\n");
if (priv->plat->pmt) {
pr_info(" Wake-Up On Lan supported\n");
device_set_wakeup_capable(priv->device, 1);
}
return 0;
}
/**
* stmmac_dvr_probe
* @device: device pointer
* @plat_dat: platform data pointer
* @addr: iobase memory address
* Description: this is the main probe function used to
* call the alloc_etherdev, allocate the priv structure.
*/
struct stmmac_priv *stmmac_dvr_probe(struct device *device,
struct plat_stmmacenet_data *plat_dat,
void __iomem *addr)
{
int ret = 0;
struct net_device *ndev = NULL;
struct stmmac_priv *priv;
ndev = alloc_etherdev(sizeof(struct stmmac_priv));
if (!ndev)
return NULL;
SET_NETDEV_DEV(ndev, device);
priv = netdev_priv(ndev);
priv->device = device;
priv->dev = ndev;
ether_setup(ndev);
stmmac_set_ethtool_ops(ndev);
priv->pause = pause;
priv->plat = plat_dat;
priv->ioaddr = addr;
priv->dev->base_addr = (unsigned long)addr;
/* Verify driver arguments */
stmmac_verify_args();
/* Override with kernel parameters if supplied XXX CRS XXX
* this needs to have multiple instances
*/
if ((phyaddr >= 0) && (phyaddr <= 31))
priv->plat->phy_addr = phyaddr;
priv->stmmac_clk = devm_clk_get(priv->device, STMMAC_RESOURCE_NAME);
if (IS_ERR(priv->stmmac_clk)) {
dev_warn(priv->device, "%s: warning: cannot get CSR clock\n",
__func__);
ret = PTR_ERR(priv->stmmac_clk);
goto error_clk_get;
}
clk_prepare_enable(priv->stmmac_clk);
priv->stmmac_rst = devm_reset_control_get(priv->device,
STMMAC_RESOURCE_NAME);
if (IS_ERR(priv->stmmac_rst)) {
if (PTR_ERR(priv->stmmac_rst) == -EPROBE_DEFER) {
ret = -EPROBE_DEFER;
goto error_hw_init;
}
dev_info(priv->device, "no reset control found\n");
priv->stmmac_rst = NULL;
}
if (priv->stmmac_rst)
reset_control_deassert(priv->stmmac_rst);
/* Init MAC and get the capabilities */
ret = stmmac_hw_init(priv);
if (ret)
goto error_hw_init;
ndev->netdev_ops = &stmmac_netdev_ops;
ndev->hw_features = NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
NETIF_F_RXCSUM;
ndev->features |= ndev->hw_features | NETIF_F_HIGHDMA;
ndev->watchdog_timeo = msecs_to_jiffies(watchdog);
#ifdef STMMAC_VLAN_TAG_USED
/* Both mac100 and gmac support receive VLAN tag detection */
ndev->features |= NETIF_F_HW_VLAN_CTAG_RX;
#endif
priv->msg_enable = netif_msg_init(debug, default_msg_level);
if (flow_ctrl)
priv->flow_ctrl = FLOW_AUTO; /* RX/TX pause on */
/* Rx Watchdog is available in the COREs newer than the 3.40.
* In some case, for example on bugged HW this feature
* has to be disable and this can be done by passing the
* riwt_off field from the platform.
*/
if ((priv->synopsys_id >= DWMAC_CORE_3_50) && (!priv->plat->riwt_off)) {
priv->use_riwt = 1;
pr_info(" Enable RX Mitigation via HW Watchdog Timer\n");
}
netif_napi_add(ndev, &priv->napi, stmmac_poll, 64);
spin_lock_init(&priv->lock);
spin_lock_init(&priv->tx_lock);
ret = register_netdev(ndev);
if (ret) {
pr_err("%s: ERROR %i registering the device\n", __func__, ret);
goto error_netdev_register;
}
/* If a specific clk_csr value is passed from the platform
* this means that the CSR Clock Range selection cannot be
* changed at run-time and it is fixed. Viceversa the driver'll try to
* set the MDC clock dynamically according to the csr actual
* clock input.
*/
if (!priv->plat->clk_csr)
stmmac_clk_csr_set(priv);
else
priv->clk_csr = priv->plat->clk_csr;
stmmac_check_pcs_mode(priv);
if (priv->pcs != STMMAC_PCS_RGMII && priv->pcs != STMMAC_PCS_TBI &&
priv->pcs != STMMAC_PCS_RTBI) {
/* MDIO bus Registration */
ret = stmmac_mdio_register(ndev);
if (ret < 0) {
pr_debug("%s: MDIO bus (id: %d) registration failed",
__func__, priv->plat->bus_id);
goto error_mdio_register;
}
}
return priv;
error_mdio_register:
unregister_netdev(ndev);
error_netdev_register:
netif_napi_del(&priv->napi);
error_hw_init:
clk_disable_unprepare(priv->stmmac_clk);
error_clk_get:
free_netdev(ndev);
return ERR_PTR(ret);
}
/**
* stmmac_dvr_remove
* @ndev: net device pointer
* Description: this function resets the TX/RX processes, disables the MAC RX/TX
* changes the link status, releases the DMA descriptor rings.
*/
int stmmac_dvr_remove(struct net_device *ndev)
{
struct stmmac_priv *priv = netdev_priv(ndev);
pr_info("%s:\n\tremoving driver", __func__);
priv->hw->dma->stop_rx(priv->ioaddr);
priv->hw->dma->stop_tx(priv->ioaddr);
stmmac_set_mac(priv->ioaddr, false);
if (priv->pcs != STMMAC_PCS_RGMII && priv->pcs != STMMAC_PCS_TBI &&
priv->pcs != STMMAC_PCS_RTBI)
stmmac_mdio_unregister(ndev);
netif_carrier_off(ndev);
unregister_netdev(ndev);
if (priv->stmmac_rst)
reset_control_assert(priv->stmmac_rst);
clk_disable_unprepare(priv->stmmac_clk);
free_netdev(ndev);
return 0;
}
#ifdef CONFIG_PM
int stmmac_suspend(struct net_device *ndev)
{
struct stmmac_priv *priv = netdev_priv(ndev);
unsigned long flags;
if (!ndev || !netif_running(ndev))
return 0;
if (priv->phydev)
phy_stop(priv->phydev);
spin_lock_irqsave(&priv->lock, flags);
netif_device_detach(ndev);
netif_stop_queue(ndev);
napi_disable(&priv->napi);
/* Stop TX/RX DMA */
priv->hw->dma->stop_tx(priv->ioaddr);
priv->hw->dma->stop_rx(priv->ioaddr);
stmmac_clear_descriptors(priv);
/* Enable Power down mode by programming the PMT regs */
if (device_may_wakeup(priv->device)) {
priv->hw->mac->pmt(priv->ioaddr, priv->wolopts);
priv->irq_wake = 1;
} else {
stmmac_set_mac(priv->ioaddr, false);
pinctrl_pm_select_sleep_state(priv->device);
/* Disable clock in case of PWM is off */
clk_disable_unprepare(priv->stmmac_clk);
}
spin_unlock_irqrestore(&priv->lock, flags);
return 0;
}
int stmmac_resume(struct net_device *ndev)
{
struct stmmac_priv *priv = netdev_priv(ndev);
unsigned long flags;
if (!netif_running(ndev))
return 0;
spin_lock_irqsave(&priv->lock, flags);
/* Power Down bit, into the PM register, is cleared
* automatically as soon as a magic packet or a Wake-up frame
* is received. Anyway, it's better to manually clear
* this bit because it can generate problems while resuming
* from another devices (e.g. serial console).
*/
if (device_may_wakeup(priv->device)) {
priv->hw->mac->pmt(priv->ioaddr, 0);
priv->irq_wake = 0;
} else {
pinctrl_pm_select_default_state(priv->device);
/* enable the clk prevously disabled */
clk_prepare_enable(priv->stmmac_clk);
/* reset the phy so that it's ready */
if (priv->mii)
stmmac_mdio_reset(priv->mii);
}
netif_device_attach(ndev);
stmmac_hw_setup(ndev);
napi_enable(&priv->napi);
netif_start_queue(ndev);
spin_unlock_irqrestore(&priv->lock, flags);
if (priv->phydev)
phy_start(priv->phydev);
return 0;
}
#endif /* CONFIG_PM */
/* Driver can be configured w/ and w/ both PCI and Platf drivers
* depending on the configuration selected.
*/
static int __init stmmac_init(void)
{
int ret;
ret = stmmac_register_platform();
if (ret)
goto err;
ret = stmmac_register_pci();
if (ret)
goto err_pci;
return 0;
err_pci:
stmmac_unregister_platform();
err:
pr_err("stmmac: driver registration failed\n");
return ret;
}
static void __exit stmmac_exit(void)
{
stmmac_unregister_platform();
stmmac_unregister_pci();
}
module_init(stmmac_init);
module_exit(stmmac_exit);
#ifndef MODULE
static int __init stmmac_cmdline_opt(char *str)
{
char *opt;
if (!str || !*str)
return -EINVAL;
while ((opt = strsep(&str, ",")) != NULL) {
if (!strncmp(opt, "debug:", 6)) {
if (kstrtoint(opt + 6, 0, &debug))
goto err;
} else if (!strncmp(opt, "phyaddr:", 8)) {
if (kstrtoint(opt + 8, 0, &phyaddr))
goto err;
} else if (!strncmp(opt, "dma_txsize:", 11)) {
if (kstrtoint(opt + 11, 0, &dma_txsize))
goto err;
} else if (!strncmp(opt, "dma_rxsize:", 11)) {
if (kstrtoint(opt + 11, 0, &dma_rxsize))
goto err;
} else if (!strncmp(opt, "buf_sz:", 7)) {
if (kstrtoint(opt + 7, 0, &buf_sz))
goto err;
} else if (!strncmp(opt, "tc:", 3)) {
if (kstrtoint(opt + 3, 0, &tc))
goto err;
} else if (!strncmp(opt, "watchdog:", 9)) {
if (kstrtoint(opt + 9, 0, &watchdog))
goto err;
} else if (!strncmp(opt, "flow_ctrl:", 10)) {
if (kstrtoint(opt + 10, 0, &flow_ctrl))
goto err;
} else if (!strncmp(opt, "pause:", 6)) {
if (kstrtoint(opt + 6, 0, &pause))
goto err;
} else if (!strncmp(opt, "eee_timer:", 10)) {
if (kstrtoint(opt + 10, 0, &eee_timer))
goto err;
} else if (!strncmp(opt, "chain_mode:", 11)) {
if (kstrtoint(opt + 11, 0, &chain_mode))
goto err;
}
}
return 0;
err:
pr_err("%s: ERROR broken module parameter conversion", __func__);
return -EINVAL;
}
__setup("stmmaceth=", stmmac_cmdline_opt);
#endif /* MODULE */
MODULE_DESCRIPTION("STMMAC 10/100/1000 Ethernet device driver");
MODULE_AUTHOR("Giuseppe Cavallaro <peppe.cavallaro@st.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
anthonyryan1/xbmc | xbmc/windowing/wayland/OptionalsReg.cpp | 27 | 1964 | /*
* Copyright (C) 2005-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "OptionalsReg.h"
//-----------------------------------------------------------------------------
// VAAPI
//-----------------------------------------------------------------------------
#if defined (HAVE_LIBVA)
#include <va/va_wayland.h>
#include "cores/VideoPlayer/DVDCodecs/Video/VAAPI.h"
#include "cores/VideoPlayer/VideoRenderers/HwDecRender/RendererVAAPIGL.h"
class CVaapiProxy : public VAAPI::IVaapiWinSystem
{
public:
CVaapiProxy() = default;
virtual ~CVaapiProxy() = default;
VADisplay GetVADisplay() override { return vaGetDisplayWl(dpy); };
void *GetEGLDisplay() override { return eglDisplay; };
wl_display *dpy;
void *eglDisplay;
};
CVaapiProxy* WAYLAND::VaapiProxyCreate()
{
return new CVaapiProxy();
}
void WAYLAND::VaapiProxyDelete(CVaapiProxy *proxy)
{
delete proxy;
}
void WAYLAND::VaapiProxyConfig(CVaapiProxy *proxy, void *dpy, void *eglDpy)
{
proxy->dpy = static_cast<wl_display*>(dpy);
proxy->eglDisplay = eglDpy;
}
void WAYLAND::VAAPIRegister(CVaapiProxy *winSystem, bool deepColor)
{
VAAPI::CDecoder::Register(winSystem, deepColor);
}
void WAYLAND::VAAPIRegisterRender(CVaapiProxy *winSystem, bool &general, bool &deepColor)
{
EGLDisplay eglDpy = winSystem->eglDisplay;
VADisplay vaDpy = vaGetDisplayWl(winSystem->dpy);
CRendererVAAPI::Register(winSystem, vaDpy, eglDpy, general, deepColor);
}
#else
class CVaapiProxy
{
};
CVaapiProxy* WAYLAND::VaapiProxyCreate()
{
return nullptr;
}
void WAYLAND::VaapiProxyDelete(CVaapiProxy *proxy)
{
}
void WAYLAND::VaapiProxyConfig(CVaapiProxy *proxy, void *dpy, void *eglDpy)
{
}
void WAYLAND::VAAPIRegister(CVaapiProxy *winSystem, bool deepColor)
{
}
void WAYLAND::VAAPIRegisterRender(CVaapiProxy *winSystem, bool &general, bool &deepColor)
{
}
#endif
| gpl-2.0 |
bilalliberty/SebastianFM-kernel | drivers/misc/time_helper.c | 539 | 4986 | #include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/cdev.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <linux/time_helper.h>
MODULE_LICENSE("Dual BSD/GPL");
struct time_helper {
struct cdev dev;
};
static int time_helper_major = 0;
static int time_helper_minor = 0;
static int time_helper_nr_devs = 1;
static struct class* time_helper_class = NULL;
static struct time_helper *time_helper_dev=NULL;
static long time_helper_ioctl(struct file *filp, unsigned int cmd, unsigned long arg);
static int time_helper_open(struct inode* inode, struct file* filp);
static int time_helper_release(struct inode* inode, struct file* filp);
static struct file_operations time_helper_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = time_helper_ioctl,
.open = time_helper_open,
.release = time_helper_release,
};
static int time_helper_open(struct inode* inode, struct file* filp)
{
struct time_helper *dev;
dev = container_of(inode->i_cdev, struct time_helper, dev);
filp->private_data = dev;
return 0;
}
static int time_helper_release(struct inode* inode, struct file* filp)
{
return 0;
}
static long time_helper_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
int retval = 0;
if (_IOC_TYPE(cmd) != TIME_HELPER_IOC_MAGIC) return -ENOTTY;
if (_IOC_NR(cmd) > TIME_HELPER_IOC_MAXNR) return -ENOTTY;
switch (cmd) {
case TIME_HELPER_IOCRESET:
break;
case TIME_HELPER_IOCXMONOTONIC2REALTIME:
{
struct timespec mono_ts;
struct timespec boot_time;
if (copy_from_user(&mono_ts, (struct timespec __user *)arg, sizeof(struct timespec))) {
printk(KERN_ALERT "copy_from_user fail\n");
return -EFAULT;
}
getboottime(&boot_time);
monotonic_to_bootbased(&mono_ts);
mono_ts = timespec_add(mono_ts, boot_time);
if (copy_to_user((struct timespec __user *)arg, &mono_ts, sizeof(struct timespec))) {
printk(KERN_ALERT "copy_to_user fail\n");
return -EFAULT;
}
}
break;
default:
return -ENOTTY;
}
return retval;
}
static int __time_helper_setup_dev(struct time_helper* dev)
{
int err;
dev_t devno = MKDEV(time_helper_major, time_helper_minor);
memset(dev, 0, sizeof(struct time_helper));
cdev_init(&(dev->dev), &time_helper_fops);
dev->dev.owner = THIS_MODULE;
dev->dev.ops = &time_helper_fops;
err = cdev_add(&(dev->dev), devno, 1);
if(err) {
return err;
}
return 0;
}
static int time_helper_init(void)
{
int err=-1;
dev_t dev=0;
if (time_helper_major) {
dev = MKDEV(time_helper_major, time_helper_minor);
err = register_chrdev_region(dev, time_helper_nr_devs, "time_helper");
} else {
err = alloc_chrdev_region(&dev, time_helper_minor, time_helper_nr_devs, "time_helper");
time_helper_major = MAJOR(dev);
}
if (err < 0) {
printk(KERN_WARNING "time_helper: can't get major %d\n", time_helper_major);
goto fail;
}
time_helper_dev = (struct time_helper *)kmalloc(sizeof(struct time_helper), GFP_KERNEL);
if(!time_helper_dev) {
err = -ENOMEM;
printk(KERN_ALERT"Failed to alloc hello_dev.\n");
goto unregister;
}
err = __time_helper_setup_dev(time_helper_dev);
if(err) {
printk(KERN_ALERT"Failed to setup dev: %d.\n", err);
goto cleanup;
}
time_helper_class = class_create(THIS_MODULE, TIME_HELPER_DEVICE_CLASS_NAME);
if(IS_ERR(time_helper_class)) {
err = PTR_ERR(time_helper_class);
printk(KERN_ALERT"Failed to create time_helper class.\n");
goto destroy_cdev;
}
{
struct device* temp = NULL;
temp = device_create(time_helper_class, NULL, dev, "%s", TIME_HELPER_DEVICE_FILE_NAME);
if(IS_ERR(temp)) {
err = PTR_ERR(temp);
printk(KERN_ALERT"Failed to create time_helper device.");
goto destroy_class;
}
}
return 0;
destroy_class:
class_destroy(time_helper_class);
destroy_cdev:
cdev_del(&(time_helper_dev->dev));
cleanup:
kfree(time_helper_dev);
unregister:
unregister_chrdev_region(MKDEV(time_helper_major, time_helper_minor), time_helper_nr_devs);
fail:
return err;
}
static void time_helper_exit(void)
{
dev_t devno = MKDEV(time_helper_major, time_helper_minor);
if(time_helper_class) {
device_destroy(time_helper_class, MKDEV(time_helper_major, time_helper_minor));
class_destroy(time_helper_class);
}
if(time_helper_dev) {
cdev_del(&(time_helper_dev->dev));
kfree(time_helper_dev);
}
unregister_chrdev_region(devno, time_helper_nr_devs);
}
module_init(time_helper_init);
module_exit(time_helper_exit);
| gpl-2.0 |
sthalik/android_kernel_motorola_msm8916 | arch/arm/mm/fault.c | 795 | 16160 | /*
* linux/arch/arm/mm/fault.c
*
* Copyright (C) 1995 Linus Torvalds
* Modifications for ARM processor (c) 1995-2004 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/signal.h>
#include <linux/mm.h>
#include <linux/hardirq.h>
#include <linux/init.h>
#include <linux/kprobes.h>
#include <linux/uaccess.h>
#include <linux/page-flags.h>
#include <linux/sched.h>
#include <linux/highmem.h>
#include <linux/perf_event.h>
#include <asm/exception.h>
#include <asm/pgtable.h>
#include <asm/system_misc.h>
#include <asm/system_info.h>
#include <asm/tlbflush.h>
#if defined(CONFIG_ARCH_MSM_SCORPION) && !defined(CONFIG_MSM_SMP)
#include <asm/io.h>
#include <mach/msm_iomap.h>
#endif
#include "fault.h"
#include <trace/events/exception.h>
#ifdef CONFIG_MMU
#ifdef CONFIG_KPROBES
static inline int notify_page_fault(struct pt_regs *regs, unsigned int fsr)
{
int ret = 0;
if (!user_mode(regs)) {
/* kprobe_running() needs smp_processor_id() */
preempt_disable();
if (kprobe_running() && kprobe_fault_handler(regs, fsr))
ret = 1;
preempt_enable();
}
return ret;
}
#else
static inline int notify_page_fault(struct pt_regs *regs, unsigned int fsr)
{
return 0;
}
#endif
/*
* This is useful to dump out the page tables associated with
* 'addr' in mm 'mm'.
*/
void show_pte(struct mm_struct *mm, unsigned long addr)
{
pgd_t *pgd;
if (!mm)
mm = &init_mm;
printk(KERN_ALERT "pgd = %p\n", mm->pgd);
pgd = pgd_offset(mm, addr);
printk(KERN_ALERT "[%08lx] *pgd=%08llx",
addr, (long long)pgd_val(*pgd));
do {
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
if (pgd_none(*pgd))
break;
if (pgd_bad(*pgd)) {
printk("(bad)");
break;
}
pud = pud_offset(pgd, addr);
if (PTRS_PER_PUD != 1)
printk(", *pud=%08llx", (long long)pud_val(*pud));
if (pud_none(*pud))
break;
if (pud_bad(*pud)) {
printk("(bad)");
break;
}
pmd = pmd_offset(pud, addr);
if (PTRS_PER_PMD != 1)
printk(", *pmd=%08llx", (long long)pmd_val(*pmd));
if (pmd_none(*pmd))
break;
if (pmd_bad(*pmd)) {
printk("(bad)");
break;
}
/* We must not map this if we have highmem enabled */
if (PageHighMem(pfn_to_page(pmd_val(*pmd) >> PAGE_SHIFT)))
break;
pte = pte_offset_map(pmd, addr);
printk(", *pte=%08llx", (long long)pte_val(*pte));
#ifndef CONFIG_ARM_LPAE
printk(", *ppte=%08llx",
(long long)pte_val(pte[PTE_HWTABLE_PTRS]));
#endif
pte_unmap(pte);
} while(0);
printk("\n");
}
#else /* CONFIG_MMU */
void show_pte(struct mm_struct *mm, unsigned long addr)
{ }
#endif /* CONFIG_MMU */
/*
* Oops. The kernel tried to access some page that wasn't present.
*/
static void
__do_kernel_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr,
struct pt_regs *regs)
{
/*
* Are we prepared to handle this kernel fault?
*/
if (fixup_exception(regs))
return;
/*
* No handler, we'll have to terminate things with extreme prejudice.
*/
bust_spinlocks(1);
printk(KERN_ALERT
"Unable to handle kernel %s at virtual address %08lx\n",
(addr < PAGE_SIZE) ? "NULL pointer dereference" :
"paging request", addr);
show_pte(mm, addr);
die("Oops", regs, fsr);
bust_spinlocks(0);
do_exit(SIGKILL);
}
/*
* Something tried to access memory that isn't in our memory map..
* User mode accesses just cause a SIGSEGV
*/
static void
__do_user_fault(struct task_struct *tsk, unsigned long addr,
unsigned int fsr, unsigned int sig, int code,
struct pt_regs *regs)
{
struct siginfo si;
trace_user_fault(tsk, addr, fsr);
#ifdef CONFIG_DEBUG_USER
if (((user_debug & UDBG_SEGV) && (sig == SIGSEGV)) ||
((user_debug & UDBG_BUS) && (sig == SIGBUS))) {
printk(KERN_DEBUG "%s: unhandled page fault (%d) at 0x%08lx, code 0x%03x\n",
tsk->comm, sig, addr, fsr);
show_pte(tsk->mm, addr);
show_regs(regs);
}
#endif
tsk->thread.address = addr;
tsk->thread.error_code = fsr;
tsk->thread.trap_no = 14;
si.si_signo = sig;
si.si_errno = 0;
si.si_code = code;
si.si_addr = (void __user *)addr;
force_sig_info(sig, &si, tsk);
}
void do_bad_area(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->active_mm;
/*
* If we are in kernel mode at this point, we
* have no context to handle this fault with.
*/
if (user_mode(regs))
__do_user_fault(tsk, addr, fsr, SIGSEGV, SEGV_MAPERR, regs);
else
__do_kernel_fault(mm, addr, fsr, regs);
}
#ifdef CONFIG_MMU
#define VM_FAULT_BADMAP 0x010000
#define VM_FAULT_BADACCESS 0x020000
/*
* Check that the permissions on the VMA allow for the fault which occurred.
* If we encountered a write fault, we must have write permission, otherwise
* we allow any permission.
*/
static inline bool access_error(unsigned int fsr, struct vm_area_struct *vma)
{
unsigned int mask = VM_READ | VM_WRITE | VM_EXEC;
if (fsr & FSR_WRITE)
mask = VM_WRITE;
if (fsr & FSR_LNX_PF)
mask = VM_EXEC;
return vma->vm_flags & mask ? false : true;
}
static int __kprobes
__do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr,
unsigned int flags, struct task_struct *tsk)
{
struct vm_area_struct *vma;
int fault;
vma = find_vma(mm, addr);
fault = VM_FAULT_BADMAP;
if (unlikely(!vma))
goto out;
if (unlikely(vma->vm_start > addr))
goto check_stack;
/*
* Ok, we have a good vm_area for this
* memory access, so we can handle it.
*/
good_area:
if (access_error(fsr, vma)) {
fault = VM_FAULT_BADACCESS;
goto out;
}
return handle_mm_fault(mm, vma, addr & PAGE_MASK, flags);
check_stack:
/* Don't allow expansion below FIRST_USER_ADDRESS */
if (vma->vm_flags & VM_GROWSDOWN &&
addr >= FIRST_USER_ADDRESS && !expand_stack(vma, addr))
goto good_area;
out:
return fault;
}
static int __kprobes
do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
if (notify_page_fault(regs, fsr))
return 0;
tsk = current;
mm = tsk->mm;
/* Enable interrupts if they were enabled in the parent context. */
if (interrupts_enabled(regs))
local_irq_enable();
/*
* If we're in an interrupt, or have no irqs, or have no user
* context, we must not take the fault..
*/
if (in_atomic() || irqs_disabled() || !mm)
goto no_context;
if (user_mode(regs))
flags |= FAULT_FLAG_USER;
if (fsr & FSR_WRITE)
flags |= FAULT_FLAG_WRITE;
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc))
goto no_context;
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in
* which case, we'll have missed the might_sleep() from
* down_read()
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) &&
!search_exception_tables(regs->ARM_pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, fsr, flags, tsk);
/* If we need to retry but a fatal signal is pending, handle the
* signal first. We do not need to release the mmap_sem because
* it would already be released in __lock_page_or_retry in
* mm/filemap.c. */
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return 0;
/*
* Major/minor page fault accounting is only done on the
* initial attempt. If we go through a retry, it is extremely
* likely that the page will be found in page cache at that point.
*/
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (!(fault & VM_FAULT_ERROR) && flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1,
regs, addr);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1,
regs, addr);
}
if (fault & VM_FAULT_RETRY) {
/* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk
* of starvation. */
flags &= ~FAULT_FLAG_ALLOW_RETRY;
flags |= FAULT_FLAG_TRIED;
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS))))
return 0;
/*
* If we are in kernel mode at this point, we
* have no context to handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we
* got oom-killed)
*/
pagefault_out_of_memory();
return 0;
}
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to
* successfully fix up this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that
* isn't in our memory map..
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, fsr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, fsr, regs);
return 0;
}
#else /* CONFIG_MMU */
static int
do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
return 0;
}
#endif /* CONFIG_MMU */
/*
* First Level Translation Fault Handler
*
* We enter here because the first level page table doesn't contain
* a valid entry for the address.
*
* If the address is in kernel space (>= TASK_SIZE), then we are
* probably faulting in the vmalloc() area.
*
* If the init_task's first level page tables contains the relevant
* entry, we copy the it to this task. If not, we send the process
* a signal, fixup the exception, or oops the kernel.
*
* NOTE! We MUST NOT take any locks for this case. We may be in an
* interrupt or a critical region, and should only copy the information
* from the master page table, nothing more.
*/
#ifdef CONFIG_MMU
static int __kprobes
do_translation_fault(unsigned long addr, unsigned int fsr,
struct pt_regs *regs)
{
unsigned int index;
pgd_t *pgd, *pgd_k;
pud_t *pud, *pud_k;
pmd_t *pmd, *pmd_k;
if (addr < TASK_SIZE)
return do_page_fault(addr, fsr, regs);
if (user_mode(regs))
goto bad_area;
index = pgd_index(addr);
pgd = cpu_get_pgd() + index;
pgd_k = init_mm.pgd + index;
if (pgd_none(*pgd_k))
goto bad_area;
if (!pgd_present(*pgd))
set_pgd(pgd, *pgd_k);
pud = pud_offset(pgd, addr);
pud_k = pud_offset(pgd_k, addr);
if (pud_none(*pud_k))
goto bad_area;
if (!pud_present(*pud))
set_pud(pud, *pud_k);
pmd = pmd_offset(pud, addr);
pmd_k = pmd_offset(pud_k, addr);
#ifdef CONFIG_ARM_LPAE
/*
* Only one hardware entry per PMD with LPAE.
*/
index = 0;
#else
/*
* On ARM one Linux PGD entry contains two hardware entries (see page
* tables layout in pgtable.h). We normally guarantee that we always
* fill both L1 entries. But create_mapping() doesn't follow the rule.
* It can create inidividual L1 entries, so here we have to call
* pmd_none() check for the entry really corresponded to address, not
* for the first of pair.
*/
index = (addr >> SECTION_SHIFT) & 1;
#endif
if (pmd_none(pmd_k[index]))
goto bad_area;
copy_pmd(pmd, pmd_k);
return 0;
bad_area:
do_bad_area(addr, fsr, regs);
return 0;
}
#else /* CONFIG_MMU */
static int
do_translation_fault(unsigned long addr, unsigned int fsr,
struct pt_regs *regs)
{
return 0;
}
#endif /* CONFIG_MMU */
/*
* Some section permission faults need to be handled gracefully.
* They can happen due to a __{get,put}_user during an oops.
*/
static int
do_sect_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
do_bad_area(addr, fsr, regs);
return 0;
}
/*
* This abort handler always returns "fault".
*/
static int
do_bad(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
return 1;
}
#if defined(CONFIG_ARCH_MSM_SCORPION) && !defined(CONFIG_MSM_SMP)
#define __str(x) #x
#define MRC(x, v1, v2, v4, v5, v6) do { \
unsigned int __##x; \
asm("mrc " __str(v1) ", " __str(v2) ", %0, " __str(v4) ", " \
__str(v5) ", " __str(v6) "\n" \
: "=r" (__##x)); \
pr_info("%s: %s = 0x%.8x\n", __func__, #x, __##x); \
} while(0)
#define MSM_TCSR_SPARE2 (MSM_TCSR_BASE + 0x60)
#endif
int
do_imprecise_ext(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
#if defined(CONFIG_ARCH_MSM_SCORPION) && !defined(CONFIG_MSM_SMP)
MRC(ADFSR, p15, 0, c5, c1, 0);
MRC(DFSR, p15, 0, c5, c0, 0);
MRC(ACTLR, p15, 0, c1, c0, 1);
MRC(EFSR, p15, 7, c15, c0, 1);
MRC(L2SR, p15, 3, c15, c1, 0);
MRC(L2CR0, p15, 3, c15, c0, 1);
MRC(L2CPUESR, p15, 3, c15, c1, 1);
MRC(L2CPUCR, p15, 3, c15, c0, 2);
MRC(SPESR, p15, 1, c9, c7, 0);
MRC(SPCR, p15, 0, c9, c7, 0);
MRC(DMACHSR, p15, 1, c11, c0, 0);
MRC(DMACHESR, p15, 1, c11, c0, 1);
MRC(DMACHCR, p15, 0, c11, c0, 2);
/* clear out EFSR and ADFSR after fault */
asm volatile ("mcr p15, 7, %0, c15, c0, 1\n\t"
"mcr p15, 0, %0, c5, c1, 0"
: : "r" (0));
#endif
#if defined(CONFIG_ARCH_MSM_SCORPION) && !defined(CONFIG_MSM_SMP)
pr_info("%s: TCSR_SPARE2 = 0x%.8x\n", __func__, readl(MSM_TCSR_SPARE2));
#endif
return 1;
}
struct fsr_info {
int (*fn)(unsigned long addr, unsigned int fsr, struct pt_regs *regs);
int sig;
int code;
const char *name;
};
/* FSR definition */
#ifdef CONFIG_ARM_LPAE
#include "fsr-3level.c"
#else
#include "fsr-2level.c"
#endif
void __init
hook_fault_code(int nr, int (*fn)(unsigned long, unsigned int, struct pt_regs *),
int sig, int code, const char *name)
{
if (nr < 0 || nr >= ARRAY_SIZE(fsr_info))
BUG();
fsr_info[nr].fn = fn;
fsr_info[nr].sig = sig;
fsr_info[nr].code = code;
fsr_info[nr].name = name;
}
/*
* Dispatch a data abort to the relevant handler.
*/
asmlinkage void __exception
do_DataAbort(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
const struct fsr_info *inf = fsr_info + fsr_fs(fsr);
struct siginfo info;
if (!inf->fn(addr, fsr & ~FSR_LNX_PF, regs))
return;
trace_unhandled_abort(regs, addr, fsr);
printk(KERN_ALERT "Unhandled fault: %s (0x%03x) at 0x%08lx\n",
inf->name, fsr, addr);
info.si_signo = inf->sig;
info.si_errno = 0;
info.si_code = inf->code;
info.si_addr = (void __user *)addr;
arm_notify_die("", regs, &info, fsr, 0);
}
void __init
hook_ifault_code(int nr, int (*fn)(unsigned long, unsigned int, struct pt_regs *),
int sig, int code, const char *name)
{
if (nr < 0 || nr >= ARRAY_SIZE(ifsr_info))
BUG();
ifsr_info[nr].fn = fn;
ifsr_info[nr].sig = sig;
ifsr_info[nr].code = code;
ifsr_info[nr].name = name;
}
asmlinkage void __exception
do_PrefetchAbort(unsigned long addr, unsigned int ifsr, struct pt_regs *regs)
{
const struct fsr_info *inf = ifsr_info + fsr_fs(ifsr);
struct siginfo info;
if (!inf->fn(addr, ifsr | FSR_LNX_PF, regs))
return;
trace_unhandled_abort(regs, addr, ifsr);
printk(KERN_ALERT "Unhandled prefetch abort: %s (0x%03x) at 0x%08lx\n",
inf->name, ifsr, addr);
info.si_signo = inf->sig;
info.si_errno = 0;
info.si_code = inf->code;
info.si_addr = (void __user *)addr;
arm_notify_die("", regs, &info, ifsr, 0);
}
#ifndef CONFIG_ARM_LPAE
static int __init exceptions_init(void)
{
if (cpu_architecture() >= CPU_ARCH_ARMv6) {
hook_fault_code(4, do_translation_fault, SIGSEGV, SEGV_MAPERR,
"I-cache maintenance fault");
}
if (cpu_architecture() >= CPU_ARCH_ARMv7) {
/*
* TODO: Access flag faults introduced in ARMv6K.
* Runtime check for 'K' extension is needed
*/
hook_fault_code(3, do_bad, SIGSEGV, SEGV_MAPERR,
"section access flag fault");
hook_fault_code(6, do_bad, SIGSEGV, SEGV_MAPERR,
"section access flag fault");
}
return 0;
}
arch_initcall(exceptions_init);
#endif
| gpl-2.0 |
markfasheh/linux-4.1-dedupe_fixes | arch/arm/mach-orion5x/ts209-setup.c | 1307 | 8846 | /*
* QNAP TS-109/TS-209 Board Setup
*
* Maintainer: Byron Bradley <byron.bbradley@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/gpio.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/pci.h>
#include <linux/irq.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/nand.h>
#include <linux/mv643xx_eth.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/i2c.h>
#include <linux/serial_reg.h>
#include <linux/ata_platform.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/pci.h>
#include <mach/orion5x.h>
#include "common.h"
#include "mpp.h"
#include "tsx09-common.h"
#define QNAP_TS209_NOR_BOOT_BASE 0xf4000000
#define QNAP_TS209_NOR_BOOT_SIZE SZ_8M
/****************************************************************************
* 8MiB NOR flash. The struct mtd_partition is not in the same order as the
* partitions on the device because we want to keep compatibility with
* existing QNAP firmware.
*
* Layout as used by QNAP:
* [2] 0x00000000-0x00200000 : "Kernel"
* [3] 0x00200000-0x00600000 : "RootFS1"
* [4] 0x00600000-0x00700000 : "RootFS2"
* [6] 0x00700000-0x00760000 : "NAS Config" (read-only)
* [5] 0x00760000-0x00780000 : "U-Boot Config"
* [1] 0x00780000-0x00800000 : "U-Boot" (read-only)
***************************************************************************/
static struct mtd_partition qnap_ts209_partitions[] = {
{
.name = "U-Boot",
.size = 0x00080000,
.offset = 0x00780000,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "Kernel",
.size = 0x00200000,
.offset = 0,
}, {
.name = "RootFS1",
.size = 0x00400000,
.offset = 0x00200000,
}, {
.name = "RootFS2",
.size = 0x00100000,
.offset = 0x00600000,
}, {
.name = "U-Boot Config",
.size = 0x00020000,
.offset = 0x00760000,
}, {
.name = "NAS Config",
.size = 0x00060000,
.offset = 0x00700000,
.mask_flags = MTD_WRITEABLE,
},
};
static struct physmap_flash_data qnap_ts209_nor_flash_data = {
.width = 1,
.parts = qnap_ts209_partitions,
.nr_parts = ARRAY_SIZE(qnap_ts209_partitions)
};
static struct resource qnap_ts209_nor_flash_resource = {
.flags = IORESOURCE_MEM,
.start = QNAP_TS209_NOR_BOOT_BASE,
.end = QNAP_TS209_NOR_BOOT_BASE + QNAP_TS209_NOR_BOOT_SIZE - 1,
};
static struct platform_device qnap_ts209_nor_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &qnap_ts209_nor_flash_data,
},
.resource = &qnap_ts209_nor_flash_resource,
.num_resources = 1,
};
/*****************************************************************************
* PCI
****************************************************************************/
#define QNAP_TS209_PCI_SLOT0_OFFS 7
#define QNAP_TS209_PCI_SLOT0_IRQ_PIN 6
#define QNAP_TS209_PCI_SLOT1_IRQ_PIN 7
static void __init qnap_ts209_pci_preinit(void)
{
int pin;
/*
* Configure PCI GPIO IRQ pins
*/
pin = QNAP_TS209_PCI_SLOT0_IRQ_PIN;
if (gpio_request(pin, "PCI Int1") == 0) {
if (gpio_direction_input(pin) == 0) {
irq_set_irq_type(gpio_to_irq(pin), IRQ_TYPE_LEVEL_LOW);
} else {
printk(KERN_ERR "qnap_ts209_pci_preinit failed to "
"set_irq_type pin %d\n", pin);
gpio_free(pin);
}
} else {
printk(KERN_ERR "qnap_ts209_pci_preinit failed to gpio_request "
"%d\n", pin);
}
pin = QNAP_TS209_PCI_SLOT1_IRQ_PIN;
if (gpio_request(pin, "PCI Int2") == 0) {
if (gpio_direction_input(pin) == 0) {
irq_set_irq_type(gpio_to_irq(pin), IRQ_TYPE_LEVEL_LOW);
} else {
printk(KERN_ERR "qnap_ts209_pci_preinit failed "
"to set_irq_type pin %d\n", pin);
gpio_free(pin);
}
} else {
printk(KERN_ERR "qnap_ts209_pci_preinit failed to gpio_request "
"%d\n", pin);
}
}
static int __init qnap_ts209_pci_map_irq(const struct pci_dev *dev, u8 slot,
u8 pin)
{
int irq;
/*
* Check for devices with hard-wired IRQs.
*/
irq = orion5x_pci_map_irq(dev, slot, pin);
if (irq != -1)
return irq;
/*
* PCI IRQs are connected via GPIOs.
*/
switch (slot - QNAP_TS209_PCI_SLOT0_OFFS) {
case 0:
return gpio_to_irq(QNAP_TS209_PCI_SLOT0_IRQ_PIN);
case 1:
return gpio_to_irq(QNAP_TS209_PCI_SLOT1_IRQ_PIN);
default:
return -1;
}
}
static struct hw_pci qnap_ts209_pci __initdata = {
.nr_controllers = 2,
.preinit = qnap_ts209_pci_preinit,
.setup = orion5x_pci_sys_setup,
.scan = orion5x_pci_sys_scan_bus,
.map_irq = qnap_ts209_pci_map_irq,
};
static int __init qnap_ts209_pci_init(void)
{
if (machine_is_ts209())
pci_common_init(&qnap_ts209_pci);
return 0;
}
subsys_initcall(qnap_ts209_pci_init);
/*****************************************************************************
* RTC S35390A on I2C bus
****************************************************************************/
#define TS209_RTC_GPIO 3
static struct i2c_board_info __initdata qnap_ts209_i2c_rtc = {
I2C_BOARD_INFO("s35390a", 0x30),
.irq = 0,
};
/****************************************************************************
* GPIO Attached Keys
* Power button is attached to the PIC microcontroller
****************************************************************************/
#define QNAP_TS209_GPIO_KEY_MEDIA 1
#define QNAP_TS209_GPIO_KEY_RESET 2
static struct gpio_keys_button qnap_ts209_buttons[] = {
{
.code = KEY_COPY,
.gpio = QNAP_TS209_GPIO_KEY_MEDIA,
.desc = "USB Copy Button",
.active_low = 1,
}, {
.code = KEY_RESTART,
.gpio = QNAP_TS209_GPIO_KEY_RESET,
.desc = "Reset Button",
.active_low = 1,
},
};
static struct gpio_keys_platform_data qnap_ts209_button_data = {
.buttons = qnap_ts209_buttons,
.nbuttons = ARRAY_SIZE(qnap_ts209_buttons),
};
static struct platform_device qnap_ts209_button_device = {
.name = "gpio-keys",
.id = -1,
.num_resources = 0,
.dev = {
.platform_data = &qnap_ts209_button_data,
},
};
/*****************************************************************************
* SATA
****************************************************************************/
static struct mv_sata_platform_data qnap_ts209_sata_data = {
.n_ports = 2,
};
/*****************************************************************************
* General Setup
****************************************************************************/
static unsigned int ts209_mpp_modes[] __initdata = {
MPP0_UNUSED,
MPP1_GPIO, /* USB copy button */
MPP2_GPIO, /* Load defaults button */
MPP3_GPIO, /* GPIO RTC */
MPP4_UNUSED,
MPP5_UNUSED,
MPP6_GPIO, /* PCI Int A */
MPP7_GPIO, /* PCI Int B */
MPP8_UNUSED,
MPP9_UNUSED,
MPP10_UNUSED,
MPP11_UNUSED,
MPP12_SATA_LED, /* SATA 0 presence */
MPP13_SATA_LED, /* SATA 1 presence */
MPP14_SATA_LED, /* SATA 0 active */
MPP15_SATA_LED, /* SATA 1 active */
MPP16_UART, /* UART1 RXD */
MPP17_UART, /* UART1 TXD */
MPP18_GPIO, /* SW_RST */
MPP19_UNUSED,
0,
};
static void __init qnap_ts209_init(void)
{
/*
* Setup basic Orion functions. Need to be called early.
*/
orion5x_init();
orion5x_mpp_conf(ts209_mpp_modes);
/*
* MPP[20] PCI clock 0
* MPP[21] PCI clock 1
* MPP[22] USB 0 over current
* MPP[23-25] Reserved
*/
/*
* Configure peripherals.
*/
mvebu_mbus_add_window_by_id(ORION_MBUS_DEVBUS_BOOT_TARGET,
ORION_MBUS_DEVBUS_BOOT_ATTR,
QNAP_TS209_NOR_BOOT_BASE,
QNAP_TS209_NOR_BOOT_SIZE);
platform_device_register(&qnap_ts209_nor_flash);
orion5x_ehci0_init();
orion5x_ehci1_init();
qnap_tsx09_find_mac_addr(QNAP_TS209_NOR_BOOT_BASE +
qnap_ts209_partitions[5].offset,
qnap_ts209_partitions[5].size);
orion5x_eth_init(&qnap_tsx09_eth_data);
orion5x_i2c_init();
orion5x_sata_init(&qnap_ts209_sata_data);
orion5x_uart0_init();
orion5x_uart1_init();
orion5x_xor_init();
platform_device_register(&qnap_ts209_button_device);
/* Get RTC IRQ and register the chip */
if (gpio_request(TS209_RTC_GPIO, "rtc") == 0) {
if (gpio_direction_input(TS209_RTC_GPIO) == 0)
qnap_ts209_i2c_rtc.irq = gpio_to_irq(TS209_RTC_GPIO);
else
gpio_free(TS209_RTC_GPIO);
}
if (qnap_ts209_i2c_rtc.irq == 0)
pr_warn("qnap_ts209_init: failed to get RTC IRQ\n");
i2c_register_board_info(0, &qnap_ts209_i2c_rtc, 1);
/* register tsx09 specific power-off method */
pm_power_off = qnap_tsx09_power_off;
}
MACHINE_START(TS209, "QNAP TS-109/TS-209")
/* Maintainer: Byron Bradley <byron.bbradley@gmail.com> */
.atag_offset = 0x100,
.init_machine = qnap_ts209_init,
.map_io = orion5x_map_io,
.init_early = orion5x_init_early,
.init_irq = orion5x_init_irq,
.init_time = orion5x_timer_init,
.fixup = tag_fixup_mem32,
.restart = orion5x_restart,
MACHINE_END
| gpl-2.0 |
quadcores/Full_Dedup_Liu | net/phonet/pn_dev.c | 1563 | 10178 | /*
* File: pn_dev.c
*
* Phonet network device
*
* Copyright (C) 2008 Nokia Corporation.
*
* Authors: Sakari Ailus <sakari.ailus@nokia.com>
* Rémi Denis-Courmont
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <linux/netdevice.h>
#include <linux/phonet.h>
#include <linux/proc_fs.h>
#include <linux/if_arp.h>
#include <net/sock.h>
#include <net/netns/generic.h>
#include <net/phonet/pn_dev.h>
struct phonet_routes {
struct mutex lock;
struct net_device __rcu *table[64];
};
struct phonet_net {
struct phonet_device_list pndevs;
struct phonet_routes routes;
};
static int phonet_net_id __read_mostly;
static struct phonet_net *phonet_pernet(struct net *net)
{
BUG_ON(!net);
return net_generic(net, phonet_net_id);
}
struct phonet_device_list *phonet_device_list(struct net *net)
{
struct phonet_net *pnn = phonet_pernet(net);
return &pnn->pndevs;
}
/* Allocate new Phonet device. */
static struct phonet_device *__phonet_device_alloc(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd = kmalloc(sizeof(*pnd), GFP_ATOMIC);
if (pnd == NULL)
return NULL;
pnd->netdev = dev;
bitmap_zero(pnd->addrs, 64);
BUG_ON(!mutex_is_locked(&pndevs->lock));
list_add_rcu(&pnd->list, &pndevs->list);
return pnd;
}
static struct phonet_device *__phonet_get(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
BUG_ON(!mutex_is_locked(&pndevs->lock));
list_for_each_entry(pnd, &pndevs->list, list) {
if (pnd->netdev == dev)
return pnd;
}
return NULL;
}
static struct phonet_device *__phonet_get_rcu(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
list_for_each_entry_rcu(pnd, &pndevs->list, list) {
if (pnd->netdev == dev)
return pnd;
}
return NULL;
}
static void phonet_device_destroy(struct net_device *dev)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
ASSERT_RTNL();
mutex_lock(&pndevs->lock);
pnd = __phonet_get(dev);
if (pnd)
list_del_rcu(&pnd->list);
mutex_unlock(&pndevs->lock);
if (pnd) {
u8 addr;
for_each_set_bit(addr, pnd->addrs, 64)
phonet_address_notify(RTM_DELADDR, dev, addr);
kfree(pnd);
}
}
struct net_device *phonet_device_get(struct net *net)
{
struct phonet_device_list *pndevs = phonet_device_list(net);
struct phonet_device *pnd;
struct net_device *dev = NULL;
rcu_read_lock();
list_for_each_entry_rcu(pnd, &pndevs->list, list) {
dev = pnd->netdev;
BUG_ON(!dev);
if ((dev->reg_state == NETREG_REGISTERED) &&
((pnd->netdev->flags & IFF_UP)) == IFF_UP)
break;
dev = NULL;
}
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
int phonet_address_add(struct net_device *dev, u8 addr)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
int err = 0;
mutex_lock(&pndevs->lock);
/* Find or create Phonet-specific device data */
pnd = __phonet_get(dev);
if (pnd == NULL)
pnd = __phonet_device_alloc(dev);
if (unlikely(pnd == NULL))
err = -ENOMEM;
else if (test_and_set_bit(addr >> 2, pnd->addrs))
err = -EEXIST;
mutex_unlock(&pndevs->lock);
return err;
}
int phonet_address_del(struct net_device *dev, u8 addr)
{
struct phonet_device_list *pndevs = phonet_device_list(dev_net(dev));
struct phonet_device *pnd;
int err = 0;
mutex_lock(&pndevs->lock);
pnd = __phonet_get(dev);
if (!pnd || !test_and_clear_bit(addr >> 2, pnd->addrs)) {
err = -EADDRNOTAVAIL;
pnd = NULL;
} else if (bitmap_empty(pnd->addrs, 64))
list_del_rcu(&pnd->list);
else
pnd = NULL;
mutex_unlock(&pndevs->lock);
if (pnd)
kfree_rcu(pnd, rcu);
return err;
}
/* Gets a source address toward a destination, through a interface. */
u8 phonet_address_get(struct net_device *dev, u8 daddr)
{
struct phonet_device *pnd;
u8 saddr;
rcu_read_lock();
pnd = __phonet_get_rcu(dev);
if (pnd) {
BUG_ON(bitmap_empty(pnd->addrs, 64));
/* Use same source address as destination, if possible */
if (test_bit(daddr >> 2, pnd->addrs))
saddr = daddr;
else
saddr = find_first_bit(pnd->addrs, 64) << 2;
} else
saddr = PN_NO_ADDR;
rcu_read_unlock();
if (saddr == PN_NO_ADDR) {
/* Fallback to another device */
struct net_device *def_dev;
def_dev = phonet_device_get(dev_net(dev));
if (def_dev) {
if (def_dev != dev)
saddr = phonet_address_get(def_dev, daddr);
dev_put(def_dev);
}
}
return saddr;
}
int phonet_address_lookup(struct net *net, u8 addr)
{
struct phonet_device_list *pndevs = phonet_device_list(net);
struct phonet_device *pnd;
int err = -EADDRNOTAVAIL;
rcu_read_lock();
list_for_each_entry_rcu(pnd, &pndevs->list, list) {
/* Don't allow unregistering devices! */
if ((pnd->netdev->reg_state != NETREG_REGISTERED) ||
((pnd->netdev->flags & IFF_UP)) != IFF_UP)
continue;
if (test_bit(addr >> 2, pnd->addrs)) {
err = 0;
goto found;
}
}
found:
rcu_read_unlock();
return err;
}
/* automatically configure a Phonet device, if supported */
static int phonet_device_autoconf(struct net_device *dev)
{
struct if_phonet_req req;
int ret;
if (!dev->netdev_ops->ndo_do_ioctl)
return -EOPNOTSUPP;
ret = dev->netdev_ops->ndo_do_ioctl(dev, (struct ifreq *)&req,
SIOCPNGAUTOCONF);
if (ret < 0)
return ret;
ASSERT_RTNL();
ret = phonet_address_add(dev, req.ifr_phonet_autoconf.device);
if (ret)
return ret;
phonet_address_notify(RTM_NEWADDR, dev,
req.ifr_phonet_autoconf.device);
return 0;
}
static void phonet_route_autodel(struct net_device *dev)
{
struct phonet_net *pnn = phonet_pernet(dev_net(dev));
unsigned int i;
DECLARE_BITMAP(deleted, 64);
/* Remove left-over Phonet routes */
bitmap_zero(deleted, 64);
mutex_lock(&pnn->routes.lock);
for (i = 0; i < 64; i++)
if (rcu_access_pointer(pnn->routes.table[i]) == dev) {
RCU_INIT_POINTER(pnn->routes.table[i], NULL);
set_bit(i, deleted);
}
mutex_unlock(&pnn->routes.lock);
if (bitmap_empty(deleted, 64))
return; /* short-circuit RCU */
synchronize_rcu();
for_each_set_bit(i, deleted, 64) {
rtm_phonet_notify(RTM_DELROUTE, dev, i);
dev_put(dev);
}
}
/* notify Phonet of device events */
static int phonet_device_notify(struct notifier_block *me, unsigned long what,
void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
switch (what) {
case NETDEV_REGISTER:
if (dev->type == ARPHRD_PHONET)
phonet_device_autoconf(dev);
break;
case NETDEV_UNREGISTER:
phonet_device_destroy(dev);
phonet_route_autodel(dev);
break;
}
return 0;
}
static struct notifier_block phonet_device_notifier = {
.notifier_call = phonet_device_notify,
.priority = 0,
};
/* Per-namespace Phonet devices handling */
static int __net_init phonet_init_net(struct net *net)
{
struct phonet_net *pnn = phonet_pernet(net);
if (!proc_create("phonet", 0, net->proc_net, &pn_sock_seq_fops))
return -ENOMEM;
INIT_LIST_HEAD(&pnn->pndevs.list);
mutex_init(&pnn->pndevs.lock);
mutex_init(&pnn->routes.lock);
return 0;
}
static void __net_exit phonet_exit_net(struct net *net)
{
remove_proc_entry("phonet", net->proc_net);
}
static struct pernet_operations phonet_net_ops = {
.init = phonet_init_net,
.exit = phonet_exit_net,
.id = &phonet_net_id,
.size = sizeof(struct phonet_net),
};
/* Initialize Phonet devices list */
int __init phonet_device_init(void)
{
int err = register_pernet_subsys(&phonet_net_ops);
if (err)
return err;
proc_create("pnresource", 0, init_net.proc_net, &pn_res_seq_fops);
register_netdevice_notifier(&phonet_device_notifier);
err = phonet_netlink_register();
if (err)
phonet_device_exit();
return err;
}
void phonet_device_exit(void)
{
rtnl_unregister_all(PF_PHONET);
unregister_netdevice_notifier(&phonet_device_notifier);
unregister_pernet_subsys(&phonet_net_ops);
remove_proc_entry("pnresource", init_net.proc_net);
}
int phonet_route_add(struct net_device *dev, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(dev_net(dev));
struct phonet_routes *routes = &pnn->routes;
int err = -EEXIST;
daddr = daddr >> 2;
mutex_lock(&routes->lock);
if (routes->table[daddr] == NULL) {
rcu_assign_pointer(routes->table[daddr], dev);
dev_hold(dev);
err = 0;
}
mutex_unlock(&routes->lock);
return err;
}
int phonet_route_del(struct net_device *dev, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(dev_net(dev));
struct phonet_routes *routes = &pnn->routes;
daddr = daddr >> 2;
mutex_lock(&routes->lock);
if (rcu_access_pointer(routes->table[daddr]) == dev)
RCU_INIT_POINTER(routes->table[daddr], NULL);
else
dev = NULL;
mutex_unlock(&routes->lock);
if (!dev)
return -ENOENT;
synchronize_rcu();
dev_put(dev);
return 0;
}
struct net_device *phonet_route_get_rcu(struct net *net, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(net);
struct phonet_routes *routes = &pnn->routes;
struct net_device *dev;
daddr >>= 2;
dev = rcu_dereference(routes->table[daddr]);
return dev;
}
struct net_device *phonet_route_output(struct net *net, u8 daddr)
{
struct phonet_net *pnn = phonet_pernet(net);
struct phonet_routes *routes = &pnn->routes;
struct net_device *dev;
daddr >>= 2;
rcu_read_lock();
dev = rcu_dereference(routes->table[daddr]);
if (dev)
dev_hold(dev);
rcu_read_unlock();
if (!dev)
dev = phonet_device_get(net); /* Default route */
return dev;
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_galaxytab-cdma | fs/hfsplus/part_tbl.c | 1819 | 3704 | /*
* linux/fs/hfsplus/part_tbl.c
*
* Copyright (C) 1996-1997 Paul H. Hargrove
* This file may be distributed under the terms of the GNU General Public License.
*
* Original code to handle the new style Mac partition table based on
* a patch contributed by Holger Schemel (aeglos@valinor.owl.de).
*
* In function preconditions the term "valid" applied to a pointer to
* a structure means that the pointer is non-NULL and the structure it
* points to has all fields initialized to consistent values.
*
*/
#include "hfsplus_fs.h"
/* offsets to various blocks */
#define HFS_DD_BLK 0 /* Driver Descriptor block */
#define HFS_PMAP_BLK 1 /* First block of partition map */
#define HFS_MDB_BLK 2 /* Block (w/i partition) of MDB */
/* magic numbers for various disk blocks */
#define HFS_DRVR_DESC_MAGIC 0x4552 /* "ER": driver descriptor map */
#define HFS_OLD_PMAP_MAGIC 0x5453 /* "TS": old-type partition map */
#define HFS_NEW_PMAP_MAGIC 0x504D /* "PM": new-type partition map */
#define HFS_SUPER_MAGIC 0x4244 /* "BD": HFS MDB (super block) */
#define HFS_MFS_SUPER_MAGIC 0xD2D7 /* MFS MDB (super block) */
/*
* The new style Mac partition map
*
* For each partition on the media there is a physical block (512-byte
* block) containing one of these structures. These blocks are
* contiguous starting at block 1.
*/
struct new_pmap {
__be16 pmSig; /* signature */
__be16 reSigPad; /* padding */
__be32 pmMapBlkCnt; /* partition blocks count */
__be32 pmPyPartStart; /* physical block start of partition */
__be32 pmPartBlkCnt; /* physical block count of partition */
u8 pmPartName[32]; /* (null terminated?) string
giving the name of this
partition */
u8 pmPartType[32]; /* (null terminated?) string
giving the type of this
partition */
/* a bunch more stuff we don't need */
} __packed;
/*
* The old style Mac partition map
*
* The partition map consists for a 2-byte signature followed by an
* array of these structures. The map is terminated with an all-zero
* one of these.
*/
struct old_pmap {
__be16 pdSig; /* Signature bytes */
struct old_pmap_entry {
__be32 pdStart;
__be32 pdSize;
__be32 pdFSID;
} pdEntry[42];
} __packed;
/*
* hfs_part_find()
*
* Parse the partition map looking for the
* start and length of the 'part'th HFS partition.
*/
int hfs_part_find(struct super_block *sb,
sector_t *part_start, sector_t *part_size)
{
struct buffer_head *bh;
__be16 *data;
int i, size, res;
res = -ENOENT;
bh = sb_bread512(sb, *part_start + HFS_PMAP_BLK, data);
if (!bh)
return -EIO;
switch (be16_to_cpu(*data)) {
case HFS_OLD_PMAP_MAGIC:
{
struct old_pmap *pm;
struct old_pmap_entry *p;
pm = (struct old_pmap *)bh->b_data;
p = pm->pdEntry;
size = 42;
for (i = 0; i < size; p++, i++) {
if (p->pdStart && p->pdSize &&
p->pdFSID == cpu_to_be32(0x54465331)/*"TFS1"*/ &&
(HFSPLUS_SB(sb).part < 0 || HFSPLUS_SB(sb).part == i)) {
*part_start += be32_to_cpu(p->pdStart);
*part_size = be32_to_cpu(p->pdSize);
res = 0;
}
}
break;
}
case HFS_NEW_PMAP_MAGIC:
{
struct new_pmap *pm;
pm = (struct new_pmap *)bh->b_data;
size = be32_to_cpu(pm->pmMapBlkCnt);
for (i = 0; i < size;) {
if (!memcmp(pm->pmPartType,"Apple_HFS", 9) &&
(HFSPLUS_SB(sb).part < 0 || HFSPLUS_SB(sb).part == i)) {
*part_start += be32_to_cpu(pm->pmPyPartStart);
*part_size = be32_to_cpu(pm->pmPartBlkCnt);
res = 0;
break;
}
brelse(bh);
bh = sb_bread512(sb, *part_start + HFS_PMAP_BLK + ++i, pm);
if (!bh)
return -EIO;
if (pm->pmSig != cpu_to_be16(HFS_NEW_PMAP_MAGIC))
break;
}
break;
}
}
brelse(bh);
return res;
}
| gpl-2.0 |
CaptainThrowback/kernel_htc_m8_LolliSense | drivers/bluetooth/hci_ldisc.c | 3099 | 13768 | /*
*
* Bluetooth HCI UART driver
*
* Copyright (C) 2002-2003 Maxim Krasnyansky <maxk@qualcomm.com>
* Copyright (C) 2004-2005 Marcel Holtmann <marcel@holtmann.org>
* Copyright (c) 2000-2001, 2010-2012, The Linux Foundation. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/signal.h>
#include <linux/ioctl.h>
#include <linux/skbuff.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include "hci_uart.h"
#define VERSION "2.2"
static bool reset = 0;
static struct hci_uart_proto *hup[HCI_UART_MAX_PROTO];
static void hci_uart_tty_wakeup_action(unsigned long data);
int hci_uart_register_proto(struct hci_uart_proto *p)
{
if (p->id >= HCI_UART_MAX_PROTO)
return -EINVAL;
if (hup[p->id])
return -EEXIST;
hup[p->id] = p;
return 0;
}
int hci_uart_unregister_proto(struct hci_uart_proto *p)
{
if (p->id >= HCI_UART_MAX_PROTO)
return -EINVAL;
if (!hup[p->id])
return -EINVAL;
hup[p->id] = NULL;
return 0;
}
static struct hci_uart_proto *hci_uart_get_proto(unsigned int id)
{
if (id >= HCI_UART_MAX_PROTO)
return NULL;
return hup[id];
}
static inline void hci_uart_tx_complete(struct hci_uart *hu, int pkt_type)
{
struct hci_dev *hdev = hu->hdev;
/* Update HCI stat counters */
switch (pkt_type) {
case HCI_COMMAND_PKT:
hdev->stat.cmd_tx++;
break;
case HCI_ACLDATA_PKT:
hdev->stat.acl_tx++;
break;
case HCI_SCODATA_PKT:
hdev->stat.sco_tx++;
break;
}
}
static inline struct sk_buff *hci_uart_dequeue(struct hci_uart *hu)
{
struct sk_buff *skb = hu->tx_skb;
if (!skb)
skb = hu->proto->dequeue(hu);
else
hu->tx_skb = NULL;
return skb;
}
int hci_uart_tx_wakeup(struct hci_uart *hu)
{
struct tty_struct *tty = hu->tty;
struct hci_dev *hdev = hu->hdev;
struct sk_buff *skb;
if (test_and_set_bit(HCI_UART_SENDING, &hu->tx_state)) {
set_bit(HCI_UART_TX_WAKEUP, &hu->tx_state);
return 0;
}
BT_DBG("");
restart:
clear_bit(HCI_UART_TX_WAKEUP, &hu->tx_state);
while ((skb = hci_uart_dequeue(hu))) {
int len;
set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
len = tty->ops->write(tty, skb->data, skb->len);
hdev->stat.byte_tx += len;
skb_pull(skb, len);
if (skb->len) {
hu->tx_skb = skb;
break;
}
hci_uart_tx_complete(hu, bt_cb(skb)->pkt_type);
kfree_skb(skb);
}
if (test_bit(HCI_UART_TX_WAKEUP, &hu->tx_state))
goto restart;
clear_bit(HCI_UART_SENDING, &hu->tx_state);
return 0;
}
/* ------- Interface to HCI layer ------ */
/* Initialize device */
static int hci_uart_open(struct hci_dev *hdev)
{
BT_DBG("%s %p", hdev->name, hdev);
/* Nothing to do for UART driver */
set_bit(HCI_RUNNING, &hdev->flags);
return 0;
}
/* Reset device */
static int hci_uart_flush(struct hci_dev *hdev)
{
struct hci_uart *hu = (struct hci_uart *) hdev->driver_data;
struct tty_struct *tty = hu->tty;
BT_DBG("hdev %p tty %p", hdev, tty);
if (hu->tx_skb) {
kfree_skb(hu->tx_skb); hu->tx_skb = NULL;
}
/* Flush any pending characters in the driver and discipline. */
tty_ldisc_flush(tty);
tty_driver_flush_buffer(tty);
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
hu->proto->flush(hu);
return 0;
}
/* Close device */
static int hci_uart_close(struct hci_dev *hdev)
{
BT_DBG("hdev %p", hdev);
if (!test_and_clear_bit(HCI_RUNNING, &hdev->flags))
return 0;
hci_uart_flush(hdev);
hdev->flush = NULL;
return 0;
}
/* Send frames from HCI layer */
static int hci_uart_send_frame(struct sk_buff *skb)
{
struct hci_dev* hdev = (struct hci_dev *) skb->dev;
struct hci_uart *hu;
if (!hdev) {
BT_ERR("Frame for unknown device (hdev=NULL)");
return -ENODEV;
}
if (!test_bit(HCI_RUNNING, &hdev->flags))
return -EBUSY;
hu = (struct hci_uart *) hdev->driver_data;
BT_DBG("%s: type %d len %d", hdev->name, bt_cb(skb)->pkt_type, skb->len);
hu->proto->enqueue(hu, skb);
hci_uart_tx_wakeup(hu);
return 0;
}
static void hci_uart_destruct(struct hci_dev *hdev)
{
if (!hdev)
return;
BT_DBG("%s", hdev->name);
kfree(hdev->driver_data);
}
/* ------ LDISC part ------ */
/* hci_uart_tty_open
*
* Called when line discipline changed to HCI_UART.
*
* Arguments:
* tty pointer to tty info structure
* Return Value:
* 0 if success, otherwise error code
*/
static int hci_uart_tty_open(struct tty_struct *tty)
{
struct hci_uart *hu = (void *) tty->disc_data;
BT_DBG("tty %p", tty);
/* FIXME: This btw is bogus, nothing requires the old ldisc to clear
the pointer */
if (hu)
return -EEXIST;
/* Error if the tty has no write op instead of leaving an exploitable
hole */
if (tty->ops->write == NULL)
return -EOPNOTSUPP;
if (!(hu = kzalloc(sizeof(struct hci_uart), GFP_KERNEL))) {
BT_ERR("Can't allocate control structure");
return -ENFILE;
}
tty->disc_data = hu;
hu->tty = tty;
tty->receive_room = 65536;
spin_lock_init(&hu->rx_lock);
tasklet_init(&hu->tty_wakeup_task, hci_uart_tty_wakeup_action,
(unsigned long)hu);
/* Flush any pending characters in the driver and line discipline. */
/* FIXME: why is this needed. Note don't use ldisc_ref here as the
open path is before the ldisc is referencable */
if (tty->ldisc->ops->flush_buffer)
tty->ldisc->ops->flush_buffer(tty);
tty_driver_flush_buffer(tty);
return 0;
}
/* hci_uart_tty_close()
*
* Called when the line discipline is changed to something
* else, the tty is closed, or the tty detects a hangup.
*/
static void hci_uart_tty_close(struct tty_struct *tty)
{
struct hci_uart *hu = (void *)tty->disc_data;
BT_DBG("tty %p", tty);
/* Detach from the tty */
tty->disc_data = NULL;
if (hu) {
struct hci_dev *hdev = hu->hdev;
if (hdev)
hci_uart_close(hdev);
tasklet_kill(&hu->tty_wakeup_task);
if (test_and_clear_bit(HCI_UART_PROTO_SET, &hu->flags)) {
hu->proto->close(hu);
if (hdev) {
hci_unregister_dev(hdev);
hci_free_dev(hdev);
}
}
}
}
/* hci_uart_tty_wakeup()
*
* Callback for transmit wakeup. Called when low level
* device driver can accept more send data.
* This callback gets called from the isr context so
* schedule the send data operation to tasklet.
*
* Arguments: tty pointer to associated tty instance data
* Return Value: None
*/
static void hci_uart_tty_wakeup(struct tty_struct *tty)
{
struct hci_uart *hu = (void *)tty->disc_data;
tasklet_schedule(&hu->tty_wakeup_task);
}
/* hci_uart_tty_wakeup_action()
*
* Scheduled action to transmit data when low level device
* driver can accept more data.
*/
static void hci_uart_tty_wakeup_action(unsigned long data)
{
struct hci_uart *hu = (struct hci_uart *)data;
struct tty_struct *tty;
BT_DBG("");
if (!hu)
return;
tty = hu->tty;
clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
if (tty != hu->tty)
return;
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
hci_uart_tx_wakeup(hu);
}
/* hci_uart_tty_receive()
*
* Called by tty low level driver when receive data is
* available.
*
* Arguments: tty pointer to tty isntance data
* data pointer to received data
* flags pointer to flags for data
* count count of received data in bytes
*
* Return Value: None
*/
static void hci_uart_tty_receive(struct tty_struct *tty, const u8 *data, char *flags, int count)
{
int ret;
struct hci_uart *hu = (void *)tty->disc_data;
if (!hu || tty != hu->tty)
return;
if (!test_bit(HCI_UART_PROTO_SET, &hu->flags))
return;
spin_lock(&hu->rx_lock);
ret = hu->proto->recv(hu, (void *) data, count);
if (ret > 0)
hu->hdev->stat.byte_rx += count;
spin_unlock(&hu->rx_lock);
tty_unthrottle(tty);
}
static int hci_uart_register_dev(struct hci_uart *hu)
{
struct hci_dev *hdev;
BT_DBG("");
/* Initialize and register HCI device */
hdev = hci_alloc_dev();
if (!hdev) {
BT_ERR("Can't allocate HCI device");
return -ENOMEM;
}
hu->hdev = hdev;
hdev->bus = HCI_UART;
hdev->driver_data = hu;
hdev->open = hci_uart_open;
hdev->close = hci_uart_close;
hdev->flush = hci_uart_flush;
hdev->send = hci_uart_send_frame;
hdev->destruct = hci_uart_destruct;
hdev->parent = hu->tty->dev;
hdev->owner = THIS_MODULE;
if (!reset)
set_bit(HCI_QUIRK_NO_RESET, &hdev->quirks);
if (test_bit(HCI_UART_RAW_DEVICE, &hu->hdev_flags))
set_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks);
if (hci_register_dev(hdev) < 0) {
BT_ERR("Can't register HCI device");
hci_free_dev(hdev);
return -ENODEV;
}
return 0;
}
static int hci_uart_set_proto(struct hci_uart *hu, int id)
{
struct hci_uart_proto *p;
int err;
p = hci_uart_get_proto(id);
if (!p)
return -EPROTONOSUPPORT;
err = p->open(hu);
if (err)
return err;
hu->proto = p;
err = hci_uart_register_dev(hu);
if (err) {
p->close(hu);
return err;
}
return 0;
}
/* hci_uart_tty_ioctl()
*
* Process IOCTL system call for the tty device.
*
* Arguments:
*
* tty pointer to tty instance data
* file pointer to open file object for device
* cmd IOCTL command code
* arg argument for IOCTL call (cmd dependent)
*
* Return Value: Command dependent
*/
static int hci_uart_tty_ioctl(struct tty_struct *tty, struct file * file,
unsigned int cmd, unsigned long arg)
{
struct hci_uart *hu = (void *)tty->disc_data;
int err = 0;
BT_DBG("");
/* Verify the status of the device */
if (!hu)
return -EBADF;
switch (cmd) {
case HCIUARTSETPROTO:
if (!test_and_set_bit(HCI_UART_PROTO_SET_IN_PROGRESS,
&hu->flags) && !test_bit(HCI_UART_PROTO_SET,
&hu->flags)) {
err = hci_uart_set_proto(hu, arg);
if (err) {
clear_bit(HCI_UART_PROTO_SET_IN_PROGRESS,
&hu->flags);
return err;
} else {
set_bit(HCI_UART_PROTO_SET, &hu->flags);
clear_bit(HCI_UART_PROTO_SET_IN_PROGRESS,
&hu->flags);
}
} else
return -EBUSY;
break;
case HCIUARTGETPROTO:
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
return hu->proto->id;
return -EUNATCH;
case HCIUARTGETDEVICE:
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
return hu->hdev->id;
return -EUNATCH;
case HCIUARTSETFLAGS:
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
return -EBUSY;
hu->hdev_flags = arg;
break;
case HCIUARTGETFLAGS:
return hu->hdev_flags;
default:
err = n_tty_ioctl_helper(tty, file, cmd, arg);
break;
};
return err;
}
/*
* We don't provide read/write/poll interface for user space.
*/
static ssize_t hci_uart_tty_read(struct tty_struct *tty, struct file *file,
unsigned char __user *buf, size_t nr)
{
return 0;
}
static ssize_t hci_uart_tty_write(struct tty_struct *tty, struct file *file,
const unsigned char *data, size_t count)
{
return 0;
}
static unsigned int hci_uart_tty_poll(struct tty_struct *tty,
struct file *filp, poll_table *wait)
{
return 0;
}
static int __init hci_uart_init(void)
{
static struct tty_ldisc_ops hci_uart_ldisc;
int err;
BT_INFO("HCI UART driver ver %s", VERSION);
/* Register the tty discipline */
memset(&hci_uart_ldisc, 0, sizeof (hci_uart_ldisc));
hci_uart_ldisc.magic = TTY_LDISC_MAGIC;
hci_uart_ldisc.name = "n_hci";
hci_uart_ldisc.open = hci_uart_tty_open;
hci_uart_ldisc.close = hci_uart_tty_close;
hci_uart_ldisc.read = hci_uart_tty_read;
hci_uart_ldisc.write = hci_uart_tty_write;
hci_uart_ldisc.ioctl = hci_uart_tty_ioctl;
hci_uart_ldisc.poll = hci_uart_tty_poll;
hci_uart_ldisc.receive_buf = hci_uart_tty_receive;
hci_uart_ldisc.write_wakeup = hci_uart_tty_wakeup;
hci_uart_ldisc.owner = THIS_MODULE;
if ((err = tty_register_ldisc(N_HCI, &hci_uart_ldisc))) {
BT_ERR("HCI line discipline registration failed. (%d)", err);
return err;
}
#ifdef CONFIG_BT_HCIUART_H4
h4_init();
#endif
#ifdef CONFIG_BT_HCIUART_BCSP
bcsp_init();
#endif
#ifdef CONFIG_BT_HCIUART_LL
ll_init();
#endif
#ifdef CONFIG_BT_HCIUART_ATH3K
ath_init();
#endif
#ifdef CONFIG_BT_HCIUART_IBS
ibs_init();
#endif
return 0;
}
static void __exit hci_uart_exit(void)
{
int err;
#ifdef CONFIG_BT_HCIUART_H4
h4_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_BCSP
bcsp_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_LL
ll_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_ATH3K
ath_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_IBS
ibs_deinit();
#endif
/* Release tty registration of line discipline */
if ((err = tty_unregister_ldisc(N_HCI)))
BT_ERR("Can't unregister HCI line discipline (%d)", err);
}
module_init(hci_uart_init);
module_exit(hci_uart_exit);
module_param(reset, bool, 0644);
MODULE_PARM_DESC(reset, "Send HCI reset command on initialization");
MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
MODULE_DESCRIPTION("Bluetooth HCI UART driver ver " VERSION);
MODULE_VERSION(VERSION);
MODULE_LICENSE("GPL");
MODULE_ALIAS_LDISC(N_HCI);
| gpl-2.0 |
faux123/Galaxy_S5 | drivers/bluetooth/hci_ldisc.c | 3099 | 13768 | /*
*
* Bluetooth HCI UART driver
*
* Copyright (C) 2002-2003 Maxim Krasnyansky <maxk@qualcomm.com>
* Copyright (C) 2004-2005 Marcel Holtmann <marcel@holtmann.org>
* Copyright (c) 2000-2001, 2010-2012, The Linux Foundation. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/signal.h>
#include <linux/ioctl.h>
#include <linux/skbuff.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include "hci_uart.h"
#define VERSION "2.2"
static bool reset = 0;
static struct hci_uart_proto *hup[HCI_UART_MAX_PROTO];
static void hci_uart_tty_wakeup_action(unsigned long data);
int hci_uart_register_proto(struct hci_uart_proto *p)
{
if (p->id >= HCI_UART_MAX_PROTO)
return -EINVAL;
if (hup[p->id])
return -EEXIST;
hup[p->id] = p;
return 0;
}
int hci_uart_unregister_proto(struct hci_uart_proto *p)
{
if (p->id >= HCI_UART_MAX_PROTO)
return -EINVAL;
if (!hup[p->id])
return -EINVAL;
hup[p->id] = NULL;
return 0;
}
static struct hci_uart_proto *hci_uart_get_proto(unsigned int id)
{
if (id >= HCI_UART_MAX_PROTO)
return NULL;
return hup[id];
}
static inline void hci_uart_tx_complete(struct hci_uart *hu, int pkt_type)
{
struct hci_dev *hdev = hu->hdev;
/* Update HCI stat counters */
switch (pkt_type) {
case HCI_COMMAND_PKT:
hdev->stat.cmd_tx++;
break;
case HCI_ACLDATA_PKT:
hdev->stat.acl_tx++;
break;
case HCI_SCODATA_PKT:
hdev->stat.sco_tx++;
break;
}
}
static inline struct sk_buff *hci_uart_dequeue(struct hci_uart *hu)
{
struct sk_buff *skb = hu->tx_skb;
if (!skb)
skb = hu->proto->dequeue(hu);
else
hu->tx_skb = NULL;
return skb;
}
int hci_uart_tx_wakeup(struct hci_uart *hu)
{
struct tty_struct *tty = hu->tty;
struct hci_dev *hdev = hu->hdev;
struct sk_buff *skb;
if (test_and_set_bit(HCI_UART_SENDING, &hu->tx_state)) {
set_bit(HCI_UART_TX_WAKEUP, &hu->tx_state);
return 0;
}
BT_DBG("");
restart:
clear_bit(HCI_UART_TX_WAKEUP, &hu->tx_state);
while ((skb = hci_uart_dequeue(hu))) {
int len;
set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
len = tty->ops->write(tty, skb->data, skb->len);
hdev->stat.byte_tx += len;
skb_pull(skb, len);
if (skb->len) {
hu->tx_skb = skb;
break;
}
hci_uart_tx_complete(hu, bt_cb(skb)->pkt_type);
kfree_skb(skb);
}
if (test_bit(HCI_UART_TX_WAKEUP, &hu->tx_state))
goto restart;
clear_bit(HCI_UART_SENDING, &hu->tx_state);
return 0;
}
/* ------- Interface to HCI layer ------ */
/* Initialize device */
static int hci_uart_open(struct hci_dev *hdev)
{
BT_DBG("%s %p", hdev->name, hdev);
/* Nothing to do for UART driver */
set_bit(HCI_RUNNING, &hdev->flags);
return 0;
}
/* Reset device */
static int hci_uart_flush(struct hci_dev *hdev)
{
struct hci_uart *hu = (struct hci_uart *) hdev->driver_data;
struct tty_struct *tty = hu->tty;
BT_DBG("hdev %p tty %p", hdev, tty);
if (hu->tx_skb) {
kfree_skb(hu->tx_skb); hu->tx_skb = NULL;
}
/* Flush any pending characters in the driver and discipline. */
tty_ldisc_flush(tty);
tty_driver_flush_buffer(tty);
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
hu->proto->flush(hu);
return 0;
}
/* Close device */
static int hci_uart_close(struct hci_dev *hdev)
{
BT_DBG("hdev %p", hdev);
if (!test_and_clear_bit(HCI_RUNNING, &hdev->flags))
return 0;
hci_uart_flush(hdev);
hdev->flush = NULL;
return 0;
}
/* Send frames from HCI layer */
static int hci_uart_send_frame(struct sk_buff *skb)
{
struct hci_dev* hdev = (struct hci_dev *) skb->dev;
struct hci_uart *hu;
if (!hdev) {
BT_ERR("Frame for unknown device (hdev=NULL)");
return -ENODEV;
}
if (!test_bit(HCI_RUNNING, &hdev->flags))
return -EBUSY;
hu = (struct hci_uart *) hdev->driver_data;
BT_DBG("%s: type %d len %d", hdev->name, bt_cb(skb)->pkt_type, skb->len);
hu->proto->enqueue(hu, skb);
hci_uart_tx_wakeup(hu);
return 0;
}
static void hci_uart_destruct(struct hci_dev *hdev)
{
if (!hdev)
return;
BT_DBG("%s", hdev->name);
kfree(hdev->driver_data);
}
/* ------ LDISC part ------ */
/* hci_uart_tty_open
*
* Called when line discipline changed to HCI_UART.
*
* Arguments:
* tty pointer to tty info structure
* Return Value:
* 0 if success, otherwise error code
*/
static int hci_uart_tty_open(struct tty_struct *tty)
{
struct hci_uart *hu = (void *) tty->disc_data;
BT_DBG("tty %p", tty);
/* FIXME: This btw is bogus, nothing requires the old ldisc to clear
the pointer */
if (hu)
return -EEXIST;
/* Error if the tty has no write op instead of leaving an exploitable
hole */
if (tty->ops->write == NULL)
return -EOPNOTSUPP;
if (!(hu = kzalloc(sizeof(struct hci_uart), GFP_KERNEL))) {
BT_ERR("Can't allocate control structure");
return -ENFILE;
}
tty->disc_data = hu;
hu->tty = tty;
tty->receive_room = 65536;
spin_lock_init(&hu->rx_lock);
tasklet_init(&hu->tty_wakeup_task, hci_uart_tty_wakeup_action,
(unsigned long)hu);
/* Flush any pending characters in the driver and line discipline. */
/* FIXME: why is this needed. Note don't use ldisc_ref here as the
open path is before the ldisc is referencable */
if (tty->ldisc->ops->flush_buffer)
tty->ldisc->ops->flush_buffer(tty);
tty_driver_flush_buffer(tty);
return 0;
}
/* hci_uart_tty_close()
*
* Called when the line discipline is changed to something
* else, the tty is closed, or the tty detects a hangup.
*/
static void hci_uart_tty_close(struct tty_struct *tty)
{
struct hci_uart *hu = (void *)tty->disc_data;
BT_DBG("tty %p", tty);
/* Detach from the tty */
tty->disc_data = NULL;
if (hu) {
struct hci_dev *hdev = hu->hdev;
if (hdev)
hci_uart_close(hdev);
tasklet_kill(&hu->tty_wakeup_task);
if (test_and_clear_bit(HCI_UART_PROTO_SET, &hu->flags)) {
hu->proto->close(hu);
if (hdev) {
hci_unregister_dev(hdev);
hci_free_dev(hdev);
}
}
}
}
/* hci_uart_tty_wakeup()
*
* Callback for transmit wakeup. Called when low level
* device driver can accept more send data.
* This callback gets called from the isr context so
* schedule the send data operation to tasklet.
*
* Arguments: tty pointer to associated tty instance data
* Return Value: None
*/
static void hci_uart_tty_wakeup(struct tty_struct *tty)
{
struct hci_uart *hu = (void *)tty->disc_data;
tasklet_schedule(&hu->tty_wakeup_task);
}
/* hci_uart_tty_wakeup_action()
*
* Scheduled action to transmit data when low level device
* driver can accept more data.
*/
static void hci_uart_tty_wakeup_action(unsigned long data)
{
struct hci_uart *hu = (struct hci_uart *)data;
struct tty_struct *tty;
BT_DBG("");
if (!hu)
return;
tty = hu->tty;
clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
if (tty != hu->tty)
return;
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
hci_uart_tx_wakeup(hu);
}
/* hci_uart_tty_receive()
*
* Called by tty low level driver when receive data is
* available.
*
* Arguments: tty pointer to tty isntance data
* data pointer to received data
* flags pointer to flags for data
* count count of received data in bytes
*
* Return Value: None
*/
static void hci_uart_tty_receive(struct tty_struct *tty, const u8 *data, char *flags, int count)
{
int ret;
struct hci_uart *hu = (void *)tty->disc_data;
if (!hu || tty != hu->tty)
return;
if (!test_bit(HCI_UART_PROTO_SET, &hu->flags))
return;
spin_lock(&hu->rx_lock);
ret = hu->proto->recv(hu, (void *) data, count);
if (ret > 0)
hu->hdev->stat.byte_rx += count;
spin_unlock(&hu->rx_lock);
tty_unthrottle(tty);
}
static int hci_uart_register_dev(struct hci_uart *hu)
{
struct hci_dev *hdev;
BT_DBG("");
/* Initialize and register HCI device */
hdev = hci_alloc_dev();
if (!hdev) {
BT_ERR("Can't allocate HCI device");
return -ENOMEM;
}
hu->hdev = hdev;
hdev->bus = HCI_UART;
hdev->driver_data = hu;
hdev->open = hci_uart_open;
hdev->close = hci_uart_close;
hdev->flush = hci_uart_flush;
hdev->send = hci_uart_send_frame;
hdev->destruct = hci_uart_destruct;
hdev->parent = hu->tty->dev;
hdev->owner = THIS_MODULE;
if (!reset)
set_bit(HCI_QUIRK_NO_RESET, &hdev->quirks);
if (test_bit(HCI_UART_RAW_DEVICE, &hu->hdev_flags))
set_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks);
if (hci_register_dev(hdev) < 0) {
BT_ERR("Can't register HCI device");
hci_free_dev(hdev);
return -ENODEV;
}
return 0;
}
static int hci_uart_set_proto(struct hci_uart *hu, int id)
{
struct hci_uart_proto *p;
int err;
p = hci_uart_get_proto(id);
if (!p)
return -EPROTONOSUPPORT;
err = p->open(hu);
if (err)
return err;
hu->proto = p;
err = hci_uart_register_dev(hu);
if (err) {
p->close(hu);
return err;
}
return 0;
}
/* hci_uart_tty_ioctl()
*
* Process IOCTL system call for the tty device.
*
* Arguments:
*
* tty pointer to tty instance data
* file pointer to open file object for device
* cmd IOCTL command code
* arg argument for IOCTL call (cmd dependent)
*
* Return Value: Command dependent
*/
static int hci_uart_tty_ioctl(struct tty_struct *tty, struct file * file,
unsigned int cmd, unsigned long arg)
{
struct hci_uart *hu = (void *)tty->disc_data;
int err = 0;
BT_DBG("");
/* Verify the status of the device */
if (!hu)
return -EBADF;
switch (cmd) {
case HCIUARTSETPROTO:
if (!test_and_set_bit(HCI_UART_PROTO_SET_IN_PROGRESS,
&hu->flags) && !test_bit(HCI_UART_PROTO_SET,
&hu->flags)) {
err = hci_uart_set_proto(hu, arg);
if (err) {
clear_bit(HCI_UART_PROTO_SET_IN_PROGRESS,
&hu->flags);
return err;
} else {
set_bit(HCI_UART_PROTO_SET, &hu->flags);
clear_bit(HCI_UART_PROTO_SET_IN_PROGRESS,
&hu->flags);
}
} else
return -EBUSY;
break;
case HCIUARTGETPROTO:
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
return hu->proto->id;
return -EUNATCH;
case HCIUARTGETDEVICE:
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
return hu->hdev->id;
return -EUNATCH;
case HCIUARTSETFLAGS:
if (test_bit(HCI_UART_PROTO_SET, &hu->flags))
return -EBUSY;
hu->hdev_flags = arg;
break;
case HCIUARTGETFLAGS:
return hu->hdev_flags;
default:
err = n_tty_ioctl_helper(tty, file, cmd, arg);
break;
};
return err;
}
/*
* We don't provide read/write/poll interface for user space.
*/
static ssize_t hci_uart_tty_read(struct tty_struct *tty, struct file *file,
unsigned char __user *buf, size_t nr)
{
return 0;
}
static ssize_t hci_uart_tty_write(struct tty_struct *tty, struct file *file,
const unsigned char *data, size_t count)
{
return 0;
}
static unsigned int hci_uart_tty_poll(struct tty_struct *tty,
struct file *filp, poll_table *wait)
{
return 0;
}
static int __init hci_uart_init(void)
{
static struct tty_ldisc_ops hci_uart_ldisc;
int err;
BT_INFO("HCI UART driver ver %s", VERSION);
/* Register the tty discipline */
memset(&hci_uart_ldisc, 0, sizeof (hci_uart_ldisc));
hci_uart_ldisc.magic = TTY_LDISC_MAGIC;
hci_uart_ldisc.name = "n_hci";
hci_uart_ldisc.open = hci_uart_tty_open;
hci_uart_ldisc.close = hci_uart_tty_close;
hci_uart_ldisc.read = hci_uart_tty_read;
hci_uart_ldisc.write = hci_uart_tty_write;
hci_uart_ldisc.ioctl = hci_uart_tty_ioctl;
hci_uart_ldisc.poll = hci_uart_tty_poll;
hci_uart_ldisc.receive_buf = hci_uart_tty_receive;
hci_uart_ldisc.write_wakeup = hci_uart_tty_wakeup;
hci_uart_ldisc.owner = THIS_MODULE;
if ((err = tty_register_ldisc(N_HCI, &hci_uart_ldisc))) {
BT_ERR("HCI line discipline registration failed. (%d)", err);
return err;
}
#ifdef CONFIG_BT_HCIUART_H4
h4_init();
#endif
#ifdef CONFIG_BT_HCIUART_BCSP
bcsp_init();
#endif
#ifdef CONFIG_BT_HCIUART_LL
ll_init();
#endif
#ifdef CONFIG_BT_HCIUART_ATH3K
ath_init();
#endif
#ifdef CONFIG_BT_HCIUART_IBS
ibs_init();
#endif
return 0;
}
static void __exit hci_uart_exit(void)
{
int err;
#ifdef CONFIG_BT_HCIUART_H4
h4_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_BCSP
bcsp_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_LL
ll_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_ATH3K
ath_deinit();
#endif
#ifdef CONFIG_BT_HCIUART_IBS
ibs_deinit();
#endif
/* Release tty registration of line discipline */
if ((err = tty_unregister_ldisc(N_HCI)))
BT_ERR("Can't unregister HCI line discipline (%d)", err);
}
module_init(hci_uart_init);
module_exit(hci_uart_exit);
module_param(reset, bool, 0644);
MODULE_PARM_DESC(reset, "Send HCI reset command on initialization");
MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
MODULE_DESCRIPTION("Bluetooth HCI UART driver ver " VERSION);
MODULE_VERSION(VERSION);
MODULE_LICENSE("GPL");
MODULE_ALIAS_LDISC(N_HCI);
| gpl-2.0 |
Quarx2k/android_kernel_asus_padfone_s | fs/nfs/dns_resolve.c | 3355 | 9684 | /*
* linux/fs/nfs/dns_resolve.c
*
* Copyright (c) 2009 Trond Myklebust <Trond.Myklebust@netapp.com>
*
* Resolves DNS hostnames into valid ip addresses
*/
#ifdef CONFIG_NFS_USE_KERNEL_DNS
#include <linux/sunrpc/clnt.h>
#include <linux/dns_resolver.h>
#include "dns_resolve.h"
ssize_t nfs_dns_resolve_name(struct net *net, char *name, size_t namelen,
struct sockaddr *sa, size_t salen)
{
ssize_t ret;
char *ip_addr = NULL;
int ip_len;
ip_len = dns_query(NULL, name, namelen, NULL, &ip_addr, NULL);
if (ip_len > 0)
ret = rpc_pton(net, ip_addr, ip_len, sa, salen);
else
ret = -ESRCH;
kfree(ip_addr);
return ret;
}
#else
#include <linux/hash.h>
#include <linux/string.h>
#include <linux/kmod.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/socket.h>
#include <linux/seq_file.h>
#include <linux/inet.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/cache.h>
#include <linux/sunrpc/svcauth.h>
#include <linux/sunrpc/rpc_pipe_fs.h>
#include "dns_resolve.h"
#include "cache_lib.h"
#include "netns.h"
#define NFS_DNS_HASHBITS 4
#define NFS_DNS_HASHTBL_SIZE (1 << NFS_DNS_HASHBITS)
struct nfs_dns_ent {
struct cache_head h;
char *hostname;
size_t namelen;
struct sockaddr_storage addr;
size_t addrlen;
};
static void nfs_dns_ent_update(struct cache_head *cnew,
struct cache_head *ckey)
{
struct nfs_dns_ent *new;
struct nfs_dns_ent *key;
new = container_of(cnew, struct nfs_dns_ent, h);
key = container_of(ckey, struct nfs_dns_ent, h);
memcpy(&new->addr, &key->addr, key->addrlen);
new->addrlen = key->addrlen;
}
static void nfs_dns_ent_init(struct cache_head *cnew,
struct cache_head *ckey)
{
struct nfs_dns_ent *new;
struct nfs_dns_ent *key;
new = container_of(cnew, struct nfs_dns_ent, h);
key = container_of(ckey, struct nfs_dns_ent, h);
kfree(new->hostname);
new->hostname = kstrndup(key->hostname, key->namelen, GFP_KERNEL);
if (new->hostname) {
new->namelen = key->namelen;
nfs_dns_ent_update(cnew, ckey);
} else {
new->namelen = 0;
new->addrlen = 0;
}
}
static void nfs_dns_ent_put(struct kref *ref)
{
struct nfs_dns_ent *item;
item = container_of(ref, struct nfs_dns_ent, h.ref);
kfree(item->hostname);
kfree(item);
}
static struct cache_head *nfs_dns_ent_alloc(void)
{
struct nfs_dns_ent *item = kmalloc(sizeof(*item), GFP_KERNEL);
if (item != NULL) {
item->hostname = NULL;
item->namelen = 0;
item->addrlen = 0;
return &item->h;
}
return NULL;
};
static unsigned int nfs_dns_hash(const struct nfs_dns_ent *key)
{
return hash_str(key->hostname, NFS_DNS_HASHBITS);
}
static void nfs_dns_request(struct cache_detail *cd,
struct cache_head *ch,
char **bpp, int *blen)
{
struct nfs_dns_ent *key = container_of(ch, struct nfs_dns_ent, h);
qword_add(bpp, blen, key->hostname);
(*bpp)[-1] = '\n';
}
static int nfs_dns_upcall(struct cache_detail *cd,
struct cache_head *ch)
{
struct nfs_dns_ent *key = container_of(ch, struct nfs_dns_ent, h);
int ret;
ret = nfs_cache_upcall(cd, key->hostname);
if (ret)
ret = sunrpc_cache_pipe_upcall(cd, ch, nfs_dns_request);
return ret;
}
static int nfs_dns_match(struct cache_head *ca,
struct cache_head *cb)
{
struct nfs_dns_ent *a;
struct nfs_dns_ent *b;
a = container_of(ca, struct nfs_dns_ent, h);
b = container_of(cb, struct nfs_dns_ent, h);
if (a->namelen == 0 || a->namelen != b->namelen)
return 0;
return memcmp(a->hostname, b->hostname, a->namelen) == 0;
}
static int nfs_dns_show(struct seq_file *m, struct cache_detail *cd,
struct cache_head *h)
{
struct nfs_dns_ent *item;
long ttl;
if (h == NULL) {
seq_puts(m, "# ip address hostname ttl\n");
return 0;
}
item = container_of(h, struct nfs_dns_ent, h);
ttl = item->h.expiry_time - seconds_since_boot();
if (ttl < 0)
ttl = 0;
if (!test_bit(CACHE_NEGATIVE, &h->flags)) {
char buf[INET6_ADDRSTRLEN+IPV6_SCOPE_ID_LEN+1];
rpc_ntop((struct sockaddr *)&item->addr, buf, sizeof(buf));
seq_printf(m, "%15s ", buf);
} else
seq_puts(m, "<none> ");
seq_printf(m, "%15s %ld\n", item->hostname, ttl);
return 0;
}
static struct nfs_dns_ent *nfs_dns_lookup(struct cache_detail *cd,
struct nfs_dns_ent *key)
{
struct cache_head *ch;
ch = sunrpc_cache_lookup(cd,
&key->h,
nfs_dns_hash(key));
if (!ch)
return NULL;
return container_of(ch, struct nfs_dns_ent, h);
}
static struct nfs_dns_ent *nfs_dns_update(struct cache_detail *cd,
struct nfs_dns_ent *new,
struct nfs_dns_ent *key)
{
struct cache_head *ch;
ch = sunrpc_cache_update(cd,
&new->h, &key->h,
nfs_dns_hash(key));
if (!ch)
return NULL;
return container_of(ch, struct nfs_dns_ent, h);
}
static int nfs_dns_parse(struct cache_detail *cd, char *buf, int buflen)
{
char buf1[NFS_DNS_HOSTNAME_MAXLEN+1];
struct nfs_dns_ent key, *item;
unsigned long ttl;
ssize_t len;
int ret = -EINVAL;
if (buf[buflen-1] != '\n')
goto out;
buf[buflen-1] = '\0';
len = qword_get(&buf, buf1, sizeof(buf1));
if (len <= 0)
goto out;
key.addrlen = rpc_pton(cd->net, buf1, len,
(struct sockaddr *)&key.addr,
sizeof(key.addr));
len = qword_get(&buf, buf1, sizeof(buf1));
if (len <= 0)
goto out;
key.hostname = buf1;
key.namelen = len;
memset(&key.h, 0, sizeof(key.h));
ttl = get_expiry(&buf);
if (ttl == 0)
goto out;
key.h.expiry_time = ttl + seconds_since_boot();
ret = -ENOMEM;
item = nfs_dns_lookup(cd, &key);
if (item == NULL)
goto out;
if (key.addrlen == 0)
set_bit(CACHE_NEGATIVE, &key.h.flags);
item = nfs_dns_update(cd, &key, item);
if (item == NULL)
goto out;
ret = 0;
cache_put(&item->h, cd);
out:
return ret;
}
static int do_cache_lookup(struct cache_detail *cd,
struct nfs_dns_ent *key,
struct nfs_dns_ent **item,
struct nfs_cache_defer_req *dreq)
{
int ret = -ENOMEM;
*item = nfs_dns_lookup(cd, key);
if (*item) {
ret = cache_check(cd, &(*item)->h, &dreq->req);
if (ret)
*item = NULL;
}
return ret;
}
static int do_cache_lookup_nowait(struct cache_detail *cd,
struct nfs_dns_ent *key,
struct nfs_dns_ent **item)
{
int ret = -ENOMEM;
*item = nfs_dns_lookup(cd, key);
if (!*item)
goto out_err;
ret = -ETIMEDOUT;
if (!test_bit(CACHE_VALID, &(*item)->h.flags)
|| (*item)->h.expiry_time < seconds_since_boot()
|| cd->flush_time > (*item)->h.last_refresh)
goto out_put;
ret = -ENOENT;
if (test_bit(CACHE_NEGATIVE, &(*item)->h.flags))
goto out_put;
return 0;
out_put:
cache_put(&(*item)->h, cd);
out_err:
*item = NULL;
return ret;
}
static int do_cache_lookup_wait(struct cache_detail *cd,
struct nfs_dns_ent *key,
struct nfs_dns_ent **item)
{
struct nfs_cache_defer_req *dreq;
int ret = -ENOMEM;
dreq = nfs_cache_defer_req_alloc();
if (!dreq)
goto out;
ret = do_cache_lookup(cd, key, item, dreq);
if (ret == -EAGAIN) {
ret = nfs_cache_wait_for_upcall(dreq);
if (!ret)
ret = do_cache_lookup_nowait(cd, key, item);
}
nfs_cache_defer_req_put(dreq);
out:
return ret;
}
ssize_t nfs_dns_resolve_name(struct net *net, char *name,
size_t namelen, struct sockaddr *sa, size_t salen)
{
struct nfs_dns_ent key = {
.hostname = name,
.namelen = namelen,
};
struct nfs_dns_ent *item = NULL;
ssize_t ret;
struct nfs_net *nn = net_generic(net, nfs_net_id);
ret = do_cache_lookup_wait(nn->nfs_dns_resolve, &key, &item);
if (ret == 0) {
if (salen >= item->addrlen) {
memcpy(sa, &item->addr, item->addrlen);
ret = item->addrlen;
} else
ret = -EOVERFLOW;
cache_put(&item->h, nn->nfs_dns_resolve);
} else if (ret == -ENOENT)
ret = -ESRCH;
return ret;
}
int nfs_dns_resolver_cache_init(struct net *net)
{
int err = -ENOMEM;
struct nfs_net *nn = net_generic(net, nfs_net_id);
struct cache_detail *cd;
struct cache_head **tbl;
cd = kzalloc(sizeof(struct cache_detail), GFP_KERNEL);
if (cd == NULL)
goto err_cd;
tbl = kzalloc(NFS_DNS_HASHTBL_SIZE * sizeof(struct cache_head *),
GFP_KERNEL);
if (tbl == NULL)
goto err_tbl;
cd->owner = THIS_MODULE,
cd->hash_size = NFS_DNS_HASHTBL_SIZE,
cd->hash_table = tbl,
cd->name = "dns_resolve",
cd->cache_put = nfs_dns_ent_put,
cd->cache_upcall = nfs_dns_upcall,
cd->cache_parse = nfs_dns_parse,
cd->cache_show = nfs_dns_show,
cd->match = nfs_dns_match,
cd->init = nfs_dns_ent_init,
cd->update = nfs_dns_ent_update,
cd->alloc = nfs_dns_ent_alloc,
nfs_cache_init(cd);
err = nfs_cache_register_net(net, cd);
if (err)
goto err_reg;
nn->nfs_dns_resolve = cd;
return 0;
err_reg:
nfs_cache_destroy(cd);
kfree(cd->hash_table);
err_tbl:
kfree(cd);
err_cd:
return err;
}
void nfs_dns_resolver_cache_destroy(struct net *net)
{
struct nfs_net *nn = net_generic(net, nfs_net_id);
struct cache_detail *cd = nn->nfs_dns_resolve;
nfs_cache_unregister_net(net, cd);
nfs_cache_destroy(cd);
kfree(cd->hash_table);
kfree(cd);
}
static int rpc_pipefs_event(struct notifier_block *nb, unsigned long event,
void *ptr)
{
struct super_block *sb = ptr;
struct net *net = sb->s_fs_info;
struct nfs_net *nn = net_generic(net, nfs_net_id);
struct cache_detail *cd = nn->nfs_dns_resolve;
int ret = 0;
if (cd == NULL)
return 0;
if (!try_module_get(THIS_MODULE))
return 0;
switch (event) {
case RPC_PIPEFS_MOUNT:
ret = nfs_cache_register_sb(sb, cd);
break;
case RPC_PIPEFS_UMOUNT:
nfs_cache_unregister_sb(sb, cd);
break;
default:
ret = -ENOTSUPP;
break;
}
module_put(THIS_MODULE);
return ret;
}
static struct notifier_block nfs_dns_resolver_block = {
.notifier_call = rpc_pipefs_event,
};
int nfs_dns_resolver_init(void)
{
return rpc_pipefs_notifier_register(&nfs_dns_resolver_block);
}
void nfs_dns_resolver_destroy(void)
{
rpc_pipefs_notifier_unregister(&nfs_dns_resolver_block);
}
#endif
| gpl-2.0 |
skipisz/linux | drivers/usb/storage/freecom.c | 4635 | 15599 | /* Driver for Freecom USB/IDE adaptor
*
* Freecom v0.1:
*
* First release
*
* Current development and maintenance by:
* (C) 2000 David Brown <usb-storage@davidb.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
* This driver was developed with information provided in FREECOM's USB
* Programmers Reference Guide. For further information contact Freecom
* (http://www.freecom.de/)
*/
#include <linux/module.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include "usb.h"
#include "transport.h"
#include "protocol.h"
#include "debug.h"
MODULE_DESCRIPTION("Driver for Freecom USB/IDE adaptor");
MODULE_AUTHOR("David Brown <usb-storage@davidb.org>");
MODULE_LICENSE("GPL");
#ifdef CONFIG_USB_STORAGE_DEBUG
static void pdump (void *, int);
#endif
/* Bits of HD_STATUS */
#define ERR_STAT 0x01
#define DRQ_STAT 0x08
/* All of the outgoing packets are 64 bytes long. */
struct freecom_cb_wrap {
u8 Type; /* Command type. */
u8 Timeout; /* Timeout in seconds. */
u8 Atapi[12]; /* An ATAPI packet. */
u8 Filler[50]; /* Padding Data. */
};
struct freecom_xfer_wrap {
u8 Type; /* Command type. */
u8 Timeout; /* Timeout in seconds. */
__le32 Count; /* Number of bytes to transfer. */
u8 Pad[58];
} __attribute__ ((packed));
struct freecom_ide_out {
u8 Type; /* Type + IDE register. */
u8 Pad;
__le16 Value; /* Value to write. */
u8 Pad2[60];
};
struct freecom_ide_in {
u8 Type; /* Type | IDE register. */
u8 Pad[63];
};
struct freecom_status {
u8 Status;
u8 Reason;
__le16 Count;
u8 Pad[60];
};
/* Freecom stuffs the interrupt status in the INDEX_STAT bit of the ide
* register. */
#define FCM_INT_STATUS 0x02 /* INDEX_STAT */
#define FCM_STATUS_BUSY 0x80
/* These are the packet types. The low bit indicates that this command
* should wait for an interrupt. */
#define FCM_PACKET_ATAPI 0x21
#define FCM_PACKET_STATUS 0x20
/* Receive data from the IDE interface. The ATAPI packet has already
* waited, so the data should be immediately available. */
#define FCM_PACKET_INPUT 0x81
/* Send data to the IDE interface. */
#define FCM_PACKET_OUTPUT 0x01
/* Write a value to an ide register. Or the ide register to write after
* munging the address a bit. */
#define FCM_PACKET_IDE_WRITE 0x40
#define FCM_PACKET_IDE_READ 0xC0
/* All packets (except for status) are 64 bytes long. */
#define FCM_PACKET_LENGTH 64
#define FCM_STATUS_PACKET_LENGTH 4
static int init_freecom(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 freecom_usb_ids[] = {
# include "unusual_freecom.h"
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, freecom_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 freecom_unusual_dev_list[] = {
# include "unusual_freecom.h"
{ } /* Terminating entry */
};
#undef UNUSUAL_DEV
static int
freecom_readdata (struct scsi_cmnd *srb, struct us_data *us,
unsigned int ipipe, unsigned int opipe, int count)
{
struct freecom_xfer_wrap *fxfr =
(struct freecom_xfer_wrap *) us->iobuf;
int result;
fxfr->Type = FCM_PACKET_INPUT | 0x00;
fxfr->Timeout = 0; /* Short timeout for debugging. */
fxfr->Count = cpu_to_le32 (count);
memset (fxfr->Pad, 0, sizeof (fxfr->Pad));
US_DEBUGP("Read data Freecom! (c=%d)\n", count);
/* Issue the transfer command. */
result = usb_stor_bulk_transfer_buf (us, opipe, fxfr,
FCM_PACKET_LENGTH, NULL);
if (result != USB_STOR_XFER_GOOD) {
US_DEBUGP ("Freecom readdata transport error\n");
return USB_STOR_TRANSPORT_ERROR;
}
/* Now transfer all of our blocks. */
US_DEBUGP("Start of read\n");
result = usb_stor_bulk_srb(us, ipipe, srb);
US_DEBUGP("freecom_readdata done!\n");
if (result > USB_STOR_XFER_SHORT)
return USB_STOR_TRANSPORT_ERROR;
return USB_STOR_TRANSPORT_GOOD;
}
static int
freecom_writedata (struct scsi_cmnd *srb, struct us_data *us,
int unsigned ipipe, unsigned int opipe, int count)
{
struct freecom_xfer_wrap *fxfr =
(struct freecom_xfer_wrap *) us->iobuf;
int result;
fxfr->Type = FCM_PACKET_OUTPUT | 0x00;
fxfr->Timeout = 0; /* Short timeout for debugging. */
fxfr->Count = cpu_to_le32 (count);
memset (fxfr->Pad, 0, sizeof (fxfr->Pad));
US_DEBUGP("Write data Freecom! (c=%d)\n", count);
/* Issue the transfer command. */
result = usb_stor_bulk_transfer_buf (us, opipe, fxfr,
FCM_PACKET_LENGTH, NULL);
if (result != USB_STOR_XFER_GOOD) {
US_DEBUGP ("Freecom writedata transport error\n");
return USB_STOR_TRANSPORT_ERROR;
}
/* Now transfer all of our blocks. */
US_DEBUGP("Start of write\n");
result = usb_stor_bulk_srb(us, opipe, srb);
US_DEBUGP("freecom_writedata done!\n");
if (result > USB_STOR_XFER_SHORT)
return USB_STOR_TRANSPORT_ERROR;
return USB_STOR_TRANSPORT_GOOD;
}
/*
* Transport for the Freecom USB/IDE adaptor.
*
*/
static int freecom_transport(struct scsi_cmnd *srb, struct us_data *us)
{
struct freecom_cb_wrap *fcb;
struct freecom_status *fst;
unsigned int ipipe, opipe; /* We need both pipes. */
int result;
unsigned int partial;
int length;
fcb = (struct freecom_cb_wrap *) us->iobuf;
fst = (struct freecom_status *) us->iobuf;
US_DEBUGP("Freecom TRANSPORT STARTED\n");
/* Get handles for both transports. */
opipe = us->send_bulk_pipe;
ipipe = us->recv_bulk_pipe;
/* The ATAPI Command always goes out first. */
fcb->Type = FCM_PACKET_ATAPI | 0x00;
fcb->Timeout = 0;
memcpy (fcb->Atapi, srb->cmnd, 12);
memset (fcb->Filler, 0, sizeof (fcb->Filler));
US_DEBUG(pdump (srb->cmnd, 12));
/* Send it out. */
result = usb_stor_bulk_transfer_buf (us, opipe, fcb,
FCM_PACKET_LENGTH, NULL);
/* The Freecom device will only fail if there is something wrong in
* USB land. It returns the status in its own registers, which
* come back in the bulk pipe. */
if (result != USB_STOR_XFER_GOOD) {
US_DEBUGP ("freecom transport error\n");
return USB_STOR_TRANSPORT_ERROR;
}
/* There are times we can optimize out this status read, but it
* doesn't hurt us to always do it now. */
result = usb_stor_bulk_transfer_buf (us, ipipe, fst,
FCM_STATUS_PACKET_LENGTH, &partial);
US_DEBUGP("foo Status result %d %u\n", result, partial);
if (result != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
US_DEBUG(pdump ((void *) fst, partial));
/* The firmware will time-out commands after 20 seconds. Some commands
* can legitimately take longer than this, so we use a different
* command that only waits for the interrupt and then sends status,
* without having to send a new ATAPI command to the device.
*
* NOTE: There is some indication that a data transfer after a timeout
* may not work, but that is a condition that should never happen.
*/
while (fst->Status & FCM_STATUS_BUSY) {
US_DEBUGP("20 second USB/ATAPI bridge TIMEOUT occurred!\n");
US_DEBUGP("fst->Status is %x\n", fst->Status);
/* Get the status again */
fcb->Type = FCM_PACKET_STATUS;
fcb->Timeout = 0;
memset (fcb->Atapi, 0, sizeof(fcb->Atapi));
memset (fcb->Filler, 0, sizeof (fcb->Filler));
/* Send it out. */
result = usb_stor_bulk_transfer_buf (us, opipe, fcb,
FCM_PACKET_LENGTH, NULL);
/* The Freecom device will only fail if there is something
* wrong in USB land. It returns the status in its own
* registers, which come back in the bulk pipe.
*/
if (result != USB_STOR_XFER_GOOD) {
US_DEBUGP ("freecom transport error\n");
return USB_STOR_TRANSPORT_ERROR;
}
/* get the data */
result = usb_stor_bulk_transfer_buf (us, ipipe, fst,
FCM_STATUS_PACKET_LENGTH, &partial);
US_DEBUGP("bar Status result %d %u\n", result, partial);
if (result != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
US_DEBUG(pdump ((void *) fst, partial));
}
if (partial != 4)
return USB_STOR_TRANSPORT_ERROR;
if ((fst->Status & 1) != 0) {
US_DEBUGP("operation failed\n");
return USB_STOR_TRANSPORT_FAILED;
}
/* The device might not have as much data available as we
* requested. If you ask for more than the device has, this reads
* and such will hang. */
US_DEBUGP("Device indicates that it has %d bytes available\n",
le16_to_cpu (fst->Count));
US_DEBUGP("SCSI requested %d\n", scsi_bufflen(srb));
/* Find the length we desire to read. */
switch (srb->cmnd[0]) {
case INQUIRY:
case REQUEST_SENSE: /* 16 or 18 bytes? spec says 18, lots of devices only have 16 */
case MODE_SENSE:
case MODE_SENSE_10:
length = le16_to_cpu(fst->Count);
break;
default:
length = scsi_bufflen(srb);
}
/* verify that this amount is legal */
if (length > scsi_bufflen(srb)) {
length = scsi_bufflen(srb);
US_DEBUGP("Truncating request to match buffer length: %d\n", length);
}
/* What we do now depends on what direction the data is supposed to
* move in. */
switch (us->srb->sc_data_direction) {
case DMA_FROM_DEVICE:
/* catch bogus "read 0 length" case */
if (!length)
break;
/* Make sure that the status indicates that the device
* wants data as well. */
if ((fst->Status & DRQ_STAT) == 0 || (fst->Reason & 3) != 2) {
US_DEBUGP("SCSI wants data, drive doesn't have any\n");
return USB_STOR_TRANSPORT_FAILED;
}
result = freecom_readdata (srb, us, ipipe, opipe, length);
if (result != USB_STOR_TRANSPORT_GOOD)
return result;
US_DEBUGP("FCM: Waiting for status\n");
result = usb_stor_bulk_transfer_buf (us, ipipe, fst,
FCM_PACKET_LENGTH, &partial);
US_DEBUG(pdump ((void *) fst, partial));
if (partial != 4 || result > USB_STOR_XFER_SHORT)
return USB_STOR_TRANSPORT_ERROR;
if ((fst->Status & ERR_STAT) != 0) {
US_DEBUGP("operation failed\n");
return USB_STOR_TRANSPORT_FAILED;
}
if ((fst->Reason & 3) != 3) {
US_DEBUGP("Drive seems still hungry\n");
return USB_STOR_TRANSPORT_FAILED;
}
US_DEBUGP("Transfer happy\n");
break;
case DMA_TO_DEVICE:
/* catch bogus "write 0 length" case */
if (!length)
break;
/* Make sure the status indicates that the device wants to
* send us data. */
/* !!IMPLEMENT!! */
result = freecom_writedata (srb, us, ipipe, opipe, length);
if (result != USB_STOR_TRANSPORT_GOOD)
return result;
US_DEBUGP("FCM: Waiting for status\n");
result = usb_stor_bulk_transfer_buf (us, ipipe, fst,
FCM_PACKET_LENGTH, &partial);
if (partial != 4 || result > USB_STOR_XFER_SHORT)
return USB_STOR_TRANSPORT_ERROR;
if ((fst->Status & ERR_STAT) != 0) {
US_DEBUGP("operation failed\n");
return USB_STOR_TRANSPORT_FAILED;
}
if ((fst->Reason & 3) != 3) {
US_DEBUGP("Drive seems still hungry\n");
return USB_STOR_TRANSPORT_FAILED;
}
US_DEBUGP("Transfer happy\n");
break;
case DMA_NONE:
/* Easy, do nothing. */
break;
default:
/* should never hit here -- filtered in usb.c */
US_DEBUGP ("freecom unimplemented direction: %d\n",
us->srb->sc_data_direction);
/* Return fail, SCSI seems to handle this better. */
return USB_STOR_TRANSPORT_FAILED;
break;
}
return USB_STOR_TRANSPORT_GOOD;
}
static int init_freecom(struct us_data *us)
{
int result;
char *buffer = us->iobuf;
/* The DMA-mapped I/O buffer is 64 bytes long, just right for
* all our packets. No need to allocate any extra buffer space.
*/
result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
0x4c, 0xc0, 0x4346, 0x0, buffer, 0x20, 3*HZ);
buffer[32] = '\0';
US_DEBUGP("String returned from FC init is: %s\n", buffer);
/* Special thanks to the people at Freecom for providing me with
* this "magic sequence", which they use in their Windows and MacOS
* drivers to make sure that all the attached perhiperals are
* properly reset.
*/
/* send reset */
result = usb_stor_control_msg(us, us->send_ctrl_pipe,
0x4d, 0x40, 0x24d8, 0x0, NULL, 0x0, 3*HZ);
US_DEBUGP("result from activate reset is %d\n", result);
/* wait 250ms */
mdelay(250);
/* clear reset */
result = usb_stor_control_msg(us, us->send_ctrl_pipe,
0x4d, 0x40, 0x24f8, 0x0, NULL, 0x0, 3*HZ);
US_DEBUGP("result from clear reset is %d\n", result);
/* wait 3 seconds */
mdelay(3 * 1000);
return USB_STOR_TRANSPORT_GOOD;
}
static int usb_stor_freecom_reset(struct us_data *us)
{
printk (KERN_CRIT "freecom reset called\n");
/* We don't really have this feature. */
return FAILED;
}
#ifdef CONFIG_USB_STORAGE_DEBUG
static void pdump (void *ibuffer, int length)
{
static char line[80];
int offset = 0;
unsigned char *buffer = (unsigned char *) ibuffer;
int i, j;
int from, base;
offset = 0;
for (i = 0; i < length; i++) {
if ((i & 15) == 0) {
if (i > 0) {
offset += sprintf (line+offset, " - ");
for (j = i - 16; j < i; j++) {
if (buffer[j] >= 32 && buffer[j] <= 126)
line[offset++] = buffer[j];
else
line[offset++] = '.';
}
line[offset] = 0;
US_DEBUGP("%s\n", line);
offset = 0;
}
offset += sprintf (line+offset, "%08x:", i);
} else if ((i & 7) == 0) {
offset += sprintf (line+offset, " -");
}
offset += sprintf (line+offset, " %02x", buffer[i] & 0xff);
}
/* Add the last "chunk" of data. */
from = (length - 1) % 16;
base = ((length - 1) / 16) * 16;
for (i = from + 1; i < 16; i++)
offset += sprintf (line+offset, " ");
if (from < 8)
offset += sprintf (line+offset, " ");
offset += sprintf (line+offset, " - ");
for (i = 0; i <= from; i++) {
if (buffer[base+i] >= 32 && buffer[base+i] <= 126)
line[offset++] = buffer[base+i];
else
line[offset++] = '.';
}
line[offset] = 0;
US_DEBUGP("%s\n", line);
offset = 0;
}
#endif
static int freecom_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 - freecom_usb_ids) + freecom_unusual_dev_list);
if (result)
return result;
us->transport_name = "Freecom";
us->transport = freecom_transport;
us->transport_reset = usb_stor_freecom_reset;
us->max_lun = 0;
result = usb_stor_probe2(us);
return result;
}
static struct usb_driver freecom_driver = {
.name = "ums-freecom",
.probe = freecom_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 = freecom_usb_ids,
.soft_unbind = 1,
.no_dynamic_id = 1,
};
module_usb_driver(freecom_driver);
| gpl-2.0 |
LIFECorp/kernel | fs/jfs/xattr.c | 5147 | 27926 | /*
* Copyright (C) International Business Machines Corp., 2000-2004
* Copyright (C) Christoph Hellwig, 2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/capability.h>
#include <linux/fs.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/slab.h>
#include <linux/quotaops.h>
#include <linux/security.h>
#include "jfs_incore.h"
#include "jfs_superblock.h"
#include "jfs_dmap.h"
#include "jfs_debug.h"
#include "jfs_dinode.h"
#include "jfs_extent.h"
#include "jfs_metapage.h"
#include "jfs_xattr.h"
#include "jfs_acl.h"
/*
* jfs_xattr.c: extended attribute service
*
* Overall design --
*
* Format:
*
* Extended attribute lists (jfs_ea_list) consist of an overall size (32 bit
* value) and a variable (0 or more) number of extended attribute
* entries. Each extended attribute entry (jfs_ea) is a <name,value> double
* where <name> is constructed from a null-terminated ascii string
* (1 ... 255 bytes in the name) and <value> is arbitrary 8 bit data
* (1 ... 65535 bytes). The in-memory format is
*
* 0 1 2 4 4 + namelen + 1
* +-------+--------+--------+----------------+-------------------+
* | Flags | Name | Value | Name String \0 | Data . . . . |
* | | Length | Length | | |
* +-------+--------+--------+----------------+-------------------+
*
* A jfs_ea_list then is structured as
*
* 0 4 4 + EA_SIZE(ea1)
* +------------+-------------------+--------------------+-----
* | Overall EA | First FEA Element | Second FEA Element | .....
* | List Size | | |
* +------------+-------------------+--------------------+-----
*
* On-disk:
*
* FEALISTs are stored on disk using blocks allocated by dbAlloc() and
* written directly. An EA list may be in-lined in the inode if there is
* sufficient room available.
*/
struct ea_buffer {
int flag; /* Indicates what storage xattr points to */
int max_size; /* largest xattr that fits in current buffer */
dxd_t new_ea; /* dxd to replace ea when modifying xattr */
struct metapage *mp; /* metapage containing ea list */
struct jfs_ea_list *xattr; /* buffer containing ea list */
};
/*
* ea_buffer.flag values
*/
#define EA_INLINE 0x0001
#define EA_EXTENT 0x0002
#define EA_NEW 0x0004
#define EA_MALLOC 0x0008
static int is_known_namespace(const char *name)
{
if (strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN) &&
strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN) &&
strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN))
return false;
return true;
}
/*
* These three routines are used to recognize on-disk extended attributes
* that are in a recognized namespace. If the attribute is not recognized,
* "os2." is prepended to the name
*/
static int is_os2_xattr(struct jfs_ea *ea)
{
return !is_known_namespace(ea->name);
}
static inline int name_size(struct jfs_ea *ea)
{
if (is_os2_xattr(ea))
return ea->namelen + XATTR_OS2_PREFIX_LEN;
else
return ea->namelen;
}
static inline int copy_name(char *buffer, struct jfs_ea *ea)
{
int len = ea->namelen;
if (is_os2_xattr(ea)) {
memcpy(buffer, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN);
buffer += XATTR_OS2_PREFIX_LEN;
len += XATTR_OS2_PREFIX_LEN;
}
memcpy(buffer, ea->name, ea->namelen);
buffer[ea->namelen] = 0;
return len;
}
/* Forward references */
static void ea_release(struct inode *inode, struct ea_buffer *ea_buf);
/*
* NAME: ea_write_inline
*
* FUNCTION: Attempt to write an EA inline if area is available
*
* PRE CONDITIONS:
* Already verified that the specified EA is small enough to fit inline
*
* PARAMETERS:
* ip - Inode pointer
* ealist - EA list pointer
* size - size of ealist in bytes
* ea - dxd_t structure to be filled in with necessary EA information
* if we successfully copy the EA inline
*
* NOTES:
* Checks if the inode's inline area is available. If so, copies EA inline
* and sets <ea> fields appropriately. Otherwise, returns failure, EA will
* have to be put into an extent.
*
* RETURNS: 0 for successful copy to inline area; -1 if area not available
*/
static int ea_write_inline(struct inode *ip, struct jfs_ea_list *ealist,
int size, dxd_t * ea)
{
struct jfs_inode_info *ji = JFS_IP(ip);
/*
* Make sure we have an EA -- the NULL EA list is valid, but you
* can't copy it!
*/
if (ealist && size > sizeof (struct jfs_ea_list)) {
assert(size <= sizeof (ji->i_inline_ea));
/*
* See if the space is available or if it is already being
* used for an inline EA.
*/
if (!(ji->mode2 & INLINEEA) && !(ji->ea.flag & DXD_INLINE))
return -EPERM;
DXDsize(ea, size);
DXDlength(ea, 0);
DXDaddress(ea, 0);
memcpy(ji->i_inline_ea, ealist, size);
ea->flag = DXD_INLINE;
ji->mode2 &= ~INLINEEA;
} else {
ea->flag = 0;
DXDsize(ea, 0);
DXDlength(ea, 0);
DXDaddress(ea, 0);
/* Free up INLINE area */
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
}
return 0;
}
/*
* NAME: ea_write
*
* FUNCTION: Write an EA for an inode
*
* PRE CONDITIONS: EA has been verified
*
* PARAMETERS:
* ip - Inode pointer
* ealist - EA list pointer
* size - size of ealist in bytes
* ea - dxd_t structure to be filled in appropriately with where the
* EA was copied
*
* NOTES: Will write EA inline if able to, otherwise allocates blocks for an
* extent and synchronously writes it to those blocks.
*
* RETURNS: 0 for success; Anything else indicates failure
*/
static int ea_write(struct inode *ip, struct jfs_ea_list *ealist, int size,
dxd_t * ea)
{
struct super_block *sb = ip->i_sb;
struct jfs_inode_info *ji = JFS_IP(ip);
struct jfs_sb_info *sbi = JFS_SBI(sb);
int nblocks;
s64 blkno;
int rc = 0, i;
char *cp;
s32 nbytes, nb;
s32 bytes_to_write;
struct metapage *mp;
/*
* Quick check to see if this is an in-linable EA. Short EAs
* and empty EAs are all in-linable, provided the space exists.
*/
if (!ealist || size <= sizeof (ji->i_inline_ea)) {
if (!ea_write_inline(ip, ealist, size, ea))
return 0;
}
/* figure out how many blocks we need */
nblocks = (size + (sb->s_blocksize - 1)) >> sb->s_blocksize_bits;
/* Allocate new blocks to quota. */
rc = dquot_alloc_block(ip, nblocks);
if (rc)
return rc;
rc = dbAlloc(ip, INOHINT(ip), nblocks, &blkno);
if (rc) {
/*Rollback quota allocation. */
dquot_free_block(ip, nblocks);
return rc;
}
/*
* Now have nblocks worth of storage to stuff into the FEALIST.
* loop over the FEALIST copying data into the buffer one page at
* a time.
*/
cp = (char *) ealist;
nbytes = size;
for (i = 0; i < nblocks; i += sbi->nbperpage) {
/*
* Determine how many bytes for this request, and round up to
* the nearest aggregate block size
*/
nb = min(PSIZE, nbytes);
bytes_to_write =
((((nb + sb->s_blocksize - 1)) >> sb->s_blocksize_bits))
<< sb->s_blocksize_bits;
if (!(mp = get_metapage(ip, blkno + i, bytes_to_write, 1))) {
rc = -EIO;
goto failed;
}
memcpy(mp->data, cp, nb);
/*
* We really need a way to propagate errors for
* forced writes like this one. --hch
*
* (__write_metapage => release_metapage => flush_metapage)
*/
#ifdef _JFS_FIXME
if ((rc = flush_metapage(mp))) {
/*
* the write failed -- this means that the buffer
* is still assigned and the blocks are not being
* used. this seems like the best error recovery
* we can get ...
*/
goto failed;
}
#else
flush_metapage(mp);
#endif
cp += PSIZE;
nbytes -= nb;
}
ea->flag = DXD_EXTENT;
DXDsize(ea, le32_to_cpu(ealist->size));
DXDlength(ea, nblocks);
DXDaddress(ea, blkno);
/* Free up INLINE area */
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
return 0;
failed:
/* Rollback quota allocation. */
dquot_free_block(ip, nblocks);
dbFree(ip, blkno, nblocks);
return rc;
}
/*
* NAME: ea_read_inline
*
* FUNCTION: Read an inlined EA into user's buffer
*
* PARAMETERS:
* ip - Inode pointer
* ealist - Pointer to buffer to fill in with EA
*
* RETURNS: 0
*/
static int ea_read_inline(struct inode *ip, struct jfs_ea_list *ealist)
{
struct jfs_inode_info *ji = JFS_IP(ip);
int ea_size = sizeDXD(&ji->ea);
if (ea_size == 0) {
ealist->size = 0;
return 0;
}
/* Sanity Check */
if ((sizeDXD(&ji->ea) > sizeof (ji->i_inline_ea)))
return -EIO;
if (le32_to_cpu(((struct jfs_ea_list *) &ji->i_inline_ea)->size)
!= ea_size)
return -EIO;
memcpy(ealist, ji->i_inline_ea, ea_size);
return 0;
}
/*
* NAME: ea_read
*
* FUNCTION: copy EA data into user's buffer
*
* PARAMETERS:
* ip - Inode pointer
* ealist - Pointer to buffer to fill in with EA
*
* NOTES: If EA is inline calls ea_read_inline() to copy EA.
*
* RETURNS: 0 for success; other indicates failure
*/
static int ea_read(struct inode *ip, struct jfs_ea_list *ealist)
{
struct super_block *sb = ip->i_sb;
struct jfs_inode_info *ji = JFS_IP(ip);
struct jfs_sb_info *sbi = JFS_SBI(sb);
int nblocks;
s64 blkno;
char *cp = (char *) ealist;
int i;
int nbytes, nb;
s32 bytes_to_read;
struct metapage *mp;
/* quick check for in-line EA */
if (ji->ea.flag & DXD_INLINE)
return ea_read_inline(ip, ealist);
nbytes = sizeDXD(&ji->ea);
if (!nbytes) {
jfs_error(sb, "ea_read: nbytes is 0");
return -EIO;
}
/*
* Figure out how many blocks were allocated when this EA list was
* originally written to disk.
*/
nblocks = lengthDXD(&ji->ea) << sbi->l2nbperpage;
blkno = addressDXD(&ji->ea) << sbi->l2nbperpage;
/*
* I have found the disk blocks which were originally used to store
* the FEALIST. now i loop over each contiguous block copying the
* data into the buffer.
*/
for (i = 0; i < nblocks; i += sbi->nbperpage) {
/*
* Determine how many bytes for this request, and round up to
* the nearest aggregate block size
*/
nb = min(PSIZE, nbytes);
bytes_to_read =
((((nb + sb->s_blocksize - 1)) >> sb->s_blocksize_bits))
<< sb->s_blocksize_bits;
if (!(mp = read_metapage(ip, blkno + i, bytes_to_read, 1)))
return -EIO;
memcpy(cp, mp->data, nb);
release_metapage(mp);
cp += PSIZE;
nbytes -= nb;
}
return 0;
}
/*
* NAME: ea_get
*
* FUNCTION: Returns buffer containing existing extended attributes.
* The size of the buffer will be the larger of the existing
* attributes size, or min_size.
*
* The buffer, which may be inlined in the inode or in the
* page cache must be release by calling ea_release or ea_put
*
* PARAMETERS:
* inode - Inode pointer
* ea_buf - Structure to be populated with ealist and its metadata
* min_size- minimum size of buffer to be returned
*
* RETURNS: 0 for success; Other indicates failure
*/
static int ea_get(struct inode *inode, struct ea_buffer *ea_buf, int min_size)
{
struct jfs_inode_info *ji = JFS_IP(inode);
struct super_block *sb = inode->i_sb;
int size;
int ea_size = sizeDXD(&ji->ea);
int blocks_needed, current_blocks;
s64 blkno;
int rc;
int quota_allocation = 0;
/* When fsck.jfs clears a bad ea, it doesn't clear the size */
if (ji->ea.flag == 0)
ea_size = 0;
if (ea_size == 0) {
if (min_size == 0) {
ea_buf->flag = 0;
ea_buf->max_size = 0;
ea_buf->xattr = NULL;
return 0;
}
if ((min_size <= sizeof (ji->i_inline_ea)) &&
(ji->mode2 & INLINEEA)) {
ea_buf->flag = EA_INLINE | EA_NEW;
ea_buf->max_size = sizeof (ji->i_inline_ea);
ea_buf->xattr = (struct jfs_ea_list *) ji->i_inline_ea;
DXDlength(&ea_buf->new_ea, 0);
DXDaddress(&ea_buf->new_ea, 0);
ea_buf->new_ea.flag = DXD_INLINE;
DXDsize(&ea_buf->new_ea, min_size);
return 0;
}
current_blocks = 0;
} else if (ji->ea.flag & DXD_INLINE) {
if (min_size <= sizeof (ji->i_inline_ea)) {
ea_buf->flag = EA_INLINE;
ea_buf->max_size = sizeof (ji->i_inline_ea);
ea_buf->xattr = (struct jfs_ea_list *) ji->i_inline_ea;
goto size_check;
}
current_blocks = 0;
} else {
if (!(ji->ea.flag & DXD_EXTENT)) {
jfs_error(sb, "ea_get: invalid ea.flag)");
return -EIO;
}
current_blocks = (ea_size + sb->s_blocksize - 1) >>
sb->s_blocksize_bits;
}
size = max(min_size, ea_size);
if (size > PSIZE) {
/*
* To keep the rest of the code simple. Allocate a
* contiguous buffer to work with
*/
ea_buf->xattr = kmalloc(size, GFP_KERNEL);
if (ea_buf->xattr == NULL)
return -ENOMEM;
ea_buf->flag = EA_MALLOC;
ea_buf->max_size = (size + sb->s_blocksize - 1) &
~(sb->s_blocksize - 1);
if (ea_size == 0)
return 0;
if ((rc = ea_read(inode, ea_buf->xattr))) {
kfree(ea_buf->xattr);
ea_buf->xattr = NULL;
return rc;
}
goto size_check;
}
blocks_needed = (min_size + sb->s_blocksize - 1) >>
sb->s_blocksize_bits;
if (blocks_needed > current_blocks) {
/* Allocate new blocks to quota. */
rc = dquot_alloc_block(inode, blocks_needed);
if (rc)
return -EDQUOT;
quota_allocation = blocks_needed;
rc = dbAlloc(inode, INOHINT(inode), (s64) blocks_needed,
&blkno);
if (rc)
goto clean_up;
DXDlength(&ea_buf->new_ea, blocks_needed);
DXDaddress(&ea_buf->new_ea, blkno);
ea_buf->new_ea.flag = DXD_EXTENT;
DXDsize(&ea_buf->new_ea, min_size);
ea_buf->flag = EA_EXTENT | EA_NEW;
ea_buf->mp = get_metapage(inode, blkno,
blocks_needed << sb->s_blocksize_bits,
1);
if (ea_buf->mp == NULL) {
dbFree(inode, blkno, (s64) blocks_needed);
rc = -EIO;
goto clean_up;
}
ea_buf->xattr = ea_buf->mp->data;
ea_buf->max_size = (min_size + sb->s_blocksize - 1) &
~(sb->s_blocksize - 1);
if (ea_size == 0)
return 0;
if ((rc = ea_read(inode, ea_buf->xattr))) {
discard_metapage(ea_buf->mp);
dbFree(inode, blkno, (s64) blocks_needed);
goto clean_up;
}
goto size_check;
}
ea_buf->flag = EA_EXTENT;
ea_buf->mp = read_metapage(inode, addressDXD(&ji->ea),
lengthDXD(&ji->ea) << sb->s_blocksize_bits,
1);
if (ea_buf->mp == NULL) {
rc = -EIO;
goto clean_up;
}
ea_buf->xattr = ea_buf->mp->data;
ea_buf->max_size = (ea_size + sb->s_blocksize - 1) &
~(sb->s_blocksize - 1);
size_check:
if (EALIST_SIZE(ea_buf->xattr) != ea_size) {
printk(KERN_ERR "ea_get: invalid extended attribute\n");
print_hex_dump(KERN_ERR, "", DUMP_PREFIX_ADDRESS, 16, 1,
ea_buf->xattr, ea_size, 1);
ea_release(inode, ea_buf);
rc = -EIO;
goto clean_up;
}
return ea_size;
clean_up:
/* Rollback quota allocation */
if (quota_allocation)
dquot_free_block(inode, quota_allocation);
return (rc);
}
static void ea_release(struct inode *inode, struct ea_buffer *ea_buf)
{
if (ea_buf->flag & EA_MALLOC)
kfree(ea_buf->xattr);
else if (ea_buf->flag & EA_EXTENT) {
assert(ea_buf->mp);
release_metapage(ea_buf->mp);
if (ea_buf->flag & EA_NEW)
dbFree(inode, addressDXD(&ea_buf->new_ea),
lengthDXD(&ea_buf->new_ea));
}
}
static int ea_put(tid_t tid, struct inode *inode, struct ea_buffer *ea_buf,
int new_size)
{
struct jfs_inode_info *ji = JFS_IP(inode);
unsigned long old_blocks, new_blocks;
int rc = 0;
if (new_size == 0) {
ea_release(inode, ea_buf);
ea_buf = NULL;
} else if (ea_buf->flag & EA_INLINE) {
assert(new_size <= sizeof (ji->i_inline_ea));
ji->mode2 &= ~INLINEEA;
ea_buf->new_ea.flag = DXD_INLINE;
DXDsize(&ea_buf->new_ea, new_size);
DXDaddress(&ea_buf->new_ea, 0);
DXDlength(&ea_buf->new_ea, 0);
} else if (ea_buf->flag & EA_MALLOC) {
rc = ea_write(inode, ea_buf->xattr, new_size, &ea_buf->new_ea);
kfree(ea_buf->xattr);
} else if (ea_buf->flag & EA_NEW) {
/* We have already allocated a new dxd */
flush_metapage(ea_buf->mp);
} else {
/* ->xattr must point to original ea's metapage */
rc = ea_write(inode, ea_buf->xattr, new_size, &ea_buf->new_ea);
discard_metapage(ea_buf->mp);
}
if (rc)
return rc;
old_blocks = new_blocks = 0;
if (ji->ea.flag & DXD_EXTENT) {
invalidate_dxd_metapages(inode, ji->ea);
old_blocks = lengthDXD(&ji->ea);
}
if (ea_buf) {
txEA(tid, inode, &ji->ea, &ea_buf->new_ea);
if (ea_buf->new_ea.flag & DXD_EXTENT) {
new_blocks = lengthDXD(&ea_buf->new_ea);
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
}
ji->ea = ea_buf->new_ea;
} else {
txEA(tid, inode, &ji->ea, NULL);
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
ji->ea.flag = 0;
ji->ea.size = 0;
}
/* If old blocks exist, they must be removed from quota allocation. */
if (old_blocks)
dquot_free_block(inode, old_blocks);
inode->i_ctime = CURRENT_TIME;
return 0;
}
/*
* can_set_system_xattr
*
* This code is specific to the system.* namespace. It contains policy
* which doesn't belong in the main xattr codepath.
*/
static int can_set_system_xattr(struct inode *inode, const char *name,
const void *value, size_t value_len)
{
#ifdef CONFIG_JFS_POSIX_ACL
struct posix_acl *acl;
int rc;
if (!inode_owner_or_capable(inode))
return -EPERM;
/*
* POSIX_ACL_XATTR_ACCESS is tied to i_mode
*/
if (strcmp(name, POSIX_ACL_XATTR_ACCESS) == 0) {
acl = posix_acl_from_xattr(value, value_len);
if (IS_ERR(acl)) {
rc = PTR_ERR(acl);
printk(KERN_ERR "posix_acl_from_xattr returned %d\n",
rc);
return rc;
}
if (acl) {
rc = posix_acl_equiv_mode(acl, &inode->i_mode);
posix_acl_release(acl);
if (rc < 0) {
printk(KERN_ERR
"posix_acl_equiv_mode returned %d\n",
rc);
return rc;
}
mark_inode_dirty(inode);
}
/*
* We're changing the ACL. Get rid of the cached one
*/
forget_cached_acl(inode, ACL_TYPE_ACCESS);
return 0;
} else if (strcmp(name, POSIX_ACL_XATTR_DEFAULT) == 0) {
acl = posix_acl_from_xattr(value, value_len);
if (IS_ERR(acl)) {
rc = PTR_ERR(acl);
printk(KERN_ERR "posix_acl_from_xattr returned %d\n",
rc);
return rc;
}
posix_acl_release(acl);
/*
* We're changing the default ACL. Get rid of the cached one
*/
forget_cached_acl(inode, ACL_TYPE_DEFAULT);
return 0;
}
#endif /* CONFIG_JFS_POSIX_ACL */
return -EOPNOTSUPP;
}
/*
* Most of the permission checking is done by xattr_permission in the vfs.
* The local file system is responsible for handling the system.* namespace.
* We also need to verify that this is a namespace that we recognize.
*/
static int can_set_xattr(struct inode *inode, const char *name,
const void *value, size_t value_len)
{
if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
return can_set_system_xattr(inode, name, value, value_len);
if (!strncmp(name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN)) {
/*
* This makes sure that we aren't trying to set an
* attribute in a different namespace by prefixing it
* with "os2."
*/
if (is_known_namespace(name + XATTR_OS2_PREFIX_LEN))
return -EOPNOTSUPP;
return 0;
}
/*
* Don't allow setting an attribute in an unknown namespace.
*/
if (strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) &&
strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN) &&
strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
return -EOPNOTSUPP;
return 0;
}
int __jfs_setxattr(tid_t tid, struct inode *inode, const char *name,
const void *value, size_t value_len, int flags)
{
struct jfs_ea_list *ealist;
struct jfs_ea *ea, *old_ea = NULL, *next_ea = NULL;
struct ea_buffer ea_buf;
int old_ea_size = 0;
int xattr_size;
int new_size;
int namelen = strlen(name);
char *os2name = NULL;
int found = 0;
int rc;
int length;
if (strncmp(name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN) == 0) {
os2name = kmalloc(namelen - XATTR_OS2_PREFIX_LEN + 1,
GFP_KERNEL);
if (!os2name)
return -ENOMEM;
strcpy(os2name, name + XATTR_OS2_PREFIX_LEN);
name = os2name;
namelen -= XATTR_OS2_PREFIX_LEN;
}
down_write(&JFS_IP(inode)->xattr_sem);
xattr_size = ea_get(inode, &ea_buf, 0);
if (xattr_size < 0) {
rc = xattr_size;
goto out;
}
again:
ealist = (struct jfs_ea_list *) ea_buf.xattr;
new_size = sizeof (struct jfs_ea_list);
if (xattr_size) {
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist);
ea = NEXT_EA(ea)) {
if ((namelen == ea->namelen) &&
(memcmp(name, ea->name, namelen) == 0)) {
found = 1;
if (flags & XATTR_CREATE) {
rc = -EEXIST;
goto release;
}
old_ea = ea;
old_ea_size = EA_SIZE(ea);
next_ea = NEXT_EA(ea);
} else
new_size += EA_SIZE(ea);
}
}
if (!found) {
if (flags & XATTR_REPLACE) {
rc = -ENODATA;
goto release;
}
if (value == NULL) {
rc = 0;
goto release;
}
}
if (value)
new_size += sizeof (struct jfs_ea) + namelen + 1 + value_len;
if (new_size > ea_buf.max_size) {
/*
* We need to allocate more space for merged ea list.
* We should only have loop to again: once.
*/
ea_release(inode, &ea_buf);
xattr_size = ea_get(inode, &ea_buf, new_size);
if (xattr_size < 0) {
rc = xattr_size;
goto out;
}
goto again;
}
/* Remove old ea of the same name */
if (found) {
/* number of bytes following target EA */
length = (char *) END_EALIST(ealist) - (char *) next_ea;
if (length > 0)
memmove(old_ea, next_ea, length);
xattr_size -= old_ea_size;
}
/* Add new entry to the end */
if (value) {
if (xattr_size == 0)
/* Completely new ea list */
xattr_size = sizeof (struct jfs_ea_list);
ea = (struct jfs_ea *) ((char *) ealist + xattr_size);
ea->flag = 0;
ea->namelen = namelen;
ea->valuelen = (cpu_to_le16(value_len));
memcpy(ea->name, name, namelen);
ea->name[namelen] = 0;
if (value_len)
memcpy(&ea->name[namelen + 1], value, value_len);
xattr_size += EA_SIZE(ea);
}
/* DEBUG - If we did this right, these number match */
if (xattr_size != new_size) {
printk(KERN_ERR
"jfs_xsetattr: xattr_size = %d, new_size = %d\n",
xattr_size, new_size);
rc = -EINVAL;
goto release;
}
/*
* If we're left with an empty list, there's no ea
*/
if (new_size == sizeof (struct jfs_ea_list))
new_size = 0;
ealist->size = cpu_to_le32(new_size);
rc = ea_put(tid, inode, &ea_buf, new_size);
goto out;
release:
ea_release(inode, &ea_buf);
out:
up_write(&JFS_IP(inode)->xattr_sem);
kfree(os2name);
return rc;
}
int jfs_setxattr(struct dentry *dentry, const char *name, const void *value,
size_t value_len, int flags)
{
struct inode *inode = dentry->d_inode;
struct jfs_inode_info *ji = JFS_IP(inode);
int rc;
tid_t tid;
if ((rc = can_set_xattr(inode, name, value, value_len)))
return rc;
if (value == NULL) { /* empty EA, do not remove */
value = "";
value_len = 0;
}
tid = txBegin(inode->i_sb, 0);
mutex_lock(&ji->commit_mutex);
rc = __jfs_setxattr(tid, dentry->d_inode, name, value, value_len,
flags);
if (!rc)
rc = txCommit(tid, 1, &inode, 0);
txEnd(tid);
mutex_unlock(&ji->commit_mutex);
return rc;
}
ssize_t __jfs_getxattr(struct inode *inode, const char *name, void *data,
size_t buf_size)
{
struct jfs_ea_list *ealist;
struct jfs_ea *ea;
struct ea_buffer ea_buf;
int xattr_size;
ssize_t size;
int namelen = strlen(name);
char *value;
down_read(&JFS_IP(inode)->xattr_sem);
xattr_size = ea_get(inode, &ea_buf, 0);
if (xattr_size < 0) {
size = xattr_size;
goto out;
}
if (xattr_size == 0)
goto not_found;
ealist = (struct jfs_ea_list *) ea_buf.xattr;
/* Find the named attribute */
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist); ea = NEXT_EA(ea))
if ((namelen == ea->namelen) &&
memcmp(name, ea->name, namelen) == 0) {
/* Found it */
size = le16_to_cpu(ea->valuelen);
if (!data)
goto release;
else if (size > buf_size) {
size = -ERANGE;
goto release;
}
value = ((char *) &ea->name) + ea->namelen + 1;
memcpy(data, value, size);
goto release;
}
not_found:
size = -ENODATA;
release:
ea_release(inode, &ea_buf);
out:
up_read(&JFS_IP(inode)->xattr_sem);
return size;
}
ssize_t jfs_getxattr(struct dentry *dentry, const char *name, void *data,
size_t buf_size)
{
int err;
if (strncmp(name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN) == 0) {
/*
* skip past "os2." prefix
*/
name += XATTR_OS2_PREFIX_LEN;
/*
* Don't allow retrieving properly prefixed attributes
* by prepending them with "os2."
*/
if (is_known_namespace(name))
return -EOPNOTSUPP;
}
err = __jfs_getxattr(dentry->d_inode, name, data, buf_size);
return err;
}
/*
* No special permissions are needed to list attributes except for trusted.*
*/
static inline int can_list(struct jfs_ea *ea)
{
return (strncmp(ea->name, XATTR_TRUSTED_PREFIX,
XATTR_TRUSTED_PREFIX_LEN) ||
capable(CAP_SYS_ADMIN));
}
ssize_t jfs_listxattr(struct dentry * dentry, char *data, size_t buf_size)
{
struct inode *inode = dentry->d_inode;
char *buffer;
ssize_t size = 0;
int xattr_size;
struct jfs_ea_list *ealist;
struct jfs_ea *ea;
struct ea_buffer ea_buf;
down_read(&JFS_IP(inode)->xattr_sem);
xattr_size = ea_get(inode, &ea_buf, 0);
if (xattr_size < 0) {
size = xattr_size;
goto out;
}
if (xattr_size == 0)
goto release;
ealist = (struct jfs_ea_list *) ea_buf.xattr;
/* compute required size of list */
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist); ea = NEXT_EA(ea)) {
if (can_list(ea))
size += name_size(ea) + 1;
}
if (!data)
goto release;
if (size > buf_size) {
size = -ERANGE;
goto release;
}
/* Copy attribute names to buffer */
buffer = data;
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist); ea = NEXT_EA(ea)) {
if (can_list(ea)) {
int namelen = copy_name(buffer, ea);
buffer += namelen + 1;
}
}
release:
ea_release(inode, &ea_buf);
out:
up_read(&JFS_IP(inode)->xattr_sem);
return size;
}
int jfs_removexattr(struct dentry *dentry, const char *name)
{
struct inode *inode = dentry->d_inode;
struct jfs_inode_info *ji = JFS_IP(inode);
int rc;
tid_t tid;
if ((rc = can_set_xattr(inode, name, NULL, 0)))
return rc;
tid = txBegin(inode->i_sb, 0);
mutex_lock(&ji->commit_mutex);
rc = __jfs_setxattr(tid, dentry->d_inode, name, NULL, 0, XATTR_REPLACE);
if (!rc)
rc = txCommit(tid, 1, &inode, 0);
txEnd(tid);
mutex_unlock(&ji->commit_mutex);
return rc;
}
#ifdef CONFIG_JFS_SECURITY
int jfs_initxattrs(struct inode *inode, const struct xattr *xattr_array,
void *fs_info)
{
const struct xattr *xattr;
tid_t *tid = fs_info;
char *name;
int err = 0;
for (xattr = xattr_array; xattr->name != NULL; xattr++) {
name = kmalloc(XATTR_SECURITY_PREFIX_LEN +
strlen(xattr->name) + 1, GFP_NOFS);
if (!name) {
err = -ENOMEM;
break;
}
strcpy(name, XATTR_SECURITY_PREFIX);
strcpy(name + XATTR_SECURITY_PREFIX_LEN, xattr->name);
err = __jfs_setxattr(*tid, inode, name,
xattr->value, xattr->value_len, 0);
kfree(name);
if (err < 0)
break;
}
return err;
}
int jfs_init_security(tid_t tid, struct inode *inode, struct inode *dir,
const struct qstr *qstr)
{
return security_inode_init_security(inode, dir, qstr,
&jfs_initxattrs, &tid);
}
#endif
| gpl-2.0 |
goodwin/android_kernel_lge_hammerhead-1 | drivers/staging/vt6655/IEEE11h.c | 5403 | 9034 | /*
* Copyright (c) 1996, 2005 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
* File: IEEE11h.c
*
* Purpose:
*
* Functions:
*
* Revision History:
*
* Author: Yiching Chen
*
* Date: Mar. 31, 2005
*
*/
#include "ttype.h"
#include "tmacro.h"
#include "tether.h"
#include "IEEE11h.h"
#include "device.h"
#include "wmgr.h"
#include "rxtx.h"
#include "channel.h"
/*--------------------- Static Definitions -------------------------*/
static int msglevel = MSG_LEVEL_INFO;
#pragma pack(1)
typedef struct _WLAN_FRAME_ACTION {
WLAN_80211HDR_A3 Header;
unsigned char byCategory;
unsigned char byAction;
unsigned char abyVars[1];
} WLAN_FRAME_ACTION, *PWLAN_FRAME_ACTION;
typedef struct _WLAN_FRAME_MSRREQ {
WLAN_80211HDR_A3 Header;
unsigned char byCategory;
unsigned char byAction;
unsigned char byDialogToken;
WLAN_IE_MEASURE_REQ sMSRReqEIDs[1];
} WLAN_FRAME_MSRREQ, *PWLAN_FRAME_MSRREQ;
typedef struct _WLAN_FRAME_MSRREP {
WLAN_80211HDR_A3 Header;
unsigned char byCategory;
unsigned char byAction;
unsigned char byDialogToken;
WLAN_IE_MEASURE_REP sMSRRepEIDs[1];
} WLAN_FRAME_MSRREP, *PWLAN_FRAME_MSRREP;
typedef struct _WLAN_FRAME_TPCREQ {
WLAN_80211HDR_A3 Header;
unsigned char byCategory;
unsigned char byAction;
unsigned char byDialogToken;
WLAN_IE_TPC_REQ sTPCReqEIDs;
} WLAN_FRAME_TPCREQ, *PWLAN_FRAME_TPCREQ;
typedef struct _WLAN_FRAME_TPCREP {
WLAN_80211HDR_A3 Header;
unsigned char byCategory;
unsigned char byAction;
unsigned char byDialogToken;
WLAN_IE_TPC_REP sTPCRepEIDs;
} WLAN_FRAME_TPCREP, *PWLAN_FRAME_TPCREP;
#pragma pack()
/* action field reference ieee 802.11h Table 20e */
#define ACTION_MSRREQ 0
#define ACTION_MSRREP 1
#define ACTION_TPCREQ 2
#define ACTION_TPCREP 3
#define ACTION_CHSW 4
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
/*--------------------- Static Functions --------------------------*/
static bool s_bRxMSRReq(PSMgmtObject pMgmt, PWLAN_FRAME_MSRREQ pMSRReq,
unsigned int uLength)
{
size_t uNumOfEIDs = 0;
bool bResult = true;
if (uLength <= WLAN_A3FR_MAXLEN)
memcpy(pMgmt->abyCurrentMSRReq, pMSRReq, uLength);
uNumOfEIDs = ((uLength - offsetof(WLAN_FRAME_MSRREQ,
sMSRReqEIDs))/
(sizeof(WLAN_IE_MEASURE_REQ)));
pMgmt->pCurrMeasureEIDRep = &(((PWLAN_FRAME_MSRREP)
(pMgmt->abyCurrentMSRRep))->sMSRRepEIDs[0]);
pMgmt->uLengthOfRepEIDs = 0;
bResult = CARDbStartMeasure(pMgmt->pAdapter,
((PWLAN_FRAME_MSRREQ)
(pMgmt->abyCurrentMSRReq))->sMSRReqEIDs,
uNumOfEIDs
);
return bResult;
}
static bool s_bRxTPCReq(PSMgmtObject pMgmt,
PWLAN_FRAME_TPCREQ pTPCReq,
unsigned char byRate,
unsigned char byRSSI)
{
PWLAN_FRAME_TPCREP pFrame;
PSTxMgmtPacket pTxPacket = NULL;
pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_A3FR_MAXLEN);
pTxPacket->p80211Header = (PUWLAN_80211HDR)((unsigned char *)pTxPacket +
sizeof(STxMgmtPacket));
pFrame = (PWLAN_FRAME_TPCREP)((unsigned char *)pTxPacket +
sizeof(STxMgmtPacket));
pFrame->Header.wFrameCtl = (WLAN_SET_FC_FTYPE(WLAN_FTYPE_MGMT) |
WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_ACTION)
);
memcpy(pFrame->Header.abyAddr1,
pTPCReq->Header.abyAddr2,
WLAN_ADDR_LEN);
memcpy(pFrame->Header.abyAddr2,
CARDpGetCurrentAddress(pMgmt->pAdapter),
WLAN_ADDR_LEN);
memcpy(pFrame->Header.abyAddr3,
pMgmt->abyCurrBSSID,
WLAN_BSSID_LEN);
pFrame->byCategory = 0;
pFrame->byAction = 3;
pFrame->byDialogToken = ((PWLAN_FRAME_MSRREQ)
(pMgmt->abyCurrentMSRReq))->byDialogToken;
pFrame->sTPCRepEIDs.byElementID = WLAN_EID_TPC_REP;
pFrame->sTPCRepEIDs.len = 2;
pFrame->sTPCRepEIDs.byTxPower = CARDbyGetTransmitPower(pMgmt->pAdapter);
switch (byRate) {
case RATE_54M:
pFrame->sTPCRepEIDs.byLinkMargin = 65 - byRSSI;
break;
case RATE_48M:
pFrame->sTPCRepEIDs.byLinkMargin = 66 - byRSSI;
break;
case RATE_36M:
pFrame->sTPCRepEIDs.byLinkMargin = 70 - byRSSI;
break;
case RATE_24M:
pFrame->sTPCRepEIDs.byLinkMargin = 74 - byRSSI;
break;
case RATE_18M:
pFrame->sTPCRepEIDs.byLinkMargin = 77 - byRSSI;
break;
case RATE_12M:
pFrame->sTPCRepEIDs.byLinkMargin = 79 - byRSSI;
break;
case RATE_9M:
pFrame->sTPCRepEIDs.byLinkMargin = 81 - byRSSI;
break;
case RATE_6M:
default:
pFrame->sTPCRepEIDs.byLinkMargin = 82 - byRSSI;
break;
}
pTxPacket->cbMPDULen = sizeof(WLAN_FRAME_TPCREP);
pTxPacket->cbPayloadLen = sizeof(WLAN_FRAME_TPCREP) -
WLAN_HDR_ADDR3_LEN;
if (csMgmt_xmit(pMgmt->pAdapter, pTxPacket) != CMD_STATUS_PENDING)
return false;
return true;
/* return (CARDbSendPacket(pMgmt->pAdapter, pFrame, PKT_TYPE_802_11_MNG,
sizeof(WLAN_FRAME_TPCREP))); */
}
/*--------------------- Export Variables --------------------------*/
/*--------------------- Export Functions --------------------------*/
/*+
*
* Description:
* Handles action management frames.
*
* Parameters:
* In:
* pMgmt - Management Object structure
* pRxPacket - Received packet
* Out:
* none
*
* Return Value: None.
*
-*/
bool
IEEE11hbMgrRxAction(void *pMgmtHandle, void *pRxPacket)
{
PSMgmtObject pMgmt = (PSMgmtObject) pMgmtHandle;
PWLAN_FRAME_ACTION pAction = NULL;
unsigned int uLength = 0;
PWLAN_IE_CH_SW pChannelSwitch = NULL;
/* decode the frame */
uLength = ((PSRxMgmtPacket)pRxPacket)->cbMPDULen;
if (uLength > WLAN_A3FR_MAXLEN)
return false;
pAction = (PWLAN_FRAME_ACTION)
(((PSRxMgmtPacket)pRxPacket)->p80211Header);
if (pAction->byCategory == 0) {
switch (pAction->byAction) {
case ACTION_MSRREQ:
return s_bRxMSRReq(pMgmt,
(PWLAN_FRAME_MSRREQ)
pAction,
uLength);
break;
case ACTION_MSRREP:
break;
case ACTION_TPCREQ:
return s_bRxTPCReq(pMgmt,
(PWLAN_FRAME_TPCREQ) pAction,
((PSRxMgmtPacket)pRxPacket)->byRxRate,
(unsigned char)
((PSRxMgmtPacket)pRxPacket)->uRSSI);
break;
case ACTION_TPCREP:
break;
case ACTION_CHSW:
pChannelSwitch = (PWLAN_IE_CH_SW) (pAction->abyVars);
if ((pChannelSwitch->byElementID == WLAN_EID_CH_SWITCH)
&& (pChannelSwitch->len == 3)) {
/* valid element id */
CARDbChannelSwitch(pMgmt->pAdapter,
pChannelSwitch->byMode,
get_channel_mapping(pMgmt->pAdapter,
pChannelSwitch->byChannel,
pMgmt->eCurrentPHYMode),
pChannelSwitch->byCount);
}
break;
default:
DBG_PRT(MSG_LEVEL_DEBUG,
KERN_INFO"Unknown Action = %d\n",
pAction->byAction);
break;
}
} else {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Unknown Category = %d\n",
pAction->byCategory);
pAction->byCategory |= 0x80;
/*return (CARDbSendPacket(pMgmt->pAdapter, pAction, PKT_TYPE_802_11_MNG,
uLength));*/
return true;
}
return true;
}
bool IEEE11hbMSRRepTx(void *pMgmtHandle)
{
PSMgmtObject pMgmt = (PSMgmtObject) pMgmtHandle;
PWLAN_FRAME_MSRREP pMSRRep = (PWLAN_FRAME_MSRREP)
(pMgmt->abyCurrentMSRRep + sizeof(STxMgmtPacket));
size_t uLength = 0;
PSTxMgmtPacket pTxPacket = NULL;
pTxPacket = (PSTxMgmtPacket)pMgmt->abyCurrentMSRRep;
memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_A3FR_MAXLEN);
pTxPacket->p80211Header = (PUWLAN_80211HDR)((unsigned char *)pTxPacket +
sizeof(STxMgmtPacket));
pMSRRep->Header.wFrameCtl = (WLAN_SET_FC_FTYPE(WLAN_FTYPE_MGMT) |
WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_ACTION)
);
memcpy(pMSRRep->Header.abyAddr1, ((PWLAN_FRAME_MSRREQ)
(pMgmt->abyCurrentMSRReq))->Header.abyAddr2, WLAN_ADDR_LEN);
memcpy(pMSRRep->Header.abyAddr2,
CARDpGetCurrentAddress(pMgmt->pAdapter), WLAN_ADDR_LEN);
memcpy(pMSRRep->Header.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
pMSRRep->byCategory = 0;
pMSRRep->byAction = 1;
pMSRRep->byDialogToken = ((PWLAN_FRAME_MSRREQ)
(pMgmt->abyCurrentMSRReq))->byDialogToken;
uLength = pMgmt->uLengthOfRepEIDs + offsetof(WLAN_FRAME_MSRREP,
sMSRRepEIDs);
pTxPacket->cbMPDULen = uLength;
pTxPacket->cbPayloadLen = uLength - WLAN_HDR_ADDR3_LEN;
if (csMgmt_xmit(pMgmt->pAdapter, pTxPacket) != CMD_STATUS_PENDING)
return false;
return true;
/* return (CARDbSendPacket(pMgmt->pAdapter, pMSRRep, PKT_TYPE_802_11_MNG,
uLength)); */
}
| gpl-2.0 |
zarboz/SaveEnergy-2 | arch/score/mm/extable.c | 13595 | 1191 | /*
* arch/score/mm/extable.c
*
* Score Processor version.
*
* Copyright (C) 2009 Sunplus Core Technology Co., Ltd.
* Lennox Wu <lennox.wu@sunplusct.com>
* Chen Liqin <liqin.chen@sunplusct.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/module.h>
int fixup_exception(struct pt_regs *regs)
{
const struct exception_table_entry *fixup;
fixup = search_exception_tables(regs->cp0_epc);
if (fixup) {
regs->cp0_epc = fixup->fixup;
return 1;
}
return 0;
}
| gpl-2.0 |
bensonhsu2013/diff-T210-T110 | arch/parisc/math-emu/fcnvuf.c | 14107 | 8168 | /*
* Linux/PA-RISC Project (http://www.parisc-linux.org/)
*
* Floating-point emulation code
* Copyright (C) 2001 Hewlett-Packard (Paul Bame) <bame@debian.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* BEGIN_DESC
*
* File:
* @(#) pa/spmath/fcnvuf.c $Revision: 1.1 $
*
* Purpose:
* Fixed point to Floating-point Converts
*
* External Interfaces:
* dbl_to_dbl_fcnvuf(srcptr,nullptr,dstptr,status)
* dbl_to_sgl_fcnvuf(srcptr,nullptr,dstptr,status)
* sgl_to_dbl_fcnvuf(srcptr,nullptr,dstptr,status)
* sgl_to_sgl_fcnvuf(srcptr,nullptr,dstptr,status)
*
* Internal Interfaces:
*
* Theory:
* <<please update with a overview of the operation of this file>>
*
* END_DESC
*/
#include "float.h"
#include "sgl_float.h"
#include "dbl_float.h"
#include "cnv_float.h"
/************************************************************************
* Fixed point to Floating-point Converts *
************************************************************************/
/*
* Convert Single Unsigned Fixed to Single Floating-point format
*/
int
sgl_to_sgl_fcnvuf(
unsigned int *srcptr,
unsigned int *nullptr,
sgl_floating_point *dstptr,
unsigned int *status)
{
register unsigned int src, result = 0;
register int dst_exponent;
src = *srcptr;
/* Check for zero */
if (src == 0) {
Sgl_setzero(result);
*dstptr = result;
return(NOEXCEPTION);
}
/*
* Generate exponent and normalized mantissa
*/
dst_exponent = 16; /* initialize for normalization */
/*
* Check word for most significant bit set. Returns
* a value in dst_exponent indicating the bit position,
* between -1 and 30.
*/
Find_ms_one_bit(src,dst_exponent);
/* left justify source, with msb at bit position 0 */
src <<= dst_exponent+1;
Sgl_set_mantissa(result, src >> SGL_EXP_LENGTH);
Sgl_set_exponent(result, 30+SGL_BIAS - dst_exponent);
/* check for inexact */
if (Suint_isinexact_to_sgl(src)) {
switch (Rounding_mode()) {
case ROUNDPLUS:
Sgl_increment(result);
break;
case ROUNDMINUS: /* never negative */
break;
case ROUNDNEAREST:
Sgl_roundnearest_from_suint(src,result);
break;
}
if (Is_inexacttrap_enabled()) {
*dstptr = result;
return(INEXACTEXCEPTION);
}
else Set_inexactflag();
}
*dstptr = result;
return(NOEXCEPTION);
}
/*
* Single Unsigned Fixed to Double Floating-point
*/
int
sgl_to_dbl_fcnvuf(
unsigned int *srcptr,
unsigned int *nullptr,
dbl_floating_point *dstptr,
unsigned int *status)
{
register int dst_exponent;
register unsigned int src, resultp1 = 0, resultp2 = 0;
src = *srcptr;
/* Check for zero */
if (src == 0) {
Dbl_setzero(resultp1,resultp2);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
/*
* Generate exponent and normalized mantissa
*/
dst_exponent = 16; /* initialize for normalization */
/*
* Check word for most significant bit set. Returns
* a value in dst_exponent indicating the bit position,
* between -1 and 30.
*/
Find_ms_one_bit(src,dst_exponent);
/* left justify source, with msb at bit position 0 */
src <<= dst_exponent+1;
Dbl_set_mantissap1(resultp1, src >> DBL_EXP_LENGTH);
Dbl_set_mantissap2(resultp2, src << (32-DBL_EXP_LENGTH));
Dbl_set_exponent(resultp1, (30+DBL_BIAS) - dst_exponent);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
/*
* Double Unsigned Fixed to Single Floating-point
*/
int
dbl_to_sgl_fcnvuf(
dbl_unsigned *srcptr,
unsigned int *nullptr,
sgl_floating_point *dstptr,
unsigned int *status)
{
int dst_exponent;
unsigned int srcp1, srcp2, result = 0;
Duint_copyfromptr(srcptr,srcp1,srcp2);
/* Check for zero */
if (srcp1 == 0 && srcp2 == 0) {
Sgl_setzero(result);
*dstptr = result;
return(NOEXCEPTION);
}
/*
* Generate exponent and normalized mantissa
*/
dst_exponent = 16; /* initialize for normalization */
if (srcp1 == 0) {
/*
* Check word for most significant bit set. Returns
* a value in dst_exponent indicating the bit position,
* between -1 and 30.
*/
Find_ms_one_bit(srcp2,dst_exponent);
/* left justify source, with msb at bit position 0 */
srcp1 = srcp2 << dst_exponent+1;
srcp2 = 0;
/*
* since msb set is in second word, need to
* adjust bit position count
*/
dst_exponent += 32;
}
else {
/*
* Check word for most significant bit set. Returns
* a value in dst_exponent indicating the bit position,
* between -1 and 30.
*
*/
Find_ms_one_bit(srcp1,dst_exponent);
/* left justify source, with msb at bit position 0 */
if (dst_exponent >= 0) {
Variable_shift_double(srcp1,srcp2,(31-dst_exponent),
srcp1);
srcp2 <<= dst_exponent+1;
}
}
Sgl_set_mantissa(result, srcp1 >> SGL_EXP_LENGTH);
Sgl_set_exponent(result, (62+SGL_BIAS) - dst_exponent);
/* check for inexact */
if (Duint_isinexact_to_sgl(srcp1,srcp2)) {
switch (Rounding_mode()) {
case ROUNDPLUS:
Sgl_increment(result);
break;
case ROUNDMINUS: /* never negative */
break;
case ROUNDNEAREST:
Sgl_roundnearest_from_duint(srcp1,srcp2,result);
break;
}
if (Is_inexacttrap_enabled()) {
*dstptr = result;
return(INEXACTEXCEPTION);
}
else Set_inexactflag();
}
*dstptr = result;
return(NOEXCEPTION);
}
/*
* Double Unsigned Fixed to Double Floating-point
*/
int
dbl_to_dbl_fcnvuf(
dbl_unsigned *srcptr,
unsigned int *nullptr,
dbl_floating_point *dstptr,
unsigned int *status)
{
register int dst_exponent;
register unsigned int srcp1, srcp2, resultp1 = 0, resultp2 = 0;
Duint_copyfromptr(srcptr,srcp1,srcp2);
/* Check for zero */
if (srcp1 == 0 && srcp2 ==0) {
Dbl_setzero(resultp1,resultp2);
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
/*
* Generate exponent and normalized mantissa
*/
dst_exponent = 16; /* initialize for normalization */
if (srcp1 == 0) {
/*
* Check word for most significant bit set. Returns
* a value in dst_exponent indicating the bit position,
* between -1 and 30.
*/
Find_ms_one_bit(srcp2,dst_exponent);
/* left justify source, with msb at bit position 0 */
srcp1 = srcp2 << dst_exponent+1;
srcp2 = 0;
/*
* since msb set is in second word, need to
* adjust bit position count
*/
dst_exponent += 32;
}
else {
/*
* Check word for most significant bit set. Returns
* a value in dst_exponent indicating the bit position,
* between -1 and 30.
*/
Find_ms_one_bit(srcp1,dst_exponent);
/* left justify source, with msb at bit position 0 */
if (dst_exponent >= 0) {
Variable_shift_double(srcp1,srcp2,(31-dst_exponent),
srcp1);
srcp2 <<= dst_exponent+1;
}
}
Dbl_set_mantissap1(resultp1, srcp1 >> DBL_EXP_LENGTH);
Shiftdouble(srcp1,srcp2,DBL_EXP_LENGTH,resultp2);
Dbl_set_exponent(resultp1, (62+DBL_BIAS) - dst_exponent);
/* check for inexact */
if (Duint_isinexact_to_dbl(srcp2)) {
switch (Rounding_mode()) {
case ROUNDPLUS:
Dbl_increment(resultp1,resultp2);
break;
case ROUNDMINUS: /* never negative */
break;
case ROUNDNEAREST:
Dbl_roundnearest_from_duint(srcp2,resultp1,
resultp2);
break;
}
if (Is_inexacttrap_enabled()) {
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(INEXACTEXCEPTION);
}
else Set_inexactflag();
}
Dbl_copytoptr(resultp1,resultp2,dstptr);
return(NOEXCEPTION);
}
| gpl-2.0 |
guohuaW/linux-rpi | net/ipv6/route.c | 28 | 73936 | /*
* Linux INET6 implementation
* FIB front-end.
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
/* Changes:
*
* YOSHIFUJI Hideaki @USAGI
* reworked default router selection.
* - respect outgoing interface
* - select from (probably) reachable routers (i.e.
* routers in REACHABLE, STALE, DELAY or PROBE states).
* - always select the same router if it is (probably)
* reachable. otherwise, round-robin the list.
* Ville Nuorvala
* Fixed routing subtrees.
*/
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/types.h>
#include <linux/times.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/mroute6.h>
#include <linux/init.h>
#include <linux/if_arp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/nsproxy.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/tcp.h>
#include <linux/rtnetlink.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <net/netevent.h>
#include <net/netlink.h>
#include <asm/uaccess.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
static struct rt6_info *ip6_rt_copy(const struct rt6_info *ort,
const struct in6_addr *dest);
static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie);
static unsigned int ip6_default_advmss(const struct dst_entry *dst);
static unsigned int ip6_mtu(const struct dst_entry *dst);
static struct dst_entry *ip6_negative_advice(struct dst_entry *);
static void ip6_dst_destroy(struct dst_entry *);
static void ip6_dst_ifdown(struct dst_entry *,
struct net_device *dev, int how);
static int ip6_dst_gc(struct dst_ops *ops);
static int ip6_pkt_discard(struct sk_buff *skb);
static int ip6_pkt_discard_out(struct sk_buff *skb);
static void ip6_link_failure(struct sk_buff *skb);
static void ip6_rt_update_pmtu(struct dst_entry *dst, u32 mtu);
#ifdef CONFIG_IPV6_ROUTE_INFO
static struct rt6_info *rt6_add_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex,
unsigned pref);
static struct rt6_info *rt6_get_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex);
#endif
static u32 *ipv6_cow_metrics(struct dst_entry *dst, unsigned long old)
{
struct rt6_info *rt = (struct rt6_info *) dst;
struct inet_peer *peer;
u32 *p = NULL;
if (!(rt->dst.flags & DST_HOST))
return NULL;
if (!rt->rt6i_peer)
rt6_bind_peer(rt, 1);
peer = rt->rt6i_peer;
if (peer) {
u32 *old_p = __DST_METRICS_PTR(old);
unsigned long prev, new;
p = peer->metrics;
if (inet_metrics_new(peer))
memcpy(p, old_p, sizeof(u32) * RTAX_MAX);
new = (unsigned long) p;
prev = cmpxchg(&dst->_metrics, old, new);
if (prev != old) {
p = __DST_METRICS_PTR(prev);
if (prev & DST_METRICS_READ_ONLY)
p = NULL;
}
}
return p;
}
static struct neighbour *ip6_neigh_lookup(const struct dst_entry *dst, const void *daddr)
{
struct neighbour *n = __ipv6_neigh_lookup(&nd_tbl, dst->dev, daddr);
if (n)
return n;
return neigh_create(&nd_tbl, daddr, dst->dev);
}
static int rt6_bind_neighbour(struct rt6_info *rt, struct net_device *dev)
{
struct neighbour *n = __ipv6_neigh_lookup(&nd_tbl, dev, &rt->rt6i_gateway);
if (!n) {
n = neigh_create(&nd_tbl, &rt->rt6i_gateway, dev);
if (IS_ERR(n))
return PTR_ERR(n);
}
dst_set_neighbour(&rt->dst, n);
return 0;
}
static struct dst_ops ip6_dst_ops_template = {
.family = AF_INET6,
.protocol = cpu_to_be16(ETH_P_IPV6),
.gc = ip6_dst_gc,
.gc_thresh = 1024,
.check = ip6_dst_check,
.default_advmss = ip6_default_advmss,
.mtu = ip6_mtu,
.cow_metrics = ipv6_cow_metrics,
.destroy = ip6_dst_destroy,
.ifdown = ip6_dst_ifdown,
.negative_advice = ip6_negative_advice,
.link_failure = ip6_link_failure,
.update_pmtu = ip6_rt_update_pmtu,
.local_out = __ip6_local_out,
.neigh_lookup = ip6_neigh_lookup,
};
static unsigned int ip6_blackhole_mtu(const struct dst_entry *dst)
{
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
return mtu ? : dst->dev->mtu;
}
static void ip6_rt_blackhole_update_pmtu(struct dst_entry *dst, u32 mtu)
{
}
static u32 *ip6_rt_blackhole_cow_metrics(struct dst_entry *dst,
unsigned long old)
{
return NULL;
}
static struct dst_ops ip6_dst_blackhole_ops = {
.family = AF_INET6,
.protocol = cpu_to_be16(ETH_P_IPV6),
.destroy = ip6_dst_destroy,
.check = ip6_dst_check,
.mtu = ip6_blackhole_mtu,
.default_advmss = ip6_default_advmss,
.update_pmtu = ip6_rt_blackhole_update_pmtu,
.cow_metrics = ip6_rt_blackhole_cow_metrics,
.neigh_lookup = ip6_neigh_lookup,
};
static const u32 ip6_template_metrics[RTAX_MAX] = {
[RTAX_HOPLIMIT - 1] = 255,
};
static struct rt6_info ip6_null_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = -1,
.error = -ENETUNREACH,
.input = ip6_pkt_discard,
.output = ip6_pkt_discard_out,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static int ip6_pkt_prohibit(struct sk_buff *skb);
static int ip6_pkt_prohibit_out(struct sk_buff *skb);
static struct rt6_info ip6_prohibit_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = -1,
.error = -EACCES,
.input = ip6_pkt_prohibit,
.output = ip6_pkt_prohibit_out,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
static struct rt6_info ip6_blk_hole_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = -1,
.error = -EINVAL,
.input = dst_discard,
.output = dst_discard,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
#endif
/* allocate dst with ip6_dst_ops */
static inline struct rt6_info *ip6_dst_alloc(struct dst_ops *ops,
struct net_device *dev,
int flags)
{
struct rt6_info *rt = dst_alloc(ops, dev, 0, 0, flags);
if (rt)
memset(&rt->rt6i_table, 0,
sizeof(*rt) - sizeof(struct dst_entry));
return rt;
}
static void ip6_dst_destroy(struct dst_entry *dst)
{
struct rt6_info *rt = (struct rt6_info *)dst;
struct inet6_dev *idev = rt->rt6i_idev;
struct inet_peer *peer = rt->rt6i_peer;
if (!(rt->dst.flags & DST_HOST))
dst_destroy_metrics_generic(dst);
if (idev) {
rt->rt6i_idev = NULL;
in6_dev_put(idev);
}
if (peer) {
rt->rt6i_peer = NULL;
inet_putpeer(peer);
}
}
static atomic_t __rt6_peer_genid = ATOMIC_INIT(0);
static u32 rt6_peer_genid(void)
{
return atomic_read(&__rt6_peer_genid);
}
void rt6_bind_peer(struct rt6_info *rt, int create)
{
struct inet_peer *peer;
peer = inet_getpeer_v6(&rt->rt6i_dst.addr, create);
if (peer && cmpxchg(&rt->rt6i_peer, NULL, peer) != NULL)
inet_putpeer(peer);
else
rt->rt6i_peer_genid = rt6_peer_genid();
}
static void ip6_dst_ifdown(struct dst_entry *dst, struct net_device *dev,
int how)
{
struct rt6_info *rt = (struct rt6_info *)dst;
struct inet6_dev *idev = rt->rt6i_idev;
struct net_device *loopback_dev =
dev_net(dev)->loopback_dev;
if (dev != loopback_dev && idev && idev->dev == dev) {
struct inet6_dev *loopback_idev =
in6_dev_get(loopback_dev);
if (loopback_idev) {
rt->rt6i_idev = loopback_idev;
in6_dev_put(idev);
}
}
}
static __inline__ int rt6_check_expired(const struct rt6_info *rt)
{
return (rt->rt6i_flags & RTF_EXPIRES) &&
time_after(jiffies, rt->dst.expires);
}
static inline int rt6_need_strict(const struct in6_addr *daddr)
{
return ipv6_addr_type(daddr) &
(IPV6_ADDR_MULTICAST | IPV6_ADDR_LINKLOCAL | IPV6_ADDR_LOOPBACK);
}
/*
* Route lookup. Any table->tb6_lock is implied.
*/
static inline struct rt6_info *rt6_device_match(struct net *net,
struct rt6_info *rt,
const struct in6_addr *saddr,
int oif,
int flags)
{
struct rt6_info *local = NULL;
struct rt6_info *sprt;
if (!oif && ipv6_addr_any(saddr))
goto out;
for (sprt = rt; sprt; sprt = sprt->dst.rt6_next) {
struct net_device *dev = sprt->dst.dev;
if (oif) {
if (dev->ifindex == oif)
return sprt;
if (dev->flags & IFF_LOOPBACK) {
if (!sprt->rt6i_idev ||
sprt->rt6i_idev->dev->ifindex != oif) {
if (flags & RT6_LOOKUP_F_IFACE && oif)
continue;
if (local && (!oif ||
local->rt6i_idev->dev->ifindex == oif))
continue;
}
local = sprt;
}
} else {
if (ipv6_chk_addr(net, saddr, dev,
flags & RT6_LOOKUP_F_IFACE))
return sprt;
}
}
if (oif) {
if (local)
return local;
if (flags & RT6_LOOKUP_F_IFACE)
return net->ipv6.ip6_null_entry;
}
out:
return rt;
}
#ifdef CONFIG_IPV6_ROUTER_PREF
static void rt6_probe(struct rt6_info *rt)
{
struct neighbour *neigh;
/*
* Okay, this does not seem to be appropriate
* for now, however, we need to check if it
* is really so; aka Router Reachability Probing.
*
* Router Reachability Probe MUST be rate-limited
* to no more than one per minute.
*/
rcu_read_lock();
neigh = rt ? dst_get_neighbour_noref(&rt->dst) : NULL;
if (!neigh || (neigh->nud_state & NUD_VALID))
goto out;
read_lock_bh(&neigh->lock);
if (!(neigh->nud_state & NUD_VALID) &&
time_after(jiffies, neigh->updated + rt->rt6i_idev->cnf.rtr_probe_interval)) {
struct in6_addr mcaddr;
struct in6_addr *target;
neigh->updated = jiffies;
read_unlock_bh(&neigh->lock);
target = (struct in6_addr *)&neigh->primary_key;
addrconf_addr_solict_mult(target, &mcaddr);
ndisc_send_ns(rt->dst.dev, NULL, target, &mcaddr, NULL);
} else {
read_unlock_bh(&neigh->lock);
}
out:
rcu_read_unlock();
}
#else
static inline void rt6_probe(struct rt6_info *rt)
{
}
#endif
/*
* Default Router Selection (RFC 2461 6.3.6)
*/
static inline int rt6_check_dev(struct rt6_info *rt, int oif)
{
struct net_device *dev = rt->dst.dev;
if (!oif || dev->ifindex == oif)
return 2;
if ((dev->flags & IFF_LOOPBACK) &&
rt->rt6i_idev && rt->rt6i_idev->dev->ifindex == oif)
return 1;
return 0;
}
static inline int rt6_check_neigh(struct rt6_info *rt)
{
struct neighbour *neigh;
int m;
rcu_read_lock();
neigh = dst_get_neighbour_noref(&rt->dst);
if (rt->rt6i_flags & RTF_NONEXTHOP ||
!(rt->rt6i_flags & RTF_GATEWAY))
m = 1;
else if (neigh) {
read_lock_bh(&neigh->lock);
if (neigh->nud_state & NUD_VALID)
m = 2;
#ifdef CONFIG_IPV6_ROUTER_PREF
else if (neigh->nud_state & NUD_FAILED)
m = 0;
#endif
else
m = 1;
read_unlock_bh(&neigh->lock);
} else
m = 0;
rcu_read_unlock();
return m;
}
static int rt6_score_route(struct rt6_info *rt, int oif,
int strict)
{
int m, n;
m = rt6_check_dev(rt, oif);
if (!m && (strict & RT6_LOOKUP_F_IFACE))
return -1;
#ifdef CONFIG_IPV6_ROUTER_PREF
m |= IPV6_DECODE_PREF(IPV6_EXTRACT_PREF(rt->rt6i_flags)) << 2;
#endif
n = rt6_check_neigh(rt);
if (!n && (strict & RT6_LOOKUP_F_REACHABLE))
return -1;
return m;
}
static struct rt6_info *find_match(struct rt6_info *rt, int oif, int strict,
int *mpri, struct rt6_info *match)
{
int m;
if (rt6_check_expired(rt))
goto out;
m = rt6_score_route(rt, oif, strict);
if (m < 0)
goto out;
if (m > *mpri) {
if (strict & RT6_LOOKUP_F_REACHABLE)
rt6_probe(match);
*mpri = m;
match = rt;
} else if (strict & RT6_LOOKUP_F_REACHABLE) {
rt6_probe(rt);
}
out:
return match;
}
static struct rt6_info *find_rr_leaf(struct fib6_node *fn,
struct rt6_info *rr_head,
u32 metric, int oif, int strict)
{
struct rt6_info *rt, *match;
int mpri = -1;
match = NULL;
for (rt = rr_head; rt && rt->rt6i_metric == metric;
rt = rt->dst.rt6_next)
match = find_match(rt, oif, strict, &mpri, match);
for (rt = fn->leaf; rt && rt != rr_head && rt->rt6i_metric == metric;
rt = rt->dst.rt6_next)
match = find_match(rt, oif, strict, &mpri, match);
return match;
}
static struct rt6_info *rt6_select(struct fib6_node *fn, int oif, int strict)
{
struct rt6_info *match, *rt0;
struct net *net;
rt0 = fn->rr_ptr;
if (!rt0)
fn->rr_ptr = rt0 = fn->leaf;
match = find_rr_leaf(fn, rt0, rt0->rt6i_metric, oif, strict);
if (!match &&
(strict & RT6_LOOKUP_F_REACHABLE)) {
struct rt6_info *next = rt0->dst.rt6_next;
/* no entries matched; do round-robin */
if (!next || next->rt6i_metric != rt0->rt6i_metric)
next = fn->leaf;
if (next != rt0)
fn->rr_ptr = next;
}
net = dev_net(rt0->dst.dev);
return match ? match : net->ipv6.ip6_null_entry;
}
#ifdef CONFIG_IPV6_ROUTE_INFO
int rt6_route_rcv(struct net_device *dev, u8 *opt, int len,
const struct in6_addr *gwaddr)
{
struct net *net = dev_net(dev);
struct route_info *rinfo = (struct route_info *) opt;
struct in6_addr prefix_buf, *prefix;
unsigned int pref;
unsigned long lifetime;
struct rt6_info *rt;
if (len < sizeof(struct route_info)) {
return -EINVAL;
}
/* Sanity check for prefix_len and length */
if (rinfo->length > 3) {
return -EINVAL;
} else if (rinfo->prefix_len > 128) {
return -EINVAL;
} else if (rinfo->prefix_len > 64) {
if (rinfo->length < 2) {
return -EINVAL;
}
} else if (rinfo->prefix_len > 0) {
if (rinfo->length < 1) {
return -EINVAL;
}
}
pref = rinfo->route_pref;
if (pref == ICMPV6_ROUTER_PREF_INVALID)
return -EINVAL;
lifetime = addrconf_timeout_fixup(ntohl(rinfo->lifetime), HZ);
if (rinfo->length == 3)
prefix = (struct in6_addr *)rinfo->prefix;
else {
/* this function is safe */
ipv6_addr_prefix(&prefix_buf,
(struct in6_addr *)rinfo->prefix,
rinfo->prefix_len);
prefix = &prefix_buf;
}
rt = rt6_get_route_info(net, prefix, rinfo->prefix_len, gwaddr,
dev->ifindex);
if (rt && !lifetime) {
ip6_del_rt(rt);
rt = NULL;
}
if (!rt && lifetime)
rt = rt6_add_route_info(net, prefix, rinfo->prefix_len, gwaddr, dev->ifindex,
pref);
else if (rt)
rt->rt6i_flags = RTF_ROUTEINFO |
(rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref);
if (rt) {
if (!addrconf_finite_timeout(lifetime)) {
rt->rt6i_flags &= ~RTF_EXPIRES;
} else {
rt->dst.expires = jiffies + HZ * lifetime;
rt->rt6i_flags |= RTF_EXPIRES;
}
dst_release(&rt->dst);
}
return 0;
}
#endif
#define BACKTRACK(__net, saddr) \
do { \
if (rt == __net->ipv6.ip6_null_entry) { \
struct fib6_node *pn; \
while (1) { \
if (fn->fn_flags & RTN_TL_ROOT) \
goto out; \
pn = fn->parent; \
if (FIB6_SUBTREE(pn) && FIB6_SUBTREE(pn) != fn) \
fn = fib6_lookup(FIB6_SUBTREE(pn), NULL, saddr); \
else \
fn = pn; \
if (fn->fn_flags & RTN_RTINFO) \
goto restart; \
} \
} \
} while (0)
static struct rt6_info *ip6_pol_route_lookup(struct net *net,
struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
struct fib6_node *fn;
struct rt6_info *rt;
read_lock_bh(&table->tb6_lock);
fn = fib6_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
restart:
rt = fn->leaf;
rt = rt6_device_match(net, rt, &fl6->saddr, fl6->flowi6_oif, flags);
BACKTRACK(net, &fl6->saddr);
out:
dst_use(&rt->dst, jiffies);
read_unlock_bh(&table->tb6_lock);
return rt;
}
struct dst_entry * ip6_route_lookup(struct net *net, struct flowi6 *fl6,
int flags)
{
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_lookup);
}
EXPORT_SYMBOL_GPL(ip6_route_lookup);
struct rt6_info *rt6_lookup(struct net *net, const struct in6_addr *daddr,
const struct in6_addr *saddr, int oif, int strict)
{
struct flowi6 fl6 = {
.flowi6_oif = oif,
.daddr = *daddr,
};
struct dst_entry *dst;
int flags = strict ? RT6_LOOKUP_F_IFACE : 0;
if (saddr) {
memcpy(&fl6.saddr, saddr, sizeof(*saddr));
flags |= RT6_LOOKUP_F_HAS_SADDR;
}
dst = fib6_rule_lookup(net, &fl6, flags, ip6_pol_route_lookup);
if (dst->error == 0)
return (struct rt6_info *) dst;
dst_release(dst);
return NULL;
}
EXPORT_SYMBOL(rt6_lookup);
/* ip6_ins_rt is called with FREE table->tb6_lock.
It takes new route entry, the addition fails by any reason the
route is freed. In any case, if caller does not hold it, it may
be destroyed.
*/
static int __ip6_ins_rt(struct rt6_info *rt, struct nl_info *info)
{
int err;
struct fib6_table *table;
table = rt->rt6i_table;
write_lock_bh(&table->tb6_lock);
err = fib6_add(&table->tb6_root, rt, info);
write_unlock_bh(&table->tb6_lock);
return err;
}
int ip6_ins_rt(struct rt6_info *rt)
{
struct nl_info info = {
.nl_net = dev_net(rt->dst.dev),
};
return __ip6_ins_rt(rt, &info);
}
static struct rt6_info *rt6_alloc_cow(const struct rt6_info *ort,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
struct rt6_info *rt;
/*
* Clone the route.
*/
rt = ip6_rt_copy(ort, daddr);
if (rt) {
int attempts = !in_softirq();
if (!(rt->rt6i_flags & RTF_GATEWAY)) {
if (ort->rt6i_dst.plen != 128 &&
ipv6_addr_equal(&ort->rt6i_dst.addr, daddr))
rt->rt6i_flags |= RTF_ANYCAST;
rt->rt6i_gateway = *daddr;
}
rt->rt6i_flags |= RTF_CACHE;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->rt6i_src.plen && saddr) {
rt->rt6i_src.addr = *saddr;
rt->rt6i_src.plen = 128;
}
#endif
retry:
if (rt6_bind_neighbour(rt, rt->dst.dev)) {
struct net *net = dev_net(rt->dst.dev);
int saved_rt_min_interval =
net->ipv6.sysctl.ip6_rt_gc_min_interval;
int saved_rt_elasticity =
net->ipv6.sysctl.ip6_rt_gc_elasticity;
if (attempts-- > 0) {
net->ipv6.sysctl.ip6_rt_gc_elasticity = 1;
net->ipv6.sysctl.ip6_rt_gc_min_interval = 0;
ip6_dst_gc(&net->ipv6.ip6_dst_ops);
net->ipv6.sysctl.ip6_rt_gc_elasticity =
saved_rt_elasticity;
net->ipv6.sysctl.ip6_rt_gc_min_interval =
saved_rt_min_interval;
goto retry;
}
if (net_ratelimit())
printk(KERN_WARNING
"ipv6: Neighbour table overflow.\n");
dst_free(&rt->dst);
return NULL;
}
}
return rt;
}
static struct rt6_info *rt6_alloc_clone(struct rt6_info *ort,
const struct in6_addr *daddr)
{
struct rt6_info *rt = ip6_rt_copy(ort, daddr);
if (rt) {
rt->rt6i_flags |= RTF_CACHE;
dst_set_neighbour(&rt->dst, neigh_clone(dst_get_neighbour_noref_raw(&ort->dst)));
}
return rt;
}
static struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table, int oif,
struct flowi6 *fl6, int flags)
{
struct fib6_node *fn;
struct rt6_info *rt, *nrt;
int strict = 0;
int attempts = 3;
int err;
int reachable = net->ipv6.devconf_all->forwarding ? 0 : RT6_LOOKUP_F_REACHABLE;
strict |= flags & RT6_LOOKUP_F_IFACE;
relookup:
read_lock_bh(&table->tb6_lock);
restart_2:
fn = fib6_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
restart:
rt = rt6_select(fn, oif, strict | reachable);
BACKTRACK(net, &fl6->saddr);
if (rt == net->ipv6.ip6_null_entry ||
rt->rt6i_flags & RTF_CACHE)
goto out;
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
if (!dst_get_neighbour_noref_raw(&rt->dst) && !(rt->rt6i_flags & RTF_NONEXTHOP))
nrt = rt6_alloc_cow(rt, &fl6->daddr, &fl6->saddr);
else if (!(rt->dst.flags & DST_HOST))
nrt = rt6_alloc_clone(rt, &fl6->daddr);
else
goto out2;
dst_release(&rt->dst);
rt = nrt ? : net->ipv6.ip6_null_entry;
dst_hold(&rt->dst);
if (nrt) {
err = ip6_ins_rt(nrt);
if (!err)
goto out2;
}
if (--attempts <= 0)
goto out2;
/*
* Race condition! In the gap, when table->tb6_lock was
* released someone could insert this route. Relookup.
*/
dst_release(&rt->dst);
goto relookup;
out:
if (reachable) {
reachable = 0;
goto restart_2;
}
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
out2:
rt->dst.lastuse = jiffies;
rt->dst.__use++;
return rt;
}
static struct rt6_info *ip6_pol_route_input(struct net *net, struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
return ip6_pol_route(net, table, fl6->flowi6_iif, fl6, flags);
}
void ip6_route_input(struct sk_buff *skb)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
struct net *net = dev_net(skb->dev);
int flags = RT6_LOOKUP_F_HAS_SADDR;
struct flowi6 fl6 = {
.flowi6_iif = skb->dev->ifindex,
.daddr = iph->daddr,
.saddr = iph->saddr,
.flowlabel = (* (__be32 *) iph) & IPV6_FLOWINFO_MASK,
.flowi6_mark = skb->mark,
.flowi6_proto = iph->nexthdr,
};
if (rt6_need_strict(&iph->daddr) && skb->dev->type != ARPHRD_PIMREG)
flags |= RT6_LOOKUP_F_IFACE;
skb_dst_set(skb, fib6_rule_lookup(net, &fl6, flags, ip6_pol_route_input));
}
static struct rt6_info *ip6_pol_route_output(struct net *net, struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
return ip6_pol_route(net, table, fl6->flowi6_oif, fl6, flags);
}
struct dst_entry * ip6_route_output(struct net *net, const struct sock *sk,
struct flowi6 *fl6)
{
int flags = 0;
if ((sk && sk->sk_bound_dev_if) || rt6_need_strict(&fl6->daddr))
flags |= RT6_LOOKUP_F_IFACE;
if (!ipv6_addr_any(&fl6->saddr))
flags |= RT6_LOOKUP_F_HAS_SADDR;
else if (sk)
flags |= rt6_srcprefs2flags(inet6_sk(sk)->srcprefs);
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_output);
}
EXPORT_SYMBOL(ip6_route_output);
struct dst_entry *ip6_blackhole_route(struct net *net, struct dst_entry *dst_orig)
{
struct rt6_info *rt, *ort = (struct rt6_info *) dst_orig;
struct dst_entry *new = NULL;
rt = dst_alloc(&ip6_dst_blackhole_ops, ort->dst.dev, 1, 0, 0);
if (rt) {
memset(&rt->rt6i_table, 0, sizeof(*rt) - sizeof(struct dst_entry));
new = &rt->dst;
new->__use = 1;
new->input = dst_discard;
new->output = dst_discard;
if (dst_metrics_read_only(&ort->dst))
new->_metrics = ort->dst._metrics;
else
dst_copy_metrics(new, &ort->dst);
rt->rt6i_idev = ort->rt6i_idev;
if (rt->rt6i_idev)
in6_dev_hold(rt->rt6i_idev);
rt->dst.expires = 0;
rt->rt6i_gateway = ort->rt6i_gateway;
rt->rt6i_flags = ort->rt6i_flags & ~RTF_EXPIRES;
rt->rt6i_metric = 0;
memcpy(&rt->rt6i_dst, &ort->rt6i_dst, sizeof(struct rt6key));
#ifdef CONFIG_IPV6_SUBTREES
memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
#endif
dst_free(new);
}
dst_release(dst_orig);
return new ? new : ERR_PTR(-ENOMEM);
}
/*
* Destination cache support functions
*/
static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie)
{
struct rt6_info *rt;
rt = (struct rt6_info *) dst;
if (rt->rt6i_node && (rt->rt6i_node->fn_sernum == cookie)) {
if (rt->rt6i_peer_genid != rt6_peer_genid()) {
if (!rt->rt6i_peer)
rt6_bind_peer(rt, 0);
rt->rt6i_peer_genid = rt6_peer_genid();
}
return dst;
}
return NULL;
}
static struct dst_entry *ip6_negative_advice(struct dst_entry *dst)
{
struct rt6_info *rt = (struct rt6_info *) dst;
if (rt) {
if (rt->rt6i_flags & RTF_CACHE) {
if (rt6_check_expired(rt)) {
ip6_del_rt(rt);
dst = NULL;
}
} else {
dst_release(dst);
dst = NULL;
}
}
return dst;
}
static void ip6_link_failure(struct sk_buff *skb)
{
struct rt6_info *rt;
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_ADDR_UNREACH, 0);
rt = (struct rt6_info *) skb_dst(skb);
if (rt) {
if (rt->rt6i_flags & RTF_CACHE) {
dst_set_expires(&rt->dst, 0);
rt->rt6i_flags |= RTF_EXPIRES;
} else if (rt->rt6i_node && (rt->rt6i_flags & RTF_DEFAULT))
rt->rt6i_node->fn_sernum = -1;
}
}
static void ip6_rt_update_pmtu(struct dst_entry *dst, u32 mtu)
{
struct rt6_info *rt6 = (struct rt6_info*)dst;
if (mtu < dst_mtu(dst) && rt6->rt6i_dst.plen == 128) {
rt6->rt6i_flags |= RTF_MODIFIED;
if (mtu < IPV6_MIN_MTU) {
u32 features = dst_metric(dst, RTAX_FEATURES);
mtu = IPV6_MIN_MTU;
features |= RTAX_FEATURE_ALLFRAG;
dst_metric_set(dst, RTAX_FEATURES, features);
}
dst_metric_set(dst, RTAX_MTU, mtu);
}
}
static unsigned int ip6_default_advmss(const struct dst_entry *dst)
{
struct net_device *dev = dst->dev;
unsigned int mtu = dst_mtu(dst);
struct net *net = dev_net(dev);
mtu -= sizeof(struct ipv6hdr) + sizeof(struct tcphdr);
if (mtu < net->ipv6.sysctl.ip6_rt_min_advmss)
mtu = net->ipv6.sysctl.ip6_rt_min_advmss;
/*
* Maximal non-jumbo IPv6 payload is IPV6_MAXPLEN and
* corresponding MSS is IPV6_MAXPLEN - tcp_header_size.
* IPV6_MAXPLEN is also valid and means: "any MSS,
* rely only on pmtu discovery"
*/
if (mtu > IPV6_MAXPLEN - sizeof(struct tcphdr))
mtu = IPV6_MAXPLEN;
return mtu;
}
static unsigned int ip6_mtu(const struct dst_entry *dst)
{
struct inet6_dev *idev;
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
if (mtu)
return mtu;
mtu = IPV6_MIN_MTU;
rcu_read_lock();
idev = __in6_dev_get(dst->dev);
if (idev)
mtu = idev->cnf.mtu6;
rcu_read_unlock();
return mtu;
}
static struct dst_entry *icmp6_dst_gc_list;
static DEFINE_SPINLOCK(icmp6_dst_lock);
struct dst_entry *icmp6_dst_alloc(struct net_device *dev,
struct neighbour *neigh,
struct flowi6 *fl6)
{
struct dst_entry *dst;
struct rt6_info *rt;
struct inet6_dev *idev = in6_dev_get(dev);
struct net *net = dev_net(dev);
if (unlikely(!idev))
return NULL;
rt = ip6_dst_alloc(&net->ipv6.ip6_dst_ops, dev, 0);
if (unlikely(!rt)) {
in6_dev_put(idev);
dst = ERR_PTR(-ENOMEM);
goto out;
}
if (neigh)
neigh_hold(neigh);
else {
neigh = ip6_neigh_lookup(&rt->dst, &fl6->daddr);
if (IS_ERR(neigh)) {
dst_free(&rt->dst);
return ERR_CAST(neigh);
}
}
rt->dst.flags |= DST_HOST;
rt->dst.output = ip6_output;
dst_set_neighbour(&rt->dst, neigh);
atomic_set(&rt->dst.__refcnt, 1);
rt->rt6i_dst.addr = fl6->daddr;
rt->rt6i_dst.plen = 128;
rt->rt6i_idev = idev;
dst_metric_set(&rt->dst, RTAX_HOPLIMIT, 255);
spin_lock_bh(&icmp6_dst_lock);
rt->dst.next = icmp6_dst_gc_list;
icmp6_dst_gc_list = &rt->dst;
spin_unlock_bh(&icmp6_dst_lock);
fib6_force_start_gc(net);
dst = xfrm_lookup(net, &rt->dst, flowi6_to_flowi(fl6), NULL, 0);
out:
return dst;
}
int icmp6_dst_gc(void)
{
struct dst_entry *dst, **pprev;
int more = 0;
spin_lock_bh(&icmp6_dst_lock);
pprev = &icmp6_dst_gc_list;
while ((dst = *pprev) != NULL) {
if (!atomic_read(&dst->__refcnt)) {
*pprev = dst->next;
dst_free(dst);
} else {
pprev = &dst->next;
++more;
}
}
spin_unlock_bh(&icmp6_dst_lock);
return more;
}
static void icmp6_clean_all(int (*func)(struct rt6_info *rt, void *arg),
void *arg)
{
struct dst_entry *dst, **pprev;
spin_lock_bh(&icmp6_dst_lock);
pprev = &icmp6_dst_gc_list;
while ((dst = *pprev) != NULL) {
struct rt6_info *rt = (struct rt6_info *) dst;
if (func(rt, arg)) {
*pprev = dst->next;
dst_free(dst);
} else {
pprev = &dst->next;
}
}
spin_unlock_bh(&icmp6_dst_lock);
}
static int ip6_dst_gc(struct dst_ops *ops)
{
unsigned long now = jiffies;
struct net *net = container_of(ops, struct net, ipv6.ip6_dst_ops);
int rt_min_interval = net->ipv6.sysctl.ip6_rt_gc_min_interval;
int rt_max_size = net->ipv6.sysctl.ip6_rt_max_size;
int rt_elasticity = net->ipv6.sysctl.ip6_rt_gc_elasticity;
int rt_gc_timeout = net->ipv6.sysctl.ip6_rt_gc_timeout;
unsigned long rt_last_gc = net->ipv6.ip6_rt_last_gc;
int entries;
entries = dst_entries_get_fast(ops);
if (time_after(rt_last_gc + rt_min_interval, now) &&
entries <= rt_max_size)
goto out;
net->ipv6.ip6_rt_gc_expire++;
fib6_run_gc(net->ipv6.ip6_rt_gc_expire, net);
net->ipv6.ip6_rt_last_gc = now;
entries = dst_entries_get_slow(ops);
if (entries < ops->gc_thresh)
net->ipv6.ip6_rt_gc_expire = rt_gc_timeout>>1;
out:
net->ipv6.ip6_rt_gc_expire -= net->ipv6.ip6_rt_gc_expire>>rt_elasticity;
return entries > rt_max_size;
}
/* Clean host part of a prefix. Not necessary in radix tree,
but results in cleaner routing tables.
Remove it only when all the things will work!
*/
int ip6_dst_hoplimit(struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0) {
struct net_device *dev = dst->dev;
struct inet6_dev *idev;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev)
hoplimit = idev->cnf.hop_limit;
else
hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit;
rcu_read_unlock();
}
return hoplimit;
}
EXPORT_SYMBOL(ip6_dst_hoplimit);
/*
*
*/
int ip6_route_add(struct fib6_config *cfg)
{
int err;
struct net *net = cfg->fc_nlinfo.nl_net;
struct rt6_info *rt = NULL;
struct net_device *dev = NULL;
struct inet6_dev *idev = NULL;
struct fib6_table *table;
int addr_type;
if (cfg->fc_dst_len > 128 || cfg->fc_src_len > 128)
return -EINVAL;
#ifndef CONFIG_IPV6_SUBTREES
if (cfg->fc_src_len)
return -EINVAL;
#endif
if (cfg->fc_ifindex) {
err = -ENODEV;
dev = dev_get_by_index(net, cfg->fc_ifindex);
if (!dev)
goto out;
idev = in6_dev_get(dev);
if (!idev)
goto out;
}
if (cfg->fc_metric == 0)
cfg->fc_metric = IP6_RT_PRIO_USER;
err = -ENOBUFS;
if (cfg->fc_nlinfo.nlh &&
!(cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_CREATE)) {
table = fib6_get_table(net, cfg->fc_table);
if (!table) {
printk(KERN_WARNING "IPv6: NLM_F_CREATE should be specified when creating new route\n");
table = fib6_new_table(net, cfg->fc_table);
}
} else {
table = fib6_new_table(net, cfg->fc_table);
}
if (!table)
goto out;
rt = ip6_dst_alloc(&net->ipv6.ip6_dst_ops, NULL, DST_NOCOUNT);
if (!rt) {
err = -ENOMEM;
goto out;
}
rt->dst.obsolete = -1;
rt->dst.expires = (cfg->fc_flags & RTF_EXPIRES) ?
jiffies + clock_t_to_jiffies(cfg->fc_expires) :
0;
if (cfg->fc_protocol == RTPROT_UNSPEC)
cfg->fc_protocol = RTPROT_BOOT;
rt->rt6i_protocol = cfg->fc_protocol;
addr_type = ipv6_addr_type(&cfg->fc_dst);
if (addr_type & IPV6_ADDR_MULTICAST)
rt->dst.input = ip6_mc_input;
else if (cfg->fc_flags & RTF_LOCAL)
rt->dst.input = ip6_input;
else
rt->dst.input = ip6_forward;
rt->dst.output = ip6_output;
ipv6_addr_prefix(&rt->rt6i_dst.addr, &cfg->fc_dst, cfg->fc_dst_len);
rt->rt6i_dst.plen = cfg->fc_dst_len;
if (rt->rt6i_dst.plen == 128)
rt->dst.flags |= DST_HOST;
if (!(rt->dst.flags & DST_HOST) && cfg->fc_mx) {
u32 *metrics = kzalloc(sizeof(u32) * RTAX_MAX, GFP_KERNEL);
if (!metrics) {
err = -ENOMEM;
goto out;
}
dst_init_metrics(&rt->dst, metrics, 0);
}
#ifdef CONFIG_IPV6_SUBTREES
ipv6_addr_prefix(&rt->rt6i_src.addr, &cfg->fc_src, cfg->fc_src_len);
rt->rt6i_src.plen = cfg->fc_src_len;
#endif
rt->rt6i_metric = cfg->fc_metric;
/* We cannot add true routes via loopback here,
they would result in kernel looping; promote them to reject routes
*/
if ((cfg->fc_flags & RTF_REJECT) ||
(dev && (dev->flags & IFF_LOOPBACK) &&
!(addr_type & IPV6_ADDR_LOOPBACK) &&
!(cfg->fc_flags & RTF_LOCAL))) {
/* hold loopback dev/idev if we haven't done so. */
if (dev != net->loopback_dev) {
if (dev) {
dev_put(dev);
in6_dev_put(idev);
}
dev = net->loopback_dev;
dev_hold(dev);
idev = in6_dev_get(dev);
if (!idev) {
err = -ENODEV;
goto out;
}
}
rt->dst.output = ip6_pkt_discard_out;
rt->dst.input = ip6_pkt_discard;
rt->dst.error = -ENETUNREACH;
rt->rt6i_flags = RTF_REJECT|RTF_NONEXTHOP;
goto install_route;
}
if (cfg->fc_flags & RTF_GATEWAY) {
const struct in6_addr *gw_addr;
int gwa_type;
gw_addr = &cfg->fc_gateway;
rt->rt6i_gateway = *gw_addr;
gwa_type = ipv6_addr_type(gw_addr);
if (gwa_type != (IPV6_ADDR_LINKLOCAL|IPV6_ADDR_UNICAST)) {
struct rt6_info *grt;
/* IPv6 strictly inhibits using not link-local
addresses as nexthop address.
Otherwise, router will not able to send redirects.
It is very good, but in some (rare!) circumstances
(SIT, PtP, NBMA NOARP links) it is handy to allow
some exceptions. --ANK
*/
err = -EINVAL;
if (!(gwa_type & IPV6_ADDR_UNICAST))
goto out;
grt = rt6_lookup(net, gw_addr, NULL, cfg->fc_ifindex, 1);
err = -EHOSTUNREACH;
if (!grt)
goto out;
if (dev) {
if (dev != grt->dst.dev) {
dst_release(&grt->dst);
goto out;
}
} else {
dev = grt->dst.dev;
idev = grt->rt6i_idev;
dev_hold(dev);
in6_dev_hold(grt->rt6i_idev);
}
if (!(grt->rt6i_flags & RTF_GATEWAY))
err = 0;
dst_release(&grt->dst);
if (err)
goto out;
}
err = -EINVAL;
if (!dev || (dev->flags & IFF_LOOPBACK))
goto out;
}
err = -ENODEV;
if (!dev)
goto out;
if (!ipv6_addr_any(&cfg->fc_prefsrc)) {
if (!ipv6_chk_addr(net, &cfg->fc_prefsrc, dev, 0)) {
err = -EINVAL;
goto out;
}
rt->rt6i_prefsrc.addr = cfg->fc_prefsrc;
rt->rt6i_prefsrc.plen = 128;
} else
rt->rt6i_prefsrc.plen = 0;
if (cfg->fc_flags & (RTF_GATEWAY | RTF_NONEXTHOP)) {
err = rt6_bind_neighbour(rt, dev);
if (err)
goto out;
}
rt->rt6i_flags = cfg->fc_flags;
install_route:
if (cfg->fc_mx) {
struct nlattr *nla;
int remaining;
nla_for_each_attr(nla, cfg->fc_mx, cfg->fc_mx_len, remaining) {
int type = nla_type(nla);
if (type) {
if (type > RTAX_MAX) {
err = -EINVAL;
goto out;
}
dst_metric_set(&rt->dst, type, nla_get_u32(nla));
}
}
}
rt->dst.dev = dev;
rt->rt6i_idev = idev;
rt->rt6i_table = table;
cfg->fc_nlinfo.nl_net = dev_net(dev);
return __ip6_ins_rt(rt, &cfg->fc_nlinfo);
out:
if (dev)
dev_put(dev);
if (idev)
in6_dev_put(idev);
if (rt)
dst_free(&rt->dst);
return err;
}
static int __ip6_del_rt(struct rt6_info *rt, struct nl_info *info)
{
int err;
struct fib6_table *table;
struct net *net = dev_net(rt->dst.dev);
if (rt == net->ipv6.ip6_null_entry)
return -ENOENT;
table = rt->rt6i_table;
write_lock_bh(&table->tb6_lock);
err = fib6_del(rt, info);
dst_release(&rt->dst);
write_unlock_bh(&table->tb6_lock);
return err;
}
int ip6_del_rt(struct rt6_info *rt)
{
struct nl_info info = {
.nl_net = dev_net(rt->dst.dev),
};
return __ip6_del_rt(rt, &info);
}
static int ip6_route_del(struct fib6_config *cfg)
{
struct fib6_table *table;
struct fib6_node *fn;
struct rt6_info *rt;
int err = -ESRCH;
table = fib6_get_table(cfg->fc_nlinfo.nl_net, cfg->fc_table);
if (!table)
return err;
read_lock_bh(&table->tb6_lock);
fn = fib6_locate(&table->tb6_root,
&cfg->fc_dst, cfg->fc_dst_len,
&cfg->fc_src, cfg->fc_src_len);
if (fn) {
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
if (cfg->fc_ifindex &&
(!rt->dst.dev ||
rt->dst.dev->ifindex != cfg->fc_ifindex))
continue;
if (cfg->fc_flags & RTF_GATEWAY &&
!ipv6_addr_equal(&cfg->fc_gateway, &rt->rt6i_gateway))
continue;
if (cfg->fc_metric && cfg->fc_metric != rt->rt6i_metric)
continue;
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
return __ip6_del_rt(rt, &cfg->fc_nlinfo);
}
}
read_unlock_bh(&table->tb6_lock);
return err;
}
/*
* Handle redirects
*/
struct ip6rd_flowi {
struct flowi6 fl6;
struct in6_addr gateway;
};
static struct rt6_info *__ip6_route_redirect(struct net *net,
struct fib6_table *table,
struct flowi6 *fl6,
int flags)
{
struct ip6rd_flowi *rdfl = (struct ip6rd_flowi *)fl6;
struct rt6_info *rt;
struct fib6_node *fn;
/*
* Get the "current" route for this destination and
* check if the redirect has come from approriate router.
*
* RFC 2461 specifies that redirects should only be
* accepted if they come from the nexthop to the target.
* Due to the way the routes are chosen, this notion
* is a bit fuzzy and one might need to check all possible
* routes.
*/
read_lock_bh(&table->tb6_lock);
fn = fib6_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
restart:
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
/*
* Current route is on-link; redirect is always invalid.
*
* Seems, previous statement is not true. It could
* be node, which looks for us as on-link (f.e. proxy ndisc)
* But then router serving it might decide, that we should
* know truth 8)8) --ANK (980726).
*/
if (rt6_check_expired(rt))
continue;
if (!(rt->rt6i_flags & RTF_GATEWAY))
continue;
if (fl6->flowi6_oif != rt->dst.dev->ifindex)
continue;
if (!ipv6_addr_equal(&rdfl->gateway, &rt->rt6i_gateway))
continue;
break;
}
if (!rt)
rt = net->ipv6.ip6_null_entry;
BACKTRACK(net, &fl6->saddr);
out:
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
return rt;
};
static struct rt6_info *ip6_route_redirect(const struct in6_addr *dest,
const struct in6_addr *src,
const struct in6_addr *gateway,
struct net_device *dev)
{
int flags = RT6_LOOKUP_F_HAS_SADDR;
struct net *net = dev_net(dev);
struct ip6rd_flowi rdfl = {
.fl6 = {
.flowi6_oif = dev->ifindex,
.daddr = *dest,
.saddr = *src,
},
};
rdfl.gateway = *gateway;
if (rt6_need_strict(dest))
flags |= RT6_LOOKUP_F_IFACE;
return (struct rt6_info *)fib6_rule_lookup(net, &rdfl.fl6,
flags, __ip6_route_redirect);
}
void rt6_redirect(const struct in6_addr *dest, const struct in6_addr *src,
const struct in6_addr *saddr,
struct neighbour *neigh, u8 *lladdr, int on_link)
{
struct rt6_info *rt, *nrt = NULL;
struct netevent_redirect netevent;
struct net *net = dev_net(neigh->dev);
rt = ip6_route_redirect(dest, src, saddr, neigh->dev);
if (rt == net->ipv6.ip6_null_entry) {
if (net_ratelimit())
printk(KERN_DEBUG "rt6_redirect: source isn't a valid nexthop "
"for redirect target\n");
goto out;
}
/*
* We have finally decided to accept it.
*/
neigh_update(neigh, lladdr, NUD_STALE,
NEIGH_UPDATE_F_WEAK_OVERRIDE|
NEIGH_UPDATE_F_OVERRIDE|
(on_link ? 0 : (NEIGH_UPDATE_F_OVERRIDE_ISROUTER|
NEIGH_UPDATE_F_ISROUTER))
);
/*
* Redirect received -> path was valid.
* Look, redirects are sent only in response to data packets,
* so that this nexthop apparently is reachable. --ANK
*/
dst_confirm(&rt->dst);
/* Duplicate redirect: silently ignore. */
if (neigh == dst_get_neighbour_noref_raw(&rt->dst))
goto out;
nrt = ip6_rt_copy(rt, dest);
if (!nrt)
goto out;
nrt->rt6i_flags = RTF_GATEWAY|RTF_UP|RTF_DYNAMIC|RTF_CACHE;
if (on_link)
nrt->rt6i_flags &= ~RTF_GATEWAY;
nrt->rt6i_gateway = *(struct in6_addr *)neigh->primary_key;
dst_set_neighbour(&nrt->dst, neigh_clone(neigh));
if (ip6_ins_rt(nrt))
goto out;
netevent.old = &rt->dst;
netevent.new = &nrt->dst;
call_netevent_notifiers(NETEVENT_REDIRECT, &netevent);
if (rt->rt6i_flags & RTF_CACHE) {
ip6_del_rt(rt);
return;
}
out:
dst_release(&rt->dst);
}
/*
* Handle ICMP "packet too big" messages
* i.e. Path MTU discovery
*/
static void rt6_do_pmtu_disc(const struct in6_addr *daddr, const struct in6_addr *saddr,
struct net *net, u32 pmtu, int ifindex)
{
struct rt6_info *rt, *nrt;
int allfrag = 0;
again:
rt = rt6_lookup(net, daddr, saddr, ifindex, 0);
if (!rt)
return;
if (rt6_check_expired(rt)) {
ip6_del_rt(rt);
goto again;
}
if (pmtu >= dst_mtu(&rt->dst))
goto out;
if (pmtu < IPV6_MIN_MTU) {
/*
* According to RFC2460, PMTU is set to the IPv6 Minimum Link
* MTU (1280) and a fragment header should always be included
* after a node receiving Too Big message reporting PMTU is
* less than the IPv6 Minimum Link MTU.
*/
pmtu = IPV6_MIN_MTU;
allfrag = 1;
}
/* New mtu received -> path was valid.
They are sent only in response to data packets,
so that this nexthop apparently is reachable. --ANK
*/
dst_confirm(&rt->dst);
/* Host route. If it is static, it would be better
not to override it, but add new one, so that
when cache entry will expire old pmtu
would return automatically.
*/
if (rt->rt6i_flags & RTF_CACHE) {
dst_metric_set(&rt->dst, RTAX_MTU, pmtu);
if (allfrag) {
u32 features = dst_metric(&rt->dst, RTAX_FEATURES);
features |= RTAX_FEATURE_ALLFRAG;
dst_metric_set(&rt->dst, RTAX_FEATURES, features);
}
dst_set_expires(&rt->dst, net->ipv6.sysctl.ip6_rt_mtu_expires);
rt->rt6i_flags |= RTF_MODIFIED|RTF_EXPIRES;
goto out;
}
/* Network route.
Two cases are possible:
1. It is connected route. Action: COW
2. It is gatewayed route or NONEXTHOP route. Action: clone it.
*/
if (!dst_get_neighbour_noref_raw(&rt->dst) && !(rt->rt6i_flags & RTF_NONEXTHOP))
nrt = rt6_alloc_cow(rt, daddr, saddr);
else
nrt = rt6_alloc_clone(rt, daddr);
if (nrt) {
dst_metric_set(&nrt->dst, RTAX_MTU, pmtu);
if (allfrag) {
u32 features = dst_metric(&nrt->dst, RTAX_FEATURES);
features |= RTAX_FEATURE_ALLFRAG;
dst_metric_set(&nrt->dst, RTAX_FEATURES, features);
}
/* According to RFC 1981, detecting PMTU increase shouldn't be
* happened within 5 mins, the recommended timer is 10 mins.
* Here this route expiration time is set to ip6_rt_mtu_expires
* which is 10 mins. After 10 mins the decreased pmtu is expired
* and detecting PMTU increase will be automatically happened.
*/
dst_set_expires(&nrt->dst, net->ipv6.sysctl.ip6_rt_mtu_expires);
nrt->rt6i_flags |= RTF_DYNAMIC|RTF_EXPIRES;
ip6_ins_rt(nrt);
}
out:
dst_release(&rt->dst);
}
void rt6_pmtu_discovery(const struct in6_addr *daddr, const struct in6_addr *saddr,
struct net_device *dev, u32 pmtu)
{
struct net *net = dev_net(dev);
/*
* RFC 1981 states that a node "MUST reduce the size of the packets it
* is sending along the path" that caused the Packet Too Big message.
* Since it's not possible in the general case to determine which
* interface was used to send the original packet, we update the MTU
* on the interface that will be used to send future packets. We also
* update the MTU on the interface that received the Packet Too Big in
* case the original packet was forced out that interface with
* SO_BINDTODEVICE or similar. This is the next best thing to the
* correct behaviour, which would be to update the MTU on all
* interfaces.
*/
rt6_do_pmtu_disc(daddr, saddr, net, pmtu, 0);
rt6_do_pmtu_disc(daddr, saddr, net, pmtu, dev->ifindex);
}
/*
* Misc support functions
*/
static struct rt6_info *ip6_rt_copy(const struct rt6_info *ort,
const struct in6_addr *dest)
{
struct net *net = dev_net(ort->dst.dev);
struct rt6_info *rt = ip6_dst_alloc(&net->ipv6.ip6_dst_ops,
ort->dst.dev, 0);
if (rt) {
rt->dst.input = ort->dst.input;
rt->dst.output = ort->dst.output;
rt->dst.flags |= DST_HOST;
rt->rt6i_dst.addr = *dest;
rt->rt6i_dst.plen = 128;
dst_copy_metrics(&rt->dst, &ort->dst);
rt->dst.error = ort->dst.error;
rt->rt6i_idev = ort->rt6i_idev;
if (rt->rt6i_idev)
in6_dev_hold(rt->rt6i_idev);
rt->dst.lastuse = jiffies;
rt->dst.expires = 0;
rt->rt6i_gateway = ort->rt6i_gateway;
rt->rt6i_flags = ort->rt6i_flags & ~RTF_EXPIRES;
rt->rt6i_metric = 0;
#ifdef CONFIG_IPV6_SUBTREES
memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
#endif
memcpy(&rt->rt6i_prefsrc, &ort->rt6i_prefsrc, sizeof(struct rt6key));
rt->rt6i_table = ort->rt6i_table;
}
return rt;
}
#ifdef CONFIG_IPV6_ROUTE_INFO
static struct rt6_info *rt6_get_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex)
{
struct fib6_node *fn;
struct rt6_info *rt = NULL;
struct fib6_table *table;
table = fib6_get_table(net, RT6_TABLE_INFO);
if (!table)
return NULL;
write_lock_bh(&table->tb6_lock);
fn = fib6_locate(&table->tb6_root, prefix ,prefixlen, NULL, 0);
if (!fn)
goto out;
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
if (rt->dst.dev->ifindex != ifindex)
continue;
if ((rt->rt6i_flags & (RTF_ROUTEINFO|RTF_GATEWAY)) != (RTF_ROUTEINFO|RTF_GATEWAY))
continue;
if (!ipv6_addr_equal(&rt->rt6i_gateway, gwaddr))
continue;
dst_hold(&rt->dst);
break;
}
out:
write_unlock_bh(&table->tb6_lock);
return rt;
}
static struct rt6_info *rt6_add_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex,
unsigned pref)
{
struct fib6_config cfg = {
.fc_table = RT6_TABLE_INFO,
.fc_metric = IP6_RT_PRIO_USER,
.fc_ifindex = ifindex,
.fc_dst_len = prefixlen,
.fc_flags = RTF_GATEWAY | RTF_ADDRCONF | RTF_ROUTEINFO |
RTF_UP | RTF_PREF(pref),
.fc_nlinfo.pid = 0,
.fc_nlinfo.nlh = NULL,
.fc_nlinfo.nl_net = net,
};
cfg.fc_dst = *prefix;
cfg.fc_gateway = *gwaddr;
/* We should treat it as a default route if prefix length is 0. */
if (!prefixlen)
cfg.fc_flags |= RTF_DEFAULT;
ip6_route_add(&cfg);
return rt6_get_route_info(net, prefix, prefixlen, gwaddr, ifindex);
}
#endif
struct rt6_info *rt6_get_dflt_router(const struct in6_addr *addr, struct net_device *dev)
{
struct rt6_info *rt;
struct fib6_table *table;
table = fib6_get_table(dev_net(dev), RT6_TABLE_DFLT);
if (!table)
return NULL;
write_lock_bh(&table->tb6_lock);
for (rt = table->tb6_root.leaf; rt; rt=rt->dst.rt6_next) {
if (dev == rt->dst.dev &&
((rt->rt6i_flags & (RTF_ADDRCONF | RTF_DEFAULT)) == (RTF_ADDRCONF | RTF_DEFAULT)) &&
ipv6_addr_equal(&rt->rt6i_gateway, addr))
break;
}
if (rt)
dst_hold(&rt->dst);
write_unlock_bh(&table->tb6_lock);
return rt;
}
struct rt6_info *rt6_add_dflt_router(const struct in6_addr *gwaddr,
struct net_device *dev,
unsigned int pref)
{
struct fib6_config cfg = {
.fc_table = RT6_TABLE_DFLT,
.fc_metric = IP6_RT_PRIO_USER,
.fc_ifindex = dev->ifindex,
.fc_flags = RTF_GATEWAY | RTF_ADDRCONF | RTF_DEFAULT |
RTF_UP | RTF_EXPIRES | RTF_PREF(pref),
.fc_nlinfo.pid = 0,
.fc_nlinfo.nlh = NULL,
.fc_nlinfo.nl_net = dev_net(dev),
};
cfg.fc_gateway = *gwaddr;
ip6_route_add(&cfg);
return rt6_get_dflt_router(gwaddr, dev);
}
void rt6_purge_dflt_routers(struct net *net)
{
struct rt6_info *rt;
struct fib6_table *table;
/* NOTE: Keep consistent with rt6_get_dflt_router */
table = fib6_get_table(net, RT6_TABLE_DFLT);
if (!table)
return;
restart:
read_lock_bh(&table->tb6_lock);
for (rt = table->tb6_root.leaf; rt; rt = rt->dst.rt6_next) {
if (rt->rt6i_flags & (RTF_DEFAULT | RTF_ADDRCONF)) {
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
ip6_del_rt(rt);
goto restart;
}
}
read_unlock_bh(&table->tb6_lock);
}
static void rtmsg_to_fib6_config(struct net *net,
struct in6_rtmsg *rtmsg,
struct fib6_config *cfg)
{
memset(cfg, 0, sizeof(*cfg));
cfg->fc_table = RT6_TABLE_MAIN;
cfg->fc_ifindex = rtmsg->rtmsg_ifindex;
cfg->fc_metric = rtmsg->rtmsg_metric;
cfg->fc_expires = rtmsg->rtmsg_info;
cfg->fc_dst_len = rtmsg->rtmsg_dst_len;
cfg->fc_src_len = rtmsg->rtmsg_src_len;
cfg->fc_flags = rtmsg->rtmsg_flags;
cfg->fc_nlinfo.nl_net = net;
cfg->fc_dst = rtmsg->rtmsg_dst;
cfg->fc_src = rtmsg->rtmsg_src;
cfg->fc_gateway = rtmsg->rtmsg_gateway;
}
int ipv6_route_ioctl(struct net *net, unsigned int cmd, void __user *arg)
{
struct fib6_config cfg;
struct in6_rtmsg rtmsg;
int err;
switch(cmd) {
case SIOCADDRT: /* Add a route */
case SIOCDELRT: /* Delete a route */
if (!capable(CAP_NET_ADMIN))
return -EPERM;
err = copy_from_user(&rtmsg, arg,
sizeof(struct in6_rtmsg));
if (err)
return -EFAULT;
rtmsg_to_fib6_config(net, &rtmsg, &cfg);
rtnl_lock();
switch (cmd) {
case SIOCADDRT:
err = ip6_route_add(&cfg);
break;
case SIOCDELRT:
err = ip6_route_del(&cfg);
break;
default:
err = -EINVAL;
}
rtnl_unlock();
return err;
}
return -EINVAL;
}
/*
* Drop the packet on the floor
*/
static int ip6_pkt_drop(struct sk_buff *skb, u8 code, int ipstats_mib_noroutes)
{
int type;
struct dst_entry *dst = skb_dst(skb);
switch (ipstats_mib_noroutes) {
case IPSTATS_MIB_INNOROUTES:
type = ipv6_addr_type(&ipv6_hdr(skb)->daddr);
if (type == IPV6_ADDR_ANY) {
IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst),
IPSTATS_MIB_INADDRERRORS);
break;
}
/* FALLTHROUGH */
case IPSTATS_MIB_OUTNOROUTES:
IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst),
ipstats_mib_noroutes);
break;
}
icmpv6_send(skb, ICMPV6_DEST_UNREACH, code, 0);
kfree_skb(skb);
return 0;
}
static int ip6_pkt_discard(struct sk_buff *skb)
{
return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_INNOROUTES);
}
static int ip6_pkt_discard_out(struct sk_buff *skb)
{
skb->dev = skb_dst(skb)->dev;
return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_OUTNOROUTES);
}
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static int ip6_pkt_prohibit(struct sk_buff *skb)
{
return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_INNOROUTES);
}
static int ip6_pkt_prohibit_out(struct sk_buff *skb)
{
skb->dev = skb_dst(skb)->dev;
return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_OUTNOROUTES);
}
#endif
/*
* Allocate a dst for local (unicast / anycast) address.
*/
struct rt6_info *addrconf_dst_alloc(struct inet6_dev *idev,
const struct in6_addr *addr,
bool anycast)
{
struct net *net = dev_net(idev->dev);
struct rt6_info *rt = ip6_dst_alloc(&net->ipv6.ip6_dst_ops,
net->loopback_dev, 0);
int err;
if (!rt) {
if (net_ratelimit())
pr_warning("IPv6: Maximum number of routes reached,"
" consider increasing route/max_size.\n");
return ERR_PTR(-ENOMEM);
}
in6_dev_hold(idev);
rt->dst.flags |= DST_HOST;
rt->dst.input = ip6_input;
rt->dst.output = ip6_output;
rt->rt6i_idev = idev;
rt->dst.obsolete = -1;
rt->rt6i_flags = RTF_UP | RTF_NONEXTHOP;
if (anycast)
rt->rt6i_flags |= RTF_ANYCAST;
else
rt->rt6i_flags |= RTF_LOCAL;
err = rt6_bind_neighbour(rt, rt->dst.dev);
if (err) {
dst_free(&rt->dst);
return ERR_PTR(err);
}
rt->rt6i_dst.addr = *addr;
rt->rt6i_dst.plen = 128;
rt->rt6i_table = fib6_get_table(net, RT6_TABLE_LOCAL);
atomic_set(&rt->dst.__refcnt, 1);
return rt;
}
int ip6_route_get_saddr(struct net *net,
struct rt6_info *rt,
const struct in6_addr *daddr,
unsigned int prefs,
struct in6_addr *saddr)
{
struct inet6_dev *idev = ip6_dst_idev((struct dst_entry*)rt);
int err = 0;
if (rt->rt6i_prefsrc.plen)
*saddr = rt->rt6i_prefsrc.addr;
else
err = ipv6_dev_get_saddr(net, idev ? idev->dev : NULL,
daddr, prefs, saddr);
return err;
}
/* remove deleted ip from prefsrc entries */
struct arg_dev_net_ip {
struct net_device *dev;
struct net *net;
struct in6_addr *addr;
};
static int fib6_remove_prefsrc(struct rt6_info *rt, void *arg)
{
struct net_device *dev = ((struct arg_dev_net_ip *)arg)->dev;
struct net *net = ((struct arg_dev_net_ip *)arg)->net;
struct in6_addr *addr = ((struct arg_dev_net_ip *)arg)->addr;
if (((void *)rt->dst.dev == dev || !dev) &&
rt != net->ipv6.ip6_null_entry &&
ipv6_addr_equal(addr, &rt->rt6i_prefsrc.addr)) {
/* remove prefsrc entry */
rt->rt6i_prefsrc.plen = 0;
}
return 0;
}
void rt6_remove_prefsrc(struct inet6_ifaddr *ifp)
{
struct net *net = dev_net(ifp->idev->dev);
struct arg_dev_net_ip adni = {
.dev = ifp->idev->dev,
.net = net,
.addr = &ifp->addr,
};
fib6_clean_all(net, fib6_remove_prefsrc, 0, &adni);
}
struct arg_dev_net {
struct net_device *dev;
struct net *net;
};
static int fib6_ifdown(struct rt6_info *rt, void *arg)
{
const struct arg_dev_net *adn = arg;
const struct net_device *dev = adn->dev;
if ((rt->dst.dev == dev || !dev) &&
rt != adn->net->ipv6.ip6_null_entry)
return -1;
return 0;
}
void rt6_ifdown(struct net *net, struct net_device *dev)
{
struct arg_dev_net adn = {
.dev = dev,
.net = net,
};
fib6_clean_all(net, fib6_ifdown, 0, &adn);
icmp6_clean_all(fib6_ifdown, &adn);
}
struct rt6_mtu_change_arg
{
struct net_device *dev;
unsigned mtu;
};
static int rt6_mtu_change_route(struct rt6_info *rt, void *p_arg)
{
struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *) p_arg;
struct inet6_dev *idev;
/* In IPv6 pmtu discovery is not optional,
so that RTAX_MTU lock cannot disable it.
We still use this lock to block changes
caused by addrconf/ndisc.
*/
idev = __in6_dev_get(arg->dev);
if (!idev)
return 0;
/* For administrative MTU increase, there is no way to discover
IPv6 PMTU increase, so PMTU increase should be updated here.
Since RFC 1981 doesn't include administrative MTU increase
update PMTU increase is a MUST. (i.e. jumbo frame)
*/
/*
If new MTU is less than route PMTU, this new MTU will be the
lowest MTU in the path, update the route PMTU to reflect PMTU
decreases; if new MTU is greater than route PMTU, and the
old MTU is the lowest MTU in the path, update the route PMTU
to reflect the increase. In this case if the other nodes' MTU
also have the lowest MTU, TOO BIG MESSAGE will be lead to
PMTU discouvery.
*/
if (rt->dst.dev == arg->dev &&
!dst_metric_locked(&rt->dst, RTAX_MTU) &&
(dst_mtu(&rt->dst) >= arg->mtu ||
(dst_mtu(&rt->dst) < arg->mtu &&
dst_mtu(&rt->dst) == idev->cnf.mtu6))) {
dst_metric_set(&rt->dst, RTAX_MTU, arg->mtu);
}
return 0;
}
void rt6_mtu_change(struct net_device *dev, unsigned mtu)
{
struct rt6_mtu_change_arg arg = {
.dev = dev,
.mtu = mtu,
};
fib6_clean_all(dev_net(dev), rt6_mtu_change_route, 0, &arg);
}
static const struct nla_policy rtm_ipv6_policy[RTA_MAX+1] = {
[RTA_GATEWAY] = { .len = sizeof(struct in6_addr) },
[RTA_OIF] = { .type = NLA_U32 },
[RTA_IIF] = { .type = NLA_U32 },
[RTA_PRIORITY] = { .type = NLA_U32 },
[RTA_METRICS] = { .type = NLA_NESTED },
};
static int rtm_to_fib6_config(struct sk_buff *skb, struct nlmsghdr *nlh,
struct fib6_config *cfg)
{
struct rtmsg *rtm;
struct nlattr *tb[RTA_MAX+1];
int err;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv6_policy);
if (err < 0)
goto errout;
err = -EINVAL;
rtm = nlmsg_data(nlh);
memset(cfg, 0, sizeof(*cfg));
cfg->fc_table = rtm->rtm_table;
cfg->fc_dst_len = rtm->rtm_dst_len;
cfg->fc_src_len = rtm->rtm_src_len;
cfg->fc_flags = RTF_UP;
cfg->fc_protocol = rtm->rtm_protocol;
if (rtm->rtm_type == RTN_UNREACHABLE)
cfg->fc_flags |= RTF_REJECT;
if (rtm->rtm_type == RTN_LOCAL)
cfg->fc_flags |= RTF_LOCAL;
cfg->fc_nlinfo.pid = NETLINK_CB(skb).pid;
cfg->fc_nlinfo.nlh = nlh;
cfg->fc_nlinfo.nl_net = sock_net(skb->sk);
if (tb[RTA_GATEWAY]) {
nla_memcpy(&cfg->fc_gateway, tb[RTA_GATEWAY], 16);
cfg->fc_flags |= RTF_GATEWAY;
}
if (tb[RTA_DST]) {
int plen = (rtm->rtm_dst_len + 7) >> 3;
if (nla_len(tb[RTA_DST]) < plen)
goto errout;
nla_memcpy(&cfg->fc_dst, tb[RTA_DST], plen);
}
if (tb[RTA_SRC]) {
int plen = (rtm->rtm_src_len + 7) >> 3;
if (nla_len(tb[RTA_SRC]) < plen)
goto errout;
nla_memcpy(&cfg->fc_src, tb[RTA_SRC], plen);
}
if (tb[RTA_PREFSRC])
nla_memcpy(&cfg->fc_prefsrc, tb[RTA_PREFSRC], 16);
if (tb[RTA_OIF])
cfg->fc_ifindex = nla_get_u32(tb[RTA_OIF]);
if (tb[RTA_PRIORITY])
cfg->fc_metric = nla_get_u32(tb[RTA_PRIORITY]);
if (tb[RTA_METRICS]) {
cfg->fc_mx = nla_data(tb[RTA_METRICS]);
cfg->fc_mx_len = nla_len(tb[RTA_METRICS]);
}
if (tb[RTA_TABLE])
cfg->fc_table = nla_get_u32(tb[RTA_TABLE]);
err = 0;
errout:
return err;
}
static int inet6_rtm_delroute(struct sk_buff *skb, struct nlmsghdr* nlh, void *arg)
{
struct fib6_config cfg;
int err;
err = rtm_to_fib6_config(skb, nlh, &cfg);
if (err < 0)
return err;
return ip6_route_del(&cfg);
}
static int inet6_rtm_newroute(struct sk_buff *skb, struct nlmsghdr* nlh, void *arg)
{
struct fib6_config cfg;
int err;
err = rtm_to_fib6_config(skb, nlh, &cfg);
if (err < 0)
return err;
return ip6_route_add(&cfg);
}
static inline size_t rt6_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct rtmsg))
+ nla_total_size(16) /* RTA_SRC */
+ nla_total_size(16) /* RTA_DST */
+ nla_total_size(16) /* RTA_GATEWAY */
+ nla_total_size(16) /* RTA_PREFSRC */
+ nla_total_size(4) /* RTA_TABLE */
+ nla_total_size(4) /* RTA_IIF */
+ nla_total_size(4) /* RTA_OIF */
+ nla_total_size(4) /* RTA_PRIORITY */
+ RTAX_MAX * nla_total_size(4) /* RTA_METRICS */
+ nla_total_size(sizeof(struct rta_cacheinfo));
}
static int rt6_fill_node(struct net *net,
struct sk_buff *skb, struct rt6_info *rt,
struct in6_addr *dst, struct in6_addr *src,
int iif, int type, u32 pid, u32 seq,
int prefix, int nowait, unsigned int flags)
{
const struct inet_peer *peer;
struct rtmsg *rtm;
struct nlmsghdr *nlh;
long expires;
u32 table;
struct neighbour *n;
u32 ts, tsage;
if (prefix) { /* user wants prefix routes only */
if (!(rt->rt6i_flags & RTF_PREFIX_RT)) {
/* success since this is not a prefix route */
return 1;
}
}
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*rtm), flags);
if (!nlh)
return -EMSGSIZE;
rtm = nlmsg_data(nlh);
rtm->rtm_family = AF_INET6;
rtm->rtm_dst_len = rt->rt6i_dst.plen;
rtm->rtm_src_len = rt->rt6i_src.plen;
rtm->rtm_tos = 0;
if (rt->rt6i_table)
table = rt->rt6i_table->tb6_id;
else
table = RT6_TABLE_UNSPEC;
rtm->rtm_table = table;
NLA_PUT_U32(skb, RTA_TABLE, table);
if (rt->rt6i_flags & RTF_REJECT)
rtm->rtm_type = RTN_UNREACHABLE;
else if (rt->rt6i_flags & RTF_LOCAL)
rtm->rtm_type = RTN_LOCAL;
else if (rt->dst.dev && (rt->dst.dev->flags & IFF_LOOPBACK))
rtm->rtm_type = RTN_LOCAL;
else
rtm->rtm_type = RTN_UNICAST;
rtm->rtm_flags = 0;
rtm->rtm_scope = RT_SCOPE_UNIVERSE;
rtm->rtm_protocol = rt->rt6i_protocol;
if (rt->rt6i_flags & RTF_DYNAMIC)
rtm->rtm_protocol = RTPROT_REDIRECT;
else if (rt->rt6i_flags & RTF_ADDRCONF)
rtm->rtm_protocol = RTPROT_KERNEL;
else if (rt->rt6i_flags & RTF_DEFAULT)
rtm->rtm_protocol = RTPROT_RA;
if (rt->rt6i_flags & RTF_CACHE)
rtm->rtm_flags |= RTM_F_CLONED;
if (dst) {
NLA_PUT(skb, RTA_DST, 16, dst);
rtm->rtm_dst_len = 128;
} else if (rtm->rtm_dst_len)
NLA_PUT(skb, RTA_DST, 16, &rt->rt6i_dst.addr);
#ifdef CONFIG_IPV6_SUBTREES
if (src) {
NLA_PUT(skb, RTA_SRC, 16, src);
rtm->rtm_src_len = 128;
} else if (rtm->rtm_src_len)
NLA_PUT(skb, RTA_SRC, 16, &rt->rt6i_src.addr);
#endif
if (iif) {
#ifdef CONFIG_IPV6_MROUTE
if (ipv6_addr_is_multicast(&rt->rt6i_dst.addr)) {
int err = ip6mr_get_route(net, skb, rtm, nowait);
if (err <= 0) {
if (!nowait) {
if (err == 0)
return 0;
goto nla_put_failure;
} else {
if (err == -EMSGSIZE)
goto nla_put_failure;
}
}
} else
#endif
NLA_PUT_U32(skb, RTA_IIF, iif);
} else if (dst) {
struct in6_addr saddr_buf;
if (ip6_route_get_saddr(net, rt, dst, 0, &saddr_buf) == 0)
NLA_PUT(skb, RTA_PREFSRC, 16, &saddr_buf);
}
if (rt->rt6i_prefsrc.plen) {
struct in6_addr saddr_buf;
saddr_buf = rt->rt6i_prefsrc.addr;
NLA_PUT(skb, RTA_PREFSRC, 16, &saddr_buf);
}
if (rtnetlink_put_metrics(skb, dst_metrics_ptr(&rt->dst)) < 0)
goto nla_put_failure;
rcu_read_lock();
n = dst_get_neighbour_noref(&rt->dst);
if (n)
NLA_PUT(skb, RTA_GATEWAY, 16, &n->primary_key);
rcu_read_unlock();
if (rt->dst.dev)
NLA_PUT_U32(skb, RTA_OIF, rt->dst.dev->ifindex);
NLA_PUT_U32(skb, RTA_PRIORITY, rt->rt6i_metric);
if (!(rt->rt6i_flags & RTF_EXPIRES))
expires = 0;
else if (rt->dst.expires - jiffies < INT_MAX)
expires = rt->dst.expires - jiffies;
else
expires = INT_MAX;
peer = rt->rt6i_peer;
ts = tsage = 0;
if (peer && peer->tcp_ts_stamp) {
ts = peer->tcp_ts;
tsage = get_seconds() - peer->tcp_ts_stamp;
}
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, ts, tsage,
expires, rt->dst.error) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
int rt6_dump_route(struct rt6_info *rt, void *p_arg)
{
struct rt6_rtnl_dump_arg *arg = (struct rt6_rtnl_dump_arg *) p_arg;
int prefix;
if (nlmsg_len(arg->cb->nlh) >= sizeof(struct rtmsg)) {
struct rtmsg *rtm = nlmsg_data(arg->cb->nlh);
prefix = (rtm->rtm_flags & RTM_F_PREFIX) != 0;
} else
prefix = 0;
return rt6_fill_node(arg->net,
arg->skb, rt, NULL, NULL, 0, RTM_NEWROUTE,
NETLINK_CB(arg->cb->skb).pid, arg->cb->nlh->nlmsg_seq,
prefix, 0, NLM_F_MULTI);
}
static int inet6_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr* nlh, void *arg)
{
struct net *net = sock_net(in_skb->sk);
struct nlattr *tb[RTA_MAX+1];
struct rt6_info *rt;
struct sk_buff *skb;
struct rtmsg *rtm;
struct flowi6 fl6;
int err, iif = 0;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv6_policy);
if (err < 0)
goto errout;
err = -EINVAL;
memset(&fl6, 0, sizeof(fl6));
if (tb[RTA_SRC]) {
if (nla_len(tb[RTA_SRC]) < sizeof(struct in6_addr))
goto errout;
fl6.saddr = *(struct in6_addr *)nla_data(tb[RTA_SRC]);
}
if (tb[RTA_DST]) {
if (nla_len(tb[RTA_DST]) < sizeof(struct in6_addr))
goto errout;
fl6.daddr = *(struct in6_addr *)nla_data(tb[RTA_DST]);
}
if (tb[RTA_IIF])
iif = nla_get_u32(tb[RTA_IIF]);
if (tb[RTA_OIF])
fl6.flowi6_oif = nla_get_u32(tb[RTA_OIF]);
if (iif) {
struct net_device *dev;
dev = __dev_get_by_index(net, iif);
if (!dev) {
err = -ENODEV;
goto errout;
}
}
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
err = -ENOBUFS;
goto errout;
}
/* Reserve room for dummy headers, this skb can pass
through good chunk of routing engine.
*/
skb_reset_mac_header(skb);
skb_reserve(skb, MAX_HEADER + sizeof(struct ipv6hdr));
rt = (struct rt6_info*) ip6_route_output(net, NULL, &fl6);
skb_dst_set(skb, &rt->dst);
err = rt6_fill_node(net, skb, rt, &fl6.daddr, &fl6.saddr, iif,
RTM_NEWROUTE, NETLINK_CB(in_skb).pid,
nlh->nlmsg_seq, 0, 0, 0);
if (err < 0) {
kfree_skb(skb);
goto errout;
}
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).pid);
errout:
return err;
}
void inet6_rt_notify(int event, struct rt6_info *rt, struct nl_info *info)
{
struct sk_buff *skb;
struct net *net = info->nl_net;
u32 seq;
int err;
err = -ENOBUFS;
seq = info->nlh ? info->nlh->nlmsg_seq : 0;
skb = nlmsg_new(rt6_nlmsg_size(), gfp_any());
if (!skb)
goto errout;
err = rt6_fill_node(net, skb, rt, NULL, NULL, 0,
event, info->pid, seq, 0, 0, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, info->pid, RTNLGRP_IPV6_ROUTE,
info->nlh, gfp_any());
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
}
static int ip6_route_dev_notify(struct notifier_block *this,
unsigned long event, void *data)
{
struct net_device *dev = (struct net_device *)data;
struct net *net = dev_net(dev);
if (event == NETDEV_REGISTER && (dev->flags & IFF_LOOPBACK)) {
net->ipv6.ip6_null_entry->dst.dev = dev;
net->ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(dev);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.ip6_prohibit_entry->dst.dev = dev;
net->ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(dev);
net->ipv6.ip6_blk_hole_entry->dst.dev = dev;
net->ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(dev);
#endif
}
return NOTIFY_OK;
}
/*
* /proc
*/
#ifdef CONFIG_PROC_FS
struct rt6_proc_arg
{
char *buffer;
int offset;
int length;
int skip;
int len;
};
static int rt6_info_route(struct rt6_info *rt, void *p_arg)
{
struct seq_file *m = p_arg;
struct neighbour *n;
seq_printf(m, "%pi6 %02x ", &rt->rt6i_dst.addr, rt->rt6i_dst.plen);
#ifdef CONFIG_IPV6_SUBTREES
seq_printf(m, "%pi6 %02x ", &rt->rt6i_src.addr, rt->rt6i_src.plen);
#else
seq_puts(m, "00000000000000000000000000000000 00 ");
#endif
rcu_read_lock();
n = dst_get_neighbour_noref(&rt->dst);
if (n) {
seq_printf(m, "%pi6", n->primary_key);
} else {
seq_puts(m, "00000000000000000000000000000000");
}
rcu_read_unlock();
seq_printf(m, " %08x %08x %08x %08x %8s\n",
rt->rt6i_metric, atomic_read(&rt->dst.__refcnt),
rt->dst.__use, rt->rt6i_flags,
rt->dst.dev ? rt->dst.dev->name : "");
return 0;
}
static int ipv6_route_show(struct seq_file *m, void *v)
{
struct net *net = (struct net *)m->private;
fib6_clean_all_ro(net, rt6_info_route, 0, m);
return 0;
}
static int ipv6_route_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, ipv6_route_show);
}
static const struct file_operations ipv6_route_proc_fops = {
.owner = THIS_MODULE,
.open = ipv6_route_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
static int rt6_stats_seq_show(struct seq_file *seq, void *v)
{
struct net *net = (struct net *)seq->private;
seq_printf(seq, "%04x %04x %04x %04x %04x %04x %04x\n",
net->ipv6.rt6_stats->fib_nodes,
net->ipv6.rt6_stats->fib_route_nodes,
net->ipv6.rt6_stats->fib_rt_alloc,
net->ipv6.rt6_stats->fib_rt_entries,
net->ipv6.rt6_stats->fib_rt_cache,
dst_entries_get_slow(&net->ipv6.ip6_dst_ops),
net->ipv6.rt6_stats->fib_discarded_routes);
return 0;
}
static int rt6_stats_seq_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, rt6_stats_seq_show);
}
static const struct file_operations rt6_stats_seq_fops = {
.owner = THIS_MODULE,
.open = rt6_stats_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
#endif /* CONFIG_PROC_FS */
#ifdef CONFIG_SYSCTL
static
int ipv6_sysctl_rtcache_flush(ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net;
int delay;
if (!write)
return -EINVAL;
net = (struct net *)ctl->extra1;
delay = net->ipv6.sysctl.flush_delay;
proc_dointvec(ctl, write, buffer, lenp, ppos);
fib6_run_gc(delay <= 0 ? ~0UL : (unsigned long)delay, net);
return 0;
}
ctl_table ipv6_route_table_template[] = {
{
.procname = "flush",
.data = &init_net.ipv6.sysctl.flush_delay,
.maxlen = sizeof(int),
.mode = 0200,
.proc_handler = ipv6_sysctl_rtcache_flush
},
{
.procname = "gc_thresh",
.data = &ip6_dst_ops_template.gc_thresh,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_size",
.data = &init_net.ipv6.sysctl.ip6_rt_max_size,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "gc_min_interval",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_timeout",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_interval",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_elasticity",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_elasticity,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mtu_expires",
.data = &init_net.ipv6.sysctl.ip6_rt_mtu_expires,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "min_adv_mss",
.data = &init_net.ipv6.sysctl.ip6_rt_min_advmss,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "gc_min_interval_ms",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{ }
};
struct ctl_table * __net_init ipv6_route_sysctl_init(struct net *net)
{
struct ctl_table *table;
table = kmemdup(ipv6_route_table_template,
sizeof(ipv6_route_table_template),
GFP_KERNEL);
if (table) {
table[0].data = &net->ipv6.sysctl.flush_delay;
table[0].extra1 = net;
table[1].data = &net->ipv6.ip6_dst_ops.gc_thresh;
table[2].data = &net->ipv6.sysctl.ip6_rt_max_size;
table[3].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
table[4].data = &net->ipv6.sysctl.ip6_rt_gc_timeout;
table[5].data = &net->ipv6.sysctl.ip6_rt_gc_interval;
table[6].data = &net->ipv6.sysctl.ip6_rt_gc_elasticity;
table[7].data = &net->ipv6.sysctl.ip6_rt_mtu_expires;
table[8].data = &net->ipv6.sysctl.ip6_rt_min_advmss;
table[9].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
}
return table;
}
#endif
static int __net_init ip6_route_net_init(struct net *net)
{
int ret = -ENOMEM;
memcpy(&net->ipv6.ip6_dst_ops, &ip6_dst_ops_template,
sizeof(net->ipv6.ip6_dst_ops));
if (dst_entries_init(&net->ipv6.ip6_dst_ops) < 0)
goto out_ip6_dst_ops;
net->ipv6.ip6_null_entry = kmemdup(&ip6_null_entry_template,
sizeof(*net->ipv6.ip6_null_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_null_entry)
goto out_ip6_dst_entries;
net->ipv6.ip6_null_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_null_entry;
net->ipv6.ip6_null_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_null_entry->dst,
ip6_template_metrics, true);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.ip6_prohibit_entry = kmemdup(&ip6_prohibit_entry_template,
sizeof(*net->ipv6.ip6_prohibit_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_prohibit_entry)
goto out_ip6_null_entry;
net->ipv6.ip6_prohibit_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_prohibit_entry;
net->ipv6.ip6_prohibit_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_prohibit_entry->dst,
ip6_template_metrics, true);
net->ipv6.ip6_blk_hole_entry = kmemdup(&ip6_blk_hole_entry_template,
sizeof(*net->ipv6.ip6_blk_hole_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_blk_hole_entry)
goto out_ip6_prohibit_entry;
net->ipv6.ip6_blk_hole_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_blk_hole_entry;
net->ipv6.ip6_blk_hole_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_blk_hole_entry->dst,
ip6_template_metrics, true);
#endif
net->ipv6.sysctl.flush_delay = 0;
net->ipv6.sysctl.ip6_rt_max_size = 4096;
net->ipv6.sysctl.ip6_rt_gc_min_interval = HZ / 2;
net->ipv6.sysctl.ip6_rt_gc_timeout = 60*HZ;
net->ipv6.sysctl.ip6_rt_gc_interval = 30*HZ;
net->ipv6.sysctl.ip6_rt_gc_elasticity = 9;
net->ipv6.sysctl.ip6_rt_mtu_expires = 10*60*HZ;
net->ipv6.sysctl.ip6_rt_min_advmss = IPV6_MIN_MTU - 20 - 40;
#ifdef CONFIG_PROC_FS
proc_net_fops_create(net, "ipv6_route", 0, &ipv6_route_proc_fops);
proc_net_fops_create(net, "rt6_stats", S_IRUGO, &rt6_stats_seq_fops);
#endif
net->ipv6.ip6_rt_gc_expire = 30*HZ;
ret = 0;
out:
return ret;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
out_ip6_prohibit_entry:
kfree(net->ipv6.ip6_prohibit_entry);
out_ip6_null_entry:
kfree(net->ipv6.ip6_null_entry);
#endif
out_ip6_dst_entries:
dst_entries_destroy(&net->ipv6.ip6_dst_ops);
out_ip6_dst_ops:
goto out;
}
static void __net_exit ip6_route_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_net_remove(net, "ipv6_route");
proc_net_remove(net, "rt6_stats");
#endif
kfree(net->ipv6.ip6_null_entry);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
kfree(net->ipv6.ip6_prohibit_entry);
kfree(net->ipv6.ip6_blk_hole_entry);
#endif
dst_entries_destroy(&net->ipv6.ip6_dst_ops);
}
static struct pernet_operations ip6_route_net_ops = {
.init = ip6_route_net_init,
.exit = ip6_route_net_exit,
};
static struct notifier_block ip6_route_dev_notifier = {
.notifier_call = ip6_route_dev_notify,
.priority = 0,
};
int __init ip6_route_init(void)
{
int ret;
ret = -ENOMEM;
ip6_dst_ops_template.kmem_cachep =
kmem_cache_create("ip6_dst_cache", sizeof(struct rt6_info), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!ip6_dst_ops_template.kmem_cachep)
goto out;
ret = dst_entries_init(&ip6_dst_blackhole_ops);
if (ret)
goto out_kmem_cache;
ret = register_pernet_subsys(&ip6_route_net_ops);
if (ret)
goto out_dst_entries;
ip6_dst_blackhole_ops.kmem_cachep = ip6_dst_ops_template.kmem_cachep;
/* Registering of the loopback is done before this portion of code,
* the loopback reference in rt6_info will not be taken, do it
* manually for init_net */
init_net.ipv6.ip6_null_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
init_net.ipv6.ip6_prohibit_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
init_net.ipv6.ip6_blk_hole_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
#endif
ret = fib6_init();
if (ret)
goto out_register_subsys;
ret = xfrm6_init();
if (ret)
goto out_fib6_init;
ret = fib6_rules_init();
if (ret)
goto xfrm6_init;
ret = -ENOBUFS;
if (__rtnl_register(PF_INET6, RTM_NEWROUTE, inet6_rtm_newroute, NULL, NULL) ||
__rtnl_register(PF_INET6, RTM_DELROUTE, inet6_rtm_delroute, NULL, NULL) ||
__rtnl_register(PF_INET6, RTM_GETROUTE, inet6_rtm_getroute, NULL, NULL))
goto fib6_rules_init;
ret = register_netdevice_notifier(&ip6_route_dev_notifier);
if (ret)
goto fib6_rules_init;
out:
return ret;
fib6_rules_init:
fib6_rules_cleanup();
xfrm6_init:
xfrm6_fini();
out_fib6_init:
fib6_gc_cleanup();
out_register_subsys:
unregister_pernet_subsys(&ip6_route_net_ops);
out_dst_entries:
dst_entries_destroy(&ip6_dst_blackhole_ops);
out_kmem_cache:
kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
goto out;
}
void ip6_route_cleanup(void)
{
unregister_netdevice_notifier(&ip6_route_dev_notifier);
fib6_rules_cleanup();
xfrm6_fini();
fib6_gc_cleanup();
unregister_pernet_subsys(&ip6_route_net_ops);
dst_entries_destroy(&ip6_dst_blackhole_ops);
kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
}
| gpl-2.0 |
cfpeng/linux | net/ipv6/syncookies.c | 28 | 7291 | /*
* IPv6 Syncookies implementation for the Linux kernel
*
* Authors:
* Glenn Griffin <ggriffin.kernel@gmail.com>
*
* Based on IPv4 implementation by Andi Kleen
* linux/net/ipv4/syncookies.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <linux/tcp.h>
#include <linux/random.h>
#include <linux/cryptohash.h>
#include <linux/kernel.h>
#include <net/ipv6.h>
#include <net/tcp.h>
#define COOKIEBITS 24 /* Upper bits store count */
#define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
static u32 syncookie6_secret[2][16-4+SHA_DIGEST_WORDS] __read_mostly;
/* RFC 2460, Section 8.3:
* [ipv6 tcp] MSS must be computed as the maximum packet size minus 60 [..]
*
* Due to IPV6_MIN_MTU=1280 the lowest possible MSS is 1220, which allows
* using higher values than ipv4 tcp syncookies.
* The other values are chosen based on ethernet (1500 and 9k MTU), plus
* one that accounts for common encap (PPPoe) overhead. Table must be sorted.
*/
static __u16 const msstab[] = {
1280 - 60, /* IPV6_MIN_MTU - 60 */
1480 - 60,
1500 - 60,
9000 - 60,
};
static DEFINE_PER_CPU(__u32 [16 + 5 + SHA_WORKSPACE_WORDS],
ipv6_cookie_scratch);
static u32 cookie_hash(const struct in6_addr *saddr, const struct in6_addr *daddr,
__be16 sport, __be16 dport, u32 count, int c)
{
__u32 *tmp;
net_get_random_once(syncookie6_secret, sizeof(syncookie6_secret));
tmp = this_cpu_ptr(ipv6_cookie_scratch);
/*
* we have 320 bits of information to hash, copy in the remaining
* 192 bits required for sha_transform, from the syncookie6_secret
* and overwrite the digest with the secret
*/
memcpy(tmp + 10, syncookie6_secret[c], 44);
memcpy(tmp, saddr, 16);
memcpy(tmp + 4, daddr, 16);
tmp[8] = ((__force u32)sport << 16) + (__force u32)dport;
tmp[9] = count;
sha_transform(tmp + 16, (__u8 *)tmp, tmp + 16 + 5);
return tmp[17];
}
static __u32 secure_tcp_syn_cookie(const struct in6_addr *saddr,
const struct in6_addr *daddr,
__be16 sport, __be16 dport, __u32 sseq,
__u32 data)
{
u32 count = tcp_cookie_time();
return (cookie_hash(saddr, daddr, sport, dport, 0, 0) +
sseq + (count << COOKIEBITS) +
((cookie_hash(saddr, daddr, sport, dport, count, 1) + data)
& COOKIEMASK));
}
static __u32 check_tcp_syn_cookie(__u32 cookie, const struct in6_addr *saddr,
const struct in6_addr *daddr, __be16 sport,
__be16 dport, __u32 sseq)
{
__u32 diff, count = tcp_cookie_time();
cookie -= cookie_hash(saddr, daddr, sport, dport, 0, 0) + sseq;
diff = (count - (cookie >> COOKIEBITS)) & ((__u32) -1 >> COOKIEBITS);
if (diff >= MAX_SYNCOOKIE_AGE)
return (__u32)-1;
return (cookie -
cookie_hash(saddr, daddr, sport, dport, count - diff, 1))
& COOKIEMASK;
}
u32 __cookie_v6_init_sequence(const struct ipv6hdr *iph,
const struct tcphdr *th, __u16 *mssp)
{
int mssind;
const __u16 mss = *mssp;
for (mssind = ARRAY_SIZE(msstab) - 1; mssind ; mssind--)
if (mss >= msstab[mssind])
break;
*mssp = msstab[mssind];
return secure_tcp_syn_cookie(&iph->saddr, &iph->daddr, th->source,
th->dest, ntohl(th->seq), mssind);
}
EXPORT_SYMBOL_GPL(__cookie_v6_init_sequence);
__u32 cookie_v6_init_sequence(const struct sk_buff *skb, __u16 *mssp)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
const struct tcphdr *th = tcp_hdr(skb);
return __cookie_v6_init_sequence(iph, th, mssp);
}
int __cookie_v6_check(const struct ipv6hdr *iph, const struct tcphdr *th,
__u32 cookie)
{
__u32 seq = ntohl(th->seq) - 1;
__u32 mssind = check_tcp_syn_cookie(cookie, &iph->saddr, &iph->daddr,
th->source, th->dest, seq);
return mssind < ARRAY_SIZE(msstab) ? msstab[mssind] : 0;
}
EXPORT_SYMBOL_GPL(__cookie_v6_check);
struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb)
{
struct tcp_options_received tcp_opt;
struct inet_request_sock *ireq;
struct tcp_request_sock *treq;
struct ipv6_pinfo *np = inet6_sk(sk);
struct tcp_sock *tp = tcp_sk(sk);
const struct tcphdr *th = tcp_hdr(skb);
__u32 cookie = ntohl(th->ack_seq) - 1;
struct sock *ret = sk;
struct request_sock *req;
int mss;
struct dst_entry *dst;
__u8 rcv_wscale;
if (!sysctl_tcp_syncookies || !th->ack || th->rst)
goto out;
if (tcp_synq_no_recent_overflow(sk))
goto out;
mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie);
if (mss == 0) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED);
goto out;
}
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV);
/* check for timestamp cookie support */
memset(&tcp_opt, 0, sizeof(tcp_opt));
tcp_parse_options(skb, &tcp_opt, 0, NULL);
if (!cookie_timestamp_decode(&tcp_opt))
goto out;
ret = NULL;
req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false);
if (!req)
goto out;
ireq = inet_rsk(req);
treq = tcp_rsk(req);
treq->tfo_listener = false;
if (security_inet_conn_request(sk, skb, req))
goto out_free;
req->mss = mss;
ireq->ir_rmt_port = th->source;
ireq->ir_num = ntohs(th->dest);
ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr;
ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr;
if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) ||
np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo ||
np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) {
atomic_inc(&skb->users);
ireq->pktopts = skb;
}
ireq->ir_iif = sk->sk_bound_dev_if;
/* So that link locals have meaning */
if (!sk->sk_bound_dev_if &&
ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL)
ireq->ir_iif = tcp_v6_iif(skb);
ireq->ir_mark = inet_request_mark(sk, skb);
req->num_retrans = 0;
ireq->snd_wscale = tcp_opt.snd_wscale;
ireq->sack_ok = tcp_opt.sack_ok;
ireq->wscale_ok = tcp_opt.wscale_ok;
ireq->tstamp_ok = tcp_opt.saw_tstamp;
req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0;
treq->snt_synack.v64 = 0;
treq->rcv_isn = ntohl(th->seq) - 1;
treq->snt_isn = cookie;
/*
* We need to lookup the dst_entry to get the correct window size.
* This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten
* me if there is a preferred way.
*/
{
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_TCP;
fl6.daddr = ireq->ir_v6_rmt_addr;
final_p = fl6_update_dst(&fl6, np->opt, &final);
fl6.saddr = ireq->ir_v6_loc_addr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = ireq->ir_mark;
fl6.fl6_dport = ireq->ir_rmt_port;
fl6.fl6_sport = inet_sk(sk)->inet_sport;
security_req_classify_flow(req, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst))
goto out_free;
}
req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW);
tcp_select_initial_window(tcp_full_space(sk), req->mss,
&req->rsk_rcv_wnd, &req->rsk_window_clamp,
ireq->wscale_ok, &rcv_wscale,
dst_metric(dst, RTAX_INITRWND));
ireq->rcv_wscale = rcv_wscale;
ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst);
ret = tcp_get_cookie_sock(sk, skb, req, dst);
out:
return ret;
out_free:
reqsk_free(req);
return NULL;
}
| gpl-2.0 |
arif8323/linux | drivers/usb/host/ohci-s5p.c | 28 | 12742 | /* ohci-s5p.c - Driver for USB HOST on Samsung S5P platform device
*
* Bus Glue for SAMSUNG S5P USB HOST OHCI Controller
*
* (C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at>
* (C) Copyright 2000-2002 David Brownell <dbrownell@users.sourceforge.net>
* (C) Copyright 2002 Hewlett-Packard Company
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* Author: Jingoo Han <jg1.han@samsung.com>
*
* Based on "ohci-au1xxx.c" by Matt Porter <mporter@kernel.crashing.org>
* Modified for SAMSUNG s5p OHCI by Jingoo Han <jg1.han@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <plat/ehci.h>
#include <plat/usb-phy.h>
#include <mach/board_rev.h>
struct s5p_ohci_hcd {
struct device *dev;
struct usb_hcd *hcd;
struct clk *clk;
int power_on;
};
#ifdef CONFIG_USB_EXYNOS_SWITCH
int s5p_ohci_port_power_off(struct platform_device *pdev)
{
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
ohci_writel(ohci, OHCI_INTR_MIE, &ohci->regs->intrdisable);
(void)ohci_readl(ohci, &ohci->regs->intrdisable);
ohci_writel (ohci, RH_HS_LPS, &ohci->regs->roothub.status);
return 0;
}
EXPORT_SYMBOL_GPL(s5p_ohci_port_power_off);
int s5p_ohci_port_power_on(struct platform_device *pdev)
{
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
ohci_writel (ohci, RH_HS_LPSC, &ohci->regs->roothub.status);
return 0;
}
EXPORT_SYMBOL_GPL(s5p_ohci_port_power_on);
#endif
#ifdef CONFIG_PM
static int ohci_hcd_s5p_drv_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s5p_ohci_platdata *pdata = pdev->dev.platform_data;
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
unsigned long flags;
int rc = 0;
/* Root hub was already suspended. Disable irq emission and
* mark HW unaccessible, bail out if RH has been resumed. Use
* the spinlock to properly synchronize with possible pending
* RH suspend or resume activity.
*
* This is still racy as hcd->state is manipulated outside of
* any locks =P But that will be a different fix.
*/
spin_lock_irqsave(&ohci->lock, flags);
if (hcd->state != HC_STATE_SUSPENDED && hcd->state != HC_STATE_HALT) {
spin_unlock_irqrestore(&ohci->lock, flags);
return -EINVAL;
}
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
spin_unlock_irqrestore(&ohci->lock, flags);
if (pdata && pdata->phy_exit)
pdata->phy_exit(pdev, S5P_USB_PHY_HOST);
clk_disable(s5p_ohci->clk);
return rc;
}
static int ohci_hcd_s5p_drv_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s5p_ohci_platdata *pdata = pdev->dev.platform_data;
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
int rc = 0;
clk_enable(s5p_ohci->clk);
pm_runtime_resume(&pdev->dev);
if (pdata->phy_init)
pdata->phy_init(pdev, S5P_USB_PHY_HOST);
/* Mark hardware accessible again as we are out of D3 state by now */
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
ohci_finish_controller_resume(hcd);
return rc;
}
#else
#define ohci_hcd_s5p_drv_suspend NULL
#define ohci_hcd_s5p_drv_resume NULL
#endif
#ifdef CONFIG_USB_SUSPEND
static int ohci_hcd_s5p_drv_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s5p_ohci_platdata *pdata = pdev->dev.platform_data;
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
unsigned long flags;
int rc = 0;
/* Root hub was already suspended. Disable irq emission and
* mark HW unaccessible, bail out if RH has been resumed. Use
* the spinlock to properly synchronize with possible pending
* RH suspend or resume activity.
*
* This is still racy as hcd->state is manipulated outside of
* any locks =P But that will be a different fix.
*/
spin_lock_irqsave(&ohci->lock, flags);
if (hcd->state != HC_STATE_SUSPENDED && hcd->state != HC_STATE_HALT) {
spin_unlock_irqrestore(&ohci->lock, flags);
err("Not ready %s", hcd->self.bus_name);
return rc;
}
ohci_writel(ohci, OHCI_INTR_MIE, &ohci->regs->intrdisable);
(void)ohci_readl(ohci, &ohci->regs->intrdisable);
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
spin_unlock_irqrestore(&ohci->lock, flags);
#ifdef CONFIG_USB_EXYNOS_SWITCH
if (samsung_board_rev_is_0_0())
ohci_writel (ohci, RH_HS_LPS, &ohci->regs->roothub.status);
#endif
if (pdata->phy_suspend)
pdata->phy_suspend(pdev, S5P_USB_PHY_HOST);
return rc;
}
static int ohci_hcd_s5p_drv_runtime_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s5p_ohci_platdata *pdata = pdev->dev.platform_data;
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
#ifdef CONFIG_USB_EXYNOS_SWITCH
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
#endif
if (dev->power.is_suspended)
return 0;
if (pdata->phy_resume)
pdata->phy_resume(pdev, S5P_USB_PHY_HOST);
/* Mark hardware accessible again as we are out of D3 state by now */
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
#ifdef CONFIG_USB_EXYNOS_SWITCH
if (samsung_board_rev_is_0_0())
ohci_writel (ohci, RH_HS_LPSC, &ohci->regs->roothub.status);
#endif
ohci_finish_controller_resume(hcd);
return 0;
}
#else
#define ohci_hcd_s5p_drv_runtime_suspend NULL
#define ohci_hcd_s5p_drv_runtime_resume NULL
#endif
static int ohci_s5p_start(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
int ret;
ohci_dbg(ohci, "ohci_s5p_start, ohci:%p", ohci);
ret = ohci_init(ohci);
if (ret < 0)
return ret;
ret = ohci_run(ohci);
if (ret < 0) {
err("can't start %s", hcd->self.bus_name);
ohci_stop(hcd);
return ret;
}
return 0;
}
static const struct hc_driver ohci_s5p_hc_driver = {
.description = hcd_name,
.product_desc = "s5p OHCI",
.hcd_priv_size = sizeof(struct ohci_hcd),
.irq = ohci_irq,
.flags = HCD_MEMORY|HCD_USB11,
.start = ohci_s5p_start,
.stop = ohci_stop,
.shutdown = ohci_shutdown,
.get_frame_number = ohci_get_frame,
.urb_enqueue = ohci_urb_enqueue,
.urb_dequeue = ohci_urb_dequeue,
.endpoint_disable = ohci_endpoint_disable,
.hub_status_data = ohci_hub_status_data,
.hub_control = ohci_hub_control,
#ifdef CONFIG_PM
.bus_suspend = ohci_bus_suspend,
.bus_resume = ohci_bus_resume,
#endif
.start_port_reset = ohci_start_port_reset,
};
static ssize_t show_ohci_power(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
return sprintf(buf, "EHCI Power %s\n", (s5p_ohci->power_on) ? "on" : "off");
}
static ssize_t store_ohci_power(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct s5p_ohci_platdata *pdata = pdev->dev.platform_data;
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
int power_on;
int irq;
int retval;
if (sscanf(buf, "%d", &power_on) != 1)
return -EINVAL;
device_lock(dev);
if (!power_on && s5p_ohci->power_on) {
printk(KERN_DEBUG "%s: EHCI turns off\n", __func__);
pm_runtime_forbid(dev);
s5p_ohci->power_on = 0;
usb_remove_hcd(hcd);
if (pdata && pdata->phy_exit)
pdata->phy_exit(pdev, S5P_USB_PHY_HOST);
} else if (power_on) {
printk(KERN_DEBUG "%s: EHCI turns on\n", __func__);
if (s5p_ohci->power_on) {
usb_remove_hcd(hcd);
}
if (pdata->phy_init)
pdata->phy_init(pdev, S5P_USB_PHY_HOST);
irq = platform_get_irq(pdev, 0);
retval = usb_add_hcd(hcd, irq,
IRQF_DISABLED | IRQF_SHARED);
if (retval < 0) {
dev_err(dev, "Power On Fail\n");
goto exit;
}
s5p_ohci->power_on = 1;
pm_runtime_allow(dev);
}
exit:
device_unlock(dev);
return count;
}
static DEVICE_ATTR(ohci_power, 0664, show_ohci_power, store_ohci_power);
static inline int create_ohci_sys_file(struct ohci_hcd *ohci)
{
return device_create_file(ohci_to_hcd(ohci)->self.controller,
&dev_attr_ohci_power);
}
static inline void remove_ohci_sys_file(struct ohci_hcd *ohci)
{
device_remove_file(ohci_to_hcd(ohci)->self.controller,
&dev_attr_ohci_power);
}
static int __devinit ohci_hcd_s5p_drv_probe(struct platform_device *pdev)
{
struct s5p_ohci_platdata *pdata;
struct s5p_ohci_hcd *s5p_ohci;
struct usb_hcd *hcd = NULL;
struct ohci_hcd *ohci;
struct resource *res;
int irq;
int err;
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "No platform data defined\n");
return -EINVAL;
}
s5p_ohci = kzalloc(sizeof(struct s5p_ohci_hcd), GFP_KERNEL);
if (!s5p_ohci)
return -ENOMEM;
s5p_ohci->dev = &pdev->dev;
hcd = usb_create_hcd(&ohci_s5p_hc_driver, &pdev->dev,
dev_name(&pdev->dev));
if (!hcd) {
dev_err(&pdev->dev, "Unable to create HCD\n");
err = -ENOMEM;
goto fail_hcd;
}
s5p_ohci->hcd = hcd;
s5p_ohci->clk = clk_get(&pdev->dev, "usbhost");
if (IS_ERR(s5p_ohci->clk)) {
dev_err(&pdev->dev, "Failed to get usbhost clock\n");
err = PTR_ERR(s5p_ohci->clk);
goto fail_clk;
}
err = clk_enable(s5p_ohci->clk);
if (err)
goto fail_clken;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "Failed to get I/O memory\n");
err = -ENXIO;
goto fail_io;
}
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
hcd->regs = ioremap(res->start, resource_size(res));
if (!hcd->regs) {
dev_err(&pdev->dev, "Failed to remap I/O memory\n");
err = -ENOMEM;
goto fail_io;
}
irq = platform_get_irq(pdev, 0);
if (!irq) {
dev_err(&pdev->dev, "Failed to get IRQ\n");
err = -ENODEV;
goto fail;
}
if (pdata->phy_init)
pdata->phy_init(pdev, S5P_USB_PHY_HOST);
ohci = hcd_to_ohci(hcd);
ohci_hcd_init(ohci);
#ifdef CONFIG_USB_EXYNOS_SWITCH
if (samsung_board_rev_is_0_0())
ohci->flags |= OHCI_QUIRK_SUPERIO;
#endif
err = usb_add_hcd(hcd, irq,
IRQF_DISABLED | IRQF_SHARED);
if (err) {
dev_err(&pdev->dev, "Failed to add USB HCD\n");
goto fail;
}
platform_set_drvdata(pdev, s5p_ohci);
create_ohci_sys_file(ohci);
s5p_ohci->power_on = 1;
#ifdef CONFIG_USB_EXYNOS_SWITCH
if (samsung_board_rev_is_0_0()) {
ohci_writel(ohci, OHCI_INTR_MIE, &ohci->regs->intrdisable);
(void)ohci_readl(ohci, &ohci->regs->intrdisable);
ohci_writel (ohci, RH_HS_LPS, &ohci->regs->roothub.status);
}
#endif
pm_runtime_set_active(&pdev->dev);
pm_runtime_enable(&pdev->dev);
return 0;
fail:
iounmap(hcd->regs);
fail_io:
clk_disable(s5p_ohci->clk);
fail_clken:
clk_put(s5p_ohci->clk);
fail_clk:
usb_put_hcd(hcd);
fail_hcd:
kfree(s5p_ohci);
return err;
}
static int __devexit ohci_hcd_s5p_drv_remove(struct platform_device *pdev)
{
struct s5p_ohci_platdata *pdata = pdev->dev.platform_data;
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
if (pdata && pdata->phy_resume)
pdata->phy_resume(pdev, S5P_USB_PHY_HOST);
usb_remove_hcd(hcd);
s5p_ohci->power_on = 0;
remove_ohci_sys_file(hcd_to_ohci(hcd));
if (pdata && pdata->phy_exit)
pdata->phy_exit(pdev, S5P_USB_PHY_HOST);
iounmap(hcd->regs);
clk_disable(s5p_ohci->clk);
clk_put(s5p_ohci->clk);
usb_put_hcd(hcd);
kfree(s5p_ohci);
platform_set_drvdata(pdev, NULL);
return 0;
}
static void ohci_hcd_s5p_drv_shutdown(struct platform_device *pdev)
{
struct s5p_ohci_platdata *pdata = pdev->dev.platform_data;
struct s5p_ohci_hcd *s5p_ohci = platform_get_drvdata(pdev);
struct usb_hcd *hcd = s5p_ohci->hcd;
if (!s5p_ohci->power_on)
return;
if (pdata && pdata->phy_resume)
pdata->phy_resume(pdev, S5P_USB_PHY_HOST);
if (hcd->driver->shutdown)
hcd->driver->shutdown(hcd);
}
static const struct dev_pm_ops ohci_s5p_pm_ops = {
.suspend = ohci_hcd_s5p_drv_suspend,
.resume = ohci_hcd_s5p_drv_resume,
.runtime_suspend = ohci_hcd_s5p_drv_runtime_suspend,
.runtime_resume = ohci_hcd_s5p_drv_runtime_resume,
};
static struct platform_driver ohci_hcd_s5p_driver = {
.probe = ohci_hcd_s5p_drv_probe,
.remove = __devexit_p(ohci_hcd_s5p_drv_remove),
.shutdown = ohci_hcd_s5p_drv_shutdown,
.driver = {
.name = "s5p-ohci",
.owner = THIS_MODULE,
.pm = &ohci_s5p_pm_ops,
}
};
MODULE_ALIAS("platform:s5p-ohci");
| gpl-2.0 |
heesub/tglx | drivers/mtd/maps/netsc520.c | 28 | 4271 | /* netsc520.c -- MTD map driver for AMD NetSc520 Demonstration Board
*
* Copyright (C) 2001 Mark Langsdorf (mark.langsdorf@amd.com)
* based on sc520cdp.c by Sysgo Real-Time Solutions GmbH
*
* $Id: netsc520.c,v 1.13 2004/11/28 09:40:40 dwmw2 Exp $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* The NetSc520 is a demonstration board for the Elan Sc520 processor available
* from AMD. It has a single back of 16 megs of 32-bit Flash ROM and another
* 16 megs of SDRAM.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
/*
** The single, 16 megabyte flash bank is divided into four virtual
** partitions. The first partition is 768 KiB and is intended to
** store the kernel image loaded by the bootstrap loader. The second
** partition is 256 KiB and holds the BIOS image. The third
** partition is 14.5 MiB and is intended for the flash file system
** image. The last partition is 512 KiB and contains another copy
** of the BIOS image and the reset vector.
**
** Only the third partition should be mounted. The first partition
** should not be mounted, but it can erased and written to using the
** MTD character routines. The second and fourth partitions should
** not be touched - it is possible to corrupt the BIOS image by
** mounting these partitions, and potentially the board will not be
** recoverable afterwards.
*/
/* partition_info gives details on the logical partitions that the split the
* single flash device into. If the size if zero we use up to the end of the
* device. */
static struct mtd_partition partition_info[]={
{
.name = "NetSc520 boot kernel",
.offset = 0,
.size = 0xc0000
},
{
.name = "NetSc520 Low BIOS",
.offset = 0xc0000,
.size = 0x40000
},
{
.name = "NetSc520 file system",
.offset = 0x100000,
.size = 0xe80000
},
{
.name = "NetSc520 High BIOS",
.offset = 0xf80000,
.size = 0x80000
},
};
#define NUM_PARTITIONS (sizeof(partition_info)/sizeof(partition_info[0]))
#define WINDOW_SIZE 0x00100000
#define WINDOW_ADDR 0x00200000
static struct map_info netsc520_map = {
.name = "netsc520 Flash Bank",
.size = WINDOW_SIZE,
.bankwidth = 4,
.phys = WINDOW_ADDR,
};
#define NUM_FLASH_BANKS (sizeof(netsc520_map)/sizeof(struct map_info))
static struct mtd_info *mymtd;
static int __init init_netsc520(void)
{
printk(KERN_NOTICE "NetSc520 flash device: 0x%lx at 0x%lx\n", netsc520_map.size, netsc520_map.phys);
netsc520_map.virt = ioremap_nocache(netsc520_map.phys, netsc520_map.size);
if (!netsc520_map.virt) {
printk("Failed to ioremap_nocache\n");
return -EIO;
}
simple_map_init(&netsc520_map);
mymtd = do_map_probe("cfi_probe", &netsc520_map);
if(!mymtd)
mymtd = do_map_probe("map_ram", &netsc520_map);
if(!mymtd)
mymtd = do_map_probe("map_rom", &netsc520_map);
if (!mymtd) {
iounmap(netsc520_map.virt);
return -ENXIO;
}
mymtd->owner = THIS_MODULE;
add_mtd_partitions( mymtd, partition_info, NUM_PARTITIONS );
return 0;
}
static void __exit cleanup_netsc520(void)
{
if (mymtd) {
del_mtd_partitions(mymtd);
map_destroy(mymtd);
}
if (netsc520_map.virt) {
iounmap(netsc520_map.virt);
netsc520_map.virt = NULL;
}
}
module_init(init_netsc520);
module_exit(cleanup_netsc520);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mark Langsdorf <mark.langsdorf@amd.com>");
MODULE_DESCRIPTION("MTD map driver for AMD NetSc520 Demonstration Board");
| gpl-2.0 |
finch0219/linux | drivers/platform/x86/dell-wmi.c | 540 | 11104 | /*
* Dell WMI hotkeys
*
* Copyright (C) 2008 Red Hat <mjg@redhat.com>
*
* Portions based on wistron_btns.c:
* Copyright (C) 2005 Miloslav Trmac <mitr@volny.cz>
* Copyright (C) 2005 Bernhard Rosenkraenzer <bero@arklinux.org>
* Copyright (C) 2005 Dmitry Torokhov <dtor@mail.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/acpi.h>
#include <linux/string.h>
#include <linux/dmi.h>
#include <acpi/video.h>
MODULE_AUTHOR("Matthew Garrett <mjg@redhat.com>");
MODULE_DESCRIPTION("Dell laptop WMI hotkeys driver");
MODULE_LICENSE("GPL");
#define DELL_EVENT_GUID "9DBB5994-A997-11DA-B012-B622A1EF5492"
static int acpi_video;
MODULE_ALIAS("wmi:"DELL_EVENT_GUID);
/*
* Certain keys are flagged as KE_IGNORE. All of these are either
* notifications (rather than requests for change) or are also sent
* via the keyboard controller so should not be sent again.
*/
static const struct key_entry dell_wmi_legacy_keymap[] __initconst = {
{ KE_IGNORE, 0x003a, { KEY_CAPSLOCK } },
{ KE_KEY, 0xe045, { KEY_PROG1 } },
{ KE_KEY, 0xe009, { KEY_EJECTCD } },
/* These also contain the brightness level at offset 6 */
{ KE_KEY, 0xe006, { KEY_BRIGHTNESSUP } },
{ KE_KEY, 0xe005, { KEY_BRIGHTNESSDOWN } },
/* Battery health status button */
{ KE_KEY, 0xe007, { KEY_BATTERY } },
/* Radio devices state change */
{ KE_IGNORE, 0xe008, { KEY_RFKILL } },
/* The next device is at offset 6, the active devices are at
offset 8 and the attached devices at offset 10 */
{ KE_KEY, 0xe00b, { KEY_SWITCHVIDEOMODE } },
{ KE_IGNORE, 0xe00c, { KEY_KBDILLUMTOGGLE } },
/* BIOS error detected */
{ KE_IGNORE, 0xe00d, { KEY_RESERVED } },
/* Wifi Catcher */
{ KE_KEY, 0xe011, {KEY_PROG2 } },
/* Ambient light sensor toggle */
{ KE_IGNORE, 0xe013, { KEY_RESERVED } },
{ KE_IGNORE, 0xe020, { KEY_MUTE } },
/* Shortcut and audio panel keys */
{ KE_IGNORE, 0xe025, { KEY_RESERVED } },
{ KE_IGNORE, 0xe026, { KEY_RESERVED } },
{ KE_IGNORE, 0xe02e, { KEY_VOLUMEDOWN } },
{ KE_IGNORE, 0xe030, { KEY_VOLUMEUP } },
{ KE_IGNORE, 0xe033, { KEY_KBDILLUMUP } },
{ KE_IGNORE, 0xe034, { KEY_KBDILLUMDOWN } },
{ KE_IGNORE, 0xe03a, { KEY_CAPSLOCK } },
{ KE_IGNORE, 0xe045, { KEY_NUMLOCK } },
{ KE_IGNORE, 0xe046, { KEY_SCROLLLOCK } },
{ KE_IGNORE, 0xe0f7, { KEY_MUTE } },
{ KE_IGNORE, 0xe0f8, { KEY_VOLUMEDOWN } },
{ KE_IGNORE, 0xe0f9, { KEY_VOLUMEUP } },
{ KE_END, 0 }
};
static bool dell_new_hk_type;
struct dell_bios_keymap_entry {
u16 scancode;
u16 keycode;
};
struct dell_bios_hotkey_table {
struct dmi_header header;
struct dell_bios_keymap_entry keymap[];
};
static const struct dell_bios_hotkey_table *dell_bios_hotkey_table;
static const u16 bios_to_linux_keycode[256] __initconst = {
KEY_MEDIA, KEY_NEXTSONG, KEY_PLAYPAUSE, KEY_PREVIOUSSONG,
KEY_STOPCD, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
KEY_WWW, KEY_UNKNOWN, KEY_VOLUMEDOWN, KEY_MUTE,
KEY_VOLUMEUP, KEY_UNKNOWN, KEY_BATTERY, KEY_EJECTCD,
KEY_UNKNOWN, KEY_SLEEP, KEY_PROG1, KEY_BRIGHTNESSDOWN,
KEY_BRIGHTNESSUP, KEY_UNKNOWN, KEY_KBDILLUMTOGGLE,
KEY_UNKNOWN, KEY_SWITCHVIDEOMODE, KEY_UNKNOWN, KEY_UNKNOWN,
KEY_SWITCHVIDEOMODE, KEY_UNKNOWN, KEY_UNKNOWN, KEY_PROG2,
KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_MICMUTE,
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, 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, KEY_PROG3
};
static struct input_dev *dell_wmi_input_dev;
static void dell_wmi_process_key(int reported_key)
{
const struct key_entry *key;
key = sparse_keymap_entry_from_scancode(dell_wmi_input_dev,
reported_key);
if (!key) {
pr_info("Unknown key %x pressed\n", reported_key);
return;
}
pr_debug("Key %x pressed\n", reported_key);
/* Don't report brightness notifications that will also come via ACPI */
if ((key->keycode == KEY_BRIGHTNESSUP ||
key->keycode == KEY_BRIGHTNESSDOWN) && acpi_video)
return;
sparse_keymap_report_entry(dell_wmi_input_dev, key, 1, true);
}
static void dell_wmi_notify(u32 value, void *context)
{
struct acpi_buffer response = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *obj;
acpi_status status;
acpi_size buffer_size;
u16 *buffer_entry, *buffer_end;
int len, i;
status = wmi_get_event_data(value, &response);
if (status != AE_OK) {
pr_warn("bad event status 0x%x\n", status);
return;
}
obj = (union acpi_object *)response.pointer;
if (!obj) {
pr_warn("no response\n");
return;
}
if (obj->type != ACPI_TYPE_BUFFER) {
pr_warn("bad response type %x\n", obj->type);
kfree(obj);
return;
}
pr_debug("Received WMI event (%*ph)\n",
obj->buffer.length, obj->buffer.pointer);
buffer_entry = (u16 *)obj->buffer.pointer;
buffer_size = obj->buffer.length/2;
if (!dell_new_hk_type) {
if (buffer_size >= 3 && buffer_entry[1] == 0x0)
dell_wmi_process_key(buffer_entry[2]);
else if (buffer_size >= 2)
dell_wmi_process_key(buffer_entry[1]);
else
pr_info("Received unknown WMI event\n");
kfree(obj);
return;
}
buffer_end = buffer_entry + buffer_size;
while (buffer_entry < buffer_end) {
len = buffer_entry[0];
if (len == 0)
break;
len++;
if (buffer_entry + len > buffer_end) {
pr_warn("Invalid length of WMI event\n");
break;
}
pr_debug("Process buffer (%*ph)\n", len*2, buffer_entry);
switch (buffer_entry[1]) {
case 0x00:
for (i = 2; i < len; ++i) {
switch (buffer_entry[i]) {
case 0xe043:
/* NIC Link is Up */
pr_debug("NIC Link is Up\n");
break;
case 0xe044:
/* NIC Link is Down */
pr_debug("NIC Link is Down\n");
break;
case 0xe045:
/* Unknown event but defined in DSDT */
default:
/* Unknown event */
pr_info("Unknown WMI event type 0x00: "
"0x%x\n", (int)buffer_entry[i]);
break;
}
}
break;
case 0x10:
/* Keys pressed */
for (i = 2; i < len; ++i)
dell_wmi_process_key(buffer_entry[i]);
break;
case 0x11:
for (i = 2; i < len; ++i) {
switch (buffer_entry[i]) {
case 0xfff0:
/* Battery unplugged */
pr_debug("Battery unplugged\n");
break;
case 0xfff1:
/* Battery inserted */
pr_debug("Battery inserted\n");
break;
case 0x01e1:
case 0x02ea:
case 0x02eb:
case 0x02ec:
case 0x02f6:
/* Keyboard backlight level changed */
pr_debug("Keyboard backlight level "
"changed\n");
break;
default:
/* Unknown event */
pr_info("Unknown WMI event type 0x11: "
"0x%x\n", (int)buffer_entry[i]);
break;
}
}
break;
default:
/* Unknown event */
pr_info("Unknown WMI event type 0x%x\n",
(int)buffer_entry[1]);
break;
}
buffer_entry += len;
}
kfree(obj);
}
static const struct key_entry * __init dell_wmi_prepare_new_keymap(void)
{
int hotkey_num = (dell_bios_hotkey_table->header.length - 4) /
sizeof(struct dell_bios_keymap_entry);
struct key_entry *keymap;
int i;
keymap = kcalloc(hotkey_num + 1, sizeof(struct key_entry), GFP_KERNEL);
if (!keymap)
return NULL;
for (i = 0; i < hotkey_num; i++) {
const struct dell_bios_keymap_entry *bios_entry =
&dell_bios_hotkey_table->keymap[i];
u16 keycode = bios_entry->keycode < 256 ?
bios_to_linux_keycode[bios_entry->keycode] :
KEY_RESERVED;
if (keycode == KEY_KBDILLUMTOGGLE)
keymap[i].type = KE_IGNORE;
else
keymap[i].type = KE_KEY;
keymap[i].code = bios_entry->scancode;
keymap[i].keycode = keycode;
}
keymap[hotkey_num].type = KE_END;
return keymap;
}
static int __init dell_wmi_input_setup(void)
{
int err;
dell_wmi_input_dev = input_allocate_device();
if (!dell_wmi_input_dev)
return -ENOMEM;
dell_wmi_input_dev->name = "Dell WMI hotkeys";
dell_wmi_input_dev->phys = "wmi/input0";
dell_wmi_input_dev->id.bustype = BUS_HOST;
if (dell_new_hk_type) {
const struct key_entry *keymap = dell_wmi_prepare_new_keymap();
if (!keymap) {
err = -ENOMEM;
goto err_free_dev;
}
err = sparse_keymap_setup(dell_wmi_input_dev, keymap, NULL);
/*
* Sparse keymap library makes a copy of keymap so we
* don't need the original one that was allocated.
*/
kfree(keymap);
} else {
err = sparse_keymap_setup(dell_wmi_input_dev,
dell_wmi_legacy_keymap, NULL);
}
if (err)
goto err_free_dev;
err = input_register_device(dell_wmi_input_dev);
if (err)
goto err_free_keymap;
return 0;
err_free_keymap:
sparse_keymap_free(dell_wmi_input_dev);
err_free_dev:
input_free_device(dell_wmi_input_dev);
return err;
}
static void dell_wmi_input_destroy(void)
{
sparse_keymap_free(dell_wmi_input_dev);
input_unregister_device(dell_wmi_input_dev);
}
static void __init find_hk_type(const struct dmi_header *dm, void *dummy)
{
if (dm->type == 0xb2 && dm->length > 6) {
dell_new_hk_type = true;
dell_bios_hotkey_table =
container_of(dm, struct dell_bios_hotkey_table, header);
}
}
static int __init dell_wmi_init(void)
{
int err;
acpi_status status;
if (!wmi_has_guid(DELL_EVENT_GUID)) {
pr_warn("No known WMI GUID found\n");
return -ENODEV;
}
dmi_walk(find_hk_type, NULL);
acpi_video = acpi_video_get_backlight_type() != acpi_backlight_vendor;
err = dell_wmi_input_setup();
if (err)
return err;
status = wmi_install_notify_handler(DELL_EVENT_GUID,
dell_wmi_notify, NULL);
if (ACPI_FAILURE(status)) {
dell_wmi_input_destroy();
pr_err("Unable to register notify handler - %d\n", status);
return -ENODEV;
}
return 0;
}
module_init(dell_wmi_init);
static void __exit dell_wmi_exit(void)
{
wmi_remove_notify_handler(DELL_EVENT_GUID);
dell_wmi_input_destroy();
}
module_exit(dell_wmi_exit);
| gpl-2.0 |
sdadier/gb_kernel_2.6.32.9-mtd | Kernel/drivers/media/radio/radio-tea5764.c | 540 | 16535 | /*
* driver/media/radio/radio-tea5764.c
*
* Driver for TEA5764 radio chip for linux 2.6.
* This driver is for TEA5764 chip from NXP, used in EZX phones from Motorola.
* The I2C protocol is used for communicate with chip.
*
* Based in radio-tea5761.c Copyright (C) 2005 Nokia Corporation
*
* Copyright (c) 2008 Fabio Belavenuto <belavenuto@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* History:
* 2008-12-06 Fabio Belavenuto <belavenuto@gmail.com>
* initial code
*
* TODO:
* add platform_data support for IRQs platform dependencies
* add RDS support
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h> /* Initdata */
#include <linux/videodev2.h> /* kernel radio structs */
#include <linux/i2c.h> /* I2C */
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <linux/version.h> /* for KERNEL_VERSION MACRO */
#define DRIVER_VERSION "v0.01"
#define RADIO_VERSION KERNEL_VERSION(0, 0, 1)
#define DRIVER_AUTHOR "Fabio Belavenuto <belavenuto@gmail.com>"
#define DRIVER_DESC "A driver for the TEA5764 radio chip for EZX Phones."
#define PINFO(format, ...)\
printk(KERN_INFO KBUILD_MODNAME ": "\
DRIVER_VERSION ": " format "\n", ## __VA_ARGS__)
#define PWARN(format, ...)\
printk(KERN_WARNING KBUILD_MODNAME ": "\
DRIVER_VERSION ": " format "\n", ## __VA_ARGS__)
# define PDEBUG(format, ...)\
printk(KERN_DEBUG KBUILD_MODNAME ": "\
DRIVER_VERSION ": " format "\n", ## __VA_ARGS__)
/* Frequency limits in MHz -- these are European values. For Japanese
devices, that would be 76000 and 91000. */
#define FREQ_MIN 87500
#define FREQ_MAX 108000
#define FREQ_MUL 16
/* TEA5764 registers */
#define TEA5764_MANID 0x002b
#define TEA5764_CHIPID 0x5764
#define TEA5764_INTREG_BLMSK 0x0001
#define TEA5764_INTREG_FRRMSK 0x0002
#define TEA5764_INTREG_LEVMSK 0x0008
#define TEA5764_INTREG_IFMSK 0x0010
#define TEA5764_INTREG_BLMFLAG 0x0100
#define TEA5764_INTREG_FRRFLAG 0x0200
#define TEA5764_INTREG_LEVFLAG 0x0800
#define TEA5764_INTREG_IFFLAG 0x1000
#define TEA5764_FRQSET_SUD 0x8000
#define TEA5764_FRQSET_SM 0x4000
#define TEA5764_TNCTRL_PUPD1 0x8000
#define TEA5764_TNCTRL_PUPD0 0x4000
#define TEA5764_TNCTRL_BLIM 0x2000
#define TEA5764_TNCTRL_SWPM 0x1000
#define TEA5764_TNCTRL_IFCTC 0x0800
#define TEA5764_TNCTRL_AFM 0x0400
#define TEA5764_TNCTRL_SMUTE 0x0200
#define TEA5764_TNCTRL_SNC 0x0100
#define TEA5764_TNCTRL_MU 0x0080
#define TEA5764_TNCTRL_SSL1 0x0040
#define TEA5764_TNCTRL_SSL0 0x0020
#define TEA5764_TNCTRL_HLSI 0x0010
#define TEA5764_TNCTRL_MST 0x0008
#define TEA5764_TNCTRL_SWP 0x0004
#define TEA5764_TNCTRL_DTC 0x0002
#define TEA5764_TNCTRL_AHLSI 0x0001
#define TEA5764_TUNCHK_LEVEL(x) (((x) & 0x00F0) >> 4)
#define TEA5764_TUNCHK_IFCNT(x) (((x) & 0xFE00) >> 9)
#define TEA5764_TUNCHK_TUNTO 0x0100
#define TEA5764_TUNCHK_LD 0x0008
#define TEA5764_TUNCHK_STEREO 0x0004
#define TEA5764_TESTREG_TRIGFR 0x0800
struct tea5764_regs {
u16 intreg; /* INTFLAG & INTMSK */
u16 frqset; /* FRQSETMSB & FRQSETLSB */
u16 tnctrl; /* TNCTRL1 & TNCTRL2 */
u16 frqchk; /* FRQCHKMSB & FRQCHKLSB */
u16 tunchk; /* IFCHK & LEVCHK */
u16 testreg; /* TESTBITS & TESTMODE */
u16 rdsstat; /* RDSSTAT1 & RDSSTAT2 */
u16 rdslb; /* RDSLBMSB & RDSLBLSB */
u16 rdspb; /* RDSPBMSB & RDSPBLSB */
u16 rdsbc; /* RDSBBC & RDSGBC */
u16 rdsctrl; /* RDSCTRL1 & RDSCTRL2 */
u16 rdsbbl; /* PAUSEDET & RDSBBL */
u16 manid; /* MANID1 & MANID2 */
u16 chipid; /* CHIPID1 & CHIPID2 */
} __attribute__ ((packed));
struct tea5764_write_regs {
u8 intreg; /* INTMSK */
u16 frqset; /* FRQSETMSB & FRQSETLSB */
u16 tnctrl; /* TNCTRL1 & TNCTRL2 */
u16 testreg; /* TESTBITS & TESTMODE */
u16 rdsctrl; /* RDSCTRL1 & RDSCTRL2 */
u16 rdsbbl; /* PAUSEDET & RDSBBL */
} __attribute__ ((packed));
#ifndef RADIO_TEA5764_XTAL
#define RADIO_TEA5764_XTAL 1
#endif
static int radio_nr = -1;
static int use_xtal = RADIO_TEA5764_XTAL;
struct tea5764_device {
struct i2c_client *i2c_client;
struct video_device *videodev;
struct tea5764_regs regs;
struct mutex mutex;
int users;
};
/* I2C code related */
int tea5764_i2c_read(struct tea5764_device *radio)
{
int i;
u16 *p = (u16 *) &radio->regs;
struct i2c_msg msgs[1] = {
{ radio->i2c_client->addr, I2C_M_RD, sizeof(radio->regs),
(void *)&radio->regs },
};
if (i2c_transfer(radio->i2c_client->adapter, msgs, 1) != 1)
return -EIO;
for (i = 0; i < sizeof(struct tea5764_regs) / sizeof(u16); i++)
p[i] = __be16_to_cpu(p[i]);
return 0;
}
int tea5764_i2c_write(struct tea5764_device *radio)
{
struct tea5764_write_regs wr;
struct tea5764_regs *r = &radio->regs;
struct i2c_msg msgs[1] = {
{ radio->i2c_client->addr, 0, sizeof(wr), (void *) &wr },
};
wr.intreg = r->intreg & 0xff;
wr.frqset = __cpu_to_be16(r->frqset);
wr.tnctrl = __cpu_to_be16(r->tnctrl);
wr.testreg = __cpu_to_be16(r->testreg);
wr.rdsctrl = __cpu_to_be16(r->rdsctrl);
wr.rdsbbl = __cpu_to_be16(r->rdsbbl);
if (i2c_transfer(radio->i2c_client->adapter, msgs, 1) != 1)
return -EIO;
return 0;
}
/* V4L2 code related */
static struct v4l2_queryctrl radio_qctrl[] = {
{
.id = V4L2_CID_AUDIO_MUTE,
.name = "Mute",
.minimum = 0,
.maximum = 1,
.default_value = 1,
.type = V4L2_CTRL_TYPE_BOOLEAN,
}
};
static void tea5764_power_up(struct tea5764_device *radio)
{
struct tea5764_regs *r = &radio->regs;
if (!(r->tnctrl & TEA5764_TNCTRL_PUPD0)) {
r->tnctrl &= ~(TEA5764_TNCTRL_AFM | TEA5764_TNCTRL_MU |
TEA5764_TNCTRL_HLSI);
if (!use_xtal)
r->testreg |= TEA5764_TESTREG_TRIGFR;
else
r->testreg &= ~TEA5764_TESTREG_TRIGFR;
r->tnctrl |= TEA5764_TNCTRL_PUPD0;
tea5764_i2c_write(radio);
}
}
static void tea5764_power_down(struct tea5764_device *radio)
{
struct tea5764_regs *r = &radio->regs;
if (r->tnctrl & TEA5764_TNCTRL_PUPD0) {
r->tnctrl &= ~TEA5764_TNCTRL_PUPD0;
tea5764_i2c_write(radio);
}
}
static void tea5764_set_freq(struct tea5764_device *radio, int freq)
{
struct tea5764_regs *r = &radio->regs;
/* formula: (freq [+ or -] 225000) / 8192 */
if (r->tnctrl & TEA5764_TNCTRL_HLSI)
r->frqset = (freq + 225000) / 8192;
else
r->frqset = (freq - 225000) / 8192;
}
static int tea5764_get_freq(struct tea5764_device *radio)
{
struct tea5764_regs *r = &radio->regs;
if (r->tnctrl & TEA5764_TNCTRL_HLSI)
return (r->frqchk * 8192) - 225000;
else
return (r->frqchk * 8192) + 225000;
}
/* tune an frequency, freq is defined by v4l's TUNER_LOW, i.e. 1/16th kHz */
static void tea5764_tune(struct tea5764_device *radio, int freq)
{
tea5764_set_freq(radio, freq);
if (tea5764_i2c_write(radio))
PWARN("Could not set frequency!");
}
static void tea5764_set_audout_mode(struct tea5764_device *radio, int audmode)
{
struct tea5764_regs *r = &radio->regs;
int tnctrl = r->tnctrl;
if (audmode == V4L2_TUNER_MODE_MONO)
r->tnctrl |= TEA5764_TNCTRL_MST;
else
r->tnctrl &= ~TEA5764_TNCTRL_MST;
if (tnctrl != r->tnctrl)
tea5764_i2c_write(radio);
}
static int tea5764_get_audout_mode(struct tea5764_device *radio)
{
struct tea5764_regs *r = &radio->regs;
if (r->tnctrl & TEA5764_TNCTRL_MST)
return V4L2_TUNER_MODE_MONO;
else
return V4L2_TUNER_MODE_STEREO;
}
static void tea5764_mute(struct tea5764_device *radio, int on)
{
struct tea5764_regs *r = &radio->regs;
int tnctrl = r->tnctrl;
if (on)
r->tnctrl |= TEA5764_TNCTRL_MU;
else
r->tnctrl &= ~TEA5764_TNCTRL_MU;
if (tnctrl != r->tnctrl)
tea5764_i2c_write(radio);
}
static int tea5764_is_muted(struct tea5764_device *radio)
{
return radio->regs.tnctrl & TEA5764_TNCTRL_MU;
}
/* V4L2 vidioc */
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
struct tea5764_device *radio = video_drvdata(file);
struct video_device *dev = radio->videodev;
strlcpy(v->driver, dev->dev.driver->name, sizeof(v->driver));
strlcpy(v->card, dev->name, sizeof(v->card));
snprintf(v->bus_info, sizeof(v->bus_info),
"I2C:%s", dev_name(&dev->dev));
v->version = RADIO_VERSION;
v->capabilities = V4L2_CAP_TUNER | V4L2_CAP_RADIO;
return 0;
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct tea5764_device *radio = video_drvdata(file);
struct tea5764_regs *r = &radio->regs;
if (v->index > 0)
return -EINVAL;
memset(v, 0, sizeof(v));
strcpy(v->name, "FM");
v->type = V4L2_TUNER_RADIO;
tea5764_i2c_read(radio);
v->rangelow = FREQ_MIN * FREQ_MUL;
v->rangehigh = FREQ_MAX * FREQ_MUL;
v->capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_STEREO;
if (r->tunchk & TEA5764_TUNCHK_STEREO)
v->rxsubchans = V4L2_TUNER_SUB_STEREO;
else
v->rxsubchans = V4L2_TUNER_SUB_MONO;
v->audmode = tea5764_get_audout_mode(radio);
v->signal = TEA5764_TUNCHK_LEVEL(r->tunchk) * 0xffff / 0xf;
v->afc = TEA5764_TUNCHK_IFCNT(r->tunchk);
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct tea5764_device *radio = video_drvdata(file);
if (v->index > 0)
return -EINVAL;
tea5764_set_audout_mode(radio, v->audmode);
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct tea5764_device *radio = video_drvdata(file);
if (f->tuner != 0)
return -EINVAL;
if (f->frequency == 0) {
/* We special case this as a power down control. */
tea5764_power_down(radio);
}
if (f->frequency < (FREQ_MIN * FREQ_MUL))
return -EINVAL;
if (f->frequency > (FREQ_MAX * FREQ_MUL))
return -EINVAL;
tea5764_power_up(radio);
tea5764_tune(radio, (f->frequency * 125) / 2);
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct tea5764_device *radio = video_drvdata(file);
struct tea5764_regs *r = &radio->regs;
tea5764_i2c_read(radio);
memset(f, 0, sizeof(f));
f->type = V4L2_TUNER_RADIO;
if (r->tnctrl & TEA5764_TNCTRL_PUPD0)
f->frequency = (tea5764_get_freq(radio) * 2) / 125;
else
f->frequency = 0;
return 0;
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
int i;
for (i = 0; i < ARRAY_SIZE(radio_qctrl); i++) {
if (qc->id && qc->id == radio_qctrl[i].id) {
memcpy(qc, &(radio_qctrl[i]), sizeof(*qc));
return 0;
}
}
return -EINVAL;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct tea5764_device *radio = video_drvdata(file);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
tea5764_i2c_read(radio);
ctrl->value = tea5764_is_muted(radio) ? 1 : 0;
return 0;
}
return -EINVAL;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct tea5764_device *radio = video_drvdata(file);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
tea5764_mute(radio, ctrl->value);
return 0;
}
return -EINVAL;
}
static int vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int vidioc_s_input(struct file *filp, void *priv, unsigned int i)
{
if (i != 0)
return -EINVAL;
return 0;
}
static int vidioc_g_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
if (a->index > 1)
return -EINVAL;
strcpy(a->name, "Radio");
a->capability = V4L2_AUDCAP_STEREO;
return 0;
}
static int vidioc_s_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
if (a->index != 0)
return -EINVAL;
return 0;
}
static int tea5764_open(struct file *file)
{
/* Currently we support only one device */
int minor = video_devdata(file)->minor;
struct tea5764_device *radio = video_drvdata(file);
if (radio->videodev->minor != minor)
return -ENODEV;
mutex_lock(&radio->mutex);
/* Only exclusive access */
if (radio->users) {
mutex_unlock(&radio->mutex);
return -EBUSY;
}
radio->users++;
mutex_unlock(&radio->mutex);
file->private_data = radio;
return 0;
}
static int tea5764_close(struct file *file)
{
struct tea5764_device *radio = video_drvdata(file);
if (!radio)
return -ENODEV;
mutex_lock(&radio->mutex);
radio->users--;
mutex_unlock(&radio->mutex);
return 0;
}
/* File system interface */
static const struct v4l2_file_operations tea5764_fops = {
.owner = THIS_MODULE,
.open = tea5764_open,
.release = tea5764_close,
.ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops tea5764_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
};
/* V4L2 interface */
static struct video_device tea5764_radio_template = {
.name = "TEA5764 FM-Radio",
.fops = &tea5764_fops,
.ioctl_ops = &tea5764_ioctl_ops,
.release = video_device_release,
};
/* I2C probe: check if the device exists and register with v4l if it is */
static int __devinit tea5764_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tea5764_device *radio;
struct tea5764_regs *r;
int ret;
PDEBUG("probe");
radio = kmalloc(sizeof(struct tea5764_device), GFP_KERNEL);
if (!radio)
return -ENOMEM;
mutex_init(&radio->mutex);
radio->i2c_client = client;
ret = tea5764_i2c_read(radio);
if (ret)
goto errfr;
r = &radio->regs;
PDEBUG("chipid = %04X, manid = %04X", r->chipid, r->manid);
if (r->chipid != TEA5764_CHIPID ||
(r->manid & 0x0fff) != TEA5764_MANID) {
PWARN("This chip is not a TEA5764!");
ret = -EINVAL;
goto errfr;
}
radio->videodev = video_device_alloc();
if (!(radio->videodev)) {
ret = -ENOMEM;
goto errfr;
}
memcpy(radio->videodev, &tea5764_radio_template,
sizeof(tea5764_radio_template));
i2c_set_clientdata(client, radio);
video_set_drvdata(radio->videodev, radio);
ret = video_register_device(radio->videodev, VFL_TYPE_RADIO, radio_nr);
if (ret < 0) {
PWARN("Could not register video device!");
goto errrel;
}
/* initialize and power off the chip */
tea5764_i2c_read(radio);
tea5764_set_audout_mode(radio, V4L2_TUNER_MODE_STEREO);
tea5764_mute(radio, 1);
tea5764_power_down(radio);
PINFO("registered.");
return 0;
errrel:
video_device_release(radio->videodev);
errfr:
kfree(radio);
return ret;
}
static int __devexit tea5764_i2c_remove(struct i2c_client *client)
{
struct tea5764_device *radio = i2c_get_clientdata(client);
PDEBUG("remove");
if (radio) {
tea5764_power_down(radio);
video_unregister_device(radio->videodev);
kfree(radio);
}
return 0;
}
/* I2C subsystem interface */
static const struct i2c_device_id tea5764_id[] = {
{ "radio-tea5764", 0 },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(i2c, tea5764_id);
static struct i2c_driver tea5764_i2c_driver = {
.driver = {
.name = "radio-tea5764",
.owner = THIS_MODULE,
},
.probe = tea5764_i2c_probe,
.remove = __devexit_p(tea5764_i2c_remove),
.id_table = tea5764_id,
};
/* init the driver */
static int __init tea5764_init(void)
{
int ret = i2c_add_driver(&tea5764_i2c_driver);
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ": "
DRIVER_DESC "\n");
return ret;
}
/* cleanup the driver */
static void __exit tea5764_exit(void)
{
i2c_del_driver(&tea5764_i2c_driver);
}
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(use_xtal, int, 1);
MODULE_PARM_DESC(use_xtal, "Chip have a xtal connected in board");
module_param(radio_nr, int, 0);
MODULE_PARM_DESC(radio_nr, "video4linux device number to use");
module_init(tea5764_init);
module_exit(tea5764_exit);
| gpl-2.0 |
damageless/linux-kernel-ican-tab | drivers/acpi/acpica/evgpe.c | 540 | 20765 | /******************************************************************************
*
* Module Name: evgpe - General Purpose Event handling and dispatch
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2008, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acevents.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_EVENTS
ACPI_MODULE_NAME("evgpe")
/* Local prototypes */
static void ACPI_SYSTEM_XFACE acpi_ev_asynch_execute_gpe_method(void *context);
/*******************************************************************************
*
* FUNCTION: acpi_ev_set_gpe_type
*
* PARAMETERS: gpe_event_info - GPE to set
* Type - New type
*
* RETURN: Status
*
* DESCRIPTION: Sets the new type for the GPE (wake, run, or wake/run)
*
******************************************************************************/
acpi_status
acpi_ev_set_gpe_type(struct acpi_gpe_event_info *gpe_event_info, u8 type)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ev_set_gpe_type);
/* Validate type and update register enable masks */
switch (type) {
case ACPI_GPE_TYPE_WAKE:
case ACPI_GPE_TYPE_RUNTIME:
case ACPI_GPE_TYPE_WAKE_RUN:
break;
default:
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Disable the GPE if currently enabled */
status = acpi_ev_disable_gpe(gpe_event_info);
/* Clear the type bits and insert the new Type */
gpe_event_info->flags &= ~ACPI_GPE_TYPE_MASK;
gpe_event_info->flags |= type;
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_update_gpe_enable_masks
*
* PARAMETERS: gpe_event_info - GPE to update
* Type - What to do: ACPI_GPE_DISABLE or
* ACPI_GPE_ENABLE
*
* RETURN: Status
*
* DESCRIPTION: Updates GPE register enable masks based on the GPE type
*
******************************************************************************/
acpi_status
acpi_ev_update_gpe_enable_masks(struct acpi_gpe_event_info *gpe_event_info,
u8 type)
{
struct acpi_gpe_register_info *gpe_register_info;
u8 register_bit;
ACPI_FUNCTION_TRACE(ev_update_gpe_enable_masks);
gpe_register_info = gpe_event_info->register_info;
if (!gpe_register_info) {
return_ACPI_STATUS(AE_NOT_EXIST);
}
register_bit = (u8)
(1 <<
(gpe_event_info->gpe_number - gpe_register_info->base_gpe_number));
/* 1) Disable case. Simply clear all enable bits */
if (type == ACPI_GPE_DISABLE) {
ACPI_CLEAR_BIT(gpe_register_info->enable_for_wake,
register_bit);
ACPI_CLEAR_BIT(gpe_register_info->enable_for_run, register_bit);
return_ACPI_STATUS(AE_OK);
}
/* 2) Enable case. Set/Clear the appropriate enable bits */
switch (gpe_event_info->flags & ACPI_GPE_TYPE_MASK) {
case ACPI_GPE_TYPE_WAKE:
ACPI_SET_BIT(gpe_register_info->enable_for_wake, register_bit);
ACPI_CLEAR_BIT(gpe_register_info->enable_for_run, register_bit);
break;
case ACPI_GPE_TYPE_RUNTIME:
ACPI_CLEAR_BIT(gpe_register_info->enable_for_wake,
register_bit);
ACPI_SET_BIT(gpe_register_info->enable_for_run, register_bit);
break;
case ACPI_GPE_TYPE_WAKE_RUN:
ACPI_SET_BIT(gpe_register_info->enable_for_wake, register_bit);
ACPI_SET_BIT(gpe_register_info->enable_for_run, register_bit);
break;
default:
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_enable_gpe
*
* PARAMETERS: gpe_event_info - GPE to enable
* write_to_hardware - Enable now, or just mark data structs
* (WAKE GPEs should be deferred)
*
* RETURN: Status
*
* DESCRIPTION: Enable a GPE based on the GPE type
*
******************************************************************************/
acpi_status
acpi_ev_enable_gpe(struct acpi_gpe_event_info *gpe_event_info,
u8 write_to_hardware)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ev_enable_gpe);
/* Make sure HW enable masks are updated */
status =
acpi_ev_update_gpe_enable_masks(gpe_event_info, ACPI_GPE_ENABLE);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Mark wake-enabled or HW enable, or both */
switch (gpe_event_info->flags & ACPI_GPE_TYPE_MASK) {
case ACPI_GPE_TYPE_WAKE:
ACPI_SET_BIT(gpe_event_info->flags, ACPI_GPE_WAKE_ENABLED);
break;
case ACPI_GPE_TYPE_WAKE_RUN:
ACPI_SET_BIT(gpe_event_info->flags, ACPI_GPE_WAKE_ENABLED);
/*lint -fallthrough */
case ACPI_GPE_TYPE_RUNTIME:
ACPI_SET_BIT(gpe_event_info->flags, ACPI_GPE_RUN_ENABLED);
if (write_to_hardware) {
/* Clear the GPE (of stale events), then enable it */
status = acpi_hw_clear_gpe(gpe_event_info);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Enable the requested runtime GPE */
status = acpi_hw_write_gpe_enable_reg(gpe_event_info);
}
break;
default:
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_disable_gpe
*
* PARAMETERS: gpe_event_info - GPE to disable
*
* RETURN: Status
*
* DESCRIPTION: Disable a GPE based on the GPE type
*
******************************************************************************/
acpi_status acpi_ev_disable_gpe(struct acpi_gpe_event_info *gpe_event_info)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ev_disable_gpe);
/* Make sure HW enable masks are updated */
status =
acpi_ev_update_gpe_enable_masks(gpe_event_info, ACPI_GPE_DISABLE);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Clear the appropriate enabled flags for this GPE */
switch (gpe_event_info->flags & ACPI_GPE_TYPE_MASK) {
case ACPI_GPE_TYPE_WAKE:
ACPI_CLEAR_BIT(gpe_event_info->flags, ACPI_GPE_WAKE_ENABLED);
break;
case ACPI_GPE_TYPE_WAKE_RUN:
ACPI_CLEAR_BIT(gpe_event_info->flags, ACPI_GPE_WAKE_ENABLED);
/* fallthrough */
case ACPI_GPE_TYPE_RUNTIME:
/* Disable the requested runtime GPE */
ACPI_CLEAR_BIT(gpe_event_info->flags, ACPI_GPE_RUN_ENABLED);
break;
default:
break;
}
/*
* Even if we don't know the GPE type, make sure that we always
* disable it. low_disable_gpe will just clear the enable bit for this
* GPE and write it. It will not write out the current GPE enable mask,
* since this may inadvertently enable GPEs too early, if a rogue GPE has
* come in during ACPICA initialization - possibly as a result of AML or
* other code that has enabled the GPE.
*/
status = acpi_hw_low_disable_gpe(gpe_event_info);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_get_gpe_event_info
*
* PARAMETERS: gpe_device - Device node. NULL for GPE0/GPE1
* gpe_number - Raw GPE number
*
* RETURN: A GPE event_info struct. NULL if not a valid GPE
*
* DESCRIPTION: Returns the event_info struct associated with this GPE.
* Validates the gpe_block and the gpe_number
*
* Should be called only when the GPE lists are semaphore locked
* and not subject to change.
*
******************************************************************************/
struct acpi_gpe_event_info *acpi_ev_get_gpe_event_info(acpi_handle gpe_device,
u32 gpe_number)
{
union acpi_operand_object *obj_desc;
struct acpi_gpe_block_info *gpe_block;
u32 i;
ACPI_FUNCTION_ENTRY();
/* A NULL gpe_block means use the FADT-defined GPE block(s) */
if (!gpe_device) {
/* Examine GPE Block 0 and 1 (These blocks are permanent) */
for (i = 0; i < ACPI_MAX_GPE_BLOCKS; i++) {
gpe_block = acpi_gbl_gpe_fadt_blocks[i];
if (gpe_block) {
if ((gpe_number >= gpe_block->block_base_number)
&& (gpe_number <
gpe_block->block_base_number +
(gpe_block->register_count * 8))) {
return (&gpe_block->
event_info[gpe_number -
gpe_block->
block_base_number]);
}
}
}
/* The gpe_number was not in the range of either FADT GPE block */
return (NULL);
}
/* A Non-NULL gpe_device means this is a GPE Block Device */
obj_desc = acpi_ns_get_attached_object((struct acpi_namespace_node *)
gpe_device);
if (!obj_desc || !obj_desc->device.gpe_block) {
return (NULL);
}
gpe_block = obj_desc->device.gpe_block;
if ((gpe_number >= gpe_block->block_base_number) &&
(gpe_number <
gpe_block->block_base_number + (gpe_block->register_count * 8))) {
return (&gpe_block->
event_info[gpe_number - gpe_block->block_base_number]);
}
return (NULL);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_gpe_detect
*
* PARAMETERS: gpe_xrupt_list - Interrupt block for this interrupt.
* Can have multiple GPE blocks attached.
*
* RETURN: INTERRUPT_HANDLED or INTERRUPT_NOT_HANDLED
*
* DESCRIPTION: Detect if any GP events have occurred. This function is
* executed at interrupt level.
*
******************************************************************************/
u32 acpi_ev_gpe_detect(struct acpi_gpe_xrupt_info * gpe_xrupt_list)
{
acpi_status status;
struct acpi_gpe_block_info *gpe_block;
struct acpi_gpe_register_info *gpe_register_info;
u32 int_status = ACPI_INTERRUPT_NOT_HANDLED;
u8 enabled_status_byte;
u32 status_reg;
u32 enable_reg;
acpi_cpu_flags flags;
u32 i;
u32 j;
ACPI_FUNCTION_NAME(ev_gpe_detect);
/* Check for the case where there are no GPEs */
if (!gpe_xrupt_list) {
return (int_status);
}
/*
* We need to obtain the GPE lock for both the data structs and registers
* Note: Not necessary to obtain the hardware lock, since the GPE
* registers are owned by the gpe_lock.
*/
flags = acpi_os_acquire_lock(acpi_gbl_gpe_lock);
/* Examine all GPE blocks attached to this interrupt level */
gpe_block = gpe_xrupt_list->gpe_block_list_head;
while (gpe_block) {
/*
* Read all of the 8-bit GPE status and enable registers in this GPE
* block, saving all of them. Find all currently active GP events.
*/
for (i = 0; i < gpe_block->register_count; i++) {
/* Get the next status/enable pair */
gpe_register_info = &gpe_block->register_info[i];
/* Read the Status Register */
status =
acpi_hw_read(&status_reg,
&gpe_register_info->status_address);
if (ACPI_FAILURE(status)) {
goto unlock_and_exit;
}
/* Read the Enable Register */
status =
acpi_hw_read(&enable_reg,
&gpe_register_info->enable_address);
if (ACPI_FAILURE(status)) {
goto unlock_and_exit;
}
ACPI_DEBUG_PRINT((ACPI_DB_INTERRUPTS,
"Read GPE Register at GPE%X: Status=%02X, Enable=%02X\n",
gpe_register_info->base_gpe_number,
status_reg, enable_reg));
/* Check if there is anything active at all in this register */
enabled_status_byte = (u8) (status_reg & enable_reg);
if (!enabled_status_byte) {
/* No active GPEs in this register, move on */
continue;
}
/* Now look at the individual GPEs in this byte register */
for (j = 0; j < ACPI_GPE_REGISTER_WIDTH; j++) {
/* Examine one GPE bit */
if (enabled_status_byte & (1 << j)) {
/*
* Found an active GPE. Dispatch the event to a handler
* or method.
*/
int_status |=
acpi_ev_gpe_dispatch(&gpe_block->
event_info[((acpi_size) i * ACPI_GPE_REGISTER_WIDTH) + j], j + gpe_register_info->base_gpe_number);
}
}
}
gpe_block = gpe_block->next;
}
unlock_and_exit:
acpi_os_release_lock(acpi_gbl_gpe_lock, flags);
return (int_status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_asynch_execute_gpe_method
*
* PARAMETERS: Context (gpe_event_info) - Info for this GPE
*
* RETURN: None
*
* DESCRIPTION: Perform the actual execution of a GPE control method. This
* function is called from an invocation of acpi_os_execute and
* therefore does NOT execute at interrupt level - so that
* the control method itself is not executed in the context of
* an interrupt handler.
*
******************************************************************************/
static void acpi_ev_asynch_enable_gpe(void *context);
static void ACPI_SYSTEM_XFACE acpi_ev_asynch_execute_gpe_method(void *context)
{
struct acpi_gpe_event_info *gpe_event_info = (void *)context;
acpi_status status;
struct acpi_gpe_event_info local_gpe_event_info;
struct acpi_evaluate_info *info;
ACPI_FUNCTION_TRACE(ev_asynch_execute_gpe_method);
status = acpi_ut_acquire_mutex(ACPI_MTX_EVENTS);
if (ACPI_FAILURE(status)) {
return_VOID;
}
/* Must revalidate the gpe_number/gpe_block */
if (!acpi_ev_valid_gpe_event(gpe_event_info)) {
status = acpi_ut_release_mutex(ACPI_MTX_EVENTS);
return_VOID;
}
/* Set the GPE flags for return to enabled state */
(void)acpi_ev_enable_gpe(gpe_event_info, FALSE);
/*
* Take a snapshot of the GPE info for this level - we copy the info to
* prevent a race condition with remove_handler/remove_block.
*/
ACPI_MEMCPY(&local_gpe_event_info, gpe_event_info,
sizeof(struct acpi_gpe_event_info));
status = acpi_ut_release_mutex(ACPI_MTX_EVENTS);
if (ACPI_FAILURE(status)) {
return_VOID;
}
/*
* Must check for control method type dispatch one more time to avoid a
* race with ev_gpe_install_handler
*/
if ((local_gpe_event_info.flags & ACPI_GPE_DISPATCH_MASK) ==
ACPI_GPE_DISPATCH_METHOD) {
/* Allocate the evaluation information block */
info = ACPI_ALLOCATE_ZEROED(sizeof(struct acpi_evaluate_info));
if (!info) {
status = AE_NO_MEMORY;
} else {
/*
* Invoke the GPE Method (_Lxx, _Exx) i.e., evaluate the _Lxx/_Exx
* control method that corresponds to this GPE
*/
info->prefix_node =
local_gpe_event_info.dispatch.method_node;
info->flags = ACPI_IGNORE_RETURN_VALUE;
status = acpi_ns_evaluate(info);
ACPI_FREE(info);
}
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"while evaluating GPE method [%4.4s]",
acpi_ut_get_node_name
(local_gpe_event_info.dispatch.
method_node)));
}
}
/* Defer enabling of GPE until all notify handlers are done */
acpi_os_execute(OSL_NOTIFY_HANDLER, acpi_ev_asynch_enable_gpe,
gpe_event_info);
return_VOID;
}
static void acpi_ev_asynch_enable_gpe(void *context)
{
struct acpi_gpe_event_info *gpe_event_info = context;
acpi_status status;
if ((gpe_event_info->flags & ACPI_GPE_XRUPT_TYPE_MASK) ==
ACPI_GPE_LEVEL_TRIGGERED) {
/*
* GPE is level-triggered, we clear the GPE status bit after handling
* the event.
*/
status = acpi_hw_clear_gpe(gpe_event_info);
if (ACPI_FAILURE(status)) {
return_VOID;
}
}
/* Enable this GPE */
(void)acpi_hw_write_gpe_enable_reg(gpe_event_info);
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_gpe_dispatch
*
* PARAMETERS: gpe_event_info - Info for this GPE
* gpe_number - Number relative to the parent GPE block
*
* RETURN: INTERRUPT_HANDLED or INTERRUPT_NOT_HANDLED
*
* DESCRIPTION: Dispatch a General Purpose Event to either a function (e.g. EC)
* or method (e.g. _Lxx/_Exx) handler.
*
* This function executes at interrupt level.
*
******************************************************************************/
u32
acpi_ev_gpe_dispatch(struct acpi_gpe_event_info *gpe_event_info, u32 gpe_number)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ev_gpe_dispatch);
acpi_os_gpe_count(gpe_number);
/*
* If edge-triggered, clear the GPE status bit now. Note that
* level-triggered events are cleared after the GPE is serviced.
*/
if ((gpe_event_info->flags & ACPI_GPE_XRUPT_TYPE_MASK) ==
ACPI_GPE_EDGE_TRIGGERED) {
status = acpi_hw_clear_gpe(gpe_event_info);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to clear GPE[%2X]",
gpe_number));
return_UINT32(ACPI_INTERRUPT_NOT_HANDLED);
}
}
/*
* Dispatch the GPE to either an installed handler, or the control method
* associated with this GPE (_Lxx or _Exx). If a handler exists, we invoke
* it and do not attempt to run the method. If there is neither a handler
* nor a method, we disable this GPE to prevent further such pointless
* events from firing.
*/
switch (gpe_event_info->flags & ACPI_GPE_DISPATCH_MASK) {
case ACPI_GPE_DISPATCH_HANDLER:
/*
* Invoke the installed handler (at interrupt level)
* Ignore return status for now.
* TBD: leave GPE disabled on error?
*/
(void)gpe_event_info->dispatch.handler->address(gpe_event_info->
dispatch.
handler->
context);
/* It is now safe to clear level-triggered events. */
if ((gpe_event_info->flags & ACPI_GPE_XRUPT_TYPE_MASK) ==
ACPI_GPE_LEVEL_TRIGGERED) {
status = acpi_hw_clear_gpe(gpe_event_info);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to clear GPE[%2X]",
gpe_number));
return_UINT32(ACPI_INTERRUPT_NOT_HANDLED);
}
}
break;
case ACPI_GPE_DISPATCH_METHOD:
/*
* Disable the GPE, so it doesn't keep firing before the method has a
* chance to run (it runs asynchronously with interrupts enabled).
*/
status = acpi_ev_disable_gpe(gpe_event_info);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to disable GPE[%2X]",
gpe_number));
return_UINT32(ACPI_INTERRUPT_NOT_HANDLED);
}
/*
* Execute the method associated with the GPE
* NOTE: Level-triggered GPEs are cleared after the method completes.
*/
status = acpi_os_execute(OSL_GPE_HANDLER,
acpi_ev_asynch_execute_gpe_method,
gpe_event_info);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to queue handler for GPE[%2X] - event disabled",
gpe_number));
}
break;
default:
/* No handler or method to run! */
ACPI_ERROR((AE_INFO,
"No handler or method for GPE[%2X], disabling event",
gpe_number));
/*
* Disable the GPE. The GPE will remain disabled until the ACPICA
* Core Subsystem is restarted, or a handler is installed.
*/
status = acpi_ev_disable_gpe(gpe_event_info);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to disable GPE[%2X]",
gpe_number));
return_UINT32(ACPI_INTERRUPT_NOT_HANDLED);
}
break;
}
return_UINT32(ACPI_INTERRUPT_HANDLED);
}
| gpl-2.0 |
robacklin/ts4700 | fs/pnode.c | 796 | 9070 | /*
* linux/fs/pnode.c
*
* (C) Copyright IBM Corporation 2005.
* Released under GPL v2.
* Author : Ram Pai (linuxram@us.ibm.com)
*
*/
#include <linux/mnt_namespace.h>
#include <linux/mount.h>
#include <linux/fs.h>
#include "internal.h"
#include "pnode.h"
/* return the next shared peer mount of @p */
static inline struct vfsmount *next_peer(struct vfsmount *p)
{
return list_entry(p->mnt_share.next, struct vfsmount, mnt_share);
}
static inline struct vfsmount *first_slave(struct vfsmount *p)
{
return list_entry(p->mnt_slave_list.next, struct vfsmount, mnt_slave);
}
static inline struct vfsmount *next_slave(struct vfsmount *p)
{
return list_entry(p->mnt_slave.next, struct vfsmount, mnt_slave);
}
/*
* Return true if path is reachable from root
*
* namespace_sem is held, and mnt is attached
*/
static bool is_path_reachable(struct vfsmount *mnt, struct dentry *dentry,
const struct path *root)
{
while (mnt != root->mnt && mnt->mnt_parent != mnt) {
dentry = mnt->mnt_mountpoint;
mnt = mnt->mnt_parent;
}
return mnt == root->mnt && is_subdir(dentry, root->dentry);
}
static struct vfsmount *get_peer_under_root(struct vfsmount *mnt,
struct mnt_namespace *ns,
const struct path *root)
{
struct vfsmount *m = mnt;
do {
/* Check the namespace first for optimization */
if (m->mnt_ns == ns && is_path_reachable(m, m->mnt_root, root))
return m;
m = next_peer(m);
} while (m != mnt);
return NULL;
}
/*
* Get ID of closest dominating peer group having a representative
* under the given root.
*
* Caller must hold namespace_sem
*/
int get_dominating_id(struct vfsmount *mnt, const struct path *root)
{
struct vfsmount *m;
for (m = mnt->mnt_master; m != NULL; m = m->mnt_master) {
struct vfsmount *d = get_peer_under_root(m, mnt->mnt_ns, root);
if (d)
return d->mnt_group_id;
}
return 0;
}
static int do_make_slave(struct vfsmount *mnt)
{
struct vfsmount *peer_mnt = mnt, *master = mnt->mnt_master;
struct vfsmount *slave_mnt;
/*
* slave 'mnt' to a peer mount that has the
* same root dentry. If none is available than
* slave it to anything that is available.
*/
while ((peer_mnt = next_peer(peer_mnt)) != mnt &&
peer_mnt->mnt_root != mnt->mnt_root) ;
if (peer_mnt == mnt) {
peer_mnt = next_peer(mnt);
if (peer_mnt == mnt)
peer_mnt = NULL;
}
if (IS_MNT_SHARED(mnt) && list_empty(&mnt->mnt_share))
mnt_release_group_id(mnt);
list_del_init(&mnt->mnt_share);
mnt->mnt_group_id = 0;
if (peer_mnt)
master = peer_mnt;
if (master) {
list_for_each_entry(slave_mnt, &mnt->mnt_slave_list, mnt_slave)
slave_mnt->mnt_master = master;
list_move(&mnt->mnt_slave, &master->mnt_slave_list);
list_splice(&mnt->mnt_slave_list, master->mnt_slave_list.prev);
INIT_LIST_HEAD(&mnt->mnt_slave_list);
} else {
struct list_head *p = &mnt->mnt_slave_list;
while (!list_empty(p)) {
slave_mnt = list_first_entry(p,
struct vfsmount, mnt_slave);
list_del_init(&slave_mnt->mnt_slave);
slave_mnt->mnt_master = NULL;
}
}
mnt->mnt_master = master;
CLEAR_MNT_SHARED(mnt);
return 0;
}
void change_mnt_propagation(struct vfsmount *mnt, int type)
{
if (type == MS_SHARED) {
set_mnt_shared(mnt);
return;
}
do_make_slave(mnt);
if (type != MS_SLAVE) {
list_del_init(&mnt->mnt_slave);
mnt->mnt_master = NULL;
if (type == MS_UNBINDABLE)
mnt->mnt_flags |= MNT_UNBINDABLE;
else
mnt->mnt_flags &= ~MNT_UNBINDABLE;
}
}
/*
* get the next mount in the propagation tree.
* @m: the mount seen last
* @origin: the original mount from where the tree walk initiated
*/
static struct vfsmount *propagation_next(struct vfsmount *m,
struct vfsmount *origin)
{
/* are there any slaves of this mount? */
if (!IS_MNT_NEW(m) && !list_empty(&m->mnt_slave_list))
return first_slave(m);
while (1) {
struct vfsmount *next;
struct vfsmount *master = m->mnt_master;
if (master == origin->mnt_master) {
next = next_peer(m);
return ((next == origin) ? NULL : next);
} else if (m->mnt_slave.next != &master->mnt_slave_list)
return next_slave(m);
/* back at master */
m = master;
}
}
/*
* return the source mount to be used for cloning
*
* @dest the current destination mount
* @last_dest the last seen destination mount
* @last_src the last seen source mount
* @type return CL_SLAVE if the new mount has to be
* cloned as a slave.
*/
static struct vfsmount *get_source(struct vfsmount *dest,
struct vfsmount *last_dest,
struct vfsmount *last_src,
int *type)
{
struct vfsmount *p_last_src = NULL;
struct vfsmount *p_last_dest = NULL;
*type = CL_PROPAGATION;
if (IS_MNT_SHARED(dest))
*type |= CL_MAKE_SHARED;
while (last_dest != dest->mnt_master) {
p_last_dest = last_dest;
p_last_src = last_src;
last_dest = last_dest->mnt_master;
last_src = last_src->mnt_master;
}
if (p_last_dest) {
do {
p_last_dest = next_peer(p_last_dest);
} while (IS_MNT_NEW(p_last_dest));
}
if (dest != p_last_dest) {
*type |= CL_SLAVE;
return last_src;
} else
return p_last_src;
}
/*
* mount 'source_mnt' under the destination 'dest_mnt' at
* dentry 'dest_dentry'. And propagate that mount to
* all the peer and slave mounts of 'dest_mnt'.
* Link all the new mounts into a propagation tree headed at
* source_mnt. Also link all the new mounts using ->mnt_list
* headed at source_mnt's ->mnt_list
*
* @dest_mnt: destination mount.
* @dest_dentry: destination dentry.
* @source_mnt: source mount.
* @tree_list : list of heads of trees to be attached.
*/
int propagate_mnt(struct vfsmount *dest_mnt, struct dentry *dest_dentry,
struct vfsmount *source_mnt, struct list_head *tree_list)
{
struct vfsmount *m, *child;
int ret = 0;
struct vfsmount *prev_dest_mnt = dest_mnt;
struct vfsmount *prev_src_mnt = source_mnt;
LIST_HEAD(tmp_list);
LIST_HEAD(umount_list);
for (m = propagation_next(dest_mnt, dest_mnt); m;
m = propagation_next(m, dest_mnt)) {
int type;
struct vfsmount *source;
if (IS_MNT_NEW(m))
continue;
source = get_source(m, prev_dest_mnt, prev_src_mnt, &type);
if (!(child = copy_tree(source, source->mnt_root, type))) {
ret = -ENOMEM;
list_splice(tree_list, tmp_list.prev);
goto out;
}
if (is_subdir(dest_dentry, m->mnt_root)) {
mnt_set_mountpoint(m, dest_dentry, child);
list_add_tail(&child->mnt_hash, tree_list);
} else {
/*
* This can happen if the parent mount was bind mounted
* on some subdirectory of a shared/slave mount.
*/
list_add_tail(&child->mnt_hash, &tmp_list);
}
prev_dest_mnt = m;
prev_src_mnt = child;
}
out:
spin_lock(&vfsmount_lock);
while (!list_empty(&tmp_list)) {
child = list_first_entry(&tmp_list, struct vfsmount, mnt_hash);
umount_tree(child, 0, &umount_list);
}
spin_unlock(&vfsmount_lock);
release_mounts(&umount_list);
return ret;
}
/*
* return true if the refcount is greater than count
*/
static inline int do_refcount_check(struct vfsmount *mnt, int count)
{
int mycount = atomic_read(&mnt->mnt_count) - mnt->mnt_ghosts;
return (mycount > count);
}
/*
* check if the mount 'mnt' can be unmounted successfully.
* @mnt: the mount to be checked for unmount
* NOTE: unmounting 'mnt' would naturally propagate to all
* other mounts its parent propagates to.
* Check if any of these mounts that **do not have submounts**
* have more references than 'refcnt'. If so return busy.
*/
int propagate_mount_busy(struct vfsmount *mnt, int refcnt)
{
struct vfsmount *m, *child;
struct vfsmount *parent = mnt->mnt_parent;
int ret = 0;
if (mnt == parent)
return do_refcount_check(mnt, refcnt);
/*
* quickly check if the current mount can be unmounted.
* If not, we don't have to go checking for all other
* mounts
*/
if (!list_empty(&mnt->mnt_mounts) || do_refcount_check(mnt, refcnt))
return 1;
for (m = propagation_next(parent, parent); m;
m = propagation_next(m, parent)) {
child = __lookup_mnt(m, mnt->mnt_mountpoint, 0);
if (child && list_empty(&child->mnt_mounts) &&
(ret = do_refcount_check(child, 1)))
break;
}
return ret;
}
/*
* NOTE: unmounting 'mnt' naturally propagates to all other mounts its
* parent propagates to.
*/
static void __propagate_umount(struct vfsmount *mnt)
{
struct vfsmount *parent = mnt->mnt_parent;
struct vfsmount *m;
BUG_ON(parent == mnt);
for (m = propagation_next(parent, parent); m;
m = propagation_next(m, parent)) {
struct vfsmount *child = __lookup_mnt(m,
mnt->mnt_mountpoint, 0);
/*
* umount the child only if the child has no
* other children
*/
if (child && list_empty(&child->mnt_mounts))
list_move_tail(&child->mnt_hash, &mnt->mnt_hash);
}
}
/*
* collect all mounts that receive propagation from the mount in @list,
* and return these additional mounts in the same list.
* @list: the list of mounts to be unmounted.
*/
int propagate_umount(struct list_head *list)
{
struct vfsmount *mnt;
list_for_each_entry(mnt, list, mnt_hash)
__propagate_umount(mnt);
return 0;
}
| gpl-2.0 |
Jamesjue/linux_kernel_db | drivers/gpu/drm/radeon/radeon_legacy_encoders.c | 1052 | 56893 | /*
* Copyright 2007-8 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
*/
#include <drm/drmP.h>
#include <drm/drm_crtc_helper.h>
#include <drm/radeon_drm.h>
#include "radeon.h"
#include "atom.h"
#include <linux/backlight.h>
#ifdef CONFIG_PMAC_BACKLIGHT
#include <asm/backlight.h>
#endif
static void radeon_legacy_encoder_disable(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_encoder_helper_funcs *encoder_funcs;
encoder_funcs = encoder->helper_private;
encoder_funcs->dpms(encoder, DRM_MODE_DPMS_OFF);
radeon_encoder->active_device = 0;
}
static void radeon_legacy_lvds_update(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t lvds_gen_cntl, lvds_pll_cntl, pixclks_cntl, disp_pwr_man;
int panel_pwr_delay = 2000;
bool is_mac = false;
uint8_t backlight_level;
DRM_DEBUG_KMS("\n");
lvds_gen_cntl = RREG32(RADEON_LVDS_GEN_CNTL);
backlight_level = (lvds_gen_cntl >> RADEON_LVDS_BL_MOD_LEVEL_SHIFT) & 0xff;
if (radeon_encoder->enc_priv) {
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
panel_pwr_delay = lvds->panel_pwr_delay;
if (lvds->bl_dev)
backlight_level = lvds->backlight_level;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
panel_pwr_delay = lvds->panel_pwr_delay;
if (lvds->bl_dev)
backlight_level = lvds->backlight_level;
}
}
/* macs (and possibly some x86 oem systems?) wire up LVDS strangely
* Taken from radeonfb.
*/
if ((rdev->mode_info.connector_table == CT_IBOOK) ||
(rdev->mode_info.connector_table == CT_POWERBOOK_EXTERNAL) ||
(rdev->mode_info.connector_table == CT_POWERBOOK_INTERNAL) ||
(rdev->mode_info.connector_table == CT_POWERBOOK_VGA))
is_mac = true;
switch (mode) {
case DRM_MODE_DPMS_ON:
disp_pwr_man = RREG32(RADEON_DISP_PWR_MAN);
disp_pwr_man |= RADEON_AUTO_PWRUP_EN;
WREG32(RADEON_DISP_PWR_MAN, disp_pwr_man);
lvds_pll_cntl = RREG32(RADEON_LVDS_PLL_CNTL);
lvds_pll_cntl |= RADEON_LVDS_PLL_EN;
WREG32(RADEON_LVDS_PLL_CNTL, lvds_pll_cntl);
mdelay(1);
lvds_pll_cntl = RREG32(RADEON_LVDS_PLL_CNTL);
lvds_pll_cntl &= ~RADEON_LVDS_PLL_RESET;
WREG32(RADEON_LVDS_PLL_CNTL, lvds_pll_cntl);
lvds_gen_cntl &= ~(RADEON_LVDS_DISPLAY_DIS |
RADEON_LVDS_BL_MOD_LEVEL_MASK);
lvds_gen_cntl |= (RADEON_LVDS_ON | RADEON_LVDS_EN |
RADEON_LVDS_DIGON | RADEON_LVDS_BLON |
(backlight_level << RADEON_LVDS_BL_MOD_LEVEL_SHIFT));
if (is_mac)
lvds_gen_cntl |= RADEON_LVDS_BL_MOD_EN;
mdelay(panel_pwr_delay);
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
pixclks_cntl = RREG32_PLL(RADEON_PIXCLKS_CNTL);
WREG32_PLL_P(RADEON_PIXCLKS_CNTL, 0, ~RADEON_PIXCLK_LVDS_ALWAYS_ONb);
lvds_gen_cntl |= RADEON_LVDS_DISPLAY_DIS;
if (is_mac) {
lvds_gen_cntl &= ~RADEON_LVDS_BL_MOD_EN;
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
lvds_gen_cntl &= ~(RADEON_LVDS_ON | RADEON_LVDS_EN);
} else {
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
lvds_gen_cntl &= ~(RADEON_LVDS_ON | RADEON_LVDS_BLON | RADEON_LVDS_EN | RADEON_LVDS_DIGON);
}
mdelay(panel_pwr_delay);
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
WREG32_PLL(RADEON_PIXCLKS_CNTL, pixclks_cntl);
mdelay(panel_pwr_delay);
break;
}
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_lvds_dpms(struct drm_encoder *encoder, int mode)
{
struct radeon_device *rdev = encoder->dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
DRM_DEBUG("\n");
if (radeon_encoder->enc_priv) {
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
lvds->dpms_mode = mode;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
lvds->dpms_mode = mode;
}
}
radeon_legacy_lvds_update(encoder, mode);
}
static void radeon_legacy_lvds_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_lvds_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_lvds_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_lvds_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, false);
else
radeon_combios_output_lock(encoder, false);
}
static void radeon_legacy_lvds_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t lvds_pll_cntl, lvds_gen_cntl, lvds_ss_gen_cntl;
DRM_DEBUG_KMS("\n");
lvds_pll_cntl = RREG32(RADEON_LVDS_PLL_CNTL);
lvds_pll_cntl &= ~RADEON_LVDS_PLL_EN;
lvds_ss_gen_cntl = RREG32(RADEON_LVDS_SS_GEN_CNTL);
if (rdev->is_atom_bios) {
/* LVDS_GEN_CNTL parameters are computed in LVDSEncoderControl
* need to call that on resume to set up the reg properly.
*/
radeon_encoder->pixel_clock = adjusted_mode->clock;
atombios_digital_setup(encoder, PANEL_ENCODER_ACTION_ENABLE);
lvds_gen_cntl = RREG32(RADEON_LVDS_GEN_CNTL);
} else {
struct radeon_encoder_lvds *lvds = (struct radeon_encoder_lvds *)radeon_encoder->enc_priv;
if (lvds) {
DRM_DEBUG_KMS("bios LVDS_GEN_CNTL: 0x%x\n", lvds->lvds_gen_cntl);
lvds_gen_cntl = lvds->lvds_gen_cntl;
lvds_ss_gen_cntl &= ~((0xf << RADEON_LVDS_PWRSEQ_DELAY1_SHIFT) |
(0xf << RADEON_LVDS_PWRSEQ_DELAY2_SHIFT));
lvds_ss_gen_cntl |= ((lvds->panel_digon_delay << RADEON_LVDS_PWRSEQ_DELAY1_SHIFT) |
(lvds->panel_blon_delay << RADEON_LVDS_PWRSEQ_DELAY2_SHIFT));
} else
lvds_gen_cntl = RREG32(RADEON_LVDS_GEN_CNTL);
}
lvds_gen_cntl |= RADEON_LVDS_DISPLAY_DIS;
lvds_gen_cntl &= ~(RADEON_LVDS_ON |
RADEON_LVDS_BLON |
RADEON_LVDS_EN |
RADEON_LVDS_RST_FM);
if (ASIC_IS_R300(rdev))
lvds_pll_cntl &= ~(R300_LVDS_SRC_SEL_MASK);
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev)) {
if (radeon_encoder->rmx_type != RMX_OFF)
lvds_pll_cntl |= R300_LVDS_SRC_SEL_RMX;
} else
lvds_gen_cntl &= ~RADEON_LVDS_SEL_CRTC2;
} else {
if (ASIC_IS_R300(rdev))
lvds_pll_cntl |= R300_LVDS_SRC_SEL_CRTC2;
else
lvds_gen_cntl |= RADEON_LVDS_SEL_CRTC2;
}
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
WREG32(RADEON_LVDS_PLL_CNTL, lvds_pll_cntl);
WREG32(RADEON_LVDS_SS_GEN_CNTL, lvds_ss_gen_cntl);
if (rdev->family == CHIP_RV410)
WREG32(RADEON_CLOCK_CNTL_INDEX, 0);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static bool radeon_legacy_mode_fixup(struct drm_encoder *encoder,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
/* set the active encoder to connector routing */
radeon_encoder_set_active_device(encoder);
drm_mode_set_crtcinfo(adjusted_mode, 0);
/* get the native mode for LVDS */
if (radeon_encoder->active_device & (ATOM_DEVICE_LCD_SUPPORT))
radeon_panel_mode_fixup(encoder, adjusted_mode);
return true;
}
static const struct drm_encoder_helper_funcs radeon_legacy_lvds_helper_funcs = {
.dpms = radeon_legacy_lvds_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_lvds_prepare,
.mode_set = radeon_legacy_lvds_mode_set,
.commit = radeon_legacy_lvds_commit,
.disable = radeon_legacy_encoder_disable,
};
u8
radeon_legacy_get_backlight_level(struct radeon_encoder *radeon_encoder)
{
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
u8 backlight_level;
backlight_level = (RREG32(RADEON_LVDS_GEN_CNTL) >>
RADEON_LVDS_BL_MOD_LEVEL_SHIFT) & 0xff;
return backlight_level;
}
void
radeon_legacy_set_backlight_level(struct radeon_encoder *radeon_encoder, u8 level)
{
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
int dpms_mode = DRM_MODE_DPMS_ON;
if (radeon_encoder->enc_priv) {
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
if (lvds->backlight_level > 0)
dpms_mode = lvds->dpms_mode;
else
dpms_mode = DRM_MODE_DPMS_OFF;
lvds->backlight_level = level;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
if (lvds->backlight_level > 0)
dpms_mode = lvds->dpms_mode;
else
dpms_mode = DRM_MODE_DPMS_OFF;
lvds->backlight_level = level;
}
}
radeon_legacy_lvds_update(&radeon_encoder->base, dpms_mode);
}
#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) || defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
static uint8_t radeon_legacy_lvds_level(struct backlight_device *bd)
{
struct radeon_backlight_privdata *pdata = bl_get_data(bd);
uint8_t level;
/* Convert brightness to hardware level */
if (bd->props.brightness < 0)
level = 0;
else if (bd->props.brightness > RADEON_MAX_BL_LEVEL)
level = RADEON_MAX_BL_LEVEL;
else
level = bd->props.brightness;
if (pdata->negative)
level = RADEON_MAX_BL_LEVEL - level;
return level;
}
static int radeon_legacy_backlight_update_status(struct backlight_device *bd)
{
struct radeon_backlight_privdata *pdata = bl_get_data(bd);
struct radeon_encoder *radeon_encoder = pdata->encoder;
radeon_legacy_set_backlight_level(radeon_encoder,
radeon_legacy_lvds_level(bd));
return 0;
}
static int radeon_legacy_backlight_get_brightness(struct backlight_device *bd)
{
struct radeon_backlight_privdata *pdata = bl_get_data(bd);
struct radeon_encoder *radeon_encoder = pdata->encoder;
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
uint8_t backlight_level;
backlight_level = (RREG32(RADEON_LVDS_GEN_CNTL) >>
RADEON_LVDS_BL_MOD_LEVEL_SHIFT) & 0xff;
return pdata->negative ? RADEON_MAX_BL_LEVEL - backlight_level : backlight_level;
}
static const struct backlight_ops radeon_backlight_ops = {
.get_brightness = radeon_legacy_backlight_get_brightness,
.update_status = radeon_legacy_backlight_update_status,
};
void radeon_legacy_backlight_init(struct radeon_encoder *radeon_encoder,
struct drm_connector *drm_connector)
{
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct backlight_device *bd;
struct backlight_properties props;
struct radeon_backlight_privdata *pdata;
uint8_t backlight_level;
char bl_name[16];
if (!radeon_encoder->enc_priv)
return;
#ifdef CONFIG_PMAC_BACKLIGHT
if (!pmac_has_backlight_type("ati") &&
!pmac_has_backlight_type("mnca"))
return;
#endif
pdata = kmalloc(sizeof(struct radeon_backlight_privdata), GFP_KERNEL);
if (!pdata) {
DRM_ERROR("Memory allocation failed\n");
goto error;
}
memset(&props, 0, sizeof(props));
props.max_brightness = RADEON_MAX_BL_LEVEL;
props.type = BACKLIGHT_RAW;
snprintf(bl_name, sizeof(bl_name),
"radeon_bl%d", dev->primary->index);
bd = backlight_device_register(bl_name, drm_connector->kdev,
pdata, &radeon_backlight_ops, &props);
if (IS_ERR(bd)) {
DRM_ERROR("Backlight registration failed\n");
goto error;
}
pdata->encoder = radeon_encoder;
backlight_level = (RREG32(RADEON_LVDS_GEN_CNTL) >>
RADEON_LVDS_BL_MOD_LEVEL_SHIFT) & 0xff;
/* First, try to detect backlight level sense based on the assumption
* that firmware set it up at full brightness
*/
if (backlight_level == 0)
pdata->negative = true;
else if (backlight_level == 0xff)
pdata->negative = false;
else {
/* XXX hack... maybe some day we can figure out in what direction
* backlight should work on a given panel?
*/
pdata->negative = (rdev->family != CHIP_RV200 &&
rdev->family != CHIP_RV250 &&
rdev->family != CHIP_RV280 &&
rdev->family != CHIP_RV350);
#ifdef CONFIG_PMAC_BACKLIGHT
pdata->negative = (pdata->negative ||
of_machine_is_compatible("PowerBook4,3") ||
of_machine_is_compatible("PowerBook6,3") ||
of_machine_is_compatible("PowerBook6,5"));
#endif
}
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
lvds->bl_dev = bd;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
lvds->bl_dev = bd;
}
bd->props.brightness = radeon_legacy_backlight_get_brightness(bd);
bd->props.power = FB_BLANK_UNBLANK;
backlight_update_status(bd);
DRM_INFO("radeon legacy LVDS backlight initialized\n");
return;
error:
kfree(pdata);
return;
}
static void radeon_legacy_backlight_exit(struct radeon_encoder *radeon_encoder)
{
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct backlight_device *bd = NULL;
if (!radeon_encoder->enc_priv)
return;
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
bd = lvds->bl_dev;
lvds->bl_dev = NULL;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
bd = lvds->bl_dev;
lvds->bl_dev = NULL;
}
if (bd) {
struct radeon_backlight_privdata *pdata;
pdata = bl_get_data(bd);
backlight_device_unregister(bd);
kfree(pdata);
DRM_INFO("radeon legacy LVDS backlight unloaded\n");
}
}
#else /* !CONFIG_BACKLIGHT_CLASS_DEVICE */
void radeon_legacy_backlight_init(struct radeon_encoder *encoder)
{
}
static void radeon_legacy_backlight_exit(struct radeon_encoder *encoder)
{
}
#endif
static void radeon_lvds_enc_destroy(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->enc_priv) {
radeon_legacy_backlight_exit(radeon_encoder);
kfree(radeon_encoder->enc_priv);
}
drm_encoder_cleanup(encoder);
kfree(radeon_encoder);
}
static const struct drm_encoder_funcs radeon_legacy_lvds_enc_funcs = {
.destroy = radeon_lvds_enc_destroy,
};
static void radeon_legacy_primary_dac_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t crtc_ext_cntl = RREG32(RADEON_CRTC_EXT_CNTL);
uint32_t dac_cntl = RREG32(RADEON_DAC_CNTL);
uint32_t dac_macro_cntl = RREG32(RADEON_DAC_MACRO_CNTL);
DRM_DEBUG_KMS("\n");
switch (mode) {
case DRM_MODE_DPMS_ON:
crtc_ext_cntl |= RADEON_CRTC_CRT_ON;
dac_cntl &= ~RADEON_DAC_PDWN;
dac_macro_cntl &= ~(RADEON_DAC_PDWN_R |
RADEON_DAC_PDWN_G |
RADEON_DAC_PDWN_B);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
crtc_ext_cntl &= ~RADEON_CRTC_CRT_ON;
dac_cntl |= RADEON_DAC_PDWN;
dac_macro_cntl |= (RADEON_DAC_PDWN_R |
RADEON_DAC_PDWN_G |
RADEON_DAC_PDWN_B);
break;
}
/* handled in radeon_crtc_dpms() */
if (!(rdev->flags & RADEON_SINGLE_CRTC))
WREG32(RADEON_CRTC_EXT_CNTL, crtc_ext_cntl);
WREG32(RADEON_DAC_CNTL, dac_cntl);
WREG32(RADEON_DAC_MACRO_CNTL, dac_macro_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_primary_dac_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_primary_dac_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_primary_dac_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_primary_dac_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, false);
else
radeon_combios_output_lock(encoder, false);
}
static void radeon_legacy_primary_dac_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t disp_output_cntl, dac_cntl, dac2_cntl, dac_macro_cntl;
DRM_DEBUG_KMS("\n");
if (radeon_crtc->crtc_id == 0) {
if (rdev->family == CHIP_R200 || ASIC_IS_R300(rdev)) {
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL) &
~(RADEON_DISP_DAC_SOURCE_MASK);
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
} else {
dac2_cntl = RREG32(RADEON_DAC_CNTL2) & ~(RADEON_DAC2_DAC_CLK_SEL);
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
}
} else {
if (rdev->family == CHIP_R200 || ASIC_IS_R300(rdev)) {
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL) &
~(RADEON_DISP_DAC_SOURCE_MASK);
disp_output_cntl |= RADEON_DISP_DAC_SOURCE_CRTC2;
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
} else {
dac2_cntl = RREG32(RADEON_DAC_CNTL2) | RADEON_DAC2_DAC_CLK_SEL;
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
}
}
dac_cntl = (RADEON_DAC_MASK_ALL |
RADEON_DAC_VGA_ADR_EN |
/* TODO 6-bits */
RADEON_DAC_8BIT_EN);
WREG32_P(RADEON_DAC_CNTL,
dac_cntl,
RADEON_DAC_RANGE_CNTL |
RADEON_DAC_BLANKING);
if (radeon_encoder->enc_priv) {
struct radeon_encoder_primary_dac *p_dac = (struct radeon_encoder_primary_dac *)radeon_encoder->enc_priv;
dac_macro_cntl = p_dac->ps2_pdac_adj;
} else
dac_macro_cntl = RREG32(RADEON_DAC_MACRO_CNTL);
dac_macro_cntl |= RADEON_DAC_PDWN_R | RADEON_DAC_PDWN_G | RADEON_DAC_PDWN_B;
WREG32(RADEON_DAC_MACRO_CNTL, dac_macro_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static enum drm_connector_status radeon_legacy_primary_dac_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t vclk_ecp_cntl, crtc_ext_cntl;
uint32_t dac_ext_cntl, dac_cntl, dac_macro_cntl, tmp;
enum drm_connector_status found = connector_status_disconnected;
bool color = true;
/* just don't bother on RN50 those chip are often connected to remoting
* console hw and often we get failure to load detect those. So to make
* everyone happy report the encoder as always connected.
*/
if (ASIC_IS_RN50(rdev)) {
return connector_status_connected;
}
/* save the regs we need */
vclk_ecp_cntl = RREG32_PLL(RADEON_VCLK_ECP_CNTL);
crtc_ext_cntl = RREG32(RADEON_CRTC_EXT_CNTL);
dac_ext_cntl = RREG32(RADEON_DAC_EXT_CNTL);
dac_cntl = RREG32(RADEON_DAC_CNTL);
dac_macro_cntl = RREG32(RADEON_DAC_MACRO_CNTL);
tmp = vclk_ecp_cntl &
~(RADEON_PIXCLK_ALWAYS_ONb | RADEON_PIXCLK_DAC_ALWAYS_ONb);
WREG32_PLL(RADEON_VCLK_ECP_CNTL, tmp);
tmp = crtc_ext_cntl | RADEON_CRTC_CRT_ON;
WREG32(RADEON_CRTC_EXT_CNTL, tmp);
tmp = RADEON_DAC_FORCE_BLANK_OFF_EN |
RADEON_DAC_FORCE_DATA_EN;
if (color)
tmp |= RADEON_DAC_FORCE_DATA_SEL_RGB;
else
tmp |= RADEON_DAC_FORCE_DATA_SEL_G;
if (ASIC_IS_R300(rdev))
tmp |= (0x1b6 << RADEON_DAC_FORCE_DATA_SHIFT);
else if (ASIC_IS_RV100(rdev))
tmp |= (0x1ac << RADEON_DAC_FORCE_DATA_SHIFT);
else
tmp |= (0x180 << RADEON_DAC_FORCE_DATA_SHIFT);
WREG32(RADEON_DAC_EXT_CNTL, tmp);
tmp = dac_cntl & ~(RADEON_DAC_RANGE_CNTL_MASK | RADEON_DAC_PDWN);
tmp |= RADEON_DAC_RANGE_CNTL_PS2 | RADEON_DAC_CMP_EN;
WREG32(RADEON_DAC_CNTL, tmp);
tmp = dac_macro_cntl;
tmp &= ~(RADEON_DAC_PDWN_R |
RADEON_DAC_PDWN_G |
RADEON_DAC_PDWN_B);
WREG32(RADEON_DAC_MACRO_CNTL, tmp);
mdelay(2);
if (RREG32(RADEON_DAC_CNTL) & RADEON_DAC_CMP_OUTPUT)
found = connector_status_connected;
/* restore the regs we used */
WREG32(RADEON_DAC_CNTL, dac_cntl);
WREG32(RADEON_DAC_MACRO_CNTL, dac_macro_cntl);
WREG32(RADEON_DAC_EXT_CNTL, dac_ext_cntl);
WREG32(RADEON_CRTC_EXT_CNTL, crtc_ext_cntl);
WREG32_PLL(RADEON_VCLK_ECP_CNTL, vclk_ecp_cntl);
return found;
}
static const struct drm_encoder_helper_funcs radeon_legacy_primary_dac_helper_funcs = {
.dpms = radeon_legacy_primary_dac_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_primary_dac_prepare,
.mode_set = radeon_legacy_primary_dac_mode_set,
.commit = radeon_legacy_primary_dac_commit,
.detect = radeon_legacy_primary_dac_detect,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_primary_dac_enc_funcs = {
.destroy = radeon_enc_destroy,
};
static void radeon_legacy_tmds_int_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t fp_gen_cntl = RREG32(RADEON_FP_GEN_CNTL);
DRM_DEBUG_KMS("\n");
switch (mode) {
case DRM_MODE_DPMS_ON:
fp_gen_cntl |= (RADEON_FP_FPON | RADEON_FP_TMDS_EN);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
fp_gen_cntl &= ~(RADEON_FP_FPON | RADEON_FP_TMDS_EN);
break;
}
WREG32(RADEON_FP_GEN_CNTL, fp_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_tmds_int_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_tmds_int_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_tmds_int_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_tmds_int_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
}
static void radeon_legacy_tmds_int_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t tmp, tmds_pll_cntl, tmds_transmitter_cntl, fp_gen_cntl;
int i;
DRM_DEBUG_KMS("\n");
tmp = tmds_pll_cntl = RREG32(RADEON_TMDS_PLL_CNTL);
tmp &= 0xfffff;
if (rdev->family == CHIP_RV280) {
/* bit 22 of TMDS_PLL_CNTL is read-back inverted */
tmp ^= (1 << 22);
tmds_pll_cntl ^= (1 << 22);
}
if (radeon_encoder->enc_priv) {
struct radeon_encoder_int_tmds *tmds = (struct radeon_encoder_int_tmds *)radeon_encoder->enc_priv;
for (i = 0; i < 4; i++) {
if (tmds->tmds_pll[i].freq == 0)
break;
if ((uint32_t)(mode->clock / 10) < tmds->tmds_pll[i].freq) {
tmp = tmds->tmds_pll[i].value ;
break;
}
}
}
if (ASIC_IS_R300(rdev) || (rdev->family == CHIP_RV280)) {
if (tmp & 0xfff00000)
tmds_pll_cntl = tmp;
else {
tmds_pll_cntl &= 0xfff00000;
tmds_pll_cntl |= tmp;
}
} else
tmds_pll_cntl = tmp;
tmds_transmitter_cntl = RREG32(RADEON_TMDS_TRANSMITTER_CNTL) &
~(RADEON_TMDS_TRANSMITTER_PLLRST);
if (rdev->family == CHIP_R200 ||
rdev->family == CHIP_R100 ||
ASIC_IS_R300(rdev))
tmds_transmitter_cntl &= ~(RADEON_TMDS_TRANSMITTER_PLLEN);
else /* RV chips got this bit reversed */
tmds_transmitter_cntl |= RADEON_TMDS_TRANSMITTER_PLLEN;
fp_gen_cntl = (RREG32(RADEON_FP_GEN_CNTL) |
(RADEON_FP_CRTC_DONT_SHADOW_VPAR |
RADEON_FP_CRTC_DONT_SHADOW_HEND));
fp_gen_cntl &= ~(RADEON_FP_FPON | RADEON_FP_TMDS_EN);
fp_gen_cntl &= ~(RADEON_FP_RMX_HVSYNC_CONTROL_EN |
RADEON_FP_DFP_SYNC_SEL |
RADEON_FP_CRT_SYNC_SEL |
RADEON_FP_CRTC_LOCK_8DOT |
RADEON_FP_USE_SHADOW_EN |
RADEON_FP_CRTC_USE_SHADOW_VEND |
RADEON_FP_CRT_SYNC_ALT);
if (1) /* FIXME rgbBits == 8 */
fp_gen_cntl |= RADEON_FP_PANEL_FORMAT; /* 24 bit format */
else
fp_gen_cntl &= ~RADEON_FP_PANEL_FORMAT;/* 18 bit format */
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev) || rdev->family == CHIP_R200) {
fp_gen_cntl &= ~R200_FP_SOURCE_SEL_MASK;
if (radeon_encoder->rmx_type != RMX_OFF)
fp_gen_cntl |= R200_FP_SOURCE_SEL_RMX;
else
fp_gen_cntl |= R200_FP_SOURCE_SEL_CRTC1;
} else
fp_gen_cntl &= ~RADEON_FP_SEL_CRTC2;
} else {
if (ASIC_IS_R300(rdev) || rdev->family == CHIP_R200) {
fp_gen_cntl &= ~R200_FP_SOURCE_SEL_MASK;
fp_gen_cntl |= R200_FP_SOURCE_SEL_CRTC2;
} else
fp_gen_cntl |= RADEON_FP_SEL_CRTC2;
}
WREG32(RADEON_TMDS_PLL_CNTL, tmds_pll_cntl);
WREG32(RADEON_TMDS_TRANSMITTER_CNTL, tmds_transmitter_cntl);
WREG32(RADEON_FP_GEN_CNTL, fp_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static const struct drm_encoder_helper_funcs radeon_legacy_tmds_int_helper_funcs = {
.dpms = radeon_legacy_tmds_int_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_tmds_int_prepare,
.mode_set = radeon_legacy_tmds_int_mode_set,
.commit = radeon_legacy_tmds_int_commit,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_tmds_int_enc_funcs = {
.destroy = radeon_enc_destroy,
};
static void radeon_legacy_tmds_ext_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
DRM_DEBUG_KMS("\n");
switch (mode) {
case DRM_MODE_DPMS_ON:
fp2_gen_cntl &= ~RADEON_FP2_BLANK_EN;
fp2_gen_cntl |= (RADEON_FP2_ON | RADEON_FP2_DVO_EN);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
fp2_gen_cntl |= RADEON_FP2_BLANK_EN;
fp2_gen_cntl &= ~(RADEON_FP2_ON | RADEON_FP2_DVO_EN);
break;
}
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_tmds_ext_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_tmds_ext_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_tmds_ext_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_tmds_ext_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, false);
else
radeon_combios_output_lock(encoder, false);
}
static void radeon_legacy_tmds_ext_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t fp2_gen_cntl;
DRM_DEBUG_KMS("\n");
if (rdev->is_atom_bios) {
radeon_encoder->pixel_clock = adjusted_mode->clock;
atombios_dvo_setup(encoder, ATOM_ENABLE);
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
} else {
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
if (1) /* FIXME rgbBits == 8 */
fp2_gen_cntl |= RADEON_FP2_PANEL_FORMAT; /* 24 bit format, */
else
fp2_gen_cntl &= ~RADEON_FP2_PANEL_FORMAT;/* 18 bit format, */
fp2_gen_cntl &= ~(RADEON_FP2_ON |
RADEON_FP2_DVO_EN |
RADEON_FP2_DVO_RATE_SEL_SDR);
/* XXX: these are oem specific */
if (ASIC_IS_R300(rdev)) {
if ((dev->pdev->device == 0x4850) &&
(dev->pdev->subsystem_vendor == 0x1028) &&
(dev->pdev->subsystem_device == 0x2001)) /* Dell Inspiron 8600 */
fp2_gen_cntl |= R300_FP2_DVO_CLOCK_MODE_SINGLE;
else
fp2_gen_cntl |= RADEON_FP2_PAD_FLOP_EN | R300_FP2_DVO_CLOCK_MODE_SINGLE;
/*if (mode->clock > 165000)
fp2_gen_cntl |= R300_FP2_DVO_DUAL_CHANNEL_EN;*/
}
if (!radeon_combios_external_tmds_setup(encoder))
radeon_external_tmds_setup(encoder);
}
if (radeon_crtc->crtc_id == 0) {
if ((rdev->family == CHIP_R200) || ASIC_IS_R300(rdev)) {
fp2_gen_cntl &= ~R200_FP2_SOURCE_SEL_MASK;
if (radeon_encoder->rmx_type != RMX_OFF)
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_RMX;
else
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_CRTC1;
} else
fp2_gen_cntl &= ~RADEON_FP2_SRC_SEL_CRTC2;
} else {
if ((rdev->family == CHIP_R200) || ASIC_IS_R300(rdev)) {
fp2_gen_cntl &= ~R200_FP2_SOURCE_SEL_MASK;
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_CRTC2;
} else
fp2_gen_cntl |= RADEON_FP2_SRC_SEL_CRTC2;
}
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static void radeon_ext_tmds_enc_destroy(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
/* don't destroy the i2c bus record here, this will be done in radeon_i2c_fini */
kfree(radeon_encoder->enc_priv);
drm_encoder_cleanup(encoder);
kfree(radeon_encoder);
}
static const struct drm_encoder_helper_funcs radeon_legacy_tmds_ext_helper_funcs = {
.dpms = radeon_legacy_tmds_ext_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_tmds_ext_prepare,
.mode_set = radeon_legacy_tmds_ext_mode_set,
.commit = radeon_legacy_tmds_ext_commit,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_tmds_ext_enc_funcs = {
.destroy = radeon_ext_tmds_enc_destroy,
};
static void radeon_legacy_tv_dac_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t fp2_gen_cntl = 0, crtc2_gen_cntl = 0, tv_dac_cntl = 0;
uint32_t tv_master_cntl = 0;
bool is_tv;
DRM_DEBUG_KMS("\n");
is_tv = radeon_encoder->active_device & ATOM_DEVICE_TV_SUPPORT ? true : false;
if (rdev->family == CHIP_R200)
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
else {
if (is_tv)
tv_master_cntl = RREG32(RADEON_TV_MASTER_CNTL);
else
crtc2_gen_cntl = RREG32(RADEON_CRTC2_GEN_CNTL);
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
}
switch (mode) {
case DRM_MODE_DPMS_ON:
if (rdev->family == CHIP_R200) {
fp2_gen_cntl |= (RADEON_FP2_ON | RADEON_FP2_DVO_EN);
} else {
if (is_tv)
tv_master_cntl |= RADEON_TV_ON;
else
crtc2_gen_cntl |= RADEON_CRTC2_CRT2_ON;
if (rdev->family == CHIP_R420 ||
rdev->family == CHIP_R423 ||
rdev->family == CHIP_RV410)
tv_dac_cntl &= ~(R420_TV_DAC_RDACPD |
R420_TV_DAC_GDACPD |
R420_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
else
tv_dac_cntl &= ~(RADEON_TV_DAC_RDACPD |
RADEON_TV_DAC_GDACPD |
RADEON_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
}
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
if (rdev->family == CHIP_R200)
fp2_gen_cntl &= ~(RADEON_FP2_ON | RADEON_FP2_DVO_EN);
else {
if (is_tv)
tv_master_cntl &= ~RADEON_TV_ON;
else
crtc2_gen_cntl &= ~RADEON_CRTC2_CRT2_ON;
if (rdev->family == CHIP_R420 ||
rdev->family == CHIP_R423 ||
rdev->family == CHIP_RV410)
tv_dac_cntl |= (R420_TV_DAC_RDACPD |
R420_TV_DAC_GDACPD |
R420_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
else
tv_dac_cntl |= (RADEON_TV_DAC_RDACPD |
RADEON_TV_DAC_GDACPD |
RADEON_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
}
break;
}
if (rdev->family == CHIP_R200) {
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
} else {
if (is_tv)
WREG32(RADEON_TV_MASTER_CNTL, tv_master_cntl);
/* handled in radeon_crtc_dpms() */
else if (!(rdev->flags & RADEON_SINGLE_CRTC))
WREG32(RADEON_CRTC2_GEN_CNTL, crtc2_gen_cntl);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
}
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_tv_dac_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_tv_dac_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_tv_dac_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_tv_dac_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
}
static void radeon_legacy_tv_dac_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_tv_dac *tv_dac = radeon_encoder->enc_priv;
uint32_t tv_dac_cntl, gpiopad_a = 0, dac2_cntl, disp_output_cntl = 0;
uint32_t disp_hw_debug = 0, fp2_gen_cntl = 0, disp_tv_out_cntl = 0;
bool is_tv = false;
DRM_DEBUG_KMS("\n");
is_tv = radeon_encoder->active_device & ATOM_DEVICE_TV_SUPPORT ? true : false;
if (rdev->family != CHIP_R200) {
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
if (rdev->family == CHIP_R420 ||
rdev->family == CHIP_R423 ||
rdev->family == CHIP_RV410) {
tv_dac_cntl &= ~(RADEON_TV_DAC_STD_MASK |
RADEON_TV_DAC_BGADJ_MASK |
R420_TV_DAC_DACADJ_MASK |
R420_TV_DAC_RDACPD |
R420_TV_DAC_GDACPD |
R420_TV_DAC_BDACPD |
R420_TV_DAC_TVENABLE);
} else {
tv_dac_cntl &= ~(RADEON_TV_DAC_STD_MASK |
RADEON_TV_DAC_BGADJ_MASK |
RADEON_TV_DAC_DACADJ_MASK |
RADEON_TV_DAC_RDACPD |
RADEON_TV_DAC_GDACPD |
RADEON_TV_DAC_BDACPD);
}
tv_dac_cntl |= RADEON_TV_DAC_NBLANK | RADEON_TV_DAC_NHOLD;
if (is_tv) {
if (tv_dac->tv_std == TV_STD_NTSC ||
tv_dac->tv_std == TV_STD_NTSC_J ||
tv_dac->tv_std == TV_STD_PAL_M ||
tv_dac->tv_std == TV_STD_PAL_60)
tv_dac_cntl |= tv_dac->ntsc_tvdac_adj;
else
tv_dac_cntl |= tv_dac->pal_tvdac_adj;
if (tv_dac->tv_std == TV_STD_NTSC ||
tv_dac->tv_std == TV_STD_NTSC_J)
tv_dac_cntl |= RADEON_TV_DAC_STD_NTSC;
else
tv_dac_cntl |= RADEON_TV_DAC_STD_PAL;
} else
tv_dac_cntl |= (RADEON_TV_DAC_STD_PS2 |
tv_dac->ps2_tvdac_adj);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
}
if (ASIC_IS_R300(rdev)) {
gpiopad_a = RREG32(RADEON_GPIOPAD_A) | 1;
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL);
} else if (rdev->family != CHIP_R200)
disp_hw_debug = RREG32(RADEON_DISP_HW_DEBUG);
else if (rdev->family == CHIP_R200)
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
if (rdev->family >= CHIP_R200)
disp_tv_out_cntl = RREG32(RADEON_DISP_TV_OUT_CNTL);
if (is_tv) {
uint32_t dac_cntl;
dac_cntl = RREG32(RADEON_DAC_CNTL);
dac_cntl &= ~RADEON_DAC_TVO_EN;
WREG32(RADEON_DAC_CNTL, dac_cntl);
if (ASIC_IS_R300(rdev))
gpiopad_a = RREG32(RADEON_GPIOPAD_A) & ~1;
dac2_cntl = RREG32(RADEON_DAC_CNTL2) & ~RADEON_DAC2_DAC2_CLK_SEL;
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= (RADEON_DISP_TVDAC_SOURCE_CRTC |
RADEON_DISP_TV_SOURCE_CRTC);
}
if (rdev->family >= CHIP_R200) {
disp_tv_out_cntl &= ~RADEON_DISP_TV_PATH_SRC_CRTC2;
} else {
disp_hw_debug |= RADEON_CRT2_DISP1_SEL;
}
} else {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= RADEON_DISP_TV_SOURCE_CRTC;
}
if (rdev->family >= CHIP_R200) {
disp_tv_out_cntl |= RADEON_DISP_TV_PATH_SRC_CRTC2;
} else {
disp_hw_debug &= ~RADEON_CRT2_DISP1_SEL;
}
}
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
} else {
dac2_cntl = RREG32(RADEON_DAC_CNTL2) | RADEON_DAC2_DAC2_CLK_SEL;
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= RADEON_DISP_TVDAC_SOURCE_CRTC;
} else if (rdev->family == CHIP_R200) {
fp2_gen_cntl &= ~(R200_FP2_SOURCE_SEL_MASK |
RADEON_FP2_DVO_RATE_SEL_SDR);
} else
disp_hw_debug |= RADEON_CRT2_DISP1_SEL;
} else {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= RADEON_DISP_TVDAC_SOURCE_CRTC2;
} else if (rdev->family == CHIP_R200) {
fp2_gen_cntl &= ~(R200_FP2_SOURCE_SEL_MASK |
RADEON_FP2_DVO_RATE_SEL_SDR);
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_CRTC2;
} else
disp_hw_debug &= ~RADEON_CRT2_DISP1_SEL;
}
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
}
if (ASIC_IS_R300(rdev)) {
WREG32_P(RADEON_GPIOPAD_A, gpiopad_a, ~1);
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
} else if (rdev->family != CHIP_R200)
WREG32(RADEON_DISP_HW_DEBUG, disp_hw_debug);
else if (rdev->family == CHIP_R200)
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
if (rdev->family >= CHIP_R200)
WREG32(RADEON_DISP_TV_OUT_CNTL, disp_tv_out_cntl);
if (is_tv)
radeon_legacy_tv_mode_set(encoder, mode, adjusted_mode);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static bool r300_legacy_tv_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t crtc2_gen_cntl, tv_dac_cntl, dac_cntl2, dac_ext_cntl;
uint32_t disp_output_cntl, gpiopad_a, tmp;
bool found = false;
/* save regs needed */
gpiopad_a = RREG32(RADEON_GPIOPAD_A);
dac_cntl2 = RREG32(RADEON_DAC_CNTL2);
crtc2_gen_cntl = RREG32(RADEON_CRTC2_GEN_CNTL);
dac_ext_cntl = RREG32(RADEON_DAC_EXT_CNTL);
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL);
WREG32_P(RADEON_GPIOPAD_A, 0, ~1);
WREG32(RADEON_DAC_CNTL2, RADEON_DAC2_DAC2_CLK_SEL);
WREG32(RADEON_CRTC2_GEN_CNTL,
RADEON_CRTC2_CRT2_ON | RADEON_CRTC2_VSYNC_TRISTAT);
tmp = disp_output_cntl & ~RADEON_DISP_TVDAC_SOURCE_MASK;
tmp |= RADEON_DISP_TVDAC_SOURCE_CRTC2;
WREG32(RADEON_DISP_OUTPUT_CNTL, tmp);
WREG32(RADEON_DAC_EXT_CNTL,
RADEON_DAC2_FORCE_BLANK_OFF_EN |
RADEON_DAC2_FORCE_DATA_EN |
RADEON_DAC_FORCE_DATA_SEL_RGB |
(0xec << RADEON_DAC_FORCE_DATA_SHIFT));
WREG32(RADEON_TV_DAC_CNTL,
RADEON_TV_DAC_STD_NTSC |
(8 << RADEON_TV_DAC_BGADJ_SHIFT) |
(6 << RADEON_TV_DAC_DACADJ_SHIFT));
RREG32(RADEON_TV_DAC_CNTL);
mdelay(4);
WREG32(RADEON_TV_DAC_CNTL,
RADEON_TV_DAC_NBLANK |
RADEON_TV_DAC_NHOLD |
RADEON_TV_MONITOR_DETECT_EN |
RADEON_TV_DAC_STD_NTSC |
(8 << RADEON_TV_DAC_BGADJ_SHIFT) |
(6 << RADEON_TV_DAC_DACADJ_SHIFT));
RREG32(RADEON_TV_DAC_CNTL);
mdelay(6);
tmp = RREG32(RADEON_TV_DAC_CNTL);
if ((tmp & RADEON_TV_DAC_GDACDET) != 0) {
found = true;
DRM_DEBUG_KMS("S-video TV connection detected\n");
} else if ((tmp & RADEON_TV_DAC_BDACDET) != 0) {
found = true;
DRM_DEBUG_KMS("Composite TV connection detected\n");
}
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
WREG32(RADEON_DAC_EXT_CNTL, dac_ext_cntl);
WREG32(RADEON_CRTC2_GEN_CNTL, crtc2_gen_cntl);
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
WREG32(RADEON_DAC_CNTL2, dac_cntl2);
WREG32_P(RADEON_GPIOPAD_A, gpiopad_a, ~1);
return found;
}
static bool radeon_legacy_tv_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t tv_dac_cntl, dac_cntl2;
uint32_t config_cntl, tv_pre_dac_mux_cntl, tv_master_cntl, tmp;
bool found = false;
if (ASIC_IS_R300(rdev))
return r300_legacy_tv_detect(encoder, connector);
dac_cntl2 = RREG32(RADEON_DAC_CNTL2);
tv_master_cntl = RREG32(RADEON_TV_MASTER_CNTL);
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
config_cntl = RREG32(RADEON_CONFIG_CNTL);
tv_pre_dac_mux_cntl = RREG32(RADEON_TV_PRE_DAC_MUX_CNTL);
tmp = dac_cntl2 & ~RADEON_DAC2_DAC2_CLK_SEL;
WREG32(RADEON_DAC_CNTL2, tmp);
tmp = tv_master_cntl | RADEON_TV_ON;
tmp &= ~(RADEON_TV_ASYNC_RST |
RADEON_RESTART_PHASE_FIX |
RADEON_CRT_FIFO_CE_EN |
RADEON_TV_FIFO_CE_EN |
RADEON_RE_SYNC_NOW_SEL_MASK);
tmp |= RADEON_TV_FIFO_ASYNC_RST | RADEON_CRT_ASYNC_RST;
WREG32(RADEON_TV_MASTER_CNTL, tmp);
tmp = RADEON_TV_DAC_NBLANK | RADEON_TV_DAC_NHOLD |
RADEON_TV_MONITOR_DETECT_EN | RADEON_TV_DAC_STD_NTSC |
(8 << RADEON_TV_DAC_BGADJ_SHIFT);
if (config_cntl & RADEON_CFG_ATI_REV_ID_MASK)
tmp |= (4 << RADEON_TV_DAC_DACADJ_SHIFT);
else
tmp |= (8 << RADEON_TV_DAC_DACADJ_SHIFT);
WREG32(RADEON_TV_DAC_CNTL, tmp);
tmp = RADEON_C_GRN_EN | RADEON_CMP_BLU_EN |
RADEON_RED_MX_FORCE_DAC_DATA |
RADEON_GRN_MX_FORCE_DAC_DATA |
RADEON_BLU_MX_FORCE_DAC_DATA |
(0x109 << RADEON_TV_FORCE_DAC_DATA_SHIFT);
WREG32(RADEON_TV_PRE_DAC_MUX_CNTL, tmp);
mdelay(3);
tmp = RREG32(RADEON_TV_DAC_CNTL);
if (tmp & RADEON_TV_DAC_GDACDET) {
found = true;
DRM_DEBUG_KMS("S-video TV connection detected\n");
} else if ((tmp & RADEON_TV_DAC_BDACDET) != 0) {
found = true;
DRM_DEBUG_KMS("Composite TV connection detected\n");
}
WREG32(RADEON_TV_PRE_DAC_MUX_CNTL, tv_pre_dac_mux_cntl);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
WREG32(RADEON_TV_MASTER_CNTL, tv_master_cntl);
WREG32(RADEON_DAC_CNTL2, dac_cntl2);
return found;
}
static bool radeon_legacy_ext_dac_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t gpio_monid, fp2_gen_cntl, disp_output_cntl, crtc2_gen_cntl;
uint32_t disp_lin_trans_grph_a, disp_lin_trans_grph_b, disp_lin_trans_grph_c;
uint32_t disp_lin_trans_grph_d, disp_lin_trans_grph_e, disp_lin_trans_grph_f;
uint32_t tmp, crtc2_h_total_disp, crtc2_v_total_disp;
uint32_t crtc2_h_sync_strt_wid, crtc2_v_sync_strt_wid;
bool found = false;
int i;
/* save the regs we need */
gpio_monid = RREG32(RADEON_GPIO_MONID);
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL);
crtc2_gen_cntl = RREG32(RADEON_CRTC2_GEN_CNTL);
disp_lin_trans_grph_a = RREG32(RADEON_DISP_LIN_TRANS_GRPH_A);
disp_lin_trans_grph_b = RREG32(RADEON_DISP_LIN_TRANS_GRPH_B);
disp_lin_trans_grph_c = RREG32(RADEON_DISP_LIN_TRANS_GRPH_C);
disp_lin_trans_grph_d = RREG32(RADEON_DISP_LIN_TRANS_GRPH_D);
disp_lin_trans_grph_e = RREG32(RADEON_DISP_LIN_TRANS_GRPH_E);
disp_lin_trans_grph_f = RREG32(RADEON_DISP_LIN_TRANS_GRPH_F);
crtc2_h_total_disp = RREG32(RADEON_CRTC2_H_TOTAL_DISP);
crtc2_v_total_disp = RREG32(RADEON_CRTC2_V_TOTAL_DISP);
crtc2_h_sync_strt_wid = RREG32(RADEON_CRTC2_H_SYNC_STRT_WID);
crtc2_v_sync_strt_wid = RREG32(RADEON_CRTC2_V_SYNC_STRT_WID);
tmp = RREG32(RADEON_GPIO_MONID);
tmp &= ~RADEON_GPIO_A_0;
WREG32(RADEON_GPIO_MONID, tmp);
WREG32(RADEON_FP2_GEN_CNTL, (RADEON_FP2_ON |
RADEON_FP2_PANEL_FORMAT |
R200_FP2_SOURCE_SEL_TRANS_UNIT |
RADEON_FP2_DVO_EN |
R200_FP2_DVO_RATE_SEL_SDR));
WREG32(RADEON_DISP_OUTPUT_CNTL, (RADEON_DISP_DAC_SOURCE_RMX |
RADEON_DISP_TRANS_MATRIX_GRAPHICS));
WREG32(RADEON_CRTC2_GEN_CNTL, (RADEON_CRTC2_EN |
RADEON_CRTC2_DISP_REQ_EN_B));
WREG32(RADEON_DISP_LIN_TRANS_GRPH_A, 0x00000000);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_B, 0x000003f0);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_C, 0x00000000);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_D, 0x000003f0);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_E, 0x00000000);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_F, 0x000003f0);
WREG32(RADEON_CRTC2_H_TOTAL_DISP, 0x01000008);
WREG32(RADEON_CRTC2_H_SYNC_STRT_WID, 0x00000800);
WREG32(RADEON_CRTC2_V_TOTAL_DISP, 0x00080001);
WREG32(RADEON_CRTC2_V_SYNC_STRT_WID, 0x00000080);
for (i = 0; i < 200; i++) {
tmp = RREG32(RADEON_GPIO_MONID);
if (tmp & RADEON_GPIO_Y_0)
found = true;
if (found)
break;
if (!drm_can_sleep())
mdelay(1);
else
msleep(1);
}
/* restore the regs we used */
WREG32(RADEON_DISP_LIN_TRANS_GRPH_A, disp_lin_trans_grph_a);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_B, disp_lin_trans_grph_b);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_C, disp_lin_trans_grph_c);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_D, disp_lin_trans_grph_d);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_E, disp_lin_trans_grph_e);
WREG32(RADEON_DISP_LIN_TRANS_GRPH_F, disp_lin_trans_grph_f);
WREG32(RADEON_CRTC2_H_TOTAL_DISP, crtc2_h_total_disp);
WREG32(RADEON_CRTC2_V_TOTAL_DISP, crtc2_v_total_disp);
WREG32(RADEON_CRTC2_H_SYNC_STRT_WID, crtc2_h_sync_strt_wid);
WREG32(RADEON_CRTC2_V_SYNC_STRT_WID, crtc2_v_sync_strt_wid);
WREG32(RADEON_CRTC2_GEN_CNTL, crtc2_gen_cntl);
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
WREG32(RADEON_GPIO_MONID, gpio_monid);
return found;
}
static enum drm_connector_status radeon_legacy_tv_dac_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t crtc2_gen_cntl = 0, tv_dac_cntl, dac_cntl2, dac_ext_cntl;
uint32_t gpiopad_a = 0, pixclks_cntl, tmp;
uint32_t disp_output_cntl = 0, disp_hw_debug = 0, crtc_ext_cntl = 0;
enum drm_connector_status found = connector_status_disconnected;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_tv_dac *tv_dac = radeon_encoder->enc_priv;
bool color = true;
struct drm_crtc *crtc;
/* find out if crtc2 is in use or if this encoder is using it */
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
if ((radeon_crtc->crtc_id == 1) && crtc->enabled) {
if (encoder->crtc != crtc) {
return connector_status_disconnected;
}
}
}
if (connector->connector_type == DRM_MODE_CONNECTOR_SVIDEO ||
connector->connector_type == DRM_MODE_CONNECTOR_Composite ||
connector->connector_type == DRM_MODE_CONNECTOR_9PinDIN) {
bool tv_detect;
if (radeon_encoder->active_device && !(radeon_encoder->active_device & ATOM_DEVICE_TV_SUPPORT))
return connector_status_disconnected;
tv_detect = radeon_legacy_tv_detect(encoder, connector);
if (tv_detect && tv_dac)
found = connector_status_connected;
return found;
}
/* don't probe if the encoder is being used for something else not CRT related */
if (radeon_encoder->active_device && !(radeon_encoder->active_device & ATOM_DEVICE_CRT_SUPPORT)) {
DRM_INFO("not detecting due to %08x\n", radeon_encoder->active_device);
return connector_status_disconnected;
}
/* R200 uses an external DAC for secondary DAC */
if (rdev->family == CHIP_R200) {
if (radeon_legacy_ext_dac_detect(encoder, connector))
found = connector_status_connected;
return found;
}
/* save the regs we need */
pixclks_cntl = RREG32_PLL(RADEON_PIXCLKS_CNTL);
if (rdev->flags & RADEON_SINGLE_CRTC) {
crtc_ext_cntl = RREG32(RADEON_CRTC_EXT_CNTL);
} else {
if (ASIC_IS_R300(rdev)) {
gpiopad_a = RREG32(RADEON_GPIOPAD_A);
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL);
} else {
disp_hw_debug = RREG32(RADEON_DISP_HW_DEBUG);
}
crtc2_gen_cntl = RREG32(RADEON_CRTC2_GEN_CNTL);
}
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
dac_ext_cntl = RREG32(RADEON_DAC_EXT_CNTL);
dac_cntl2 = RREG32(RADEON_DAC_CNTL2);
tmp = pixclks_cntl & ~(RADEON_PIX2CLK_ALWAYS_ONb
| RADEON_PIX2CLK_DAC_ALWAYS_ONb);
WREG32_PLL(RADEON_PIXCLKS_CNTL, tmp);
if (rdev->flags & RADEON_SINGLE_CRTC) {
tmp = crtc_ext_cntl | RADEON_CRTC_CRT_ON;
WREG32(RADEON_CRTC_EXT_CNTL, tmp);
} else {
tmp = crtc2_gen_cntl & ~RADEON_CRTC2_PIX_WIDTH_MASK;
tmp |= RADEON_CRTC2_CRT2_ON |
(2 << RADEON_CRTC2_PIX_WIDTH_SHIFT);
WREG32(RADEON_CRTC2_GEN_CNTL, tmp);
if (ASIC_IS_R300(rdev)) {
WREG32_P(RADEON_GPIOPAD_A, 1, ~1);
tmp = disp_output_cntl & ~RADEON_DISP_TVDAC_SOURCE_MASK;
tmp |= RADEON_DISP_TVDAC_SOURCE_CRTC2;
WREG32(RADEON_DISP_OUTPUT_CNTL, tmp);
} else {
tmp = disp_hw_debug & ~RADEON_CRT2_DISP1_SEL;
WREG32(RADEON_DISP_HW_DEBUG, tmp);
}
}
tmp = RADEON_TV_DAC_NBLANK |
RADEON_TV_DAC_NHOLD |
RADEON_TV_MONITOR_DETECT_EN |
RADEON_TV_DAC_STD_PS2;
WREG32(RADEON_TV_DAC_CNTL, tmp);
tmp = RADEON_DAC2_FORCE_BLANK_OFF_EN |
RADEON_DAC2_FORCE_DATA_EN;
if (color)
tmp |= RADEON_DAC_FORCE_DATA_SEL_RGB;
else
tmp |= RADEON_DAC_FORCE_DATA_SEL_G;
if (ASIC_IS_R300(rdev))
tmp |= (0x1b6 << RADEON_DAC_FORCE_DATA_SHIFT);
else
tmp |= (0x180 << RADEON_DAC_FORCE_DATA_SHIFT);
WREG32(RADEON_DAC_EXT_CNTL, tmp);
tmp = dac_cntl2 | RADEON_DAC2_DAC2_CLK_SEL | RADEON_DAC2_CMP_EN;
WREG32(RADEON_DAC_CNTL2, tmp);
mdelay(10);
if (ASIC_IS_R300(rdev)) {
if (RREG32(RADEON_DAC_CNTL2) & RADEON_DAC2_CMP_OUT_B)
found = connector_status_connected;
} else {
if (RREG32(RADEON_DAC_CNTL2) & RADEON_DAC2_CMP_OUTPUT)
found = connector_status_connected;
}
/* restore regs we used */
WREG32(RADEON_DAC_CNTL2, dac_cntl2);
WREG32(RADEON_DAC_EXT_CNTL, dac_ext_cntl);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
if (rdev->flags & RADEON_SINGLE_CRTC) {
WREG32(RADEON_CRTC_EXT_CNTL, crtc_ext_cntl);
} else {
WREG32(RADEON_CRTC2_GEN_CNTL, crtc2_gen_cntl);
if (ASIC_IS_R300(rdev)) {
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
WREG32_P(RADEON_GPIOPAD_A, gpiopad_a, ~1);
} else {
WREG32(RADEON_DISP_HW_DEBUG, disp_hw_debug);
}
}
WREG32_PLL(RADEON_PIXCLKS_CNTL, pixclks_cntl);
return found;
}
static const struct drm_encoder_helper_funcs radeon_legacy_tv_dac_helper_funcs = {
.dpms = radeon_legacy_tv_dac_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_tv_dac_prepare,
.mode_set = radeon_legacy_tv_dac_mode_set,
.commit = radeon_legacy_tv_dac_commit,
.detect = radeon_legacy_tv_dac_detect,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_tv_dac_enc_funcs = {
.destroy = radeon_enc_destroy,
};
static struct radeon_encoder_int_tmds *radeon_legacy_get_tmds_info(struct radeon_encoder *encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder_int_tmds *tmds = NULL;
bool ret;
tmds = kzalloc(sizeof(struct radeon_encoder_int_tmds), GFP_KERNEL);
if (!tmds)
return NULL;
if (rdev->is_atom_bios)
ret = radeon_atombios_get_tmds_info(encoder, tmds);
else
ret = radeon_legacy_get_tmds_info_from_combios(encoder, tmds);
if (ret == false)
radeon_legacy_get_tmds_info_from_table(encoder, tmds);
return tmds;
}
static struct radeon_encoder_ext_tmds *radeon_legacy_get_ext_tmds_info(struct radeon_encoder *encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder_ext_tmds *tmds = NULL;
bool ret;
if (rdev->is_atom_bios)
return NULL;
tmds = kzalloc(sizeof(struct radeon_encoder_ext_tmds), GFP_KERNEL);
if (!tmds)
return NULL;
ret = radeon_legacy_get_ext_tmds_info_from_combios(encoder, tmds);
if (ret == false)
radeon_legacy_get_ext_tmds_info_from_table(encoder, tmds);
return tmds;
}
void
radeon_add_legacy_encoder(struct drm_device *dev, uint32_t encoder_enum, uint32_t supported_device)
{
struct radeon_device *rdev = dev->dev_private;
struct drm_encoder *encoder;
struct radeon_encoder *radeon_encoder;
/* see if we already added it */
list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->encoder_enum == encoder_enum) {
radeon_encoder->devices |= supported_device;
return;
}
}
/* add a new one */
radeon_encoder = kzalloc(sizeof(struct radeon_encoder), GFP_KERNEL);
if (!radeon_encoder)
return;
encoder = &radeon_encoder->base;
if (rdev->flags & RADEON_SINGLE_CRTC)
encoder->possible_crtcs = 0x1;
else
encoder->possible_crtcs = 0x3;
radeon_encoder->enc_priv = NULL;
radeon_encoder->encoder_enum = encoder_enum;
radeon_encoder->encoder_id = (encoder_enum & OBJECT_ID_MASK) >> OBJECT_ID_SHIFT;
radeon_encoder->devices = supported_device;
radeon_encoder->rmx_type = RMX_OFF;
switch (radeon_encoder->encoder_id) {
case ENCODER_OBJECT_ID_INTERNAL_LVDS:
encoder->possible_crtcs = 0x1;
drm_encoder_init(dev, encoder, &radeon_legacy_lvds_enc_funcs, DRM_MODE_ENCODER_LVDS);
drm_encoder_helper_add(encoder, &radeon_legacy_lvds_helper_funcs);
if (rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_atombios_get_lvds_info(radeon_encoder);
else
radeon_encoder->enc_priv = radeon_combios_get_lvds_info(radeon_encoder);
radeon_encoder->rmx_type = RMX_FULL;
break;
case ENCODER_OBJECT_ID_INTERNAL_TMDS1:
drm_encoder_init(dev, encoder, &radeon_legacy_tmds_int_enc_funcs, DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(encoder, &radeon_legacy_tmds_int_helper_funcs);
radeon_encoder->enc_priv = radeon_legacy_get_tmds_info(radeon_encoder);
break;
case ENCODER_OBJECT_ID_INTERNAL_DAC1:
drm_encoder_init(dev, encoder, &radeon_legacy_primary_dac_enc_funcs, DRM_MODE_ENCODER_DAC);
drm_encoder_helper_add(encoder, &radeon_legacy_primary_dac_helper_funcs);
if (rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_atombios_get_primary_dac_info(radeon_encoder);
else
radeon_encoder->enc_priv = radeon_combios_get_primary_dac_info(radeon_encoder);
break;
case ENCODER_OBJECT_ID_INTERNAL_DAC2:
drm_encoder_init(dev, encoder, &radeon_legacy_tv_dac_enc_funcs, DRM_MODE_ENCODER_TVDAC);
drm_encoder_helper_add(encoder, &radeon_legacy_tv_dac_helper_funcs);
if (rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_atombios_get_tv_dac_info(radeon_encoder);
else
radeon_encoder->enc_priv = radeon_combios_get_tv_dac_info(radeon_encoder);
break;
case ENCODER_OBJECT_ID_INTERNAL_DVO1:
drm_encoder_init(dev, encoder, &radeon_legacy_tmds_ext_enc_funcs, DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(encoder, &radeon_legacy_tmds_ext_helper_funcs);
if (!rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_legacy_get_ext_tmds_info(radeon_encoder);
break;
}
}
| gpl-2.0 |
TeamDS/htc-kernel-doubleshot_26 | drivers/staging/rt2860/common/rt_rf.c | 1052 | 5278 | /*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2007, Ralink Technology, Inc.
*
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************
Module Name:
rt_rf.c
Abstract:
Ralink Wireless driver RF related functions
Revision History:
Who When What
-------- ---------- ----------------------------------------------
*/
#include "../rt_config.h"
#ifdef RTMP_RF_RW_SUPPORT
/*
========================================================================
Routine Description: Write RT30xx RF register through MAC
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
int RT30xxWriteRFRegister(struct rt_rtmp_adapter *pAd,
u8 regID, u8 value)
{
RF_CSR_CFG_STRUC rfcsr;
u32 i = 0;
do {
RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
if (!rfcsr.field.RF_CSR_KICK)
break;
i++;
}
while ((i < RETRY_LIMIT)
&& (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
if ((i == RETRY_LIMIT)
|| (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))) {
DBGPRINT_RAW(RT_DEBUG_ERROR,
("Retry count exhausted or device removed!\n"));
return STATUS_UNSUCCESSFUL;
}
rfcsr.field.RF_CSR_WR = 1;
rfcsr.field.RF_CSR_KICK = 1;
rfcsr.field.TESTCSR_RFACC_REGNUM = regID;
rfcsr.field.RF_CSR_DATA = value;
RTMP_IO_WRITE32(pAd, RF_CSR_CFG, rfcsr.word);
return NDIS_STATUS_SUCCESS;
}
/*
========================================================================
Routine Description: Read RT30xx RF register through MAC
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
int RT30xxReadRFRegister(struct rt_rtmp_adapter *pAd,
u8 regID, u8 *pValue)
{
RF_CSR_CFG_STRUC rfcsr;
u32 i = 0, k = 0;
for (i = 0; i < MAX_BUSY_COUNT; i++) {
RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
if (rfcsr.field.RF_CSR_KICK == BUSY) {
continue;
}
rfcsr.word = 0;
rfcsr.field.RF_CSR_WR = 0;
rfcsr.field.RF_CSR_KICK = 1;
rfcsr.field.TESTCSR_RFACC_REGNUM = regID;
RTMP_IO_WRITE32(pAd, RF_CSR_CFG, rfcsr.word);
for (k = 0; k < MAX_BUSY_COUNT; k++) {
RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
if (rfcsr.field.RF_CSR_KICK == IDLE)
break;
}
if ((rfcsr.field.RF_CSR_KICK == IDLE) &&
(rfcsr.field.TESTCSR_RFACC_REGNUM == regID)) {
*pValue = (u8)rfcsr.field.RF_CSR_DATA;
break;
}
}
if (rfcsr.field.RF_CSR_KICK == BUSY) {
DBGPRINT_ERR(("RF read R%d=0x%x fail, i[%d], k[%d]\n", regID,
rfcsr.word, i, k));
return STATUS_UNSUCCESSFUL;
}
return STATUS_SUCCESS;
}
void NICInitRFRegisters(struct rt_rtmp_adapter *pAd)
{
if (pAd->chipOps.AsicRfInit)
pAd->chipOps.AsicRfInit(pAd);
}
void RtmpChipOpsRFHook(struct rt_rtmp_adapter *pAd)
{
struct rt_rtmp_chip_op *pChipOps = &pAd->chipOps;
pChipOps->pRFRegTable = NULL;
pChipOps->AsicRfInit = NULL;
pChipOps->AsicRfTurnOn = NULL;
pChipOps->AsicRfTurnOff = NULL;
pChipOps->AsicReverseRfFromSleepMode = NULL;
pChipOps->AsicHaltAction = NULL;
/* We depends on RfICType and MACVersion to assign the corresponding operation callbacks. */
#ifdef RT30xx
if (IS_RT30xx(pAd)) {
pChipOps->pRFRegTable = RT30xx_RFRegTable;
pChipOps->AsicHaltAction = RT30xxHaltAction;
#ifdef RT3070
if ((IS_RT3070(pAd) || IS_RT3071(pAd))
&& (pAd->infType == RTMP_DEV_INF_USB)) {
pChipOps->AsicRfInit = NICInitRT3070RFRegisters;
if (IS_RT3071(pAd)) {
pChipOps->AsicRfTurnOff =
RT30xxLoadRFSleepModeSetup;
pChipOps->AsicReverseRfFromSleepMode =
RT30xxReverseRFSleepModeSetup;
}
}
#endif /* RT3070 // */
#ifdef RT3090
if (IS_RT3090(pAd) && (pAd->infType == RTMP_DEV_INF_PCI)) {
pChipOps->AsicRfTurnOff = RT30xxLoadRFSleepModeSetup;
pChipOps->AsicRfInit = NICInitRT3090RFRegisters;
pChipOps->AsicReverseRfFromSleepMode =
RT30xxReverseRFSleepModeSetup;
}
#endif /* RT3090 // */
}
#endif /* RT30xx // */
}
#endif /* RTMP_RF_RW_SUPPORT // */
| gpl-2.0 |
martingkelly/nunchuk | sound/soc/pxa/mmp-sspa.c | 1052 | 12277 | /*
* linux/sound/soc/pxa/mmp-sspa.c
* Base on pxa2xx-ssp.c
*
* Copyright (C) 2011 Marvell 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/slab.h>
#include <linux/pxa2xx_ssp.h>
#include <linux/io.h>
#include <linux/dmaengine.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/pxa2xx-lib.h>
#include <sound/dmaengine_pcm.h>
#include "mmp-sspa.h"
/*
* SSPA audio private data
*/
struct sspa_priv {
struct ssp_device *sspa;
struct snd_dmaengine_dai_dma_data *dma_params;
struct clk *audio_clk;
struct clk *sysclk;
int dai_fmt;
int running_cnt;
};
static void mmp_sspa_write_reg(struct ssp_device *sspa, u32 reg, u32 val)
{
__raw_writel(val, sspa->mmio_base + reg);
}
static u32 mmp_sspa_read_reg(struct ssp_device *sspa, u32 reg)
{
return __raw_readl(sspa->mmio_base + reg);
}
static void mmp_sspa_tx_enable(struct ssp_device *sspa)
{
unsigned int sspa_sp;
sspa_sp = mmp_sspa_read_reg(sspa, SSPA_TXSP);
sspa_sp |= SSPA_SP_S_EN;
sspa_sp |= SSPA_SP_WEN;
mmp_sspa_write_reg(sspa, SSPA_TXSP, sspa_sp);
}
static void mmp_sspa_tx_disable(struct ssp_device *sspa)
{
unsigned int sspa_sp;
sspa_sp = mmp_sspa_read_reg(sspa, SSPA_TXSP);
sspa_sp &= ~SSPA_SP_S_EN;
sspa_sp |= SSPA_SP_WEN;
mmp_sspa_write_reg(sspa, SSPA_TXSP, sspa_sp);
}
static void mmp_sspa_rx_enable(struct ssp_device *sspa)
{
unsigned int sspa_sp;
sspa_sp = mmp_sspa_read_reg(sspa, SSPA_RXSP);
sspa_sp |= SSPA_SP_S_EN;
sspa_sp |= SSPA_SP_WEN;
mmp_sspa_write_reg(sspa, SSPA_RXSP, sspa_sp);
}
static void mmp_sspa_rx_disable(struct ssp_device *sspa)
{
unsigned int sspa_sp;
sspa_sp = mmp_sspa_read_reg(sspa, SSPA_RXSP);
sspa_sp &= ~SSPA_SP_S_EN;
sspa_sp |= SSPA_SP_WEN;
mmp_sspa_write_reg(sspa, SSPA_RXSP, sspa_sp);
}
static int mmp_sspa_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct sspa_priv *priv = snd_soc_dai_get_drvdata(dai);
clk_enable(priv->sysclk);
clk_enable(priv->sspa->clk);
return 0;
}
static void mmp_sspa_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct sspa_priv *priv = snd_soc_dai_get_drvdata(dai);
clk_disable(priv->sspa->clk);
clk_disable(priv->sysclk);
return;
}
/*
* Set the SSP ports SYSCLK.
*/
static int mmp_sspa_set_dai_sysclk(struct snd_soc_dai *cpu_dai,
int clk_id, unsigned int freq, int dir)
{
struct sspa_priv *priv = snd_soc_dai_get_drvdata(cpu_dai);
int ret = 0;
switch (clk_id) {
case MMP_SSPA_CLK_AUDIO:
ret = clk_set_rate(priv->audio_clk, freq);
if (ret)
return ret;
break;
case MMP_SSPA_CLK_PLL:
case MMP_SSPA_CLK_VCXO:
/* not support yet */
return -EINVAL;
default:
return -EINVAL;
}
return 0;
}
static int mmp_sspa_set_dai_pll(struct snd_soc_dai *cpu_dai, int pll_id,
int source, unsigned int freq_in,
unsigned int freq_out)
{
struct sspa_priv *priv = snd_soc_dai_get_drvdata(cpu_dai);
int ret = 0;
switch (pll_id) {
case MMP_SYSCLK:
ret = clk_set_rate(priv->sysclk, freq_out);
if (ret)
return ret;
break;
case MMP_SSPA_CLK:
ret = clk_set_rate(priv->sspa->clk, freq_out);
if (ret)
return ret;
break;
default:
return -ENODEV;
}
return 0;
}
/*
* Set up the sspa dai format. The sspa port must be inactive
* before calling this function as the physical
* interface format is changed.
*/
static int mmp_sspa_set_dai_fmt(struct snd_soc_dai *cpu_dai,
unsigned int fmt)
{
struct sspa_priv *sspa_priv = snd_soc_dai_get_drvdata(cpu_dai);
struct ssp_device *sspa = sspa_priv->sspa;
u32 sspa_sp, sspa_ctrl;
/* check if we need to change anything at all */
if (sspa_priv->dai_fmt == fmt)
return 0;
/* we can only change the settings if the port is not in use */
if ((mmp_sspa_read_reg(sspa, SSPA_TXSP) & SSPA_SP_S_EN) ||
(mmp_sspa_read_reg(sspa, SSPA_RXSP) & SSPA_SP_S_EN)) {
dev_err(&sspa->pdev->dev,
"can't change hardware dai format: stream is in use\n");
return -EINVAL;
}
/* reset port settings */
sspa_sp = SSPA_SP_WEN | SSPA_SP_S_RST | SSPA_SP_FFLUSH;
sspa_ctrl = 0;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
sspa_sp |= SSPA_SP_MSL;
break;
case SND_SOC_DAIFMT_CBM_CFM:
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
sspa_sp |= SSPA_SP_FSP;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
sspa_sp |= SSPA_TXSP_FPER(63);
sspa_sp |= SSPA_SP_FWID(31);
sspa_ctrl |= SSPA_CTL_XDATDLY(1);
break;
default:
return -EINVAL;
}
mmp_sspa_write_reg(sspa, SSPA_TXSP, sspa_sp);
mmp_sspa_write_reg(sspa, SSPA_RXSP, sspa_sp);
sspa_sp &= ~(SSPA_SP_S_RST | SSPA_SP_FFLUSH);
mmp_sspa_write_reg(sspa, SSPA_TXSP, sspa_sp);
mmp_sspa_write_reg(sspa, SSPA_RXSP, sspa_sp);
/*
* FIXME: hw issue, for the tx serial port,
* can not config the master/slave mode;
* so must clean this bit.
* The master/slave mode has been set in the
* rx port.
*/
sspa_sp &= ~SSPA_SP_MSL;
mmp_sspa_write_reg(sspa, SSPA_TXSP, sspa_sp);
mmp_sspa_write_reg(sspa, SSPA_TXCTL, sspa_ctrl);
mmp_sspa_write_reg(sspa, SSPA_RXCTL, sspa_ctrl);
/* Since we are configuring the timings for the format by hand
* we have to defer some things until hw_params() where we
* know parameters like the sample size.
*/
sspa_priv->dai_fmt = fmt;
return 0;
}
/*
* Set the SSPA audio DMA parameters and sample size.
* Can be called multiple times by oss emulation.
*/
static int mmp_sspa_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
struct sspa_priv *sspa_priv = snd_soc_dai_get_drvdata(dai);
struct ssp_device *sspa = sspa_priv->sspa;
struct snd_dmaengine_dai_dma_data *dma_params;
u32 sspa_ctrl;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
sspa_ctrl = mmp_sspa_read_reg(sspa, SSPA_TXCTL);
else
sspa_ctrl = mmp_sspa_read_reg(sspa, SSPA_RXCTL);
sspa_ctrl &= ~SSPA_CTL_XFRLEN1_MASK;
sspa_ctrl |= SSPA_CTL_XFRLEN1(params_channels(params) - 1);
sspa_ctrl &= ~SSPA_CTL_XWDLEN1_MASK;
sspa_ctrl |= SSPA_CTL_XWDLEN1(SSPA_CTL_32_BITS);
sspa_ctrl &= ~SSPA_CTL_XSSZ1_MASK;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S8:
sspa_ctrl |= SSPA_CTL_XSSZ1(SSPA_CTL_8_BITS);
break;
case SNDRV_PCM_FORMAT_S16_LE:
sspa_ctrl |= SSPA_CTL_XSSZ1(SSPA_CTL_16_BITS);
break;
case SNDRV_PCM_FORMAT_S20_3LE:
sspa_ctrl |= SSPA_CTL_XSSZ1(SSPA_CTL_20_BITS);
break;
case SNDRV_PCM_FORMAT_S24_3LE:
sspa_ctrl |= SSPA_CTL_XSSZ1(SSPA_CTL_24_BITS);
break;
case SNDRV_PCM_FORMAT_S32_LE:
sspa_ctrl |= SSPA_CTL_XSSZ1(SSPA_CTL_32_BITS);
break;
default:
return -EINVAL;
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
mmp_sspa_write_reg(sspa, SSPA_TXCTL, sspa_ctrl);
mmp_sspa_write_reg(sspa, SSPA_TXFIFO_LL, 0x1);
} else {
mmp_sspa_write_reg(sspa, SSPA_RXCTL, sspa_ctrl);
mmp_sspa_write_reg(sspa, SSPA_RXFIFO_UL, 0x0);
}
dma_params = &sspa_priv->dma_params[substream->stream];
dma_params->addr = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ?
(sspa->phys_base + SSPA_TXD) :
(sspa->phys_base + SSPA_RXD);
snd_soc_dai_set_dma_data(cpu_dai, substream, dma_params);
return 0;
}
static int mmp_sspa_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct sspa_priv *sspa_priv = snd_soc_dai_get_drvdata(dai);
struct ssp_device *sspa = sspa_priv->sspa;
int ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
/*
* whatever playback or capture, must enable rx.
* this is a hw issue, so need check if rx has been
* enabled or not; if has been enabled by another
* stream, do not enable again.
*/
if (!sspa_priv->running_cnt)
mmp_sspa_rx_enable(sspa);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
mmp_sspa_tx_enable(sspa);
sspa_priv->running_cnt++;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
sspa_priv->running_cnt--;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
mmp_sspa_tx_disable(sspa);
/* have no capture stream, disable rx port */
if (!sspa_priv->running_cnt)
mmp_sspa_rx_disable(sspa);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int mmp_sspa_probe(struct snd_soc_dai *dai)
{
struct sspa_priv *priv = dev_get_drvdata(dai->dev);
snd_soc_dai_set_drvdata(dai, priv);
return 0;
}
#define MMP_SSPA_RATES SNDRV_PCM_RATE_8000_192000
#define MMP_SSPA_FORMATS (SNDRV_PCM_FMTBIT_S8 | \
SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S24_LE | \
SNDRV_PCM_FMTBIT_S24_LE | \
SNDRV_PCM_FMTBIT_S32_LE)
static struct snd_soc_dai_ops mmp_sspa_dai_ops = {
.startup = mmp_sspa_startup,
.shutdown = mmp_sspa_shutdown,
.trigger = mmp_sspa_trigger,
.hw_params = mmp_sspa_hw_params,
.set_sysclk = mmp_sspa_set_dai_sysclk,
.set_pll = mmp_sspa_set_dai_pll,
.set_fmt = mmp_sspa_set_dai_fmt,
};
static struct snd_soc_dai_driver mmp_sspa_dai = {
.probe = mmp_sspa_probe,
.playback = {
.channels_min = 1,
.channels_max = 128,
.rates = MMP_SSPA_RATES,
.formats = MMP_SSPA_FORMATS,
},
.capture = {
.channels_min = 1,
.channels_max = 2,
.rates = MMP_SSPA_RATES,
.formats = MMP_SSPA_FORMATS,
},
.ops = &mmp_sspa_dai_ops,
};
static const struct snd_soc_component_driver mmp_sspa_component = {
.name = "mmp-sspa",
};
static int asoc_mmp_sspa_probe(struct platform_device *pdev)
{
struct sspa_priv *priv;
struct resource *res;
priv = devm_kzalloc(&pdev->dev,
sizeof(struct sspa_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->sspa = devm_kzalloc(&pdev->dev,
sizeof(struct ssp_device), GFP_KERNEL);
if (priv->sspa == NULL)
return -ENOMEM;
priv->dma_params = devm_kzalloc(&pdev->dev,
2 * sizeof(struct snd_dmaengine_dai_dma_data),
GFP_KERNEL);
if (priv->dma_params == NULL)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
priv->sspa->mmio_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(priv->sspa->mmio_base))
return PTR_ERR(priv->sspa->mmio_base);
priv->sspa->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(priv->sspa->clk))
return PTR_ERR(priv->sspa->clk);
priv->audio_clk = clk_get(NULL, "mmp-audio");
if (IS_ERR(priv->audio_clk))
return PTR_ERR(priv->audio_clk);
priv->sysclk = clk_get(NULL, "mmp-sysclk");
if (IS_ERR(priv->sysclk)) {
clk_put(priv->audio_clk);
return PTR_ERR(priv->sysclk);
}
clk_enable(priv->audio_clk);
priv->dai_fmt = (unsigned int) -1;
platform_set_drvdata(pdev, priv);
return devm_snd_soc_register_component(&pdev->dev, &mmp_sspa_component,
&mmp_sspa_dai, 1);
}
static int asoc_mmp_sspa_remove(struct platform_device *pdev)
{
struct sspa_priv *priv = platform_get_drvdata(pdev);
clk_disable(priv->audio_clk);
clk_put(priv->audio_clk);
clk_put(priv->sysclk);
return 0;
}
static struct platform_driver asoc_mmp_sspa_driver = {
.driver = {
.name = "mmp-sspa-dai",
},
.probe = asoc_mmp_sspa_probe,
.remove = asoc_mmp_sspa_remove,
};
module_platform_driver(asoc_mmp_sspa_driver);
MODULE_AUTHOR("Leo Yan <leoy@marvell.com>");
MODULE_DESCRIPTION("MMP SSPA SoC Interface");
MODULE_LICENSE("GPL");
| gpl-2.0 |
verygreen/green_kernel_omap | arch/arm/mach-kirkwood/common.c | 1564 | 14958 | /*
* arch/arm/mach-kirkwood/common.c
*
* Core functions for Marvell Kirkwood SoCs
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/serial_8250.h>
#include <linux/mbus.h>
#include <linux/ata_platform.h>
#include <linux/mtd/nand.h>
#include <linux/dma-mapping.h>
#include <net/dsa.h>
#include <asm/page.h>
#include <asm/timex.h>
#include <asm/kexec.h>
#include <asm/mach/map.h>
#include <asm/mach/time.h>
#include <mach/kirkwood.h>
#include <mach/bridge-regs.h>
#include <plat/audio.h>
#include <plat/cache-feroceon-l2.h>
#include <plat/mvsdio.h>
#include <plat/orion_nand.h>
#include <plat/ehci-orion.h>
#include <plat/common.h>
#include <plat/time.h>
#include "common.h"
/*****************************************************************************
* I/O Address Mapping
****************************************************************************/
static struct map_desc kirkwood_io_desc[] __initdata = {
{
.virtual = KIRKWOOD_PCIE_IO_VIRT_BASE,
.pfn = __phys_to_pfn(KIRKWOOD_PCIE_IO_PHYS_BASE),
.length = KIRKWOOD_PCIE_IO_SIZE,
.type = MT_DEVICE,
}, {
.virtual = KIRKWOOD_PCIE1_IO_VIRT_BASE,
.pfn = __phys_to_pfn(KIRKWOOD_PCIE1_IO_PHYS_BASE),
.length = KIRKWOOD_PCIE1_IO_SIZE,
.type = MT_DEVICE,
}, {
.virtual = KIRKWOOD_REGS_VIRT_BASE,
.pfn = __phys_to_pfn(KIRKWOOD_REGS_PHYS_BASE),
.length = KIRKWOOD_REGS_SIZE,
.type = MT_DEVICE,
},
};
void __init kirkwood_map_io(void)
{
iotable_init(kirkwood_io_desc, ARRAY_SIZE(kirkwood_io_desc));
}
/*
* Default clock control bits. Any bit _not_ set in this variable
* will be cleared from the hardware after platform devices have been
* registered. Some reserved bits must be set to 1.
*/
unsigned int kirkwood_clk_ctrl = CGC_DUNIT | CGC_RESERVED;
/*****************************************************************************
* EHCI0
****************************************************************************/
void __init kirkwood_ehci_init(void)
{
kirkwood_clk_ctrl |= CGC_USB0;
orion_ehci_init(&kirkwood_mbus_dram_info,
USB_PHYS_BASE, IRQ_KIRKWOOD_USB, EHCI_PHY_NA);
}
/*****************************************************************************
* GE00
****************************************************************************/
void __init kirkwood_ge00_init(struct mv643xx_eth_platform_data *eth_data)
{
kirkwood_clk_ctrl |= CGC_GE0;
orion_ge00_init(eth_data, &kirkwood_mbus_dram_info,
GE00_PHYS_BASE, IRQ_KIRKWOOD_GE00_SUM,
IRQ_KIRKWOOD_GE00_ERR, kirkwood_tclk);
}
/*****************************************************************************
* GE01
****************************************************************************/
void __init kirkwood_ge01_init(struct mv643xx_eth_platform_data *eth_data)
{
kirkwood_clk_ctrl |= CGC_GE1;
orion_ge01_init(eth_data, &kirkwood_mbus_dram_info,
GE01_PHYS_BASE, IRQ_KIRKWOOD_GE01_SUM,
IRQ_KIRKWOOD_GE01_ERR, kirkwood_tclk);
}
/*****************************************************************************
* Ethernet switch
****************************************************************************/
void __init kirkwood_ge00_switch_init(struct dsa_platform_data *d, int irq)
{
orion_ge00_switch_init(d, irq);
}
/*****************************************************************************
* NAND flash
****************************************************************************/
static struct resource kirkwood_nand_resource = {
.flags = IORESOURCE_MEM,
.start = KIRKWOOD_NAND_MEM_PHYS_BASE,
.end = KIRKWOOD_NAND_MEM_PHYS_BASE +
KIRKWOOD_NAND_MEM_SIZE - 1,
};
static struct orion_nand_data kirkwood_nand_data = {
.cle = 0,
.ale = 1,
.width = 8,
};
static struct platform_device kirkwood_nand_flash = {
.name = "orion_nand",
.id = -1,
.dev = {
.platform_data = &kirkwood_nand_data,
},
.resource = &kirkwood_nand_resource,
.num_resources = 1,
};
void __init kirkwood_nand_init(struct mtd_partition *parts, int nr_parts,
int chip_delay)
{
kirkwood_clk_ctrl |= CGC_RUNIT;
kirkwood_nand_data.parts = parts;
kirkwood_nand_data.nr_parts = nr_parts;
kirkwood_nand_data.chip_delay = chip_delay;
platform_device_register(&kirkwood_nand_flash);
}
void __init kirkwood_nand_init_rnb(struct mtd_partition *parts, int nr_parts,
int (*dev_ready)(struct mtd_info *))
{
kirkwood_clk_ctrl |= CGC_RUNIT;
kirkwood_nand_data.parts = parts;
kirkwood_nand_data.nr_parts = nr_parts;
kirkwood_nand_data.dev_ready = dev_ready;
platform_device_register(&kirkwood_nand_flash);
}
/*****************************************************************************
* SoC RTC
****************************************************************************/
static void __init kirkwood_rtc_init(void)
{
orion_rtc_init(RTC_PHYS_BASE, IRQ_KIRKWOOD_RTC);
}
/*****************************************************************************
* SATA
****************************************************************************/
void __init kirkwood_sata_init(struct mv_sata_platform_data *sata_data)
{
kirkwood_clk_ctrl |= CGC_SATA0;
if (sata_data->n_ports > 1)
kirkwood_clk_ctrl |= CGC_SATA1;
orion_sata_init(sata_data, &kirkwood_mbus_dram_info,
SATA_PHYS_BASE, IRQ_KIRKWOOD_SATA);
}
/*****************************************************************************
* SD/SDIO/MMC
****************************************************************************/
static struct resource mvsdio_resources[] = {
[0] = {
.start = SDIO_PHYS_BASE,
.end = SDIO_PHYS_BASE + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_KIRKWOOD_SDIO,
.end = IRQ_KIRKWOOD_SDIO,
.flags = IORESOURCE_IRQ,
},
};
static u64 mvsdio_dmamask = DMA_BIT_MASK(32);
static struct platform_device kirkwood_sdio = {
.name = "mvsdio",
.id = -1,
.dev = {
.dma_mask = &mvsdio_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.num_resources = ARRAY_SIZE(mvsdio_resources),
.resource = mvsdio_resources,
};
void __init kirkwood_sdio_init(struct mvsdio_platform_data *mvsdio_data)
{
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
if (rev == 0 && dev != MV88F6282_DEV_ID) /* catch all Kirkwood Z0's */
mvsdio_data->clock = 100000000;
else
mvsdio_data->clock = 200000000;
mvsdio_data->dram = &kirkwood_mbus_dram_info;
kirkwood_clk_ctrl |= CGC_SDIO;
kirkwood_sdio.dev.platform_data = mvsdio_data;
platform_device_register(&kirkwood_sdio);
}
/*****************************************************************************
* SPI
****************************************************************************/
void __init kirkwood_spi_init()
{
kirkwood_clk_ctrl |= CGC_RUNIT;
orion_spi_init(SPI_PHYS_BASE, kirkwood_tclk);
}
/*****************************************************************************
* I2C
****************************************************************************/
void __init kirkwood_i2c_init(void)
{
orion_i2c_init(I2C_PHYS_BASE, IRQ_KIRKWOOD_TWSI, 8);
}
/*****************************************************************************
* UART0
****************************************************************************/
void __init kirkwood_uart0_init(void)
{
orion_uart0_init(UART0_VIRT_BASE, UART0_PHYS_BASE,
IRQ_KIRKWOOD_UART_0, kirkwood_tclk);
}
/*****************************************************************************
* UART1
****************************************************************************/
void __init kirkwood_uart1_init(void)
{
orion_uart1_init(UART1_VIRT_BASE, UART1_PHYS_BASE,
IRQ_KIRKWOOD_UART_1, kirkwood_tclk);
}
/*****************************************************************************
* Cryptographic Engines and Security Accelerator (CESA)
****************************************************************************/
void __init kirkwood_crypto_init(void)
{
kirkwood_clk_ctrl |= CGC_CRYPTO;
orion_crypto_init(CRYPTO_PHYS_BASE, KIRKWOOD_SRAM_PHYS_BASE,
KIRKWOOD_SRAM_SIZE, IRQ_KIRKWOOD_CRYPTO);
}
/*****************************************************************************
* XOR0
****************************************************************************/
static void __init kirkwood_xor0_init(void)
{
kirkwood_clk_ctrl |= CGC_XOR0;
orion_xor0_init(&kirkwood_mbus_dram_info,
XOR0_PHYS_BASE, XOR0_HIGH_PHYS_BASE,
IRQ_KIRKWOOD_XOR_00, IRQ_KIRKWOOD_XOR_01);
}
/*****************************************************************************
* XOR1
****************************************************************************/
static void __init kirkwood_xor1_init(void)
{
kirkwood_clk_ctrl |= CGC_XOR1;
orion_xor1_init(XOR1_PHYS_BASE, XOR1_HIGH_PHYS_BASE,
IRQ_KIRKWOOD_XOR_10, IRQ_KIRKWOOD_XOR_11);
}
/*****************************************************************************
* Watchdog
****************************************************************************/
static void __init kirkwood_wdt_init(void)
{
orion_wdt_init(kirkwood_tclk);
}
/*****************************************************************************
* Time handling
****************************************************************************/
void __init kirkwood_init_early(void)
{
orion_time_set_base(TIMER_VIRT_BASE);
}
int kirkwood_tclk;
static int __init kirkwood_find_tclk(void)
{
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
if (dev == MV88F6281_DEV_ID || dev == MV88F6282_DEV_ID)
if (((readl(SAMPLE_AT_RESET) >> 21) & 1) == 0)
return 200000000;
return 166666667;
}
static void __init kirkwood_timer_init(void)
{
kirkwood_tclk = kirkwood_find_tclk();
orion_time_init(BRIDGE_VIRT_BASE, BRIDGE_INT_TIMER1_CLR,
IRQ_KIRKWOOD_BRIDGE, kirkwood_tclk);
}
struct sys_timer kirkwood_timer = {
.init = kirkwood_timer_init,
};
/*****************************************************************************
* Audio
****************************************************************************/
static struct resource kirkwood_i2s_resources[] = {
[0] = {
.start = AUDIO_PHYS_BASE,
.end = AUDIO_PHYS_BASE + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_KIRKWOOD_I2S,
.end = IRQ_KIRKWOOD_I2S,
.flags = IORESOURCE_IRQ,
},
};
static struct kirkwood_asoc_platform_data kirkwood_i2s_data = {
.dram = &kirkwood_mbus_dram_info,
.burst = 128,
};
static struct platform_device kirkwood_i2s_device = {
.name = "kirkwood-i2s",
.id = -1,
.num_resources = ARRAY_SIZE(kirkwood_i2s_resources),
.resource = kirkwood_i2s_resources,
.dev = {
.platform_data = &kirkwood_i2s_data,
},
};
static struct platform_device kirkwood_pcm_device = {
.name = "kirkwood-pcm-audio",
.id = -1,
};
void __init kirkwood_audio_init(void)
{
kirkwood_clk_ctrl |= CGC_AUDIO;
platform_device_register(&kirkwood_i2s_device);
platform_device_register(&kirkwood_pcm_device);
}
/*****************************************************************************
* General
****************************************************************************/
/*
* Identify device ID and revision.
*/
static char * __init kirkwood_id(void)
{
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
if (dev == MV88F6281_DEV_ID) {
if (rev == MV88F6281_REV_Z0)
return "MV88F6281-Z0";
else if (rev == MV88F6281_REV_A0)
return "MV88F6281-A0";
else if (rev == MV88F6281_REV_A1)
return "MV88F6281-A1";
else
return "MV88F6281-Rev-Unsupported";
} else if (dev == MV88F6192_DEV_ID) {
if (rev == MV88F6192_REV_Z0)
return "MV88F6192-Z0";
else if (rev == MV88F6192_REV_A0)
return "MV88F6192-A0";
else if (rev == MV88F6192_REV_A1)
return "MV88F6192-A1";
else
return "MV88F6192-Rev-Unsupported";
} else if (dev == MV88F6180_DEV_ID) {
if (rev == MV88F6180_REV_A0)
return "MV88F6180-Rev-A0";
else if (rev == MV88F6180_REV_A1)
return "MV88F6180-Rev-A1";
else
return "MV88F6180-Rev-Unsupported";
} else if (dev == MV88F6282_DEV_ID) {
if (rev == MV88F6282_REV_A0)
return "MV88F6282-Rev-A0";
else
return "MV88F6282-Rev-Unsupported";
} else {
return "Device-Unknown";
}
}
static void __init kirkwood_l2_init(void)
{
#ifdef CONFIG_CACHE_FEROCEON_L2_WRITETHROUGH
writel(readl(L2_CONFIG_REG) | L2_WRITETHROUGH, L2_CONFIG_REG);
feroceon_l2_init(1);
#else
writel(readl(L2_CONFIG_REG) & ~L2_WRITETHROUGH, L2_CONFIG_REG);
feroceon_l2_init(0);
#endif
}
void __init kirkwood_init(void)
{
printk(KERN_INFO "Kirkwood: %s, TCLK=%d.\n",
kirkwood_id(), kirkwood_tclk);
kirkwood_i2s_data.tclk = kirkwood_tclk;
/*
* Disable propagation of mbus errors to the CPU local bus,
* as this causes mbus errors (which can occur for example
* for PCI aborts) to throw CPU aborts, which we're not set
* up to deal with.
*/
writel(readl(CPU_CONFIG) & ~CPU_CONFIG_ERROR_PROP, CPU_CONFIG);
kirkwood_setup_cpu_mbus();
#ifdef CONFIG_CACHE_FEROCEON_L2
kirkwood_l2_init();
#endif
/* internal devices that every board has */
kirkwood_rtc_init();
kirkwood_wdt_init();
kirkwood_xor0_init();
kirkwood_xor1_init();
kirkwood_crypto_init();
#ifdef CONFIG_KEXEC
kexec_reinit = kirkwood_enable_pcie;
#endif
}
static int __init kirkwood_clock_gate(void)
{
unsigned int curr = readl(CLOCK_GATING_CTRL);
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
printk(KERN_DEBUG "Gating clock of unused units\n");
printk(KERN_DEBUG "before: 0x%08x\n", curr);
/* Make sure those units are accessible */
writel(curr | CGC_SATA0 | CGC_SATA1 | CGC_PEX0 | CGC_PEX1, CLOCK_GATING_CTRL);
/* For SATA: first shutdown the phy */
if (!(kirkwood_clk_ctrl & CGC_SATA0)) {
/* Disable PLL and IVREF */
writel(readl(SATA0_PHY_MODE_2) & ~0xf, SATA0_PHY_MODE_2);
/* Disable PHY */
writel(readl(SATA0_IF_CTRL) | 0x200, SATA0_IF_CTRL);
}
if (!(kirkwood_clk_ctrl & CGC_SATA1)) {
/* Disable PLL and IVREF */
writel(readl(SATA1_PHY_MODE_2) & ~0xf, SATA1_PHY_MODE_2);
/* Disable PHY */
writel(readl(SATA1_IF_CTRL) | 0x200, SATA1_IF_CTRL);
}
/* For PCIe: first shutdown the phy */
if (!(kirkwood_clk_ctrl & CGC_PEX0)) {
writel(readl(PCIE_LINK_CTRL) | 0x10, PCIE_LINK_CTRL);
while (1)
if (readl(PCIE_STATUS) & 0x1)
break;
writel(readl(PCIE_LINK_CTRL) & ~0x10, PCIE_LINK_CTRL);
}
/* For PCIe 1: first shutdown the phy */
if (dev == MV88F6282_DEV_ID) {
if (!(kirkwood_clk_ctrl & CGC_PEX1)) {
writel(readl(PCIE1_LINK_CTRL) | 0x10, PCIE1_LINK_CTRL);
while (1)
if (readl(PCIE1_STATUS) & 0x1)
break;
writel(readl(PCIE1_LINK_CTRL) & ~0x10, PCIE1_LINK_CTRL);
}
} else /* keep this bit set for devices that don't have PCIe1 */
kirkwood_clk_ctrl |= CGC_PEX1;
/* Now gate clock the required units */
writel(kirkwood_clk_ctrl, CLOCK_GATING_CTRL);
printk(KERN_DEBUG " after: 0x%08x\n", readl(CLOCK_GATING_CTRL));
return 0;
}
late_initcall(kirkwood_clock_gate);
| gpl-2.0 |
Surge1223/android_kernel_moto_shamu | fs/ceph/inode.c | 1564 | 51450 | #include <linux/ceph/ceph_debug.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/namei.h>
#include <linux/writeback.h>
#include <linux/vmalloc.h>
#include "super.h"
#include "mds_client.h"
#include <linux/ceph/decode.h>
/*
* Ceph inode operations
*
* Implement basic inode helpers (get, alloc) and inode ops (getattr,
* setattr, etc.), xattr helpers, and helpers for assimilating
* metadata returned by the MDS into our cache.
*
* Also define helpers for doing asynchronous writeback, invalidation,
* and truncation for the benefit of those who can't afford to block
* (typically because they are in the message handler path).
*/
static const struct inode_operations ceph_symlink_iops;
static void ceph_invalidate_work(struct work_struct *work);
static void ceph_writeback_work(struct work_struct *work);
static void ceph_vmtruncate_work(struct work_struct *work);
/*
* find or create an inode, given the ceph ino number
*/
static int ceph_set_ino_cb(struct inode *inode, void *data)
{
ceph_inode(inode)->i_vino = *(struct ceph_vino *)data;
inode->i_ino = ceph_vino_to_ino(*(struct ceph_vino *)data);
return 0;
}
struct inode *ceph_get_inode(struct super_block *sb, struct ceph_vino vino)
{
struct inode *inode;
ino_t t = ceph_vino_to_ino(vino);
inode = iget5_locked(sb, t, ceph_ino_compare, ceph_set_ino_cb, &vino);
if (inode == NULL)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
dout("get_inode created new inode %p %llx.%llx ino %llx\n",
inode, ceph_vinop(inode), (u64)inode->i_ino);
unlock_new_inode(inode);
}
dout("get_inode on %lu=%llx.%llx got %p\n", inode->i_ino, vino.ino,
vino.snap, inode);
return inode;
}
/*
* get/constuct snapdir inode for a given directory
*/
struct inode *ceph_get_snapdir(struct inode *parent)
{
struct ceph_vino vino = {
.ino = ceph_ino(parent),
.snap = CEPH_SNAPDIR,
};
struct inode *inode = ceph_get_inode(parent->i_sb, vino);
struct ceph_inode_info *ci = ceph_inode(inode);
BUG_ON(!S_ISDIR(parent->i_mode));
if (IS_ERR(inode))
return inode;
inode->i_mode = parent->i_mode;
inode->i_uid = parent->i_uid;
inode->i_gid = parent->i_gid;
inode->i_op = &ceph_dir_iops;
inode->i_fop = &ceph_dir_fops;
ci->i_snap_caps = CEPH_CAP_PIN; /* so we can open */
ci->i_rbytes = 0;
return inode;
}
const struct inode_operations ceph_file_iops = {
.permission = ceph_permission,
.setattr = ceph_setattr,
.getattr = ceph_getattr,
.setxattr = ceph_setxattr,
.getxattr = ceph_getxattr,
.listxattr = ceph_listxattr,
.removexattr = ceph_removexattr,
};
/*
* We use a 'frag tree' to keep track of the MDS's directory fragments
* for a given inode (usually there is just a single fragment). We
* need to know when a child frag is delegated to a new MDS, or when
* it is flagged as replicated, so we can direct our requests
* accordingly.
*/
/*
* find/create a frag in the tree
*/
static struct ceph_inode_frag *__get_or_create_frag(struct ceph_inode_info *ci,
u32 f)
{
struct rb_node **p;
struct rb_node *parent = NULL;
struct ceph_inode_frag *frag;
int c;
p = &ci->i_fragtree.rb_node;
while (*p) {
parent = *p;
frag = rb_entry(parent, struct ceph_inode_frag, node);
c = ceph_frag_compare(f, frag->frag);
if (c < 0)
p = &(*p)->rb_left;
else if (c > 0)
p = &(*p)->rb_right;
else
return frag;
}
frag = kmalloc(sizeof(*frag), GFP_NOFS);
if (!frag) {
pr_err("__get_or_create_frag ENOMEM on %p %llx.%llx "
"frag %x\n", &ci->vfs_inode,
ceph_vinop(&ci->vfs_inode), f);
return ERR_PTR(-ENOMEM);
}
frag->frag = f;
frag->split_by = 0;
frag->mds = -1;
frag->ndist = 0;
rb_link_node(&frag->node, parent, p);
rb_insert_color(&frag->node, &ci->i_fragtree);
dout("get_or_create_frag added %llx.%llx frag %x\n",
ceph_vinop(&ci->vfs_inode), f);
return frag;
}
/*
* find a specific frag @f
*/
struct ceph_inode_frag *__ceph_find_frag(struct ceph_inode_info *ci, u32 f)
{
struct rb_node *n = ci->i_fragtree.rb_node;
while (n) {
struct ceph_inode_frag *frag =
rb_entry(n, struct ceph_inode_frag, node);
int c = ceph_frag_compare(f, frag->frag);
if (c < 0)
n = n->rb_left;
else if (c > 0)
n = n->rb_right;
else
return frag;
}
return NULL;
}
/*
* Choose frag containing the given value @v. If @pfrag is
* specified, copy the frag delegation info to the caller if
* it is present.
*/
u32 ceph_choose_frag(struct ceph_inode_info *ci, u32 v,
struct ceph_inode_frag *pfrag,
int *found)
{
u32 t = ceph_frag_make(0, 0);
struct ceph_inode_frag *frag;
unsigned nway, i;
u32 n;
if (found)
*found = 0;
mutex_lock(&ci->i_fragtree_mutex);
while (1) {
WARN_ON(!ceph_frag_contains_value(t, v));
frag = __ceph_find_frag(ci, t);
if (!frag)
break; /* t is a leaf */
if (frag->split_by == 0) {
if (pfrag)
memcpy(pfrag, frag, sizeof(*pfrag));
if (found)
*found = 1;
break;
}
/* choose child */
nway = 1 << frag->split_by;
dout("choose_frag(%x) %x splits by %d (%d ways)\n", v, t,
frag->split_by, nway);
for (i = 0; i < nway; i++) {
n = ceph_frag_make_child(t, frag->split_by, i);
if (ceph_frag_contains_value(n, v)) {
t = n;
break;
}
}
BUG_ON(i == nway);
}
dout("choose_frag(%x) = %x\n", v, t);
mutex_unlock(&ci->i_fragtree_mutex);
return t;
}
/*
* Process dirfrag (delegation) info from the mds. Include leaf
* fragment in tree ONLY if ndist > 0. Otherwise, only
* branches/splits are included in i_fragtree)
*/
static int ceph_fill_dirfrag(struct inode *inode,
struct ceph_mds_reply_dirfrag *dirinfo)
{
struct ceph_inode_info *ci = ceph_inode(inode);
struct ceph_inode_frag *frag;
u32 id = le32_to_cpu(dirinfo->frag);
int mds = le32_to_cpu(dirinfo->auth);
int ndist = le32_to_cpu(dirinfo->ndist);
int i;
int err = 0;
mutex_lock(&ci->i_fragtree_mutex);
if (ndist == 0) {
/* no delegation info needed. */
frag = __ceph_find_frag(ci, id);
if (!frag)
goto out;
if (frag->split_by == 0) {
/* tree leaf, remove */
dout("fill_dirfrag removed %llx.%llx frag %x"
" (no ref)\n", ceph_vinop(inode), id);
rb_erase(&frag->node, &ci->i_fragtree);
kfree(frag);
} else {
/* tree branch, keep and clear */
dout("fill_dirfrag cleared %llx.%llx frag %x"
" referral\n", ceph_vinop(inode), id);
frag->mds = -1;
frag->ndist = 0;
}
goto out;
}
/* find/add this frag to store mds delegation info */
frag = __get_or_create_frag(ci, id);
if (IS_ERR(frag)) {
/* this is not the end of the world; we can continue
with bad/inaccurate delegation info */
pr_err("fill_dirfrag ENOMEM on mds ref %llx.%llx fg %x\n",
ceph_vinop(inode), le32_to_cpu(dirinfo->frag));
err = -ENOMEM;
goto out;
}
frag->mds = mds;
frag->ndist = min_t(u32, ndist, CEPH_MAX_DIRFRAG_REP);
for (i = 0; i < frag->ndist; i++)
frag->dist[i] = le32_to_cpu(dirinfo->dist[i]);
dout("fill_dirfrag %llx.%llx frag %x ndist=%d\n",
ceph_vinop(inode), frag->frag, frag->ndist);
out:
mutex_unlock(&ci->i_fragtree_mutex);
return err;
}
/*
* initialize a newly allocated inode.
*/
struct inode *ceph_alloc_inode(struct super_block *sb)
{
struct ceph_inode_info *ci;
int i;
ci = kmem_cache_alloc(ceph_inode_cachep, GFP_NOFS);
if (!ci)
return NULL;
dout("alloc_inode %p\n", &ci->vfs_inode);
spin_lock_init(&ci->i_ceph_lock);
ci->i_version = 0;
ci->i_time_warp_seq = 0;
ci->i_ceph_flags = 0;
atomic_set(&ci->i_release_count, 1);
atomic_set(&ci->i_complete_count, 0);
ci->i_symlink = NULL;
memset(&ci->i_dir_layout, 0, sizeof(ci->i_dir_layout));
ci->i_fragtree = RB_ROOT;
mutex_init(&ci->i_fragtree_mutex);
ci->i_xattrs.blob = NULL;
ci->i_xattrs.prealloc_blob = NULL;
ci->i_xattrs.dirty = false;
ci->i_xattrs.index = RB_ROOT;
ci->i_xattrs.count = 0;
ci->i_xattrs.names_size = 0;
ci->i_xattrs.vals_size = 0;
ci->i_xattrs.version = 0;
ci->i_xattrs.index_version = 0;
ci->i_caps = RB_ROOT;
ci->i_auth_cap = NULL;
ci->i_dirty_caps = 0;
ci->i_flushing_caps = 0;
INIT_LIST_HEAD(&ci->i_dirty_item);
INIT_LIST_HEAD(&ci->i_flushing_item);
ci->i_cap_flush_seq = 0;
ci->i_cap_flush_last_tid = 0;
memset(&ci->i_cap_flush_tid, 0, sizeof(ci->i_cap_flush_tid));
init_waitqueue_head(&ci->i_cap_wq);
ci->i_hold_caps_min = 0;
ci->i_hold_caps_max = 0;
INIT_LIST_HEAD(&ci->i_cap_delay_list);
ci->i_cap_exporting_mds = 0;
ci->i_cap_exporting_mseq = 0;
ci->i_cap_exporting_issued = 0;
INIT_LIST_HEAD(&ci->i_cap_snaps);
ci->i_head_snapc = NULL;
ci->i_snap_caps = 0;
for (i = 0; i < CEPH_FILE_MODE_NUM; i++)
ci->i_nr_by_mode[i] = 0;
ci->i_truncate_seq = 0;
ci->i_truncate_size = 0;
ci->i_truncate_pending = 0;
ci->i_max_size = 0;
ci->i_reported_size = 0;
ci->i_wanted_max_size = 0;
ci->i_requested_max_size = 0;
ci->i_pin_ref = 0;
ci->i_rd_ref = 0;
ci->i_rdcache_ref = 0;
ci->i_wr_ref = 0;
ci->i_wb_ref = 0;
ci->i_wrbuffer_ref = 0;
ci->i_wrbuffer_ref_head = 0;
ci->i_shared_gen = 0;
ci->i_rdcache_gen = 0;
ci->i_rdcache_revoking = 0;
INIT_LIST_HEAD(&ci->i_unsafe_writes);
INIT_LIST_HEAD(&ci->i_unsafe_dirops);
spin_lock_init(&ci->i_unsafe_lock);
ci->i_snap_realm = NULL;
INIT_LIST_HEAD(&ci->i_snap_realm_item);
INIT_LIST_HEAD(&ci->i_snap_flush_item);
INIT_WORK(&ci->i_wb_work, ceph_writeback_work);
INIT_WORK(&ci->i_pg_inv_work, ceph_invalidate_work);
INIT_WORK(&ci->i_vmtruncate_work, ceph_vmtruncate_work);
return &ci->vfs_inode;
}
static void ceph_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
struct ceph_inode_info *ci = ceph_inode(inode);
kmem_cache_free(ceph_inode_cachep, ci);
}
void ceph_destroy_inode(struct inode *inode)
{
struct ceph_inode_info *ci = ceph_inode(inode);
struct ceph_inode_frag *frag;
struct rb_node *n;
dout("destroy_inode %p ino %llx.%llx\n", inode, ceph_vinop(inode));
ceph_queue_caps_release(inode);
/*
* we may still have a snap_realm reference if there are stray
* caps in i_cap_exporting_issued or i_snap_caps.
*/
if (ci->i_snap_realm) {
struct ceph_mds_client *mdsc =
ceph_sb_to_client(ci->vfs_inode.i_sb)->mdsc;
struct ceph_snap_realm *realm = ci->i_snap_realm;
dout(" dropping residual ref to snap realm %p\n", realm);
spin_lock(&realm->inodes_with_caps_lock);
list_del_init(&ci->i_snap_realm_item);
spin_unlock(&realm->inodes_with_caps_lock);
ceph_put_snap_realm(mdsc, realm);
}
kfree(ci->i_symlink);
while ((n = rb_first(&ci->i_fragtree)) != NULL) {
frag = rb_entry(n, struct ceph_inode_frag, node);
rb_erase(n, &ci->i_fragtree);
kfree(frag);
}
__ceph_destroy_xattrs(ci);
if (ci->i_xattrs.blob)
ceph_buffer_put(ci->i_xattrs.blob);
if (ci->i_xattrs.prealloc_blob)
ceph_buffer_put(ci->i_xattrs.prealloc_blob);
call_rcu(&inode->i_rcu, ceph_i_callback);
}
/*
* Helpers to fill in size, ctime, mtime, and atime. We have to be
* careful because either the client or MDS may have more up to date
* info, depending on which capabilities are held, and whether
* time_warp_seq or truncate_seq have increased. (Ordinarily, mtime
* and size are monotonically increasing, except when utimes() or
* truncate() increments the corresponding _seq values.)
*/
int ceph_fill_file_size(struct inode *inode, int issued,
u32 truncate_seq, u64 truncate_size, u64 size)
{
struct ceph_inode_info *ci = ceph_inode(inode);
int queue_trunc = 0;
if (ceph_seq_cmp(truncate_seq, ci->i_truncate_seq) > 0 ||
(truncate_seq == ci->i_truncate_seq && size > inode->i_size)) {
dout("size %lld -> %llu\n", inode->i_size, size);
inode->i_size = size;
inode->i_blocks = (size + (1<<9) - 1) >> 9;
ci->i_reported_size = size;
if (truncate_seq != ci->i_truncate_seq) {
dout("truncate_seq %u -> %u\n",
ci->i_truncate_seq, truncate_seq);
ci->i_truncate_seq = truncate_seq;
/*
* If we hold relevant caps, or in the case where we're
* not the only client referencing this file and we
* don't hold those caps, then we need to check whether
* the file is either opened or mmaped
*/
if ((issued & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_RD|
CEPH_CAP_FILE_WR|CEPH_CAP_FILE_BUFFER|
CEPH_CAP_FILE_EXCL|
CEPH_CAP_FILE_LAZYIO)) ||
mapping_mapped(inode->i_mapping) ||
__ceph_caps_file_wanted(ci)) {
ci->i_truncate_pending++;
queue_trunc = 1;
}
}
}
if (ceph_seq_cmp(truncate_seq, ci->i_truncate_seq) >= 0 &&
ci->i_truncate_size != truncate_size) {
dout("truncate_size %lld -> %llu\n", ci->i_truncate_size,
truncate_size);
ci->i_truncate_size = truncate_size;
}
return queue_trunc;
}
void ceph_fill_file_time(struct inode *inode, int issued,
u64 time_warp_seq, struct timespec *ctime,
struct timespec *mtime, struct timespec *atime)
{
struct ceph_inode_info *ci = ceph_inode(inode);
int warn = 0;
if (issued & (CEPH_CAP_FILE_EXCL|
CEPH_CAP_FILE_WR|
CEPH_CAP_FILE_BUFFER|
CEPH_CAP_AUTH_EXCL|
CEPH_CAP_XATTR_EXCL)) {
if (timespec_compare(ctime, &inode->i_ctime) > 0) {
dout("ctime %ld.%09ld -> %ld.%09ld inc w/ cap\n",
inode->i_ctime.tv_sec, inode->i_ctime.tv_nsec,
ctime->tv_sec, ctime->tv_nsec);
inode->i_ctime = *ctime;
}
if (ceph_seq_cmp(time_warp_seq, ci->i_time_warp_seq) > 0) {
/* the MDS did a utimes() */
dout("mtime %ld.%09ld -> %ld.%09ld "
"tw %d -> %d\n",
inode->i_mtime.tv_sec, inode->i_mtime.tv_nsec,
mtime->tv_sec, mtime->tv_nsec,
ci->i_time_warp_seq, (int)time_warp_seq);
inode->i_mtime = *mtime;
inode->i_atime = *atime;
ci->i_time_warp_seq = time_warp_seq;
} else if (time_warp_seq == ci->i_time_warp_seq) {
/* nobody did utimes(); take the max */
if (timespec_compare(mtime, &inode->i_mtime) > 0) {
dout("mtime %ld.%09ld -> %ld.%09ld inc\n",
inode->i_mtime.tv_sec,
inode->i_mtime.tv_nsec,
mtime->tv_sec, mtime->tv_nsec);
inode->i_mtime = *mtime;
}
if (timespec_compare(atime, &inode->i_atime) > 0) {
dout("atime %ld.%09ld -> %ld.%09ld inc\n",
inode->i_atime.tv_sec,
inode->i_atime.tv_nsec,
atime->tv_sec, atime->tv_nsec);
inode->i_atime = *atime;
}
} else if (issued & CEPH_CAP_FILE_EXCL) {
/* we did a utimes(); ignore mds values */
} else {
warn = 1;
}
} else {
/* we have no write|excl caps; whatever the MDS says is true */
if (ceph_seq_cmp(time_warp_seq, ci->i_time_warp_seq) >= 0) {
inode->i_ctime = *ctime;
inode->i_mtime = *mtime;
inode->i_atime = *atime;
ci->i_time_warp_seq = time_warp_seq;
} else {
warn = 1;
}
}
if (warn) /* time_warp_seq shouldn't go backwards */
dout("%p mds time_warp_seq %llu < %u\n",
inode, time_warp_seq, ci->i_time_warp_seq);
}
/*
* Populate an inode based on info from mds. May be called on new or
* existing inodes.
*/
static int fill_inode(struct inode *inode,
struct ceph_mds_reply_info_in *iinfo,
struct ceph_mds_reply_dirfrag *dirinfo,
struct ceph_mds_session *session,
unsigned long ttl_from, int cap_fmode,
struct ceph_cap_reservation *caps_reservation)
{
struct ceph_mds_reply_inode *info = iinfo->in;
struct ceph_inode_info *ci = ceph_inode(inode);
int i;
int issued = 0, implemented;
struct timespec mtime, atime, ctime;
u32 nsplits;
struct ceph_buffer *xattr_blob = NULL;
int err = 0;
int queue_trunc = 0;
dout("fill_inode %p ino %llx.%llx v %llu had %llu\n",
inode, ceph_vinop(inode), le64_to_cpu(info->version),
ci->i_version);
/*
* prealloc xattr data, if it looks like we'll need it. only
* if len > 4 (meaning there are actually xattrs; the first 4
* bytes are the xattr count).
*/
if (iinfo->xattr_len > 4) {
xattr_blob = ceph_buffer_new(iinfo->xattr_len, GFP_NOFS);
if (!xattr_blob)
pr_err("fill_inode ENOMEM xattr blob %d bytes\n",
iinfo->xattr_len);
}
spin_lock(&ci->i_ceph_lock);
/*
* provided version will be odd if inode value is projected,
* even if stable. skip the update if we have newer stable
* info (ours>=theirs, e.g. due to racing mds replies), unless
* we are getting projected (unstable) info (in which case the
* version is odd, and we want ours>theirs).
* us them
* 2 2 skip
* 3 2 skip
* 3 3 update
*/
if (le64_to_cpu(info->version) > 0 &&
(ci->i_version & ~1) >= le64_to_cpu(info->version))
goto no_change;
issued = __ceph_caps_issued(ci, &implemented);
issued |= implemented | __ceph_caps_dirty(ci);
/* update inode */
ci->i_version = le64_to_cpu(info->version);
inode->i_version++;
inode->i_rdev = le32_to_cpu(info->rdev);
if ((issued & CEPH_CAP_AUTH_EXCL) == 0) {
inode->i_mode = le32_to_cpu(info->mode);
inode->i_uid = make_kuid(&init_user_ns, le32_to_cpu(info->uid));
inode->i_gid = make_kgid(&init_user_ns, le32_to_cpu(info->gid));
dout("%p mode 0%o uid.gid %d.%d\n", inode, inode->i_mode,
from_kuid(&init_user_ns, inode->i_uid),
from_kgid(&init_user_ns, inode->i_gid));
}
if ((issued & CEPH_CAP_LINK_EXCL) == 0)
set_nlink(inode, le32_to_cpu(info->nlink));
/* be careful with mtime, atime, size */
ceph_decode_timespec(&atime, &info->atime);
ceph_decode_timespec(&mtime, &info->mtime);
ceph_decode_timespec(&ctime, &info->ctime);
queue_trunc = ceph_fill_file_size(inode, issued,
le32_to_cpu(info->truncate_seq),
le64_to_cpu(info->truncate_size),
le64_to_cpu(info->size));
ceph_fill_file_time(inode, issued,
le32_to_cpu(info->time_warp_seq),
&ctime, &mtime, &atime);
/* only update max_size on auth cap */
if ((info->cap.flags & CEPH_CAP_FLAG_AUTH) &&
ci->i_max_size != le64_to_cpu(info->max_size)) {
dout("max_size %lld -> %llu\n", ci->i_max_size,
le64_to_cpu(info->max_size));
ci->i_max_size = le64_to_cpu(info->max_size);
}
ci->i_layout = info->layout;
inode->i_blkbits = fls(le32_to_cpu(info->layout.fl_stripe_unit)) - 1;
/* xattrs */
/* note that if i_xattrs.len <= 4, i_xattrs.data will still be NULL. */
if ((issued & CEPH_CAP_XATTR_EXCL) == 0 &&
le64_to_cpu(info->xattr_version) > ci->i_xattrs.version) {
if (ci->i_xattrs.blob)
ceph_buffer_put(ci->i_xattrs.blob);
ci->i_xattrs.blob = xattr_blob;
if (xattr_blob)
memcpy(ci->i_xattrs.blob->vec.iov_base,
iinfo->xattr_data, iinfo->xattr_len);
ci->i_xattrs.version = le64_to_cpu(info->xattr_version);
xattr_blob = NULL;
}
inode->i_mapping->a_ops = &ceph_aops;
inode->i_mapping->backing_dev_info =
&ceph_sb_to_client(inode->i_sb)->backing_dev_info;
switch (inode->i_mode & S_IFMT) {
case S_IFIFO:
case S_IFBLK:
case S_IFCHR:
case S_IFSOCK:
init_special_inode(inode, inode->i_mode, inode->i_rdev);
inode->i_op = &ceph_file_iops;
break;
case S_IFREG:
inode->i_op = &ceph_file_iops;
inode->i_fop = &ceph_file_fops;
break;
case S_IFLNK:
inode->i_op = &ceph_symlink_iops;
if (!ci->i_symlink) {
u32 symlen = iinfo->symlink_len;
char *sym;
spin_unlock(&ci->i_ceph_lock);
err = -EINVAL;
if (WARN_ON(symlen != inode->i_size))
goto out;
err = -ENOMEM;
sym = kstrndup(iinfo->symlink, symlen, GFP_NOFS);
if (!sym)
goto out;
spin_lock(&ci->i_ceph_lock);
if (!ci->i_symlink)
ci->i_symlink = sym;
else
kfree(sym); /* lost a race */
}
break;
case S_IFDIR:
inode->i_op = &ceph_dir_iops;
inode->i_fop = &ceph_dir_fops;
ci->i_dir_layout = iinfo->dir_layout;
ci->i_files = le64_to_cpu(info->files);
ci->i_subdirs = le64_to_cpu(info->subdirs);
ci->i_rbytes = le64_to_cpu(info->rbytes);
ci->i_rfiles = le64_to_cpu(info->rfiles);
ci->i_rsubdirs = le64_to_cpu(info->rsubdirs);
ceph_decode_timespec(&ci->i_rctime, &info->rctime);
break;
default:
pr_err("fill_inode %llx.%llx BAD mode 0%o\n",
ceph_vinop(inode), inode->i_mode);
}
/* set dir completion flag? */
if (S_ISDIR(inode->i_mode) &&
ci->i_files == 0 && ci->i_subdirs == 0 &&
ceph_snap(inode) == CEPH_NOSNAP &&
(le32_to_cpu(info->cap.caps) & CEPH_CAP_FILE_SHARED) &&
(issued & CEPH_CAP_FILE_EXCL) == 0 &&
!__ceph_dir_is_complete(ci)) {
dout(" marking %p complete (empty)\n", inode);
__ceph_dir_set_complete(ci, atomic_read(&ci->i_release_count));
ci->i_max_offset = 2;
}
no_change:
spin_unlock(&ci->i_ceph_lock);
/* queue truncate if we saw i_size decrease */
if (queue_trunc)
ceph_queue_vmtruncate(inode);
/* populate frag tree */
/* FIXME: move me up, if/when version reflects fragtree changes */
nsplits = le32_to_cpu(info->fragtree.nsplits);
mutex_lock(&ci->i_fragtree_mutex);
for (i = 0; i < nsplits; i++) {
u32 id = le32_to_cpu(info->fragtree.splits[i].frag);
struct ceph_inode_frag *frag = __get_or_create_frag(ci, id);
if (IS_ERR(frag))
continue;
frag->split_by = le32_to_cpu(info->fragtree.splits[i].by);
dout(" frag %x split by %d\n", frag->frag, frag->split_by);
}
mutex_unlock(&ci->i_fragtree_mutex);
/* were we issued a capability? */
if (info->cap.caps) {
if (ceph_snap(inode) == CEPH_NOSNAP) {
ceph_add_cap(inode, session,
le64_to_cpu(info->cap.cap_id),
cap_fmode,
le32_to_cpu(info->cap.caps),
le32_to_cpu(info->cap.wanted),
le32_to_cpu(info->cap.seq),
le32_to_cpu(info->cap.mseq),
le64_to_cpu(info->cap.realm),
info->cap.flags,
caps_reservation);
} else {
spin_lock(&ci->i_ceph_lock);
dout(" %p got snap_caps %s\n", inode,
ceph_cap_string(le32_to_cpu(info->cap.caps)));
ci->i_snap_caps |= le32_to_cpu(info->cap.caps);
if (cap_fmode >= 0)
__ceph_get_fmode(ci, cap_fmode);
spin_unlock(&ci->i_ceph_lock);
}
} else if (cap_fmode >= 0) {
pr_warning("mds issued no caps on %llx.%llx\n",
ceph_vinop(inode));
__ceph_get_fmode(ci, cap_fmode);
}
/* update delegation info? */
if (dirinfo)
ceph_fill_dirfrag(inode, dirinfo);
err = 0;
out:
if (xattr_blob)
ceph_buffer_put(xattr_blob);
return err;
}
/*
* caller should hold session s_mutex.
*/
static void update_dentry_lease(struct dentry *dentry,
struct ceph_mds_reply_lease *lease,
struct ceph_mds_session *session,
unsigned long from_time)
{
struct ceph_dentry_info *di = ceph_dentry(dentry);
long unsigned duration = le32_to_cpu(lease->duration_ms);
long unsigned ttl = from_time + (duration * HZ) / 1000;
long unsigned half_ttl = from_time + (duration * HZ / 2) / 1000;
struct inode *dir;
/* only track leases on regular dentries */
if (dentry->d_op != &ceph_dentry_ops)
return;
spin_lock(&dentry->d_lock);
dout("update_dentry_lease %p duration %lu ms ttl %lu\n",
dentry, duration, ttl);
/* make lease_rdcache_gen match directory */
dir = dentry->d_parent->d_inode;
di->lease_shared_gen = ceph_inode(dir)->i_shared_gen;
if (duration == 0)
goto out_unlock;
if (di->lease_gen == session->s_cap_gen &&
time_before(ttl, dentry->d_time))
goto out_unlock; /* we already have a newer lease. */
if (di->lease_session && di->lease_session != session)
goto out_unlock;
ceph_dentry_lru_touch(dentry);
if (!di->lease_session)
di->lease_session = ceph_get_mds_session(session);
di->lease_gen = session->s_cap_gen;
di->lease_seq = le32_to_cpu(lease->seq);
di->lease_renew_after = half_ttl;
di->lease_renew_from = 0;
dentry->d_time = ttl;
out_unlock:
spin_unlock(&dentry->d_lock);
return;
}
/*
* Set dentry's directory position based on the current dir's max, and
* order it in d_subdirs, so that dcache_readdir behaves.
*
* Always called under directory's i_mutex.
*/
static void ceph_set_dentry_offset(struct dentry *dn)
{
struct dentry *dir = dn->d_parent;
struct inode *inode = dir->d_inode;
struct ceph_inode_info *ci;
struct ceph_dentry_info *di;
BUG_ON(!inode);
ci = ceph_inode(inode);
di = ceph_dentry(dn);
spin_lock(&ci->i_ceph_lock);
if (!__ceph_dir_is_complete(ci)) {
spin_unlock(&ci->i_ceph_lock);
return;
}
di->offset = ceph_inode(inode)->i_max_offset++;
spin_unlock(&ci->i_ceph_lock);
spin_lock(&dir->d_lock);
spin_lock_nested(&dn->d_lock, DENTRY_D_LOCK_NESTED);
list_move(&dn->d_u.d_child, &dir->d_subdirs);
dout("set_dentry_offset %p %lld (%p %p)\n", dn, di->offset,
dn->d_u.d_child.prev, dn->d_u.d_child.next);
spin_unlock(&dn->d_lock);
spin_unlock(&dir->d_lock);
}
/*
* splice a dentry to an inode.
* caller must hold directory i_mutex for this to be safe.
*
* we will only rehash the resulting dentry if @prehash is
* true; @prehash will be set to false (for the benefit of
* the caller) if we fail.
*/
static struct dentry *splice_dentry(struct dentry *dn, struct inode *in,
bool *prehash, bool set_offset)
{
struct dentry *realdn;
BUG_ON(dn->d_inode);
/* dn must be unhashed */
if (!d_unhashed(dn))
d_drop(dn);
realdn = d_materialise_unique(dn, in);
if (IS_ERR(realdn)) {
pr_err("splice_dentry error %ld %p inode %p ino %llx.%llx\n",
PTR_ERR(realdn), dn, in, ceph_vinop(in));
if (prehash)
*prehash = false; /* don't rehash on error */
dn = realdn; /* note realdn contains the error */
goto out;
} else if (realdn) {
dout("dn %p (%d) spliced with %p (%d) "
"inode %p ino %llx.%llx\n",
dn, dn->d_count,
realdn, realdn->d_count,
realdn->d_inode, ceph_vinop(realdn->d_inode));
dput(dn);
dn = realdn;
} else {
BUG_ON(!ceph_dentry(dn));
dout("dn %p attached to %p ino %llx.%llx\n",
dn, dn->d_inode, ceph_vinop(dn->d_inode));
}
if ((!prehash || *prehash) && d_unhashed(dn))
d_rehash(dn);
if (set_offset)
ceph_set_dentry_offset(dn);
out:
return dn;
}
/*
* Incorporate results into the local cache. This is either just
* one inode, or a directory, dentry, and possibly linked-to inode (e.g.,
* after a lookup).
*
* A reply may contain
* a directory inode along with a dentry.
* and/or a target inode
*
* Called with snap_rwsem (read).
*/
int ceph_fill_trace(struct super_block *sb, struct ceph_mds_request *req,
struct ceph_mds_session *session)
{
struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
struct inode *in = NULL;
struct ceph_mds_reply_inode *ininfo;
struct ceph_vino vino;
struct ceph_fs_client *fsc = ceph_sb_to_client(sb);
int i = 0;
int err = 0;
dout("fill_trace %p is_dentry %d is_target %d\n", req,
rinfo->head->is_dentry, rinfo->head->is_target);
#if 0
/*
* Debugging hook:
*
* If we resend completed ops to a recovering mds, we get no
* trace. Since that is very rare, pretend this is the case
* to ensure the 'no trace' handlers in the callers behave.
*
* Fill in inodes unconditionally to avoid breaking cap
* invariants.
*/
if (rinfo->head->op & CEPH_MDS_OP_WRITE) {
pr_info("fill_trace faking empty trace on %lld %s\n",
req->r_tid, ceph_mds_op_name(rinfo->head->op));
if (rinfo->head->is_dentry) {
rinfo->head->is_dentry = 0;
err = fill_inode(req->r_locked_dir,
&rinfo->diri, rinfo->dirfrag,
session, req->r_request_started, -1);
}
if (rinfo->head->is_target) {
rinfo->head->is_target = 0;
ininfo = rinfo->targeti.in;
vino.ino = le64_to_cpu(ininfo->ino);
vino.snap = le64_to_cpu(ininfo->snapid);
in = ceph_get_inode(sb, vino);
err = fill_inode(in, &rinfo->targeti, NULL,
session, req->r_request_started,
req->r_fmode);
iput(in);
}
}
#endif
if (!rinfo->head->is_target && !rinfo->head->is_dentry) {
dout("fill_trace reply is empty!\n");
if (rinfo->head->result == 0 && req->r_locked_dir)
ceph_invalidate_dir_request(req);
return 0;
}
if (rinfo->head->is_dentry) {
struct inode *dir = req->r_locked_dir;
if (dir) {
err = fill_inode(dir, &rinfo->diri, rinfo->dirfrag,
session, req->r_request_started, -1,
&req->r_caps_reservation);
if (err < 0)
return err;
} else {
WARN_ON_ONCE(1);
}
}
/*
* ignore null lease/binding on snapdir ENOENT, or else we
* will have trouble splicing in the virtual snapdir later
*/
if (rinfo->head->is_dentry && !req->r_aborted &&
req->r_locked_dir &&
(rinfo->head->is_target || strncmp(req->r_dentry->d_name.name,
fsc->mount_options->snapdir_name,
req->r_dentry->d_name.len))) {
/*
* lookup link rename : null -> possibly existing inode
* mknod symlink mkdir : null -> new inode
* unlink : linked -> null
*/
struct inode *dir = req->r_locked_dir;
struct dentry *dn = req->r_dentry;
bool have_dir_cap, have_lease;
BUG_ON(!dn);
BUG_ON(!dir);
BUG_ON(dn->d_parent->d_inode != dir);
BUG_ON(ceph_ino(dir) !=
le64_to_cpu(rinfo->diri.in->ino));
BUG_ON(ceph_snap(dir) !=
le64_to_cpu(rinfo->diri.in->snapid));
/* do we have a lease on the whole dir? */
have_dir_cap =
(le32_to_cpu(rinfo->diri.in->cap.caps) &
CEPH_CAP_FILE_SHARED);
/* do we have a dn lease? */
have_lease = have_dir_cap ||
le32_to_cpu(rinfo->dlease->duration_ms);
if (!have_lease)
dout("fill_trace no dentry lease or dir cap\n");
/* rename? */
if (req->r_old_dentry && req->r_op == CEPH_MDS_OP_RENAME) {
dout(" src %p '%.*s' dst %p '%.*s'\n",
req->r_old_dentry,
req->r_old_dentry->d_name.len,
req->r_old_dentry->d_name.name,
dn, dn->d_name.len, dn->d_name.name);
dout("fill_trace doing d_move %p -> %p\n",
req->r_old_dentry, dn);
d_move(req->r_old_dentry, dn);
dout(" src %p '%.*s' dst %p '%.*s'\n",
req->r_old_dentry,
req->r_old_dentry->d_name.len,
req->r_old_dentry->d_name.name,
dn, dn->d_name.len, dn->d_name.name);
/* ensure target dentry is invalidated, despite
rehashing bug in vfs_rename_dir */
ceph_invalidate_dentry_lease(dn);
/*
* d_move() puts the renamed dentry at the end of
* d_subdirs. We need to assign it an appropriate
* directory offset so we can behave when dir is
* complete.
*/
ceph_set_dentry_offset(req->r_old_dentry);
dout("dn %p gets new offset %lld\n", req->r_old_dentry,
ceph_dentry(req->r_old_dentry)->offset);
dn = req->r_old_dentry; /* use old_dentry */
in = dn->d_inode;
}
/* null dentry? */
if (!rinfo->head->is_target) {
dout("fill_trace null dentry\n");
if (dn->d_inode) {
dout("d_delete %p\n", dn);
d_delete(dn);
} else {
dout("d_instantiate %p NULL\n", dn);
d_instantiate(dn, NULL);
if (have_lease && d_unhashed(dn))
d_rehash(dn);
update_dentry_lease(dn, rinfo->dlease,
session,
req->r_request_started);
}
goto done;
}
/* attach proper inode */
ininfo = rinfo->targeti.in;
vino.ino = le64_to_cpu(ininfo->ino);
vino.snap = le64_to_cpu(ininfo->snapid);
in = dn->d_inode;
if (!in) {
in = ceph_get_inode(sb, vino);
if (IS_ERR(in)) {
pr_err("fill_trace bad get_inode "
"%llx.%llx\n", vino.ino, vino.snap);
err = PTR_ERR(in);
d_drop(dn);
goto done;
}
dn = splice_dentry(dn, in, &have_lease, true);
if (IS_ERR(dn)) {
err = PTR_ERR(dn);
goto done;
}
req->r_dentry = dn; /* may have spliced */
ihold(in);
} else if (ceph_ino(in) == vino.ino &&
ceph_snap(in) == vino.snap) {
ihold(in);
} else {
dout(" %p links to %p %llx.%llx, not %llx.%llx\n",
dn, in, ceph_ino(in), ceph_snap(in),
vino.ino, vino.snap);
have_lease = false;
in = NULL;
}
if (have_lease)
update_dentry_lease(dn, rinfo->dlease, session,
req->r_request_started);
dout(" final dn %p\n", dn);
i++;
} else if ((req->r_op == CEPH_MDS_OP_LOOKUPSNAP ||
req->r_op == CEPH_MDS_OP_MKSNAP) && !req->r_aborted) {
struct dentry *dn = req->r_dentry;
/* fill out a snapdir LOOKUPSNAP dentry */
BUG_ON(!dn);
BUG_ON(!req->r_locked_dir);
BUG_ON(ceph_snap(req->r_locked_dir) != CEPH_SNAPDIR);
ininfo = rinfo->targeti.in;
vino.ino = le64_to_cpu(ininfo->ino);
vino.snap = le64_to_cpu(ininfo->snapid);
in = ceph_get_inode(sb, vino);
if (IS_ERR(in)) {
pr_err("fill_inode get_inode badness %llx.%llx\n",
vino.ino, vino.snap);
err = PTR_ERR(in);
d_delete(dn);
goto done;
}
dout(" linking snapped dir %p to dn %p\n", in, dn);
dn = splice_dentry(dn, in, NULL, true);
if (IS_ERR(dn)) {
err = PTR_ERR(dn);
goto done;
}
req->r_dentry = dn; /* may have spliced */
ihold(in);
rinfo->head->is_dentry = 1; /* fool notrace handlers */
}
if (rinfo->head->is_target) {
vino.ino = le64_to_cpu(rinfo->targeti.in->ino);
vino.snap = le64_to_cpu(rinfo->targeti.in->snapid);
if (in == NULL || ceph_ino(in) != vino.ino ||
ceph_snap(in) != vino.snap) {
in = ceph_get_inode(sb, vino);
if (IS_ERR(in)) {
err = PTR_ERR(in);
goto done;
}
}
req->r_target_inode = in;
err = fill_inode(in,
&rinfo->targeti, NULL,
session, req->r_request_started,
(le32_to_cpu(rinfo->head->result) == 0) ?
req->r_fmode : -1,
&req->r_caps_reservation);
if (err < 0) {
pr_err("fill_inode badness %p %llx.%llx\n",
in, ceph_vinop(in));
goto done;
}
}
done:
dout("fill_trace done err=%d\n", err);
return err;
}
/*
* Prepopulate our cache with readdir results, leases, etc.
*/
static int readdir_prepopulate_inodes_only(struct ceph_mds_request *req,
struct ceph_mds_session *session)
{
struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
int i, err = 0;
for (i = 0; i < rinfo->dir_nr; i++) {
struct ceph_vino vino;
struct inode *in;
int rc;
vino.ino = le64_to_cpu(rinfo->dir_in[i].in->ino);
vino.snap = le64_to_cpu(rinfo->dir_in[i].in->snapid);
in = ceph_get_inode(req->r_dentry->d_sb, vino);
if (IS_ERR(in)) {
err = PTR_ERR(in);
dout("new_inode badness got %d\n", err);
continue;
}
rc = fill_inode(in, &rinfo->dir_in[i], NULL, session,
req->r_request_started, -1,
&req->r_caps_reservation);
if (rc < 0) {
pr_err("fill_inode badness on %p got %d\n", in, rc);
err = rc;
continue;
}
}
return err;
}
int ceph_readdir_prepopulate(struct ceph_mds_request *req,
struct ceph_mds_session *session)
{
struct dentry *parent = req->r_dentry;
struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
struct qstr dname;
struct dentry *dn;
struct inode *in;
int err = 0, i;
struct inode *snapdir = NULL;
struct ceph_mds_request_head *rhead = req->r_request->front.iov_base;
u64 frag = le32_to_cpu(rhead->args.readdir.frag);
struct ceph_dentry_info *di;
if (req->r_aborted)
return readdir_prepopulate_inodes_only(req, session);
if (le32_to_cpu(rinfo->head->op) == CEPH_MDS_OP_LSSNAP) {
snapdir = ceph_get_snapdir(parent->d_inode);
parent = d_find_alias(snapdir);
dout("readdir_prepopulate %d items under SNAPDIR dn %p\n",
rinfo->dir_nr, parent);
} else {
dout("readdir_prepopulate %d items under dn %p\n",
rinfo->dir_nr, parent);
if (rinfo->dir_dir)
ceph_fill_dirfrag(parent->d_inode, rinfo->dir_dir);
}
for (i = 0; i < rinfo->dir_nr; i++) {
struct ceph_vino vino;
dname.name = rinfo->dir_dname[i];
dname.len = rinfo->dir_dname_len[i];
dname.hash = full_name_hash(dname.name, dname.len);
vino.ino = le64_to_cpu(rinfo->dir_in[i].in->ino);
vino.snap = le64_to_cpu(rinfo->dir_in[i].in->snapid);
retry_lookup:
dn = d_lookup(parent, &dname);
dout("d_lookup on parent=%p name=%.*s got %p\n",
parent, dname.len, dname.name, dn);
if (!dn) {
dn = d_alloc(parent, &dname);
dout("d_alloc %p '%.*s' = %p\n", parent,
dname.len, dname.name, dn);
if (dn == NULL) {
dout("d_alloc badness\n");
err = -ENOMEM;
goto out;
}
err = ceph_init_dentry(dn);
if (err < 0) {
dput(dn);
goto out;
}
} else if (dn->d_inode &&
(ceph_ino(dn->d_inode) != vino.ino ||
ceph_snap(dn->d_inode) != vino.snap)) {
dout(" dn %p points to wrong inode %p\n",
dn, dn->d_inode);
d_delete(dn);
dput(dn);
goto retry_lookup;
} else {
/* reorder parent's d_subdirs */
spin_lock(&parent->d_lock);
spin_lock_nested(&dn->d_lock, DENTRY_D_LOCK_NESTED);
list_move(&dn->d_u.d_child, &parent->d_subdirs);
spin_unlock(&dn->d_lock);
spin_unlock(&parent->d_lock);
}
di = dn->d_fsdata;
di->offset = ceph_make_fpos(frag, i + req->r_readdir_offset);
/* inode */
if (dn->d_inode) {
in = dn->d_inode;
} else {
in = ceph_get_inode(parent->d_sb, vino);
if (IS_ERR(in)) {
dout("new_inode badness\n");
d_drop(dn);
dput(dn);
err = PTR_ERR(in);
goto out;
}
dn = splice_dentry(dn, in, NULL, false);
if (IS_ERR(dn))
dn = NULL;
}
if (fill_inode(in, &rinfo->dir_in[i], NULL, session,
req->r_request_started, -1,
&req->r_caps_reservation) < 0) {
pr_err("fill_inode badness on %p\n", in);
goto next_item;
}
if (dn)
update_dentry_lease(dn, rinfo->dir_dlease[i],
req->r_session,
req->r_request_started);
next_item:
if (dn)
dput(dn);
}
req->r_did_prepopulate = true;
out:
if (snapdir) {
iput(snapdir);
dput(parent);
}
dout("readdir_prepopulate done\n");
return err;
}
int ceph_inode_set_size(struct inode *inode, loff_t size)
{
struct ceph_inode_info *ci = ceph_inode(inode);
int ret = 0;
spin_lock(&ci->i_ceph_lock);
dout("set_size %p %llu -> %llu\n", inode, inode->i_size, size);
inode->i_size = size;
inode->i_blocks = (size + (1 << 9) - 1) >> 9;
/* tell the MDS if we are approaching max_size */
if ((size << 1) >= ci->i_max_size &&
(ci->i_reported_size << 1) < ci->i_max_size)
ret = 1;
spin_unlock(&ci->i_ceph_lock);
return ret;
}
/*
* Write back inode data in a worker thread. (This can't be done
* in the message handler context.)
*/
void ceph_queue_writeback(struct inode *inode)
{
ihold(inode);
if (queue_work(ceph_inode_to_client(inode)->wb_wq,
&ceph_inode(inode)->i_wb_work)) {
dout("ceph_queue_writeback %p\n", inode);
} else {
dout("ceph_queue_writeback %p failed\n", inode);
iput(inode);
}
}
static void ceph_writeback_work(struct work_struct *work)
{
struct ceph_inode_info *ci = container_of(work, struct ceph_inode_info,
i_wb_work);
struct inode *inode = &ci->vfs_inode;
dout("writeback %p\n", inode);
filemap_fdatawrite(&inode->i_data);
iput(inode);
}
/*
* queue an async invalidation
*/
void ceph_queue_invalidate(struct inode *inode)
{
ihold(inode);
if (queue_work(ceph_inode_to_client(inode)->pg_inv_wq,
&ceph_inode(inode)->i_pg_inv_work)) {
dout("ceph_queue_invalidate %p\n", inode);
} else {
dout("ceph_queue_invalidate %p failed\n", inode);
iput(inode);
}
}
/*
* Invalidate inode pages in a worker thread. (This can't be done
* in the message handler context.)
*/
static void ceph_invalidate_work(struct work_struct *work)
{
struct ceph_inode_info *ci = container_of(work, struct ceph_inode_info,
i_pg_inv_work);
struct inode *inode = &ci->vfs_inode;
u32 orig_gen;
int check = 0;
spin_lock(&ci->i_ceph_lock);
dout("invalidate_pages %p gen %d revoking %d\n", inode,
ci->i_rdcache_gen, ci->i_rdcache_revoking);
if (ci->i_rdcache_revoking != ci->i_rdcache_gen) {
/* nevermind! */
spin_unlock(&ci->i_ceph_lock);
goto out;
}
orig_gen = ci->i_rdcache_gen;
spin_unlock(&ci->i_ceph_lock);
truncate_inode_pages(&inode->i_data, 0);
spin_lock(&ci->i_ceph_lock);
if (orig_gen == ci->i_rdcache_gen &&
orig_gen == ci->i_rdcache_revoking) {
dout("invalidate_pages %p gen %d successful\n", inode,
ci->i_rdcache_gen);
ci->i_rdcache_revoking--;
check = 1;
} else {
dout("invalidate_pages %p gen %d raced, now %d revoking %d\n",
inode, orig_gen, ci->i_rdcache_gen,
ci->i_rdcache_revoking);
}
spin_unlock(&ci->i_ceph_lock);
if (check)
ceph_check_caps(ci, 0, NULL);
out:
iput(inode);
}
/*
* called by trunc_wq;
*
* We also truncate in a separate thread as well.
*/
static void ceph_vmtruncate_work(struct work_struct *work)
{
struct ceph_inode_info *ci = container_of(work, struct ceph_inode_info,
i_vmtruncate_work);
struct inode *inode = &ci->vfs_inode;
dout("vmtruncate_work %p\n", inode);
__ceph_do_pending_vmtruncate(inode, true);
iput(inode);
}
/*
* Queue an async vmtruncate. If we fail to queue work, we will handle
* the truncation the next time we call __ceph_do_pending_vmtruncate.
*/
void ceph_queue_vmtruncate(struct inode *inode)
{
struct ceph_inode_info *ci = ceph_inode(inode);
ihold(inode);
if (queue_work(ceph_sb_to_client(inode->i_sb)->trunc_wq,
&ci->i_vmtruncate_work)) {
dout("ceph_queue_vmtruncate %p\n", inode);
} else {
dout("ceph_queue_vmtruncate %p failed, pending=%d\n",
inode, ci->i_truncate_pending);
iput(inode);
}
}
/*
* Make sure any pending truncation is applied before doing anything
* that may depend on it.
*/
void __ceph_do_pending_vmtruncate(struct inode *inode, bool needlock)
{
struct ceph_inode_info *ci = ceph_inode(inode);
u64 to;
int wrbuffer_refs, finish = 0;
retry:
spin_lock(&ci->i_ceph_lock);
if (ci->i_truncate_pending == 0) {
dout("__do_pending_vmtruncate %p none pending\n", inode);
spin_unlock(&ci->i_ceph_lock);
return;
}
/*
* make sure any dirty snapped pages are flushed before we
* possibly truncate them.. so write AND block!
*/
if (ci->i_wrbuffer_ref_head < ci->i_wrbuffer_ref) {
dout("__do_pending_vmtruncate %p flushing snaps first\n",
inode);
spin_unlock(&ci->i_ceph_lock);
filemap_write_and_wait_range(&inode->i_data, 0,
inode->i_sb->s_maxbytes);
goto retry;
}
to = ci->i_truncate_size;
wrbuffer_refs = ci->i_wrbuffer_ref;
dout("__do_pending_vmtruncate %p (%d) to %lld\n", inode,
ci->i_truncate_pending, to);
spin_unlock(&ci->i_ceph_lock);
if (needlock)
mutex_lock(&inode->i_mutex);
truncate_inode_pages(inode->i_mapping, to);
if (needlock)
mutex_unlock(&inode->i_mutex);
spin_lock(&ci->i_ceph_lock);
if (to == ci->i_truncate_size) {
ci->i_truncate_pending = 0;
finish = 1;
}
spin_unlock(&ci->i_ceph_lock);
if (!finish)
goto retry;
if (wrbuffer_refs == 0)
ceph_check_caps(ci, CHECK_CAPS_AUTHONLY, NULL);
wake_up_all(&ci->i_cap_wq);
}
/*
* symlinks
*/
static void *ceph_sym_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct ceph_inode_info *ci = ceph_inode(dentry->d_inode);
nd_set_link(nd, ci->i_symlink);
return NULL;
}
static const struct inode_operations ceph_symlink_iops = {
.readlink = generic_readlink,
.follow_link = ceph_sym_follow_link,
.setattr = ceph_setattr,
.getattr = ceph_getattr,
.setxattr = ceph_setxattr,
.getxattr = ceph_getxattr,
.listxattr = ceph_listxattr,
.removexattr = ceph_removexattr,
};
/*
* setattr
*/
int ceph_setattr(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = dentry->d_inode;
struct ceph_inode_info *ci = ceph_inode(inode);
struct inode *parent_inode;
const unsigned int ia_valid = attr->ia_valid;
struct ceph_mds_request *req;
struct ceph_mds_client *mdsc = ceph_sb_to_client(dentry->d_sb)->mdsc;
int issued;
int release = 0, dirtied = 0;
int mask = 0;
int err = 0;
int inode_dirty_flags = 0;
if (ceph_snap(inode) != CEPH_NOSNAP)
return -EROFS;
__ceph_do_pending_vmtruncate(inode, false);
err = inode_change_ok(inode, attr);
if (err != 0)
return err;
req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_SETATTR,
USE_AUTH_MDS);
if (IS_ERR(req))
return PTR_ERR(req);
spin_lock(&ci->i_ceph_lock);
issued = __ceph_caps_issued(ci, NULL);
dout("setattr %p issued %s\n", inode, ceph_cap_string(issued));
if (ia_valid & ATTR_UID) {
dout("setattr %p uid %d -> %d\n", inode,
from_kuid(&init_user_ns, inode->i_uid),
from_kuid(&init_user_ns, attr->ia_uid));
if (issued & CEPH_CAP_AUTH_EXCL) {
inode->i_uid = attr->ia_uid;
dirtied |= CEPH_CAP_AUTH_EXCL;
} else if ((issued & CEPH_CAP_AUTH_SHARED) == 0 ||
!uid_eq(attr->ia_uid, inode->i_uid)) {
req->r_args.setattr.uid = cpu_to_le32(
from_kuid(&init_user_ns, attr->ia_uid));
mask |= CEPH_SETATTR_UID;
release |= CEPH_CAP_AUTH_SHARED;
}
}
if (ia_valid & ATTR_GID) {
dout("setattr %p gid %d -> %d\n", inode,
from_kgid(&init_user_ns, inode->i_gid),
from_kgid(&init_user_ns, attr->ia_gid));
if (issued & CEPH_CAP_AUTH_EXCL) {
inode->i_gid = attr->ia_gid;
dirtied |= CEPH_CAP_AUTH_EXCL;
} else if ((issued & CEPH_CAP_AUTH_SHARED) == 0 ||
!gid_eq(attr->ia_gid, inode->i_gid)) {
req->r_args.setattr.gid = cpu_to_le32(
from_kgid(&init_user_ns, attr->ia_gid));
mask |= CEPH_SETATTR_GID;
release |= CEPH_CAP_AUTH_SHARED;
}
}
if (ia_valid & ATTR_MODE) {
dout("setattr %p mode 0%o -> 0%o\n", inode, inode->i_mode,
attr->ia_mode);
if (issued & CEPH_CAP_AUTH_EXCL) {
inode->i_mode = attr->ia_mode;
dirtied |= CEPH_CAP_AUTH_EXCL;
} else if ((issued & CEPH_CAP_AUTH_SHARED) == 0 ||
attr->ia_mode != inode->i_mode) {
req->r_args.setattr.mode = cpu_to_le32(attr->ia_mode);
mask |= CEPH_SETATTR_MODE;
release |= CEPH_CAP_AUTH_SHARED;
}
}
if (ia_valid & ATTR_ATIME) {
dout("setattr %p atime %ld.%ld -> %ld.%ld\n", inode,
inode->i_atime.tv_sec, inode->i_atime.tv_nsec,
attr->ia_atime.tv_sec, attr->ia_atime.tv_nsec);
if (issued & CEPH_CAP_FILE_EXCL) {
ci->i_time_warp_seq++;
inode->i_atime = attr->ia_atime;
dirtied |= CEPH_CAP_FILE_EXCL;
} else if ((issued & CEPH_CAP_FILE_WR) &&
timespec_compare(&inode->i_atime,
&attr->ia_atime) < 0) {
inode->i_atime = attr->ia_atime;
dirtied |= CEPH_CAP_FILE_WR;
} else if ((issued & CEPH_CAP_FILE_SHARED) == 0 ||
!timespec_equal(&inode->i_atime, &attr->ia_atime)) {
ceph_encode_timespec(&req->r_args.setattr.atime,
&attr->ia_atime);
mask |= CEPH_SETATTR_ATIME;
release |= CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_RD |
CEPH_CAP_FILE_WR;
}
}
if (ia_valid & ATTR_MTIME) {
dout("setattr %p mtime %ld.%ld -> %ld.%ld\n", inode,
inode->i_mtime.tv_sec, inode->i_mtime.tv_nsec,
attr->ia_mtime.tv_sec, attr->ia_mtime.tv_nsec);
if (issued & CEPH_CAP_FILE_EXCL) {
ci->i_time_warp_seq++;
inode->i_mtime = attr->ia_mtime;
dirtied |= CEPH_CAP_FILE_EXCL;
} else if ((issued & CEPH_CAP_FILE_WR) &&
timespec_compare(&inode->i_mtime,
&attr->ia_mtime) < 0) {
inode->i_mtime = attr->ia_mtime;
dirtied |= CEPH_CAP_FILE_WR;
} else if ((issued & CEPH_CAP_FILE_SHARED) == 0 ||
!timespec_equal(&inode->i_mtime, &attr->ia_mtime)) {
ceph_encode_timespec(&req->r_args.setattr.mtime,
&attr->ia_mtime);
mask |= CEPH_SETATTR_MTIME;
release |= CEPH_CAP_FILE_SHARED | CEPH_CAP_FILE_RD |
CEPH_CAP_FILE_WR;
}
}
if (ia_valid & ATTR_SIZE) {
dout("setattr %p size %lld -> %lld\n", inode,
inode->i_size, attr->ia_size);
if (attr->ia_size > inode->i_sb->s_maxbytes) {
err = -EINVAL;
goto out;
}
if ((issued & CEPH_CAP_FILE_EXCL) &&
attr->ia_size > inode->i_size) {
inode->i_size = attr->ia_size;
inode->i_blocks =
(attr->ia_size + (1 << 9) - 1) >> 9;
inode->i_ctime = attr->ia_ctime;
ci->i_reported_size = attr->ia_size;
dirtied |= CEPH_CAP_FILE_EXCL;
} else if ((issued & CEPH_CAP_FILE_SHARED) == 0 ||
attr->ia_size != inode->i_size) {
req->r_args.setattr.size = cpu_to_le64(attr->ia_size);
req->r_args.setattr.old_size =
cpu_to_le64(inode->i_size);
mask |= CEPH_SETATTR_SIZE;
release |= CEPH_CAP_FILE_SHARED | CEPH_CAP_FILE_RD |
CEPH_CAP_FILE_WR;
}
}
/* these do nothing */
if (ia_valid & ATTR_CTIME) {
bool only = (ia_valid & (ATTR_SIZE|ATTR_MTIME|ATTR_ATIME|
ATTR_MODE|ATTR_UID|ATTR_GID)) == 0;
dout("setattr %p ctime %ld.%ld -> %ld.%ld (%s)\n", inode,
inode->i_ctime.tv_sec, inode->i_ctime.tv_nsec,
attr->ia_ctime.tv_sec, attr->ia_ctime.tv_nsec,
only ? "ctime only" : "ignored");
inode->i_ctime = attr->ia_ctime;
if (only) {
/*
* if kernel wants to dirty ctime but nothing else,
* we need to choose a cap to dirty under, or do
* a almost-no-op setattr
*/
if (issued & CEPH_CAP_AUTH_EXCL)
dirtied |= CEPH_CAP_AUTH_EXCL;
else if (issued & CEPH_CAP_FILE_EXCL)
dirtied |= CEPH_CAP_FILE_EXCL;
else if (issued & CEPH_CAP_XATTR_EXCL)
dirtied |= CEPH_CAP_XATTR_EXCL;
else
mask |= CEPH_SETATTR_CTIME;
}
}
if (ia_valid & ATTR_FILE)
dout("setattr %p ATTR_FILE ... hrm!\n", inode);
if (dirtied) {
inode_dirty_flags = __ceph_mark_dirty_caps(ci, dirtied);
inode->i_ctime = CURRENT_TIME;
}
release &= issued;
spin_unlock(&ci->i_ceph_lock);
if (inode_dirty_flags)
__mark_inode_dirty(inode, inode_dirty_flags);
if (mask) {
req->r_inode = inode;
ihold(inode);
req->r_inode_drop = release;
req->r_args.setattr.mask = cpu_to_le32(mask);
req->r_num_caps = 1;
parent_inode = ceph_get_dentry_parent_inode(dentry);
err = ceph_mdsc_do_request(mdsc, parent_inode, req);
iput(parent_inode);
}
dout("setattr %p result=%d (%s locally, %d remote)\n", inode, err,
ceph_cap_string(dirtied), mask);
ceph_mdsc_put_request(req);
__ceph_do_pending_vmtruncate(inode, false);
return err;
out:
spin_unlock(&ci->i_ceph_lock);
ceph_mdsc_put_request(req);
return err;
}
/*
* Verify that we have a lease on the given mask. If not,
* do a getattr against an mds.
*/
int ceph_do_getattr(struct inode *inode, int mask)
{
struct ceph_fs_client *fsc = ceph_sb_to_client(inode->i_sb);
struct ceph_mds_client *mdsc = fsc->mdsc;
struct ceph_mds_request *req;
int err;
if (ceph_snap(inode) == CEPH_SNAPDIR) {
dout("do_getattr inode %p SNAPDIR\n", inode);
return 0;
}
dout("do_getattr inode %p mask %s mode 0%o\n", inode, ceph_cap_string(mask), inode->i_mode);
if (ceph_caps_issued_mask(ceph_inode(inode), mask, 1))
return 0;
req = ceph_mdsc_create_request(mdsc, CEPH_MDS_OP_GETATTR, USE_ANY_MDS);
if (IS_ERR(req))
return PTR_ERR(req);
req->r_inode = inode;
ihold(inode);
req->r_num_caps = 1;
req->r_args.getattr.mask = cpu_to_le32(mask);
err = ceph_mdsc_do_request(mdsc, NULL, req);
ceph_mdsc_put_request(req);
dout("do_getattr result=%d\n", err);
return err;
}
/*
* Check inode permissions. We verify we have a valid value for
* the AUTH cap, then call the generic handler.
*/
int ceph_permission(struct inode *inode, int mask)
{
int err;
if (mask & MAY_NOT_BLOCK)
return -ECHILD;
err = ceph_do_getattr(inode, CEPH_CAP_AUTH_SHARED);
if (!err)
err = generic_permission(inode, mask);
return err;
}
/*
* Get all attributes. Hopefully somedata we'll have a statlite()
* and can limit the fields we require to be accurate.
*/
int ceph_getattr(struct vfsmount *mnt, struct dentry *dentry,
struct kstat *stat)
{
struct inode *inode = dentry->d_inode;
struct ceph_inode_info *ci = ceph_inode(inode);
int err;
err = ceph_do_getattr(inode, CEPH_STAT_CAP_INODE_ALL);
if (!err) {
generic_fillattr(inode, stat);
stat->ino = ceph_translate_ino(inode->i_sb, inode->i_ino);
if (ceph_snap(inode) != CEPH_NOSNAP)
stat->dev = ceph_snap(inode);
else
stat->dev = 0;
if (S_ISDIR(inode->i_mode)) {
if (ceph_test_mount_opt(ceph_sb_to_client(inode->i_sb),
RBYTES))
stat->size = ci->i_rbytes;
else
stat->size = ci->i_files + ci->i_subdirs;
stat->blocks = 0;
stat->blksize = 65536;
}
}
return err;
}
| gpl-2.0 |
vivalto/android_kernel_samsung_vivalto3gvn | 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 |
sg3/android_kernel_samsung_apollo | arch/sparc/kernel/sbus.c | 2588 | 20478 | /*
* sbus.c: UltraSparc SBUS controller support.
*
* Copyright (C) 1999 David S. Miller (davem@redhat.com)
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <asm/page.h>
#include <asm/io.h>
#include <asm/upa.h>
#include <asm/cache.h>
#include <asm/dma.h>
#include <asm/irq.h>
#include <asm/prom.h>
#include <asm/oplib.h>
#include <asm/starfire.h>
#include "iommu_common.h"
#define MAP_BASE ((u32)0xc0000000)
/* Offsets from iommu_regs */
#define SYSIO_IOMMUREG_BASE 0x2400UL
#define IOMMU_CONTROL (0x2400UL - 0x2400UL) /* IOMMU control register */
#define IOMMU_TSBBASE (0x2408UL - 0x2400UL) /* TSB base address register */
#define IOMMU_FLUSH (0x2410UL - 0x2400UL) /* IOMMU flush register */
#define IOMMU_VADIAG (0x4400UL - 0x2400UL) /* SBUS virtual address diagnostic */
#define IOMMU_TAGCMP (0x4408UL - 0x2400UL) /* TLB tag compare diagnostics */
#define IOMMU_LRUDIAG (0x4500UL - 0x2400UL) /* IOMMU LRU queue diagnostics */
#define IOMMU_TAGDIAG (0x4580UL - 0x2400UL) /* TLB tag diagnostics */
#define IOMMU_DRAMDIAG (0x4600UL - 0x2400UL) /* TLB data RAM diagnostics */
#define IOMMU_DRAM_VALID (1UL << 30UL)
/* Offsets from strbuf_regs */
#define SYSIO_STRBUFREG_BASE 0x2800UL
#define STRBUF_CONTROL (0x2800UL - 0x2800UL) /* Control */
#define STRBUF_PFLUSH (0x2808UL - 0x2800UL) /* Page flush/invalidate */
#define STRBUF_FSYNC (0x2810UL - 0x2800UL) /* Flush synchronization */
#define STRBUF_DRAMDIAG (0x5000UL - 0x2800UL) /* data RAM diagnostic */
#define STRBUF_ERRDIAG (0x5400UL - 0x2800UL) /* error status diagnostics */
#define STRBUF_PTAGDIAG (0x5800UL - 0x2800UL) /* Page tag diagnostics */
#define STRBUF_LTAGDIAG (0x5900UL - 0x2800UL) /* Line tag diagnostics */
#define STRBUF_TAG_VALID 0x02UL
/* Enable 64-bit DVMA mode for the given device. */
void sbus_set_sbus64(struct device *dev, int bursts)
{
struct iommu *iommu = dev->archdata.iommu;
struct platform_device *op = to_platform_device(dev);
const struct linux_prom_registers *regs;
unsigned long cfg_reg;
int slot;
u64 val;
regs = of_get_property(op->dev.of_node, "reg", NULL);
if (!regs) {
printk(KERN_ERR "sbus_set_sbus64: Cannot find regs for %s\n",
op->dev.of_node->full_name);
return;
}
slot = regs->which_io;
cfg_reg = iommu->write_complete_reg;
switch (slot) {
case 0:
cfg_reg += 0x20UL;
break;
case 1:
cfg_reg += 0x28UL;
break;
case 2:
cfg_reg += 0x30UL;
break;
case 3:
cfg_reg += 0x38UL;
break;
case 13:
cfg_reg += 0x40UL;
break;
case 14:
cfg_reg += 0x48UL;
break;
case 15:
cfg_reg += 0x50UL;
break;
default:
return;
}
val = upa_readq(cfg_reg);
if (val & (1UL << 14UL)) {
/* Extended transfer mode already enabled. */
return;
}
val |= (1UL << 14UL);
if (bursts & DMA_BURST8)
val |= (1UL << 1UL);
if (bursts & DMA_BURST16)
val |= (1UL << 2UL);
if (bursts & DMA_BURST32)
val |= (1UL << 3UL);
if (bursts & DMA_BURST64)
val |= (1UL << 4UL);
upa_writeq(val, cfg_reg);
}
EXPORT_SYMBOL(sbus_set_sbus64);
/* INO number to IMAP register offset for SYSIO external IRQ's.
* This should conform to both Sunfire/Wildfire server and Fusion
* desktop designs.
*/
#define SYSIO_IMAP_SLOT0 0x2c00UL
#define SYSIO_IMAP_SLOT1 0x2c08UL
#define SYSIO_IMAP_SLOT2 0x2c10UL
#define SYSIO_IMAP_SLOT3 0x2c18UL
#define SYSIO_IMAP_SCSI 0x3000UL
#define SYSIO_IMAP_ETH 0x3008UL
#define SYSIO_IMAP_BPP 0x3010UL
#define SYSIO_IMAP_AUDIO 0x3018UL
#define SYSIO_IMAP_PFAIL 0x3020UL
#define SYSIO_IMAP_KMS 0x3028UL
#define SYSIO_IMAP_FLPY 0x3030UL
#define SYSIO_IMAP_SHW 0x3038UL
#define SYSIO_IMAP_KBD 0x3040UL
#define SYSIO_IMAP_MS 0x3048UL
#define SYSIO_IMAP_SER 0x3050UL
#define SYSIO_IMAP_TIM0 0x3060UL
#define SYSIO_IMAP_TIM1 0x3068UL
#define SYSIO_IMAP_UE 0x3070UL
#define SYSIO_IMAP_CE 0x3078UL
#define SYSIO_IMAP_SBERR 0x3080UL
#define SYSIO_IMAP_PMGMT 0x3088UL
#define SYSIO_IMAP_GFX 0x3090UL
#define SYSIO_IMAP_EUPA 0x3098UL
#define bogon ((unsigned long) -1)
static unsigned long sysio_irq_offsets[] = {
/* SBUS Slot 0 --> 3, level 1 --> 7 */
SYSIO_IMAP_SLOT0, SYSIO_IMAP_SLOT0, SYSIO_IMAP_SLOT0, SYSIO_IMAP_SLOT0,
SYSIO_IMAP_SLOT0, SYSIO_IMAP_SLOT0, SYSIO_IMAP_SLOT0, SYSIO_IMAP_SLOT0,
SYSIO_IMAP_SLOT1, SYSIO_IMAP_SLOT1, SYSIO_IMAP_SLOT1, SYSIO_IMAP_SLOT1,
SYSIO_IMAP_SLOT1, SYSIO_IMAP_SLOT1, SYSIO_IMAP_SLOT1, SYSIO_IMAP_SLOT1,
SYSIO_IMAP_SLOT2, SYSIO_IMAP_SLOT2, SYSIO_IMAP_SLOT2, SYSIO_IMAP_SLOT2,
SYSIO_IMAP_SLOT2, SYSIO_IMAP_SLOT2, SYSIO_IMAP_SLOT2, SYSIO_IMAP_SLOT2,
SYSIO_IMAP_SLOT3, SYSIO_IMAP_SLOT3, SYSIO_IMAP_SLOT3, SYSIO_IMAP_SLOT3,
SYSIO_IMAP_SLOT3, SYSIO_IMAP_SLOT3, SYSIO_IMAP_SLOT3, SYSIO_IMAP_SLOT3,
/* Onboard devices (not relevant/used on SunFire). */
SYSIO_IMAP_SCSI,
SYSIO_IMAP_ETH,
SYSIO_IMAP_BPP,
bogon,
SYSIO_IMAP_AUDIO,
SYSIO_IMAP_PFAIL,
bogon,
bogon,
SYSIO_IMAP_KMS,
SYSIO_IMAP_FLPY,
SYSIO_IMAP_SHW,
SYSIO_IMAP_KBD,
SYSIO_IMAP_MS,
SYSIO_IMAP_SER,
bogon,
bogon,
SYSIO_IMAP_TIM0,
SYSIO_IMAP_TIM1,
bogon,
bogon,
SYSIO_IMAP_UE,
SYSIO_IMAP_CE,
SYSIO_IMAP_SBERR,
SYSIO_IMAP_PMGMT,
};
#undef bogon
#define NUM_SYSIO_OFFSETS ARRAY_SIZE(sysio_irq_offsets)
/* Convert Interrupt Mapping register pointer to associated
* Interrupt Clear register pointer, SYSIO specific version.
*/
#define SYSIO_ICLR_UNUSED0 0x3400UL
#define SYSIO_ICLR_SLOT0 0x3408UL
#define SYSIO_ICLR_SLOT1 0x3448UL
#define SYSIO_ICLR_SLOT2 0x3488UL
#define SYSIO_ICLR_SLOT3 0x34c8UL
static unsigned long sysio_imap_to_iclr(unsigned long imap)
{
unsigned long diff = SYSIO_ICLR_UNUSED0 - SYSIO_IMAP_SLOT0;
return imap + diff;
}
static unsigned int sbus_build_irq(struct platform_device *op, unsigned int ino)
{
struct iommu *iommu = op->dev.archdata.iommu;
unsigned long reg_base = iommu->write_complete_reg - 0x2000UL;
unsigned long imap, iclr;
int sbus_level = 0;
imap = sysio_irq_offsets[ino];
if (imap == ((unsigned long)-1)) {
prom_printf("get_irq_translations: Bad SYSIO INO[%x]\n",
ino);
prom_halt();
}
imap += reg_base;
/* SYSIO inconsistency. For external SLOTS, we have to select
* the right ICLR register based upon the lower SBUS irq level
* bits.
*/
if (ino >= 0x20) {
iclr = sysio_imap_to_iclr(imap);
} else {
int sbus_slot = (ino & 0x18)>>3;
sbus_level = ino & 0x7;
switch(sbus_slot) {
case 0:
iclr = reg_base + SYSIO_ICLR_SLOT0;
break;
case 1:
iclr = reg_base + SYSIO_ICLR_SLOT1;
break;
case 2:
iclr = reg_base + SYSIO_ICLR_SLOT2;
break;
default:
case 3:
iclr = reg_base + SYSIO_ICLR_SLOT3;
break;
}
iclr += ((unsigned long)sbus_level - 1UL) * 8UL;
}
return build_irq(sbus_level, iclr, imap);
}
/* Error interrupt handling. */
#define SYSIO_UE_AFSR 0x0030UL
#define SYSIO_UE_AFAR 0x0038UL
#define SYSIO_UEAFSR_PPIO 0x8000000000000000UL /* Primary PIO cause */
#define SYSIO_UEAFSR_PDRD 0x4000000000000000UL /* Primary DVMA read cause */
#define SYSIO_UEAFSR_PDWR 0x2000000000000000UL /* Primary DVMA write cause */
#define SYSIO_UEAFSR_SPIO 0x1000000000000000UL /* Secondary PIO is cause */
#define SYSIO_UEAFSR_SDRD 0x0800000000000000UL /* Secondary DVMA read cause */
#define SYSIO_UEAFSR_SDWR 0x0400000000000000UL /* Secondary DVMA write cause*/
#define SYSIO_UEAFSR_RESV1 0x03ff000000000000UL /* Reserved */
#define SYSIO_UEAFSR_DOFF 0x0000e00000000000UL /* Doubleword Offset */
#define SYSIO_UEAFSR_SIZE 0x00001c0000000000UL /* Bad transfer size 2^SIZE */
#define SYSIO_UEAFSR_MID 0x000003e000000000UL /* UPA MID causing the fault */
#define SYSIO_UEAFSR_RESV2 0x0000001fffffffffUL /* Reserved */
static irqreturn_t sysio_ue_handler(int irq, void *dev_id)
{
struct platform_device *op = dev_id;
struct iommu *iommu = op->dev.archdata.iommu;
unsigned long reg_base = iommu->write_complete_reg - 0x2000UL;
unsigned long afsr_reg, afar_reg;
unsigned long afsr, afar, error_bits;
int reported, portid;
afsr_reg = reg_base + SYSIO_UE_AFSR;
afar_reg = reg_base + SYSIO_UE_AFAR;
/* Latch error status. */
afsr = upa_readq(afsr_reg);
afar = upa_readq(afar_reg);
/* Clear primary/secondary error status bits. */
error_bits = afsr &
(SYSIO_UEAFSR_PPIO | SYSIO_UEAFSR_PDRD | SYSIO_UEAFSR_PDWR |
SYSIO_UEAFSR_SPIO | SYSIO_UEAFSR_SDRD | SYSIO_UEAFSR_SDWR);
upa_writeq(error_bits, afsr_reg);
portid = of_getintprop_default(op->dev.of_node, "portid", -1);
/* Log the error. */
printk("SYSIO[%x]: Uncorrectable ECC Error, primary error type[%s]\n",
portid,
(((error_bits & SYSIO_UEAFSR_PPIO) ?
"PIO" :
((error_bits & SYSIO_UEAFSR_PDRD) ?
"DVMA Read" :
((error_bits & SYSIO_UEAFSR_PDWR) ?
"DVMA Write" : "???")))));
printk("SYSIO[%x]: DOFF[%lx] SIZE[%lx] MID[%lx]\n",
portid,
(afsr & SYSIO_UEAFSR_DOFF) >> 45UL,
(afsr & SYSIO_UEAFSR_SIZE) >> 42UL,
(afsr & SYSIO_UEAFSR_MID) >> 37UL);
printk("SYSIO[%x]: AFAR[%016lx]\n", portid, afar);
printk("SYSIO[%x]: Secondary UE errors [", portid);
reported = 0;
if (afsr & SYSIO_UEAFSR_SPIO) {
reported++;
printk("(PIO)");
}
if (afsr & SYSIO_UEAFSR_SDRD) {
reported++;
printk("(DVMA Read)");
}
if (afsr & SYSIO_UEAFSR_SDWR) {
reported++;
printk("(DVMA Write)");
}
if (!reported)
printk("(none)");
printk("]\n");
return IRQ_HANDLED;
}
#define SYSIO_CE_AFSR 0x0040UL
#define SYSIO_CE_AFAR 0x0048UL
#define SYSIO_CEAFSR_PPIO 0x8000000000000000UL /* Primary PIO cause */
#define SYSIO_CEAFSR_PDRD 0x4000000000000000UL /* Primary DVMA read cause */
#define SYSIO_CEAFSR_PDWR 0x2000000000000000UL /* Primary DVMA write cause */
#define SYSIO_CEAFSR_SPIO 0x1000000000000000UL /* Secondary PIO cause */
#define SYSIO_CEAFSR_SDRD 0x0800000000000000UL /* Secondary DVMA read cause */
#define SYSIO_CEAFSR_SDWR 0x0400000000000000UL /* Secondary DVMA write cause*/
#define SYSIO_CEAFSR_RESV1 0x0300000000000000UL /* Reserved */
#define SYSIO_CEAFSR_ESYND 0x00ff000000000000UL /* Syndrome Bits */
#define SYSIO_CEAFSR_DOFF 0x0000e00000000000UL /* Double Offset */
#define SYSIO_CEAFSR_SIZE 0x00001c0000000000UL /* Bad transfer size 2^SIZE */
#define SYSIO_CEAFSR_MID 0x000003e000000000UL /* UPA MID causing the fault */
#define SYSIO_CEAFSR_RESV2 0x0000001fffffffffUL /* Reserved */
static irqreturn_t sysio_ce_handler(int irq, void *dev_id)
{
struct platform_device *op = dev_id;
struct iommu *iommu = op->dev.archdata.iommu;
unsigned long reg_base = iommu->write_complete_reg - 0x2000UL;
unsigned long afsr_reg, afar_reg;
unsigned long afsr, afar, error_bits;
int reported, portid;
afsr_reg = reg_base + SYSIO_CE_AFSR;
afar_reg = reg_base + SYSIO_CE_AFAR;
/* Latch error status. */
afsr = upa_readq(afsr_reg);
afar = upa_readq(afar_reg);
/* Clear primary/secondary error status bits. */
error_bits = afsr &
(SYSIO_CEAFSR_PPIO | SYSIO_CEAFSR_PDRD | SYSIO_CEAFSR_PDWR |
SYSIO_CEAFSR_SPIO | SYSIO_CEAFSR_SDRD | SYSIO_CEAFSR_SDWR);
upa_writeq(error_bits, afsr_reg);
portid = of_getintprop_default(op->dev.of_node, "portid", -1);
printk("SYSIO[%x]: Correctable ECC Error, primary error type[%s]\n",
portid,
(((error_bits & SYSIO_CEAFSR_PPIO) ?
"PIO" :
((error_bits & SYSIO_CEAFSR_PDRD) ?
"DVMA Read" :
((error_bits & SYSIO_CEAFSR_PDWR) ?
"DVMA Write" : "???")))));
/* XXX Use syndrome and afar to print out module string just like
* XXX UDB CE trap handler does... -DaveM
*/
printk("SYSIO[%x]: DOFF[%lx] ECC Syndrome[%lx] Size[%lx] MID[%lx]\n",
portid,
(afsr & SYSIO_CEAFSR_DOFF) >> 45UL,
(afsr & SYSIO_CEAFSR_ESYND) >> 48UL,
(afsr & SYSIO_CEAFSR_SIZE) >> 42UL,
(afsr & SYSIO_CEAFSR_MID) >> 37UL);
printk("SYSIO[%x]: AFAR[%016lx]\n", portid, afar);
printk("SYSIO[%x]: Secondary CE errors [", portid);
reported = 0;
if (afsr & SYSIO_CEAFSR_SPIO) {
reported++;
printk("(PIO)");
}
if (afsr & SYSIO_CEAFSR_SDRD) {
reported++;
printk("(DVMA Read)");
}
if (afsr & SYSIO_CEAFSR_SDWR) {
reported++;
printk("(DVMA Write)");
}
if (!reported)
printk("(none)");
printk("]\n");
return IRQ_HANDLED;
}
#define SYSIO_SBUS_AFSR 0x2010UL
#define SYSIO_SBUS_AFAR 0x2018UL
#define SYSIO_SBAFSR_PLE 0x8000000000000000UL /* Primary Late PIO Error */
#define SYSIO_SBAFSR_PTO 0x4000000000000000UL /* Primary SBUS Timeout */
#define SYSIO_SBAFSR_PBERR 0x2000000000000000UL /* Primary SBUS Error ACK */
#define SYSIO_SBAFSR_SLE 0x1000000000000000UL /* Secondary Late PIO Error */
#define SYSIO_SBAFSR_STO 0x0800000000000000UL /* Secondary SBUS Timeout */
#define SYSIO_SBAFSR_SBERR 0x0400000000000000UL /* Secondary SBUS Error ACK */
#define SYSIO_SBAFSR_RESV1 0x03ff000000000000UL /* Reserved */
#define SYSIO_SBAFSR_RD 0x0000800000000000UL /* Primary was late PIO read */
#define SYSIO_SBAFSR_RESV2 0x0000600000000000UL /* Reserved */
#define SYSIO_SBAFSR_SIZE 0x00001c0000000000UL /* Size of transfer */
#define SYSIO_SBAFSR_MID 0x000003e000000000UL /* MID causing the error */
#define SYSIO_SBAFSR_RESV3 0x0000001fffffffffUL /* Reserved */
static irqreturn_t sysio_sbus_error_handler(int irq, void *dev_id)
{
struct platform_device *op = dev_id;
struct iommu *iommu = op->dev.archdata.iommu;
unsigned long afsr_reg, afar_reg, reg_base;
unsigned long afsr, afar, error_bits;
int reported, portid;
reg_base = iommu->write_complete_reg - 0x2000UL;
afsr_reg = reg_base + SYSIO_SBUS_AFSR;
afar_reg = reg_base + SYSIO_SBUS_AFAR;
afsr = upa_readq(afsr_reg);
afar = upa_readq(afar_reg);
/* Clear primary/secondary error status bits. */
error_bits = afsr &
(SYSIO_SBAFSR_PLE | SYSIO_SBAFSR_PTO | SYSIO_SBAFSR_PBERR |
SYSIO_SBAFSR_SLE | SYSIO_SBAFSR_STO | SYSIO_SBAFSR_SBERR);
upa_writeq(error_bits, afsr_reg);
portid = of_getintprop_default(op->dev.of_node, "portid", -1);
/* Log the error. */
printk("SYSIO[%x]: SBUS Error, primary error type[%s] read(%d)\n",
portid,
(((error_bits & SYSIO_SBAFSR_PLE) ?
"Late PIO Error" :
((error_bits & SYSIO_SBAFSR_PTO) ?
"Time Out" :
((error_bits & SYSIO_SBAFSR_PBERR) ?
"Error Ack" : "???")))),
(afsr & SYSIO_SBAFSR_RD) ? 1 : 0);
printk("SYSIO[%x]: size[%lx] MID[%lx]\n",
portid,
(afsr & SYSIO_SBAFSR_SIZE) >> 42UL,
(afsr & SYSIO_SBAFSR_MID) >> 37UL);
printk("SYSIO[%x]: AFAR[%016lx]\n", portid, afar);
printk("SYSIO[%x]: Secondary SBUS errors [", portid);
reported = 0;
if (afsr & SYSIO_SBAFSR_SLE) {
reported++;
printk("(Late PIO Error)");
}
if (afsr & SYSIO_SBAFSR_STO) {
reported++;
printk("(Time Out)");
}
if (afsr & SYSIO_SBAFSR_SBERR) {
reported++;
printk("(Error Ack)");
}
if (!reported)
printk("(none)");
printk("]\n");
/* XXX check iommu/strbuf for further error status XXX */
return IRQ_HANDLED;
}
#define ECC_CONTROL 0x0020UL
#define SYSIO_ECNTRL_ECCEN 0x8000000000000000UL /* Enable ECC Checking */
#define SYSIO_ECNTRL_UEEN 0x4000000000000000UL /* Enable UE Interrupts */
#define SYSIO_ECNTRL_CEEN 0x2000000000000000UL /* Enable CE Interrupts */
#define SYSIO_UE_INO 0x34
#define SYSIO_CE_INO 0x35
#define SYSIO_SBUSERR_INO 0x36
static void __init sysio_register_error_handlers(struct platform_device *op)
{
struct iommu *iommu = op->dev.archdata.iommu;
unsigned long reg_base = iommu->write_complete_reg - 0x2000UL;
unsigned int irq;
u64 control;
int portid;
portid = of_getintprop_default(op->dev.of_node, "portid", -1);
irq = sbus_build_irq(op, SYSIO_UE_INO);
if (request_irq(irq, sysio_ue_handler, 0,
"SYSIO_UE", op) < 0) {
prom_printf("SYSIO[%x]: Cannot register UE interrupt.\n",
portid);
prom_halt();
}
irq = sbus_build_irq(op, SYSIO_CE_INO);
if (request_irq(irq, sysio_ce_handler, 0,
"SYSIO_CE", op) < 0) {
prom_printf("SYSIO[%x]: Cannot register CE interrupt.\n",
portid);
prom_halt();
}
irq = sbus_build_irq(op, SYSIO_SBUSERR_INO);
if (request_irq(irq, sysio_sbus_error_handler, 0,
"SYSIO_SBERR", op) < 0) {
prom_printf("SYSIO[%x]: Cannot register SBUS Error interrupt.\n",
portid);
prom_halt();
}
/* Now turn the error interrupts on and also enable ECC checking. */
upa_writeq((SYSIO_ECNTRL_ECCEN |
SYSIO_ECNTRL_UEEN |
SYSIO_ECNTRL_CEEN),
reg_base + ECC_CONTROL);
control = upa_readq(iommu->write_complete_reg);
control |= 0x100UL; /* SBUS Error Interrupt Enable */
upa_writeq(control, iommu->write_complete_reg);
}
/* Boot time initialization. */
static void __init sbus_iommu_init(struct platform_device *op)
{
const struct linux_prom64_registers *pr;
struct device_node *dp = op->dev.of_node;
struct iommu *iommu;
struct strbuf *strbuf;
unsigned long regs, reg_base;
int i, portid;
u64 control;
pr = of_get_property(dp, "reg", NULL);
if (!pr) {
prom_printf("sbus_iommu_init: Cannot map SYSIO "
"control registers.\n");
prom_halt();
}
regs = pr->phys_addr;
iommu = kzalloc(sizeof(*iommu), GFP_ATOMIC);
if (!iommu)
goto fatal_memory_error;
strbuf = kzalloc(sizeof(*strbuf), GFP_ATOMIC);
if (!strbuf)
goto fatal_memory_error;
op->dev.archdata.iommu = iommu;
op->dev.archdata.stc = strbuf;
op->dev.archdata.numa_node = -1;
reg_base = regs + SYSIO_IOMMUREG_BASE;
iommu->iommu_control = reg_base + IOMMU_CONTROL;
iommu->iommu_tsbbase = reg_base + IOMMU_TSBBASE;
iommu->iommu_flush = reg_base + IOMMU_FLUSH;
iommu->iommu_tags = iommu->iommu_control +
(IOMMU_TAGDIAG - IOMMU_CONTROL);
reg_base = regs + SYSIO_STRBUFREG_BASE;
strbuf->strbuf_control = reg_base + STRBUF_CONTROL;
strbuf->strbuf_pflush = reg_base + STRBUF_PFLUSH;
strbuf->strbuf_fsync = reg_base + STRBUF_FSYNC;
strbuf->strbuf_enabled = 1;
strbuf->strbuf_flushflag = (volatile unsigned long *)
((((unsigned long)&strbuf->__flushflag_buf[0])
+ 63UL)
& ~63UL);
strbuf->strbuf_flushflag_pa = (unsigned long)
__pa(strbuf->strbuf_flushflag);
/* The SYSIO SBUS control register is used for dummy reads
* in order to ensure write completion.
*/
iommu->write_complete_reg = regs + 0x2000UL;
portid = of_getintprop_default(op->dev.of_node, "portid", -1);
printk(KERN_INFO "SYSIO: UPA portID %x, at %016lx\n",
portid, regs);
/* Setup for TSB_SIZE=7, TBW_SIZE=0, MMU_DE=1, MMU_EN=1 */
if (iommu_table_init(iommu, IO_TSB_SIZE, MAP_BASE, 0xffffffff, -1))
goto fatal_memory_error;
control = upa_readq(iommu->iommu_control);
control = ((7UL << 16UL) |
(0UL << 2UL) |
(1UL << 1UL) |
(1UL << 0UL));
upa_writeq(control, iommu->iommu_control);
/* Clean out any cruft in the IOMMU using
* diagnostic accesses.
*/
for (i = 0; i < 16; i++) {
unsigned long dram, tag;
dram = iommu->iommu_control + (IOMMU_DRAMDIAG - IOMMU_CONTROL);
tag = iommu->iommu_control + (IOMMU_TAGDIAG - IOMMU_CONTROL);
dram += (unsigned long)i * 8UL;
tag += (unsigned long)i * 8UL;
upa_writeq(0, dram);
upa_writeq(0, tag);
}
upa_readq(iommu->write_complete_reg);
/* Give the TSB to SYSIO. */
upa_writeq(__pa(iommu->page_table), iommu->iommu_tsbbase);
/* Setup streaming buffer, DE=1 SB_EN=1 */
control = (1UL << 1UL) | (1UL << 0UL);
upa_writeq(control, strbuf->strbuf_control);
/* Clear out the tags using diagnostics. */
for (i = 0; i < 16; i++) {
unsigned long ptag, ltag;
ptag = strbuf->strbuf_control +
(STRBUF_PTAGDIAG - STRBUF_CONTROL);
ltag = strbuf->strbuf_control +
(STRBUF_LTAGDIAG - STRBUF_CONTROL);
ptag += (unsigned long)i * 8UL;
ltag += (unsigned long)i * 8UL;
upa_writeq(0UL, ptag);
upa_writeq(0UL, ltag);
}
/* Enable DVMA arbitration for all devices/slots. */
control = upa_readq(iommu->write_complete_reg);
control |= 0x3fUL;
upa_writeq(control, iommu->write_complete_reg);
/* Now some Xfire specific grot... */
if (this_is_starfire)
starfire_hookup(portid);
sysio_register_error_handlers(op);
return;
fatal_memory_error:
prom_printf("sbus_iommu_init: Fatal memory allocation error.\n");
}
static int __init sbus_init(void)
{
struct device_node *dp;
for_each_node_by_name(dp, "sbus") {
struct platform_device *op = of_find_device_by_node(dp);
sbus_iommu_init(op);
of_propagate_archdata(op);
}
return 0;
}
subsys_initcall(sbus_init);
| gpl-2.0 |
Shamestick/android_kernel_htc_msm8974 | drivers/usb/class/cdc-acm.c | 2588 | 47608 | /*
* cdc-acm.c
*
* Copyright (c) 1999 Armin Fuerst <fuerst@in.tum.de>
* Copyright (c) 1999 Pavel Machek <pavel@ucw.cz>
* Copyright (c) 1999 Johannes Erdfelt <johannes@erdfelt.com>
* Copyright (c) 2000 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2004 Oliver Neukum <oliver@neukum.name>
* Copyright (c) 2005 David Kubicek <dave@awk.cz>
* Copyright (c) 2011 Johan Hovold <jhovold@gmail.com>
*
* USB Abstract Control Model driver for USB modems and ISDN adapters
*
* Sponsored by SuSE
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#undef DEBUG
#undef VERBOSE_DEBUG
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/serial.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/serial.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/cdc.h>
#include <asm/byteorder.h>
#include <asm/unaligned.h>
#include <linux/list.h>
#include "cdc-acm.h"
#define DRIVER_AUTHOR "Armin Fuerst, Pavel Machek, Johannes Erdfelt, Vojtech Pavlik, David Kubicek, Johan Hovold"
#define DRIVER_DESC "USB Abstract Control Model driver for USB modems and ISDN adapters"
static struct usb_driver acm_driver;
static struct tty_driver *acm_tty_driver;
static struct acm *acm_table[ACM_TTY_MINORS];
static DEFINE_MUTEX(acm_table_lock);
/*
* acm_table accessors
*/
/*
* Look up an ACM structure by index. If found and not disconnected, increment
* its refcount and return it with its mutex held.
*/
static struct acm *acm_get_by_index(unsigned index)
{
struct acm *acm;
mutex_lock(&acm_table_lock);
acm = acm_table[index];
if (acm) {
mutex_lock(&acm->mutex);
if (acm->disconnected) {
mutex_unlock(&acm->mutex);
acm = NULL;
} else {
tty_port_get(&acm->port);
mutex_unlock(&acm->mutex);
}
}
mutex_unlock(&acm_table_lock);
return acm;
}
/*
* Try to find an available minor number and if found, associate it with 'acm'.
*/
static int acm_alloc_minor(struct acm *acm)
{
int minor;
mutex_lock(&acm_table_lock);
for (minor = 0; minor < ACM_TTY_MINORS; minor++) {
if (!acm_table[minor]) {
acm_table[minor] = acm;
break;
}
}
mutex_unlock(&acm_table_lock);
return minor;
}
/* Release the minor number associated with 'acm'. */
static void acm_release_minor(struct acm *acm)
{
mutex_lock(&acm_table_lock);
acm_table[acm->minor] = NULL;
mutex_unlock(&acm_table_lock);
}
/*
* Functions for ACM control messages.
*/
static int acm_ctrl_msg(struct acm *acm, int request, int value,
void *buf, int len)
{
int retval = usb_control_msg(acm->dev, usb_sndctrlpipe(acm->dev, 0),
request, USB_RT_ACM, value,
acm->control->altsetting[0].desc.bInterfaceNumber,
buf, len, 5000);
dev_dbg(&acm->control->dev,
"%s - rq 0x%02x, val %#x, len %#x, result %d\n",
__func__, request, value, len, retval);
return retval < 0 ? retval : 0;
}
/* devices aren't required to support these requests.
* the cdc acm descriptor tells whether they do...
*/
#define acm_set_control(acm, control) \
acm_ctrl_msg(acm, USB_CDC_REQ_SET_CONTROL_LINE_STATE, control, NULL, 0)
#define acm_set_line(acm, line) \
acm_ctrl_msg(acm, USB_CDC_REQ_SET_LINE_CODING, 0, line, sizeof *(line))
#define acm_send_break(acm, ms) \
acm_ctrl_msg(acm, USB_CDC_REQ_SEND_BREAK, ms, NULL, 0)
/*
* Write buffer management.
* All of these assume proper locks taken by the caller.
*/
static int acm_wb_alloc(struct acm *acm)
{
int i, wbn;
struct acm_wb *wb;
wbn = 0;
i = 0;
for (;;) {
wb = &acm->wb[wbn];
if (!wb->use) {
wb->use = 1;
return wbn;
}
wbn = (wbn + 1) % ACM_NW;
if (++i >= ACM_NW)
return -1;
}
}
static int acm_wb_is_avail(struct acm *acm)
{
int i, n;
unsigned long flags;
n = ACM_NW;
spin_lock_irqsave(&acm->write_lock, flags);
for (i = 0; i < ACM_NW; i++)
n -= acm->wb[i].use;
spin_unlock_irqrestore(&acm->write_lock, flags);
return n;
}
/*
* Finish write. Caller must hold acm->write_lock
*/
static void acm_write_done(struct acm *acm, struct acm_wb *wb)
{
wb->use = 0;
acm->transmitting--;
usb_autopm_put_interface_async(acm->control);
}
/*
* Poke write.
*
* the caller is responsible for locking
*/
static int acm_start_wb(struct acm *acm, struct acm_wb *wb)
{
int rc;
acm->transmitting++;
wb->urb->transfer_buffer = wb->buf;
wb->urb->transfer_dma = wb->dmah;
wb->urb->transfer_buffer_length = wb->len;
wb->urb->dev = acm->dev;
rc = usb_submit_urb(wb->urb, GFP_ATOMIC);
if (rc < 0) {
dev_err(&acm->data->dev,
"%s - usb_submit_urb(write bulk) failed: %d\n",
__func__, rc);
acm_write_done(acm, wb);
}
return rc;
}
static int acm_write_start(struct acm *acm, int wbn)
{
unsigned long flags;
struct acm_wb *wb = &acm->wb[wbn];
int rc;
spin_lock_irqsave(&acm->write_lock, flags);
if (!acm->dev) {
wb->use = 0;
spin_unlock_irqrestore(&acm->write_lock, flags);
return -ENODEV;
}
dev_vdbg(&acm->data->dev, "%s - susp_count %d\n", __func__,
acm->susp_count);
usb_autopm_get_interface_async(acm->control);
if (acm->susp_count) {
if (!acm->delayed_wb)
acm->delayed_wb = wb;
else
usb_autopm_put_interface_async(acm->control);
spin_unlock_irqrestore(&acm->write_lock, flags);
return 0; /* A white lie */
}
usb_mark_last_busy(acm->dev);
rc = acm_start_wb(acm, wb);
spin_unlock_irqrestore(&acm->write_lock, flags);
return rc;
}
/*
* attributes exported through sysfs
*/
static ssize_t show_caps
(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct acm *acm = usb_get_intfdata(intf);
return sprintf(buf, "%d", acm->ctrl_caps);
}
static DEVICE_ATTR(bmCapabilities, S_IRUGO, show_caps, NULL);
static ssize_t show_country_codes
(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct acm *acm = usb_get_intfdata(intf);
memcpy(buf, acm->country_codes, acm->country_code_size);
return acm->country_code_size;
}
static DEVICE_ATTR(wCountryCodes, S_IRUGO, show_country_codes, NULL);
static ssize_t show_country_rel_date
(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct acm *acm = usb_get_intfdata(intf);
return sprintf(buf, "%d", acm->country_rel_date);
}
static DEVICE_ATTR(iCountryCodeRelDate, S_IRUGO, show_country_rel_date, NULL);
/*
* Interrupt handlers for various ACM device responses
*/
/* control interface reports status changes with "interrupt" transfers */
static void acm_ctrl_irq(struct urb *urb)
{
struct acm *acm = urb->context;
struct usb_cdc_notification *dr = urb->transfer_buffer;
struct tty_struct *tty;
unsigned char *data;
int newctrl;
int retval;
int status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&acm->control->dev,
"%s - urb shutting down with status: %d\n",
__func__, status);
return;
default:
dev_dbg(&acm->control->dev,
"%s - nonzero urb status received: %d\n",
__func__, status);
goto exit;
}
usb_mark_last_busy(acm->dev);
data = (unsigned char *)(dr + 1);
switch (dr->bNotificationType) {
case USB_CDC_NOTIFY_NETWORK_CONNECTION:
dev_dbg(&acm->control->dev, "%s - network connection: %d\n",
__func__, dr->wValue);
break;
case USB_CDC_NOTIFY_SERIAL_STATE:
tty = tty_port_tty_get(&acm->port);
newctrl = get_unaligned_le16(data);
if (tty) {
if (!acm->clocal &&
(acm->ctrlin & ~newctrl & ACM_CTRL_DCD)) {
dev_dbg(&acm->control->dev,
"%s - calling hangup\n", __func__);
tty_hangup(tty);
}
tty_kref_put(tty);
}
acm->ctrlin = newctrl;
dev_dbg(&acm->control->dev,
"%s - input control lines: dcd%c dsr%c break%c "
"ring%c framing%c parity%c overrun%c\n",
__func__,
acm->ctrlin & ACM_CTRL_DCD ? '+' : '-',
acm->ctrlin & ACM_CTRL_DSR ? '+' : '-',
acm->ctrlin & ACM_CTRL_BRK ? '+' : '-',
acm->ctrlin & ACM_CTRL_RI ? '+' : '-',
acm->ctrlin & ACM_CTRL_FRAMING ? '+' : '-',
acm->ctrlin & ACM_CTRL_PARITY ? '+' : '-',
acm->ctrlin & ACM_CTRL_OVERRUN ? '+' : '-');
break;
default:
dev_dbg(&acm->control->dev,
"%s - unknown notification %d received: index %d "
"len %d data0 %d data1 %d\n",
__func__,
dr->bNotificationType, dr->wIndex,
dr->wLength, data[0], data[1]);
break;
}
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
dev_err(&acm->control->dev, "%s - usb_submit_urb failed: %d\n",
__func__, retval);
}
static int acm_submit_read_urb(struct acm *acm, int index, gfp_t mem_flags)
{
int res;
if (!test_and_clear_bit(index, &acm->read_urbs_free))
return 0;
dev_vdbg(&acm->data->dev, "%s - urb %d\n", __func__, index);
res = usb_submit_urb(acm->read_urbs[index], mem_flags);
if (res) {
if (res != -EPERM) {
dev_err(&acm->data->dev,
"%s - usb_submit_urb failed: %d\n",
__func__, res);
}
set_bit(index, &acm->read_urbs_free);
return res;
}
return 0;
}
static int acm_submit_read_urbs(struct acm *acm, gfp_t mem_flags)
{
int res;
int i;
for (i = 0; i < acm->rx_buflimit; ++i) {
res = acm_submit_read_urb(acm, i, mem_flags);
if (res)
return res;
}
return 0;
}
static void acm_process_read_urb(struct acm *acm, struct urb *urb)
{
struct tty_struct *tty;
if (!urb->actual_length)
return;
tty = tty_port_tty_get(&acm->port);
if (!tty)
return;
tty_insert_flip_string(tty, urb->transfer_buffer, urb->actual_length);
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
static void acm_read_bulk_callback(struct urb *urb)
{
struct acm_rb *rb = urb->context;
struct acm *acm = rb->instance;
unsigned long flags;
dev_vdbg(&acm->data->dev, "%s - urb %d, len %d\n", __func__,
rb->index, urb->actual_length);
set_bit(rb->index, &acm->read_urbs_free);
if (!acm->dev) {
dev_dbg(&acm->data->dev, "%s - disconnected\n", __func__);
return;
}
usb_mark_last_busy(acm->dev);
if (urb->status) {
dev_dbg(&acm->data->dev, "%s - non-zero urb status: %d\n",
__func__, urb->status);
return;
}
acm_process_read_urb(acm, urb);
/* throttle device if requested by tty */
spin_lock_irqsave(&acm->read_lock, flags);
acm->throttled = acm->throttle_req;
if (!acm->throttled && !acm->susp_count) {
spin_unlock_irqrestore(&acm->read_lock, flags);
acm_submit_read_urb(acm, rb->index, GFP_ATOMIC);
} else {
spin_unlock_irqrestore(&acm->read_lock, flags);
}
}
/* data interface wrote those outgoing bytes */
static void acm_write_bulk(struct urb *urb)
{
struct acm_wb *wb = urb->context;
struct acm *acm = wb->instance;
unsigned long flags;
if (urb->status || (urb->actual_length != urb->transfer_buffer_length))
dev_vdbg(&acm->data->dev, "%s - len %d/%d, status %d\n",
__func__,
urb->actual_length,
urb->transfer_buffer_length,
urb->status);
spin_lock_irqsave(&acm->write_lock, flags);
acm_write_done(acm, wb);
spin_unlock_irqrestore(&acm->write_lock, flags);
schedule_work(&acm->work);
}
static void acm_softint(struct work_struct *work)
{
struct acm *acm = container_of(work, struct acm, work);
struct tty_struct *tty;
dev_vdbg(&acm->data->dev, "%s\n", __func__);
tty = tty_port_tty_get(&acm->port);
if (!tty)
return;
tty_wakeup(tty);
tty_kref_put(tty);
}
/*
* TTY handlers
*/
static int acm_tty_install(struct tty_driver *driver, struct tty_struct *tty)
{
struct acm *acm;
int retval;
dev_dbg(tty->dev, "%s\n", __func__);
acm = acm_get_by_index(tty->index);
if (!acm)
return -ENODEV;
retval = tty_standard_install(driver, tty);
if (retval)
goto error_init_termios;
tty->driver_data = acm;
return 0;
error_init_termios:
tty_port_put(&acm->port);
return retval;
}
static int acm_tty_open(struct tty_struct *tty, struct file *filp)
{
struct acm *acm = tty->driver_data;
dev_dbg(tty->dev, "%s\n", __func__);
return tty_port_open(&acm->port, tty, filp);
}
static int acm_port_activate(struct tty_port *port, struct tty_struct *tty)
{
struct acm *acm = container_of(port, struct acm, port);
int retval = -ENODEV;
dev_dbg(&acm->control->dev, "%s\n", __func__);
mutex_lock(&acm->mutex);
if (acm->disconnected)
goto disconnected;
retval = usb_autopm_get_interface(acm->control);
if (retval)
goto error_get_interface;
/*
* FIXME: Why do we need this? Allocating 64K of physically contiguous
* memory is really nasty...
*/
set_bit(TTY_NO_WRITE_SPLIT, &tty->flags);
acm->control->needs_remote_wakeup = 1;
acm->ctrlurb->dev = acm->dev;
if (usb_submit_urb(acm->ctrlurb, GFP_KERNEL)) {
dev_err(&acm->control->dev,
"%s - usb_submit_urb(ctrl irq) failed\n", __func__);
goto error_submit_urb;
}
acm->ctrlout = ACM_CTRL_DTR | ACM_CTRL_RTS;
if (acm_set_control(acm, acm->ctrlout) < 0 &&
(acm->ctrl_caps & USB_CDC_CAP_LINE))
goto error_set_control;
usb_autopm_put_interface(acm->control);
if (acm_submit_read_urbs(acm, GFP_KERNEL))
goto error_submit_read_urbs;
mutex_unlock(&acm->mutex);
return 0;
error_submit_read_urbs:
acm->ctrlout = 0;
acm_set_control(acm, acm->ctrlout);
error_set_control:
usb_kill_urb(acm->ctrlurb);
error_submit_urb:
usb_autopm_put_interface(acm->control);
error_get_interface:
disconnected:
mutex_unlock(&acm->mutex);
return retval;
}
static void acm_port_destruct(struct tty_port *port)
{
struct acm *acm = container_of(port, struct acm, port);
dev_dbg(&acm->control->dev, "%s\n", __func__);
tty_unregister_device(acm_tty_driver, acm->minor);
acm_release_minor(acm);
usb_put_intf(acm->control);
kfree(acm->country_codes);
kfree(acm);
}
static void acm_port_shutdown(struct tty_port *port)
{
struct acm *acm = container_of(port, struct acm, port);
int i;
dev_dbg(&acm->control->dev, "%s\n", __func__);
mutex_lock(&acm->mutex);
if (!acm->disconnected) {
usb_autopm_get_interface(acm->control);
acm_set_control(acm, acm->ctrlout = 0);
usb_kill_urb(acm->ctrlurb);
for (i = 0; i < ACM_NW; i++)
usb_kill_urb(acm->wb[i].urb);
for (i = 0; i < acm->rx_buflimit; i++)
usb_kill_urb(acm->read_urbs[i]);
acm->control->needs_remote_wakeup = 0;
usb_autopm_put_interface(acm->control);
}
mutex_unlock(&acm->mutex);
}
static void acm_tty_cleanup(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
dev_dbg(&acm->control->dev, "%s\n", __func__);
tty_port_put(&acm->port);
}
static void acm_tty_hangup(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
dev_dbg(&acm->control->dev, "%s\n", __func__);
tty_port_hangup(&acm->port);
}
static void acm_tty_close(struct tty_struct *tty, struct file *filp)
{
struct acm *acm = tty->driver_data;
dev_dbg(&acm->control->dev, "%s\n", __func__);
tty_port_close(&acm->port, tty, filp);
}
static int acm_tty_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
struct acm *acm = tty->driver_data;
int stat;
unsigned long flags;
int wbn;
struct acm_wb *wb;
if (!count)
return 0;
dev_vdbg(&acm->data->dev, "%s - count %d\n", __func__, count);
spin_lock_irqsave(&acm->write_lock, flags);
wbn = acm_wb_alloc(acm);
if (wbn < 0) {
spin_unlock_irqrestore(&acm->write_lock, flags);
return 0;
}
wb = &acm->wb[wbn];
count = (count > acm->writesize) ? acm->writesize : count;
dev_vdbg(&acm->data->dev, "%s - write %d\n", __func__, count);
memcpy(wb->buf, buf, count);
wb->len = count;
spin_unlock_irqrestore(&acm->write_lock, flags);
stat = acm_write_start(acm, wbn);
if (stat < 0)
return stat;
return count;
}
static int acm_tty_write_room(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
/*
* Do not let the line discipline to know that we have a reserve,
* or it might get too enthusiastic.
*/
return acm_wb_is_avail(acm) ? acm->writesize : 0;
}
static int acm_tty_chars_in_buffer(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
/*
* if the device was unplugged then any remaining characters fell out
* of the connector ;)
*/
if (acm->disconnected)
return 0;
/*
* This is inaccurate (overcounts), but it works.
*/
return (ACM_NW - acm_wb_is_avail(acm)) * acm->writesize;
}
static void acm_tty_throttle(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
spin_lock_irq(&acm->read_lock);
acm->throttle_req = 1;
spin_unlock_irq(&acm->read_lock);
}
static void acm_tty_unthrottle(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
unsigned int was_throttled;
spin_lock_irq(&acm->read_lock);
was_throttled = acm->throttled;
acm->throttled = 0;
acm->throttle_req = 0;
spin_unlock_irq(&acm->read_lock);
if (was_throttled)
acm_submit_read_urbs(acm, GFP_KERNEL);
}
static int acm_tty_break_ctl(struct tty_struct *tty, int state)
{
struct acm *acm = tty->driver_data;
int retval;
retval = acm_send_break(acm, state ? 0xffff : 0);
if (retval < 0)
dev_dbg(&acm->control->dev, "%s - send break failed\n",
__func__);
return retval;
}
static int acm_tty_tiocmget(struct tty_struct *tty)
{
struct acm *acm = tty->driver_data;
return (acm->ctrlout & ACM_CTRL_DTR ? TIOCM_DTR : 0) |
(acm->ctrlout & ACM_CTRL_RTS ? TIOCM_RTS : 0) |
(acm->ctrlin & ACM_CTRL_DSR ? TIOCM_DSR : 0) |
(acm->ctrlin & ACM_CTRL_RI ? TIOCM_RI : 0) |
(acm->ctrlin & ACM_CTRL_DCD ? TIOCM_CD : 0) |
TIOCM_CTS;
}
static int acm_tty_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct acm *acm = tty->driver_data;
unsigned int newctrl;
newctrl = acm->ctrlout;
set = (set & TIOCM_DTR ? ACM_CTRL_DTR : 0) |
(set & TIOCM_RTS ? ACM_CTRL_RTS : 0);
clear = (clear & TIOCM_DTR ? ACM_CTRL_DTR : 0) |
(clear & TIOCM_RTS ? ACM_CTRL_RTS : 0);
newctrl = (newctrl & ~clear) | set;
if (acm->ctrlout == newctrl)
return 0;
return acm_set_control(acm, acm->ctrlout = newctrl);
}
static int get_serial_info(struct acm *acm, struct serial_struct __user *info)
{
struct serial_struct tmp;
if (!info)
return -EINVAL;
memset(&tmp, 0, sizeof(tmp));
tmp.flags = ASYNC_LOW_LATENCY;
tmp.xmit_fifo_size = acm->writesize;
tmp.baud_base = le32_to_cpu(acm->line.dwDTERate);
if (copy_to_user(info, &tmp, sizeof(tmp)))
return -EFAULT;
else
return 0;
}
static int acm_tty_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct acm *acm = tty->driver_data;
int rv = -ENOIOCTLCMD;
switch (cmd) {
case TIOCGSERIAL: /* gets serial port data */
rv = get_serial_info(acm, (struct serial_struct __user *) arg);
break;
}
return rv;
}
static const __u32 acm_tty_speed[] = {
0, 50, 75, 110, 134, 150, 200, 300, 600,
1200, 1800, 2400, 4800, 9600, 19200, 38400,
57600, 115200, 230400, 460800, 500000, 576000,
921600, 1000000, 1152000, 1500000, 2000000,
2500000, 3000000, 3500000, 4000000
};
static const __u8 acm_tty_size[] = {
5, 6, 7, 8
};
static void acm_tty_set_termios(struct tty_struct *tty,
struct ktermios *termios_old)
{
struct acm *acm = tty->driver_data;
struct ktermios *termios = tty->termios;
struct usb_cdc_line_coding newline;
int newctrl = acm->ctrlout;
newline.dwDTERate = cpu_to_le32(tty_get_baud_rate(tty));
newline.bCharFormat = termios->c_cflag & CSTOPB ? 2 : 0;
newline.bParityType = termios->c_cflag & PARENB ?
(termios->c_cflag & PARODD ? 1 : 2) +
(termios->c_cflag & CMSPAR ? 2 : 0) : 0;
newline.bDataBits = acm_tty_size[(termios->c_cflag & CSIZE) >> 4];
/* FIXME: Needs to clear unsupported bits in the termios */
acm->clocal = ((termios->c_cflag & CLOCAL) != 0);
if (!newline.dwDTERate) {
newline.dwDTERate = acm->line.dwDTERate;
newctrl &= ~ACM_CTRL_DTR;
} else
newctrl |= ACM_CTRL_DTR;
if (newctrl != acm->ctrlout)
acm_set_control(acm, acm->ctrlout = newctrl);
if (memcmp(&acm->line, &newline, sizeof newline)) {
memcpy(&acm->line, &newline, sizeof newline);
dev_dbg(&acm->control->dev, "%s - set line: %d %d %d %d\n",
__func__,
le32_to_cpu(newline.dwDTERate),
newline.bCharFormat, newline.bParityType,
newline.bDataBits);
acm_set_line(acm, &acm->line);
}
}
static const struct tty_port_operations acm_port_ops = {
.shutdown = acm_port_shutdown,
.activate = acm_port_activate,
.destruct = acm_port_destruct,
};
/*
* USB probe and disconnect routines.
*/
/* Little helpers: write/read buffers free */
static void acm_write_buffers_free(struct acm *acm)
{
int i;
struct acm_wb *wb;
struct usb_device *usb_dev = interface_to_usbdev(acm->control);
for (wb = &acm->wb[0], i = 0; i < ACM_NW; i++, wb++)
usb_free_coherent(usb_dev, acm->writesize, wb->buf, wb->dmah);
}
static void acm_read_buffers_free(struct acm *acm)
{
struct usb_device *usb_dev = interface_to_usbdev(acm->control);
int i;
for (i = 0; i < acm->rx_buflimit; i++)
usb_free_coherent(usb_dev, acm->readsize,
acm->read_buffers[i].base, acm->read_buffers[i].dma);
}
/* Little helper: write buffers allocate */
static int acm_write_buffers_alloc(struct acm *acm)
{
int i;
struct acm_wb *wb;
for (wb = &acm->wb[0], i = 0; i < ACM_NW; i++, wb++) {
wb->buf = usb_alloc_coherent(acm->dev, acm->writesize, GFP_KERNEL,
&wb->dmah);
if (!wb->buf) {
while (i != 0) {
--i;
--wb;
usb_free_coherent(acm->dev, acm->writesize,
wb->buf, wb->dmah);
}
return -ENOMEM;
}
}
return 0;
}
static int acm_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_cdc_union_desc *union_header = NULL;
struct usb_cdc_country_functional_desc *cfd = NULL;
unsigned char *buffer = intf->altsetting->extra;
int buflen = intf->altsetting->extralen;
struct usb_interface *control_interface;
struct usb_interface *data_interface;
struct usb_endpoint_descriptor *epctrl = NULL;
struct usb_endpoint_descriptor *epread = NULL;
struct usb_endpoint_descriptor *epwrite = NULL;
struct usb_device *usb_dev = interface_to_usbdev(intf);
struct acm *acm;
int minor;
int ctrlsize, readsize;
u8 *buf;
u8 ac_management_function = 0;
u8 call_management_function = 0;
int call_interface_num = -1;
int data_interface_num = -1;
unsigned long quirks;
int num_rx_buf;
int i;
int combined_interfaces = 0;
/* normal quirks */
quirks = (unsigned long)id->driver_info;
num_rx_buf = (quirks == SINGLE_RX_URB) ? 1 : ACM_NR;
/* handle quirks deadly to normal probing*/
if (quirks == NO_UNION_NORMAL) {
data_interface = usb_ifnum_to_if(usb_dev, 1);
control_interface = usb_ifnum_to_if(usb_dev, 0);
goto skip_normal_probe;
}
/* normal probing*/
if (!buffer) {
dev_err(&intf->dev, "Weird descriptor references\n");
return -EINVAL;
}
if (!buflen) {
if (intf->cur_altsetting->endpoint &&
intf->cur_altsetting->endpoint->extralen &&
intf->cur_altsetting->endpoint->extra) {
dev_dbg(&intf->dev,
"Seeking extra descriptors on endpoint\n");
buflen = intf->cur_altsetting->endpoint->extralen;
buffer = intf->cur_altsetting->endpoint->extra;
} else {
dev_err(&intf->dev,
"Zero length descriptor references\n");
return -EINVAL;
}
}
while (buflen > 0) {
if (buffer[1] != USB_DT_CS_INTERFACE) {
dev_err(&intf->dev, "skipping garbage\n");
goto next_desc;
}
switch (buffer[2]) {
case USB_CDC_UNION_TYPE: /* we've found it */
if (union_header) {
dev_err(&intf->dev, "More than one "
"union descriptor, skipping ...\n");
goto next_desc;
}
union_header = (struct usb_cdc_union_desc *)buffer;
break;
case USB_CDC_COUNTRY_TYPE: /* export through sysfs*/
cfd = (struct usb_cdc_country_functional_desc *)buffer;
break;
case USB_CDC_HEADER_TYPE: /* maybe check version */
break; /* for now we ignore it */
case USB_CDC_ACM_TYPE:
ac_management_function = buffer[3];
break;
case USB_CDC_CALL_MANAGEMENT_TYPE:
call_management_function = buffer[3];
call_interface_num = buffer[4];
if ( (quirks & NOT_A_MODEM) == 0 && (call_management_function & 3) != 3)
dev_err(&intf->dev, "This device cannot do calls on its own. It is not a modem.\n");
break;
default:
/* there are LOTS more CDC descriptors that
* could legitimately be found here.
*/
dev_dbg(&intf->dev, "Ignoring descriptor: "
"type %02x, length %d\n",
buffer[2], buffer[0]);
break;
}
next_desc:
buflen -= buffer[0];
buffer += buffer[0];
}
if (!union_header) {
if (call_interface_num > 0) {
dev_dbg(&intf->dev, "No union descriptor, using call management descriptor\n");
/* quirks for Droids MuIn LCD */
if (quirks & NO_DATA_INTERFACE)
data_interface = usb_ifnum_to_if(usb_dev, 0);
else
data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = call_interface_num));
control_interface = intf;
} else {
if (intf->cur_altsetting->desc.bNumEndpoints != 3) {
dev_dbg(&intf->dev,"No union descriptor, giving up\n");
return -ENODEV;
} else {
dev_warn(&intf->dev,"No union descriptor, testing for castrated device\n");
combined_interfaces = 1;
control_interface = data_interface = intf;
goto look_for_collapsed_interface;
}
}
} else {
control_interface = usb_ifnum_to_if(usb_dev, union_header->bMasterInterface0);
data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = union_header->bSlaveInterface0));
if (!control_interface || !data_interface) {
dev_dbg(&intf->dev, "no interfaces\n");
return -ENODEV;
}
}
if (data_interface_num != call_interface_num)
dev_dbg(&intf->dev, "Separate call control interface. That is not fully supported.\n");
if (control_interface == data_interface) {
/* some broken devices designed for windows work this way */
dev_warn(&intf->dev,"Control and data interfaces are not separated!\n");
combined_interfaces = 1;
/* a popular other OS doesn't use it */
quirks |= NO_CAP_LINE;
if (data_interface->cur_altsetting->desc.bNumEndpoints != 3) {
dev_err(&intf->dev, "This needs exactly 3 endpoints\n");
return -EINVAL;
}
look_for_collapsed_interface:
for (i = 0; i < 3; i++) {
struct usb_endpoint_descriptor *ep;
ep = &data_interface->cur_altsetting->endpoint[i].desc;
if (usb_endpoint_is_int_in(ep))
epctrl = ep;
else if (usb_endpoint_is_bulk_out(ep))
epwrite = ep;
else if (usb_endpoint_is_bulk_in(ep))
epread = ep;
else
return -EINVAL;
}
if (!epctrl || !epread || !epwrite)
return -ENODEV;
else
goto made_compressed_probe;
}
skip_normal_probe:
/*workaround for switched interfaces */
if (data_interface->cur_altsetting->desc.bInterfaceClass
!= CDC_DATA_INTERFACE_TYPE) {
if (control_interface->cur_altsetting->desc.bInterfaceClass
== CDC_DATA_INTERFACE_TYPE) {
struct usb_interface *t;
dev_dbg(&intf->dev,
"Your device has switched interfaces.\n");
t = control_interface;
control_interface = data_interface;
data_interface = t;
} else {
return -EINVAL;
}
}
/* Accept probe requests only for the control interface */
if (!combined_interfaces && intf != control_interface)
return -ENODEV;
if (!combined_interfaces && usb_interface_claimed(data_interface)) {
/* valid in this context */
dev_dbg(&intf->dev, "The data interface isn't available\n");
return -EBUSY;
}
if (data_interface->cur_altsetting->desc.bNumEndpoints < 2)
return -EINVAL;
epctrl = &control_interface->cur_altsetting->endpoint[0].desc;
epread = &data_interface->cur_altsetting->endpoint[0].desc;
epwrite = &data_interface->cur_altsetting->endpoint[1].desc;
/* workaround for switched endpoints */
if (!usb_endpoint_dir_in(epread)) {
/* descriptors are swapped */
struct usb_endpoint_descriptor *t;
dev_dbg(&intf->dev,
"The data interface has switched endpoints\n");
t = epread;
epread = epwrite;
epwrite = t;
}
made_compressed_probe:
dev_dbg(&intf->dev, "interfaces are valid\n");
acm = kzalloc(sizeof(struct acm), GFP_KERNEL);
if (acm == NULL) {
dev_err(&intf->dev, "out of memory (acm kzalloc)\n");
goto alloc_fail;
}
minor = acm_alloc_minor(acm);
if (minor == ACM_TTY_MINORS) {
dev_err(&intf->dev, "no more free acm devices\n");
kfree(acm);
return -ENODEV;
}
ctrlsize = usb_endpoint_maxp(epctrl);
readsize = usb_endpoint_maxp(epread) *
(quirks == SINGLE_RX_URB ? 1 : 2);
acm->combined_interfaces = combined_interfaces;
acm->writesize = usb_endpoint_maxp(epwrite) * 20;
acm->control = control_interface;
acm->data = data_interface;
acm->minor = minor;
acm->dev = usb_dev;
acm->ctrl_caps = ac_management_function;
if (quirks & NO_CAP_LINE)
acm->ctrl_caps &= ~USB_CDC_CAP_LINE;
acm->ctrlsize = ctrlsize;
acm->readsize = readsize;
acm->rx_buflimit = num_rx_buf;
INIT_WORK(&acm->work, acm_softint);
spin_lock_init(&acm->write_lock);
spin_lock_init(&acm->read_lock);
mutex_init(&acm->mutex);
acm->rx_endpoint = usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress);
acm->is_int_ep = usb_endpoint_xfer_int(epread);
if (acm->is_int_ep)
acm->bInterval = epread->bInterval;
tty_port_init(&acm->port);
acm->port.ops = &acm_port_ops;
buf = usb_alloc_coherent(usb_dev, ctrlsize, GFP_KERNEL, &acm->ctrl_dma);
if (!buf) {
dev_err(&intf->dev, "out of memory (ctrl buffer alloc)\n");
goto alloc_fail2;
}
acm->ctrl_buffer = buf;
if (acm_write_buffers_alloc(acm) < 0) {
dev_err(&intf->dev, "out of memory (write buffer alloc)\n");
goto alloc_fail4;
}
acm->ctrlurb = usb_alloc_urb(0, GFP_KERNEL);
if (!acm->ctrlurb) {
dev_err(&intf->dev, "out of memory (ctrlurb kmalloc)\n");
goto alloc_fail5;
}
for (i = 0; i < num_rx_buf; i++) {
struct acm_rb *rb = &(acm->read_buffers[i]);
struct urb *urb;
rb->base = usb_alloc_coherent(acm->dev, readsize, GFP_KERNEL,
&rb->dma);
if (!rb->base) {
dev_err(&intf->dev, "out of memory "
"(read bufs usb_alloc_coherent)\n");
goto alloc_fail6;
}
rb->index = i;
rb->instance = acm;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb) {
dev_err(&intf->dev,
"out of memory (read urbs usb_alloc_urb)\n");
goto alloc_fail6;
}
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
urb->transfer_dma = rb->dma;
if (acm->is_int_ep) {
usb_fill_int_urb(urb, acm->dev,
acm->rx_endpoint,
rb->base,
acm->readsize,
acm_read_bulk_callback, rb,
acm->bInterval);
} else {
usb_fill_bulk_urb(urb, acm->dev,
acm->rx_endpoint,
rb->base,
acm->readsize,
acm_read_bulk_callback, rb);
}
acm->read_urbs[i] = urb;
__set_bit(i, &acm->read_urbs_free);
}
for (i = 0; i < ACM_NW; i++) {
struct acm_wb *snd = &(acm->wb[i]);
snd->urb = usb_alloc_urb(0, GFP_KERNEL);
if (snd->urb == NULL) {
dev_err(&intf->dev,
"out of memory (write urbs usb_alloc_urb)\n");
goto alloc_fail7;
}
if (usb_endpoint_xfer_int(epwrite))
usb_fill_int_urb(snd->urb, usb_dev,
usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress),
NULL, acm->writesize, acm_write_bulk, snd, epwrite->bInterval);
else
usb_fill_bulk_urb(snd->urb, usb_dev,
usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress),
NULL, acm->writesize, acm_write_bulk, snd);
snd->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
snd->instance = acm;
}
usb_set_intfdata(intf, acm);
i = device_create_file(&intf->dev, &dev_attr_bmCapabilities);
if (i < 0)
goto alloc_fail7;
if (cfd) { /* export the country data */
acm->country_codes = kmalloc(cfd->bLength - 4, GFP_KERNEL);
if (!acm->country_codes)
goto skip_countries;
acm->country_code_size = cfd->bLength - 4;
memcpy(acm->country_codes, (u8 *)&cfd->wCountyCode0,
cfd->bLength - 4);
acm->country_rel_date = cfd->iCountryCodeRelDate;
i = device_create_file(&intf->dev, &dev_attr_wCountryCodes);
if (i < 0) {
kfree(acm->country_codes);
acm->country_codes = NULL;
acm->country_code_size = 0;
goto skip_countries;
}
i = device_create_file(&intf->dev,
&dev_attr_iCountryCodeRelDate);
if (i < 0) {
device_remove_file(&intf->dev, &dev_attr_wCountryCodes);
kfree(acm->country_codes);
acm->country_codes = NULL;
acm->country_code_size = 0;
goto skip_countries;
}
}
skip_countries:
usb_fill_int_urb(acm->ctrlurb, usb_dev,
usb_rcvintpipe(usb_dev, epctrl->bEndpointAddress),
acm->ctrl_buffer, ctrlsize, acm_ctrl_irq, acm,
/* works around buggy devices */
epctrl->bInterval ? epctrl->bInterval : 0xff);
acm->ctrlurb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
acm->ctrlurb->transfer_dma = acm->ctrl_dma;
dev_info(&intf->dev, "ttyACM%d: USB ACM device\n", minor);
acm_set_control(acm, acm->ctrlout);
acm->line.dwDTERate = cpu_to_le32(9600);
acm->line.bDataBits = 8;
acm_set_line(acm, &acm->line);
usb_driver_claim_interface(&acm_driver, data_interface, acm);
usb_set_intfdata(data_interface, acm);
usb_get_intf(control_interface);
tty_register_device(acm_tty_driver, minor, &control_interface->dev);
return 0;
alloc_fail7:
for (i = 0; i < ACM_NW; i++)
usb_free_urb(acm->wb[i].urb);
alloc_fail6:
for (i = 0; i < num_rx_buf; i++)
usb_free_urb(acm->read_urbs[i]);
acm_read_buffers_free(acm);
usb_free_urb(acm->ctrlurb);
alloc_fail5:
acm_write_buffers_free(acm);
alloc_fail4:
usb_free_coherent(usb_dev, ctrlsize, acm->ctrl_buffer, acm->ctrl_dma);
alloc_fail2:
acm_release_minor(acm);
kfree(acm);
alloc_fail:
return -ENOMEM;
}
static void stop_data_traffic(struct acm *acm)
{
int i;
dev_dbg(&acm->control->dev, "%s\n", __func__);
usb_kill_urb(acm->ctrlurb);
for (i = 0; i < ACM_NW; i++)
usb_kill_urb(acm->wb[i].urb);
for (i = 0; i < acm->rx_buflimit; i++)
usb_kill_urb(acm->read_urbs[i]);
cancel_work_sync(&acm->work);
}
static void acm_disconnect(struct usb_interface *intf)
{
struct acm *acm = usb_get_intfdata(intf);
struct usb_device *usb_dev = interface_to_usbdev(intf);
struct tty_struct *tty;
int i;
dev_dbg(&intf->dev, "%s\n", __func__);
/* sibling interface is already cleaning up */
if (!acm)
return;
mutex_lock(&acm->mutex);
acm->disconnected = true;
if (acm->country_codes) {
device_remove_file(&acm->control->dev,
&dev_attr_wCountryCodes);
device_remove_file(&acm->control->dev,
&dev_attr_iCountryCodeRelDate);
}
device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities);
usb_set_intfdata(acm->control, NULL);
usb_set_intfdata(acm->data, NULL);
mutex_unlock(&acm->mutex);
tty = tty_port_tty_get(&acm->port);
if (tty) {
tty_vhangup(tty);
tty_kref_put(tty);
}
stop_data_traffic(acm);
usb_free_urb(acm->ctrlurb);
for (i = 0; i < ACM_NW; i++)
usb_free_urb(acm->wb[i].urb);
for (i = 0; i < acm->rx_buflimit; i++)
usb_free_urb(acm->read_urbs[i]);
acm_write_buffers_free(acm);
usb_free_coherent(usb_dev, acm->ctrlsize, acm->ctrl_buffer, acm->ctrl_dma);
acm_read_buffers_free(acm);
if (!acm->combined_interfaces)
usb_driver_release_interface(&acm_driver, intf == acm->control ?
acm->data : acm->control);
tty_port_put(&acm->port);
}
#ifdef CONFIG_PM
static int acm_suspend(struct usb_interface *intf, pm_message_t message)
{
struct acm *acm = usb_get_intfdata(intf);
int cnt;
if (PMSG_IS_AUTO(message)) {
int b;
spin_lock_irq(&acm->write_lock);
b = acm->transmitting;
spin_unlock_irq(&acm->write_lock);
if (b)
return -EBUSY;
}
spin_lock_irq(&acm->read_lock);
spin_lock(&acm->write_lock);
cnt = acm->susp_count++;
spin_unlock(&acm->write_lock);
spin_unlock_irq(&acm->read_lock);
if (cnt)
return 0;
if (test_bit(ASYNCB_INITIALIZED, &acm->port.flags))
stop_data_traffic(acm);
return 0;
}
static int acm_resume(struct usb_interface *intf)
{
struct acm *acm = usb_get_intfdata(intf);
struct acm_wb *wb;
int rv = 0;
int cnt;
spin_lock_irq(&acm->read_lock);
acm->susp_count -= 1;
cnt = acm->susp_count;
spin_unlock_irq(&acm->read_lock);
if (cnt)
return 0;
if (test_bit(ASYNCB_INITIALIZED, &acm->port.flags)) {
rv = usb_submit_urb(acm->ctrlurb, GFP_NOIO);
spin_lock_irq(&acm->write_lock);
if (acm->delayed_wb) {
wb = acm->delayed_wb;
acm->delayed_wb = NULL;
spin_unlock_irq(&acm->write_lock);
acm_start_wb(acm, wb);
} else {
spin_unlock_irq(&acm->write_lock);
}
/*
* delayed error checking because we must
* do the write path at all cost
*/
if (rv < 0)
goto err_out;
rv = acm_submit_read_urbs(acm, GFP_NOIO);
}
err_out:
return rv;
}
static int acm_reset_resume(struct usb_interface *intf)
{
struct acm *acm = usb_get_intfdata(intf);
struct tty_struct *tty;
if (test_bit(ASYNCB_INITIALIZED, &acm->port.flags)) {
tty = tty_port_tty_get(&acm->port);
if (tty) {
tty_hangup(tty);
tty_kref_put(tty);
}
}
return acm_resume(intf);
}
#endif /* CONFIG_PM */
#define NOKIA_PCSUITE_ACM_INFO(x) \
USB_DEVICE_AND_INTERFACE_INFO(0x0421, x, \
USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, \
USB_CDC_ACM_PROTO_VENDOR)
#define SAMSUNG_PCSUITE_ACM_INFO(x) \
USB_DEVICE_AND_INTERFACE_INFO(0x04e7, x, \
USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM, \
USB_CDC_ACM_PROTO_VENDOR)
/*
* USB driver structure.
*/
static const struct usb_device_id acm_ids[] = {
/* quirky and broken devices */
{ USB_DEVICE(0x0870, 0x0001), /* Metricom GS Modem */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0e8d, 0x0003), /* FIREFLY, MediaTek Inc; andrey.arapov@gmail.com */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0e8d, 0x3329), /* MediaTek Inc GPS */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0482, 0x0203), /* KYOCERA AH-K3001V */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x079b, 0x000f), /* BT On-Air USB MODEM */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0ace, 0x1602), /* ZyDAS 56K USB MODEM */
.driver_info = SINGLE_RX_URB,
},
{ USB_DEVICE(0x0ace, 0x1608), /* ZyDAS 56K USB MODEM */
.driver_info = SINGLE_RX_URB, /* firmware bug */
},
{ USB_DEVICE(0x0ace, 0x1611), /* ZyDAS 56K USB MODEM - new version */
.driver_info = SINGLE_RX_URB, /* firmware bug */
},
{ USB_DEVICE(0x22b8, 0x7000), /* Motorola Q Phone */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0803, 0x3095), /* Zoom Telephonics Model 3095F USB MODEM */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0572, 0x1321), /* Conexant USB MODEM CX93010 */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0572, 0x1324), /* Conexant USB MODEM RD02-D400 */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x0572, 0x1328), /* Shiro / Aztech USB MODEM UM-3100 */
.driver_info = NO_UNION_NORMAL, /* has no union descriptor */
},
{ USB_DEVICE(0x22b8, 0x6425), /* Motorola MOTOMAGX phones */
},
/* Motorola H24 HSPA module: */
{ USB_DEVICE(0x22b8, 0x2d91) }, /* modem */
{ USB_DEVICE(0x22b8, 0x2d92) }, /* modem + diagnostics */
{ USB_DEVICE(0x22b8, 0x2d93) }, /* modem + AT port */
{ USB_DEVICE(0x22b8, 0x2d95) }, /* modem + AT port + diagnostics */
{ USB_DEVICE(0x22b8, 0x2d96) }, /* modem + NMEA */
{ USB_DEVICE(0x22b8, 0x2d97) }, /* modem + diagnostics + NMEA */
{ USB_DEVICE(0x22b8, 0x2d99) }, /* modem + AT port + NMEA */
{ USB_DEVICE(0x22b8, 0x2d9a) }, /* modem + AT port + diagnostics + NMEA */
{ USB_DEVICE(0x0572, 0x1329), /* Hummingbird huc56s (Conexant) */
.driver_info = NO_UNION_NORMAL, /* union descriptor misplaced on
data interface instead of
communications interface.
Maybe we should define a new
quirk for this. */
},
{ USB_DEVICE(0x1bbb, 0x0003), /* Alcatel OT-I650 */
.driver_info = NO_UNION_NORMAL, /* reports zero length descriptor */
},
{ USB_DEVICE(0x1576, 0x03b1), /* Maretron USB100 */
.driver_info = NO_UNION_NORMAL, /* reports zero length descriptor */
},
/* Nokia S60 phones expose two ACM channels. The first is
* a modem and is picked up by the standard AT-command
* information below. The second is 'vendor-specific' but
* is treated as a serial device at the S60 end, so we want
* to expose it on Linux too. */
{ NOKIA_PCSUITE_ACM_INFO(0x042D), }, /* Nokia 3250 */
{ NOKIA_PCSUITE_ACM_INFO(0x04D8), }, /* Nokia 5500 Sport */
{ NOKIA_PCSUITE_ACM_INFO(0x04C9), }, /* Nokia E50 */
{ NOKIA_PCSUITE_ACM_INFO(0x0419), }, /* Nokia E60 */
{ NOKIA_PCSUITE_ACM_INFO(0x044D), }, /* Nokia E61 */
{ NOKIA_PCSUITE_ACM_INFO(0x0001), }, /* Nokia E61i */
{ NOKIA_PCSUITE_ACM_INFO(0x0475), }, /* Nokia E62 */
{ NOKIA_PCSUITE_ACM_INFO(0x0508), }, /* Nokia E65 */
{ NOKIA_PCSUITE_ACM_INFO(0x0418), }, /* Nokia E70 */
{ NOKIA_PCSUITE_ACM_INFO(0x0425), }, /* Nokia N71 */
{ NOKIA_PCSUITE_ACM_INFO(0x0486), }, /* Nokia N73 */
{ NOKIA_PCSUITE_ACM_INFO(0x04DF), }, /* Nokia N75 */
{ NOKIA_PCSUITE_ACM_INFO(0x000e), }, /* Nokia N77 */
{ NOKIA_PCSUITE_ACM_INFO(0x0445), }, /* Nokia N80 */
{ NOKIA_PCSUITE_ACM_INFO(0x042F), }, /* Nokia N91 & N91 8GB */
{ NOKIA_PCSUITE_ACM_INFO(0x048E), }, /* Nokia N92 */
{ NOKIA_PCSUITE_ACM_INFO(0x0420), }, /* Nokia N93 */
{ NOKIA_PCSUITE_ACM_INFO(0x04E6), }, /* Nokia N93i */
{ NOKIA_PCSUITE_ACM_INFO(0x04B2), }, /* Nokia 5700 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x0134), }, /* Nokia 6110 Navigator (China) */
{ NOKIA_PCSUITE_ACM_INFO(0x046E), }, /* Nokia 6110 Navigator */
{ NOKIA_PCSUITE_ACM_INFO(0x002f), }, /* Nokia 6120 classic & */
{ NOKIA_PCSUITE_ACM_INFO(0x0088), }, /* Nokia 6121 classic */
{ NOKIA_PCSUITE_ACM_INFO(0x00fc), }, /* Nokia 6124 classic */
{ NOKIA_PCSUITE_ACM_INFO(0x0042), }, /* Nokia E51 */
{ NOKIA_PCSUITE_ACM_INFO(0x00b0), }, /* Nokia E66 */
{ NOKIA_PCSUITE_ACM_INFO(0x00ab), }, /* Nokia E71 */
{ NOKIA_PCSUITE_ACM_INFO(0x0481), }, /* Nokia N76 */
{ NOKIA_PCSUITE_ACM_INFO(0x0007), }, /* Nokia N81 & N81 8GB */
{ NOKIA_PCSUITE_ACM_INFO(0x0071), }, /* Nokia N82 */
{ NOKIA_PCSUITE_ACM_INFO(0x04F0), }, /* Nokia N95 & N95-3 NAM */
{ NOKIA_PCSUITE_ACM_INFO(0x0070), }, /* Nokia N95 8GB */
{ NOKIA_PCSUITE_ACM_INFO(0x00e9), }, /* Nokia 5320 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x0099), }, /* Nokia 6210 Navigator, RM-367 */
{ NOKIA_PCSUITE_ACM_INFO(0x0128), }, /* Nokia 6210 Navigator, RM-419 */
{ NOKIA_PCSUITE_ACM_INFO(0x008f), }, /* Nokia 6220 Classic */
{ NOKIA_PCSUITE_ACM_INFO(0x00a0), }, /* Nokia 6650 */
{ NOKIA_PCSUITE_ACM_INFO(0x007b), }, /* Nokia N78 */
{ NOKIA_PCSUITE_ACM_INFO(0x0094), }, /* Nokia N85 */
{ NOKIA_PCSUITE_ACM_INFO(0x003a), }, /* Nokia N96 & N96-3 */
{ NOKIA_PCSUITE_ACM_INFO(0x00e9), }, /* Nokia 5320 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x0108), }, /* Nokia 5320 XpressMusic 2G */
{ NOKIA_PCSUITE_ACM_INFO(0x01f5), }, /* Nokia N97, RM-505 */
{ NOKIA_PCSUITE_ACM_INFO(0x02e3), }, /* Nokia 5230, RM-588 */
{ NOKIA_PCSUITE_ACM_INFO(0x0178), }, /* Nokia E63 */
{ NOKIA_PCSUITE_ACM_INFO(0x010e), }, /* Nokia E75 */
{ NOKIA_PCSUITE_ACM_INFO(0x02d9), }, /* Nokia 6760 Slide */
{ NOKIA_PCSUITE_ACM_INFO(0x01d0), }, /* Nokia E52 */
{ NOKIA_PCSUITE_ACM_INFO(0x0223), }, /* Nokia E72 */
{ NOKIA_PCSUITE_ACM_INFO(0x0275), }, /* Nokia X6 */
{ NOKIA_PCSUITE_ACM_INFO(0x026c), }, /* Nokia N97 Mini */
{ NOKIA_PCSUITE_ACM_INFO(0x0154), }, /* Nokia 5800 XpressMusic */
{ NOKIA_PCSUITE_ACM_INFO(0x04ce), }, /* Nokia E90 */
{ NOKIA_PCSUITE_ACM_INFO(0x01d4), }, /* Nokia E55 */
{ NOKIA_PCSUITE_ACM_INFO(0x0302), }, /* Nokia N8 */
{ NOKIA_PCSUITE_ACM_INFO(0x0335), }, /* Nokia E7 */
{ NOKIA_PCSUITE_ACM_INFO(0x03cd), }, /* Nokia C7 */
{ SAMSUNG_PCSUITE_ACM_INFO(0x6651), }, /* Samsung GTi8510 (INNOV8) */
/* Support for Owen devices */
{ USB_DEVICE(0x03eb, 0x0030), }, /* Owen SI30 */
/* NOTE: non-Nokia COMM/ACM/0xff is likely MSFT RNDIS... NOT a modem! */
/* Support Lego NXT using pbLua firmware */
{ USB_DEVICE(0x0694, 0xff00),
.driver_info = NOT_A_MODEM,
},
/* Support for Droids MuIn LCD */
{ USB_DEVICE(0x04d8, 0x000b),
.driver_info = NO_DATA_INTERFACE,
},
/* control interfaces without any protocol set */
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_PROTO_NONE) },
/* control interfaces with various AT-command sets */
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_V25TER) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_PCCA101) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_PCCA101_WAKE) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_GSM) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_3G) },
{ USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_ACM,
USB_CDC_ACM_PROTO_AT_CDMA) },
{ }
};
MODULE_DEVICE_TABLE(usb, acm_ids);
static struct usb_driver acm_driver = {
.name = "cdc_acm",
.probe = acm_probe,
.disconnect = acm_disconnect,
#ifdef CONFIG_PM
.suspend = acm_suspend,
.resume = acm_resume,
.reset_resume = acm_reset_resume,
#endif
.id_table = acm_ids,
#ifdef CONFIG_PM
.supports_autosuspend = 1,
#endif
};
/*
* TTY driver structures.
*/
static const struct tty_operations acm_ops = {
.install = acm_tty_install,
.open = acm_tty_open,
.close = acm_tty_close,
.cleanup = acm_tty_cleanup,
.hangup = acm_tty_hangup,
.write = acm_tty_write,
.write_room = acm_tty_write_room,
.ioctl = acm_tty_ioctl,
.throttle = acm_tty_throttle,
.unthrottle = acm_tty_unthrottle,
.chars_in_buffer = acm_tty_chars_in_buffer,
.break_ctl = acm_tty_break_ctl,
.set_termios = acm_tty_set_termios,
.tiocmget = acm_tty_tiocmget,
.tiocmset = acm_tty_tiocmset,
};
/*
* Init / exit.
*/
static int __init acm_init(void)
{
int retval;
acm_tty_driver = alloc_tty_driver(ACM_TTY_MINORS);
if (!acm_tty_driver)
return -ENOMEM;
acm_tty_driver->driver_name = "acm",
acm_tty_driver->name = "ttyACM",
acm_tty_driver->major = ACM_TTY_MAJOR,
acm_tty_driver->minor_start = 0,
acm_tty_driver->type = TTY_DRIVER_TYPE_SERIAL,
acm_tty_driver->subtype = SERIAL_TYPE_NORMAL,
acm_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
acm_tty_driver->init_termios = tty_std_termios;
acm_tty_driver->init_termios.c_cflag = B9600 | CS8 | CREAD |
HUPCL | CLOCAL;
tty_set_operations(acm_tty_driver, &acm_ops);
retval = tty_register_driver(acm_tty_driver);
if (retval) {
put_tty_driver(acm_tty_driver);
return retval;
}
retval = usb_register(&acm_driver);
if (retval) {
tty_unregister_driver(acm_tty_driver);
put_tty_driver(acm_tty_driver);
return retval;
}
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_DESC "\n");
return 0;
}
static void __exit acm_exit(void)
{
usb_deregister(&acm_driver);
tty_unregister_driver(acm_tty_driver);
put_tty_driver(acm_tty_driver);
}
module_init(acm_init);
module_exit(acm_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(ACM_TTY_MAJOR);
| gpl-2.0 |
nicholaschw/jared-rA | drivers/infiniband/hw/qib/qib_uc.c | 3100 | 14566 | /*
* Copyright (c) 2006, 2007, 2008, 2009, 2010 QLogic Corporation.
* All rights reserved.
* Copyright (c) 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "qib.h"
/* cut down ridiculously long IB macro names */
#define OP(x) IB_OPCODE_UC_##x
/**
* qib_make_uc_req - construct a request packet (SEND, RDMA write)
* @qp: a pointer to the QP
*
* Return 1 if constructed; otherwise, return 0.
*/
int qib_make_uc_req(struct qib_qp *qp)
{
struct qib_other_headers *ohdr;
struct qib_swqe *wqe;
unsigned long flags;
u32 hwords;
u32 bth0;
u32 len;
u32 pmtu = ib_mtu_enum_to_int(qp->path_mtu);
int ret = 0;
spin_lock_irqsave(&qp->s_lock, flags);
if (!(ib_qib_state_ops[qp->state] & QIB_PROCESS_SEND_OK)) {
if (!(ib_qib_state_ops[qp->state] & QIB_FLUSH_SEND))
goto bail;
/* We are in the error state, flush the work request. */
if (qp->s_last == qp->s_head)
goto bail;
/* If DMAs are in progress, we can't flush immediately. */
if (atomic_read(&qp->s_dma_busy)) {
qp->s_flags |= QIB_S_WAIT_DMA;
goto bail;
}
wqe = get_swqe_ptr(qp, qp->s_last);
qib_send_complete(qp, wqe, IB_WC_WR_FLUSH_ERR);
goto done;
}
ohdr = &qp->s_hdr.u.oth;
if (qp->remote_ah_attr.ah_flags & IB_AH_GRH)
ohdr = &qp->s_hdr.u.l.oth;
/* header size in 32-bit words LRH+BTH = (8+12)/4. */
hwords = 5;
bth0 = 0;
/* Get the next send request. */
wqe = get_swqe_ptr(qp, qp->s_cur);
qp->s_wqe = NULL;
switch (qp->s_state) {
default:
if (!(ib_qib_state_ops[qp->state] &
QIB_PROCESS_NEXT_SEND_OK))
goto bail;
/* Check if send work queue is empty. */
if (qp->s_cur == qp->s_head)
goto bail;
/*
* Start a new request.
*/
wqe->psn = qp->s_next_psn;
qp->s_psn = qp->s_next_psn;
qp->s_sge.sge = wqe->sg_list[0];
qp->s_sge.sg_list = wqe->sg_list + 1;
qp->s_sge.num_sge = wqe->wr.num_sge;
qp->s_sge.total_len = wqe->length;
len = wqe->length;
qp->s_len = len;
switch (wqe->wr.opcode) {
case IB_WR_SEND:
case IB_WR_SEND_WITH_IMM:
if (len > pmtu) {
qp->s_state = OP(SEND_FIRST);
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_SEND)
qp->s_state = OP(SEND_ONLY);
else {
qp->s_state =
OP(SEND_ONLY_WITH_IMMEDIATE);
/* Immediate data comes after the BTH */
ohdr->u.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
}
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
ohdr->u.rc.reth.vaddr =
cpu_to_be64(wqe->wr.wr.rdma.remote_addr);
ohdr->u.rc.reth.rkey =
cpu_to_be32(wqe->wr.wr.rdma.rkey);
ohdr->u.rc.reth.length = cpu_to_be32(len);
hwords += sizeof(struct ib_reth) / 4;
if (len > pmtu) {
qp->s_state = OP(RDMA_WRITE_FIRST);
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_RDMA_WRITE)
qp->s_state = OP(RDMA_WRITE_ONLY);
else {
qp->s_state =
OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE);
/* Immediate data comes after the RETH */
ohdr->u.rc.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
}
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
default:
goto bail;
}
break;
case OP(SEND_FIRST):
qp->s_state = OP(SEND_MIDDLE);
/* FALLTHROUGH */
case OP(SEND_MIDDLE):
len = qp->s_len;
if (len > pmtu) {
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_SEND)
qp->s_state = OP(SEND_LAST);
else {
qp->s_state = OP(SEND_LAST_WITH_IMMEDIATE);
/* Immediate data comes after the BTH */
ohdr->u.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
}
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
case OP(RDMA_WRITE_FIRST):
qp->s_state = OP(RDMA_WRITE_MIDDLE);
/* FALLTHROUGH */
case OP(RDMA_WRITE_MIDDLE):
len = qp->s_len;
if (len > pmtu) {
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_RDMA_WRITE)
qp->s_state = OP(RDMA_WRITE_LAST);
else {
qp->s_state =
OP(RDMA_WRITE_LAST_WITH_IMMEDIATE);
/* Immediate data comes after the BTH */
ohdr->u.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
}
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
}
qp->s_len -= len;
qp->s_hdrwords = hwords;
qp->s_cur_sge = &qp->s_sge;
qp->s_cur_size = len;
qib_make_ruc_header(qp, ohdr, bth0 | (qp->s_state << 24),
qp->s_next_psn++ & QIB_PSN_MASK);
done:
ret = 1;
goto unlock;
bail:
qp->s_flags &= ~QIB_S_BUSY;
unlock:
spin_unlock_irqrestore(&qp->s_lock, flags);
return ret;
}
/**
* qib_uc_rcv - handle an incoming UC packet
* @ibp: the port the packet came in on
* @hdr: the header of the packet
* @has_grh: true if the packet has a GRH
* @data: the packet data
* @tlen: the length of the packet
* @qp: the QP for this packet.
*
* This is called from qib_qp_rcv() to process an incoming UC packet
* for the given QP.
* Called at interrupt level.
*/
void qib_uc_rcv(struct qib_ibport *ibp, struct qib_ib_header *hdr,
int has_grh, void *data, u32 tlen, struct qib_qp *qp)
{
struct qib_other_headers *ohdr;
unsigned long flags;
u32 opcode;
u32 hdrsize;
u32 psn;
u32 pad;
struct ib_wc wc;
u32 pmtu = ib_mtu_enum_to_int(qp->path_mtu);
struct ib_reth *reth;
int ret;
/* Check for GRH */
if (!has_grh) {
ohdr = &hdr->u.oth;
hdrsize = 8 + 12; /* LRH + BTH */
} else {
ohdr = &hdr->u.l.oth;
hdrsize = 8 + 40 + 12; /* LRH + GRH + BTH */
}
opcode = be32_to_cpu(ohdr->bth[0]);
spin_lock_irqsave(&qp->s_lock, flags);
if (qib_ruc_check_hdr(ibp, hdr, has_grh, qp, opcode))
goto sunlock;
spin_unlock_irqrestore(&qp->s_lock, flags);
psn = be32_to_cpu(ohdr->bth[2]);
opcode >>= 24;
memset(&wc, 0, sizeof wc);
/* Compare the PSN verses the expected PSN. */
if (unlikely(qib_cmp24(psn, qp->r_psn) != 0)) {
/*
* Handle a sequence error.
* Silently drop any current message.
*/
qp->r_psn = psn;
inv:
if (qp->r_state == OP(SEND_FIRST) ||
qp->r_state == OP(SEND_MIDDLE)) {
set_bit(QIB_R_REWIND_SGE, &qp->r_aflags);
qp->r_sge.num_sge = 0;
} else
while (qp->r_sge.num_sge) {
atomic_dec(&qp->r_sge.sge.mr->refcount);
if (--qp->r_sge.num_sge)
qp->r_sge.sge = *qp->r_sge.sg_list++;
}
qp->r_state = OP(SEND_LAST);
switch (opcode) {
case OP(SEND_FIRST):
case OP(SEND_ONLY):
case OP(SEND_ONLY_WITH_IMMEDIATE):
goto send_first;
case OP(RDMA_WRITE_FIRST):
case OP(RDMA_WRITE_ONLY):
case OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE):
goto rdma_first;
default:
goto drop;
}
}
/* Check for opcode sequence errors. */
switch (qp->r_state) {
case OP(SEND_FIRST):
case OP(SEND_MIDDLE):
if (opcode == OP(SEND_MIDDLE) ||
opcode == OP(SEND_LAST) ||
opcode == OP(SEND_LAST_WITH_IMMEDIATE))
break;
goto inv;
case OP(RDMA_WRITE_FIRST):
case OP(RDMA_WRITE_MIDDLE):
if (opcode == OP(RDMA_WRITE_MIDDLE) ||
opcode == OP(RDMA_WRITE_LAST) ||
opcode == OP(RDMA_WRITE_LAST_WITH_IMMEDIATE))
break;
goto inv;
default:
if (opcode == OP(SEND_FIRST) ||
opcode == OP(SEND_ONLY) ||
opcode == OP(SEND_ONLY_WITH_IMMEDIATE) ||
opcode == OP(RDMA_WRITE_FIRST) ||
opcode == OP(RDMA_WRITE_ONLY) ||
opcode == OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE))
break;
goto inv;
}
if (qp->state == IB_QPS_RTR && !(qp->r_flags & QIB_R_COMM_EST)) {
qp->r_flags |= QIB_R_COMM_EST;
if (qp->ibqp.event_handler) {
struct ib_event ev;
ev.device = qp->ibqp.device;
ev.element.qp = &qp->ibqp;
ev.event = IB_EVENT_COMM_EST;
qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
}
}
/* OK, process the packet. */
switch (opcode) {
case OP(SEND_FIRST):
case OP(SEND_ONLY):
case OP(SEND_ONLY_WITH_IMMEDIATE):
send_first:
if (test_and_clear_bit(QIB_R_REWIND_SGE, &qp->r_aflags))
qp->r_sge = qp->s_rdma_read_sge;
else {
ret = qib_get_rwqe(qp, 0);
if (ret < 0)
goto op_err;
if (!ret)
goto drop;
/*
* qp->s_rdma_read_sge will be the owner
* of the mr references.
*/
qp->s_rdma_read_sge = qp->r_sge;
}
qp->r_rcv_len = 0;
if (opcode == OP(SEND_ONLY))
goto send_last;
else if (opcode == OP(SEND_ONLY_WITH_IMMEDIATE))
goto send_last_imm;
/* FALLTHROUGH */
case OP(SEND_MIDDLE):
/* Check for invalid length PMTU or posted rwqe len. */
if (unlikely(tlen != (hdrsize + pmtu + 4)))
goto rewind;
qp->r_rcv_len += pmtu;
if (unlikely(qp->r_rcv_len > qp->r_len))
goto rewind;
qib_copy_sge(&qp->r_sge, data, pmtu, 0);
break;
case OP(SEND_LAST_WITH_IMMEDIATE):
send_last_imm:
wc.ex.imm_data = ohdr->u.imm_data;
hdrsize += 4;
wc.wc_flags = IB_WC_WITH_IMM;
/* FALLTHROUGH */
case OP(SEND_LAST):
send_last:
/* Get the number of bytes the message was padded by. */
pad = (be32_to_cpu(ohdr->bth[0]) >> 20) & 3;
/* Check for invalid length. */
/* XXX LAST len should be >= 1 */
if (unlikely(tlen < (hdrsize + pad + 4)))
goto rewind;
/* Don't count the CRC. */
tlen -= (hdrsize + pad + 4);
wc.byte_len = tlen + qp->r_rcv_len;
if (unlikely(wc.byte_len > qp->r_len))
goto rewind;
wc.opcode = IB_WC_RECV;
last_imm:
qib_copy_sge(&qp->r_sge, data, tlen, 0);
while (qp->s_rdma_read_sge.num_sge) {
atomic_dec(&qp->s_rdma_read_sge.sge.mr->refcount);
if (--qp->s_rdma_read_sge.num_sge)
qp->s_rdma_read_sge.sge =
*qp->s_rdma_read_sge.sg_list++;
}
wc.wr_id = qp->r_wr_id;
wc.status = IB_WC_SUCCESS;
wc.qp = &qp->ibqp;
wc.src_qp = qp->remote_qpn;
wc.slid = qp->remote_ah_attr.dlid;
wc.sl = qp->remote_ah_attr.sl;
/* Signal completion event if the solicited bit is set. */
qib_cq_enter(to_icq(qp->ibqp.recv_cq), &wc,
(ohdr->bth[0] &
cpu_to_be32(IB_BTH_SOLICITED)) != 0);
break;
case OP(RDMA_WRITE_FIRST):
case OP(RDMA_WRITE_ONLY):
case OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE): /* consume RWQE */
rdma_first:
if (unlikely(!(qp->qp_access_flags &
IB_ACCESS_REMOTE_WRITE))) {
goto drop;
}
reth = &ohdr->u.rc.reth;
hdrsize += sizeof(*reth);
qp->r_len = be32_to_cpu(reth->length);
qp->r_rcv_len = 0;
qp->r_sge.sg_list = NULL;
if (qp->r_len != 0) {
u32 rkey = be32_to_cpu(reth->rkey);
u64 vaddr = be64_to_cpu(reth->vaddr);
int ok;
/* Check rkey */
ok = qib_rkey_ok(qp, &qp->r_sge.sge, qp->r_len,
vaddr, rkey, IB_ACCESS_REMOTE_WRITE);
if (unlikely(!ok))
goto drop;
qp->r_sge.num_sge = 1;
} else {
qp->r_sge.num_sge = 0;
qp->r_sge.sge.mr = NULL;
qp->r_sge.sge.vaddr = NULL;
qp->r_sge.sge.length = 0;
qp->r_sge.sge.sge_length = 0;
}
if (opcode == OP(RDMA_WRITE_ONLY))
goto rdma_last;
else if (opcode == OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE)) {
wc.ex.imm_data = ohdr->u.rc.imm_data;
goto rdma_last_imm;
}
/* FALLTHROUGH */
case OP(RDMA_WRITE_MIDDLE):
/* Check for invalid length PMTU or posted rwqe len. */
if (unlikely(tlen != (hdrsize + pmtu + 4)))
goto drop;
qp->r_rcv_len += pmtu;
if (unlikely(qp->r_rcv_len > qp->r_len))
goto drop;
qib_copy_sge(&qp->r_sge, data, pmtu, 1);
break;
case OP(RDMA_WRITE_LAST_WITH_IMMEDIATE):
wc.ex.imm_data = ohdr->u.imm_data;
rdma_last_imm:
hdrsize += 4;
wc.wc_flags = IB_WC_WITH_IMM;
/* Get the number of bytes the message was padded by. */
pad = (be32_to_cpu(ohdr->bth[0]) >> 20) & 3;
/* Check for invalid length. */
/* XXX LAST len should be >= 1 */
if (unlikely(tlen < (hdrsize + pad + 4)))
goto drop;
/* Don't count the CRC. */
tlen -= (hdrsize + pad + 4);
if (unlikely(tlen + qp->r_rcv_len != qp->r_len))
goto drop;
if (test_and_clear_bit(QIB_R_REWIND_SGE, &qp->r_aflags))
while (qp->s_rdma_read_sge.num_sge) {
atomic_dec(&qp->s_rdma_read_sge.sge.mr->
refcount);
if (--qp->s_rdma_read_sge.num_sge)
qp->s_rdma_read_sge.sge =
*qp->s_rdma_read_sge.sg_list++;
}
else {
ret = qib_get_rwqe(qp, 1);
if (ret < 0)
goto op_err;
if (!ret)
goto drop;
}
wc.byte_len = qp->r_len;
wc.opcode = IB_WC_RECV_RDMA_WITH_IMM;
goto last_imm;
case OP(RDMA_WRITE_LAST):
rdma_last:
/* Get the number of bytes the message was padded by. */
pad = (be32_to_cpu(ohdr->bth[0]) >> 20) & 3;
/* Check for invalid length. */
/* XXX LAST len should be >= 1 */
if (unlikely(tlen < (hdrsize + pad + 4)))
goto drop;
/* Don't count the CRC. */
tlen -= (hdrsize + pad + 4);
if (unlikely(tlen + qp->r_rcv_len != qp->r_len))
goto drop;
qib_copy_sge(&qp->r_sge, data, tlen, 1);
while (qp->r_sge.num_sge) {
atomic_dec(&qp->r_sge.sge.mr->refcount);
if (--qp->r_sge.num_sge)
qp->r_sge.sge = *qp->r_sge.sg_list++;
}
break;
default:
/* Drop packet for unknown opcodes. */
goto drop;
}
qp->r_psn++;
qp->r_state = opcode;
return;
rewind:
set_bit(QIB_R_REWIND_SGE, &qp->r_aflags);
qp->r_sge.num_sge = 0;
drop:
ibp->n_pkt_drops++;
return;
op_err:
qib_rc_error(qp, IB_WC_LOC_QP_OP_ERR);
return;
sunlock:
spin_unlock_irqrestore(&qp->s_lock, flags);
}
| gpl-2.0 |
mydongistiny/kernel_huawei_angler-ak | arch/sh/boards/mach-ap325rxa/setup.c | 3100 | 17386 | /*
* Renesas - AP-325RXA
* (Compatible with Algo System ., LTD. - AP-320A)
*
* Copyright (C) 2008 Renesas Solutions Corp.
* Author : Yusuke Goda <goda.yuske@renesas.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sh_mobile_sdhi.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/sh_flctl.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/regulator/fixed.h>
#include <linux/regulator/machine.h>
#include <linux/smsc911x.h>
#include <linux/gpio.h>
#include <linux/videodev2.h>
#include <linux/sh_intc.h>
#include <media/ov772x.h>
#include <media/soc_camera.h>
#include <media/soc_camera_platform.h>
#include <media/sh_mobile_ceu.h>
#include <video/sh_mobile_lcdc.h>
#include <asm/io.h>
#include <asm/clock.h>
#include <asm/suspend.h>
#include <cpu/sh7723.h>
/* Dummy supplies, where voltage doesn't matter */
static struct regulator_consumer_supply dummy_supplies[] = {
REGULATOR_SUPPLY("vddvario", "smsc911x"),
REGULATOR_SUPPLY("vdd33a", "smsc911x"),
};
static struct smsc911x_platform_config smsc911x_config = {
.phy_interface = PHY_INTERFACE_MODE_MII,
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN,
.flags = SMSC911X_USE_32BIT,
};
static struct resource smsc9118_resources[] = {
[0] = {
.start = 0xb6080000,
.end = 0xb60fffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x660),
.end = evt2irq(0x660),
.flags = IORESOURCE_IRQ,
}
};
static struct platform_device smsc9118_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(smsc9118_resources),
.resource = smsc9118_resources,
.dev = {
.platform_data = &smsc911x_config,
},
};
/*
* AP320 and AP325RXA has CPLD data in NOR Flash(0xA80000-0xABFFFF).
* If this area erased, this board can not boot.
*/
static struct mtd_partition ap325rxa_nor_flash_partitions[] = {
{
.name = "uboot",
.offset = 0,
.size = (1 * 1024 * 1024),
.mask_flags = MTD_WRITEABLE, /* Read-only */
}, {
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = (2 * 1024 * 1024),
}, {
.name = "free-area0",
.offset = MTDPART_OFS_APPEND,
.size = ((7 * 1024 * 1024) + (512 * 1024)),
}, {
.name = "CPLD-Data",
.offset = MTDPART_OFS_APPEND,
.mask_flags = MTD_WRITEABLE, /* Read-only */
.size = (1024 * 128 * 2),
}, {
.name = "free-area1",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct physmap_flash_data ap325rxa_nor_flash_data = {
.width = 2,
.parts = ap325rxa_nor_flash_partitions,
.nr_parts = ARRAY_SIZE(ap325rxa_nor_flash_partitions),
};
static struct resource ap325rxa_nor_flash_resources[] = {
[0] = {
.name = "NOR Flash",
.start = 0x00000000,
.end = 0x00ffffff,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device ap325rxa_nor_flash_device = {
.name = "physmap-flash",
.resource = ap325rxa_nor_flash_resources,
.num_resources = ARRAY_SIZE(ap325rxa_nor_flash_resources),
.dev = {
.platform_data = &ap325rxa_nor_flash_data,
},
};
static struct mtd_partition nand_partition_info[] = {
{
.name = "nand_data",
.offset = 0,
.size = MTDPART_SIZ_FULL,
},
};
static struct resource nand_flash_resources[] = {
[0] = {
.start = 0xa4530000,
.end = 0xa45300ff,
.flags = IORESOURCE_MEM,
}
};
static struct sh_flctl_platform_data nand_flash_data = {
.parts = nand_partition_info,
.nr_parts = ARRAY_SIZE(nand_partition_info),
.flcmncr_val = FCKSEL_E | TYPESEL_SET | NANWF_E,
.has_hwecc = 1,
};
static struct platform_device nand_flash_device = {
.name = "sh_flctl",
.resource = nand_flash_resources,
.num_resources = ARRAY_SIZE(nand_flash_resources),
.dev = {
.platform_data = &nand_flash_data,
},
};
#define FPGA_LCDREG 0xB4100180
#define FPGA_BKLREG 0xB4100212
#define FPGA_LCDREG_VAL 0x0018
#define PORT_MSELCRB 0xA4050182
#define PORT_HIZCRC 0xA405015C
#define PORT_DRVCRA 0xA405018A
#define PORT_DRVCRB 0xA405018C
static int ap320_wvga_set_brightness(int brightness)
{
if (brightness) {
gpio_set_value(GPIO_PTS3, 0);
__raw_writew(0x100, FPGA_BKLREG);
} else {
__raw_writew(0, FPGA_BKLREG);
gpio_set_value(GPIO_PTS3, 1);
}
return 0;
}
static void ap320_wvga_power_on(void)
{
msleep(100);
/* ASD AP-320/325 LCD ON */
__raw_writew(FPGA_LCDREG_VAL, FPGA_LCDREG);
}
static void ap320_wvga_power_off(void)
{
/* ASD AP-320/325 LCD OFF */
__raw_writew(0, FPGA_LCDREG);
}
static const struct fb_videomode ap325rxa_lcdc_modes[] = {
{
.name = "LB070WV1",
.xres = 800,
.yres = 480,
.left_margin = 32,
.right_margin = 160,
.hsync_len = 8,
.upper_margin = 63,
.lower_margin = 80,
.vsync_len = 1,
.sync = 0, /* hsync and vsync are active low */
},
};
static struct sh_mobile_lcdc_info lcdc_info = {
.clock_source = LCDC_CLK_EXTERNAL,
.ch[0] = {
.chan = LCDC_CHAN_MAINLCD,
.fourcc = V4L2_PIX_FMT_RGB565,
.interface_type = RGB18,
.clock_divider = 1,
.lcd_modes = ap325rxa_lcdc_modes,
.num_modes = ARRAY_SIZE(ap325rxa_lcdc_modes),
.panel_cfg = {
.width = 152, /* 7.0 inch */
.height = 91,
.display_on = ap320_wvga_power_on,
.display_off = ap320_wvga_power_off,
},
.bl_info = {
.name = "sh_mobile_lcdc_bl",
.max_brightness = 1,
.set_brightness = ap320_wvga_set_brightness,
},
}
};
static struct resource lcdc_resources[] = {
[0] = {
.name = "LCDC",
.start = 0xfe940000, /* P4-only space */
.end = 0xfe942fff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x580),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device lcdc_device = {
.name = "sh_mobile_lcdc_fb",
.num_resources = ARRAY_SIZE(lcdc_resources),
.resource = lcdc_resources,
.dev = {
.platform_data = &lcdc_info,
},
};
static void camera_power(int val)
{
gpio_set_value(GPIO_PTZ5, val); /* RST_CAM/RSTB */
mdelay(10);
}
#ifdef CONFIG_I2C
/* support for the old ncm03j camera */
static unsigned char camera_ncm03j_magic[] =
{
0x87, 0x00, 0x88, 0x08, 0x89, 0x01, 0x8A, 0xE8,
0x1D, 0x00, 0x1E, 0x8A, 0x21, 0x00, 0x33, 0x36,
0x36, 0x60, 0x37, 0x08, 0x3B, 0x31, 0x44, 0x0F,
0x46, 0xF0, 0x4B, 0x28, 0x4C, 0x21, 0x4D, 0x55,
0x4E, 0x1B, 0x4F, 0xC7, 0x50, 0xFC, 0x51, 0x12,
0x58, 0x02, 0x66, 0xC0, 0x67, 0x46, 0x6B, 0xA0,
0x6C, 0x34, 0x7E, 0x25, 0x7F, 0x25, 0x8D, 0x0F,
0x92, 0x40, 0x93, 0x04, 0x94, 0x26, 0x95, 0x0A,
0x99, 0x03, 0x9A, 0xF0, 0x9B, 0x14, 0x9D, 0x7A,
0xC5, 0x02, 0xD6, 0x07, 0x59, 0x00, 0x5A, 0x1A,
0x5B, 0x2A, 0x5C, 0x37, 0x5D, 0x42, 0x5E, 0x56,
0xC8, 0x00, 0xC9, 0x1A, 0xCA, 0x2A, 0xCB, 0x37,
0xCC, 0x42, 0xCD, 0x56, 0xCE, 0x00, 0xCF, 0x1A,
0xD0, 0x2A, 0xD1, 0x37, 0xD2, 0x42, 0xD3, 0x56,
0x5F, 0x68, 0x60, 0x87, 0x61, 0xA3, 0x62, 0xBC,
0x63, 0xD4, 0x64, 0xEA, 0xD6, 0x0F,
};
static int camera_probe(void)
{
struct i2c_adapter *a = i2c_get_adapter(0);
struct i2c_msg msg;
int ret;
if (!a)
return -ENODEV;
camera_power(1);
msg.addr = 0x6e;
msg.buf = camera_ncm03j_magic;
msg.len = 2;
msg.flags = 0;
ret = i2c_transfer(a, &msg, 1);
camera_power(0);
return ret;
}
static int camera_set_capture(struct soc_camera_platform_info *info,
int enable)
{
struct i2c_adapter *a = i2c_get_adapter(0);
struct i2c_msg msg;
int ret = 0;
int i;
camera_power(0);
if (!enable)
return 0; /* no disable for now */
camera_power(1);
for (i = 0; i < ARRAY_SIZE(camera_ncm03j_magic); i += 2) {
u_int8_t buf[8];
msg.addr = 0x6e;
msg.buf = buf;
msg.len = 2;
msg.flags = 0;
buf[0] = camera_ncm03j_magic[i];
buf[1] = camera_ncm03j_magic[i + 1];
ret = (ret < 0) ? ret : i2c_transfer(a, &msg, 1);
}
return ret;
}
static int ap325rxa_camera_add(struct soc_camera_device *icd);
static void ap325rxa_camera_del(struct soc_camera_device *icd);
static struct soc_camera_platform_info camera_info = {
.format_name = "UYVY",
.format_depth = 16,
.format = {
.code = V4L2_MBUS_FMT_UYVY8_2X8,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.field = V4L2_FIELD_NONE,
.width = 640,
.height = 480,
},
.mbus_param = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_HIGH |
V4L2_MBUS_DATA_ACTIVE_HIGH,
.mbus_type = V4L2_MBUS_PARALLEL,
.set_capture = camera_set_capture,
};
static struct soc_camera_link camera_link = {
.bus_id = 0,
.add_device = ap325rxa_camera_add,
.del_device = ap325rxa_camera_del,
.module_name = "soc_camera_platform",
.priv = &camera_info,
};
static struct platform_device *camera_device;
static void ap325rxa_camera_release(struct device *dev)
{
soc_camera_platform_release(&camera_device);
}
static int ap325rxa_camera_add(struct soc_camera_device *icd)
{
int ret = soc_camera_platform_add(icd, &camera_device, &camera_link,
ap325rxa_camera_release, 0);
if (ret < 0)
return ret;
ret = camera_probe();
if (ret < 0)
soc_camera_platform_del(icd, camera_device, &camera_link);
return ret;
}
static void ap325rxa_camera_del(struct soc_camera_device *icd)
{
soc_camera_platform_del(icd, camera_device, &camera_link);
}
#endif /* CONFIG_I2C */
static int ov7725_power(struct device *dev, int mode)
{
camera_power(0);
if (mode)
camera_power(1);
return 0;
}
static struct sh_mobile_ceu_info sh_mobile_ceu_info = {
.flags = SH_CEU_FLAG_USE_8BIT_BUS,
};
static struct resource ceu_resources[] = {
[0] = {
.name = "CEU",
.start = 0xfe910000,
.end = 0xfe91009f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x880),
.flags = IORESOURCE_IRQ,
},
[2] = {
/* place holder for contiguous memory */
},
};
static struct platform_device ceu_device = {
.name = "sh_mobile_ceu",
.id = 0, /* "ceu0" clock */
.num_resources = ARRAY_SIZE(ceu_resources),
.resource = ceu_resources,
.dev = {
.platform_data = &sh_mobile_ceu_info,
},
};
/* Fixed 3.3V regulators to be used by SDHI0, SDHI1 */
static struct regulator_consumer_supply fixed3v3_power_consumers[] =
{
REGULATOR_SUPPLY("vmmc", "sh_mobile_sdhi.0"),
REGULATOR_SUPPLY("vqmmc", "sh_mobile_sdhi.0"),
REGULATOR_SUPPLY("vmmc", "sh_mobile_sdhi.1"),
REGULATOR_SUPPLY("vqmmc", "sh_mobile_sdhi.1"),
};
static struct resource sdhi0_cn3_resources[] = {
[0] = {
.name = "SDHI0",
.start = 0x04ce0000,
.end = 0x04ce00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0xe80),
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mobile_sdhi_info sdhi0_cn3_data = {
.tmio_caps = MMC_CAP_SDIO_IRQ,
};
static struct platform_device sdhi0_cn3_device = {
.name = "sh_mobile_sdhi",
.id = 0, /* "sdhi0" clock */
.num_resources = ARRAY_SIZE(sdhi0_cn3_resources),
.resource = sdhi0_cn3_resources,
.dev = {
.platform_data = &sdhi0_cn3_data,
},
};
static struct resource sdhi1_cn7_resources[] = {
[0] = {
.name = "SDHI1",
.start = 0x04cf0000,
.end = 0x04cf00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x4e0),
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mobile_sdhi_info sdhi1_cn7_data = {
.tmio_caps = MMC_CAP_SDIO_IRQ,
};
static struct platform_device sdhi1_cn7_device = {
.name = "sh_mobile_sdhi",
.id = 1, /* "sdhi1" clock */
.num_resources = ARRAY_SIZE(sdhi1_cn7_resources),
.resource = sdhi1_cn7_resources,
.dev = {
.platform_data = &sdhi1_cn7_data,
},
};
static struct i2c_board_info __initdata ap325rxa_i2c_devices[] = {
{
I2C_BOARD_INFO("pcf8563", 0x51),
},
};
static struct i2c_board_info ap325rxa_i2c_camera[] = {
{
I2C_BOARD_INFO("ov772x", 0x21),
},
};
static struct ov772x_camera_info ov7725_info = {
.flags = OV772X_FLAG_VFLIP | OV772X_FLAG_HFLIP,
.edgectrl = OV772X_AUTO_EDGECTRL(0xf, 0),
};
static struct soc_camera_link ov7725_link = {
.bus_id = 0,
.power = ov7725_power,
.board_info = &ap325rxa_i2c_camera[0],
.i2c_adapter_id = 0,
.priv = &ov7725_info,
};
static struct platform_device ap325rxa_camera[] = {
{
.name = "soc-camera-pdrv",
.id = 0,
.dev = {
.platform_data = &ov7725_link,
},
}, {
.name = "soc-camera-pdrv",
.id = 1,
.dev = {
.platform_data = &camera_link,
},
},
};
static struct platform_device *ap325rxa_devices[] __initdata = {
&smsc9118_device,
&ap325rxa_nor_flash_device,
&lcdc_device,
&ceu_device,
&nand_flash_device,
&sdhi0_cn3_device,
&sdhi1_cn7_device,
&ap325rxa_camera[0],
&ap325rxa_camera[1],
};
extern char ap325rxa_sdram_enter_start;
extern char ap325rxa_sdram_enter_end;
extern char ap325rxa_sdram_leave_start;
extern char ap325rxa_sdram_leave_end;
static int __init ap325rxa_devices_setup(void)
{
/* register board specific self-refresh code */
sh_mobile_register_self_refresh(SUSP_SH_STANDBY | SUSP_SH_SF,
&ap325rxa_sdram_enter_start,
&ap325rxa_sdram_enter_end,
&ap325rxa_sdram_leave_start,
&ap325rxa_sdram_leave_end);
regulator_register_always_on(0, "fixed-3.3V", fixed3v3_power_consumers,
ARRAY_SIZE(fixed3v3_power_consumers), 3300000);
regulator_register_fixed(1, dummy_supplies, ARRAY_SIZE(dummy_supplies));
/* LD3 and LD4 LEDs */
gpio_request(GPIO_PTX5, NULL); /* RUN */
gpio_direction_output(GPIO_PTX5, 1);
gpio_export(GPIO_PTX5, 0);
gpio_request(GPIO_PTX4, NULL); /* INDICATOR */
gpio_direction_output(GPIO_PTX4, 0);
gpio_export(GPIO_PTX4, 0);
/* SW1 input */
gpio_request(GPIO_PTF7, NULL); /* MODE */
gpio_direction_input(GPIO_PTF7);
gpio_export(GPIO_PTF7, 0);
/* LCDC */
gpio_request(GPIO_FN_LCDD15, NULL);
gpio_request(GPIO_FN_LCDD14, NULL);
gpio_request(GPIO_FN_LCDD13, NULL);
gpio_request(GPIO_FN_LCDD12, NULL);
gpio_request(GPIO_FN_LCDD11, NULL);
gpio_request(GPIO_FN_LCDD10, NULL);
gpio_request(GPIO_FN_LCDD9, NULL);
gpio_request(GPIO_FN_LCDD8, NULL);
gpio_request(GPIO_FN_LCDD7, NULL);
gpio_request(GPIO_FN_LCDD6, NULL);
gpio_request(GPIO_FN_LCDD5, NULL);
gpio_request(GPIO_FN_LCDD4, NULL);
gpio_request(GPIO_FN_LCDD3, NULL);
gpio_request(GPIO_FN_LCDD2, NULL);
gpio_request(GPIO_FN_LCDD1, NULL);
gpio_request(GPIO_FN_LCDD0, NULL);
gpio_request(GPIO_FN_LCDLCLK_PTR, NULL);
gpio_request(GPIO_FN_LCDDCK, NULL);
gpio_request(GPIO_FN_LCDVEPWC, NULL);
gpio_request(GPIO_FN_LCDVCPWC, NULL);
gpio_request(GPIO_FN_LCDVSYN, NULL);
gpio_request(GPIO_FN_LCDHSYN, NULL);
gpio_request(GPIO_FN_LCDDISP, NULL);
gpio_request(GPIO_FN_LCDDON, NULL);
/* LCD backlight */
gpio_request(GPIO_PTS3, NULL);
gpio_direction_output(GPIO_PTS3, 1);
/* CEU */
gpio_request(GPIO_FN_VIO_CLK2, NULL);
gpio_request(GPIO_FN_VIO_VD2, NULL);
gpio_request(GPIO_FN_VIO_HD2, NULL);
gpio_request(GPIO_FN_VIO_FLD, NULL);
gpio_request(GPIO_FN_VIO_CKO, NULL);
gpio_request(GPIO_FN_VIO_D15, NULL);
gpio_request(GPIO_FN_VIO_D14, NULL);
gpio_request(GPIO_FN_VIO_D13, NULL);
gpio_request(GPIO_FN_VIO_D12, NULL);
gpio_request(GPIO_FN_VIO_D11, NULL);
gpio_request(GPIO_FN_VIO_D10, NULL);
gpio_request(GPIO_FN_VIO_D9, NULL);
gpio_request(GPIO_FN_VIO_D8, NULL);
gpio_request(GPIO_PTZ7, NULL);
gpio_direction_output(GPIO_PTZ7, 0); /* OE_CAM */
gpio_request(GPIO_PTZ6, NULL);
gpio_direction_output(GPIO_PTZ6, 0); /* STBY_CAM */
gpio_request(GPIO_PTZ5, NULL);
gpio_direction_output(GPIO_PTZ5, 0); /* RST_CAM */
gpio_request(GPIO_PTZ4, NULL);
gpio_direction_output(GPIO_PTZ4, 0); /* SADDR */
__raw_writew(__raw_readw(PORT_MSELCRB) & ~0x0001, PORT_MSELCRB);
/* FLCTL */
gpio_request(GPIO_FN_FCE, NULL);
gpio_request(GPIO_FN_NAF7, NULL);
gpio_request(GPIO_FN_NAF6, NULL);
gpio_request(GPIO_FN_NAF5, NULL);
gpio_request(GPIO_FN_NAF4, NULL);
gpio_request(GPIO_FN_NAF3, NULL);
gpio_request(GPIO_FN_NAF2, NULL);
gpio_request(GPIO_FN_NAF1, NULL);
gpio_request(GPIO_FN_NAF0, NULL);
gpio_request(GPIO_FN_FCDE, NULL);
gpio_request(GPIO_FN_FOE, NULL);
gpio_request(GPIO_FN_FSC, NULL);
gpio_request(GPIO_FN_FWE, NULL);
gpio_request(GPIO_FN_FRB, NULL);
__raw_writew(0, PORT_HIZCRC);
__raw_writew(0xFFFF, PORT_DRVCRA);
__raw_writew(0xFFFF, PORT_DRVCRB);
platform_resource_setup_memory(&ceu_device, "ceu", 4 << 20);
/* SDHI0 - CN3 - SD CARD */
gpio_request(GPIO_FN_SDHI0CD_PTD, NULL);
gpio_request(GPIO_FN_SDHI0WP_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D3_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D2_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D1_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D0_PTD, NULL);
gpio_request(GPIO_FN_SDHI0CMD_PTD, NULL);
gpio_request(GPIO_FN_SDHI0CLK_PTD, NULL);
/* SDHI1 - CN7 - MICRO SD CARD */
gpio_request(GPIO_FN_SDHI1CD, NULL);
gpio_request(GPIO_FN_SDHI1D3, NULL);
gpio_request(GPIO_FN_SDHI1D2, NULL);
gpio_request(GPIO_FN_SDHI1D1, NULL);
gpio_request(GPIO_FN_SDHI1D0, NULL);
gpio_request(GPIO_FN_SDHI1CMD, NULL);
gpio_request(GPIO_FN_SDHI1CLK, NULL);
i2c_register_board_info(0, ap325rxa_i2c_devices,
ARRAY_SIZE(ap325rxa_i2c_devices));
return platform_add_devices(ap325rxa_devices,
ARRAY_SIZE(ap325rxa_devices));
}
arch_initcall(ap325rxa_devices_setup);
/* Return the board specific boot mode pin configuration */
static int ap325rxa_mode_pins(void)
{
/* MD0=0, MD1=0, MD2=0: Clock Mode 0
* MD3=0: 16-bit Area0 Bus Width
* MD5=1: Little Endian
* TSTMD=1, MD8=1: Test Mode Disabled
*/
return MODE_PIN5 | MODE_PIN8;
}
static struct sh_machine_vector mv_ap325rxa __initmv = {
.mv_name = "AP-325RXA",
.mv_mode_pins = ap325rxa_mode_pins,
};
| gpl-2.0 |
savoca/ifc6540 | arch/sparc/kernel/central.c | 3100 | 6142 | /* central.c: Central FHC driver for Sunfire/Starfire/Wildfire.
*
* Copyright (C) 1997, 1999, 2008 David S. Miller (davem@davemloft.net)
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <asm/fhc.h>
#include <asm/upa.h>
struct clock_board {
void __iomem *clock_freq_regs;
void __iomem *clock_regs;
void __iomem *clock_ver_reg;
int num_slots;
struct resource leds_resource;
struct platform_device leds_pdev;
};
struct fhc {
void __iomem *pregs;
bool central;
bool jtag_master;
int board_num;
struct resource leds_resource;
struct platform_device leds_pdev;
};
static int clock_board_calc_nslots(struct clock_board *p)
{
u8 reg = upa_readb(p->clock_regs + CLOCK_STAT1) & 0xc0;
switch (reg) {
case 0x40:
return 16;
case 0xc0:
return 8;
case 0x80:
reg = 0;
if (p->clock_ver_reg)
reg = upa_readb(p->clock_ver_reg);
if (reg) {
if (reg & 0x80)
return 4;
else
return 5;
}
/* Fallthrough */
default:
return 4;
}
}
static int clock_board_probe(struct platform_device *op)
{
struct clock_board *p = kzalloc(sizeof(*p), GFP_KERNEL);
int err = -ENOMEM;
if (!p) {
printk(KERN_ERR "clock_board: Cannot allocate struct clock_board\n");
goto out;
}
p->clock_freq_regs = of_ioremap(&op->resource[0], 0,
resource_size(&op->resource[0]),
"clock_board_freq");
if (!p->clock_freq_regs) {
printk(KERN_ERR "clock_board: Cannot map clock_freq_regs\n");
goto out_free;
}
p->clock_regs = of_ioremap(&op->resource[1], 0,
resource_size(&op->resource[1]),
"clock_board_regs");
if (!p->clock_regs) {
printk(KERN_ERR "clock_board: Cannot map clock_regs\n");
goto out_unmap_clock_freq_regs;
}
if (op->resource[2].flags) {
p->clock_ver_reg = of_ioremap(&op->resource[2], 0,
resource_size(&op->resource[2]),
"clock_ver_reg");
if (!p->clock_ver_reg) {
printk(KERN_ERR "clock_board: Cannot map clock_ver_reg\n");
goto out_unmap_clock_regs;
}
}
p->num_slots = clock_board_calc_nslots(p);
p->leds_resource.start = (unsigned long)
(p->clock_regs + CLOCK_CTRL);
p->leds_resource.end = p->leds_resource.start;
p->leds_resource.name = "leds";
p->leds_pdev.name = "sunfire-clockboard-leds";
p->leds_pdev.id = -1;
p->leds_pdev.resource = &p->leds_resource;
p->leds_pdev.num_resources = 1;
p->leds_pdev.dev.parent = &op->dev;
err = platform_device_register(&p->leds_pdev);
if (err) {
printk(KERN_ERR "clock_board: Could not register LEDS "
"platform device\n");
goto out_unmap_clock_ver_reg;
}
printk(KERN_INFO "clock_board: Detected %d slot Enterprise system.\n",
p->num_slots);
err = 0;
out:
return err;
out_unmap_clock_ver_reg:
if (p->clock_ver_reg)
of_iounmap(&op->resource[2], p->clock_ver_reg,
resource_size(&op->resource[2]));
out_unmap_clock_regs:
of_iounmap(&op->resource[1], p->clock_regs,
resource_size(&op->resource[1]));
out_unmap_clock_freq_regs:
of_iounmap(&op->resource[0], p->clock_freq_regs,
resource_size(&op->resource[0]));
out_free:
kfree(p);
goto out;
}
static const struct of_device_id clock_board_match[] = {
{
.name = "clock-board",
},
{},
};
static struct platform_driver clock_board_driver = {
.probe = clock_board_probe,
.driver = {
.name = "clock_board",
.owner = THIS_MODULE,
.of_match_table = clock_board_match,
},
};
static int fhc_probe(struct platform_device *op)
{
struct fhc *p = kzalloc(sizeof(*p), GFP_KERNEL);
int err = -ENOMEM;
u32 reg;
if (!p) {
printk(KERN_ERR "fhc: Cannot allocate struct fhc\n");
goto out;
}
if (!strcmp(op->dev.of_node->parent->name, "central"))
p->central = true;
p->pregs = of_ioremap(&op->resource[0], 0,
resource_size(&op->resource[0]),
"fhc_pregs");
if (!p->pregs) {
printk(KERN_ERR "fhc: Cannot map pregs\n");
goto out_free;
}
if (p->central) {
reg = upa_readl(p->pregs + FHC_PREGS_BSR);
p->board_num = ((reg >> 16) & 1) | ((reg >> 12) & 0x0e);
} else {
p->board_num = of_getintprop_default(op->dev.of_node, "board#", -1);
if (p->board_num == -1) {
printk(KERN_ERR "fhc: No board# property\n");
goto out_unmap_pregs;
}
if (upa_readl(p->pregs + FHC_PREGS_JCTRL) & FHC_JTAG_CTRL_MENAB)
p->jtag_master = true;
}
if (!p->central) {
p->leds_resource.start = (unsigned long)
(p->pregs + FHC_PREGS_CTRL);
p->leds_resource.end = p->leds_resource.start;
p->leds_resource.name = "leds";
p->leds_pdev.name = "sunfire-fhc-leds";
p->leds_pdev.id = p->board_num;
p->leds_pdev.resource = &p->leds_resource;
p->leds_pdev.num_resources = 1;
p->leds_pdev.dev.parent = &op->dev;
err = platform_device_register(&p->leds_pdev);
if (err) {
printk(KERN_ERR "fhc: Could not register LEDS "
"platform device\n");
goto out_unmap_pregs;
}
}
reg = upa_readl(p->pregs + FHC_PREGS_CTRL);
if (!p->central)
reg |= FHC_CONTROL_IXIST;
reg &= ~(FHC_CONTROL_AOFF |
FHC_CONTROL_BOFF |
FHC_CONTROL_SLINE);
upa_writel(reg, p->pregs + FHC_PREGS_CTRL);
upa_readl(p->pregs + FHC_PREGS_CTRL);
reg = upa_readl(p->pregs + FHC_PREGS_ID);
printk(KERN_INFO "fhc: Board #%d, Version[%x] PartID[%x] Manuf[%x] %s\n",
p->board_num,
(reg & FHC_ID_VERS) >> 28,
(reg & FHC_ID_PARTID) >> 12,
(reg & FHC_ID_MANUF) >> 1,
(p->jtag_master ?
"(JTAG Master)" :
(p->central ? "(Central)" : "")));
err = 0;
out:
return err;
out_unmap_pregs:
of_iounmap(&op->resource[0], p->pregs, resource_size(&op->resource[0]));
out_free:
kfree(p);
goto out;
}
static const struct of_device_id fhc_match[] = {
{
.name = "fhc",
},
{},
};
static struct platform_driver fhc_driver = {
.probe = fhc_probe,
.driver = {
.name = "fhc",
.owner = THIS_MODULE,
.of_match_table = fhc_match,
},
};
static int __init sunfire_init(void)
{
(void) platform_driver_register(&fhc_driver);
(void) platform_driver_register(&clock_board_driver);
return 0;
}
fs_initcall(sunfire_init);
| gpl-2.0 |
cometzero/cometzero_e210s | drivers/regulator/ad5398.c | 3356 | 6514 | /*
* Voltage and current regulation for AD5398 and AD5821
*
* Copyright 2010 Analog Devices Inc.
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#define AD5398_CURRENT_EN_MASK 0x8000
struct ad5398_chip_info {
struct i2c_client *client;
int min_uA;
int max_uA;
unsigned int current_level;
unsigned int current_mask;
unsigned int current_offset;
struct regulator_dev *rdev;
};
static int ad5398_calc_current(struct ad5398_chip_info *chip,
unsigned selector)
{
unsigned range_uA = chip->max_uA - chip->min_uA;
return chip->min_uA + (selector * range_uA / chip->current_level);
}
static int ad5398_read_reg(struct i2c_client *client, unsigned short *data)
{
unsigned short val;
int ret;
ret = i2c_master_recv(client, (char *)&val, 2);
if (ret < 0) {
dev_err(&client->dev, "I2C read error\n");
return ret;
}
*data = be16_to_cpu(val);
return ret;
}
static int ad5398_write_reg(struct i2c_client *client, const unsigned short data)
{
unsigned short val;
int ret;
val = cpu_to_be16(data);
ret = i2c_master_send(client, (char *)&val, 2);
if (ret < 0)
dev_err(&client->dev, "I2C write error\n");
return ret;
}
static int ad5398_get_current_limit(struct regulator_dev *rdev)
{
struct ad5398_chip_info *chip = rdev_get_drvdata(rdev);
struct i2c_client *client = chip->client;
unsigned short data;
int ret;
ret = ad5398_read_reg(client, &data);
if (ret < 0)
return ret;
ret = (data & chip->current_mask) >> chip->current_offset;
return ad5398_calc_current(chip, ret);
}
static int ad5398_set_current_limit(struct regulator_dev *rdev, int min_uA, int max_uA)
{
struct ad5398_chip_info *chip = rdev_get_drvdata(rdev);
struct i2c_client *client = chip->client;
unsigned range_uA = chip->max_uA - chip->min_uA;
unsigned selector;
unsigned short data;
int ret;
if (min_uA > chip->max_uA || min_uA < chip->min_uA)
return -EINVAL;
if (max_uA > chip->max_uA || max_uA < chip->min_uA)
return -EINVAL;
selector = ((min_uA - chip->min_uA) * chip->current_level +
range_uA - 1) / range_uA;
if (ad5398_calc_current(chip, selector) > max_uA)
return -EINVAL;
dev_dbg(&client->dev, "changing current %dmA\n",
ad5398_calc_current(chip, selector) / 1000);
/* read chip enable bit */
ret = ad5398_read_reg(client, &data);
if (ret < 0)
return ret;
/* prepare register data */
selector = (selector << chip->current_offset) & chip->current_mask;
data = (unsigned short)selector | (data & AD5398_CURRENT_EN_MASK);
/* write the new current value back as well as enable bit */
ret = ad5398_write_reg(client, data);
return ret;
}
static int ad5398_is_enabled(struct regulator_dev *rdev)
{
struct ad5398_chip_info *chip = rdev_get_drvdata(rdev);
struct i2c_client *client = chip->client;
unsigned short data;
int ret;
ret = ad5398_read_reg(client, &data);
if (ret < 0)
return ret;
if (data & AD5398_CURRENT_EN_MASK)
return 1;
else
return 0;
}
static int ad5398_enable(struct regulator_dev *rdev)
{
struct ad5398_chip_info *chip = rdev_get_drvdata(rdev);
struct i2c_client *client = chip->client;
unsigned short data;
int ret;
ret = ad5398_read_reg(client, &data);
if (ret < 0)
return ret;
if (data & AD5398_CURRENT_EN_MASK)
return 0;
data |= AD5398_CURRENT_EN_MASK;
ret = ad5398_write_reg(client, data);
return ret;
}
static int ad5398_disable(struct regulator_dev *rdev)
{
struct ad5398_chip_info *chip = rdev_get_drvdata(rdev);
struct i2c_client *client = chip->client;
unsigned short data;
int ret;
ret = ad5398_read_reg(client, &data);
if (ret < 0)
return ret;
if (!(data & AD5398_CURRENT_EN_MASK))
return 0;
data &= ~AD5398_CURRENT_EN_MASK;
ret = ad5398_write_reg(client, data);
return ret;
}
static struct regulator_ops ad5398_ops = {
.get_current_limit = ad5398_get_current_limit,
.set_current_limit = ad5398_set_current_limit,
.enable = ad5398_enable,
.disable = ad5398_disable,
.is_enabled = ad5398_is_enabled,
};
static struct regulator_desc ad5398_reg = {
.name = "isink",
.id = 0,
.ops = &ad5398_ops,
.type = REGULATOR_CURRENT,
.owner = THIS_MODULE,
};
struct ad5398_current_data_format {
int current_bits;
int current_offset;
int min_uA;
int max_uA;
};
static const struct ad5398_current_data_format df_10_4_120 = {10, 4, 0, 120000};
static const struct i2c_device_id ad5398_id[] = {
{ "ad5398", (kernel_ulong_t)&df_10_4_120 },
{ "ad5821", (kernel_ulong_t)&df_10_4_120 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ad5398_id);
static int __devinit ad5398_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct regulator_init_data *init_data = client->dev.platform_data;
struct ad5398_chip_info *chip;
const struct ad5398_current_data_format *df =
(struct ad5398_current_data_format *)id->driver_data;
int ret;
if (!init_data)
return -EINVAL;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
chip->client = client;
chip->min_uA = df->min_uA;
chip->max_uA = df->max_uA;
chip->current_level = 1 << df->current_bits;
chip->current_offset = df->current_offset;
chip->current_mask = (chip->current_level - 1) << chip->current_offset;
chip->rdev = regulator_register(&ad5398_reg, &client->dev,
init_data, chip);
if (IS_ERR(chip->rdev)) {
ret = PTR_ERR(chip->rdev);
dev_err(&client->dev, "failed to register %s %s\n",
id->name, ad5398_reg.name);
goto err;
}
i2c_set_clientdata(client, chip);
dev_dbg(&client->dev, "%s regulator driver is registered.\n", id->name);
return 0;
err:
kfree(chip);
return ret;
}
static int __devexit ad5398_remove(struct i2c_client *client)
{
struct ad5398_chip_info *chip = i2c_get_clientdata(client);
regulator_unregister(chip->rdev);
kfree(chip);
return 0;
}
static struct i2c_driver ad5398_driver = {
.probe = ad5398_probe,
.remove = __devexit_p(ad5398_remove),
.driver = {
.name = "ad5398",
},
.id_table = ad5398_id,
};
static int __init ad5398_init(void)
{
return i2c_add_driver(&ad5398_driver);
}
subsys_initcall(ad5398_init);
static void __exit ad5398_exit(void)
{
i2c_del_driver(&ad5398_driver);
}
module_exit(ad5398_exit);
MODULE_DESCRIPTION("AD5398 and AD5821 current regulator driver");
MODULE_AUTHOR("Sonic Zhang");
MODULE_LICENSE("GPL");
MODULE_ALIAS("i2c:ad5398-regulator");
| gpl-2.0 |
futranbg/ef65l-kernel-2.0 | sound/pci/echoaudio/gina20.c | 3612 | 3018 | /*
* ALSA driver for Echoaudio soundcards.
* Copyright (C) 2003-2004 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 ECHOGALS_FAMILY
#define ECHOCARD_GINA20
#define ECHOCARD_NAME "Gina20"
#define ECHOCARD_HAS_MONITOR
#define ECHOCARD_HAS_INPUT_GAIN
#define ECHOCARD_HAS_DIGITAL_IO
#define ECHOCARD_HAS_EXTERNAL_CLOCK
#define ECHOCARD_HAS_ADAT FALSE
/* Pipe indexes */
#define PX_ANALOG_OUT 0 /* 8 */
#define PX_DIGITAL_OUT 8 /* 2 */
#define PX_ANALOG_IN 10 /* 2 */
#define PX_DIGITAL_IN 12 /* 2 */
#define PX_NUM 14
/* Bus indexes */
#define BX_ANALOG_OUT 0 /* 8 */
#define BX_DIGITAL_OUT 8 /* 2 */
#define BX_ANALOG_IN 10 /* 2 */
#define BX_DIGITAL_IN 12 /* 2 */
#define BX_NUM 14
#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/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/io.h>
#include <asm/atomic.h>
#include "echoaudio.h"
MODULE_FIRMWARE("ea/gina20_dsp.fw");
#define FW_GINA20_DSP 0
static const struct firmware card_fw[] = {
{0, "gina20_dsp.fw"}
};
static DEFINE_PCI_DEVICE_TABLE(snd_echo_ids) = {
{0x1057, 0x1801, 0xECC0, 0x0020, 0, 0, 0}, /* DSP 56301 Gina20 rev.0 */
{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_44100 | SNDRV_PCM_RATE_48000,
.rate_min = 44100,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 262144,
.period_bytes_min = 32,
.period_bytes_max = 131072,
.periods_min = 2,
.periods_max = 220,
/* One page (4k) contains 512 instructions. I don't know if the hw
supports lists longer than this. In this case periods_max=220 is a
safe limit to make sure the list never exceeds 512 instructions. */
};
#include "gina20_dsp.c"
#include "echoaudio_dsp.c"
#include "echoaudio.c"
| gpl-2.0 |
ztemt/NX505J_5.1_kernel | drivers/net/ethernet/chelsio/cxgb4/sge.c | 4892 | 67896 | /*
* This file is part of the Chelsio T4 Ethernet driver for Linux.
*
* Copyright (c) 2003-2010 Chelsio Communications, 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/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <linux/dma-mapping.h>
#include <linux/jiffies.h>
#include <linux/prefetch.h>
#include <linux/export.h>
#include <net/ipv6.h>
#include <net/tcp.h>
#include "cxgb4.h"
#include "t4_regs.h"
#include "t4_msg.h"
#include "t4fw_api.h"
/*
* Rx buffer size. We use largish buffers if possible but settle for single
* pages under memory shortage.
*/
#if PAGE_SHIFT >= 16
# define FL_PG_ORDER 0
#else
# define FL_PG_ORDER (16 - PAGE_SHIFT)
#endif
/* RX_PULL_LEN should be <= RX_COPY_THRES */
#define RX_COPY_THRES 256
#define RX_PULL_LEN 128
/*
* Main body length for sk_buffs used for Rx Ethernet packets with fragments.
* Should be >= RX_PULL_LEN but possibly bigger to give pskb_may_pull some room.
*/
#define RX_PKT_SKB_LEN 512
/* Ethernet header padding prepended to RX_PKTs */
#define RX_PKT_PAD 2
/*
* Max number of Tx descriptors we clean up at a time. Should be modest as
* freeing skbs isn't cheap and it happens while holding locks. We just need
* to free packets faster than they arrive, we eventually catch up and keep
* the amortized cost reasonable. Must be >= 2 * TXQ_STOP_THRES.
*/
#define MAX_TX_RECLAIM 16
/*
* Max number of Rx buffers we replenish at a time. Again keep this modest,
* allocating buffers isn't cheap either.
*/
#define MAX_RX_REFILL 16U
/*
* Period of the Rx queue check timer. This timer is infrequent as it has
* something to do only when the system experiences severe memory shortage.
*/
#define RX_QCHECK_PERIOD (HZ / 2)
/*
* Period of the Tx queue check timer.
*/
#define TX_QCHECK_PERIOD (HZ / 2)
/*
* Max number of Tx descriptors to be reclaimed by the Tx timer.
*/
#define MAX_TIMER_TX_RECLAIM 100
/*
* Timer index used when backing off due to memory shortage.
*/
#define NOMEM_TMR_IDX (SGE_NTIMERS - 1)
/*
* An FL with <= FL_STARVE_THRES buffers is starving and a periodic timer will
* attempt to refill it.
*/
#define FL_STARVE_THRES 4
/*
* Suspend an Ethernet Tx queue with fewer available descriptors than this.
* This is the same as calc_tx_descs() for a TSO packet with
* nr_frags == MAX_SKB_FRAGS.
*/
#define ETHTXQ_STOP_THRES \
(1 + DIV_ROUND_UP((3 * MAX_SKB_FRAGS) / 2 + (MAX_SKB_FRAGS & 1), 8))
/*
* Suspension threshold for non-Ethernet Tx queues. We require enough room
* for a full sized WR.
*/
#define TXQ_STOP_THRES (SGE_MAX_WR_LEN / sizeof(struct tx_desc))
/*
* Max Tx descriptor space we allow for an Ethernet packet to be inlined
* into a WR.
*/
#define MAX_IMM_TX_PKT_LEN 128
/*
* Max size of a WR sent through a control Tx queue.
*/
#define MAX_CTRL_WR_LEN SGE_MAX_WR_LEN
enum {
/* packet alignment in FL buffers */
FL_ALIGN = L1_CACHE_BYTES < 32 ? 32 : L1_CACHE_BYTES,
/* egress status entry size */
STAT_LEN = L1_CACHE_BYTES > 64 ? 128 : 64
};
struct tx_sw_desc { /* SW state per Tx descriptor */
struct sk_buff *skb;
struct ulptx_sgl *sgl;
};
struct rx_sw_desc { /* SW state per Rx descriptor */
struct page *page;
dma_addr_t dma_addr;
};
/*
* The low bits of rx_sw_desc.dma_addr have special meaning.
*/
enum {
RX_LARGE_BUF = 1 << 0, /* buffer is larger than PAGE_SIZE */
RX_UNMAPPED_BUF = 1 << 1, /* buffer is not mapped */
};
static inline dma_addr_t get_buf_addr(const struct rx_sw_desc *d)
{
return d->dma_addr & ~(dma_addr_t)(RX_LARGE_BUF | RX_UNMAPPED_BUF);
}
static inline bool is_buf_mapped(const struct rx_sw_desc *d)
{
return !(d->dma_addr & RX_UNMAPPED_BUF);
}
/**
* txq_avail - return the number of available slots in a Tx queue
* @q: the Tx queue
*
* Returns the number of descriptors in a Tx queue available to write new
* packets.
*/
static inline unsigned int txq_avail(const struct sge_txq *q)
{
return q->size - 1 - q->in_use;
}
/**
* fl_cap - return the capacity of a free-buffer list
* @fl: the FL
*
* Returns the capacity of a free-buffer list. The capacity is less than
* the size because one descriptor needs to be left unpopulated, otherwise
* HW will think the FL is empty.
*/
static inline unsigned int fl_cap(const struct sge_fl *fl)
{
return fl->size - 8; /* 1 descriptor = 8 buffers */
}
static inline bool fl_starving(const struct sge_fl *fl)
{
return fl->avail - fl->pend_cred <= FL_STARVE_THRES;
}
static int map_skb(struct device *dev, const struct sk_buff *skb,
dma_addr_t *addr)
{
const skb_frag_t *fp, *end;
const struct skb_shared_info *si;
*addr = dma_map_single(dev, skb->data, skb_headlen(skb), DMA_TO_DEVICE);
if (dma_mapping_error(dev, *addr))
goto out_err;
si = skb_shinfo(skb);
end = &si->frags[si->nr_frags];
for (fp = si->frags; fp < end; fp++) {
*++addr = skb_frag_dma_map(dev, fp, 0, skb_frag_size(fp),
DMA_TO_DEVICE);
if (dma_mapping_error(dev, *addr))
goto unwind;
}
return 0;
unwind:
while (fp-- > si->frags)
dma_unmap_page(dev, *--addr, skb_frag_size(fp), DMA_TO_DEVICE);
dma_unmap_single(dev, addr[-1], skb_headlen(skb), DMA_TO_DEVICE);
out_err:
return -ENOMEM;
}
#ifdef CONFIG_NEED_DMA_MAP_STATE
static void unmap_skb(struct device *dev, const struct sk_buff *skb,
const dma_addr_t *addr)
{
const skb_frag_t *fp, *end;
const struct skb_shared_info *si;
dma_unmap_single(dev, *addr++, skb_headlen(skb), DMA_TO_DEVICE);
si = skb_shinfo(skb);
end = &si->frags[si->nr_frags];
for (fp = si->frags; fp < end; fp++)
dma_unmap_page(dev, *addr++, skb_frag_size(fp), DMA_TO_DEVICE);
}
/**
* deferred_unmap_destructor - unmap a packet when it is freed
* @skb: the packet
*
* This is the packet destructor used for Tx packets that need to remain
* mapped until they are freed rather than until their Tx descriptors are
* freed.
*/
static void deferred_unmap_destructor(struct sk_buff *skb)
{
unmap_skb(skb->dev->dev.parent, skb, (dma_addr_t *)skb->head);
}
#endif
static void unmap_sgl(struct device *dev, const struct sk_buff *skb,
const struct ulptx_sgl *sgl, const struct sge_txq *q)
{
const struct ulptx_sge_pair *p;
unsigned int nfrags = skb_shinfo(skb)->nr_frags;
if (likely(skb_headlen(skb)))
dma_unmap_single(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
DMA_TO_DEVICE);
else {
dma_unmap_page(dev, be64_to_cpu(sgl->addr0), ntohl(sgl->len0),
DMA_TO_DEVICE);
nfrags--;
}
/*
* the complexity below is because of the possibility of a wrap-around
* in the middle of an SGL
*/
for (p = sgl->sge; nfrags >= 2; nfrags -= 2) {
if (likely((u8 *)(p + 1) <= (u8 *)q->stat)) {
unmap: dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
ntohl(p->len[0]), DMA_TO_DEVICE);
dma_unmap_page(dev, be64_to_cpu(p->addr[1]),
ntohl(p->len[1]), DMA_TO_DEVICE);
p++;
} else if ((u8 *)p == (u8 *)q->stat) {
p = (const struct ulptx_sge_pair *)q->desc;
goto unmap;
} else if ((u8 *)p + 8 == (u8 *)q->stat) {
const __be64 *addr = (const __be64 *)q->desc;
dma_unmap_page(dev, be64_to_cpu(addr[0]),
ntohl(p->len[0]), DMA_TO_DEVICE);
dma_unmap_page(dev, be64_to_cpu(addr[1]),
ntohl(p->len[1]), DMA_TO_DEVICE);
p = (const struct ulptx_sge_pair *)&addr[2];
} else {
const __be64 *addr = (const __be64 *)q->desc;
dma_unmap_page(dev, be64_to_cpu(p->addr[0]),
ntohl(p->len[0]), DMA_TO_DEVICE);
dma_unmap_page(dev, be64_to_cpu(addr[0]),
ntohl(p->len[1]), DMA_TO_DEVICE);
p = (const struct ulptx_sge_pair *)&addr[1];
}
}
if (nfrags) {
__be64 addr;
if ((u8 *)p == (u8 *)q->stat)
p = (const struct ulptx_sge_pair *)q->desc;
addr = (u8 *)p + 16 <= (u8 *)q->stat ? p->addr[0] :
*(const __be64 *)q->desc;
dma_unmap_page(dev, be64_to_cpu(addr), ntohl(p->len[0]),
DMA_TO_DEVICE);
}
}
/**
* free_tx_desc - reclaims Tx descriptors and their buffers
* @adapter: the adapter
* @q: the Tx queue to reclaim descriptors from
* @n: the number of descriptors to reclaim
* @unmap: whether the buffers should be unmapped for DMA
*
* Reclaims Tx descriptors from an SGE Tx queue and frees the associated
* Tx buffers. Called with the Tx queue lock held.
*/
static void free_tx_desc(struct adapter *adap, struct sge_txq *q,
unsigned int n, bool unmap)
{
struct tx_sw_desc *d;
unsigned int cidx = q->cidx;
struct device *dev = adap->pdev_dev;
d = &q->sdesc[cidx];
while (n--) {
if (d->skb) { /* an SGL is present */
if (unmap)
unmap_sgl(dev, d->skb, d->sgl, q);
kfree_skb(d->skb);
d->skb = NULL;
}
++d;
if (++cidx == q->size) {
cidx = 0;
d = q->sdesc;
}
}
q->cidx = cidx;
}
/*
* Return the number of reclaimable descriptors in a Tx queue.
*/
static inline int reclaimable(const struct sge_txq *q)
{
int hw_cidx = ntohs(q->stat->cidx);
hw_cidx -= q->cidx;
return hw_cidx < 0 ? hw_cidx + q->size : hw_cidx;
}
/**
* reclaim_completed_tx - reclaims completed Tx descriptors
* @adap: the adapter
* @q: the Tx queue to reclaim completed descriptors from
* @unmap: whether the buffers should be unmapped for DMA
*
* Reclaims Tx descriptors that the SGE has indicated it has processed,
* and frees the associated buffers if possible. Called with the Tx
* queue locked.
*/
static inline void reclaim_completed_tx(struct adapter *adap, struct sge_txq *q,
bool unmap)
{
int avail = reclaimable(q);
if (avail) {
/*
* Limit the amount of clean up work we do at a time to keep
* the Tx lock hold time O(1).
*/
if (avail > MAX_TX_RECLAIM)
avail = MAX_TX_RECLAIM;
free_tx_desc(adap, q, avail, unmap);
q->in_use -= avail;
}
}
static inline int get_buf_size(const struct rx_sw_desc *d)
{
#if FL_PG_ORDER > 0
return (d->dma_addr & RX_LARGE_BUF) ? (PAGE_SIZE << FL_PG_ORDER) :
PAGE_SIZE;
#else
return PAGE_SIZE;
#endif
}
/**
* free_rx_bufs - free the Rx buffers on an SGE free list
* @adap: the adapter
* @q: the SGE free list to free buffers from
* @n: how many buffers to free
*
* Release the next @n buffers on an SGE free-buffer Rx queue. The
* buffers must be made inaccessible to HW before calling this function.
*/
static void free_rx_bufs(struct adapter *adap, struct sge_fl *q, int n)
{
while (n--) {
struct rx_sw_desc *d = &q->sdesc[q->cidx];
if (is_buf_mapped(d))
dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
get_buf_size(d), PCI_DMA_FROMDEVICE);
put_page(d->page);
d->page = NULL;
if (++q->cidx == q->size)
q->cidx = 0;
q->avail--;
}
}
/**
* unmap_rx_buf - unmap the current Rx buffer on an SGE free list
* @adap: the adapter
* @q: the SGE free list
*
* Unmap the current buffer on an SGE free-buffer Rx queue. The
* buffer must be made inaccessible to HW before calling this function.
*
* This is similar to @free_rx_bufs above but does not free the buffer.
* Do note that the FL still loses any further access to the buffer.
*/
static void unmap_rx_buf(struct adapter *adap, struct sge_fl *q)
{
struct rx_sw_desc *d = &q->sdesc[q->cidx];
if (is_buf_mapped(d))
dma_unmap_page(adap->pdev_dev, get_buf_addr(d),
get_buf_size(d), PCI_DMA_FROMDEVICE);
d->page = NULL;
if (++q->cidx == q->size)
q->cidx = 0;
q->avail--;
}
static inline void ring_fl_db(struct adapter *adap, struct sge_fl *q)
{
if (q->pend_cred >= 8) {
wmb();
t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL), DBPRIO |
QID(q->cntxt_id) | PIDX(q->pend_cred / 8));
q->pend_cred &= 7;
}
}
static inline void set_rx_sw_desc(struct rx_sw_desc *sd, struct page *pg,
dma_addr_t mapping)
{
sd->page = pg;
sd->dma_addr = mapping; /* includes size low bits */
}
/**
* refill_fl - refill an SGE Rx buffer ring
* @adap: the adapter
* @q: the ring to refill
* @n: the number of new buffers to allocate
* @gfp: the gfp flags for the allocations
*
* (Re)populate an SGE free-buffer queue with up to @n new packet buffers,
* allocated with the supplied gfp flags. The caller must assure that
* @n does not exceed the queue's capacity. If afterwards the queue is
* found critically low mark it as starving in the bitmap of starving FLs.
*
* Returns the number of buffers allocated.
*/
static unsigned int refill_fl(struct adapter *adap, struct sge_fl *q, int n,
gfp_t gfp)
{
struct page *pg;
dma_addr_t mapping;
unsigned int cred = q->avail;
__be64 *d = &q->desc[q->pidx];
struct rx_sw_desc *sd = &q->sdesc[q->pidx];
gfp |= __GFP_NOWARN | __GFP_COLD;
#if FL_PG_ORDER > 0
/*
* Prefer large buffers
*/
while (n) {
pg = alloc_pages(gfp | __GFP_COMP, FL_PG_ORDER);
if (unlikely(!pg)) {
q->large_alloc_failed++;
break; /* fall back to single pages */
}
mapping = dma_map_page(adap->pdev_dev, pg, 0,
PAGE_SIZE << FL_PG_ORDER,
PCI_DMA_FROMDEVICE);
if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
__free_pages(pg, FL_PG_ORDER);
goto out; /* do not try small pages for this error */
}
mapping |= RX_LARGE_BUF;
*d++ = cpu_to_be64(mapping);
set_rx_sw_desc(sd, pg, mapping);
sd++;
q->avail++;
if (++q->pidx == q->size) {
q->pidx = 0;
sd = q->sdesc;
d = q->desc;
}
n--;
}
#endif
while (n--) {
pg = alloc_page(gfp);
if (unlikely(!pg)) {
q->alloc_failed++;
break;
}
mapping = dma_map_page(adap->pdev_dev, pg, 0, PAGE_SIZE,
PCI_DMA_FROMDEVICE);
if (unlikely(dma_mapping_error(adap->pdev_dev, mapping))) {
put_page(pg);
goto out;
}
*d++ = cpu_to_be64(mapping);
set_rx_sw_desc(sd, pg, mapping);
sd++;
q->avail++;
if (++q->pidx == q->size) {
q->pidx = 0;
sd = q->sdesc;
d = q->desc;
}
}
out: cred = q->avail - cred;
q->pend_cred += cred;
ring_fl_db(adap, q);
if (unlikely(fl_starving(q))) {
smp_wmb();
set_bit(q->cntxt_id - adap->sge.egr_start,
adap->sge.starving_fl);
}
return cred;
}
static inline void __refill_fl(struct adapter *adap, struct sge_fl *fl)
{
refill_fl(adap, fl, min(MAX_RX_REFILL, fl_cap(fl) - fl->avail),
GFP_ATOMIC);
}
/**
* alloc_ring - allocate resources for an SGE descriptor ring
* @dev: the PCI device's core device
* @nelem: the number of descriptors
* @elem_size: the size of each descriptor
* @sw_size: the size of the SW state associated with each ring element
* @phys: the physical address of the allocated ring
* @metadata: address of the array holding the SW state for the ring
* @stat_size: extra space in HW ring for status information
* @node: preferred node for memory allocations
*
* Allocates resources for an SGE descriptor ring, such as Tx queues,
* free buffer lists, or response queues. Each SGE ring requires
* space for its HW descriptors plus, optionally, space for the SW state
* associated with each HW entry (the metadata). The function returns
* three values: the virtual address for the HW ring (the return value
* of the function), the bus address of the HW ring, and the address
* of the SW ring.
*/
static void *alloc_ring(struct device *dev, size_t nelem, size_t elem_size,
size_t sw_size, dma_addr_t *phys, void *metadata,
size_t stat_size, int node)
{
size_t len = nelem * elem_size + stat_size;
void *s = NULL;
void *p = dma_alloc_coherent(dev, len, phys, GFP_KERNEL);
if (!p)
return NULL;
if (sw_size) {
s = kzalloc_node(nelem * sw_size, GFP_KERNEL, node);
if (!s) {
dma_free_coherent(dev, len, p, *phys);
return NULL;
}
}
if (metadata)
*(void **)metadata = s;
memset(p, 0, len);
return p;
}
/**
* sgl_len - calculates the size of an SGL of the given capacity
* @n: the number of SGL entries
*
* Calculates the number of flits needed for a scatter/gather list that
* can hold the given number of entries.
*/
static inline unsigned int sgl_len(unsigned int n)
{
n--;
return (3 * n) / 2 + (n & 1) + 2;
}
/**
* flits_to_desc - returns the num of Tx descriptors for the given flits
* @n: the number of flits
*
* Returns the number of Tx descriptors needed for the supplied number
* of flits.
*/
static inline unsigned int flits_to_desc(unsigned int n)
{
BUG_ON(n > SGE_MAX_WR_LEN / 8);
return DIV_ROUND_UP(n, 8);
}
/**
* is_eth_imm - can an Ethernet packet be sent as immediate data?
* @skb: the packet
*
* Returns whether an Ethernet packet is small enough to fit as
* immediate data.
*/
static inline int is_eth_imm(const struct sk_buff *skb)
{
return skb->len <= MAX_IMM_TX_PKT_LEN - sizeof(struct cpl_tx_pkt);
}
/**
* calc_tx_flits - calculate the number of flits for a packet Tx WR
* @skb: the packet
*
* Returns the number of flits needed for a Tx WR for the given Ethernet
* packet, including the needed WR and CPL headers.
*/
static inline unsigned int calc_tx_flits(const struct sk_buff *skb)
{
unsigned int flits;
if (is_eth_imm(skb))
return DIV_ROUND_UP(skb->len + sizeof(struct cpl_tx_pkt), 8);
flits = sgl_len(skb_shinfo(skb)->nr_frags + 1) + 4;
if (skb_shinfo(skb)->gso_size)
flits += 2;
return flits;
}
/**
* calc_tx_descs - calculate the number of Tx descriptors for a packet
* @skb: the packet
*
* Returns the number of Tx descriptors needed for the given Ethernet
* packet, including the needed WR and CPL headers.
*/
static inline unsigned int calc_tx_descs(const struct sk_buff *skb)
{
return flits_to_desc(calc_tx_flits(skb));
}
/**
* write_sgl - populate a scatter/gather list for a packet
* @skb: the packet
* @q: the Tx queue we are writing into
* @sgl: starting location for writing the SGL
* @end: points right after the end of the SGL
* @start: start offset into skb main-body data to include in the SGL
* @addr: the list of bus addresses for the SGL elements
*
* Generates a gather list for the buffers that make up a packet.
* The caller must provide adequate space for the SGL that will be written.
* The SGL includes all of the packet's page fragments and the data in its
* main body except for the first @start bytes. @sgl must be 16-byte
* aligned and within a Tx descriptor with available space. @end points
* right after the end of the SGL but does not account for any potential
* wrap around, i.e., @end > @sgl.
*/
static void write_sgl(const struct sk_buff *skb, struct sge_txq *q,
struct ulptx_sgl *sgl, u64 *end, unsigned int start,
const dma_addr_t *addr)
{
unsigned int i, len;
struct ulptx_sge_pair *to;
const struct skb_shared_info *si = skb_shinfo(skb);
unsigned int nfrags = si->nr_frags;
struct ulptx_sge_pair buf[MAX_SKB_FRAGS / 2 + 1];
len = skb_headlen(skb) - start;
if (likely(len)) {
sgl->len0 = htonl(len);
sgl->addr0 = cpu_to_be64(addr[0] + start);
nfrags++;
} else {
sgl->len0 = htonl(skb_frag_size(&si->frags[0]));
sgl->addr0 = cpu_to_be64(addr[1]);
}
sgl->cmd_nsge = htonl(ULPTX_CMD(ULP_TX_SC_DSGL) | ULPTX_NSGE(nfrags));
if (likely(--nfrags == 0))
return;
/*
* Most of the complexity below deals with the possibility we hit the
* end of the queue in the middle of writing the SGL. For this case
* only we create the SGL in a temporary buffer and then copy it.
*/
to = (u8 *)end > (u8 *)q->stat ? buf : sgl->sge;
for (i = (nfrags != si->nr_frags); nfrags >= 2; nfrags -= 2, to++) {
to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
to->len[1] = cpu_to_be32(skb_frag_size(&si->frags[++i]));
to->addr[0] = cpu_to_be64(addr[i]);
to->addr[1] = cpu_to_be64(addr[++i]);
}
if (nfrags) {
to->len[0] = cpu_to_be32(skb_frag_size(&si->frags[i]));
to->len[1] = cpu_to_be32(0);
to->addr[0] = cpu_to_be64(addr[i + 1]);
}
if (unlikely((u8 *)end > (u8 *)q->stat)) {
unsigned int part0 = (u8 *)q->stat - (u8 *)sgl->sge, part1;
if (likely(part0))
memcpy(sgl->sge, buf, part0);
part1 = (u8 *)end - (u8 *)q->stat;
memcpy(q->desc, (u8 *)buf + part0, part1);
end = (void *)q->desc + part1;
}
if ((uintptr_t)end & 8) /* 0-pad to multiple of 16 */
*(u64 *)end = 0;
}
/**
* ring_tx_db - check and potentially ring a Tx queue's doorbell
* @adap: the adapter
* @q: the Tx queue
* @n: number of new descriptors to give to HW
*
* Ring the doorbel for a Tx queue.
*/
static inline void ring_tx_db(struct adapter *adap, struct sge_txq *q, int n)
{
wmb(); /* write descriptors before telling HW */
t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL),
QID(q->cntxt_id) | PIDX(n));
}
/**
* inline_tx_skb - inline a packet's data into Tx descriptors
* @skb: the packet
* @q: the Tx queue where the packet will be inlined
* @pos: starting position in the Tx queue where to inline the packet
*
* Inline a packet's contents directly into Tx descriptors, starting at
* the given position within the Tx DMA ring.
* Most of the complexity of this operation is dealing with wrap arounds
* in the middle of the packet we want to inline.
*/
static void inline_tx_skb(const struct sk_buff *skb, const struct sge_txq *q,
void *pos)
{
u64 *p;
int left = (void *)q->stat - pos;
if (likely(skb->len <= left)) {
if (likely(!skb->data_len))
skb_copy_from_linear_data(skb, pos, skb->len);
else
skb_copy_bits(skb, 0, pos, skb->len);
pos += skb->len;
} else {
skb_copy_bits(skb, 0, pos, left);
skb_copy_bits(skb, left, q->desc, skb->len - left);
pos = (void *)q->desc + (skb->len - left);
}
/* 0-pad to multiple of 16 */
p = PTR_ALIGN(pos, 8);
if ((uintptr_t)p & 8)
*p = 0;
}
/*
* Figure out what HW csum a packet wants and return the appropriate control
* bits.
*/
static u64 hwcsum(const struct sk_buff *skb)
{
int csum_type;
const struct iphdr *iph = ip_hdr(skb);
if (iph->version == 4) {
if (iph->protocol == IPPROTO_TCP)
csum_type = TX_CSUM_TCPIP;
else if (iph->protocol == IPPROTO_UDP)
csum_type = TX_CSUM_UDPIP;
else {
nocsum: /*
* unknown protocol, disable HW csum
* and hope a bad packet is detected
*/
return TXPKT_L4CSUM_DIS;
}
} else {
/*
* this doesn't work with extension headers
*/
const struct ipv6hdr *ip6h = (const struct ipv6hdr *)iph;
if (ip6h->nexthdr == IPPROTO_TCP)
csum_type = TX_CSUM_TCPIP6;
else if (ip6h->nexthdr == IPPROTO_UDP)
csum_type = TX_CSUM_UDPIP6;
else
goto nocsum;
}
if (likely(csum_type >= TX_CSUM_TCPIP))
return TXPKT_CSUM_TYPE(csum_type) |
TXPKT_IPHDR_LEN(skb_network_header_len(skb)) |
TXPKT_ETHHDR_LEN(skb_network_offset(skb) - ETH_HLEN);
else {
int start = skb_transport_offset(skb);
return TXPKT_CSUM_TYPE(csum_type) | TXPKT_CSUM_START(start) |
TXPKT_CSUM_LOC(start + skb->csum_offset);
}
}
static void eth_txq_stop(struct sge_eth_txq *q)
{
netif_tx_stop_queue(q->txq);
q->q.stops++;
}
static inline void txq_advance(struct sge_txq *q, unsigned int n)
{
q->in_use += n;
q->pidx += n;
if (q->pidx >= q->size)
q->pidx -= q->size;
}
/**
* t4_eth_xmit - add a packet to an Ethernet Tx queue
* @skb: the packet
* @dev: the egress net device
*
* Add a packet to an SGE Ethernet Tx queue. Runs with softirqs disabled.
*/
netdev_tx_t t4_eth_xmit(struct sk_buff *skb, struct net_device *dev)
{
u32 wr_mid;
u64 cntrl, *end;
int qidx, credits;
unsigned int flits, ndesc;
struct adapter *adap;
struct sge_eth_txq *q;
const struct port_info *pi;
struct fw_eth_tx_pkt_wr *wr;
struct cpl_tx_pkt_core *cpl;
const struct skb_shared_info *ssi;
dma_addr_t addr[MAX_SKB_FRAGS + 1];
/*
* The chip min packet length is 10 octets but play safe and reject
* anything shorter than an Ethernet header.
*/
if (unlikely(skb->len < ETH_HLEN)) {
out_free: dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
pi = netdev_priv(dev);
adap = pi->adapter;
qidx = skb_get_queue_mapping(skb);
q = &adap->sge.ethtxq[qidx + pi->first_qset];
reclaim_completed_tx(adap, &q->q, true);
flits = calc_tx_flits(skb);
ndesc = flits_to_desc(flits);
credits = txq_avail(&q->q) - ndesc;
if (unlikely(credits < 0)) {
eth_txq_stop(q);
dev_err(adap->pdev_dev,
"%s: Tx ring %u full while queue awake!\n",
dev->name, qidx);
return NETDEV_TX_BUSY;
}
if (!is_eth_imm(skb) &&
unlikely(map_skb(adap->pdev_dev, skb, addr) < 0)) {
q->mapping_err++;
goto out_free;
}
wr_mid = FW_WR_LEN16(DIV_ROUND_UP(flits, 2));
if (unlikely(credits < ETHTXQ_STOP_THRES)) {
eth_txq_stop(q);
wr_mid |= FW_WR_EQUEQ | FW_WR_EQUIQ;
}
wr = (void *)&q->q.desc[q->q.pidx];
wr->equiq_to_len16 = htonl(wr_mid);
wr->r3 = cpu_to_be64(0);
end = (u64 *)wr + flits;
ssi = skb_shinfo(skb);
if (ssi->gso_size) {
struct cpl_tx_pkt_lso *lso = (void *)wr;
bool v6 = (ssi->gso_type & SKB_GSO_TCPV6) != 0;
int l3hdr_len = skb_network_header_len(skb);
int eth_xtra_len = skb_network_offset(skb) - ETH_HLEN;
wr->op_immdlen = htonl(FW_WR_OP(FW_ETH_TX_PKT_WR) |
FW_WR_IMMDLEN(sizeof(*lso)));
lso->c.lso_ctrl = htonl(LSO_OPCODE(CPL_TX_PKT_LSO) |
LSO_FIRST_SLICE | LSO_LAST_SLICE |
LSO_IPV6(v6) |
LSO_ETHHDR_LEN(eth_xtra_len / 4) |
LSO_IPHDR_LEN(l3hdr_len / 4) |
LSO_TCPHDR_LEN(tcp_hdr(skb)->doff));
lso->c.ipid_ofst = htons(0);
lso->c.mss = htons(ssi->gso_size);
lso->c.seqno_offset = htonl(0);
lso->c.len = htonl(skb->len);
cpl = (void *)(lso + 1);
cntrl = TXPKT_CSUM_TYPE(v6 ? TX_CSUM_TCPIP6 : TX_CSUM_TCPIP) |
TXPKT_IPHDR_LEN(l3hdr_len) |
TXPKT_ETHHDR_LEN(eth_xtra_len);
q->tso++;
q->tx_cso += ssi->gso_segs;
} else {
int len;
len = is_eth_imm(skb) ? skb->len + sizeof(*cpl) : sizeof(*cpl);
wr->op_immdlen = htonl(FW_WR_OP(FW_ETH_TX_PKT_WR) |
FW_WR_IMMDLEN(len));
cpl = (void *)(wr + 1);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
cntrl = hwcsum(skb) | TXPKT_IPCSUM_DIS;
q->tx_cso++;
} else
cntrl = TXPKT_L4CSUM_DIS | TXPKT_IPCSUM_DIS;
}
if (vlan_tx_tag_present(skb)) {
q->vlan_ins++;
cntrl |= TXPKT_VLAN_VLD | TXPKT_VLAN(vlan_tx_tag_get(skb));
}
cpl->ctrl0 = htonl(TXPKT_OPCODE(CPL_TX_PKT_XT) |
TXPKT_INTF(pi->tx_chan) | TXPKT_PF(adap->fn));
cpl->pack = htons(0);
cpl->len = htons(skb->len);
cpl->ctrl1 = cpu_to_be64(cntrl);
if (is_eth_imm(skb)) {
inline_tx_skb(skb, &q->q, cpl + 1);
dev_kfree_skb(skb);
} else {
int last_desc;
write_sgl(skb, &q->q, (struct ulptx_sgl *)(cpl + 1), end, 0,
addr);
skb_orphan(skb);
last_desc = q->q.pidx + ndesc - 1;
if (last_desc >= q->q.size)
last_desc -= q->q.size;
q->q.sdesc[last_desc].skb = skb;
q->q.sdesc[last_desc].sgl = (struct ulptx_sgl *)(cpl + 1);
}
txq_advance(&q->q, ndesc);
ring_tx_db(adap, &q->q, ndesc);
return NETDEV_TX_OK;
}
/**
* reclaim_completed_tx_imm - reclaim completed control-queue Tx descs
* @q: the SGE control Tx queue
*
* This is a variant of reclaim_completed_tx() that is used for Tx queues
* that send only immediate data (presently just the control queues) and
* thus do not have any sk_buffs to release.
*/
static inline void reclaim_completed_tx_imm(struct sge_txq *q)
{
int hw_cidx = ntohs(q->stat->cidx);
int reclaim = hw_cidx - q->cidx;
if (reclaim < 0)
reclaim += q->size;
q->in_use -= reclaim;
q->cidx = hw_cidx;
}
/**
* is_imm - check whether a packet can be sent as immediate data
* @skb: the packet
*
* Returns true if a packet can be sent as a WR with immediate data.
*/
static inline int is_imm(const struct sk_buff *skb)
{
return skb->len <= MAX_CTRL_WR_LEN;
}
/**
* ctrlq_check_stop - check if a control queue is full and should stop
* @q: the queue
* @wr: most recent WR written to the queue
*
* Check if a control queue has become full and should be stopped.
* We clean up control queue descriptors very lazily, only when we are out.
* If the queue is still full after reclaiming any completed descriptors
* we suspend it and have the last WR wake it up.
*/
static void ctrlq_check_stop(struct sge_ctrl_txq *q, struct fw_wr_hdr *wr)
{
reclaim_completed_tx_imm(&q->q);
if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
wr->lo |= htonl(FW_WR_EQUEQ | FW_WR_EQUIQ);
q->q.stops++;
q->full = 1;
}
}
/**
* ctrl_xmit - send a packet through an SGE control Tx queue
* @q: the control queue
* @skb: the packet
*
* Send a packet through an SGE control Tx queue. Packets sent through
* a control queue must fit entirely as immediate data.
*/
static int ctrl_xmit(struct sge_ctrl_txq *q, struct sk_buff *skb)
{
unsigned int ndesc;
struct fw_wr_hdr *wr;
if (unlikely(!is_imm(skb))) {
WARN_ON(1);
dev_kfree_skb(skb);
return NET_XMIT_DROP;
}
ndesc = DIV_ROUND_UP(skb->len, sizeof(struct tx_desc));
spin_lock(&q->sendq.lock);
if (unlikely(q->full)) {
skb->priority = ndesc; /* save for restart */
__skb_queue_tail(&q->sendq, skb);
spin_unlock(&q->sendq.lock);
return NET_XMIT_CN;
}
wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
inline_tx_skb(skb, &q->q, wr);
txq_advance(&q->q, ndesc);
if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES))
ctrlq_check_stop(q, wr);
ring_tx_db(q->adap, &q->q, ndesc);
spin_unlock(&q->sendq.lock);
kfree_skb(skb);
return NET_XMIT_SUCCESS;
}
/**
* restart_ctrlq - restart a suspended control queue
* @data: the control queue to restart
*
* Resumes transmission on a suspended Tx control queue.
*/
static void restart_ctrlq(unsigned long data)
{
struct sk_buff *skb;
unsigned int written = 0;
struct sge_ctrl_txq *q = (struct sge_ctrl_txq *)data;
spin_lock(&q->sendq.lock);
reclaim_completed_tx_imm(&q->q);
BUG_ON(txq_avail(&q->q) < TXQ_STOP_THRES); /* q should be empty */
while ((skb = __skb_dequeue(&q->sendq)) != NULL) {
struct fw_wr_hdr *wr;
unsigned int ndesc = skb->priority; /* previously saved */
/*
* Write descriptors and free skbs outside the lock to limit
* wait times. q->full is still set so new skbs will be queued.
*/
spin_unlock(&q->sendq.lock);
wr = (struct fw_wr_hdr *)&q->q.desc[q->q.pidx];
inline_tx_skb(skb, &q->q, wr);
kfree_skb(skb);
written += ndesc;
txq_advance(&q->q, ndesc);
if (unlikely(txq_avail(&q->q) < TXQ_STOP_THRES)) {
unsigned long old = q->q.stops;
ctrlq_check_stop(q, wr);
if (q->q.stops != old) { /* suspended anew */
spin_lock(&q->sendq.lock);
goto ringdb;
}
}
if (written > 16) {
ring_tx_db(q->adap, &q->q, written);
written = 0;
}
spin_lock(&q->sendq.lock);
}
q->full = 0;
ringdb: if (written)
ring_tx_db(q->adap, &q->q, written);
spin_unlock(&q->sendq.lock);
}
/**
* t4_mgmt_tx - send a management message
* @adap: the adapter
* @skb: the packet containing the management message
*
* Send a management message through control queue 0.
*/
int t4_mgmt_tx(struct adapter *adap, struct sk_buff *skb)
{
int ret;
local_bh_disable();
ret = ctrl_xmit(&adap->sge.ctrlq[0], skb);
local_bh_enable();
return ret;
}
/**
* is_ofld_imm - check whether a packet can be sent as immediate data
* @skb: the packet
*
* Returns true if a packet can be sent as an offload WR with immediate
* data. We currently use the same limit as for Ethernet packets.
*/
static inline int is_ofld_imm(const struct sk_buff *skb)
{
return skb->len <= MAX_IMM_TX_PKT_LEN;
}
/**
* calc_tx_flits_ofld - calculate # of flits for an offload packet
* @skb: the packet
*
* Returns the number of flits needed for the given offload packet.
* These packets are already fully constructed and no additional headers
* will be added.
*/
static inline unsigned int calc_tx_flits_ofld(const struct sk_buff *skb)
{
unsigned int flits, cnt;
if (is_ofld_imm(skb))
return DIV_ROUND_UP(skb->len, 8);
flits = skb_transport_offset(skb) / 8U; /* headers */
cnt = skb_shinfo(skb)->nr_frags;
if (skb->tail != skb->transport_header)
cnt++;
return flits + sgl_len(cnt);
}
/**
* txq_stop_maperr - stop a Tx queue due to I/O MMU exhaustion
* @adap: the adapter
* @q: the queue to stop
*
* Mark a Tx queue stopped due to I/O MMU exhaustion and resulting
* inability to map packets. A periodic timer attempts to restart
* queues so marked.
*/
static void txq_stop_maperr(struct sge_ofld_txq *q)
{
q->mapping_err++;
q->q.stops++;
set_bit(q->q.cntxt_id - q->adap->sge.egr_start,
q->adap->sge.txq_maperr);
}
/**
* ofldtxq_stop - stop an offload Tx queue that has become full
* @q: the queue to stop
* @skb: the packet causing the queue to become full
*
* Stops an offload Tx queue that has become full and modifies the packet
* being written to request a wakeup.
*/
static void ofldtxq_stop(struct sge_ofld_txq *q, struct sk_buff *skb)
{
struct fw_wr_hdr *wr = (struct fw_wr_hdr *)skb->data;
wr->lo |= htonl(FW_WR_EQUEQ | FW_WR_EQUIQ);
q->q.stops++;
q->full = 1;
}
/**
* service_ofldq - restart a suspended offload queue
* @q: the offload queue
*
* Services an offload Tx queue by moving packets from its packet queue
* to the HW Tx ring. The function starts and ends with the queue locked.
*/
static void service_ofldq(struct sge_ofld_txq *q)
{
u64 *pos;
int credits;
struct sk_buff *skb;
unsigned int written = 0;
unsigned int flits, ndesc;
while ((skb = skb_peek(&q->sendq)) != NULL && !q->full) {
/*
* We drop the lock but leave skb on sendq, thus retaining
* exclusive access to the state of the queue.
*/
spin_unlock(&q->sendq.lock);
reclaim_completed_tx(q->adap, &q->q, false);
flits = skb->priority; /* previously saved */
ndesc = flits_to_desc(flits);
credits = txq_avail(&q->q) - ndesc;
BUG_ON(credits < 0);
if (unlikely(credits < TXQ_STOP_THRES))
ofldtxq_stop(q, skb);
pos = (u64 *)&q->q.desc[q->q.pidx];
if (is_ofld_imm(skb))
inline_tx_skb(skb, &q->q, pos);
else if (map_skb(q->adap->pdev_dev, skb,
(dma_addr_t *)skb->head)) {
txq_stop_maperr(q);
spin_lock(&q->sendq.lock);
break;
} else {
int last_desc, hdr_len = skb_transport_offset(skb);
memcpy(pos, skb->data, hdr_len);
write_sgl(skb, &q->q, (void *)pos + hdr_len,
pos + flits, hdr_len,
(dma_addr_t *)skb->head);
#ifdef CONFIG_NEED_DMA_MAP_STATE
skb->dev = q->adap->port[0];
skb->destructor = deferred_unmap_destructor;
#endif
last_desc = q->q.pidx + ndesc - 1;
if (last_desc >= q->q.size)
last_desc -= q->q.size;
q->q.sdesc[last_desc].skb = skb;
}
txq_advance(&q->q, ndesc);
written += ndesc;
if (unlikely(written > 32)) {
ring_tx_db(q->adap, &q->q, written);
written = 0;
}
spin_lock(&q->sendq.lock);
__skb_unlink(skb, &q->sendq);
if (is_ofld_imm(skb))
kfree_skb(skb);
}
if (likely(written))
ring_tx_db(q->adap, &q->q, written);
}
/**
* ofld_xmit - send a packet through an offload queue
* @q: the Tx offload queue
* @skb: the packet
*
* Send an offload packet through an SGE offload queue.
*/
static int ofld_xmit(struct sge_ofld_txq *q, struct sk_buff *skb)
{
skb->priority = calc_tx_flits_ofld(skb); /* save for restart */
spin_lock(&q->sendq.lock);
__skb_queue_tail(&q->sendq, skb);
if (q->sendq.qlen == 1)
service_ofldq(q);
spin_unlock(&q->sendq.lock);
return NET_XMIT_SUCCESS;
}
/**
* restart_ofldq - restart a suspended offload queue
* @data: the offload queue to restart
*
* Resumes transmission on a suspended Tx offload queue.
*/
static void restart_ofldq(unsigned long data)
{
struct sge_ofld_txq *q = (struct sge_ofld_txq *)data;
spin_lock(&q->sendq.lock);
q->full = 0; /* the queue actually is completely empty now */
service_ofldq(q);
spin_unlock(&q->sendq.lock);
}
/**
* skb_txq - return the Tx queue an offload packet should use
* @skb: the packet
*
* Returns the Tx queue an offload packet should use as indicated by bits
* 1-15 in the packet's queue_mapping.
*/
static inline unsigned int skb_txq(const struct sk_buff *skb)
{
return skb->queue_mapping >> 1;
}
/**
* is_ctrl_pkt - return whether an offload packet is a control packet
* @skb: the packet
*
* Returns whether an offload packet should use an OFLD or a CTRL
* Tx queue as indicated by bit 0 in the packet's queue_mapping.
*/
static inline unsigned int is_ctrl_pkt(const struct sk_buff *skb)
{
return skb->queue_mapping & 1;
}
static inline int ofld_send(struct adapter *adap, struct sk_buff *skb)
{
unsigned int idx = skb_txq(skb);
if (unlikely(is_ctrl_pkt(skb)))
return ctrl_xmit(&adap->sge.ctrlq[idx], skb);
return ofld_xmit(&adap->sge.ofldtxq[idx], skb);
}
/**
* t4_ofld_send - send an offload packet
* @adap: the adapter
* @skb: the packet
*
* Sends an offload packet. We use the packet queue_mapping to select the
* appropriate Tx queue as follows: bit 0 indicates whether the packet
* should be sent as regular or control, bits 1-15 select the queue.
*/
int t4_ofld_send(struct adapter *adap, struct sk_buff *skb)
{
int ret;
local_bh_disable();
ret = ofld_send(adap, skb);
local_bh_enable();
return ret;
}
/**
* cxgb4_ofld_send - send an offload packet
* @dev: the net device
* @skb: the packet
*
* Sends an offload packet. This is an exported version of @t4_ofld_send,
* intended for ULDs.
*/
int cxgb4_ofld_send(struct net_device *dev, struct sk_buff *skb)
{
return t4_ofld_send(netdev2adap(dev), skb);
}
EXPORT_SYMBOL(cxgb4_ofld_send);
static inline void copy_frags(struct sk_buff *skb,
const struct pkt_gl *gl, unsigned int offset)
{
int i;
/* usually there's just one frag */
__skb_fill_page_desc(skb, 0, gl->frags[0].page,
gl->frags[0].offset + offset,
gl->frags[0].size - offset);
skb_shinfo(skb)->nr_frags = gl->nfrags;
for (i = 1; i < gl->nfrags; i++)
__skb_fill_page_desc(skb, i, gl->frags[i].page,
gl->frags[i].offset,
gl->frags[i].size);
/* get a reference to the last page, we don't own it */
get_page(gl->frags[gl->nfrags - 1].page);
}
/**
* cxgb4_pktgl_to_skb - build an sk_buff from a packet gather list
* @gl: the gather list
* @skb_len: size of sk_buff main body if it carries fragments
* @pull_len: amount of data to move to the sk_buff's main body
*
* Builds an sk_buff from the given packet gather list. Returns the
* sk_buff or %NULL if sk_buff allocation failed.
*/
struct sk_buff *cxgb4_pktgl_to_skb(const struct pkt_gl *gl,
unsigned int skb_len, unsigned int pull_len)
{
struct sk_buff *skb;
/*
* Below we rely on RX_COPY_THRES being less than the smallest Rx buffer
* size, which is expected since buffers are at least PAGE_SIZEd.
* In this case packets up to RX_COPY_THRES have only one fragment.
*/
if (gl->tot_len <= RX_COPY_THRES) {
skb = dev_alloc_skb(gl->tot_len);
if (unlikely(!skb))
goto out;
__skb_put(skb, gl->tot_len);
skb_copy_to_linear_data(skb, gl->va, gl->tot_len);
} else {
skb = dev_alloc_skb(skb_len);
if (unlikely(!skb))
goto out;
__skb_put(skb, pull_len);
skb_copy_to_linear_data(skb, gl->va, pull_len);
copy_frags(skb, gl, pull_len);
skb->len = gl->tot_len;
skb->data_len = skb->len - pull_len;
skb->truesize += skb->data_len;
}
out: return skb;
}
EXPORT_SYMBOL(cxgb4_pktgl_to_skb);
/**
* t4_pktgl_free - free a packet gather list
* @gl: the gather list
*
* Releases the pages of a packet gather list. We do not own the last
* page on the list and do not free it.
*/
static void t4_pktgl_free(const struct pkt_gl *gl)
{
int n;
const struct page_frag *p;
for (p = gl->frags, n = gl->nfrags - 1; n--; p++)
put_page(p->page);
}
/*
* Process an MPS trace packet. Give it an unused protocol number so it won't
* be delivered to anyone and send it to the stack for capture.
*/
static noinline int handle_trace_pkt(struct adapter *adap,
const struct pkt_gl *gl)
{
struct sk_buff *skb;
struct cpl_trace_pkt *p;
skb = cxgb4_pktgl_to_skb(gl, RX_PULL_LEN, RX_PULL_LEN);
if (unlikely(!skb)) {
t4_pktgl_free(gl);
return 0;
}
p = (struct cpl_trace_pkt *)skb->data;
__skb_pull(skb, sizeof(*p));
skb_reset_mac_header(skb);
skb->protocol = htons(0xffff);
skb->dev = adap->port[0];
netif_receive_skb(skb);
return 0;
}
static void do_gro(struct sge_eth_rxq *rxq, const struct pkt_gl *gl,
const struct cpl_rx_pkt *pkt)
{
int ret;
struct sk_buff *skb;
skb = napi_get_frags(&rxq->rspq.napi);
if (unlikely(!skb)) {
t4_pktgl_free(gl);
rxq->stats.rx_drops++;
return;
}
copy_frags(skb, gl, RX_PKT_PAD);
skb->len = gl->tot_len - RX_PKT_PAD;
skb->data_len = skb->len;
skb->truesize += skb->data_len;
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb_record_rx_queue(skb, rxq->rspq.idx);
if (rxq->rspq.netdev->features & NETIF_F_RXHASH)
skb->rxhash = (__force u32)pkt->rsshdr.hash_val;
if (unlikely(pkt->vlan_ex)) {
__vlan_hwaccel_put_tag(skb, ntohs(pkt->vlan));
rxq->stats.vlan_ex++;
}
ret = napi_gro_frags(&rxq->rspq.napi);
if (ret == GRO_HELD)
rxq->stats.lro_pkts++;
else if (ret == GRO_MERGED || ret == GRO_MERGED_FREE)
rxq->stats.lro_merged++;
rxq->stats.pkts++;
rxq->stats.rx_cso++;
}
/**
* t4_ethrx_handler - process an ingress ethernet packet
* @q: the response queue that received the packet
* @rsp: the response queue descriptor holding the RX_PKT message
* @si: the gather list of packet fragments
*
* Process an ingress ethernet packet and deliver it to the stack.
*/
int t4_ethrx_handler(struct sge_rspq *q, const __be64 *rsp,
const struct pkt_gl *si)
{
bool csum_ok;
struct sk_buff *skb;
const struct cpl_rx_pkt *pkt;
struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
if (unlikely(*(u8 *)rsp == CPL_TRACE_PKT))
return handle_trace_pkt(q->adap, si);
pkt = (const struct cpl_rx_pkt *)rsp;
csum_ok = pkt->csum_calc && !pkt->err_vec;
if ((pkt->l2info & htonl(RXF_TCP)) &&
(q->netdev->features & NETIF_F_GRO) && csum_ok && !pkt->ip_frag) {
do_gro(rxq, si, pkt);
return 0;
}
skb = cxgb4_pktgl_to_skb(si, RX_PKT_SKB_LEN, RX_PULL_LEN);
if (unlikely(!skb)) {
t4_pktgl_free(si);
rxq->stats.rx_drops++;
return 0;
}
__skb_pull(skb, RX_PKT_PAD); /* remove ethernet header padding */
skb->protocol = eth_type_trans(skb, q->netdev);
skb_record_rx_queue(skb, q->idx);
if (skb->dev->features & NETIF_F_RXHASH)
skb->rxhash = (__force u32)pkt->rsshdr.hash_val;
rxq->stats.pkts++;
if (csum_ok && (q->netdev->features & NETIF_F_RXCSUM) &&
(pkt->l2info & htonl(RXF_UDP | RXF_TCP))) {
if (!pkt->ip_frag) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
rxq->stats.rx_cso++;
} else if (pkt->l2info & htonl(RXF_IP)) {
__sum16 c = (__force __sum16)pkt->csum;
skb->csum = csum_unfold(c);
skb->ip_summed = CHECKSUM_COMPLETE;
rxq->stats.rx_cso++;
}
} else
skb_checksum_none_assert(skb);
if (unlikely(pkt->vlan_ex)) {
__vlan_hwaccel_put_tag(skb, ntohs(pkt->vlan));
rxq->stats.vlan_ex++;
}
netif_receive_skb(skb);
return 0;
}
/**
* restore_rx_bufs - put back a packet's Rx buffers
* @si: the packet gather list
* @q: the SGE free list
* @frags: number of FL buffers to restore
*
* Puts back on an FL the Rx buffers associated with @si. The buffers
* have already been unmapped and are left unmapped, we mark them so to
* prevent further unmapping attempts.
*
* This function undoes a series of @unmap_rx_buf calls when we find out
* that the current packet can't be processed right away afterall and we
* need to come back to it later. This is a very rare event and there's
* no effort to make this particularly efficient.
*/
static void restore_rx_bufs(const struct pkt_gl *si, struct sge_fl *q,
int frags)
{
struct rx_sw_desc *d;
while (frags--) {
if (q->cidx == 0)
q->cidx = q->size - 1;
else
q->cidx--;
d = &q->sdesc[q->cidx];
d->page = si->frags[frags].page;
d->dma_addr |= RX_UNMAPPED_BUF;
q->avail++;
}
}
/**
* is_new_response - check if a response is newly written
* @r: the response descriptor
* @q: the response queue
*
* Returns true if a response descriptor contains a yet unprocessed
* response.
*/
static inline bool is_new_response(const struct rsp_ctrl *r,
const struct sge_rspq *q)
{
return RSPD_GEN(r->type_gen) == q->gen;
}
/**
* rspq_next - advance to the next entry in a response queue
* @q: the queue
*
* Updates the state of a response queue to advance it to the next entry.
*/
static inline void rspq_next(struct sge_rspq *q)
{
q->cur_desc = (void *)q->cur_desc + q->iqe_len;
if (unlikely(++q->cidx == q->size)) {
q->cidx = 0;
q->gen ^= 1;
q->cur_desc = q->desc;
}
}
/**
* process_responses - process responses from an SGE response queue
* @q: the ingress queue to process
* @budget: how many responses can be processed in this round
*
* Process responses from an SGE response queue up to the supplied budget.
* Responses include received packets as well as control messages from FW
* or HW.
*
* Additionally choose the interrupt holdoff time for the next interrupt
* on this queue. If the system is under memory shortage use a fairly
* long delay to help recovery.
*/
static int process_responses(struct sge_rspq *q, int budget)
{
int ret, rsp_type;
int budget_left = budget;
const struct rsp_ctrl *rc;
struct sge_eth_rxq *rxq = container_of(q, struct sge_eth_rxq, rspq);
while (likely(budget_left)) {
rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
if (!is_new_response(rc, q))
break;
rmb();
rsp_type = RSPD_TYPE(rc->type_gen);
if (likely(rsp_type == RSP_TYPE_FLBUF)) {
struct page_frag *fp;
struct pkt_gl si;
const struct rx_sw_desc *rsd;
u32 len = ntohl(rc->pldbuflen_qid), bufsz, frags;
if (len & RSPD_NEWBUF) {
if (likely(q->offset > 0)) {
free_rx_bufs(q->adap, &rxq->fl, 1);
q->offset = 0;
}
len = RSPD_LEN(len);
}
si.tot_len = len;
/* gather packet fragments */
for (frags = 0, fp = si.frags; ; frags++, fp++) {
rsd = &rxq->fl.sdesc[rxq->fl.cidx];
bufsz = get_buf_size(rsd);
fp->page = rsd->page;
fp->offset = q->offset;
fp->size = min(bufsz, len);
len -= fp->size;
if (!len)
break;
unmap_rx_buf(q->adap, &rxq->fl);
}
/*
* Last buffer remains mapped so explicitly make it
* coherent for CPU access.
*/
dma_sync_single_for_cpu(q->adap->pdev_dev,
get_buf_addr(rsd),
fp->size, DMA_FROM_DEVICE);
si.va = page_address(si.frags[0].page) +
si.frags[0].offset;
prefetch(si.va);
si.nfrags = frags + 1;
ret = q->handler(q, q->cur_desc, &si);
if (likely(ret == 0))
q->offset += ALIGN(fp->size, FL_ALIGN);
else
restore_rx_bufs(&si, &rxq->fl, frags);
} else if (likely(rsp_type == RSP_TYPE_CPL)) {
ret = q->handler(q, q->cur_desc, NULL);
} else {
ret = q->handler(q, (const __be64 *)rc, CXGB4_MSG_AN);
}
if (unlikely(ret)) {
/* couldn't process descriptor, back off for recovery */
q->next_intr_params = QINTR_TIMER_IDX(NOMEM_TMR_IDX);
break;
}
rspq_next(q);
budget_left--;
}
if (q->offset >= 0 && rxq->fl.size - rxq->fl.avail >= 16)
__refill_fl(q->adap, &rxq->fl);
return budget - budget_left;
}
/**
* napi_rx_handler - the NAPI handler for Rx processing
* @napi: the napi instance
* @budget: how many packets we can process in this round
*
* Handler for new data events when using NAPI. This does not need any
* locking or protection from interrupts as data interrupts are off at
* this point and other adapter interrupts do not interfere (the latter
* in not a concern at all with MSI-X as non-data interrupts then have
* a separate handler).
*/
static int napi_rx_handler(struct napi_struct *napi, int budget)
{
unsigned int params;
struct sge_rspq *q = container_of(napi, struct sge_rspq, napi);
int work_done = process_responses(q, budget);
if (likely(work_done < budget)) {
napi_complete(napi);
params = q->next_intr_params;
q->next_intr_params = q->intr_params;
} else
params = QINTR_TIMER_IDX(7);
t4_write_reg(q->adap, MYPF_REG(SGE_PF_GTS), CIDXINC(work_done) |
INGRESSQID((u32)q->cntxt_id) | SEINTARM(params));
return work_done;
}
/*
* The MSI-X interrupt handler for an SGE response queue.
*/
irqreturn_t t4_sge_intr_msix(int irq, void *cookie)
{
struct sge_rspq *q = cookie;
napi_schedule(&q->napi);
return IRQ_HANDLED;
}
/*
* Process the indirect interrupt entries in the interrupt queue and kick off
* NAPI for each queue that has generated an entry.
*/
static unsigned int process_intrq(struct adapter *adap)
{
unsigned int credits;
const struct rsp_ctrl *rc;
struct sge_rspq *q = &adap->sge.intrq;
spin_lock(&adap->sge.intrq_lock);
for (credits = 0; ; credits++) {
rc = (void *)q->cur_desc + (q->iqe_len - sizeof(*rc));
if (!is_new_response(rc, q))
break;
rmb();
if (RSPD_TYPE(rc->type_gen) == RSP_TYPE_INTR) {
unsigned int qid = ntohl(rc->pldbuflen_qid);
qid -= adap->sge.ingr_start;
napi_schedule(&adap->sge.ingr_map[qid]->napi);
}
rspq_next(q);
}
t4_write_reg(adap, MYPF_REG(SGE_PF_GTS), CIDXINC(credits) |
INGRESSQID(q->cntxt_id) | SEINTARM(q->intr_params));
spin_unlock(&adap->sge.intrq_lock);
return credits;
}
/*
* The MSI interrupt handler, which handles data events from SGE response queues
* as well as error and other async events as they all use the same MSI vector.
*/
static irqreturn_t t4_intr_msi(int irq, void *cookie)
{
struct adapter *adap = cookie;
t4_slow_intr_handler(adap);
process_intrq(adap);
return IRQ_HANDLED;
}
/*
* Interrupt handler for legacy INTx interrupts.
* Handles data events from SGE response queues as well as error and other
* async events as they all use the same interrupt line.
*/
static irqreturn_t t4_intr_intx(int irq, void *cookie)
{
struct adapter *adap = cookie;
t4_write_reg(adap, MYPF_REG(PCIE_PF_CLI), 0);
if (t4_slow_intr_handler(adap) | process_intrq(adap))
return IRQ_HANDLED;
return IRQ_NONE; /* probably shared interrupt */
}
/**
* t4_intr_handler - select the top-level interrupt handler
* @adap: the adapter
*
* Selects the top-level interrupt handler based on the type of interrupts
* (MSI-X, MSI, or INTx).
*/
irq_handler_t t4_intr_handler(struct adapter *adap)
{
if (adap->flags & USING_MSIX)
return t4_sge_intr_msix;
if (adap->flags & USING_MSI)
return t4_intr_msi;
return t4_intr_intx;
}
static void sge_rx_timer_cb(unsigned long data)
{
unsigned long m;
unsigned int i, cnt[2];
struct adapter *adap = (struct adapter *)data;
struct sge *s = &adap->sge;
for (i = 0; i < ARRAY_SIZE(s->starving_fl); i++)
for (m = s->starving_fl[i]; m; m &= m - 1) {
struct sge_eth_rxq *rxq;
unsigned int id = __ffs(m) + i * BITS_PER_LONG;
struct sge_fl *fl = s->egr_map[id];
clear_bit(id, s->starving_fl);
smp_mb__after_clear_bit();
if (fl_starving(fl)) {
rxq = container_of(fl, struct sge_eth_rxq, fl);
if (napi_reschedule(&rxq->rspq.napi))
fl->starving++;
else
set_bit(id, s->starving_fl);
}
}
t4_write_reg(adap, SGE_DEBUG_INDEX, 13);
cnt[0] = t4_read_reg(adap, SGE_DEBUG_DATA_HIGH);
cnt[1] = t4_read_reg(adap, SGE_DEBUG_DATA_LOW);
for (i = 0; i < 2; i++)
if (cnt[i] >= s->starve_thres) {
if (s->idma_state[i] || cnt[i] == 0xffffffff)
continue;
s->idma_state[i] = 1;
t4_write_reg(adap, SGE_DEBUG_INDEX, 11);
m = t4_read_reg(adap, SGE_DEBUG_DATA_LOW) >> (i * 16);
dev_warn(adap->pdev_dev,
"SGE idma%u starvation detected for "
"queue %lu\n", i, m & 0xffff);
} else if (s->idma_state[i])
s->idma_state[i] = 0;
mod_timer(&s->rx_timer, jiffies + RX_QCHECK_PERIOD);
}
static void sge_tx_timer_cb(unsigned long data)
{
unsigned long m;
unsigned int i, budget;
struct adapter *adap = (struct adapter *)data;
struct sge *s = &adap->sge;
for (i = 0; i < ARRAY_SIZE(s->txq_maperr); i++)
for (m = s->txq_maperr[i]; m; m &= m - 1) {
unsigned long id = __ffs(m) + i * BITS_PER_LONG;
struct sge_ofld_txq *txq = s->egr_map[id];
clear_bit(id, s->txq_maperr);
tasklet_schedule(&txq->qresume_tsk);
}
budget = MAX_TIMER_TX_RECLAIM;
i = s->ethtxq_rover;
do {
struct sge_eth_txq *q = &s->ethtxq[i];
if (q->q.in_use &&
time_after_eq(jiffies, q->txq->trans_start + HZ / 100) &&
__netif_tx_trylock(q->txq)) {
int avail = reclaimable(&q->q);
if (avail) {
if (avail > budget)
avail = budget;
free_tx_desc(adap, &q->q, avail, true);
q->q.in_use -= avail;
budget -= avail;
}
__netif_tx_unlock(q->txq);
}
if (++i >= s->ethqsets)
i = 0;
} while (budget && i != s->ethtxq_rover);
s->ethtxq_rover = i;
mod_timer(&s->tx_timer, jiffies + (budget ? TX_QCHECK_PERIOD : 2));
}
int t4_sge_alloc_rxq(struct adapter *adap, struct sge_rspq *iq, bool fwevtq,
struct net_device *dev, int intr_idx,
struct sge_fl *fl, rspq_handler_t hnd)
{
int ret, flsz = 0;
struct fw_iq_cmd c;
struct port_info *pi = netdev_priv(dev);
/* Size needs to be multiple of 16, including status entry. */
iq->size = roundup(iq->size, 16);
iq->desc = alloc_ring(adap->pdev_dev, iq->size, iq->iqe_len, 0,
&iq->phys_addr, NULL, 0, NUMA_NO_NODE);
if (!iq->desc)
return -ENOMEM;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_IQ_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_CMD_EXEC |
FW_IQ_CMD_PFN(adap->fn) | FW_IQ_CMD_VFN(0));
c.alloc_to_len16 = htonl(FW_IQ_CMD_ALLOC | FW_IQ_CMD_IQSTART(1) |
FW_LEN16(c));
c.type_to_iqandstindex = htonl(FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
FW_IQ_CMD_IQASYNCH(fwevtq) | FW_IQ_CMD_VIID(pi->viid) |
FW_IQ_CMD_IQANDST(intr_idx < 0) | FW_IQ_CMD_IQANUD(1) |
FW_IQ_CMD_IQANDSTINDEX(intr_idx >= 0 ? intr_idx :
-intr_idx - 1));
c.iqdroprss_to_iqesize = htons(FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
FW_IQ_CMD_IQGTSMODE |
FW_IQ_CMD_IQINTCNTTHRESH(iq->pktcnt_idx) |
FW_IQ_CMD_IQESIZE(ilog2(iq->iqe_len) - 4));
c.iqsize = htons(iq->size);
c.iqaddr = cpu_to_be64(iq->phys_addr);
if (fl) {
fl->size = roundup(fl->size, 8);
fl->desc = alloc_ring(adap->pdev_dev, fl->size, sizeof(__be64),
sizeof(struct rx_sw_desc), &fl->addr,
&fl->sdesc, STAT_LEN, NUMA_NO_NODE);
if (!fl->desc)
goto fl_nomem;
flsz = fl->size / 8 + STAT_LEN / sizeof(struct tx_desc);
c.iqns_to_fl0congen = htonl(FW_IQ_CMD_FL0PACKEN |
FW_IQ_CMD_FL0FETCHRO(1) |
FW_IQ_CMD_FL0DATARO(1) |
FW_IQ_CMD_FL0PADEN);
c.fl0dcaen_to_fl0cidxfthresh = htons(FW_IQ_CMD_FL0FBMIN(2) |
FW_IQ_CMD_FL0FBMAX(3));
c.fl0size = htons(flsz);
c.fl0addr = cpu_to_be64(fl->addr);
}
ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
if (ret)
goto err;
netif_napi_add(dev, &iq->napi, napi_rx_handler, 64);
iq->cur_desc = iq->desc;
iq->cidx = 0;
iq->gen = 1;
iq->next_intr_params = iq->intr_params;
iq->cntxt_id = ntohs(c.iqid);
iq->abs_id = ntohs(c.physiqid);
iq->size--; /* subtract status entry */
iq->adap = adap;
iq->netdev = dev;
iq->handler = hnd;
/* set offset to -1 to distinguish ingress queues without FL */
iq->offset = fl ? 0 : -1;
adap->sge.ingr_map[iq->cntxt_id - adap->sge.ingr_start] = iq;
if (fl) {
fl->cntxt_id = ntohs(c.fl0id);
fl->avail = fl->pend_cred = 0;
fl->pidx = fl->cidx = 0;
fl->alloc_failed = fl->large_alloc_failed = fl->starving = 0;
adap->sge.egr_map[fl->cntxt_id - adap->sge.egr_start] = fl;
refill_fl(adap, fl, fl_cap(fl), GFP_KERNEL);
}
return 0;
fl_nomem:
ret = -ENOMEM;
err:
if (iq->desc) {
dma_free_coherent(adap->pdev_dev, iq->size * iq->iqe_len,
iq->desc, iq->phys_addr);
iq->desc = NULL;
}
if (fl && fl->desc) {
kfree(fl->sdesc);
fl->sdesc = NULL;
dma_free_coherent(adap->pdev_dev, flsz * sizeof(struct tx_desc),
fl->desc, fl->addr);
fl->desc = NULL;
}
return ret;
}
static void init_txq(struct adapter *adap, struct sge_txq *q, unsigned int id)
{
q->in_use = 0;
q->cidx = q->pidx = 0;
q->stops = q->restarts = 0;
q->stat = (void *)&q->desc[q->size];
q->cntxt_id = id;
adap->sge.egr_map[id - adap->sge.egr_start] = q;
}
int t4_sge_alloc_eth_txq(struct adapter *adap, struct sge_eth_txq *txq,
struct net_device *dev, struct netdev_queue *netdevq,
unsigned int iqid)
{
int ret, nentries;
struct fw_eq_eth_cmd c;
struct port_info *pi = netdev_priv(dev);
/* Add status entries */
nentries = txq->q.size + STAT_LEN / sizeof(struct tx_desc);
txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
&txq->q.phys_addr, &txq->q.sdesc, STAT_LEN,
netdev_queue_numa_node_read(netdevq));
if (!txq->q.desc)
return -ENOMEM;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_ETH_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_CMD_EXEC |
FW_EQ_ETH_CMD_PFN(adap->fn) | FW_EQ_ETH_CMD_VFN(0));
c.alloc_to_len16 = htonl(FW_EQ_ETH_CMD_ALLOC |
FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
c.viid_pkd = htonl(FW_EQ_ETH_CMD_VIID(pi->viid));
c.fetchszm_to_iqid = htonl(FW_EQ_ETH_CMD_HOSTFCMODE(2) |
FW_EQ_ETH_CMD_PCIECHN(pi->tx_chan) |
FW_EQ_ETH_CMD_FETCHRO(1) |
FW_EQ_ETH_CMD_IQID(iqid));
c.dcaen_to_eqsize = htonl(FW_EQ_ETH_CMD_FBMIN(2) |
FW_EQ_ETH_CMD_FBMAX(3) |
FW_EQ_ETH_CMD_CIDXFTHRESH(5) |
FW_EQ_ETH_CMD_EQSIZE(nentries));
c.eqaddr = cpu_to_be64(txq->q.phys_addr);
ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
if (ret) {
kfree(txq->q.sdesc);
txq->q.sdesc = NULL;
dma_free_coherent(adap->pdev_dev,
nentries * sizeof(struct tx_desc),
txq->q.desc, txq->q.phys_addr);
txq->q.desc = NULL;
return ret;
}
init_txq(adap, &txq->q, FW_EQ_ETH_CMD_EQID_GET(ntohl(c.eqid_pkd)));
txq->txq = netdevq;
txq->tso = txq->tx_cso = txq->vlan_ins = 0;
txq->mapping_err = 0;
return 0;
}
int t4_sge_alloc_ctrl_txq(struct adapter *adap, struct sge_ctrl_txq *txq,
struct net_device *dev, unsigned int iqid,
unsigned int cmplqid)
{
int ret, nentries;
struct fw_eq_ctrl_cmd c;
struct port_info *pi = netdev_priv(dev);
/* Add status entries */
nentries = txq->q.size + STAT_LEN / sizeof(struct tx_desc);
txq->q.desc = alloc_ring(adap->pdev_dev, nentries,
sizeof(struct tx_desc), 0, &txq->q.phys_addr,
NULL, 0, NUMA_NO_NODE);
if (!txq->q.desc)
return -ENOMEM;
c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_CTRL_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_CMD_EXEC |
FW_EQ_CTRL_CMD_PFN(adap->fn) |
FW_EQ_CTRL_CMD_VFN(0));
c.alloc_to_len16 = htonl(FW_EQ_CTRL_CMD_ALLOC |
FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
c.cmpliqid_eqid = htonl(FW_EQ_CTRL_CMD_CMPLIQID(cmplqid));
c.physeqid_pkd = htonl(0);
c.fetchszm_to_iqid = htonl(FW_EQ_CTRL_CMD_HOSTFCMODE(2) |
FW_EQ_CTRL_CMD_PCIECHN(pi->tx_chan) |
FW_EQ_CTRL_CMD_FETCHRO |
FW_EQ_CTRL_CMD_IQID(iqid));
c.dcaen_to_eqsize = htonl(FW_EQ_CTRL_CMD_FBMIN(2) |
FW_EQ_CTRL_CMD_FBMAX(3) |
FW_EQ_CTRL_CMD_CIDXFTHRESH(5) |
FW_EQ_CTRL_CMD_EQSIZE(nentries));
c.eqaddr = cpu_to_be64(txq->q.phys_addr);
ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
if (ret) {
dma_free_coherent(adap->pdev_dev,
nentries * sizeof(struct tx_desc),
txq->q.desc, txq->q.phys_addr);
txq->q.desc = NULL;
return ret;
}
init_txq(adap, &txq->q, FW_EQ_CTRL_CMD_EQID_GET(ntohl(c.cmpliqid_eqid)));
txq->adap = adap;
skb_queue_head_init(&txq->sendq);
tasklet_init(&txq->qresume_tsk, restart_ctrlq, (unsigned long)txq);
txq->full = 0;
return 0;
}
int t4_sge_alloc_ofld_txq(struct adapter *adap, struct sge_ofld_txq *txq,
struct net_device *dev, unsigned int iqid)
{
int ret, nentries;
struct fw_eq_ofld_cmd c;
struct port_info *pi = netdev_priv(dev);
/* Add status entries */
nentries = txq->q.size + STAT_LEN / sizeof(struct tx_desc);
txq->q.desc = alloc_ring(adap->pdev_dev, txq->q.size,
sizeof(struct tx_desc), sizeof(struct tx_sw_desc),
&txq->q.phys_addr, &txq->q.sdesc, STAT_LEN,
NUMA_NO_NODE);
if (!txq->q.desc)
return -ENOMEM;
memset(&c, 0, sizeof(c));
c.op_to_vfn = htonl(FW_CMD_OP(FW_EQ_OFLD_CMD) | FW_CMD_REQUEST |
FW_CMD_WRITE | FW_CMD_EXEC |
FW_EQ_OFLD_CMD_PFN(adap->fn) |
FW_EQ_OFLD_CMD_VFN(0));
c.alloc_to_len16 = htonl(FW_EQ_OFLD_CMD_ALLOC |
FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
c.fetchszm_to_iqid = htonl(FW_EQ_OFLD_CMD_HOSTFCMODE(2) |
FW_EQ_OFLD_CMD_PCIECHN(pi->tx_chan) |
FW_EQ_OFLD_CMD_FETCHRO(1) |
FW_EQ_OFLD_CMD_IQID(iqid));
c.dcaen_to_eqsize = htonl(FW_EQ_OFLD_CMD_FBMIN(2) |
FW_EQ_OFLD_CMD_FBMAX(3) |
FW_EQ_OFLD_CMD_CIDXFTHRESH(5) |
FW_EQ_OFLD_CMD_EQSIZE(nentries));
c.eqaddr = cpu_to_be64(txq->q.phys_addr);
ret = t4_wr_mbox(adap, adap->fn, &c, sizeof(c), &c);
if (ret) {
kfree(txq->q.sdesc);
txq->q.sdesc = NULL;
dma_free_coherent(adap->pdev_dev,
nentries * sizeof(struct tx_desc),
txq->q.desc, txq->q.phys_addr);
txq->q.desc = NULL;
return ret;
}
init_txq(adap, &txq->q, FW_EQ_OFLD_CMD_EQID_GET(ntohl(c.eqid_pkd)));
txq->adap = adap;
skb_queue_head_init(&txq->sendq);
tasklet_init(&txq->qresume_tsk, restart_ofldq, (unsigned long)txq);
txq->full = 0;
txq->mapping_err = 0;
return 0;
}
static void free_txq(struct adapter *adap, struct sge_txq *q)
{
dma_free_coherent(adap->pdev_dev,
q->size * sizeof(struct tx_desc) + STAT_LEN,
q->desc, q->phys_addr);
q->cntxt_id = 0;
q->sdesc = NULL;
q->desc = NULL;
}
static void free_rspq_fl(struct adapter *adap, struct sge_rspq *rq,
struct sge_fl *fl)
{
unsigned int fl_id = fl ? fl->cntxt_id : 0xffff;
adap->sge.ingr_map[rq->cntxt_id - adap->sge.ingr_start] = NULL;
t4_iq_free(adap, adap->fn, adap->fn, 0, FW_IQ_TYPE_FL_INT_CAP,
rq->cntxt_id, fl_id, 0xffff);
dma_free_coherent(adap->pdev_dev, (rq->size + 1) * rq->iqe_len,
rq->desc, rq->phys_addr);
netif_napi_del(&rq->napi);
rq->netdev = NULL;
rq->cntxt_id = rq->abs_id = 0;
rq->desc = NULL;
if (fl) {
free_rx_bufs(adap, fl, fl->avail);
dma_free_coherent(adap->pdev_dev, fl->size * 8 + STAT_LEN,
fl->desc, fl->addr);
kfree(fl->sdesc);
fl->sdesc = NULL;
fl->cntxt_id = 0;
fl->desc = NULL;
}
}
/**
* t4_free_sge_resources - free SGE resources
* @adap: the adapter
*
* Frees resources used by the SGE queue sets.
*/
void t4_free_sge_resources(struct adapter *adap)
{
int i;
struct sge_eth_rxq *eq = adap->sge.ethrxq;
struct sge_eth_txq *etq = adap->sge.ethtxq;
struct sge_ofld_rxq *oq = adap->sge.ofldrxq;
/* clean up Ethernet Tx/Rx queues */
for (i = 0; i < adap->sge.ethqsets; i++, eq++, etq++) {
if (eq->rspq.desc)
free_rspq_fl(adap, &eq->rspq, &eq->fl);
if (etq->q.desc) {
t4_eth_eq_free(adap, adap->fn, adap->fn, 0,
etq->q.cntxt_id);
free_tx_desc(adap, &etq->q, etq->q.in_use, true);
kfree(etq->q.sdesc);
free_txq(adap, &etq->q);
}
}
/* clean up RDMA and iSCSI Rx queues */
for (i = 0; i < adap->sge.ofldqsets; i++, oq++) {
if (oq->rspq.desc)
free_rspq_fl(adap, &oq->rspq, &oq->fl);
}
for (i = 0, oq = adap->sge.rdmarxq; i < adap->sge.rdmaqs; i++, oq++) {
if (oq->rspq.desc)
free_rspq_fl(adap, &oq->rspq, &oq->fl);
}
/* clean up offload Tx queues */
for (i = 0; i < ARRAY_SIZE(adap->sge.ofldtxq); i++) {
struct sge_ofld_txq *q = &adap->sge.ofldtxq[i];
if (q->q.desc) {
tasklet_kill(&q->qresume_tsk);
t4_ofld_eq_free(adap, adap->fn, adap->fn, 0,
q->q.cntxt_id);
free_tx_desc(adap, &q->q, q->q.in_use, false);
kfree(q->q.sdesc);
__skb_queue_purge(&q->sendq);
free_txq(adap, &q->q);
}
}
/* clean up control Tx queues */
for (i = 0; i < ARRAY_SIZE(adap->sge.ctrlq); i++) {
struct sge_ctrl_txq *cq = &adap->sge.ctrlq[i];
if (cq->q.desc) {
tasklet_kill(&cq->qresume_tsk);
t4_ctrl_eq_free(adap, adap->fn, adap->fn, 0,
cq->q.cntxt_id);
__skb_queue_purge(&cq->sendq);
free_txq(adap, &cq->q);
}
}
if (adap->sge.fw_evtq.desc)
free_rspq_fl(adap, &adap->sge.fw_evtq, NULL);
if (adap->sge.intrq.desc)
free_rspq_fl(adap, &adap->sge.intrq, NULL);
/* clear the reverse egress queue map */
memset(adap->sge.egr_map, 0, sizeof(adap->sge.egr_map));
}
void t4_sge_start(struct adapter *adap)
{
adap->sge.ethtxq_rover = 0;
mod_timer(&adap->sge.rx_timer, jiffies + RX_QCHECK_PERIOD);
mod_timer(&adap->sge.tx_timer, jiffies + TX_QCHECK_PERIOD);
}
/**
* t4_sge_stop - disable SGE operation
* @adap: the adapter
*
* Stop tasklets and timers associated with the DMA engine. Note that
* this is effective only if measures have been taken to disable any HW
* events that may restart them.
*/
void t4_sge_stop(struct adapter *adap)
{
int i;
struct sge *s = &adap->sge;
if (in_interrupt()) /* actions below require waiting */
return;
if (s->rx_timer.function)
del_timer_sync(&s->rx_timer);
if (s->tx_timer.function)
del_timer_sync(&s->tx_timer);
for (i = 0; i < ARRAY_SIZE(s->ofldtxq); i++) {
struct sge_ofld_txq *q = &s->ofldtxq[i];
if (q->q.desc)
tasklet_kill(&q->qresume_tsk);
}
for (i = 0; i < ARRAY_SIZE(s->ctrlq); i++) {
struct sge_ctrl_txq *cq = &s->ctrlq[i];
if (cq->q.desc)
tasklet_kill(&cq->qresume_tsk);
}
}
/**
* t4_sge_init - initialize SGE
* @adap: the adapter
*
* Performs SGE initialization needed every time after a chip reset.
* We do not initialize any of the queues here, instead the driver
* top-level must request them individually.
*/
void t4_sge_init(struct adapter *adap)
{
unsigned int i, v;
struct sge *s = &adap->sge;
unsigned int fl_align_log = ilog2(FL_ALIGN);
t4_set_reg_field(adap, SGE_CONTROL, PKTSHIFT_MASK |
INGPADBOUNDARY_MASK | EGRSTATUSPAGESIZE,
INGPADBOUNDARY(fl_align_log - 5) | PKTSHIFT(2) |
RXPKTCPLMODE |
(STAT_LEN == 128 ? EGRSTATUSPAGESIZE : 0));
for (i = v = 0; i < 32; i += 4)
v |= (PAGE_SHIFT - 10) << i;
t4_write_reg(adap, SGE_HOST_PAGE_SIZE, v);
t4_write_reg(adap, SGE_FL_BUFFER_SIZE0, PAGE_SIZE);
#if FL_PG_ORDER > 0
t4_write_reg(adap, SGE_FL_BUFFER_SIZE1, PAGE_SIZE << FL_PG_ORDER);
#endif
t4_write_reg(adap, SGE_INGRESS_RX_THRESHOLD,
THRESHOLD_0(s->counter_val[0]) |
THRESHOLD_1(s->counter_val[1]) |
THRESHOLD_2(s->counter_val[2]) |
THRESHOLD_3(s->counter_val[3]));
t4_write_reg(adap, SGE_TIMER_VALUE_0_AND_1,
TIMERVALUE0(us_to_core_ticks(adap, s->timer_val[0])) |
TIMERVALUE1(us_to_core_ticks(adap, s->timer_val[1])));
t4_write_reg(adap, SGE_TIMER_VALUE_2_AND_3,
TIMERVALUE0(us_to_core_ticks(adap, s->timer_val[2])) |
TIMERVALUE1(us_to_core_ticks(adap, s->timer_val[3])));
t4_write_reg(adap, SGE_TIMER_VALUE_4_AND_5,
TIMERVALUE0(us_to_core_ticks(adap, s->timer_val[4])) |
TIMERVALUE1(us_to_core_ticks(adap, s->timer_val[5])));
setup_timer(&s->rx_timer, sge_rx_timer_cb, (unsigned long)adap);
setup_timer(&s->tx_timer, sge_tx_timer_cb, (unsigned long)adap);
s->starve_thres = core_ticks_per_usec(adap) * 1000000; /* 1 s */
s->idma_state[0] = s->idma_state[1] = 0;
spin_lock_init(&s->intrq_lock);
}
| gpl-2.0 |
nmenon/ti-linux-kernel-nm | drivers/media/common/siano/smsdvb.c | 5148 | 29498 | /****************************************************************
Siano Mobile Silicon, Inc.
MDTV receiver kernel modules.
Copyright (C) 2006-2008, Uri Shkolnik
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 <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "smscoreapi.h"
#include "smsendian.h"
#include "sms-cards.h"
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
struct smsdvb_client_t {
struct list_head entry;
struct smscore_device_t *coredev;
struct smscore_client_t *smsclient;
struct dvb_adapter adapter;
struct dvb_demux demux;
struct dmxdev dmxdev;
struct dvb_frontend frontend;
fe_status_t fe_status;
struct completion tune_done;
struct SMSHOSTLIB_STATISTICS_DVB_S sms_stat_dvb;
int event_fe_state;
int event_unc_state;
};
static struct list_head g_smsdvb_clients;
static struct mutex g_smsdvb_clientslock;
static int sms_dbg;
module_param_named(debug, sms_dbg, int, 0644);
MODULE_PARM_DESC(debug, "set debug level (info=1, adv=2 (or-able))");
/* Events that may come from DVB v3 adapter */
static void sms_board_dvb3_event(struct smsdvb_client_t *client,
enum SMS_DVB3_EVENTS event) {
struct smscore_device_t *coredev = client->coredev;
switch (event) {
case DVB3_EVENT_INIT:
sms_debug("DVB3_EVENT_INIT");
sms_board_event(coredev, BOARD_EVENT_BIND);
break;
case DVB3_EVENT_SLEEP:
sms_debug("DVB3_EVENT_SLEEP");
sms_board_event(coredev, BOARD_EVENT_POWER_SUSPEND);
break;
case DVB3_EVENT_HOTPLUG:
sms_debug("DVB3_EVENT_HOTPLUG");
sms_board_event(coredev, BOARD_EVENT_POWER_INIT);
break;
case DVB3_EVENT_FE_LOCK:
if (client->event_fe_state != DVB3_EVENT_FE_LOCK) {
client->event_fe_state = DVB3_EVENT_FE_LOCK;
sms_debug("DVB3_EVENT_FE_LOCK");
sms_board_event(coredev, BOARD_EVENT_FE_LOCK);
}
break;
case DVB3_EVENT_FE_UNLOCK:
if (client->event_fe_state != DVB3_EVENT_FE_UNLOCK) {
client->event_fe_state = DVB3_EVENT_FE_UNLOCK;
sms_debug("DVB3_EVENT_FE_UNLOCK");
sms_board_event(coredev, BOARD_EVENT_FE_UNLOCK);
}
break;
case DVB3_EVENT_UNC_OK:
if (client->event_unc_state != DVB3_EVENT_UNC_OK) {
client->event_unc_state = DVB3_EVENT_UNC_OK;
sms_debug("DVB3_EVENT_UNC_OK");
sms_board_event(coredev, BOARD_EVENT_MULTIPLEX_OK);
}
break;
case DVB3_EVENT_UNC_ERR:
if (client->event_unc_state != DVB3_EVENT_UNC_ERR) {
client->event_unc_state = DVB3_EVENT_UNC_ERR;
sms_debug("DVB3_EVENT_UNC_ERR");
sms_board_event(coredev, BOARD_EVENT_MULTIPLEX_ERRORS);
}
break;
default:
sms_err("Unknown dvb3 api event");
break;
}
}
static void smsdvb_update_dvb_stats(struct RECEPTION_STATISTICS_S *pReceptionData,
struct SMSHOSTLIB_STATISTICS_ST *p)
{
if (sms_dbg & 2) {
printk(KERN_DEBUG "Reserved = %d", p->Reserved);
printk(KERN_DEBUG "IsRfLocked = %d", p->IsRfLocked);
printk(KERN_DEBUG "IsDemodLocked = %d", p->IsDemodLocked);
printk(KERN_DEBUG "IsExternalLNAOn = %d", p->IsExternalLNAOn);
printk(KERN_DEBUG "SNR = %d", p->SNR);
printk(KERN_DEBUG "BER = %d", p->BER);
printk(KERN_DEBUG "FIB_CRC = %d", p->FIB_CRC);
printk(KERN_DEBUG "TS_PER = %d", p->TS_PER);
printk(KERN_DEBUG "MFER = %d", p->MFER);
printk(KERN_DEBUG "RSSI = %d", p->RSSI);
printk(KERN_DEBUG "InBandPwr = %d", p->InBandPwr);
printk(KERN_DEBUG "CarrierOffset = %d", p->CarrierOffset);
printk(KERN_DEBUG "Frequency = %d", p->Frequency);
printk(KERN_DEBUG "Bandwidth = %d", p->Bandwidth);
printk(KERN_DEBUG "TransmissionMode = %d", p->TransmissionMode);
printk(KERN_DEBUG "ModemState = %d", p->ModemState);
printk(KERN_DEBUG "GuardInterval = %d", p->GuardInterval);
printk(KERN_DEBUG "CodeRate = %d", p->CodeRate);
printk(KERN_DEBUG "LPCodeRate = %d", p->LPCodeRate);
printk(KERN_DEBUG "Hierarchy = %d", p->Hierarchy);
printk(KERN_DEBUG "Constellation = %d", p->Constellation);
printk(KERN_DEBUG "BurstSize = %d", p->BurstSize);
printk(KERN_DEBUG "BurstDuration = %d", p->BurstDuration);
printk(KERN_DEBUG "BurstCycleTime = %d", p->BurstCycleTime);
printk(KERN_DEBUG "CalculatedBurstCycleTime = %d", p->CalculatedBurstCycleTime);
printk(KERN_DEBUG "NumOfRows = %d", p->NumOfRows);
printk(KERN_DEBUG "NumOfPaddCols = %d", p->NumOfPaddCols);
printk(KERN_DEBUG "NumOfPunctCols = %d", p->NumOfPunctCols);
printk(KERN_DEBUG "ErrorTSPackets = %d", p->ErrorTSPackets);
printk(KERN_DEBUG "TotalTSPackets = %d", p->TotalTSPackets);
printk(KERN_DEBUG "NumOfValidMpeTlbs = %d", p->NumOfValidMpeTlbs);
printk(KERN_DEBUG "NumOfInvalidMpeTlbs = %d", p->NumOfInvalidMpeTlbs);
printk(KERN_DEBUG "NumOfCorrectedMpeTlbs = %d", p->NumOfCorrectedMpeTlbs);
printk(KERN_DEBUG "BERErrorCount = %d", p->BERErrorCount);
printk(KERN_DEBUG "BERBitCount = %d", p->BERBitCount);
printk(KERN_DEBUG "SmsToHostTxErrors = %d", p->SmsToHostTxErrors);
printk(KERN_DEBUG "PreBER = %d", p->PreBER);
printk(KERN_DEBUG "CellId = %d", p->CellId);
printk(KERN_DEBUG "DvbhSrvIndHP = %d", p->DvbhSrvIndHP);
printk(KERN_DEBUG "DvbhSrvIndLP = %d", p->DvbhSrvIndLP);
printk(KERN_DEBUG "NumMPEReceived = %d", p->NumMPEReceived);
}
pReceptionData->IsDemodLocked = p->IsDemodLocked;
pReceptionData->SNR = p->SNR;
pReceptionData->BER = p->BER;
pReceptionData->BERErrorCount = p->BERErrorCount;
pReceptionData->InBandPwr = p->InBandPwr;
pReceptionData->ErrorTSPackets = p->ErrorTSPackets;
};
static void smsdvb_update_isdbt_stats(struct RECEPTION_STATISTICS_S *pReceptionData,
struct SMSHOSTLIB_STATISTICS_ISDBT_ST *p)
{
int i;
if (sms_dbg & 2) {
printk(KERN_DEBUG "IsRfLocked = %d", p->IsRfLocked);
printk(KERN_DEBUG "IsDemodLocked = %d", p->IsDemodLocked);
printk(KERN_DEBUG "IsExternalLNAOn = %d", p->IsExternalLNAOn);
printk(KERN_DEBUG "SNR = %d", p->SNR);
printk(KERN_DEBUG "RSSI = %d", p->RSSI);
printk(KERN_DEBUG "InBandPwr = %d", p->InBandPwr);
printk(KERN_DEBUG "CarrierOffset = %d", p->CarrierOffset);
printk(KERN_DEBUG "Frequency = %d", p->Frequency);
printk(KERN_DEBUG "Bandwidth = %d", p->Bandwidth);
printk(KERN_DEBUG "TransmissionMode = %d", p->TransmissionMode);
printk(KERN_DEBUG "ModemState = %d", p->ModemState);
printk(KERN_DEBUG "GuardInterval = %d", p->GuardInterval);
printk(KERN_DEBUG "SystemType = %d", p->SystemType);
printk(KERN_DEBUG "PartialReception = %d", p->PartialReception);
printk(KERN_DEBUG "NumOfLayers = %d", p->NumOfLayers);
printk(KERN_DEBUG "SmsToHostTxErrors = %d", p->SmsToHostTxErrors);
for (i = 0; i < 3; i++) {
printk(KERN_DEBUG "%d: CodeRate = %d", i, p->LayerInfo[i].CodeRate);
printk(KERN_DEBUG "%d: Constellation = %d", i, p->LayerInfo[i].Constellation);
printk(KERN_DEBUG "%d: BER = %d", i, p->LayerInfo[i].BER);
printk(KERN_DEBUG "%d: BERErrorCount = %d", i, p->LayerInfo[i].BERErrorCount);
printk(KERN_DEBUG "%d: BERBitCount = %d", i, p->LayerInfo[i].BERBitCount);
printk(KERN_DEBUG "%d: PreBER = %d", i, p->LayerInfo[i].PreBER);
printk(KERN_DEBUG "%d: TS_PER = %d", i, p->LayerInfo[i].TS_PER);
printk(KERN_DEBUG "%d: ErrorTSPackets = %d", i, p->LayerInfo[i].ErrorTSPackets);
printk(KERN_DEBUG "%d: TotalTSPackets = %d", i, p->LayerInfo[i].TotalTSPackets);
printk(KERN_DEBUG "%d: TILdepthI = %d", i, p->LayerInfo[i].TILdepthI);
printk(KERN_DEBUG "%d: NumberOfSegments = %d", i, p->LayerInfo[i].NumberOfSegments);
printk(KERN_DEBUG "%d: TMCCErrors = %d", i, p->LayerInfo[i].TMCCErrors);
}
}
pReceptionData->IsDemodLocked = p->IsDemodLocked;
pReceptionData->SNR = p->SNR;
pReceptionData->InBandPwr = p->InBandPwr;
pReceptionData->ErrorTSPackets = 0;
pReceptionData->BER = 0;
pReceptionData->BERErrorCount = 0;
for (i = 0; i < 3; i++) {
pReceptionData->BER += p->LayerInfo[i].BER;
pReceptionData->BERErrorCount += p->LayerInfo[i].BERErrorCount;
pReceptionData->ErrorTSPackets += p->LayerInfo[i].ErrorTSPackets;
}
}
static int smsdvb_onresponse(void *context, struct smscore_buffer_t *cb)
{
struct smsdvb_client_t *client = (struct smsdvb_client_t *) context;
struct SmsMsgHdr_ST *phdr = (struct SmsMsgHdr_ST *) (((u8 *) cb->p)
+ cb->offset);
u32 *pMsgData = (u32 *) phdr + 1;
/*u32 MsgDataLen = phdr->msgLength - sizeof(struct SmsMsgHdr_ST);*/
bool is_status_update = false;
smsendian_handle_rx_message((struct SmsMsgData_ST *) phdr);
switch (phdr->msgType) {
case MSG_SMS_DVBT_BDA_DATA:
dvb_dmx_swfilter(&client->demux, (u8 *)(phdr + 1),
cb->size - sizeof(struct SmsMsgHdr_ST));
break;
case MSG_SMS_RF_TUNE_RES:
case MSG_SMS_ISDBT_TUNE_RES:
complete(&client->tune_done);
break;
case MSG_SMS_SIGNAL_DETECTED_IND:
sms_info("MSG_SMS_SIGNAL_DETECTED_IND");
client->sms_stat_dvb.TransmissionData.IsDemodLocked = true;
is_status_update = true;
break;
case MSG_SMS_NO_SIGNAL_IND:
sms_info("MSG_SMS_NO_SIGNAL_IND");
client->sms_stat_dvb.TransmissionData.IsDemodLocked = false;
is_status_update = true;
break;
case MSG_SMS_TRANSMISSION_IND: {
sms_info("MSG_SMS_TRANSMISSION_IND");
pMsgData++;
memcpy(&client->sms_stat_dvb.TransmissionData, pMsgData,
sizeof(struct TRANSMISSION_STATISTICS_S));
/* Mo need to correct guard interval
* (as opposed to old statistics message).
*/
CORRECT_STAT_BANDWIDTH(client->sms_stat_dvb.TransmissionData);
CORRECT_STAT_TRANSMISSON_MODE(
client->sms_stat_dvb.TransmissionData);
is_status_update = true;
break;
}
case MSG_SMS_HO_PER_SLICES_IND: {
struct RECEPTION_STATISTICS_S *pReceptionData =
&client->sms_stat_dvb.ReceptionData;
struct SRVM_SIGNAL_STATUS_S SignalStatusData;
/*sms_info("MSG_SMS_HO_PER_SLICES_IND");*/
pMsgData++;
SignalStatusData.result = pMsgData[0];
SignalStatusData.snr = pMsgData[1];
SignalStatusData.inBandPower = (s32) pMsgData[2];
SignalStatusData.tsPackets = pMsgData[3];
SignalStatusData.etsPackets = pMsgData[4];
SignalStatusData.constellation = pMsgData[5];
SignalStatusData.hpCode = pMsgData[6];
SignalStatusData.tpsSrvIndLP = pMsgData[7] & 0x03;
SignalStatusData.tpsSrvIndHP = pMsgData[8] & 0x03;
SignalStatusData.cellId = pMsgData[9] & 0xFFFF;
SignalStatusData.reason = pMsgData[10];
SignalStatusData.requestId = pMsgData[11];
pReceptionData->IsRfLocked = pMsgData[16];
pReceptionData->IsDemodLocked = pMsgData[17];
pReceptionData->ModemState = pMsgData[12];
pReceptionData->SNR = pMsgData[1];
pReceptionData->BER = pMsgData[13];
pReceptionData->RSSI = pMsgData[14];
CORRECT_STAT_RSSI(client->sms_stat_dvb.ReceptionData);
pReceptionData->InBandPwr = (s32) pMsgData[2];
pReceptionData->CarrierOffset = (s32) pMsgData[15];
pReceptionData->TotalTSPackets = pMsgData[3];
pReceptionData->ErrorTSPackets = pMsgData[4];
/* TS PER */
if ((SignalStatusData.tsPackets + SignalStatusData.etsPackets)
> 0) {
pReceptionData->TS_PER = (SignalStatusData.etsPackets
* 100) / (SignalStatusData.tsPackets
+ SignalStatusData.etsPackets);
} else {
pReceptionData->TS_PER = 0;
}
pReceptionData->BERBitCount = pMsgData[18];
pReceptionData->BERErrorCount = pMsgData[19];
pReceptionData->MRC_SNR = pMsgData[20];
pReceptionData->MRC_InBandPwr = pMsgData[21];
pReceptionData->MRC_RSSI = pMsgData[22];
is_status_update = true;
break;
}
case MSG_SMS_GET_STATISTICS_RES: {
union {
struct SMSHOSTLIB_STATISTICS_ISDBT_ST isdbt;
struct SmsMsgStatisticsInfo_ST dvb;
} *p = (void *) (phdr + 1);
struct RECEPTION_STATISTICS_S *pReceptionData =
&client->sms_stat_dvb.ReceptionData;
sms_info("MSG_SMS_GET_STATISTICS_RES");
is_status_update = true;
switch (smscore_get_device_mode(client->coredev)) {
case DEVICE_MODE_ISDBT:
case DEVICE_MODE_ISDBT_BDA:
smsdvb_update_isdbt_stats(pReceptionData, &p->isdbt);
break;
default:
smsdvb_update_dvb_stats(pReceptionData, &p->dvb.Stat);
}
if (!pReceptionData->IsDemodLocked) {
pReceptionData->SNR = 0;
pReceptionData->BER = 0;
pReceptionData->BERErrorCount = 0;
pReceptionData->InBandPwr = 0;
pReceptionData->ErrorTSPackets = 0;
}
complete(&client->tune_done);
break;
}
default:
sms_info("Unhandled message %d", phdr->msgType);
}
smscore_putbuffer(client->coredev, cb);
if (is_status_update) {
if (client->sms_stat_dvb.ReceptionData.IsDemodLocked) {
client->fe_status = FE_HAS_SIGNAL | FE_HAS_CARRIER
| FE_HAS_VITERBI | FE_HAS_SYNC | FE_HAS_LOCK;
sms_board_dvb3_event(client, DVB3_EVENT_FE_LOCK);
if (client->sms_stat_dvb.ReceptionData.ErrorTSPackets
== 0)
sms_board_dvb3_event(client, DVB3_EVENT_UNC_OK);
else
sms_board_dvb3_event(client,
DVB3_EVENT_UNC_ERR);
} else {
if (client->sms_stat_dvb.ReceptionData.IsRfLocked)
client->fe_status = FE_HAS_SIGNAL | FE_HAS_CARRIER;
else
client->fe_status = 0;
sms_board_dvb3_event(client, DVB3_EVENT_FE_UNLOCK);
}
}
return 0;
}
static void smsdvb_unregister_client(struct smsdvb_client_t *client)
{
/* must be called under clientslock */
list_del(&client->entry);
smscore_unregister_client(client->smsclient);
dvb_unregister_frontend(&client->frontend);
dvb_dmxdev_release(&client->dmxdev);
dvb_dmx_release(&client->demux);
dvb_unregister_adapter(&client->adapter);
kfree(client);
}
static void smsdvb_onremove(void *context)
{
kmutex_lock(&g_smsdvb_clientslock);
smsdvb_unregister_client((struct smsdvb_client_t *) context);
kmutex_unlock(&g_smsdvb_clientslock);
}
static int smsdvb_start_feed(struct dvb_demux_feed *feed)
{
struct smsdvb_client_t *client =
container_of(feed->demux, struct smsdvb_client_t, demux);
struct SmsMsgData_ST PidMsg;
sms_debug("add pid %d(%x)",
feed->pid, feed->pid);
PidMsg.xMsgHeader.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
PidMsg.xMsgHeader.msgDstId = HIF_TASK;
PidMsg.xMsgHeader.msgFlags = 0;
PidMsg.xMsgHeader.msgType = MSG_SMS_ADD_PID_FILTER_REQ;
PidMsg.xMsgHeader.msgLength = sizeof(PidMsg);
PidMsg.msgData[0] = feed->pid;
smsendian_handle_tx_message((struct SmsMsgHdr_ST *)&PidMsg);
return smsclient_sendrequest(client->smsclient,
&PidMsg, sizeof(PidMsg));
}
static int smsdvb_stop_feed(struct dvb_demux_feed *feed)
{
struct smsdvb_client_t *client =
container_of(feed->demux, struct smsdvb_client_t, demux);
struct SmsMsgData_ST PidMsg;
sms_debug("remove pid %d(%x)",
feed->pid, feed->pid);
PidMsg.xMsgHeader.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
PidMsg.xMsgHeader.msgDstId = HIF_TASK;
PidMsg.xMsgHeader.msgFlags = 0;
PidMsg.xMsgHeader.msgType = MSG_SMS_REMOVE_PID_FILTER_REQ;
PidMsg.xMsgHeader.msgLength = sizeof(PidMsg);
PidMsg.msgData[0] = feed->pid;
smsendian_handle_tx_message((struct SmsMsgHdr_ST *)&PidMsg);
return smsclient_sendrequest(client->smsclient,
&PidMsg, sizeof(PidMsg));
}
static int smsdvb_sendrequest_and_wait(struct smsdvb_client_t *client,
void *buffer, size_t size,
struct completion *completion)
{
int rc;
smsendian_handle_tx_message((struct SmsMsgHdr_ST *)buffer);
rc = smsclient_sendrequest(client->smsclient, buffer, size);
if (rc < 0)
return rc;
return wait_for_completion_timeout(completion,
msecs_to_jiffies(2000)) ?
0 : -ETIME;
}
static int smsdvb_send_statistics_request(struct smsdvb_client_t *client)
{
int rc;
struct SmsMsgHdr_ST Msg = { MSG_SMS_GET_STATISTICS_REQ,
DVBT_BDA_CONTROL_MSG_ID,
HIF_TASK,
sizeof(struct SmsMsgHdr_ST), 0 };
rc = smsdvb_sendrequest_and_wait(client, &Msg, sizeof(Msg),
&client->tune_done);
return rc;
}
static inline int led_feedback(struct smsdvb_client_t *client)
{
if (client->fe_status & FE_HAS_LOCK)
return sms_board_led_feedback(client->coredev,
(client->sms_stat_dvb.ReceptionData.BER
== 0) ? SMS_LED_HI : SMS_LED_LO);
else
return sms_board_led_feedback(client->coredev, SMS_LED_OFF);
}
static int smsdvb_read_status(struct dvb_frontend *fe, fe_status_t *stat)
{
int rc;
struct smsdvb_client_t *client;
client = container_of(fe, struct smsdvb_client_t, frontend);
rc = smsdvb_send_statistics_request(client);
*stat = client->fe_status;
led_feedback(client);
return rc;
}
static int smsdvb_read_ber(struct dvb_frontend *fe, u32 *ber)
{
int rc;
struct smsdvb_client_t *client;
client = container_of(fe, struct smsdvb_client_t, frontend);
rc = smsdvb_send_statistics_request(client);
*ber = client->sms_stat_dvb.ReceptionData.BER;
led_feedback(client);
return rc;
}
static int smsdvb_read_signal_strength(struct dvb_frontend *fe, u16 *strength)
{
int rc;
struct smsdvb_client_t *client;
client = container_of(fe, struct smsdvb_client_t, frontend);
rc = smsdvb_send_statistics_request(client);
if (client->sms_stat_dvb.ReceptionData.InBandPwr < -95)
*strength = 0;
else if (client->sms_stat_dvb.ReceptionData.InBandPwr > -29)
*strength = 100;
else
*strength =
(client->sms_stat_dvb.ReceptionData.InBandPwr
+ 95) * 3 / 2;
led_feedback(client);
return rc;
}
static int smsdvb_read_snr(struct dvb_frontend *fe, u16 *snr)
{
int rc;
struct smsdvb_client_t *client;
client = container_of(fe, struct smsdvb_client_t, frontend);
rc = smsdvb_send_statistics_request(client);
*snr = client->sms_stat_dvb.ReceptionData.SNR;
led_feedback(client);
return rc;
}
static int smsdvb_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
int rc;
struct smsdvb_client_t *client;
client = container_of(fe, struct smsdvb_client_t, frontend);
rc = smsdvb_send_statistics_request(client);
*ucblocks = client->sms_stat_dvb.ReceptionData.ErrorTSPackets;
led_feedback(client);
return rc;
}
static int smsdvb_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *tune)
{
sms_debug("");
tune->min_delay_ms = 400;
tune->step_size = 250000;
tune->max_drift = 0;
return 0;
}
static int smsdvb_dvbt_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct smsdvb_client_t *client =
container_of(fe, struct smsdvb_client_t, frontend);
struct {
struct SmsMsgHdr_ST Msg;
u32 Data[3];
} Msg;
int ret;
client->fe_status = FE_HAS_SIGNAL;
client->event_fe_state = -1;
client->event_unc_state = -1;
fe->dtv_property_cache.delivery_system = SYS_DVBT;
Msg.Msg.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
Msg.Msg.msgDstId = HIF_TASK;
Msg.Msg.msgFlags = 0;
Msg.Msg.msgType = MSG_SMS_RF_TUNE_REQ;
Msg.Msg.msgLength = sizeof(Msg);
Msg.Data[0] = c->frequency;
Msg.Data[2] = 12000000;
sms_info("%s: freq %d band %d", __func__, c->frequency,
c->bandwidth_hz);
switch (c->bandwidth_hz / 1000000) {
case 8:
Msg.Data[1] = BW_8_MHZ;
break;
case 7:
Msg.Data[1] = BW_7_MHZ;
break;
case 6:
Msg.Data[1] = BW_6_MHZ;
break;
case 0:
return -EOPNOTSUPP;
default:
return -EINVAL;
}
/* Disable LNA, if any. An error is returned if no LNA is present */
ret = sms_board_lna_control(client->coredev, 0);
if (ret == 0) {
fe_status_t status;
/* tune with LNA off at first */
ret = smsdvb_sendrequest_and_wait(client, &Msg, sizeof(Msg),
&client->tune_done);
smsdvb_read_status(fe, &status);
if (status & FE_HAS_LOCK)
return ret;
/* previous tune didn't lock - enable LNA and tune again */
sms_board_lna_control(client->coredev, 1);
}
return smsdvb_sendrequest_and_wait(client, &Msg, sizeof(Msg),
&client->tune_done);
}
static int smsdvb_isdbt_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct smsdvb_client_t *client =
container_of(fe, struct smsdvb_client_t, frontend);
struct {
struct SmsMsgHdr_ST Msg;
u32 Data[4];
} Msg;
fe->dtv_property_cache.delivery_system = SYS_ISDBT;
Msg.Msg.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
Msg.Msg.msgDstId = HIF_TASK;
Msg.Msg.msgFlags = 0;
Msg.Msg.msgType = MSG_SMS_ISDBT_TUNE_REQ;
Msg.Msg.msgLength = sizeof(Msg);
if (c->isdbt_sb_segment_idx == -1)
c->isdbt_sb_segment_idx = 0;
switch (c->isdbt_sb_segment_count) {
case 3:
Msg.Data[1] = BW_ISDBT_3SEG;
break;
case 1:
Msg.Data[1] = BW_ISDBT_1SEG;
break;
case 0: /* AUTO */
switch (c->bandwidth_hz / 1000000) {
case 8:
case 7:
c->isdbt_sb_segment_count = 3;
Msg.Data[1] = BW_ISDBT_3SEG;
break;
case 6:
c->isdbt_sb_segment_count = 1;
Msg.Data[1] = BW_ISDBT_1SEG;
break;
default: /* Assumes 6 MHZ bw */
c->isdbt_sb_segment_count = 1;
c->bandwidth_hz = 6000;
Msg.Data[1] = BW_ISDBT_1SEG;
break;
}
break;
default:
sms_info("Segment count %d not supported", c->isdbt_sb_segment_count);
return -EINVAL;
}
Msg.Data[0] = c->frequency;
Msg.Data[2] = 12000000;
Msg.Data[3] = c->isdbt_sb_segment_idx;
sms_info("%s: freq %d segwidth %d segindex %d\n", __func__,
c->frequency, c->isdbt_sb_segment_count,
c->isdbt_sb_segment_idx);
return smsdvb_sendrequest_and_wait(client, &Msg, sizeof(Msg),
&client->tune_done);
}
static int smsdvb_set_frontend(struct dvb_frontend *fe)
{
struct smsdvb_client_t *client =
container_of(fe, struct smsdvb_client_t, frontend);
struct smscore_device_t *coredev = client->coredev;
switch (smscore_get_device_mode(coredev)) {
case DEVICE_MODE_DVBT:
case DEVICE_MODE_DVBT_BDA:
return smsdvb_dvbt_set_frontend(fe);
case DEVICE_MODE_ISDBT:
case DEVICE_MODE_ISDBT_BDA:
return smsdvb_isdbt_set_frontend(fe);
default:
return -EINVAL;
}
}
static int smsdvb_get_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *fep = &fe->dtv_property_cache;
struct smsdvb_client_t *client =
container_of(fe, struct smsdvb_client_t, frontend);
struct smscore_device_t *coredev = client->coredev;
struct TRANSMISSION_STATISTICS_S *td =
&client->sms_stat_dvb.TransmissionData;
switch (smscore_get_device_mode(coredev)) {
case DEVICE_MODE_DVBT:
case DEVICE_MODE_DVBT_BDA:
fep->frequency = td->Frequency;
switch (td->Bandwidth) {
case 6:
fep->bandwidth_hz = 6000000;
break;
case 7:
fep->bandwidth_hz = 7000000;
break;
case 8:
fep->bandwidth_hz = 8000000;
break;
}
switch (td->TransmissionMode) {
case 2:
fep->transmission_mode = TRANSMISSION_MODE_2K;
break;
case 8:
fep->transmission_mode = TRANSMISSION_MODE_8K;
}
switch (td->GuardInterval) {
case 0:
fep->guard_interval = GUARD_INTERVAL_1_32;
break;
case 1:
fep->guard_interval = GUARD_INTERVAL_1_16;
break;
case 2:
fep->guard_interval = GUARD_INTERVAL_1_8;
break;
case 3:
fep->guard_interval = GUARD_INTERVAL_1_4;
break;
}
switch (td->CodeRate) {
case 0:
fep->code_rate_HP = FEC_1_2;
break;
case 1:
fep->code_rate_HP = FEC_2_3;
break;
case 2:
fep->code_rate_HP = FEC_3_4;
break;
case 3:
fep->code_rate_HP = FEC_5_6;
break;
case 4:
fep->code_rate_HP = FEC_7_8;
break;
}
switch (td->LPCodeRate) {
case 0:
fep->code_rate_LP = FEC_1_2;
break;
case 1:
fep->code_rate_LP = FEC_2_3;
break;
case 2:
fep->code_rate_LP = FEC_3_4;
break;
case 3:
fep->code_rate_LP = FEC_5_6;
break;
case 4:
fep->code_rate_LP = FEC_7_8;
break;
}
switch (td->Constellation) {
case 0:
fep->modulation = QPSK;
break;
case 1:
fep->modulation = QAM_16;
break;
case 2:
fep->modulation = QAM_64;
break;
}
switch (td->Hierarchy) {
case 0:
fep->hierarchy = HIERARCHY_NONE;
break;
case 1:
fep->hierarchy = HIERARCHY_1;
break;
case 2:
fep->hierarchy = HIERARCHY_2;
break;
case 3:
fep->hierarchy = HIERARCHY_4;
break;
}
fep->inversion = INVERSION_AUTO;
break;
case DEVICE_MODE_ISDBT:
case DEVICE_MODE_ISDBT_BDA:
fep->frequency = td->Frequency;
fep->bandwidth_hz = 6000000;
/* todo: retrive the other parameters */
break;
default:
return -EINVAL;
}
return 0;
}
static int smsdvb_init(struct dvb_frontend *fe)
{
struct smsdvb_client_t *client =
container_of(fe, struct smsdvb_client_t, frontend);
sms_board_power(client->coredev, 1);
sms_board_dvb3_event(client, DVB3_EVENT_INIT);
return 0;
}
static int smsdvb_sleep(struct dvb_frontend *fe)
{
struct smsdvb_client_t *client =
container_of(fe, struct smsdvb_client_t, frontend);
sms_board_led_feedback(client->coredev, SMS_LED_OFF);
sms_board_power(client->coredev, 0);
sms_board_dvb3_event(client, DVB3_EVENT_SLEEP);
return 0;
}
static void smsdvb_release(struct dvb_frontend *fe)
{
/* do nothing */
}
static struct dvb_frontend_ops smsdvb_fe_ops = {
.info = {
.name = "Siano Mobile Digital MDTV Receiver",
.frequency_min = 44250000,
.frequency_max = 867250000,
.frequency_stepsize = 250000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 |
FE_CAN_QAM_AUTO | FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_RECOVER |
FE_CAN_HIERARCHY_AUTO,
},
.release = smsdvb_release,
.set_frontend = smsdvb_set_frontend,
.get_frontend = smsdvb_get_frontend,
.get_tune_settings = smsdvb_get_tune_settings,
.read_status = smsdvb_read_status,
.read_ber = smsdvb_read_ber,
.read_signal_strength = smsdvb_read_signal_strength,
.read_snr = smsdvb_read_snr,
.read_ucblocks = smsdvb_read_ucblocks,
.init = smsdvb_init,
.sleep = smsdvb_sleep,
};
static int smsdvb_hotplug(struct smscore_device_t *coredev,
struct device *device, int arrival)
{
struct smsclient_params_t params;
struct smsdvb_client_t *client;
int rc;
/* device removal handled by onremove callback */
if (!arrival)
return 0;
client = kzalloc(sizeof(struct smsdvb_client_t), GFP_KERNEL);
if (!client) {
sms_err("kmalloc() failed");
return -ENOMEM;
}
/* register dvb adapter */
rc = dvb_register_adapter(&client->adapter,
sms_get_board(
smscore_get_board_id(coredev))->name,
THIS_MODULE, device, adapter_nr);
if (rc < 0) {
sms_err("dvb_register_adapter() failed %d", rc);
goto adapter_error;
}
/* init dvb demux */
client->demux.dmx.capabilities = DMX_TS_FILTERING;
client->demux.filternum = 32; /* todo: nova ??? */
client->demux.feednum = 32;
client->demux.start_feed = smsdvb_start_feed;
client->demux.stop_feed = smsdvb_stop_feed;
rc = dvb_dmx_init(&client->demux);
if (rc < 0) {
sms_err("dvb_dmx_init failed %d", rc);
goto dvbdmx_error;
}
/* init dmxdev */
client->dmxdev.filternum = 32;
client->dmxdev.demux = &client->demux.dmx;
client->dmxdev.capabilities = 0;
rc = dvb_dmxdev_init(&client->dmxdev, &client->adapter);
if (rc < 0) {
sms_err("dvb_dmxdev_init failed %d", rc);
goto dmxdev_error;
}
/* init and register frontend */
memcpy(&client->frontend.ops, &smsdvb_fe_ops,
sizeof(struct dvb_frontend_ops));
switch (smscore_get_device_mode(coredev)) {
case DEVICE_MODE_DVBT:
case DEVICE_MODE_DVBT_BDA:
client->frontend.ops.delsys[0] = SYS_DVBT;
break;
case DEVICE_MODE_ISDBT:
case DEVICE_MODE_ISDBT_BDA:
client->frontend.ops.delsys[0] = SYS_ISDBT;
break;
}
rc = dvb_register_frontend(&client->adapter, &client->frontend);
if (rc < 0) {
sms_err("frontend registration failed %d", rc);
goto frontend_error;
}
params.initial_id = 1;
params.data_type = MSG_SMS_DVBT_BDA_DATA;
params.onresponse_handler = smsdvb_onresponse;
params.onremove_handler = smsdvb_onremove;
params.context = client;
rc = smscore_register_client(coredev, ¶ms, &client->smsclient);
if (rc < 0) {
sms_err("smscore_register_client() failed %d", rc);
goto client_error;
}
client->coredev = coredev;
init_completion(&client->tune_done);
kmutex_lock(&g_smsdvb_clientslock);
list_add(&client->entry, &g_smsdvb_clients);
kmutex_unlock(&g_smsdvb_clientslock);
client->event_fe_state = -1;
client->event_unc_state = -1;
sms_board_dvb3_event(client, DVB3_EVENT_HOTPLUG);
sms_info("success");
sms_board_setup(coredev);
return 0;
client_error:
dvb_unregister_frontend(&client->frontend);
frontend_error:
dvb_dmxdev_release(&client->dmxdev);
dmxdev_error:
dvb_dmx_release(&client->demux);
dvbdmx_error:
dvb_unregister_adapter(&client->adapter);
adapter_error:
kfree(client);
return rc;
}
static int __init smsdvb_module_init(void)
{
int rc;
INIT_LIST_HEAD(&g_smsdvb_clients);
kmutex_init(&g_smsdvb_clientslock);
rc = smscore_register_hotplug(smsdvb_hotplug);
sms_debug("");
return rc;
}
static void __exit smsdvb_module_exit(void)
{
smscore_unregister_hotplug(smsdvb_hotplug);
kmutex_lock(&g_smsdvb_clientslock);
while (!list_empty(&g_smsdvb_clients))
smsdvb_unregister_client(
(struct smsdvb_client_t *) g_smsdvb_clients.next);
kmutex_unlock(&g_smsdvb_clientslock);
}
module_init(smsdvb_module_init);
module_exit(smsdvb_module_exit);
MODULE_DESCRIPTION("SMS DVB subsystem adaptation module");
MODULE_AUTHOR("Siano Mobile Silicon, Inc. (uris@siano-ms.com)");
MODULE_LICENSE("GPL");
| gpl-2.0 |
willcast/kernel_d851 | drivers/net/ethernet/natsemi/sonic.c | 5148 | 22097 | /*
* sonic.c
*
* (C) 2005 Finn Thain
*
* Converted to DMA API, added zero-copy buffer handling, and
* (from the mac68k project) introduced dhd's support for 16-bit cards.
*
* (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)
*
* Core code included by system sonic drivers
*
* And... partially rewritten again by David Huggins-Daines in order
* to cope with screwed up Macintosh NICs that may or may not use
* 16-bit DMA.
*
* (C) 1999 David Huggins-Daines <dhd@debian.org>
*
*/
/*
* Sources: Olivetti M700-10 Risc Personal Computer hardware handbook,
* National Semiconductors data sheet for the DP83932B Sonic Ethernet
* controller, and the files "8390.c" and "skeleton.c" in this directory.
*
* Additional sources: Nat Semi data sheet for the DP83932C and Nat Semi
* Application Note AN-746, the files "lance.c" and "ibmlana.c". See also
* the NetBSD file "sys/arch/mac68k/dev/if_sn.c".
*/
/*
* Open/initialize the SONIC controller.
*
* This routine should set everything up anew at each open, even
* registers that "should" only need to be set once at boot, so that
* there is non-reboot way to recover if something goes wrong.
*/
static int sonic_open(struct net_device *dev)
{
struct sonic_local *lp = netdev_priv(dev);
int i;
if (sonic_debug > 2)
printk("sonic_open: initializing sonic driver.\n");
for (i = 0; i < SONIC_NUM_RRS; i++) {
struct sk_buff *skb = netdev_alloc_skb(dev, SONIC_RBSIZE + 2);
if (skb == NULL) {
while(i > 0) { /* free any that were allocated successfully */
i--;
dev_kfree_skb(lp->rx_skb[i]);
lp->rx_skb[i] = NULL;
}
printk(KERN_ERR "%s: couldn't allocate receive buffers\n",
dev->name);
return -ENOMEM;
}
/* align IP header unless DMA requires otherwise */
if (SONIC_BUS_SCALE(lp->dma_bitmode) == 2)
skb_reserve(skb, 2);
lp->rx_skb[i] = skb;
}
for (i = 0; i < SONIC_NUM_RRS; i++) {
dma_addr_t laddr = dma_map_single(lp->device, skb_put(lp->rx_skb[i], SONIC_RBSIZE),
SONIC_RBSIZE, DMA_FROM_DEVICE);
if (!laddr) {
while(i > 0) { /* free any that were mapped successfully */
i--;
dma_unmap_single(lp->device, lp->rx_laddr[i], SONIC_RBSIZE, DMA_FROM_DEVICE);
lp->rx_laddr[i] = (dma_addr_t)0;
}
for (i = 0; i < SONIC_NUM_RRS; i++) {
dev_kfree_skb(lp->rx_skb[i]);
lp->rx_skb[i] = NULL;
}
printk(KERN_ERR "%s: couldn't map rx DMA buffers\n",
dev->name);
return -ENOMEM;
}
lp->rx_laddr[i] = laddr;
}
/*
* Initialize the SONIC
*/
sonic_init(dev);
netif_start_queue(dev);
if (sonic_debug > 2)
printk("sonic_open: Initialization done.\n");
return 0;
}
/*
* Close the SONIC device
*/
static int sonic_close(struct net_device *dev)
{
struct sonic_local *lp = netdev_priv(dev);
int i;
if (sonic_debug > 2)
printk("sonic_close\n");
netif_stop_queue(dev);
/*
* stop the SONIC, disable interrupts
*/
SONIC_WRITE(SONIC_IMR, 0);
SONIC_WRITE(SONIC_ISR, 0x7fff);
SONIC_WRITE(SONIC_CMD, SONIC_CR_RST);
/* unmap and free skbs that haven't been transmitted */
for (i = 0; i < SONIC_NUM_TDS; i++) {
if(lp->tx_laddr[i]) {
dma_unmap_single(lp->device, lp->tx_laddr[i], lp->tx_len[i], DMA_TO_DEVICE);
lp->tx_laddr[i] = (dma_addr_t)0;
}
if(lp->tx_skb[i]) {
dev_kfree_skb(lp->tx_skb[i]);
lp->tx_skb[i] = NULL;
}
}
/* unmap and free the receive buffers */
for (i = 0; i < SONIC_NUM_RRS; i++) {
if(lp->rx_laddr[i]) {
dma_unmap_single(lp->device, lp->rx_laddr[i], SONIC_RBSIZE, DMA_FROM_DEVICE);
lp->rx_laddr[i] = (dma_addr_t)0;
}
if(lp->rx_skb[i]) {
dev_kfree_skb(lp->rx_skb[i]);
lp->rx_skb[i] = NULL;
}
}
return 0;
}
static void sonic_tx_timeout(struct net_device *dev)
{
struct sonic_local *lp = netdev_priv(dev);
int i;
/*
* put the Sonic into software-reset mode and
* disable all interrupts before releasing DMA buffers
*/
SONIC_WRITE(SONIC_IMR, 0);
SONIC_WRITE(SONIC_ISR, 0x7fff);
SONIC_WRITE(SONIC_CMD, SONIC_CR_RST);
/* We could resend the original skbs. Easier to re-initialise. */
for (i = 0; i < SONIC_NUM_TDS; i++) {
if(lp->tx_laddr[i]) {
dma_unmap_single(lp->device, lp->tx_laddr[i], lp->tx_len[i], DMA_TO_DEVICE);
lp->tx_laddr[i] = (dma_addr_t)0;
}
if(lp->tx_skb[i]) {
dev_kfree_skb(lp->tx_skb[i]);
lp->tx_skb[i] = NULL;
}
}
/* Try to restart the adaptor. */
sonic_init(dev);
lp->stats.tx_errors++;
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue(dev);
}
/*
* transmit packet
*
* Appends new TD during transmission thus avoiding any TX interrupts
* until we run out of TDs.
* This routine interacts closely with the ISR in that it may,
* set tx_skb[i]
* reset the status flags of the new TD
* set and reset EOL flags
* stop the tx queue
* The ISR interacts with this routine in various ways. It may,
* reset tx_skb[i]
* test the EOL and status flags of the TDs
* wake the tx queue
* Concurrently with all of this, the SONIC is potentially writing to
* the status flags of the TDs.
* Until some mutual exclusion is added, this code will not work with SMP. However,
* MIPS Jazz machines and m68k Macs were all uni-processor machines.
*/
static int sonic_send_packet(struct sk_buff *skb, struct net_device *dev)
{
struct sonic_local *lp = netdev_priv(dev);
dma_addr_t laddr;
int length;
int entry = lp->next_tx;
if (sonic_debug > 2)
printk("sonic_send_packet: skb=%p, dev=%p\n", skb, dev);
length = skb->len;
if (length < ETH_ZLEN) {
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
length = ETH_ZLEN;
}
/*
* Map the packet data into the logical DMA address space
*/
laddr = dma_map_single(lp->device, skb->data, length, DMA_TO_DEVICE);
if (!laddr) {
printk(KERN_ERR "%s: failed to map tx DMA buffer.\n", dev->name);
dev_kfree_skb(skb);
return NETDEV_TX_BUSY;
}
sonic_tda_put(dev, entry, SONIC_TD_STATUS, 0); /* clear status */
sonic_tda_put(dev, entry, SONIC_TD_FRAG_COUNT, 1); /* single fragment */
sonic_tda_put(dev, entry, SONIC_TD_PKTSIZE, length); /* length of packet */
sonic_tda_put(dev, entry, SONIC_TD_FRAG_PTR_L, laddr & 0xffff);
sonic_tda_put(dev, entry, SONIC_TD_FRAG_PTR_H, laddr >> 16);
sonic_tda_put(dev, entry, SONIC_TD_FRAG_SIZE, length);
sonic_tda_put(dev, entry, SONIC_TD_LINK,
sonic_tda_get(dev, entry, SONIC_TD_LINK) | SONIC_EOL);
/*
* Must set tx_skb[entry] only after clearing status, and
* before clearing EOL and before stopping queue
*/
wmb();
lp->tx_len[entry] = length;
lp->tx_laddr[entry] = laddr;
lp->tx_skb[entry] = skb;
wmb();
sonic_tda_put(dev, lp->eol_tx, SONIC_TD_LINK,
sonic_tda_get(dev, lp->eol_tx, SONIC_TD_LINK) & ~SONIC_EOL);
lp->eol_tx = entry;
lp->next_tx = (entry + 1) & SONIC_TDS_MASK;
if (lp->tx_skb[lp->next_tx] != NULL) {
/* The ring is full, the ISR has yet to process the next TD. */
if (sonic_debug > 3)
printk("%s: stopping queue\n", dev->name);
netif_stop_queue(dev);
/* after this packet, wait for ISR to free up some TDAs */
} else netif_start_queue(dev);
if (sonic_debug > 2)
printk("sonic_send_packet: issuing Tx command\n");
SONIC_WRITE(SONIC_CMD, SONIC_CR_TXP);
return NETDEV_TX_OK;
}
/*
* The typical workload of the driver:
* Handle the network interface interrupts.
*/
static irqreturn_t sonic_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct sonic_local *lp = netdev_priv(dev);
int status;
if (!(status = SONIC_READ(SONIC_ISR) & SONIC_IMR_DEFAULT))
return IRQ_NONE;
do {
if (status & SONIC_INT_PKTRX) {
if (sonic_debug > 2)
printk("%s: packet rx\n", dev->name);
sonic_rx(dev); /* got packet(s) */
SONIC_WRITE(SONIC_ISR, SONIC_INT_PKTRX); /* clear the interrupt */
}
if (status & SONIC_INT_TXDN) {
int entry = lp->cur_tx;
int td_status;
int freed_some = 0;
/* At this point, cur_tx is the index of a TD that is one of:
* unallocated/freed (status set & tx_skb[entry] clear)
* allocated and sent (status set & tx_skb[entry] set )
* allocated and not yet sent (status clear & tx_skb[entry] set )
* still being allocated by sonic_send_packet (status clear & tx_skb[entry] clear)
*/
if (sonic_debug > 2)
printk("%s: tx done\n", dev->name);
while (lp->tx_skb[entry] != NULL) {
if ((td_status = sonic_tda_get(dev, entry, SONIC_TD_STATUS)) == 0)
break;
if (td_status & 0x0001) {
lp->stats.tx_packets++;
lp->stats.tx_bytes += sonic_tda_get(dev, entry, SONIC_TD_PKTSIZE);
} else {
lp->stats.tx_errors++;
if (td_status & 0x0642)
lp->stats.tx_aborted_errors++;
if (td_status & 0x0180)
lp->stats.tx_carrier_errors++;
if (td_status & 0x0020)
lp->stats.tx_window_errors++;
if (td_status & 0x0004)
lp->stats.tx_fifo_errors++;
}
/* We must free the original skb */
dev_kfree_skb_irq(lp->tx_skb[entry]);
lp->tx_skb[entry] = NULL;
/* and unmap DMA buffer */
dma_unmap_single(lp->device, lp->tx_laddr[entry], lp->tx_len[entry], DMA_TO_DEVICE);
lp->tx_laddr[entry] = (dma_addr_t)0;
freed_some = 1;
if (sonic_tda_get(dev, entry, SONIC_TD_LINK) & SONIC_EOL) {
entry = (entry + 1) & SONIC_TDS_MASK;
break;
}
entry = (entry + 1) & SONIC_TDS_MASK;
}
if (freed_some || lp->tx_skb[entry] == NULL)
netif_wake_queue(dev); /* The ring is no longer full */
lp->cur_tx = entry;
SONIC_WRITE(SONIC_ISR, SONIC_INT_TXDN); /* clear the interrupt */
}
/*
* check error conditions
*/
if (status & SONIC_INT_RFO) {
if (sonic_debug > 1)
printk("%s: rx fifo overrun\n", dev->name);
lp->stats.rx_fifo_errors++;
SONIC_WRITE(SONIC_ISR, SONIC_INT_RFO); /* clear the interrupt */
}
if (status & SONIC_INT_RDE) {
if (sonic_debug > 1)
printk("%s: rx descriptors exhausted\n", dev->name);
lp->stats.rx_dropped++;
SONIC_WRITE(SONIC_ISR, SONIC_INT_RDE); /* clear the interrupt */
}
if (status & SONIC_INT_RBAE) {
if (sonic_debug > 1)
printk("%s: rx buffer area exceeded\n", dev->name);
lp->stats.rx_dropped++;
SONIC_WRITE(SONIC_ISR, SONIC_INT_RBAE); /* clear the interrupt */
}
/* counter overruns; all counters are 16bit wide */
if (status & SONIC_INT_FAE) {
lp->stats.rx_frame_errors += 65536;
SONIC_WRITE(SONIC_ISR, SONIC_INT_FAE); /* clear the interrupt */
}
if (status & SONIC_INT_CRC) {
lp->stats.rx_crc_errors += 65536;
SONIC_WRITE(SONIC_ISR, SONIC_INT_CRC); /* clear the interrupt */
}
if (status & SONIC_INT_MP) {
lp->stats.rx_missed_errors += 65536;
SONIC_WRITE(SONIC_ISR, SONIC_INT_MP); /* clear the interrupt */
}
/* transmit error */
if (status & SONIC_INT_TXER) {
if ((SONIC_READ(SONIC_TCR) & SONIC_TCR_FU) && (sonic_debug > 2))
printk(KERN_ERR "%s: tx fifo underrun\n", dev->name);
SONIC_WRITE(SONIC_ISR, SONIC_INT_TXER); /* clear the interrupt */
}
/* bus retry */
if (status & SONIC_INT_BR) {
printk(KERN_ERR "%s: Bus retry occurred! Device interrupt disabled.\n",
dev->name);
/* ... to help debug DMA problems causing endless interrupts. */
/* Bounce the eth interface to turn on the interrupt again. */
SONIC_WRITE(SONIC_IMR, 0);
SONIC_WRITE(SONIC_ISR, SONIC_INT_BR); /* clear the interrupt */
}
/* load CAM done */
if (status & SONIC_INT_LCD)
SONIC_WRITE(SONIC_ISR, SONIC_INT_LCD); /* clear the interrupt */
} while((status = SONIC_READ(SONIC_ISR) & SONIC_IMR_DEFAULT));
return IRQ_HANDLED;
}
/*
* We have a good packet(s), pass it/them up the network stack.
*/
static void sonic_rx(struct net_device *dev)
{
struct sonic_local *lp = netdev_priv(dev);
int status;
int entry = lp->cur_rx;
while (sonic_rda_get(dev, entry, SONIC_RD_IN_USE) == 0) {
struct sk_buff *used_skb;
struct sk_buff *new_skb;
dma_addr_t new_laddr;
u16 bufadr_l;
u16 bufadr_h;
int pkt_len;
status = sonic_rda_get(dev, entry, SONIC_RD_STATUS);
if (status & SONIC_RCR_PRX) {
/* Malloc up new buffer. */
new_skb = netdev_alloc_skb(dev, SONIC_RBSIZE + 2);
if (new_skb == NULL) {
printk(KERN_ERR "%s: Memory squeeze, dropping packet.\n", dev->name);
lp->stats.rx_dropped++;
break;
}
/* provide 16 byte IP header alignment unless DMA requires otherwise */
if(SONIC_BUS_SCALE(lp->dma_bitmode) == 2)
skb_reserve(new_skb, 2);
new_laddr = dma_map_single(lp->device, skb_put(new_skb, SONIC_RBSIZE),
SONIC_RBSIZE, DMA_FROM_DEVICE);
if (!new_laddr) {
dev_kfree_skb(new_skb);
printk(KERN_ERR "%s: Failed to map rx buffer, dropping packet.\n", dev->name);
lp->stats.rx_dropped++;
break;
}
/* now we have a new skb to replace it, pass the used one up the stack */
dma_unmap_single(lp->device, lp->rx_laddr[entry], SONIC_RBSIZE, DMA_FROM_DEVICE);
used_skb = lp->rx_skb[entry];
pkt_len = sonic_rda_get(dev, entry, SONIC_RD_PKTLEN);
skb_trim(used_skb, pkt_len);
used_skb->protocol = eth_type_trans(used_skb, dev);
netif_rx(used_skb);
lp->stats.rx_packets++;
lp->stats.rx_bytes += pkt_len;
/* and insert the new skb */
lp->rx_laddr[entry] = new_laddr;
lp->rx_skb[entry] = new_skb;
bufadr_l = (unsigned long)new_laddr & 0xffff;
bufadr_h = (unsigned long)new_laddr >> 16;
sonic_rra_put(dev, entry, SONIC_RR_BUFADR_L, bufadr_l);
sonic_rra_put(dev, entry, SONIC_RR_BUFADR_H, bufadr_h);
} else {
/* This should only happen, if we enable accepting broken packets. */
lp->stats.rx_errors++;
if (status & SONIC_RCR_FAER)
lp->stats.rx_frame_errors++;
if (status & SONIC_RCR_CRCR)
lp->stats.rx_crc_errors++;
}
if (status & SONIC_RCR_LPKT) {
/*
* this was the last packet out of the current receive buffer
* give the buffer back to the SONIC
*/
lp->cur_rwp += SIZEOF_SONIC_RR * SONIC_BUS_SCALE(lp->dma_bitmode);
if (lp->cur_rwp >= lp->rra_end) lp->cur_rwp = lp->rra_laddr & 0xffff;
SONIC_WRITE(SONIC_RWP, lp->cur_rwp);
if (SONIC_READ(SONIC_ISR) & SONIC_INT_RBE) {
if (sonic_debug > 2)
printk("%s: rx buffer exhausted\n", dev->name);
SONIC_WRITE(SONIC_ISR, SONIC_INT_RBE); /* clear the flag */
}
} else
printk(KERN_ERR "%s: rx desc without RCR_LPKT. Shouldn't happen !?\n",
dev->name);
/*
* give back the descriptor
*/
sonic_rda_put(dev, entry, SONIC_RD_LINK,
sonic_rda_get(dev, entry, SONIC_RD_LINK) | SONIC_EOL);
sonic_rda_put(dev, entry, SONIC_RD_IN_USE, 1);
sonic_rda_put(dev, lp->eol_rx, SONIC_RD_LINK,
sonic_rda_get(dev, lp->eol_rx, SONIC_RD_LINK) & ~SONIC_EOL);
lp->eol_rx = entry;
lp->cur_rx = entry = (entry + 1) & SONIC_RDS_MASK;
}
/*
* If any worth-while packets have been received, netif_rx()
* has done a mark_bh(NET_BH) for us and will work on them
* when we get to the bottom-half routine.
*/
}
/*
* Get the current statistics.
* This may be called with the device open or closed.
*/
static struct net_device_stats *sonic_get_stats(struct net_device *dev)
{
struct sonic_local *lp = netdev_priv(dev);
/* read the tally counter from the SONIC and reset them */
lp->stats.rx_crc_errors += SONIC_READ(SONIC_CRCT);
SONIC_WRITE(SONIC_CRCT, 0xffff);
lp->stats.rx_frame_errors += SONIC_READ(SONIC_FAET);
SONIC_WRITE(SONIC_FAET, 0xffff);
lp->stats.rx_missed_errors += SONIC_READ(SONIC_MPT);
SONIC_WRITE(SONIC_MPT, 0xffff);
return &lp->stats;
}
/*
* Set or clear the multicast filter for this adaptor.
*/
static void sonic_multicast_list(struct net_device *dev)
{
struct sonic_local *lp = netdev_priv(dev);
unsigned int rcr;
struct netdev_hw_addr *ha;
unsigned char *addr;
int i;
rcr = SONIC_READ(SONIC_RCR) & ~(SONIC_RCR_PRO | SONIC_RCR_AMC);
rcr |= SONIC_RCR_BRD; /* accept broadcast packets */
if (dev->flags & IFF_PROMISC) { /* set promiscuous mode */
rcr |= SONIC_RCR_PRO;
} else {
if ((dev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(dev) > 15)) {
rcr |= SONIC_RCR_AMC;
} else {
if (sonic_debug > 2)
printk("sonic_multicast_list: mc_count %d\n",
netdev_mc_count(dev));
sonic_set_cam_enable(dev, 1); /* always enable our own address */
i = 1;
netdev_for_each_mc_addr(ha, dev) {
addr = ha->addr;
sonic_cda_put(dev, i, SONIC_CD_CAP0, addr[1] << 8 | addr[0]);
sonic_cda_put(dev, i, SONIC_CD_CAP1, addr[3] << 8 | addr[2]);
sonic_cda_put(dev, i, SONIC_CD_CAP2, addr[5] << 8 | addr[4]);
sonic_set_cam_enable(dev, sonic_get_cam_enable(dev) | (1 << i));
i++;
}
SONIC_WRITE(SONIC_CDC, 16);
/* issue Load CAM command */
SONIC_WRITE(SONIC_CDP, lp->cda_laddr & 0xffff);
SONIC_WRITE(SONIC_CMD, SONIC_CR_LCAM);
}
}
if (sonic_debug > 2)
printk("sonic_multicast_list: setting RCR=%x\n", rcr);
SONIC_WRITE(SONIC_RCR, rcr);
}
/*
* Initialize the SONIC ethernet controller.
*/
static int sonic_init(struct net_device *dev)
{
unsigned int cmd;
struct sonic_local *lp = netdev_priv(dev);
int i;
/*
* put the Sonic into software-reset mode and
* disable all interrupts
*/
SONIC_WRITE(SONIC_IMR, 0);
SONIC_WRITE(SONIC_ISR, 0x7fff);
SONIC_WRITE(SONIC_CMD, SONIC_CR_RST);
/*
* clear software reset flag, disable receiver, clear and
* enable interrupts, then completely initialize the SONIC
*/
SONIC_WRITE(SONIC_CMD, 0);
SONIC_WRITE(SONIC_CMD, SONIC_CR_RXDIS);
/*
* initialize the receive resource area
*/
if (sonic_debug > 2)
printk("sonic_init: initialize receive resource area\n");
for (i = 0; i < SONIC_NUM_RRS; i++) {
u16 bufadr_l = (unsigned long)lp->rx_laddr[i] & 0xffff;
u16 bufadr_h = (unsigned long)lp->rx_laddr[i] >> 16;
sonic_rra_put(dev, i, SONIC_RR_BUFADR_L, bufadr_l);
sonic_rra_put(dev, i, SONIC_RR_BUFADR_H, bufadr_h);
sonic_rra_put(dev, i, SONIC_RR_BUFSIZE_L, SONIC_RBSIZE >> 1);
sonic_rra_put(dev, i, SONIC_RR_BUFSIZE_H, 0);
}
/* initialize all RRA registers */
lp->rra_end = (lp->rra_laddr + SONIC_NUM_RRS * SIZEOF_SONIC_RR *
SONIC_BUS_SCALE(lp->dma_bitmode)) & 0xffff;
lp->cur_rwp = (lp->rra_laddr + (SONIC_NUM_RRS - 1) * SIZEOF_SONIC_RR *
SONIC_BUS_SCALE(lp->dma_bitmode)) & 0xffff;
SONIC_WRITE(SONIC_RSA, lp->rra_laddr & 0xffff);
SONIC_WRITE(SONIC_REA, lp->rra_end);
SONIC_WRITE(SONIC_RRP, lp->rra_laddr & 0xffff);
SONIC_WRITE(SONIC_RWP, lp->cur_rwp);
SONIC_WRITE(SONIC_URRA, lp->rra_laddr >> 16);
SONIC_WRITE(SONIC_EOBC, (SONIC_RBSIZE >> 1) - (lp->dma_bitmode ? 2 : 1));
/* load the resource pointers */
if (sonic_debug > 3)
printk("sonic_init: issuing RRRA command\n");
SONIC_WRITE(SONIC_CMD, SONIC_CR_RRRA);
i = 0;
while (i++ < 100) {
if (SONIC_READ(SONIC_CMD) & SONIC_CR_RRRA)
break;
}
if (sonic_debug > 2)
printk("sonic_init: status=%x i=%d\n", SONIC_READ(SONIC_CMD), i);
/*
* Initialize the receive descriptors so that they
* become a circular linked list, ie. let the last
* descriptor point to the first again.
*/
if (sonic_debug > 2)
printk("sonic_init: initialize receive descriptors\n");
for (i=0; i<SONIC_NUM_RDS; i++) {
sonic_rda_put(dev, i, SONIC_RD_STATUS, 0);
sonic_rda_put(dev, i, SONIC_RD_PKTLEN, 0);
sonic_rda_put(dev, i, SONIC_RD_PKTPTR_L, 0);
sonic_rda_put(dev, i, SONIC_RD_PKTPTR_H, 0);
sonic_rda_put(dev, i, SONIC_RD_SEQNO, 0);
sonic_rda_put(dev, i, SONIC_RD_IN_USE, 1);
sonic_rda_put(dev, i, SONIC_RD_LINK,
lp->rda_laddr +
((i+1) * SIZEOF_SONIC_RD * SONIC_BUS_SCALE(lp->dma_bitmode)));
}
/* fix last descriptor */
sonic_rda_put(dev, SONIC_NUM_RDS - 1, SONIC_RD_LINK,
(lp->rda_laddr & 0xffff) | SONIC_EOL);
lp->eol_rx = SONIC_NUM_RDS - 1;
lp->cur_rx = 0;
SONIC_WRITE(SONIC_URDA, lp->rda_laddr >> 16);
SONIC_WRITE(SONIC_CRDA, lp->rda_laddr & 0xffff);
/*
* initialize transmit descriptors
*/
if (sonic_debug > 2)
printk("sonic_init: initialize transmit descriptors\n");
for (i = 0; i < SONIC_NUM_TDS; i++) {
sonic_tda_put(dev, i, SONIC_TD_STATUS, 0);
sonic_tda_put(dev, i, SONIC_TD_CONFIG, 0);
sonic_tda_put(dev, i, SONIC_TD_PKTSIZE, 0);
sonic_tda_put(dev, i, SONIC_TD_FRAG_COUNT, 0);
sonic_tda_put(dev, i, SONIC_TD_LINK,
(lp->tda_laddr & 0xffff) +
(i + 1) * SIZEOF_SONIC_TD * SONIC_BUS_SCALE(lp->dma_bitmode));
lp->tx_skb[i] = NULL;
}
/* fix last descriptor */
sonic_tda_put(dev, SONIC_NUM_TDS - 1, SONIC_TD_LINK,
(lp->tda_laddr & 0xffff));
SONIC_WRITE(SONIC_UTDA, lp->tda_laddr >> 16);
SONIC_WRITE(SONIC_CTDA, lp->tda_laddr & 0xffff);
lp->cur_tx = lp->next_tx = 0;
lp->eol_tx = SONIC_NUM_TDS - 1;
/*
* put our own address to CAM desc[0]
*/
sonic_cda_put(dev, 0, SONIC_CD_CAP0, dev->dev_addr[1] << 8 | dev->dev_addr[0]);
sonic_cda_put(dev, 0, SONIC_CD_CAP1, dev->dev_addr[3] << 8 | dev->dev_addr[2]);
sonic_cda_put(dev, 0, SONIC_CD_CAP2, dev->dev_addr[5] << 8 | dev->dev_addr[4]);
sonic_set_cam_enable(dev, 1);
for (i = 0; i < 16; i++)
sonic_cda_put(dev, i, SONIC_CD_ENTRY_POINTER, i);
/*
* initialize CAM registers
*/
SONIC_WRITE(SONIC_CDP, lp->cda_laddr & 0xffff);
SONIC_WRITE(SONIC_CDC, 16);
/*
* load the CAM
*/
SONIC_WRITE(SONIC_CMD, SONIC_CR_LCAM);
i = 0;
while (i++ < 100) {
if (SONIC_READ(SONIC_ISR) & SONIC_INT_LCD)
break;
}
if (sonic_debug > 2) {
printk("sonic_init: CMD=%x, ISR=%x\n, i=%d",
SONIC_READ(SONIC_CMD), SONIC_READ(SONIC_ISR), i);
}
/*
* enable receiver, disable loopback
* and enable all interrupts
*/
SONIC_WRITE(SONIC_CMD, SONIC_CR_RXEN | SONIC_CR_STP);
SONIC_WRITE(SONIC_RCR, SONIC_RCR_DEFAULT);
SONIC_WRITE(SONIC_TCR, SONIC_TCR_DEFAULT);
SONIC_WRITE(SONIC_ISR, 0x7fff);
SONIC_WRITE(SONIC_IMR, SONIC_IMR_DEFAULT);
cmd = SONIC_READ(SONIC_CMD);
if ((cmd & SONIC_CR_RXEN) == 0 || (cmd & SONIC_CR_STP) == 0)
printk(KERN_ERR "sonic_init: failed, status=%x\n", cmd);
if (sonic_debug > 2)
printk("sonic_init: new status=%x\n",
SONIC_READ(SONIC_CMD));
return 0;
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
bhundven/android_kernel_samsung_galaxys4gmtd | 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 |
donkeykang/donkeyk | drivers/pnp/driver.c | 10524 | 5551 | /*
* driver.c - device id matching, driver model, etc.
*
* Copyright 2002 Adam Belay <ambx1@neo.rr.com>
*/
#include <linux/string.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/ctype.h>
#include <linux/slab.h>
#include <linux/pnp.h>
#include "base.h"
static int compare_func(const char *ida, const char *idb)
{
int i;
/* we only need to compare the last 4 chars */
for (i = 3; i < 7; i++) {
if (ida[i] != 'X' &&
idb[i] != 'X' && toupper(ida[i]) != toupper(idb[i]))
return 0;
}
return 1;
}
int compare_pnp_id(struct pnp_id *pos, const char *id)
{
if (!pos || !id || (strlen(id) != 7))
return 0;
if (memcmp(id, "ANYDEVS", 7) == 0)
return 1;
while (pos) {
if (memcmp(pos->id, id, 3) == 0)
if (compare_func(pos->id, id) == 1)
return 1;
pos = pos->next;
}
return 0;
}
static const struct pnp_device_id *match_device(struct pnp_driver *drv,
struct pnp_dev *dev)
{
const struct pnp_device_id *drv_id = drv->id_table;
if (!drv_id)
return NULL;
while (*drv_id->id) {
if (compare_pnp_id(dev->id, drv_id->id))
return drv_id;
drv_id++;
}
return NULL;
}
int pnp_device_attach(struct pnp_dev *pnp_dev)
{
spin_lock(&pnp_lock);
if (pnp_dev->status != PNP_READY) {
spin_unlock(&pnp_lock);
return -EBUSY;
}
pnp_dev->status = PNP_ATTACHED;
spin_unlock(&pnp_lock);
return 0;
}
void pnp_device_detach(struct pnp_dev *pnp_dev)
{
spin_lock(&pnp_lock);
if (pnp_dev->status == PNP_ATTACHED)
pnp_dev->status = PNP_READY;
spin_unlock(&pnp_lock);
pnp_disable_dev(pnp_dev);
}
static int pnp_device_probe(struct device *dev)
{
int error;
struct pnp_driver *pnp_drv;
struct pnp_dev *pnp_dev;
const struct pnp_device_id *dev_id = NULL;
pnp_dev = to_pnp_dev(dev);
pnp_drv = to_pnp_driver(dev->driver);
error = pnp_device_attach(pnp_dev);
if (error < 0)
return error;
if (pnp_dev->active == 0) {
if (!(pnp_drv->flags & PNP_DRIVER_RES_DO_NOT_CHANGE)) {
error = pnp_activate_dev(pnp_dev);
if (error < 0)
return error;
}
} else if ((pnp_drv->flags & PNP_DRIVER_RES_DISABLE)
== PNP_DRIVER_RES_DISABLE) {
error = pnp_disable_dev(pnp_dev);
if (error < 0)
return error;
}
error = 0;
if (pnp_drv->probe) {
dev_id = match_device(pnp_drv, pnp_dev);
if (dev_id != NULL)
error = pnp_drv->probe(pnp_dev, dev_id);
}
if (error >= 0) {
pnp_dev->driver = pnp_drv;
error = 0;
} else
goto fail;
return error;
fail:
pnp_device_detach(pnp_dev);
return error;
}
static int pnp_device_remove(struct device *dev)
{
struct pnp_dev *pnp_dev = to_pnp_dev(dev);
struct pnp_driver *drv = pnp_dev->driver;
if (drv) {
if (drv->remove)
drv->remove(pnp_dev);
pnp_dev->driver = NULL;
}
pnp_device_detach(pnp_dev);
return 0;
}
static void pnp_device_shutdown(struct device *dev)
{
struct pnp_dev *pnp_dev = to_pnp_dev(dev);
struct pnp_driver *drv = pnp_dev->driver;
if (drv && drv->shutdown)
drv->shutdown(pnp_dev);
}
static int pnp_bus_match(struct device *dev, struct device_driver *drv)
{
struct pnp_dev *pnp_dev = to_pnp_dev(dev);
struct pnp_driver *pnp_drv = to_pnp_driver(drv);
if (match_device(pnp_drv, pnp_dev) == NULL)
return 0;
return 1;
}
static int pnp_bus_suspend(struct device *dev, pm_message_t state)
{
struct pnp_dev *pnp_dev = to_pnp_dev(dev);
struct pnp_driver *pnp_drv = pnp_dev->driver;
int error;
if (!pnp_drv)
return 0;
if (pnp_drv->suspend) {
error = pnp_drv->suspend(pnp_dev, state);
if (error)
return error;
}
if (pnp_can_disable(pnp_dev)) {
error = pnp_stop_dev(pnp_dev);
if (error)
return error;
}
if (pnp_dev->protocol->suspend)
pnp_dev->protocol->suspend(pnp_dev, state);
return 0;
}
static int pnp_bus_resume(struct device *dev)
{
struct pnp_dev *pnp_dev = to_pnp_dev(dev);
struct pnp_driver *pnp_drv = pnp_dev->driver;
int error;
if (!pnp_drv)
return 0;
if (pnp_dev->protocol->resume) {
error = pnp_dev->protocol->resume(pnp_dev);
if (error)
return error;
}
if (pnp_can_write(pnp_dev)) {
error = pnp_start_dev(pnp_dev);
if (error)
return error;
}
if (pnp_drv->resume) {
error = pnp_drv->resume(pnp_dev);
if (error)
return error;
}
return 0;
}
struct bus_type pnp_bus_type = {
.name = "pnp",
.match = pnp_bus_match,
.probe = pnp_device_probe,
.remove = pnp_device_remove,
.shutdown = pnp_device_shutdown,
.suspend = pnp_bus_suspend,
.resume = pnp_bus_resume,
.dev_attrs = pnp_interface_attrs,
};
int pnp_register_driver(struct pnp_driver *drv)
{
drv->driver.name = drv->name;
drv->driver.bus = &pnp_bus_type;
return driver_register(&drv->driver);
}
void pnp_unregister_driver(struct pnp_driver *drv)
{
driver_unregister(&drv->driver);
}
/**
* pnp_add_id - adds an EISA id to the specified device
* @dev: pointer to the desired device
* @id: pointer to an EISA id string
*/
struct pnp_id *pnp_add_id(struct pnp_dev *dev, const char *id)
{
struct pnp_id *dev_id, *ptr;
dev_id = kzalloc(sizeof(struct pnp_id), GFP_KERNEL);
if (!dev_id)
return NULL;
dev_id->id[0] = id[0];
dev_id->id[1] = id[1];
dev_id->id[2] = id[2];
dev_id->id[3] = tolower(id[3]);
dev_id->id[4] = tolower(id[4]);
dev_id->id[5] = tolower(id[5]);
dev_id->id[6] = tolower(id[6]);
dev_id->id[7] = '\0';
dev_id->next = NULL;
ptr = dev->id;
while (ptr && ptr->next)
ptr = ptr->next;
if (ptr)
ptr->next = dev_id;
else
dev->id = dev_id;
return dev_id;
}
EXPORT_SYMBOL(pnp_register_driver);
EXPORT_SYMBOL(pnp_unregister_driver);
EXPORT_SYMBOL(pnp_device_attach);
EXPORT_SYMBOL(pnp_device_detach);
| gpl-2.0 |
tellapart/ubuntu-precise | drivers/usb/gadget/dummy_hcd.c | 29 | 63192 | /*
* dummy_hcd.c -- Dummy/Loopback USB host and device emulator driver.
*
* Maintainer: Alan Stern <stern@rowland.harvard.edu>
*
* Copyright (C) 2003 David Brownell
* Copyright (C) 2003-2005 Alan Stern
*
* 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 exposes a device side "USB gadget" API, driven by requests to a
* Linux-USB host controller driver. USB traffic is simulated; there's
* no need for USB hardware. Use this with two other drivers:
*
* - Gadget driver, responding to requests (slave);
* - Host-side device driver, as already familiar in Linux.
*
* Having this all in one kernel can help some stages of development,
* bypassing some hardware (and driver) issues. UML could help too.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/usb.h>
#include <linux/usb/gadget.h>
#include <linux/usb/hcd.h>
#include <asm/byteorder.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/system.h>
#include <asm/unaligned.h>
#define DRIVER_DESC "USB Host+Gadget Emulator"
#define DRIVER_VERSION "02 May 2005"
#define POWER_BUDGET 500 /* in mA; use 8 for low-power port testing */
static const char driver_name [] = "dummy_hcd";
static const char driver_desc [] = "USB Host+Gadget Emulator";
static const char gadget_name [] = "dummy_udc";
MODULE_DESCRIPTION (DRIVER_DESC);
MODULE_AUTHOR ("David Brownell");
MODULE_LICENSE ("GPL");
struct dummy_hcd_module_parameters {
bool is_super_speed;
bool is_high_speed;
};
static struct dummy_hcd_module_parameters mod_data = {
.is_super_speed = false,
.is_high_speed = true,
};
module_param_named(is_super_speed, mod_data.is_super_speed, bool, S_IRUGO);
MODULE_PARM_DESC(is_super_speed, "true to simulate SuperSpeed connection");
module_param_named(is_high_speed, mod_data.is_high_speed, bool, S_IRUGO);
MODULE_PARM_DESC(is_high_speed, "true to simulate HighSpeed connection");
/*-------------------------------------------------------------------------*/
/* gadget side driver data structres */
struct dummy_ep {
struct list_head queue;
unsigned long last_io; /* jiffies timestamp */
struct usb_gadget *gadget;
const struct usb_endpoint_descriptor *desc;
struct usb_ep ep;
unsigned halted : 1;
unsigned wedged : 1;
unsigned already_seen : 1;
unsigned setup_stage : 1;
};
struct dummy_request {
struct list_head queue; /* ep's requests */
struct usb_request req;
};
static inline struct dummy_ep *usb_ep_to_dummy_ep (struct usb_ep *_ep)
{
return container_of (_ep, struct dummy_ep, ep);
}
static inline struct dummy_request *usb_request_to_dummy_request
(struct usb_request *_req)
{
return container_of (_req, struct dummy_request, req);
}
/*-------------------------------------------------------------------------*/
/*
* Every device has ep0 for control requests, plus up to 30 more endpoints,
* in one of two types:
*
* - Configurable: direction (in/out), type (bulk, iso, etc), and endpoint
* number can be changed. Names like "ep-a" are used for this type.
*
* - Fixed Function: in other cases. some characteristics may be mutable;
* that'd be hardware-specific. Names like "ep12out-bulk" are used.
*
* Gadget drivers are responsible for not setting up conflicting endpoint
* configurations, illegal or unsupported packet lengths, and so on.
*/
static const char ep0name [] = "ep0";
static const char *const ep_name [] = {
ep0name, /* everyone has ep0 */
/* act like a pxa250: fifteen fixed function endpoints */
"ep1in-bulk", "ep2out-bulk", "ep3in-iso", "ep4out-iso", "ep5in-int",
"ep6in-bulk", "ep7out-bulk", "ep8in-iso", "ep9out-iso", "ep10in-int",
"ep11in-bulk", "ep12out-bulk", "ep13in-iso", "ep14out-iso",
"ep15in-int",
/* or like sa1100: two fixed function endpoints */
"ep1out-bulk", "ep2in-bulk",
/* and now some generic EPs so we have enough in multi config */
"ep3out", "ep4in", "ep5out", "ep6out", "ep7in", "ep8out", "ep9in",
"ep10out", "ep11out", "ep12in", "ep13out", "ep14in", "ep15out",
};
#define DUMMY_ENDPOINTS ARRAY_SIZE(ep_name)
/*-------------------------------------------------------------------------*/
#define FIFO_SIZE 64
struct urbp {
struct urb *urb;
struct list_head urbp_list;
};
enum dummy_rh_state {
DUMMY_RH_RESET,
DUMMY_RH_SUSPENDED,
DUMMY_RH_RUNNING
};
struct dummy_hcd {
struct dummy *dum;
enum dummy_rh_state rh_state;
struct timer_list timer;
u32 port_status;
u32 old_status;
unsigned long re_timeout;
struct usb_device *udev;
struct list_head urbp_list;
unsigned active:1;
unsigned old_active:1;
unsigned resuming:1;
};
struct dummy {
spinlock_t lock;
/*
* SLAVE/GADGET side support
*/
struct dummy_ep ep [DUMMY_ENDPOINTS];
int address;
struct usb_gadget gadget;
struct usb_gadget_driver *driver;
struct dummy_request fifo_req;
u8 fifo_buf [FIFO_SIZE];
u16 devstatus;
unsigned udc_suspended:1;
unsigned pullup:1;
/*
* MASTER/HOST side support
*/
struct dummy_hcd *hs_hcd;
struct dummy_hcd *ss_hcd;
};
static inline struct dummy_hcd *hcd_to_dummy_hcd(struct usb_hcd *hcd)
{
return (struct dummy_hcd *) (hcd->hcd_priv);
}
static inline struct usb_hcd *dummy_hcd_to_hcd(struct dummy_hcd *dum)
{
return container_of((void *) dum, struct usb_hcd, hcd_priv);
}
static inline struct device *dummy_dev(struct dummy_hcd *dum)
{
return dummy_hcd_to_hcd(dum)->self.controller;
}
static inline struct device *udc_dev (struct dummy *dum)
{
return dum->gadget.dev.parent;
}
static inline struct dummy *ep_to_dummy (struct dummy_ep *ep)
{
return container_of (ep->gadget, struct dummy, gadget);
}
static inline struct dummy_hcd *gadget_to_dummy_hcd(struct usb_gadget *gadget)
{
struct dummy *dum = container_of(gadget, struct dummy, gadget);
if (dum->gadget.speed == USB_SPEED_SUPER)
return dum->ss_hcd;
else
return dum->hs_hcd;
}
static inline struct dummy *gadget_dev_to_dummy (struct device *dev)
{
return container_of (dev, struct dummy, gadget.dev);
}
static struct dummy the_controller;
/*-------------------------------------------------------------------------*/
/* SLAVE/GADGET SIDE UTILITY ROUTINES */
/* called with spinlock held */
static void nuke (struct dummy *dum, struct dummy_ep *ep)
{
while (!list_empty (&ep->queue)) {
struct dummy_request *req;
req = list_entry (ep->queue.next, struct dummy_request, queue);
list_del_init (&req->queue);
req->req.status = -ESHUTDOWN;
spin_unlock (&dum->lock);
req->req.complete (&ep->ep, &req->req);
spin_lock (&dum->lock);
}
}
/* caller must hold lock */
static void
stop_activity (struct dummy *dum)
{
struct dummy_ep *ep;
/* prevent any more requests */
dum->address = 0;
/* The timer is left running so that outstanding URBs can fail */
/* nuke any pending requests first, so driver i/o is quiesced */
list_for_each_entry (ep, &dum->gadget.ep_list, ep.ep_list)
nuke (dum, ep);
/* driver now does any non-usb quiescing necessary */
}
/**
* set_link_state_by_speed() - Sets the current state of the link according to
* the hcd speed
* @dum_hcd: pointer to the dummy_hcd structure to update the link state for
*
* This function updates the port_status according to the link state and the
* speed of the hcd.
*/
static void set_link_state_by_speed(struct dummy_hcd *dum_hcd)
{
struct dummy *dum = dum_hcd->dum;
if (dummy_hcd_to_hcd(dum_hcd)->speed == HCD_USB3) {
if ((dum_hcd->port_status & USB_SS_PORT_STAT_POWER) == 0) {
dum_hcd->port_status = 0;
} else if (!dum->pullup || dum->udc_suspended) {
/* UDC suspend must cause a disconnect */
dum_hcd->port_status &= ~(USB_PORT_STAT_CONNECTION |
USB_PORT_STAT_ENABLE);
if ((dum_hcd->old_status &
USB_PORT_STAT_CONNECTION) != 0)
dum_hcd->port_status |=
(USB_PORT_STAT_C_CONNECTION << 16);
} else {
/* device is connected and not suspended */
dum_hcd->port_status |= (USB_PORT_STAT_CONNECTION |
USB_PORT_STAT_SPEED_5GBPS) ;
if ((dum_hcd->old_status &
USB_PORT_STAT_CONNECTION) == 0)
dum_hcd->port_status |=
(USB_PORT_STAT_C_CONNECTION << 16);
if ((dum_hcd->port_status &
USB_PORT_STAT_ENABLE) == 1 &&
(dum_hcd->port_status &
USB_SS_PORT_LS_U0) == 1 &&
dum_hcd->rh_state != DUMMY_RH_SUSPENDED)
dum_hcd->active = 1;
}
} else {
if ((dum_hcd->port_status & USB_PORT_STAT_POWER) == 0) {
dum_hcd->port_status = 0;
} else if (!dum->pullup || dum->udc_suspended) {
/* UDC suspend must cause a disconnect */
dum_hcd->port_status &= ~(USB_PORT_STAT_CONNECTION |
USB_PORT_STAT_ENABLE |
USB_PORT_STAT_LOW_SPEED |
USB_PORT_STAT_HIGH_SPEED |
USB_PORT_STAT_SUSPEND);
if ((dum_hcd->old_status &
USB_PORT_STAT_CONNECTION) != 0)
dum_hcd->port_status |=
(USB_PORT_STAT_C_CONNECTION << 16);
} else {
dum_hcd->port_status |= USB_PORT_STAT_CONNECTION;
if ((dum_hcd->old_status &
USB_PORT_STAT_CONNECTION) == 0)
dum_hcd->port_status |=
(USB_PORT_STAT_C_CONNECTION << 16);
if ((dum_hcd->port_status & USB_PORT_STAT_ENABLE) == 0)
dum_hcd->port_status &= ~USB_PORT_STAT_SUSPEND;
else if ((dum_hcd->port_status &
USB_PORT_STAT_SUSPEND) == 0 &&
dum_hcd->rh_state != DUMMY_RH_SUSPENDED)
dum_hcd->active = 1;
}
}
}
/* caller must hold lock */
static void set_link_state(struct dummy_hcd *dum_hcd)
{
struct dummy *dum = dum_hcd->dum;
dum_hcd->active = 0;
if (dum->pullup)
if ((dummy_hcd_to_hcd(dum_hcd)->speed == HCD_USB3 &&
dum->gadget.speed != USB_SPEED_SUPER) ||
(dummy_hcd_to_hcd(dum_hcd)->speed != HCD_USB3 &&
dum->gadget.speed == USB_SPEED_SUPER))
return;
set_link_state_by_speed(dum_hcd);
if ((dum_hcd->port_status & USB_PORT_STAT_ENABLE) == 0 ||
dum_hcd->active)
dum_hcd->resuming = 0;
/* if !connected or reset */
if ((dum_hcd->port_status & USB_PORT_STAT_CONNECTION) == 0 ||
(dum_hcd->port_status & USB_PORT_STAT_RESET) != 0) {
/*
* We're connected and not reset (reset occurred now),
* and driver attached - disconnect!
*/
if ((dum_hcd->old_status & USB_PORT_STAT_CONNECTION) != 0 &&
(dum_hcd->old_status & USB_PORT_STAT_RESET) == 0 &&
dum->driver) {
stop_activity(dum);
spin_unlock(&dum->lock);
dum->driver->disconnect(&dum->gadget);
spin_lock(&dum->lock);
}
} else if (dum_hcd->active != dum_hcd->old_active) {
if (dum_hcd->old_active && dum->driver->suspend) {
spin_unlock(&dum->lock);
dum->driver->suspend(&dum->gadget);
spin_lock(&dum->lock);
} else if (!dum_hcd->old_active && dum->driver->resume) {
spin_unlock(&dum->lock);
dum->driver->resume(&dum->gadget);
spin_lock(&dum->lock);
}
}
dum_hcd->old_status = dum_hcd->port_status;
dum_hcd->old_active = dum_hcd->active;
}
/*-------------------------------------------------------------------------*/
/* SLAVE/GADGET SIDE DRIVER
*
* This only tracks gadget state. All the work is done when the host
* side tries some (emulated) i/o operation. Real device controller
* drivers would do real i/o using dma, fifos, irqs, timers, etc.
*/
#define is_enabled(dum) \
(dum->port_status & USB_PORT_STAT_ENABLE)
static int
dummy_enable (struct usb_ep *_ep, const struct usb_endpoint_descriptor *desc)
{
struct dummy *dum;
struct dummy_hcd *dum_hcd;
struct dummy_ep *ep;
unsigned max;
int retval;
ep = usb_ep_to_dummy_ep (_ep);
if (!_ep || !desc || ep->desc || _ep->name == ep0name
|| desc->bDescriptorType != USB_DT_ENDPOINT)
return -EINVAL;
dum = ep_to_dummy (ep);
if (!dum->driver)
return -ESHUTDOWN;
dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
if (!is_enabled(dum_hcd))
return -ESHUTDOWN;
/*
* For HS/FS devices only bits 0..10 of the wMaxPacketSize represent the
* maximum packet size.
* For SS devices the wMaxPacketSize is limited by 1024.
*/
max = usb_endpoint_maxp(desc) & 0x7ff;
/* drivers must not request bad settings, since lower levels
* (hardware or its drivers) may not check. some endpoints
* can't do iso, many have maxpacket limitations, etc.
*
* since this "hardware" driver is here to help debugging, we
* have some extra sanity checks. (there could be more though,
* especially for "ep9out" style fixed function ones.)
*/
retval = -EINVAL;
switch (desc->bmAttributes & 0x03) {
case USB_ENDPOINT_XFER_BULK:
if (strstr (ep->ep.name, "-iso")
|| strstr (ep->ep.name, "-int")) {
goto done;
}
switch (dum->gadget.speed) {
case USB_SPEED_SUPER:
if (max == 1024)
break;
goto done;
case USB_SPEED_HIGH:
if (max == 512)
break;
goto done;
case USB_SPEED_FULL:
if (max == 8 || max == 16 || max == 32 || max == 64)
/* we'll fake any legal size */
break;
/* save a return statement */
default:
goto done;
}
break;
case USB_ENDPOINT_XFER_INT:
if (strstr (ep->ep.name, "-iso")) /* bulk is ok */
goto done;
/* real hardware might not handle all packet sizes */
switch (dum->gadget.speed) {
case USB_SPEED_SUPER:
case USB_SPEED_HIGH:
if (max <= 1024)
break;
/* save a return statement */
case USB_SPEED_FULL:
if (max <= 64)
break;
/* save a return statement */
default:
if (max <= 8)
break;
goto done;
}
break;
case USB_ENDPOINT_XFER_ISOC:
if (strstr (ep->ep.name, "-bulk")
|| strstr (ep->ep.name, "-int"))
goto done;
/* real hardware might not handle all packet sizes */
switch (dum->gadget.speed) {
case USB_SPEED_SUPER:
case USB_SPEED_HIGH:
if (max <= 1024)
break;
/* save a return statement */
case USB_SPEED_FULL:
if (max <= 1023)
break;
/* save a return statement */
default:
goto done;
}
break;
default:
/* few chips support control except on ep0 */
goto done;
}
_ep->maxpacket = max;
ep->desc = desc;
dev_dbg (udc_dev(dum), "enabled %s (ep%d%s-%s) maxpacket %d\n",
_ep->name,
desc->bEndpointAddress & 0x0f,
(desc->bEndpointAddress & USB_DIR_IN) ? "in" : "out",
({ char *val;
switch (desc->bmAttributes & 0x03) {
case USB_ENDPOINT_XFER_BULK:
val = "bulk";
break;
case USB_ENDPOINT_XFER_ISOC:
val = "iso";
break;
case USB_ENDPOINT_XFER_INT:
val = "intr";
break;
default:
val = "ctrl";
break;
}; val; }),
max);
/* at this point real hardware should be NAKing transfers
* to that endpoint, until a buffer is queued to it.
*/
ep->halted = ep->wedged = 0;
retval = 0;
done:
return retval;
}
static int dummy_disable (struct usb_ep *_ep)
{
struct dummy_ep *ep;
struct dummy *dum;
unsigned long flags;
int retval;
ep = usb_ep_to_dummy_ep (_ep);
if (!_ep || !ep->desc || _ep->name == ep0name)
return -EINVAL;
dum = ep_to_dummy (ep);
spin_lock_irqsave (&dum->lock, flags);
ep->desc = NULL;
retval = 0;
nuke (dum, ep);
spin_unlock_irqrestore (&dum->lock, flags);
dev_dbg (udc_dev(dum), "disabled %s\n", _ep->name);
return retval;
}
static struct usb_request *
dummy_alloc_request (struct usb_ep *_ep, gfp_t mem_flags)
{
struct dummy_ep *ep;
struct dummy_request *req;
if (!_ep)
return NULL;
ep = usb_ep_to_dummy_ep (_ep);
req = kzalloc(sizeof(*req), mem_flags);
if (!req)
return NULL;
INIT_LIST_HEAD (&req->queue);
return &req->req;
}
static void
dummy_free_request (struct usb_ep *_ep, struct usb_request *_req)
{
struct dummy_ep *ep;
struct dummy_request *req;
ep = usb_ep_to_dummy_ep (_ep);
if (!ep || !_req || (!ep->desc && _ep->name != ep0name))
return;
req = usb_request_to_dummy_request (_req);
WARN_ON (!list_empty (&req->queue));
kfree (req);
}
static void
fifo_complete (struct usb_ep *ep, struct usb_request *req)
{
}
static int
dummy_queue (struct usb_ep *_ep, struct usb_request *_req,
gfp_t mem_flags)
{
struct dummy_ep *ep;
struct dummy_request *req;
struct dummy *dum;
struct dummy_hcd *dum_hcd;
unsigned long flags;
req = usb_request_to_dummy_request (_req);
if (!_req || !list_empty (&req->queue) || !_req->complete)
return -EINVAL;
ep = usb_ep_to_dummy_ep (_ep);
if (!_ep || (!ep->desc && _ep->name != ep0name))
return -EINVAL;
dum = ep_to_dummy (ep);
dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
if (!dum->driver || !is_enabled(dum_hcd))
return -ESHUTDOWN;
#if 0
dev_dbg (udc_dev(dum), "ep %p queue req %p to %s, len %d buf %p\n",
ep, _req, _ep->name, _req->length, _req->buf);
#endif
_req->status = -EINPROGRESS;
_req->actual = 0;
spin_lock_irqsave (&dum->lock, flags);
/* implement an emulated single-request FIFO */
if (ep->desc && (ep->desc->bEndpointAddress & USB_DIR_IN) &&
list_empty (&dum->fifo_req.queue) &&
list_empty (&ep->queue) &&
_req->length <= FIFO_SIZE) {
req = &dum->fifo_req;
req->req = *_req;
req->req.buf = dum->fifo_buf;
memcpy (dum->fifo_buf, _req->buf, _req->length);
req->req.context = dum;
req->req.complete = fifo_complete;
list_add_tail(&req->queue, &ep->queue);
spin_unlock (&dum->lock);
_req->actual = _req->length;
_req->status = 0;
_req->complete (_ep, _req);
spin_lock (&dum->lock);
} else
list_add_tail(&req->queue, &ep->queue);
spin_unlock_irqrestore (&dum->lock, flags);
/* real hardware would likely enable transfers here, in case
* it'd been left NAKing.
*/
return 0;
}
static int dummy_dequeue (struct usb_ep *_ep, struct usb_request *_req)
{
struct dummy_ep *ep;
struct dummy *dum;
int retval = -EINVAL;
unsigned long flags;
struct dummy_request *req = NULL;
if (!_ep || !_req)
return retval;
ep = usb_ep_to_dummy_ep (_ep);
dum = ep_to_dummy (ep);
if (!dum->driver)
return -ESHUTDOWN;
local_irq_save (flags);
spin_lock (&dum->lock);
list_for_each_entry (req, &ep->queue, queue) {
if (&req->req == _req) {
list_del_init (&req->queue);
_req->status = -ECONNRESET;
retval = 0;
break;
}
}
spin_unlock (&dum->lock);
if (retval == 0) {
dev_dbg (udc_dev(dum),
"dequeued req %p from %s, len %d buf %p\n",
req, _ep->name, _req->length, _req->buf);
_req->complete (_ep, _req);
}
local_irq_restore (flags);
return retval;
}
static int
dummy_set_halt_and_wedge(struct usb_ep *_ep, int value, int wedged)
{
struct dummy_ep *ep;
struct dummy *dum;
if (!_ep)
return -EINVAL;
ep = usb_ep_to_dummy_ep (_ep);
dum = ep_to_dummy (ep);
if (!dum->driver)
return -ESHUTDOWN;
if (!value)
ep->halted = ep->wedged = 0;
else if (ep->desc && (ep->desc->bEndpointAddress & USB_DIR_IN) &&
!list_empty (&ep->queue))
return -EAGAIN;
else {
ep->halted = 1;
if (wedged)
ep->wedged = 1;
}
/* FIXME clear emulated data toggle too */
return 0;
}
static int
dummy_set_halt(struct usb_ep *_ep, int value)
{
return dummy_set_halt_and_wedge(_ep, value, 0);
}
static int dummy_set_wedge(struct usb_ep *_ep)
{
if (!_ep || _ep->name == ep0name)
return -EINVAL;
return dummy_set_halt_and_wedge(_ep, 1, 1);
}
static const struct usb_ep_ops dummy_ep_ops = {
.enable = dummy_enable,
.disable = dummy_disable,
.alloc_request = dummy_alloc_request,
.free_request = dummy_free_request,
.queue = dummy_queue,
.dequeue = dummy_dequeue,
.set_halt = dummy_set_halt,
.set_wedge = dummy_set_wedge,
};
/*-------------------------------------------------------------------------*/
/* there are both host and device side versions of this call ... */
static int dummy_g_get_frame (struct usb_gadget *_gadget)
{
struct timeval tv;
do_gettimeofday (&tv);
return tv.tv_usec / 1000;
}
static int dummy_wakeup (struct usb_gadget *_gadget)
{
struct dummy_hcd *dum_hcd;
dum_hcd = gadget_to_dummy_hcd(_gadget);
if (!(dum_hcd->dum->devstatus & ((1 << USB_DEVICE_B_HNP_ENABLE)
| (1 << USB_DEVICE_REMOTE_WAKEUP))))
return -EINVAL;
if ((dum_hcd->port_status & USB_PORT_STAT_CONNECTION) == 0)
return -ENOLINK;
if ((dum_hcd->port_status & USB_PORT_STAT_SUSPEND) == 0 &&
dum_hcd->rh_state != DUMMY_RH_SUSPENDED)
return -EIO;
/* FIXME: What if the root hub is suspended but the port isn't? */
/* hub notices our request, issues downstream resume, etc */
dum_hcd->resuming = 1;
dum_hcd->re_timeout = jiffies + msecs_to_jiffies(20);
mod_timer(&dummy_hcd_to_hcd(dum_hcd)->rh_timer, dum_hcd->re_timeout);
return 0;
}
static int dummy_set_selfpowered (struct usb_gadget *_gadget, int value)
{
struct dummy *dum;
dum = (gadget_to_dummy_hcd(_gadget))->dum;
if (value)
dum->devstatus |= (1 << USB_DEVICE_SELF_POWERED);
else
dum->devstatus &= ~(1 << USB_DEVICE_SELF_POWERED);
return 0;
}
static void dummy_udc_udpate_ep0(struct dummy *dum)
{
u32 i;
if (dum->gadget.speed == USB_SPEED_SUPER) {
for (i = 0; i < DUMMY_ENDPOINTS; i++)
dum->ep[i].ep.max_streams = 0x10;
dum->ep[0].ep.maxpacket = 9;
} else {
for (i = 0; i < DUMMY_ENDPOINTS; i++)
dum->ep[i].ep.max_streams = 0;
dum->ep[0].ep.maxpacket = 64;
}
}
static int dummy_pullup (struct usb_gadget *_gadget, int value)
{
struct dummy_hcd *dum_hcd;
struct dummy *dum;
unsigned long flags;
dum = gadget_dev_to_dummy(&_gadget->dev);
if (value && dum->driver) {
if (mod_data.is_super_speed)
dum->gadget.speed = dum->driver->speed;
else if (mod_data.is_high_speed)
dum->gadget.speed = min_t(u8, USB_SPEED_HIGH,
dum->driver->speed);
else
dum->gadget.speed = USB_SPEED_FULL;
dummy_udc_udpate_ep0(dum);
if (dum->gadget.speed < dum->driver->speed)
dev_dbg(udc_dev(dum), "This device can perform faster"
" if you connect it to a %s port...\n",
(dum->driver->speed == USB_SPEED_SUPER ?
"SuperSpeed" : "HighSpeed"));
}
dum_hcd = gadget_to_dummy_hcd(_gadget);
spin_lock_irqsave (&dum->lock, flags);
dum->pullup = (value != 0);
set_link_state(dum_hcd);
spin_unlock_irqrestore (&dum->lock, flags);
usb_hcd_poll_rh_status(dummy_hcd_to_hcd(dum_hcd));
return 0;
}
static int dummy_udc_start(struct usb_gadget *g,
struct usb_gadget_driver *driver);
static int dummy_udc_stop(struct usb_gadget *g,
struct usb_gadget_driver *driver);
static const struct usb_gadget_ops dummy_ops = {
.get_frame = dummy_g_get_frame,
.wakeup = dummy_wakeup,
.set_selfpowered = dummy_set_selfpowered,
.pullup = dummy_pullup,
.udc_start = dummy_udc_start,
.udc_stop = dummy_udc_stop,
};
/*-------------------------------------------------------------------------*/
/* "function" sysfs attribute */
static ssize_t
show_function (struct device *dev, struct device_attribute *attr, char *buf)
{
struct dummy *dum = gadget_dev_to_dummy (dev);
if (!dum->driver || !dum->driver->function)
return 0;
return scnprintf (buf, PAGE_SIZE, "%s\n", dum->driver->function);
}
static DEVICE_ATTR (function, S_IRUGO, show_function, NULL);
/*-------------------------------------------------------------------------*/
/*
* Driver registration/unregistration.
*
* This is basically hardware-specific; there's usually only one real USB
* device (not host) controller since that's how USB devices are intended
* to work. So most implementations of these api calls will rely on the
* fact that only one driver will ever bind to the hardware. But curious
* hardware can be built with discrete components, so the gadget API doesn't
* require that assumption.
*
* For this emulator, it might be convenient to create a usb slave device
* for each driver that registers: just add to a big root hub.
*/
static int dummy_udc_start(struct usb_gadget *g,
struct usb_gadget_driver *driver)
{
struct dummy_hcd *dum_hcd = gadget_to_dummy_hcd(g);
struct dummy *dum = dum_hcd->dum;
if (driver->speed == USB_SPEED_UNKNOWN)
return -EINVAL;
/*
* SLAVE side init ... the layer above hardware, which
* can't enumerate without help from the driver we're binding.
*/
dum->devstatus = 0;
dum->driver = driver;
dev_dbg (udc_dev(dum), "binding gadget driver '%s'\n",
driver->driver.name);
return 0;
}
static int dummy_udc_stop(struct usb_gadget *g,
struct usb_gadget_driver *driver)
{
struct dummy_hcd *dum_hcd = gadget_to_dummy_hcd(g);
struct dummy *dum = dum_hcd->dum;
dev_dbg (udc_dev(dum), "unregister gadget driver '%s'\n",
driver->driver.name);
dum->driver = NULL;
return 0;
}
#undef is_enabled
/* The gadget structure is stored inside the hcd structure and will be
* released along with it. */
static void
dummy_gadget_release (struct device *dev)
{
return;
}
static void init_dummy_udc_hw(struct dummy *dum)
{
int i;
INIT_LIST_HEAD(&dum->gadget.ep_list);
for (i = 0; i < DUMMY_ENDPOINTS; i++) {
struct dummy_ep *ep = &dum->ep[i];
if (!ep_name[i])
break;
ep->ep.name = ep_name[i];
ep->ep.ops = &dummy_ep_ops;
list_add_tail(&ep->ep.ep_list, &dum->gadget.ep_list);
ep->halted = ep->wedged = ep->already_seen =
ep->setup_stage = 0;
ep->ep.maxpacket = ~0;
ep->last_io = jiffies;
ep->gadget = &dum->gadget;
ep->desc = NULL;
INIT_LIST_HEAD(&ep->queue);
}
dum->gadget.ep0 = &dum->ep[0].ep;
list_del_init(&dum->ep[0].ep.ep_list);
INIT_LIST_HEAD(&dum->fifo_req.queue);
#ifdef CONFIG_USB_OTG
dum->gadget.is_otg = 1;
#endif
}
static int dummy_udc_probe (struct platform_device *pdev)
{
struct dummy *dum = &the_controller;
int rc;
dum->gadget.name = gadget_name;
dum->gadget.ops = &dummy_ops;
dum->gadget.is_dualspeed = 1;
dev_set_name(&dum->gadget.dev, "gadget");
dum->gadget.dev.parent = &pdev->dev;
dum->gadget.dev.release = dummy_gadget_release;
rc = device_register (&dum->gadget.dev);
if (rc < 0) {
put_device(&dum->gadget.dev);
return rc;
}
init_dummy_udc_hw(dum);
rc = usb_add_gadget_udc(&pdev->dev, &dum->gadget);
if (rc < 0)
goto err_udc;
rc = device_create_file (&dum->gadget.dev, &dev_attr_function);
if (rc < 0)
goto err_dev;
platform_set_drvdata(pdev, dum);
return rc;
err_dev:
usb_del_gadget_udc(&dum->gadget);
err_udc:
device_unregister(&dum->gadget.dev);
return rc;
}
static int dummy_udc_remove (struct platform_device *pdev)
{
struct dummy *dum = platform_get_drvdata (pdev);
usb_del_gadget_udc(&dum->gadget);
platform_set_drvdata (pdev, NULL);
device_remove_file (&dum->gadget.dev, &dev_attr_function);
device_unregister (&dum->gadget.dev);
return 0;
}
static void dummy_udc_pm(struct dummy *dum, struct dummy_hcd *dum_hcd,
int suspend)
{
spin_lock_irq(&dum->lock);
dum->udc_suspended = suspend;
set_link_state(dum_hcd);
spin_unlock_irq(&dum->lock);
}
static int dummy_udc_suspend(struct platform_device *pdev, pm_message_t state)
{
struct dummy *dum = platform_get_drvdata(pdev);
struct dummy_hcd *dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
dev_dbg(&pdev->dev, "%s\n", __func__);
dummy_udc_pm(dum, dum_hcd, 1);
usb_hcd_poll_rh_status(dummy_hcd_to_hcd(dum_hcd));
return 0;
}
static int dummy_udc_resume(struct platform_device *pdev)
{
struct dummy *dum = platform_get_drvdata(pdev);
struct dummy_hcd *dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
dev_dbg(&pdev->dev, "%s\n", __func__);
dummy_udc_pm(dum, dum_hcd, 0);
usb_hcd_poll_rh_status(dummy_hcd_to_hcd(dum_hcd));
return 0;
}
static struct platform_driver dummy_udc_driver = {
.probe = dummy_udc_probe,
.remove = dummy_udc_remove,
.suspend = dummy_udc_suspend,
.resume = dummy_udc_resume,
.driver = {
.name = (char *) gadget_name,
.owner = THIS_MODULE,
},
};
/*-------------------------------------------------------------------------*/
/* MASTER/HOST SIDE DRIVER
*
* this uses the hcd framework to hook up to host side drivers.
* its root hub will only have one device, otherwise it acts like
* a normal host controller.
*
* when urbs are queued, they're just stuck on a list that we
* scan in a timer callback. that callback connects writes from
* the host with reads from the device, and so on, based on the
* usb 2.0 rules.
*/
static int dummy_urb_enqueue (
struct usb_hcd *hcd,
struct urb *urb,
gfp_t mem_flags
) {
struct dummy_hcd *dum_hcd;
struct urbp *urbp;
unsigned long flags;
int rc;
if (!urb->transfer_buffer && urb->transfer_buffer_length)
return -EINVAL;
urbp = kmalloc (sizeof *urbp, mem_flags);
if (!urbp)
return -ENOMEM;
urbp->urb = urb;
dum_hcd = hcd_to_dummy_hcd(hcd);
spin_lock_irqsave(&dum_hcd->dum->lock, flags);
rc = usb_hcd_link_urb_to_ep(hcd, urb);
if (rc) {
kfree(urbp);
goto done;
}
if (!dum_hcd->udev) {
dum_hcd->udev = urb->dev;
usb_get_dev(dum_hcd->udev);
} else if (unlikely(dum_hcd->udev != urb->dev))
dev_err(dummy_dev(dum_hcd), "usb_device address has changed!\n");
list_add_tail(&urbp->urbp_list, &dum_hcd->urbp_list);
urb->hcpriv = urbp;
if (usb_pipetype (urb->pipe) == PIPE_CONTROL)
urb->error_count = 1; /* mark as a new urb */
/* kick the scheduler, it'll do the rest */
if (!timer_pending(&dum_hcd->timer))
mod_timer(&dum_hcd->timer, jiffies + 1);
done:
spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
return rc;
}
static int dummy_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
{
struct dummy_hcd *dum_hcd;
unsigned long flags;
int rc;
/* giveback happens automatically in timer callback,
* so make sure the callback happens */
dum_hcd = hcd_to_dummy_hcd(hcd);
spin_lock_irqsave(&dum_hcd->dum->lock, flags);
rc = usb_hcd_check_unlink_urb(hcd, urb, status);
if (!rc && dum_hcd->rh_state != DUMMY_RH_RUNNING &&
!list_empty(&dum_hcd->urbp_list))
mod_timer(&dum_hcd->timer, jiffies);
spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
return rc;
}
/* transfer up to a frame's worth; caller must own lock */
static int
transfer(struct dummy *dum, struct urb *urb, struct dummy_ep *ep, int limit,
int *status)
{
struct dummy_request *req;
top:
/* if there's no request queued, the device is NAKing; return */
list_for_each_entry (req, &ep->queue, queue) {
unsigned host_len, dev_len, len;
int is_short, to_host;
int rescan = 0;
/* 1..N packets of ep->ep.maxpacket each ... the last one
* may be short (including zero length).
*
* writer can send a zlp explicitly (length 0) or implicitly
* (length mod maxpacket zero, and 'zero' flag); they always
* terminate reads.
*/
host_len = urb->transfer_buffer_length - urb->actual_length;
dev_len = req->req.length - req->req.actual;
len = min (host_len, dev_len);
/* FIXME update emulated data toggle too */
to_host = usb_pipein (urb->pipe);
if (unlikely (len == 0))
is_short = 1;
else {
char *ubuf, *rbuf;
/* not enough bandwidth left? */
if (limit < ep->ep.maxpacket && limit < len)
break;
len = min (len, (unsigned) limit);
if (len == 0)
break;
/* use an extra pass for the final short packet */
if (len > ep->ep.maxpacket) {
rescan = 1;
len -= (len % ep->ep.maxpacket);
}
is_short = (len % ep->ep.maxpacket) != 0;
/* else transfer packet(s) */
ubuf = urb->transfer_buffer + urb->actual_length;
rbuf = req->req.buf + req->req.actual;
if (to_host)
memcpy (ubuf, rbuf, len);
else
memcpy (rbuf, ubuf, len);
ep->last_io = jiffies;
limit -= len;
urb->actual_length += len;
req->req.actual += len;
}
/* short packets terminate, maybe with overflow/underflow.
* it's only really an error to write too much.
*
* partially filling a buffer optionally blocks queue advances
* (so completion handlers can clean up the queue) but we don't
* need to emulate such data-in-flight.
*/
if (is_short) {
if (host_len == dev_len) {
req->req.status = 0;
*status = 0;
} else if (to_host) {
req->req.status = 0;
if (dev_len > host_len)
*status = -EOVERFLOW;
else
*status = 0;
} else if (!to_host) {
*status = 0;
if (host_len > dev_len)
req->req.status = -EOVERFLOW;
else
req->req.status = 0;
}
/* many requests terminate without a short packet */
} else {
if (req->req.length == req->req.actual
&& !req->req.zero)
req->req.status = 0;
if (urb->transfer_buffer_length == urb->actual_length
&& !(urb->transfer_flags
& URB_ZERO_PACKET))
*status = 0;
}
/* device side completion --> continuable */
if (req->req.status != -EINPROGRESS) {
list_del_init (&req->queue);
spin_unlock (&dum->lock);
req->req.complete (&ep->ep, &req->req);
spin_lock (&dum->lock);
/* requests might have been unlinked... */
rescan = 1;
}
/* host side completion --> terminate */
if (*status != -EINPROGRESS)
break;
/* rescan to continue with any other queued i/o */
if (rescan)
goto top;
}
return limit;
}
static int periodic_bytes (struct dummy *dum, struct dummy_ep *ep)
{
int limit = ep->ep.maxpacket;
if (dum->gadget.speed == USB_SPEED_HIGH) {
int tmp;
/* high bandwidth mode */
tmp = usb_endpoint_maxp(ep->desc);
tmp = (tmp >> 11) & 0x03;
tmp *= 8 /* applies to entire frame */;
limit += limit * tmp;
}
if (dum->gadget.speed == USB_SPEED_SUPER) {
switch (ep->desc->bmAttributes & 0x03) {
case USB_ENDPOINT_XFER_ISOC:
/* Sec. 4.4.8.2 USB3.0 Spec */
limit = 3 * 16 * 1024 * 8;
break;
case USB_ENDPOINT_XFER_INT:
/* Sec. 4.4.7.2 USB3.0 Spec */
limit = 3 * 1024 * 8;
break;
case USB_ENDPOINT_XFER_BULK:
default:
break;
}
}
return limit;
}
#define is_active(dum_hcd) ((dum_hcd->port_status & \
(USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE | \
USB_PORT_STAT_SUSPEND)) \
== (USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE))
static struct dummy_ep *find_endpoint (struct dummy *dum, u8 address)
{
int i;
if (!is_active((dum->gadget.speed == USB_SPEED_SUPER ?
dum->ss_hcd : dum->hs_hcd)))
return NULL;
if ((address & ~USB_DIR_IN) == 0)
return &dum->ep [0];
for (i = 1; i < DUMMY_ENDPOINTS; i++) {
struct dummy_ep *ep = &dum->ep [i];
if (!ep->desc)
continue;
if (ep->desc->bEndpointAddress == address)
return ep;
}
return NULL;
}
#undef is_active
#define Dev_Request (USB_TYPE_STANDARD | USB_RECIP_DEVICE)
#define Dev_InRequest (Dev_Request | USB_DIR_IN)
#define Intf_Request (USB_TYPE_STANDARD | USB_RECIP_INTERFACE)
#define Intf_InRequest (Intf_Request | USB_DIR_IN)
#define Ep_Request (USB_TYPE_STANDARD | USB_RECIP_ENDPOINT)
#define Ep_InRequest (Ep_Request | USB_DIR_IN)
/**
* handle_control_request() - handles all control transfers
* @dum: pointer to dummy (the_controller)
* @urb: the urb request to handle
* @setup: pointer to the setup data for a USB device control
* request
* @status: pointer to request handling status
*
* Return 0 - if the request was handled
* 1 - if the request wasn't handles
* error code on error
*/
static int handle_control_request(struct dummy_hcd *dum_hcd, struct urb *urb,
struct usb_ctrlrequest *setup,
int *status)
{
struct dummy_ep *ep2;
struct dummy *dum = dum_hcd->dum;
int ret_val = 1;
unsigned w_index;
unsigned w_value;
w_index = le16_to_cpu(setup->wIndex);
w_value = le16_to_cpu(setup->wValue);
switch (setup->bRequest) {
case USB_REQ_SET_ADDRESS:
if (setup->bRequestType != Dev_Request)
break;
dum->address = w_value;
*status = 0;
dev_dbg(udc_dev(dum), "set_address = %d\n",
w_value);
ret_val = 0;
break;
case USB_REQ_SET_FEATURE:
if (setup->bRequestType == Dev_Request) {
ret_val = 0;
switch (w_value) {
case USB_DEVICE_REMOTE_WAKEUP:
break;
case USB_DEVICE_B_HNP_ENABLE:
dum->gadget.b_hnp_enable = 1;
break;
case USB_DEVICE_A_HNP_SUPPORT:
dum->gadget.a_hnp_support = 1;
break;
case USB_DEVICE_A_ALT_HNP_SUPPORT:
dum->gadget.a_alt_hnp_support = 1;
break;
case USB_DEVICE_U1_ENABLE:
if (dummy_hcd_to_hcd(dum_hcd)->speed ==
HCD_USB3)
w_value = USB_DEV_STAT_U1_ENABLED;
else
ret_val = -EOPNOTSUPP;
break;
case USB_DEVICE_U2_ENABLE:
if (dummy_hcd_to_hcd(dum_hcd)->speed ==
HCD_USB3)
w_value = USB_DEV_STAT_U2_ENABLED;
else
ret_val = -EOPNOTSUPP;
break;
case USB_DEVICE_LTM_ENABLE:
if (dummy_hcd_to_hcd(dum_hcd)->speed ==
HCD_USB3)
w_value = USB_DEV_STAT_LTM_ENABLED;
else
ret_val = -EOPNOTSUPP;
break;
default:
ret_val = -EOPNOTSUPP;
}
if (ret_val == 0) {
dum->devstatus |= (1 << w_value);
*status = 0;
}
} else if (setup->bRequestType == Ep_Request) {
/* endpoint halt */
ep2 = find_endpoint(dum, w_index);
if (!ep2 || ep2->ep.name == ep0name) {
ret_val = -EOPNOTSUPP;
break;
}
ep2->halted = 1;
ret_val = 0;
*status = 0;
}
break;
case USB_REQ_CLEAR_FEATURE:
if (setup->bRequestType == Dev_Request) {
ret_val = 0;
switch (w_value) {
case USB_DEVICE_REMOTE_WAKEUP:
w_value = USB_DEVICE_REMOTE_WAKEUP;
break;
case USB_DEVICE_U1_ENABLE:
if (dummy_hcd_to_hcd(dum_hcd)->speed ==
HCD_USB3)
w_value = USB_DEV_STAT_U1_ENABLED;
else
ret_val = -EOPNOTSUPP;
break;
case USB_DEVICE_U2_ENABLE:
if (dummy_hcd_to_hcd(dum_hcd)->speed ==
HCD_USB3)
w_value = USB_DEV_STAT_U2_ENABLED;
else
ret_val = -EOPNOTSUPP;
break;
case USB_DEVICE_LTM_ENABLE:
if (dummy_hcd_to_hcd(dum_hcd)->speed ==
HCD_USB3)
w_value = USB_DEV_STAT_LTM_ENABLED;
else
ret_val = -EOPNOTSUPP;
break;
default:
ret_val = -EOPNOTSUPP;
break;
}
if (ret_val == 0) {
dum->devstatus &= ~(1 << w_value);
*status = 0;
}
} else if (setup->bRequestType == Ep_Request) {
/* endpoint halt */
ep2 = find_endpoint(dum, w_index);
if (!ep2) {
ret_val = -EOPNOTSUPP;
break;
}
if (!ep2->wedged)
ep2->halted = 0;
ret_val = 0;
*status = 0;
}
break;
case USB_REQ_GET_STATUS:
if (setup->bRequestType == Dev_InRequest
|| setup->bRequestType == Intf_InRequest
|| setup->bRequestType == Ep_InRequest) {
char *buf;
/*
* device: remote wakeup, selfpowered
* interface: nothing
* endpoint: halt
*/
buf = (char *)urb->transfer_buffer;
if (urb->transfer_buffer_length > 0) {
if (setup->bRequestType == Ep_InRequest) {
ep2 = find_endpoint(dum, w_index);
if (!ep2) {
ret_val = -EOPNOTSUPP;
break;
}
buf[0] = ep2->halted;
} else if (setup->bRequestType ==
Dev_InRequest) {
buf[0] = (u8)dum->devstatus;
} else
buf[0] = 0;
}
if (urb->transfer_buffer_length > 1)
buf[1] = 0;
urb->actual_length = min_t(u32, 2,
urb->transfer_buffer_length);
ret_val = 0;
*status = 0;
}
break;
}
return ret_val;
}
/* drive both sides of the transfers; looks like irq handlers to
* both drivers except the callbacks aren't in_irq().
*/
static void dummy_timer(unsigned long _dum_hcd)
{
struct dummy_hcd *dum_hcd = (struct dummy_hcd *) _dum_hcd;
struct dummy *dum = dum_hcd->dum;
struct urbp *urbp, *tmp;
unsigned long flags;
int limit, total;
int i;
/* simplistic model for one frame's bandwidth */
switch (dum->gadget.speed) {
case USB_SPEED_LOW:
total = 8/*bytes*/ * 12/*packets*/;
break;
case USB_SPEED_FULL:
total = 64/*bytes*/ * 19/*packets*/;
break;
case USB_SPEED_HIGH:
total = 512/*bytes*/ * 13/*packets*/ * 8/*uframes*/;
break;
case USB_SPEED_SUPER:
/* Bus speed is 500000 bytes/ms, so use a little less */
total = 490000;
break;
default:
dev_err(dummy_dev(dum_hcd), "bogus device speed\n");
return;
}
/* FIXME if HZ != 1000 this will probably misbehave ... */
/* look at each urb queued by the host side driver */
spin_lock_irqsave (&dum->lock, flags);
if (!dum_hcd->udev) {
dev_err(dummy_dev(dum_hcd),
"timer fired with no URBs pending?\n");
spin_unlock_irqrestore (&dum->lock, flags);
return;
}
for (i = 0; i < DUMMY_ENDPOINTS; i++) {
if (!ep_name [i])
break;
dum->ep [i].already_seen = 0;
}
restart:
list_for_each_entry_safe(urbp, tmp, &dum_hcd->urbp_list, urbp_list) {
struct urb *urb;
struct dummy_request *req;
u8 address;
struct dummy_ep *ep = NULL;
int type;
int status = -EINPROGRESS;
urb = urbp->urb;
if (urb->unlinked)
goto return_urb;
else if (dum_hcd->rh_state != DUMMY_RH_RUNNING)
continue;
type = usb_pipetype (urb->pipe);
/* used up this frame's non-periodic bandwidth?
* FIXME there's infinite bandwidth for control and
* periodic transfers ... unrealistic.
*/
if (total <= 0 && type == PIPE_BULK)
continue;
/* find the gadget's ep for this request (if configured) */
address = usb_pipeendpoint (urb->pipe);
if (usb_pipein (urb->pipe))
address |= USB_DIR_IN;
ep = find_endpoint(dum, address);
if (!ep) {
/* set_configuration() disagreement */
dev_dbg(dummy_dev(dum_hcd),
"no ep configured for urb %p\n",
urb);
status = -EPROTO;
goto return_urb;
}
if (ep->already_seen)
continue;
ep->already_seen = 1;
if (ep == &dum->ep [0] && urb->error_count) {
ep->setup_stage = 1; /* a new urb */
urb->error_count = 0;
}
if (ep->halted && !ep->setup_stage) {
/* NOTE: must not be iso! */
dev_dbg(dummy_dev(dum_hcd), "ep %s halted, urb %p\n",
ep->ep.name, urb);
status = -EPIPE;
goto return_urb;
}
/* FIXME make sure both ends agree on maxpacket */
/* handle control requests */
if (ep == &dum->ep [0] && ep->setup_stage) {
struct usb_ctrlrequest setup;
int value = 1;
setup = *(struct usb_ctrlrequest*) urb->setup_packet;
/* paranoia, in case of stale queued data */
list_for_each_entry (req, &ep->queue, queue) {
list_del_init (&req->queue);
req->req.status = -EOVERFLOW;
dev_dbg (udc_dev(dum), "stale req = %p\n",
req);
spin_unlock (&dum->lock);
req->req.complete (&ep->ep, &req->req);
spin_lock (&dum->lock);
ep->already_seen = 0;
goto restart;
}
/* gadget driver never sees set_address or operations
* on standard feature flags. some hardware doesn't
* even expose them.
*/
ep->last_io = jiffies;
ep->setup_stage = 0;
ep->halted = 0;
value = handle_control_request(dum_hcd, urb, &setup,
&status);
/* gadget driver handles all other requests. block
* until setup() returns; no reentrancy issues etc.
*/
if (value > 0) {
spin_unlock (&dum->lock);
value = dum->driver->setup (&dum->gadget,
&setup);
spin_lock (&dum->lock);
if (value >= 0) {
/* no delays (max 64KB data stage) */
limit = 64*1024;
goto treat_control_like_bulk;
}
/* error, see below */
}
if (value < 0) {
if (value != -EOPNOTSUPP)
dev_dbg (udc_dev(dum),
"setup --> %d\n",
value);
status = -EPIPE;
urb->actual_length = 0;
}
goto return_urb;
}
/* non-control requests */
limit = total;
switch (usb_pipetype (urb->pipe)) {
case PIPE_ISOCHRONOUS:
/* FIXME is it urb->interval since the last xfer?
* use urb->iso_frame_desc[i].
* complete whether or not ep has requests queued.
* report random errors, to debug drivers.
*/
limit = max (limit, periodic_bytes (dum, ep));
status = -ENOSYS;
break;
case PIPE_INTERRUPT:
/* FIXME is it urb->interval since the last xfer?
* this almost certainly polls too fast.
*/
limit = max (limit, periodic_bytes (dum, ep));
/* FALLTHROUGH */
// case PIPE_BULK: case PIPE_CONTROL:
default:
treat_control_like_bulk:
ep->last_io = jiffies;
total = transfer(dum, urb, ep, limit, &status);
break;
}
/* incomplete transfer? */
if (status == -EINPROGRESS)
continue;
return_urb:
list_del (&urbp->urbp_list);
kfree (urbp);
if (ep)
ep->already_seen = ep->setup_stage = 0;
usb_hcd_unlink_urb_from_ep(dummy_hcd_to_hcd(dum_hcd), urb);
spin_unlock (&dum->lock);
usb_hcd_giveback_urb(dummy_hcd_to_hcd(dum_hcd), urb, status);
spin_lock (&dum->lock);
goto restart;
}
if (list_empty(&dum_hcd->urbp_list)) {
usb_put_dev(dum_hcd->udev);
dum_hcd->udev = NULL;
} else if (dum_hcd->rh_state == DUMMY_RH_RUNNING) {
/* want a 1 msec delay here */
mod_timer(&dum_hcd->timer, jiffies + msecs_to_jiffies(1));
}
spin_unlock_irqrestore (&dum->lock, flags);
}
/*-------------------------------------------------------------------------*/
#define PORT_C_MASK \
((USB_PORT_STAT_C_CONNECTION \
| USB_PORT_STAT_C_ENABLE \
| USB_PORT_STAT_C_SUSPEND \
| USB_PORT_STAT_C_OVERCURRENT \
| USB_PORT_STAT_C_RESET) << 16)
static int dummy_hub_status (struct usb_hcd *hcd, char *buf)
{
struct dummy_hcd *dum_hcd;
unsigned long flags;
int retval = 0;
dum_hcd = hcd_to_dummy_hcd(hcd);
spin_lock_irqsave(&dum_hcd->dum->lock, flags);
if (!HCD_HW_ACCESSIBLE(hcd))
goto done;
if (dum_hcd->resuming && time_after_eq(jiffies, dum_hcd->re_timeout)) {
dum_hcd->port_status |= (USB_PORT_STAT_C_SUSPEND << 16);
dum_hcd->port_status &= ~USB_PORT_STAT_SUSPEND;
set_link_state(dum_hcd);
}
if ((dum_hcd->port_status & PORT_C_MASK) != 0) {
*buf = (1 << 1);
dev_dbg(dummy_dev(dum_hcd), "port status 0x%08x has changes\n",
dum_hcd->port_status);
retval = 1;
if (dum_hcd->rh_state == DUMMY_RH_SUSPENDED)
usb_hcd_resume_root_hub (hcd);
}
done:
spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
return retval;
}
static inline void
ss_hub_descriptor(struct usb_hub_descriptor *desc)
{
memset(desc, 0, sizeof *desc);
desc->bDescriptorType = 0x2a;
desc->bDescLength = 12;
desc->wHubCharacteristics = cpu_to_le16(0x0001);
desc->bNbrPorts = 1;
desc->u.ss.bHubHdrDecLat = 0x04; /* Worst case: 0.4 micro sec*/
desc->u.ss.DeviceRemovable = 0xffff;
}
static inline void
hub_descriptor (struct usb_hub_descriptor *desc)
{
memset (desc, 0, sizeof *desc);
desc->bDescriptorType = 0x29;
desc->bDescLength = 9;
desc->wHubCharacteristics = cpu_to_le16(0x0001);
desc->bNbrPorts = 1;
desc->u.hs.DeviceRemovable[0] = 0xff;
desc->u.hs.DeviceRemovable[1] = 0xff;
}
static int dummy_hub_control (
struct usb_hcd *hcd,
u16 typeReq,
u16 wValue,
u16 wIndex,
char *buf,
u16 wLength
) {
struct dummy_hcd *dum_hcd;
int retval = 0;
unsigned long flags;
if (!HCD_HW_ACCESSIBLE(hcd))
return -ETIMEDOUT;
dum_hcd = hcd_to_dummy_hcd(hcd);
spin_lock_irqsave(&dum_hcd->dum->lock, flags);
switch (typeReq) {
case ClearHubFeature:
break;
case ClearPortFeature:
switch (wValue) {
case USB_PORT_FEAT_SUSPEND:
if (hcd->speed == HCD_USB3) {
dev_dbg(dummy_dev(dum_hcd),
"USB_PORT_FEAT_SUSPEND req not "
"supported for USB 3.0 roothub\n");
goto error;
}
if (dum_hcd->port_status & USB_PORT_STAT_SUSPEND) {
/* 20msec resume signaling */
dum_hcd->resuming = 1;
dum_hcd->re_timeout = jiffies +
msecs_to_jiffies(20);
}
break;
case USB_PORT_FEAT_POWER:
if (hcd->speed == HCD_USB3) {
if (dum_hcd->port_status & USB_PORT_STAT_POWER)
dev_dbg(dummy_dev(dum_hcd),
"power-off\n");
} else
if (dum_hcd->port_status &
USB_SS_PORT_STAT_POWER)
dev_dbg(dummy_dev(dum_hcd),
"power-off\n");
/* FALLS THROUGH */
default:
dum_hcd->port_status &= ~(1 << wValue);
set_link_state(dum_hcd);
}
break;
case GetHubDescriptor:
if (hcd->speed == HCD_USB3 &&
(wLength < USB_DT_SS_HUB_SIZE ||
wValue != (USB_DT_SS_HUB << 8))) {
dev_dbg(dummy_dev(dum_hcd),
"Wrong hub descriptor type for "
"USB 3.0 roothub.\n");
goto error;
}
if (hcd->speed == HCD_USB3)
ss_hub_descriptor((struct usb_hub_descriptor *) buf);
else
hub_descriptor((struct usb_hub_descriptor *) buf);
break;
case GetHubStatus:
*(__le32 *) buf = cpu_to_le32 (0);
break;
case GetPortStatus:
if (wIndex != 1)
retval = -EPIPE;
/* whoever resets or resumes must GetPortStatus to
* complete it!!
*/
if (dum_hcd->resuming &&
time_after_eq(jiffies, dum_hcd->re_timeout)) {
dum_hcd->port_status |= (USB_PORT_STAT_C_SUSPEND << 16);
dum_hcd->port_status &= ~USB_PORT_STAT_SUSPEND;
}
if ((dum_hcd->port_status & USB_PORT_STAT_RESET) != 0 &&
time_after_eq(jiffies, dum_hcd->re_timeout)) {
dum_hcd->port_status |= (USB_PORT_STAT_C_RESET << 16);
dum_hcd->port_status &= ~USB_PORT_STAT_RESET;
if (dum_hcd->dum->pullup) {
dum_hcd->port_status |= USB_PORT_STAT_ENABLE;
if (hcd->speed < HCD_USB3) {
switch (dum_hcd->dum->gadget.speed) {
case USB_SPEED_HIGH:
dum_hcd->port_status |=
USB_PORT_STAT_HIGH_SPEED;
break;
case USB_SPEED_LOW:
dum_hcd->dum->gadget.ep0->
maxpacket = 8;
dum_hcd->port_status |=
USB_PORT_STAT_LOW_SPEED;
break;
default:
dum_hcd->dum->gadget.speed =
USB_SPEED_FULL;
break;
}
}
}
}
set_link_state(dum_hcd);
((__le16 *) buf)[0] = cpu_to_le16 (dum_hcd->port_status);
((__le16 *) buf)[1] = cpu_to_le16 (dum_hcd->port_status >> 16);
break;
case SetHubFeature:
retval = -EPIPE;
break;
case SetPortFeature:
switch (wValue) {
case USB_PORT_FEAT_LINK_STATE:
if (hcd->speed != HCD_USB3) {
dev_dbg(dummy_dev(dum_hcd),
"USB_PORT_FEAT_LINK_STATE req not "
"supported for USB 2.0 roothub\n");
goto error;
}
/*
* Since this is dummy we don't have an actual link so
* there is nothing to do for the SET_LINK_STATE cmd
*/
break;
case USB_PORT_FEAT_U1_TIMEOUT:
case USB_PORT_FEAT_U2_TIMEOUT:
/* TODO: add suspend/resume support! */
if (hcd->speed != HCD_USB3) {
dev_dbg(dummy_dev(dum_hcd),
"USB_PORT_FEAT_U1/2_TIMEOUT req not "
"supported for USB 2.0 roothub\n");
goto error;
}
break;
case USB_PORT_FEAT_SUSPEND:
/* Applicable only for USB2.0 hub */
if (hcd->speed == HCD_USB3) {
dev_dbg(dummy_dev(dum_hcd),
"USB_PORT_FEAT_SUSPEND req not "
"supported for USB 3.0 roothub\n");
goto error;
}
if (dum_hcd->active) {
dum_hcd->port_status |= USB_PORT_STAT_SUSPEND;
/* HNP would happen here; for now we
* assume b_bus_req is always true.
*/
set_link_state(dum_hcd);
if (((1 << USB_DEVICE_B_HNP_ENABLE)
& dum_hcd->dum->devstatus) != 0)
dev_dbg(dummy_dev(dum_hcd),
"no HNP yet!\n");
}
break;
case USB_PORT_FEAT_POWER:
if (hcd->speed == HCD_USB3)
dum_hcd->port_status |= USB_SS_PORT_STAT_POWER;
else
dum_hcd->port_status |= USB_PORT_STAT_POWER;
set_link_state(dum_hcd);
break;
case USB_PORT_FEAT_BH_PORT_RESET:
/* Applicable only for USB3.0 hub */
if (hcd->speed != HCD_USB3) {
dev_dbg(dummy_dev(dum_hcd),
"USB_PORT_FEAT_BH_PORT_RESET req not "
"supported for USB 2.0 roothub\n");
goto error;
}
/* FALLS THROUGH */
case USB_PORT_FEAT_RESET:
/* if it's already enabled, disable */
if (hcd->speed == HCD_USB3) {
dum_hcd->port_status = 0;
dum_hcd->port_status =
(USB_SS_PORT_STAT_POWER |
USB_PORT_STAT_CONNECTION |
USB_PORT_STAT_RESET);
} else
dum_hcd->port_status &= ~(USB_PORT_STAT_ENABLE
| USB_PORT_STAT_LOW_SPEED
| USB_PORT_STAT_HIGH_SPEED);
/*
* We want to reset device status. All but the
* Self powered feature
*/
dum_hcd->dum->devstatus &=
(1 << USB_DEVICE_SELF_POWERED);
/*
* FIXME USB3.0: what is the correct reset signaling
* interval? Is it still 50msec as for HS?
*/
dum_hcd->re_timeout = jiffies + msecs_to_jiffies(50);
/* FALLS THROUGH */
default:
if (hcd->speed == HCD_USB3) {
if ((dum_hcd->port_status &
USB_SS_PORT_STAT_POWER) != 0) {
dum_hcd->port_status |= (1 << wValue);
set_link_state(dum_hcd);
}
} else
if ((dum_hcd->port_status &
USB_PORT_STAT_POWER) != 0) {
dum_hcd->port_status |= (1 << wValue);
set_link_state(dum_hcd);
}
}
break;
case GetPortErrorCount:
if (hcd->speed != HCD_USB3) {
dev_dbg(dummy_dev(dum_hcd),
"GetPortErrorCount req not "
"supported for USB 2.0 roothub\n");
goto error;
}
/* We'll always return 0 since this is a dummy hub */
*(__le32 *) buf = cpu_to_le32(0);
break;
case SetHubDepth:
if (hcd->speed != HCD_USB3) {
dev_dbg(dummy_dev(dum_hcd),
"SetHubDepth req not supported for "
"USB 2.0 roothub\n");
goto error;
}
break;
default:
dev_dbg(dummy_dev(dum_hcd),
"hub control req%04x v%04x i%04x l%d\n",
typeReq, wValue, wIndex, wLength);
error:
/* "protocol stall" on error */
retval = -EPIPE;
}
spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
if ((dum_hcd->port_status & PORT_C_MASK) != 0)
usb_hcd_poll_rh_status (hcd);
return retval;
}
static int dummy_bus_suspend (struct usb_hcd *hcd)
{
struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
dev_dbg (&hcd->self.root_hub->dev, "%s\n", __func__);
spin_lock_irq(&dum_hcd->dum->lock);
dum_hcd->rh_state = DUMMY_RH_SUSPENDED;
set_link_state(dum_hcd);
hcd->state = HC_STATE_SUSPENDED;
spin_unlock_irq(&dum_hcd->dum->lock);
return 0;
}
static int dummy_bus_resume (struct usb_hcd *hcd)
{
struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
int rc = 0;
dev_dbg (&hcd->self.root_hub->dev, "%s\n", __func__);
spin_lock_irq(&dum_hcd->dum->lock);
if (!HCD_HW_ACCESSIBLE(hcd)) {
rc = -ESHUTDOWN;
} else {
dum_hcd->rh_state = DUMMY_RH_RUNNING;
set_link_state(dum_hcd);
if (!list_empty(&dum_hcd->urbp_list))
mod_timer(&dum_hcd->timer, jiffies);
hcd->state = HC_STATE_RUNNING;
}
spin_unlock_irq(&dum_hcd->dum->lock);
return rc;
}
/*-------------------------------------------------------------------------*/
static inline ssize_t
show_urb (char *buf, size_t size, struct urb *urb)
{
int ep = usb_pipeendpoint (urb->pipe);
return snprintf (buf, size,
"urb/%p %s ep%d%s%s len %d/%d\n",
urb,
({ char *s;
switch (urb->dev->speed) {
case USB_SPEED_LOW:
s = "ls";
break;
case USB_SPEED_FULL:
s = "fs";
break;
case USB_SPEED_HIGH:
s = "hs";
break;
case USB_SPEED_SUPER:
s = "ss";
break;
default:
s = "?";
break;
}; s; }),
ep, ep ? (usb_pipein (urb->pipe) ? "in" : "out") : "",
({ char *s; \
switch (usb_pipetype (urb->pipe)) { \
case PIPE_CONTROL: \
s = ""; \
break; \
case PIPE_BULK: \
s = "-bulk"; \
break; \
case PIPE_INTERRUPT: \
s = "-int"; \
break; \
default: \
s = "-iso"; \
break; \
}; s;}),
urb->actual_length, urb->transfer_buffer_length);
}
static ssize_t
show_urbs (struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_hcd *hcd = dev_get_drvdata (dev);
struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
struct urbp *urbp;
size_t size = 0;
unsigned long flags;
spin_lock_irqsave(&dum_hcd->dum->lock, flags);
list_for_each_entry(urbp, &dum_hcd->urbp_list, urbp_list) {
size_t temp;
temp = show_urb (buf, PAGE_SIZE - size, urbp->urb);
buf += temp;
size += temp;
}
spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
return size;
}
static DEVICE_ATTR (urbs, S_IRUGO, show_urbs, NULL);
static int dummy_start_ss(struct dummy_hcd *dum_hcd)
{
init_timer(&dum_hcd->timer);
dum_hcd->timer.function = dummy_timer;
dum_hcd->timer.data = (unsigned long)dum_hcd;
dum_hcd->rh_state = DUMMY_RH_RUNNING;
INIT_LIST_HEAD(&dum_hcd->urbp_list);
dummy_hcd_to_hcd(dum_hcd)->power_budget = POWER_BUDGET;
dummy_hcd_to_hcd(dum_hcd)->state = HC_STATE_RUNNING;
dummy_hcd_to_hcd(dum_hcd)->uses_new_polling = 1;
#ifdef CONFIG_USB_OTG
dummy_hcd_to_hcd(dum_hcd)->self.otg_port = 1;
#endif
return 0;
/* FIXME 'urbs' should be a per-device thing, maybe in usbcore */
return device_create_file(dummy_dev(dum_hcd), &dev_attr_urbs);
}
static int dummy_start(struct usb_hcd *hcd)
{
struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
/*
* MASTER side init ... we emulate a root hub that'll only ever
* talk to one device (the slave side). Also appears in sysfs,
* just like more familiar pci-based HCDs.
*/
if (!usb_hcd_is_primary_hcd(hcd))
return dummy_start_ss(dum_hcd);
spin_lock_init(&dum_hcd->dum->lock);
init_timer(&dum_hcd->timer);
dum_hcd->timer.function = dummy_timer;
dum_hcd->timer.data = (unsigned long)dum_hcd;
dum_hcd->rh_state = DUMMY_RH_RUNNING;
INIT_LIST_HEAD(&dum_hcd->urbp_list);
hcd->power_budget = POWER_BUDGET;
hcd->state = HC_STATE_RUNNING;
hcd->uses_new_polling = 1;
#ifdef CONFIG_USB_OTG
hcd->self.otg_port = 1;
#endif
/* FIXME 'urbs' should be a per-device thing, maybe in usbcore */
return device_create_file(dummy_dev(dum_hcd), &dev_attr_urbs);
}
static void dummy_stop (struct usb_hcd *hcd)
{
struct dummy *dum;
dum = (hcd_to_dummy_hcd(hcd))->dum;
device_remove_file(dummy_dev(hcd_to_dummy_hcd(hcd)), &dev_attr_urbs);
usb_gadget_unregister_driver(dum->driver);
dev_info(dummy_dev(hcd_to_dummy_hcd(hcd)), "stopped\n");
}
/*-------------------------------------------------------------------------*/
static int dummy_h_get_frame (struct usb_hcd *hcd)
{
return dummy_g_get_frame (NULL);
}
static int dummy_setup(struct usb_hcd *hcd)
{
if (usb_hcd_is_primary_hcd(hcd)) {
the_controller.hs_hcd = hcd_to_dummy_hcd(hcd);
the_controller.hs_hcd->dum = &the_controller;
/*
* Mark the first roothub as being USB 2.0.
* The USB 3.0 roothub will be registered later by
* dummy_hcd_probe()
*/
hcd->speed = HCD_USB2;
hcd->self.root_hub->speed = USB_SPEED_HIGH;
} else {
the_controller.ss_hcd = hcd_to_dummy_hcd(hcd);
the_controller.ss_hcd->dum = &the_controller;
hcd->speed = HCD_USB3;
hcd->self.root_hub->speed = USB_SPEED_SUPER;
}
return 0;
}
/* Change a group of bulk endpoints to support multiple stream IDs */
int dummy_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
struct usb_host_endpoint **eps, unsigned int num_eps,
unsigned int num_streams, gfp_t mem_flags)
{
if (hcd->speed != HCD_USB3)
dev_dbg(dummy_dev(hcd_to_dummy_hcd(hcd)),
"%s() - ERROR! Not supported for USB2.0 roothub\n",
__func__);
return 0;
}
/* Reverts a group of bulk endpoints back to not using stream IDs. */
int dummy_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
struct usb_host_endpoint **eps, unsigned int num_eps,
gfp_t mem_flags)
{
if (hcd->speed != HCD_USB3)
dev_dbg(dummy_dev(hcd_to_dummy_hcd(hcd)),
"%s() - ERROR! Not supported for USB2.0 roothub\n",
__func__);
return 0;
}
static struct hc_driver dummy_hcd = {
.description = (char *) driver_name,
.product_desc = "Dummy host controller",
.hcd_priv_size = sizeof(struct dummy_hcd),
.flags = HCD_USB3 | HCD_SHARED,
.reset = dummy_setup,
.start = dummy_start,
.stop = dummy_stop,
.urb_enqueue = dummy_urb_enqueue,
.urb_dequeue = dummy_urb_dequeue,
.get_frame_number = dummy_h_get_frame,
.hub_status_data = dummy_hub_status,
.hub_control = dummy_hub_control,
.bus_suspend = dummy_bus_suspend,
.bus_resume = dummy_bus_resume,
.alloc_streams = dummy_alloc_streams,
.free_streams = dummy_free_streams,
};
static int dummy_hcd_probe(struct platform_device *pdev)
{
struct usb_hcd *hs_hcd;
struct usb_hcd *ss_hcd;
int retval;
dev_info(&pdev->dev, "%s, driver " DRIVER_VERSION "\n", driver_desc);
if (!mod_data.is_super_speed)
dummy_hcd.flags = HCD_USB2;
hs_hcd = usb_create_hcd(&dummy_hcd, &pdev->dev, dev_name(&pdev->dev));
if (!hs_hcd)
return -ENOMEM;
hs_hcd->has_tt = 1;
retval = usb_add_hcd(hs_hcd, 0, 0);
if (retval)
goto put_usb2_hcd;
if (mod_data.is_super_speed) {
ss_hcd = usb_create_shared_hcd(&dummy_hcd, &pdev->dev,
dev_name(&pdev->dev), hs_hcd);
if (!ss_hcd) {
retval = -ENOMEM;
goto dealloc_usb2_hcd;
}
retval = usb_add_hcd(ss_hcd, 0, 0);
if (retval)
goto put_usb3_hcd;
}
return 0;
put_usb3_hcd:
usb_put_hcd(ss_hcd);
dealloc_usb2_hcd:
usb_remove_hcd(hs_hcd);
put_usb2_hcd:
usb_put_hcd(hs_hcd);
the_controller.hs_hcd = the_controller.ss_hcd = NULL;
return retval;
}
static int dummy_hcd_remove(struct platform_device *pdev)
{
struct dummy *dum;
dum = (hcd_to_dummy_hcd(platform_get_drvdata(pdev)))->dum;
if (dum->ss_hcd) {
usb_remove_hcd(dummy_hcd_to_hcd(dum->ss_hcd));
usb_put_hcd(dummy_hcd_to_hcd(dum->ss_hcd));
}
usb_remove_hcd(dummy_hcd_to_hcd(dum->hs_hcd));
usb_put_hcd(dummy_hcd_to_hcd(dum->hs_hcd));
the_controller.hs_hcd = NULL;
the_controller.ss_hcd = NULL;
return 0;
}
static int dummy_hcd_suspend (struct platform_device *pdev, pm_message_t state)
{
struct usb_hcd *hcd;
struct dummy_hcd *dum_hcd;
int rc = 0;
dev_dbg (&pdev->dev, "%s\n", __func__);
hcd = platform_get_drvdata (pdev);
dum_hcd = hcd_to_dummy_hcd(hcd);
if (dum_hcd->rh_state == DUMMY_RH_RUNNING) {
dev_warn(&pdev->dev, "Root hub isn't suspended!\n");
rc = -EBUSY;
} else
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
return rc;
}
static int dummy_hcd_resume (struct platform_device *pdev)
{
struct usb_hcd *hcd;
dev_dbg (&pdev->dev, "%s\n", __func__);
hcd = platform_get_drvdata (pdev);
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
usb_hcd_poll_rh_status (hcd);
return 0;
}
static struct platform_driver dummy_hcd_driver = {
.probe = dummy_hcd_probe,
.remove = dummy_hcd_remove,
.suspend = dummy_hcd_suspend,
.resume = dummy_hcd_resume,
.driver = {
.name = (char *) driver_name,
.owner = THIS_MODULE,
},
};
/*-------------------------------------------------------------------------*/
static struct platform_device *the_udc_pdev;
static struct platform_device *the_hcd_pdev;
static int __init init (void)
{
int retval = -ENOMEM;
if (usb_disabled ())
return -ENODEV;
if (!mod_data.is_high_speed && mod_data.is_super_speed)
return -EINVAL;
the_hcd_pdev = platform_device_alloc(driver_name, -1);
if (!the_hcd_pdev)
return retval;
the_udc_pdev = platform_device_alloc(gadget_name, -1);
if (!the_udc_pdev)
goto err_alloc_udc;
retval = platform_driver_register(&dummy_hcd_driver);
if (retval < 0)
goto err_register_hcd_driver;
retval = platform_driver_register(&dummy_udc_driver);
if (retval < 0)
goto err_register_udc_driver;
retval = platform_device_add(the_hcd_pdev);
if (retval < 0)
goto err_add_hcd;
if (!the_controller.hs_hcd ||
(!the_controller.ss_hcd && mod_data.is_super_speed)) {
/*
* The hcd was added successfully but its probe function failed
* for some reason.
*/
retval = -EINVAL;
goto err_add_udc;
}
retval = platform_device_add(the_udc_pdev);
if (retval < 0)
goto err_add_udc;
if (!platform_get_drvdata(the_udc_pdev)) {
/*
* The udc was added successfully but its probe function failed
* for some reason.
*/
retval = -EINVAL;
goto err_probe_udc;
}
return retval;
err_probe_udc:
platform_device_del(the_udc_pdev);
err_add_udc:
platform_device_del(the_hcd_pdev);
err_add_hcd:
platform_driver_unregister(&dummy_udc_driver);
err_register_udc_driver:
platform_driver_unregister(&dummy_hcd_driver);
err_register_hcd_driver:
platform_device_put(the_udc_pdev);
err_alloc_udc:
platform_device_put(the_hcd_pdev);
return retval;
}
module_init (init);
static void __exit cleanup (void)
{
platform_device_unregister(the_udc_pdev);
platform_device_unregister(the_hcd_pdev);
platform_driver_unregister(&dummy_udc_driver);
platform_driver_unregister(&dummy_hcd_driver);
}
module_exit (cleanup);
| gpl-2.0 |
mageec/mageec-gcc | gcc/testsuite/gcc.dg/vect/pr43842.c | 29 | 1081 | /* { dg-do compile } */
typedef char int8_t;
typedef short int int16_t;
typedef int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
static int16_t
safe_rshift_func_int16_t_s_u (int16_t left, unsigned int right)
{
return left || right >= 1 * 8 ? left : left >> right;
}
static int8_t
safe_rshift_func_int8_t_s_u (int8_t left, unsigned int right)
{
return left || right >= 1 * 8 ? left : left >> right;
}
static uint32_t
safe_add_func_uint32_t_u_u (uint32_t ui1, uint16_t ui2)
{
return ui1 + ui2;
}
int16_t g_4;
int8_t g_4_8;
uint32_t g_9[1];
uint32_t g_9_8[2];
void
int161 (void)
{
int32_t l_2;
for (l_2 = -25; l_2; l_2 = safe_add_func_uint32_t_u_u (l_2, 1))
g_9[0] ^= safe_rshift_func_int16_t_s_u (g_4, 1);
}
int
int81 (void)
{
int32_t l_2;
for (l_2 = -25; l_2; l_2 = safe_add_func_uint32_t_u_u (l_2, 1))
{
g_9[0] ^= safe_rshift_func_int8_t_s_u (g_4_8, 1);
g_9[1] ^= safe_rshift_func_int8_t_s_u (g_4_8, 1);
}
return 0;
}
/* { dg-final { cleanup-tree-dump "vect" } } */
| gpl-2.0 |
africallshop/africallshop-iphone | submodules/externals/ffmpeg/libavcodec/alpha/dsputil_alpha.c | 29 | 4947 | /*
* Alpha optimized DSP utils
* Copyright (c) 2002 Falk Hueffner <falk@debian.org>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/attributes.h"
#include "libavcodec/dsputil.h"
#include "dsputil_alpha.h"
#include "asm.h"
void (*put_pixels_clamped_axp_p)(const int16_t *block, uint8_t *pixels,
int line_size);
void (*add_pixels_clamped_axp_p)(const int16_t *block, uint8_t *pixels,
int line_size);
#if 0
/* These functions were the base for the optimized assembler routines,
and remain here for documentation purposes. */
static void put_pixels_clamped_mvi(const int16_t *block, uint8_t *pixels,
ptrdiff_t line_size)
{
int i = 8;
uint64_t clampmask = zap(-1, 0xaa); /* 0x00ff00ff00ff00ff */
do {
uint64_t shorts0, shorts1;
shorts0 = ldq(block);
shorts0 = maxsw4(shorts0, 0);
shorts0 = minsw4(shorts0, clampmask);
stl(pkwb(shorts0), pixels);
shorts1 = ldq(block + 4);
shorts1 = maxsw4(shorts1, 0);
shorts1 = minsw4(shorts1, clampmask);
stl(pkwb(shorts1), pixels + 4);
pixels += line_size;
block += 8;
} while (--i);
}
void add_pixels_clamped_mvi(const int16_t *block, uint8_t *pixels,
ptrdiff_t line_size)
{
int h = 8;
/* Keep this function a leaf function by generating the constants
manually (mainly for the hack value ;-). */
uint64_t clampmask = zap(-1, 0xaa); /* 0x00ff00ff00ff00ff */
uint64_t signmask = zap(-1, 0x33);
signmask ^= signmask >> 1; /* 0x8000800080008000 */
do {
uint64_t shorts0, pix0, signs0;
uint64_t shorts1, pix1, signs1;
shorts0 = ldq(block);
shorts1 = ldq(block + 4);
pix0 = unpkbw(ldl(pixels));
/* Signed subword add (MMX paddw). */
signs0 = shorts0 & signmask;
shorts0 &= ~signmask;
shorts0 += pix0;
shorts0 ^= signs0;
/* Clamp. */
shorts0 = maxsw4(shorts0, 0);
shorts0 = minsw4(shorts0, clampmask);
/* Next 4. */
pix1 = unpkbw(ldl(pixels + 4));
signs1 = shorts1 & signmask;
shorts1 &= ~signmask;
shorts1 += pix1;
shorts1 ^= signs1;
shorts1 = maxsw4(shorts1, 0);
shorts1 = minsw4(shorts1, clampmask);
stl(pkwb(shorts0), pixels);
stl(pkwb(shorts1), pixels + 4);
pixels += line_size;
block += 8;
} while (--h);
}
#endif
static void clear_blocks_axp(int16_t *blocks) {
uint64_t *p = (uint64_t *) blocks;
int n = sizeof(int16_t) * 6 * 64;
do {
p[0] = 0;
p[1] = 0;
p[2] = 0;
p[3] = 0;
p[4] = 0;
p[5] = 0;
p[6] = 0;
p[7] = 0;
p += 8;
n -= 8 * 8;
} while (n);
}
av_cold void ff_dsputil_init_alpha(DSPContext *c, AVCodecContext *avctx)
{
const int high_bit_depth = avctx->bits_per_raw_sample > 8;
if (!high_bit_depth) {
c->clear_blocks = clear_blocks_axp;
}
/* amask clears all bits that correspond to present features. */
if (amask(AMASK_MVI) == 0) {
c->put_pixels_clamped = put_pixels_clamped_mvi_asm;
c->add_pixels_clamped = add_pixels_clamped_mvi_asm;
if (!high_bit_depth)
c->get_pixels = get_pixels_mvi;
c->diff_pixels = diff_pixels_mvi;
c->sad[0] = pix_abs16x16_mvi_asm;
c->sad[1] = pix_abs8x8_mvi;
c->pix_abs[0][0] = pix_abs16x16_mvi_asm;
c->pix_abs[1][0] = pix_abs8x8_mvi;
c->pix_abs[0][1] = pix_abs16x16_x2_mvi;
c->pix_abs[0][2] = pix_abs16x16_y2_mvi;
c->pix_abs[0][3] = pix_abs16x16_xy2_mvi;
}
put_pixels_clamped_axp_p = c->put_pixels_clamped;
add_pixels_clamped_axp_p = c->add_pixels_clamped;
if (!avctx->lowres && avctx->bits_per_raw_sample <= 8 &&
(avctx->idct_algo == FF_IDCT_AUTO ||
avctx->idct_algo == FF_IDCT_SIMPLEALPHA)) {
c->idct_put = ff_simple_idct_put_axp;
c->idct_add = ff_simple_idct_add_axp;
c->idct = ff_simple_idct_axp;
}
}
| gpl-2.0 |
TeamWin/android_kernel_samsung_zerolte | drivers/cpufreq/dm_cpu_hotplug.c | 29 | 29619 | #include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cpufreq.h>
#include <linux/cpu.h>
#include <linux/jiffies.h>
#include <linux/kernel_stat.h>
#include <linux/mutex.h>
#include <linux/hrtimer.h>
#include <linux/tick.h>
#include <linux/ktime.h>
#include <linux/sched.h>
#include <linux/fb.h>
#include <linux/pm_qos.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/sort.h>
#include <linux/reboot.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
#include <mach/cpufreq.h>
#include <linux/suspend.h>
#if defined(CONFIG_SOC_EXYNOS5430)
#define NORMALMIN_FREQ 1000000
#else
#define NORMALMIN_FREQ 500000
#endif
#define POLLING_MSEC 100
#define DEFAULT_LOW_STAY_THRSHD 0
struct cpu_load_info {
cputime64_t cpu_idle;
cputime64_t cpu_iowait;
cputime64_t cpu_wall;
cputime64_t cpu_nice;
};
static DEFINE_PER_CPU(struct cpu_load_info, cur_cpu_info);
static DEFINE_MUTEX(dm_hotplug_lock);
static DEFINE_MUTEX(thread_lock);
static DEFINE_MUTEX(cluster1_hotplug_lock);
static DEFINE_MUTEX(cluster0_hotplug_in_lock);
#ifdef CONFIG_HOTPLUG_THREAD_STOP
static DEFINE_MUTEX(thread_manage_lock);
#endif
static struct task_struct *dm_hotplug_task;
#ifdef CONFIG_HOTPLUG_THREAD_STOP
static bool thread_start = false;
#endif
static unsigned int low_stay_threshold = DEFAULT_LOW_STAY_THRSHD;
static int cpu_util[NR_CPUS];
static unsigned int cur_load_freq = 0;
static bool lcd_is_on = true;
static bool forced_hotplug = false;
static bool in_low_power_mode = false;
static bool in_suspend_prepared = false;
static bool do_enable_hotplug = false;
static bool do_disable_hotplug = false;
#if defined(CONFIG_SCHED_HMP)
static bool do_hotplug_out = false;
static int cluster1_hotplugged = 0;
static int cluster0_hotplug_in = 0;
#define DEFAULT_NR_RUN_THRESHD 5
#define DEFAULT_NR_RUN_RANGE 2
static unsigned int nr_running_threshold = DEFAULT_NR_RUN_THRESHD;
static unsigned int nr_running_range = DEFAULT_NR_RUN_RANGE;
static unsigned int nr_running_count = 0;
static unsigned long cur_nr_running;
static bool cluster0_core_in_by_nr_running = false;
#endif
#ifdef CONFIG_ARM_EXYNOS_MP_CPUFREQ
static unsigned int cluster1_min_freq;
static unsigned int cluster0_max_freq;
#endif
int disable_dm_hotplug_before_suspend = 0;
int nr_sleep_prepare_cpus = CONFIG_EXYNOS5_DYNAMIC_CPU_HOTPLUG_SLEEP_PREPARE;
enum hotplug_cmd {
CMD_NORMAL,
CMD_LOW_POWER,
CMD_CLUST1_IN,
CMD_CLUST1_OUT,
CMD_CLUST0_IN,
CMD_CLUST0_ONE_IN,
CMD_CLUST0_ONE_OUT,
CMD_SLEEP_PREPARE,
};
static int on_run(void *data);
static int dynamic_hotplug(enum hotplug_cmd cmd);
static enum hotplug_cmd diagnose_condition(void);
static void calc_load(void);
static enum hotplug_cmd prev_cmd = CMD_NORMAL;
static enum hotplug_cmd exe_cmd;
static unsigned int delay = POLLING_MSEC;
static unsigned int out_delay = POLLING_MSEC;
static unsigned int in_delay = POLLING_MSEC;
#if defined(CONFIG_SCHED_HMP)
static struct workqueue_struct *hotplug_wq;
#endif
static struct workqueue_struct *force_hotplug_wq;
#ifdef CONFIG_HOTPLUG_THREAD_STOP
static struct workqueue_struct *thread_manage_wq;
#endif
static int dm_hotplug_disable = 0;
static int exynos_dm_hotplug_disabled(void)
{
return dm_hotplug_disable;
}
#ifdef CONFIG_ARGOS
void exynos_dm_hotplug_enable(void)
#else
static void exynos_dm_hotplug_enable(void)
#endif
{
mutex_lock(&dm_hotplug_lock);
if (!exynos_dm_hotplug_disabled()) {
pr_warn("%s: dynamic hotplug already enabled\n",
__func__);
mutex_unlock(&dm_hotplug_lock);
return;
}
dm_hotplug_disable--;
if (!in_suspend_prepared)
disable_dm_hotplug_before_suspend--;
mutex_unlock(&dm_hotplug_lock);
}
#ifdef CONFIG_ARGOS
void exynos_dm_hotplug_disable(void)
#else
static void exynos_dm_hotplug_disable(void)
#endif
{
mutex_lock(&dm_hotplug_lock);
dm_hotplug_disable++;
if (!in_suspend_prepared)
disable_dm_hotplug_before_suspend++;
mutex_unlock(&dm_hotplug_lock);
}
#ifdef CONFIG_PM
static ssize_t show_enable_dm_hotplug(struct kobject *kobj,
struct attribute *attr, char *buf)
{
int disabled = exynos_dm_hotplug_disabled();
return snprintf(buf, 10, "%s\n", disabled ? "disabled" : "enabled");
}
static ssize_t store_enable_dm_hotplug(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
int enable_input;
if (!sscanf(buf, "%1d", &enable_input))
return -EINVAL;
if (enable_input > 1 || enable_input < 0) {
pr_err("%s: invalid value (%d)\n", __func__, enable_input);
return -EINVAL;
}
if (enable_input) {
do_enable_hotplug = true;
if (exynos_dm_hotplug_disabled())
exynos_dm_hotplug_enable();
else
pr_info("%s: dynamic hotplug already enabled\n",
__func__);
#if defined(CONFIG_SCHED_HMP)
if (cluster1_hotplugged) {
if (dynamic_hotplug(CMD_CLUST1_OUT)) {
pr_err("%s: Cluster1 core hotplug_out is failed\n",
__func__);
do_enable_hotplug = false;
return -EINVAL;
}
}
#endif
do_enable_hotplug = false;
} else {
do_disable_hotplug = true;
if (!dynamic_hotplug(CMD_NORMAL))
prev_cmd = CMD_NORMAL;
if (!exynos_dm_hotplug_disabled())
exynos_dm_hotplug_disable();
else
pr_info("%s: dynamic hotplug already disabled\n",
__func__);
do_disable_hotplug = false;
}
return count;
}
#if defined(CONFIG_SCHED_HMP)
static ssize_t show_cluster0_core1_hotplug_in(struct kobject *kobj,
struct attribute *attr, char *buf)
{
if (exynos_dm_hotplug_disabled())
return snprintf(buf, PAGE_SIZE, "dynamic hotplug disabled\n");
return snprintf(buf, PAGE_SIZE, "%s on low power mode\n",
cluster0_hotplug_in ? "hotplug-in" : "hotplug-out");
}
static ssize_t store_cluster0_core1_hotplug_in(struct kobject *kobj,
struct attribute *attr, const char *buf, size_t count)
{
int input_cluster0_hotplug_in;
if (!sscanf(buf, "%1d", &input_cluster0_hotplug_in))
return -EINVAL;
if (input_cluster0_hotplug_in > 1 || input_cluster0_hotplug_in < 0) {
pr_err("%s: invalid value (%d)\n", __func__, input_cluster0_hotplug_in);
return -EINVAL;
}
cluster0_core1_hotplug_in((bool)input_cluster0_hotplug_in);
return count;
}
static ssize_t show_hotplug_nr_running(struct kobject *kobj,
struct attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "current_nr_running = %lu, "
"nr_running_threshold = %u, nr_running_range = %u\n",
cur_nr_running, nr_running_threshold, nr_running_range);
}
static ssize_t store_hotplug_nr_running(struct kobject *kobj,
struct attribute *attr, const char *buf, size_t count)
{
int input_nr_running_thrshd;
int input_nr_running_range;
if (!sscanf(buf, "%5d %5d", &input_nr_running_thrshd, &input_nr_running_range))
return -EINVAL;
if (input_nr_running_thrshd <= 1 || input_nr_running_range < 1) {
pr_err("%s: invalid values (thrshd = %d, range = %d)\n",
__func__, input_nr_running_thrshd, input_nr_running_range);
pr_err("%s: thrshd is should be over than 1,"
" and range is should be over than 0\n", __func__);
return -EINVAL;
}
nr_running_threshold = (unsigned int)input_nr_running_thrshd;
nr_running_range = (unsigned int)input_nr_running_range;
pr_info("%s: nr_running_threshold = %u, nr_running_range = %u\n",
__func__, nr_running_threshold, nr_running_range);
return count;
}
#endif
static ssize_t show_stay_threshold(struct kobject *kobj,
struct attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u\n", low_stay_threshold);
}
static ssize_t store_stay_threshold(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
int input_threshold;
if (!sscanf(buf, "%8d", &input_threshold))
return -EINVAL;
if (input_threshold < 0) {
pr_err("%s: invalid value (%d)\n", __func__, input_threshold);
return -EINVAL;
}
low_stay_threshold = (unsigned int)input_threshold;
return count;
}
static ssize_t show_dm_hotplug_delay(struct kobject *kobj,
struct attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "hotplug delay (out : %umsec, in : %umsec, cur : %umsec)\n",
out_delay, in_delay, delay);
}
static ssize_t store_dm_hotplug_delay(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
int input_out_delay, input_in_delay;
if (!sscanf(buf, "%8d %8d", &input_out_delay, &input_in_delay))
return -EINVAL;
if (input_out_delay < 0 || input_in_delay < 0) {
pr_err("%s: invalid value (%d, %d)\n",
__func__, input_out_delay, input_in_delay);
return -EINVAL;
}
out_delay = (unsigned int)input_out_delay;
in_delay = (unsigned int)input_in_delay;
if (in_low_power_mode)
delay = in_delay;
else
delay = out_delay;
return count;
}
static struct global_attr enable_dm_hotplug =
__ATTR(enable_dm_hotplug, S_IRUGO | S_IWUSR,
show_enable_dm_hotplug, store_enable_dm_hotplug);
#if defined(CONFIG_SCHED_HMP)
static struct global_attr cluster0_core_hotplug_in =
__ATTR(cluster0_core_hotplug_in, S_IRUGO | S_IWUSR,
show_cluster0_core1_hotplug_in, store_cluster0_core1_hotplug_in);
static struct global_attr hotplug_nr_running =
__ATTR(hotplug_nr_running, S_IRUGO | S_IWUSR,
show_hotplug_nr_running, store_hotplug_nr_running);
#endif
static struct global_attr dm_hotplug_stay_threshold =
__ATTR(dm_hotplug_stay_threshold, S_IRUGO | S_IWUSR,
show_stay_threshold, store_stay_threshold);
static struct global_attr dm_hotplug_delay =
__ATTR(dm_hotplug_delay, S_IRUGO | S_IWUSR,
show_dm_hotplug_delay, store_dm_hotplug_delay);
#endif
static inline u64 get_cpu_idle_time_jiffy(unsigned int cpu, u64 *wall)
{
u64 idle_time;
u64 cur_wall_time;
u64 busy_time;
cur_wall_time = jiffies64_to_cputime64(get_jiffies_64());
busy_time = kcpustat_cpu(cpu).cpustat[CPUTIME_USER];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_SYSTEM];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_IRQ];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_SOFTIRQ];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_STEAL];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_NICE];
idle_time = cur_wall_time - busy_time;
if (wall)
*wall = jiffies_to_usecs(cur_wall_time);
return jiffies_to_usecs(idle_time);
}
static inline cputime64_t get_cpu_idle_time(unsigned int cpu, cputime64_t *wall)
{
u64 idle_time = get_cpu_idle_time_us(cpu, NULL);
if (idle_time == -1ULL)
return get_cpu_idle_time_jiffy(cpu, wall);
else
idle_time += get_cpu_iowait_time_us(cpu, wall);
return idle_time;
}
static inline cputime64_t get_cpu_iowait_time(unsigned int cpu, cputime64_t *wall)
{
u64 iowait_time = get_cpu_iowait_time_us(cpu, wall);
if (iowait_time == -1ULL)
return 0;
return iowait_time;
}
#ifdef CONFIG_HOTPLUG_THREAD_STOP
static void thread_manage_work(struct work_struct *work)
{
mutex_lock(&thread_manage_lock);
if (thread_start) {
dm_hotplug_task =
kthread_create(on_run, NULL, "thread_hotplug");
if (IS_ERR(dm_hotplug_task)) {
pr_err("Failed in creation of thread.\n");
return;
}
wake_up_process(dm_hotplug_task);
} else {
if (dm_hotplug_task) {
kthread_stop(dm_hotplug_task);
dm_hotplug_task = NULL;
if (!dynamic_hotplug(CMD_NORMAL))
prev_cmd = CMD_NORMAL;
}
}
mutex_unlock(&thread_manage_lock);
}
static DECLARE_WORK(manage_work, thread_manage_work);
#endif
static int fb_state_change(struct notifier_block *nb,
unsigned long val, void *data)
{
struct fb_event *evdata = data;
struct fb_info *info = evdata->info;
unsigned int blank;
if (val != FB_EVENT_BLANK &&
val != FB_R_EARLY_EVENT_BLANK)
return 0;
/*
* If FBNODE is not zero, it is not primary display(LCD)
* and don't need to process these scheduling.
*/
if (info->node)
return NOTIFY_OK;
blank = *(int *)evdata->data;
switch (blank) {
case FB_BLANK_POWERDOWN:
lcd_is_on = false;
pr_info("LCD is off\n");
#ifdef CONFIG_HOTPLUG_THREAD_STOP
if (thread_manage_wq) {
if (work_pending(&manage_work))
flush_work(&manage_work);
thread_start = true;
queue_work(thread_manage_wq, &manage_work);
}
#endif
break;
case FB_BLANK_UNBLANK:
/*
* LCD blank CPU qos is set by exynos-ikcs-cpufreq
* This line of code release max limit when LCD is
* turned on.
*/
lcd_is_on = true;
pr_info("LCD is on\n");
#ifdef CONFIG_HOTPLUG_THREAD_STOP
if (thread_manage_wq) {
if (work_pending(&manage_work))
flush_work(&manage_work);
thread_start = false;
queue_work(thread_manage_wq, &manage_work);
}
#endif
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block fb_block = {
.notifier_call = fb_state_change,
};
static int __ref __cpu_hotplug(bool out_flag, enum hotplug_cmd cmd)
{
int i = 0;
int ret = 0;
#if defined(CONFIG_SCHED_HMP)
int hotplug_out_limit = 0;
#endif
if (exynos_dm_hotplug_disabled())
return 0;
#if defined(CONFIG_SCHED_HMP)
if (out_flag) {
if (do_disable_hotplug)
goto blk_out;
if (cmd == CMD_SLEEP_PREPARE) {
for (i = setup_max_cpus - 1; i >= NR_CLUST0_CPUS; i--) {
if (cpu_online(i)) {
ret = cpu_down(i);
if (ret)
goto blk_out;
}
}
for (i = 1; i < nr_sleep_prepare_cpus; i++) {
if (!cpu_online(i)) {
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
}
else if (cmd == CMD_CLUST1_OUT && !in_low_power_mode) {
for (i = setup_max_cpus - 1; i >= NR_CLUST0_CPUS; i--) {
if (cpu_online(i)) {
ret = cpu_down(i);
if (ret)
goto blk_out;
}
}
} else {
if (cmd == CMD_CLUST0_ONE_OUT) {
if (!in_low_power_mode)
goto blk_out;
for (i = NR_CLUST0_CPUS - 2; i > 0; i--) {
if (cpu_online(i)) {
ret = cpu_down(i);
if (ret)
goto blk_out;
}
}
} else {
if (cluster0_hotplug_in)
hotplug_out_limit = NR_CLUST0_CPUS - 2;
for (i = setup_max_cpus - 1; i > hotplug_out_limit; i--) {
if (cpu_online(i)) {
ret = cpu_down(i);
if (ret)
goto blk_out;
}
}
}
}
} else {
if (in_suspend_prepared)
goto blk_out;
if (cmd == CMD_CLUST1_IN) {
if (in_low_power_mode)
goto blk_out;
for (i = NR_CLUST0_CPUS; i < setup_max_cpus; i++) {
if (!cpu_online(i)) {
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
} else {
if (cmd == CMD_CLUST0_ONE_IN) {
for (i = 1; i < NR_CLUST0_CPUS - 1; i++) {
if (!cpu_online(i)) {
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
} else if ((cluster1_hotplugged && !do_disable_hotplug) ||
(cmd == CMD_CLUST0_IN)) {
for (i = 1; i < NR_CLUST0_CPUS; i++) {
if (!cpu_online(i)) {
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
} else {
if (lcd_is_on) {
for (i = NR_CLUST0_CPUS; i < setup_max_cpus; i++) {
if (do_hotplug_out)
goto blk_out;
if (!cpu_online(i)) {
if (i == NR_CLUST0_CPUS)
set_hmp_boostpulse(100000);
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
for (i = 1; i < NR_CLUST0_CPUS; i++) {
if (!cpu_online(i)) {
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
} else {
for (i = 1; i < setup_max_cpus; i++) {
if (do_hotplug_out && i >= NR_CLUST0_CPUS)
goto blk_out;
if (!cpu_online(i)) {
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
}
}
}
}
#else
if (out_flag) {
if (do_disable_hotplug)
goto blk_out;
for (i = setup_max_cpus - 1; i > 0; i--) {
if (cpu_online(i)) {
ret = cpu_down(i);
if (ret)
goto blk_out;
}
}
} else {
if (in_suspend_prepared)
goto blk_out;
for (i = 1; i < setup_max_cpus; i++) {
if (!cpu_online(i)) {
ret = cpu_up(i);
if (ret)
goto blk_out;
}
}
}
#endif
blk_out:
return ret;
}
static int dynamic_hotplug(enum hotplug_cmd cmd)
{
int ret = 0;
mutex_lock(&dm_hotplug_lock);
switch (cmd) {
case CMD_LOW_POWER:
ret = __cpu_hotplug(true, cmd);
in_low_power_mode = true;
delay = in_delay;
break;
case CMD_CLUST0_ONE_OUT:
case CMD_CLUST1_OUT:
case CMD_SLEEP_PREPARE:
ret = __cpu_hotplug(true, cmd);
break;
case CMD_CLUST0_ONE_IN:
case CMD_CLUST1_IN:
ret = __cpu_hotplug(false, cmd);
break;
case CMD_CLUST0_IN:
case CMD_NORMAL:
ret = __cpu_hotplug(false, cmd);
in_low_power_mode = false;
delay = out_delay;
break;
}
mutex_unlock(&dm_hotplug_lock);
return ret;
}
static bool force_out_flag;
static void force_dynamic_hotplug_work(struct work_struct *work)
{
enum hotplug_cmd cmd;
forced_hotplug = force_out_flag;
calc_load();
cmd = diagnose_condition();
if (!dynamic_hotplug(cmd))
prev_cmd = cmd;
}
static DECLARE_WORK(force_hotplug_work, force_dynamic_hotplug_work);
void force_dynamic_hotplug(bool out_flag, int delay_msec)
{
if (force_hotplug_wq) {
force_out_flag = out_flag;
queue_work(force_hotplug_wq, &force_hotplug_work);
}
}
#if defined(CONFIG_SCHED_HMP)
int cluster1_cores_hotplug(bool out_flag)
{
int ret = 0;
mutex_lock(&cluster1_hotplug_lock);
if (out_flag) {
do_hotplug_out = true;
if (cluster1_hotplugged) {
cluster1_hotplugged++;
do_hotplug_out = false;
goto out;
}
ret = dynamic_hotplug(CMD_CLUST1_OUT);
if (!ret) {
cluster1_hotplugged++;
do_hotplug_out = false;
}
} else {
if (WARN_ON(cluster1_hotplugged == 0)) {
pr_err("%s: cluster1 cores already hotplug in\n",
__func__);
ret = -EINVAL;
goto out;
}
if (cluster1_hotplugged > 1) {
cluster1_hotplugged--;
goto out;
}
ret = dynamic_hotplug(CMD_CLUST1_IN);
if (!ret)
cluster1_hotplugged--;
}
out:
mutex_unlock(&cluster1_hotplug_lock);
return ret;
}
int cluster0_core1_hotplug_in(bool in_flag)
{
int ret = 0;
mutex_lock(&cluster0_hotplug_in_lock);
if (in_flag) {
if (cluster0_hotplug_in) {
cluster0_hotplug_in++;
goto out;
}
ret = dynamic_hotplug(CMD_CLUST0_ONE_IN);
if (!ret)
cluster0_hotplug_in++;
} else {
if (WARN_ON(cluster0_hotplug_in == 0)) {
pr_err("%s: little core1 already hotplug out\n",
__func__);
ret = -EINVAL;
goto out;
}
if (cluster0_hotplug_in > 1) {
cluster0_hotplug_in--;
goto out;
}
ret = dynamic_hotplug(CMD_CLUST0_ONE_OUT);
if (!ret)
cluster0_hotplug_in--;
}
out:
mutex_unlock(&cluster0_hotplug_in_lock);
return ret;
}
static void event_hotplug_in_work(struct work_struct *work)
{
if(!dynamic_hotplug(CMD_NORMAL))
prev_cmd = CMD_NORMAL;
else
pr_err("%s: failed hotplug in\n", __func__);
}
static DECLARE_WORK(hotplug_in_work, event_hotplug_in_work);
void event_hotplug_in(void)
{
if (hotplug_wq)
queue_work(hotplug_wq, &hotplug_in_work);
}
#endif
static int exynos_dm_hotplug_notifier(struct notifier_block *notifier,
unsigned long pm_event, void *v)
{
switch (pm_event) {
case PM_SUSPEND_PREPARE:
mutex_lock(&thread_lock);
in_suspend_prepared = true;
if(nr_sleep_prepare_cpus > 1) {
pr_info("%s, %d : dynamic_hotplug CMD_SLEEP_PREPARE\n", __func__, __LINE__);
if (!dynamic_hotplug(CMD_SLEEP_PREPARE))
prev_cmd = CMD_LOW_POWER;
}
else {
if (!dynamic_hotplug(CMD_LOW_POWER))
prev_cmd = CMD_LOW_POWER;
}
exynos_dm_hotplug_disable();
if (dm_hotplug_task) {
kthread_stop(dm_hotplug_task);
dm_hotplug_task = NULL;
}
mutex_unlock(&thread_lock);
break;
case PM_POST_SUSPEND:
mutex_lock(&thread_lock);
exynos_dm_hotplug_enable();
dm_hotplug_task =
kthread_create(on_run, NULL, "thread_hotplug");
if (IS_ERR(dm_hotplug_task)) {
mutex_unlock(&thread_lock);
pr_err("Failed in creation of thread.\n");
return -EINVAL;
}
in_suspend_prepared = false;
wake_up_process(dm_hotplug_task);
mutex_unlock(&thread_lock);
break;
}
return NOTIFY_OK;
}
static struct notifier_block exynos_dm_hotplug_nb = {
.notifier_call = exynos_dm_hotplug_notifier,
.priority = 1,
};
static int exynos_dm_hotplut_reboot_notifier(struct notifier_block *this,
unsigned long code, void *_cmd)
{
switch (code) {
case SYSTEM_POWER_OFF:
case SYS_RESTART:
mutex_lock(&thread_lock);
exynos_dm_hotplug_disable();
if (dm_hotplug_task) {
kthread_stop(dm_hotplug_task);
dm_hotplug_task = NULL;
}
mutex_unlock(&thread_lock);
break;
}
return NOTIFY_OK;
}
static struct notifier_block exynos_dm_hotplug_reboot_nb = {
.notifier_call = exynos_dm_hotplut_reboot_notifier,
};
#ifdef CONFIG_SCHED_HMP
static void update_nr_running_count(void)
{
int ret = 0;
cur_nr_running = nr_running();
if (cur_nr_running >= nr_running_threshold) {
if (nr_running_count < nr_running_range)
nr_running_count++;
} else {
if (nr_running_count > 0)
nr_running_count--;
}
if (nr_running_count) {
if (!cluster0_core_in_by_nr_running) {
ret = cluster0_core1_hotplug_in(true);
if (!ret)
cluster0_core_in_by_nr_running = true;
}
} else {
if (cluster0_core_in_by_nr_running) {
ret = cluster0_core1_hotplug_in(false);
if (!ret)
cluster0_core_in_by_nr_running = false;
}
}
}
#endif
#ifdef CONFIG_ARM_EXYNOS_MP_CPUFREQ
extern bool cluster_on[CL_END];
#endif
static int low_stay = 0;
static enum hotplug_cmd diagnose_condition(void)
{
enum hotplug_cmd ret;
unsigned int normal_min_freq;
#ifdef CONFIG_ARM_EXYNOS_MP_CPUFREQ
struct cpufreq_policy *policy;
unsigned int cluster1_cur_freq;
#endif
#if defined(CONFIG_CPU_FREQ_GOV_INTERACTIVE)
normal_min_freq = cpufreq_interactive_get_hispeed_freq(0);
if (!normal_min_freq)
normal_min_freq = NORMALMIN_FREQ;
#else
normal_min_freq = NORMALMIN_FREQ;
#endif
#ifdef CONFIG_ARM_EXYNOS_MP_CPUFREQ
policy = cpufreq_cpu_get(0);
if (!policy) {
cluster0_max_freq = 0;
} else {
cluster0_max_freq = policy->max;
cpufreq_cpu_put(policy);
}
policy = cpufreq_cpu_get(NR_CLUST0_CPUS);
if (!policy) {
cluster1_cur_freq = 0;
} else {
if (cluster_on[CL_ONE])
cluster1_cur_freq = policy->cur;
else
cluster1_cur_freq = 0;
cpufreq_cpu_put(policy);
}
#endif
#ifdef CONFIG_SCHED_HMP
update_nr_running_count();
#endif
#if defined(CONFIG_ARM_EXYNOS_MP_CPUFREQ)
ret = CMD_CLUST0_IN;
if (cur_load_freq >= cluster0_max_freq)
ret = CMD_NORMAL;
if ((cur_load_freq > normal_min_freq) ||
(cluster1_cur_freq >= cluster1_min_freq) ||
(pm_qos_request(PM_QOS_CLUSTER1_FREQ_MIN) >= cluster1_min_freq)) {
if (in_low_power_mode)
ret = CMD_CLUST0_IN;
#else
ret = CMD_NORMAL;
if (cur_load_freq > normal_min_freq) {
#endif
low_stay = 0;
} else if (cur_load_freq <= normal_min_freq &&
low_stay <= low_stay_threshold) {
low_stay++;
}
if (low_stay > low_stay_threshold &&
(!lcd_is_on || forced_hotplug))
ret = CMD_LOW_POWER;
#ifdef CONFIG_SCHED_HMP
if (cluster0_hotplug_in || cluster0_core_in_by_nr_running) {
int i;
for (i = 1; i < NR_CLUST0_CPUS; i++) {
if (!cpu_online(i) && cur_load_freq <= normal_min_freq) {
ret = CMD_CLUST0_ONE_IN;
break;
}
}
}
#endif
return ret;
}
static void calc_load(void)
{
struct cpufreq_policy *policy;
unsigned int cpu_util_sum = 0;
int cpu = 0;
unsigned int i;
policy = cpufreq_cpu_get(cpu);
if (!policy) {
pr_err("Invalid policy\n");
return;
}
cur_load_freq = 0;
for_each_cpu(i, policy->cpus) {
struct cpu_load_info *i_load_info;
cputime64_t cur_wall_time, cur_idle_time, cur_iowait_time;
unsigned int idle_time, wall_time, iowait_time;
unsigned int load, load_freq;
i_load_info = &per_cpu(cur_cpu_info, i);
cur_idle_time = get_cpu_idle_time(i, &cur_wall_time);
cur_iowait_time = get_cpu_iowait_time(i, &cur_wall_time);
wall_time = (unsigned int)
(cur_wall_time - i_load_info->cpu_wall);
i_load_info->cpu_wall = cur_wall_time;
idle_time = (unsigned int)
(cur_idle_time - i_load_info->cpu_idle);
i_load_info->cpu_idle = cur_idle_time;
iowait_time = (unsigned int)
(cur_iowait_time - i_load_info->cpu_iowait);
i_load_info->cpu_iowait = cur_iowait_time;
if (unlikely(!wall_time || wall_time < idle_time))
continue;
load = 100 * (wall_time - idle_time) / wall_time;
cpu_util[i] = load;
cpu_util_sum += load;
load_freq = load * policy->cur;
if (policy->cur > cur_load_freq)
cur_load_freq = policy->cur;
}
cpufreq_cpu_put(policy);
return;
}
static int on_run(void *data)
{
int on_cpu = 0;
int ret;
struct cpumask thread_cpumask;
cpumask_clear(&thread_cpumask);
cpumask_set_cpu(on_cpu, &thread_cpumask);
sched_setaffinity(0, &thread_cpumask);
while (!kthread_should_stop()) {
calc_load();
exe_cmd = diagnose_condition();
#ifdef DM_HOTPLUG_DEBUG
pr_info("frequency info : %d, prev_cmd %d, exe_cmd %d\n",
cur_load_freq, prev_cmd, exe_cmd);
pr_info("lcd is on : %d, low power mode = %d, dm_hotplug disable = %d\n",
lcd_is_on, in_low_power_mode, exynos_dm_hotplug_disabled());
#if defined(CONFIG_SCHED_HMP)
pr_info("cluster1 cores hotplug out : %d\n", cluster1_hotplugged);
#endif
#endif
if (exynos_dm_hotplug_disabled())
goto sleep;
if (prev_cmd != exe_cmd) {
ret = dynamic_hotplug(exe_cmd);
if (ret < 0) {
if (ret == -EBUSY)
goto sleep;
else
goto failed_out;
}
}
prev_cmd = exe_cmd;
sleep:
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout_interruptible(msecs_to_jiffies(delay));
set_current_state(TASK_RUNNING);
}
pr_info("stopped %s\n", dm_hotplug_task->comm);
return 0;
failed_out:
panic("%s: failed dynamic hotplug (exe_cmd %d)\n", __func__, exe_cmd);
return ret;
}
#if defined(CONFIG_SCHED_HMP)
bool is_cluster1_hotplugged(void)
{
return cluster1_hotplugged ? true : false;
}
#endif
static struct dentry *cputime_debugfs;
static int cputime_debug_show(struct seq_file *s, void *unsued)
{
seq_printf(s, "cputime %llu\n",
(unsigned long long) cputime64_to_clock_t(get_jiffies_64()));
return 0;
}
static int cputime_debug_open(struct inode *inode, struct file *file)
{
return single_open(file, cputime_debug_show, inode->i_private);
}
const static struct file_operations cputime_fops = {
.open = cputime_debug_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init dm_cpu_hotplug_init(void)
{
int ret = 0;
#ifdef CONFIG_ARM_EXYNOS_MP_CPUFREQ
struct cpufreq_policy *policy;
#endif
#ifndef CONFIG_HOTPLUG_THREAD_STOP
dm_hotplug_task =
kthread_create(on_run, NULL, "thread_hotplug");
if (IS_ERR(dm_hotplug_task)) {
pr_err("Failed in creation of thread.\n");
return -EINVAL;
}
#endif
fb_register_client(&fb_block);
#ifdef CONFIG_PM
ret = sysfs_create_file(power_kobj, &enable_dm_hotplug.attr);
if (ret) {
pr_err("%s: failed to create enable_dm_hotplug sysfs interface\n",
__func__);
goto err_enable_dm_hotplug;
}
#if defined(CONFIG_SCHED_HMP)
ret = sysfs_create_file(power_kobj, &cluster0_core_hotplug_in.attr);
if (ret) {
pr_err("%s: failed to create cluster0_core_hotplug_in sysfs interface\n",
__func__);
goto err_cluster0_core_hotplug_in;
}
ret = sysfs_create_file(power_kobj, &hotplug_nr_running.attr);
if (ret) {
pr_err("%s: failed to create hotplug_nr_running sysfs interface\n",
__func__);
goto err_hotplug_nr_running;
}
#endif
ret = sysfs_create_file(power_kobj, &dm_hotplug_stay_threshold.attr);
if (ret) {
pr_err("%s: failed to create dm_hotplug_stay_threshold sysfs interface\n",
__func__);
goto err_dm_hotplug_stay_threshold;
}
ret = sysfs_create_file(power_kobj, &dm_hotplug_delay.attr);
if (ret) {
pr_err("%s: failed to create dm_hotplug_delay sysfs interface\n",
__func__);
goto err_dm_hotplug_delay;
}
#endif
#ifdef CONFIG_ARM_EXYNOS_MP_CPUFREQ
policy = cpufreq_cpu_get(NR_CLUST0_CPUS);
if (!policy) {
pr_err("%s: invaled policy cpu%d\n", __func__, NR_CLUST0_CPUS);
ret = -ENODEV;
goto err_policy;
}
cluster1_min_freq = policy->min;
cpufreq_cpu_put(policy);
#endif
#if defined(CONFIG_SCHED_HMP)
hotplug_wq = create_singlethread_workqueue("event-hotplug");
if (!hotplug_wq) {
ret = -ENOMEM;
goto err_wq;
}
#endif
force_hotplug_wq = create_singlethread_workqueue("force-hotplug");
if (!force_hotplug_wq) {
ret = -ENOMEM;
goto err_force_wq;
}
#ifdef CONFIG_HOTPLUG_THREAD_STOP
thread_manage_wq = create_singlethread_workqueue("thread-manage");
if (!thread_manage_wq) {
ret = -ENOMEM;
goto err_thread_wq;
}
#endif
register_pm_notifier(&exynos_dm_hotplug_nb);
register_reboot_notifier(&exynos_dm_hotplug_reboot_nb);
cputime_debugfs =
debugfs_create_file("cputime", S_IRUGO, NULL, NULL, &cputime_fops);
if (IS_ERR_OR_NULL(cputime_debugfs)) {
cputime_debugfs = NULL;
pr_err("%s: debugfs_create_file() failed\n", __func__);
}
#ifndef CONFIG_HOTPLUG_THREAD_STOP
wake_up_process(dm_hotplug_task);
#endif
return ret;
#ifdef CONFIG_HOTPLUG_THREAD_STOP
err_thread_wq:
destroy_workqueue(force_hotplug_wq);
#endif
err_force_wq:
#if defined(CONFIG_SCHED_HMP)
destroy_workqueue(hotplug_wq);
err_wq:
#endif
#ifdef CONFIG_ARM_EXYNOS_MP_CPUFREQ
err_policy:
#endif
#ifdef CONFIG_PM
sysfs_remove_file(power_kobj, &dm_hotplug_delay.attr);
err_dm_hotplug_delay:
sysfs_remove_file(power_kobj, &dm_hotplug_stay_threshold.attr);
err_dm_hotplug_stay_threshold:
#if defined(CONFIG_SCHED_HMP)
sysfs_remove_file(power_kobj, &hotplug_nr_running.attr);
err_hotplug_nr_running:
sysfs_remove_file(power_kobj, &cluster0_core_hotplug_in.attr);
err_cluster0_core_hotplug_in:
#endif
sysfs_remove_file(power_kobj, &enable_dm_hotplug.attr);
err_enable_dm_hotplug:
#endif
fb_unregister_client(&fb_block);
#ifndef CONFIG_HOTPLUG_THREAD_STOP
kthread_stop(dm_hotplug_task);
#endif
return ret;
}
late_initcall(dm_cpu_hotplug_init);
| gpl-2.0 |
RepoBackups/kernel_lge_g3 | fs/btrfs/inode.c | 29 | 207349 | /*
* Copyright (C) 2007 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/kernel.h>
#include <linux/bio.h>
#include <linux/buffer_head.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/backing-dev.h>
#include <linux/mpage.h>
#include <linux/swap.h>
#include <linux/writeback.h>
#include <linux/statfs.h>
#include <linux/compat.h>
#include <linux/bit_spinlock.h>
#include <linux/xattr.h>
#include <linux/posix_acl.h>
#include <linux/falloc.h>
#include <linux/slab.h>
#include <linux/ratelimit.h>
#include <linux/mount.h>
#include "compat.h"
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "btrfs_inode.h"
#include "ioctl.h"
#include "print-tree.h"
#include "ordered-data.h"
#include "xattr.h"
#include "tree-log.h"
#include "volumes.h"
#include "compression.h"
#include "locking.h"
#include "free-space-cache.h"
#include "inode-map.h"
struct btrfs_iget_args {
u64 ino;
struct btrfs_root *root;
};
static const struct inode_operations btrfs_dir_inode_operations;
static const struct inode_operations btrfs_symlink_inode_operations;
static const struct inode_operations btrfs_dir_ro_inode_operations;
static const struct inode_operations btrfs_special_inode_operations;
static const struct inode_operations btrfs_file_inode_operations;
static const struct address_space_operations btrfs_aops;
static const struct address_space_operations btrfs_symlink_aops;
static const struct file_operations btrfs_dir_file_operations;
static struct extent_io_ops btrfs_extent_io_ops;
static struct kmem_cache *btrfs_inode_cachep;
struct kmem_cache *btrfs_trans_handle_cachep;
struct kmem_cache *btrfs_transaction_cachep;
struct kmem_cache *btrfs_path_cachep;
struct kmem_cache *btrfs_free_space_cachep;
#define S_SHIFT 12
static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
[S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
[S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
[S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
[S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
[S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
[S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
[S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
};
static int btrfs_setsize(struct inode *inode, loff_t newsize);
static int btrfs_truncate(struct inode *inode);
static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
static noinline int cow_file_range(struct inode *inode,
struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written, int unlock);
static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode);
static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
struct inode *inode, struct inode *dir,
const struct qstr *qstr)
{
int err;
err = btrfs_init_acl(trans, inode, dir);
if (!err)
err = btrfs_xattr_security_init(trans, inode, dir, qstr);
return err;
}
/*
* this does all the hard work for inserting an inline extent into
* the btree. The caller should have done a btrfs_drop_extents so that
* no overlapping inline items exist in the btree
*/
static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode,
u64 start, size_t size, size_t compressed_size,
int compress_type,
struct page **compressed_pages)
{
struct btrfs_key key;
struct btrfs_path *path;
struct extent_buffer *leaf;
struct page *page = NULL;
char *kaddr;
unsigned long ptr;
struct btrfs_file_extent_item *ei;
int err = 0;
int ret;
size_t cur_size = size;
size_t datasize;
unsigned long offset;
if (compressed_size && compressed_pages)
cur_size = compressed_size;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->leave_spinning = 1;
key.objectid = btrfs_ino(inode);
key.offset = start;
btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
datasize = btrfs_file_extent_calc_inline_size(cur_size);
inode_add_bytes(inode, size);
ret = btrfs_insert_empty_item(trans, root, path, &key,
datasize);
if (ret) {
err = ret;
goto fail;
}
leaf = path->nodes[0];
ei = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, ei, trans->transid);
btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
btrfs_set_file_extent_encryption(leaf, ei, 0);
btrfs_set_file_extent_other_encoding(leaf, ei, 0);
btrfs_set_file_extent_ram_bytes(leaf, ei, size);
ptr = btrfs_file_extent_inline_start(ei);
if (compress_type != BTRFS_COMPRESS_NONE) {
struct page *cpage;
int i = 0;
while (compressed_size > 0) {
cpage = compressed_pages[i];
cur_size = min_t(unsigned long, compressed_size,
PAGE_CACHE_SIZE);
kaddr = kmap_atomic(cpage);
write_extent_buffer(leaf, kaddr, ptr, cur_size);
kunmap_atomic(kaddr);
i++;
ptr += cur_size;
compressed_size -= cur_size;
}
btrfs_set_file_extent_compression(leaf, ei,
compress_type);
} else {
page = find_get_page(inode->i_mapping,
start >> PAGE_CACHE_SHIFT);
btrfs_set_file_extent_compression(leaf, ei, 0);
kaddr = kmap_atomic(page);
offset = start & (PAGE_CACHE_SIZE - 1);
write_extent_buffer(leaf, kaddr + offset, ptr, size);
kunmap_atomic(kaddr);
page_cache_release(page);
}
btrfs_mark_buffer_dirty(leaf);
btrfs_free_path(path);
/*
* we're an inline extent, so nobody can
* extend the file past i_size without locking
* a page we already have locked.
*
* We must do any isize and inode updates
* before we unlock the pages. Otherwise we
* could end up racing with unlink.
*/
BTRFS_I(inode)->disk_i_size = inode->i_size;
ret = btrfs_update_inode(trans, root, inode);
return ret;
fail:
btrfs_free_path(path);
return err;
}
/*
* conditionally insert an inline extent into the file. This
* does the checks required to make sure the data is small enough
* to fit as an inline extent.
*/
static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *inode, u64 start, u64 end,
size_t compressed_size, int compress_type,
struct page **compressed_pages)
{
u64 isize = i_size_read(inode);
u64 actual_end = min(end + 1, isize);
u64 inline_len = actual_end - start;
u64 aligned_end = (end + root->sectorsize - 1) &
~((u64)root->sectorsize - 1);
u64 hint_byte;
u64 data_len = inline_len;
int ret;
if (compressed_size)
data_len = compressed_size;
if (start > 0 ||
actual_end >= PAGE_CACHE_SIZE ||
data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
(!compressed_size &&
(actual_end & (root->sectorsize - 1)) == 0) ||
end + 1 < isize ||
data_len > root->fs_info->max_inline) {
return 1;
}
ret = btrfs_drop_extents(trans, inode, start, aligned_end,
&hint_byte, 1);
if (ret)
return ret;
if (isize > actual_end)
inline_len = min_t(u64, isize, actual_end);
ret = insert_inline_extent(trans, root, inode, start,
inline_len, compressed_size,
compress_type, compressed_pages);
if (ret && ret != -ENOSPC) {
btrfs_abort_transaction(trans, root, ret);
return ret;
} else if (ret == -ENOSPC) {
return 1;
}
btrfs_delalloc_release_metadata(inode, end + 1 - start);
btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
return 0;
}
struct async_extent {
u64 start;
u64 ram_size;
u64 compressed_size;
struct page **pages;
unsigned long nr_pages;
int compress_type;
struct list_head list;
};
struct async_cow {
struct inode *inode;
struct btrfs_root *root;
struct page *locked_page;
u64 start;
u64 end;
struct list_head extents;
struct btrfs_work work;
};
static noinline int add_async_extent(struct async_cow *cow,
u64 start, u64 ram_size,
u64 compressed_size,
struct page **pages,
unsigned long nr_pages,
int compress_type)
{
struct async_extent *async_extent;
async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
BUG_ON(!async_extent); /* -ENOMEM */
async_extent->start = start;
async_extent->ram_size = ram_size;
async_extent->compressed_size = compressed_size;
async_extent->pages = pages;
async_extent->nr_pages = nr_pages;
async_extent->compress_type = compress_type;
list_add_tail(&async_extent->list, &cow->extents);
return 0;
}
/*
* we create compressed extents in two phases. The first
* phase compresses a range of pages that have already been
* locked (both pages and state bits are locked).
*
* This is done inside an ordered work queue, and the compression
* is spread across many cpus. The actual IO submission is step
* two, and the ordered work queue takes care of making sure that
* happens in the same order things were put onto the queue by
* writepages and friends.
*
* If this code finds it can't get good compression, it puts an
* entry onto the work queue to write the uncompressed bytes. This
* makes sure that both compressed inodes and uncompressed inodes
* are written in the same order that pdflush sent them down.
*/
static noinline int compress_file_range(struct inode *inode,
struct page *locked_page,
u64 start, u64 end,
struct async_cow *async_cow,
int *num_added)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
u64 num_bytes;
u64 blocksize = root->sectorsize;
u64 actual_end;
u64 isize = i_size_read(inode);
int ret = 0;
struct page **pages = NULL;
unsigned long nr_pages;
unsigned long nr_pages_ret = 0;
unsigned long total_compressed = 0;
unsigned long total_in = 0;
unsigned long max_compressed = 128 * 1024;
unsigned long max_uncompressed = 128 * 1024;
int i;
int will_compress;
int compress_type = root->fs_info->compress_type;
int redirty = 0;
/* if this is a small write inside eof, kick off a defrag */
if ((end - start + 1) < 16 * 1024 &&
(start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
btrfs_add_inode_defrag(NULL, inode);
actual_end = min_t(u64, isize, end + 1);
again:
will_compress = 0;
nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
/*
* we don't want to send crud past the end of i_size through
* compression, that's just a waste of CPU time. So, if the
* end of the file is before the start of our current
* requested range of bytes, we bail out to the uncompressed
* cleanup code that can deal with all of this.
*
* It isn't really the fastest way to fix things, but this is a
* very uncommon corner.
*/
if (actual_end <= start)
goto cleanup_and_bail_uncompressed;
total_compressed = actual_end - start;
/* we want to make sure that amount of ram required to uncompress
* an extent is reasonable, so we limit the total size in ram
* of a compressed extent to 128k. This is a crucial number
* because it also controls how easily we can spread reads across
* cpus for decompression.
*
* We also want to make sure the amount of IO required to do
* a random read is reasonably small, so we limit the size of
* a compressed extent to 128k.
*/
total_compressed = min(total_compressed, max_uncompressed);
num_bytes = (end - start + blocksize) & ~(blocksize - 1);
num_bytes = max(blocksize, num_bytes);
total_in = 0;
ret = 0;
/*
* we do compression for mount -o compress and when the
* inode has not been flagged as nocompress. This flag can
* change at any time if we discover bad compression ratios.
*/
if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
(btrfs_test_opt(root, COMPRESS) ||
(BTRFS_I(inode)->force_compress) ||
(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
WARN_ON(pages);
pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
if (!pages) {
/* just bail out to the uncompressed code */
goto cont;
}
if (BTRFS_I(inode)->force_compress)
compress_type = BTRFS_I(inode)->force_compress;
/*
* we need to call clear_page_dirty_for_io on each
* page in the range. Otherwise applications with the file
* mmap'd can wander in and change the page contents while
* we are compressing them.
*
* If the compression fails for any reason, we set the pages
* dirty again later on.
*/
extent_range_clear_dirty_for_io(inode, start, end);
redirty = 1;
ret = btrfs_compress_pages(compress_type,
inode->i_mapping, start,
total_compressed, pages,
nr_pages, &nr_pages_ret,
&total_in,
&total_compressed,
max_compressed);
if (!ret) {
unsigned long offset = total_compressed &
(PAGE_CACHE_SIZE - 1);
struct page *page = pages[nr_pages_ret - 1];
char *kaddr;
/* zero the tail end of the last page, we might be
* sending it down to disk
*/
if (offset) {
kaddr = kmap_atomic(page);
memset(kaddr + offset, 0,
PAGE_CACHE_SIZE - offset);
kunmap_atomic(kaddr);
}
will_compress = 1;
}
}
cont:
if (start == 0) {
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
trans = NULL;
goto cleanup_and_out;
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
/* lets try to make an inline extent */
if (ret || total_in < (actual_end - start)) {
/* we didn't compress the entire range, try
* to make an uncompressed inline extent.
*/
ret = cow_file_range_inline(trans, root, inode,
start, end, 0, 0, NULL);
} else {
/* try making a compressed inline extent */
ret = cow_file_range_inline(trans, root, inode,
start, end,
total_compressed,
compress_type, pages);
}
if (ret <= 0) {
/*
* inline extent creation worked or returned error,
* we don't need to create any more async work items.
* Unlock and free up our temp pages.
*/
extent_clear_unlock_delalloc(inode,
&BTRFS_I(inode)->io_tree,
start, end, NULL,
EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
EXTENT_CLEAR_DELALLOC |
EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
btrfs_end_transaction(trans, root);
goto free_pages_out;
}
btrfs_end_transaction(trans, root);
}
if (will_compress) {
/*
* we aren't doing an inline extent round the compressed size
* up to a block size boundary so the allocator does sane
* things
*/
total_compressed = (total_compressed + blocksize - 1) &
~(blocksize - 1);
/*
* one last check to make sure the compression is really a
* win, compare the page count read with the blocks on disk
*/
total_in = (total_in + PAGE_CACHE_SIZE - 1) &
~(PAGE_CACHE_SIZE - 1);
if (total_compressed >= total_in) {
will_compress = 0;
} else {
num_bytes = total_in;
}
}
if (!will_compress && pages) {
/*
* the compression code ran but failed to make things smaller,
* free any pages it allocated and our page pointer array
*/
for (i = 0; i < nr_pages_ret; i++) {
WARN_ON(pages[i]->mapping);
page_cache_release(pages[i]);
}
kfree(pages);
pages = NULL;
total_compressed = 0;
nr_pages_ret = 0;
/* flag the file so we don't compress in the future */
if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
!(BTRFS_I(inode)->force_compress)) {
BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
}
}
if (will_compress) {
*num_added += 1;
/* the async work queues will take care of doing actual
* allocation on disk for these compressed pages,
* and will submit them to the elevator.
*/
add_async_extent(async_cow, start, num_bytes,
total_compressed, pages, nr_pages_ret,
compress_type);
if (start + num_bytes < end) {
start += num_bytes;
pages = NULL;
cond_resched();
goto again;
}
} else {
cleanup_and_bail_uncompressed:
/*
* No compression, but we still need to write the pages in
* the file we've been given so far. redirty the locked
* page if it corresponds to our extent and set things up
* for the async work queue to run cow_file_range to do
* the normal delalloc dance
*/
if (page_offset(locked_page) >= start &&
page_offset(locked_page) <= end) {
__set_page_dirty_nobuffers(locked_page);
/* unlocked later on in the async handlers */
}
if (redirty)
extent_range_redirty_for_io(inode, start, end);
add_async_extent(async_cow, start, end - start + 1,
0, NULL, 0, BTRFS_COMPRESS_NONE);
*num_added += 1;
}
out:
return ret;
free_pages_out:
for (i = 0; i < nr_pages_ret; i++) {
WARN_ON(pages[i]->mapping);
page_cache_release(pages[i]);
}
kfree(pages);
goto out;
cleanup_and_out:
extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
start, end, NULL,
EXTENT_CLEAR_UNLOCK_PAGE |
EXTENT_CLEAR_DIRTY |
EXTENT_CLEAR_DELALLOC |
EXTENT_SET_WRITEBACK |
EXTENT_END_WRITEBACK);
if (!trans || IS_ERR(trans))
btrfs_error(root->fs_info, ret, "Failed to join transaction");
else
btrfs_abort_transaction(trans, root, ret);
goto free_pages_out;
}
/*
* phase two of compressed writeback. This is the ordered portion
* of the code, which only gets called in the order the work was
* queued. We walk all the async extents created by compress_file_range
* and send them down to the disk.
*/
static noinline int submit_compressed_extents(struct inode *inode,
struct async_cow *async_cow)
{
struct async_extent *async_extent;
u64 alloc_hint = 0;
struct btrfs_trans_handle *trans;
struct btrfs_key ins;
struct extent_map *em;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_io_tree *io_tree;
int ret = 0;
if (list_empty(&async_cow->extents))
return 0;
while (!list_empty(&async_cow->extents)) {
async_extent = list_entry(async_cow->extents.next,
struct async_extent, list);
list_del(&async_extent->list);
io_tree = &BTRFS_I(inode)->io_tree;
retry:
/* did the compression code fall back to uncompressed IO? */
if (!async_extent->pages) {
int page_started = 0;
unsigned long nr_written = 0;
lock_extent(io_tree, async_extent->start,
async_extent->start +
async_extent->ram_size - 1);
/* allocate blocks */
ret = cow_file_range(inode, async_cow->locked_page,
async_extent->start,
async_extent->start +
async_extent->ram_size - 1,
&page_started, &nr_written, 0);
/* JDM XXX */
/*
* if page_started, cow_file_range inserted an
* inline extent and took care of all the unlocking
* and IO for us. Otherwise, we need to submit
* all those pages down to the drive.
*/
if (!page_started && !ret)
extent_write_locked_range(io_tree,
inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1,
btrfs_get_extent,
WB_SYNC_ALL);
kfree(async_extent);
cond_resched();
continue;
}
lock_extent(io_tree, async_extent->start,
async_extent->start + async_extent->ram_size - 1);
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
} else {
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
ret = btrfs_reserve_extent(trans, root,
async_extent->compressed_size,
async_extent->compressed_size,
0, alloc_hint, &ins, 1);
if (ret)
btrfs_abort_transaction(trans, root, ret);
btrfs_end_transaction(trans, root);
}
if (ret) {
int i;
for (i = 0; i < async_extent->nr_pages; i++) {
WARN_ON(async_extent->pages[i]->mapping);
page_cache_release(async_extent->pages[i]);
}
kfree(async_extent->pages);
async_extent->nr_pages = 0;
async_extent->pages = NULL;
unlock_extent(io_tree, async_extent->start,
async_extent->start +
async_extent->ram_size - 1);
if (ret == -ENOSPC)
goto retry;
goto out_free; /* JDM: Requeue? */
}
/*
* here we're doing allocation and writeback of the
* compressed pages
*/
btrfs_drop_extent_cache(inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1, 0);
em = alloc_extent_map();
BUG_ON(!em); /* -ENOMEM */
em->start = async_extent->start;
em->len = async_extent->ram_size;
em->orig_start = em->start;
em->block_start = ins.objectid;
em->block_len = ins.offset;
em->bdev = root->fs_info->fs_devices->latest_bdev;
em->compress_type = async_extent->compress_type;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
while (1) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em);
write_unlock(&em_tree->lock);
if (ret != -EEXIST) {
free_extent_map(em);
break;
}
btrfs_drop_extent_cache(inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1, 0);
}
ret = btrfs_add_ordered_extent_compress(inode,
async_extent->start,
ins.objectid,
async_extent->ram_size,
ins.offset,
BTRFS_ORDERED_COMPRESSED,
async_extent->compress_type);
BUG_ON(ret); /* -ENOMEM */
/*
* clear dirty, set writeback and unlock the pages.
*/
extent_clear_unlock_delalloc(inode,
&BTRFS_I(inode)->io_tree,
async_extent->start,
async_extent->start +
async_extent->ram_size - 1,
NULL, EXTENT_CLEAR_UNLOCK_PAGE |
EXTENT_CLEAR_UNLOCK |
EXTENT_CLEAR_DELALLOC |
EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
ret = btrfs_submit_compressed_write(inode,
async_extent->start,
async_extent->ram_size,
ins.objectid,
ins.offset, async_extent->pages,
async_extent->nr_pages);
BUG_ON(ret); /* -ENOMEM */
alloc_hint = ins.objectid + ins.offset;
kfree(async_extent);
cond_resched();
}
ret = 0;
out:
return ret;
out_free:
kfree(async_extent);
goto out;
}
static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
u64 num_bytes)
{
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_map *em;
u64 alloc_hint = 0;
read_lock(&em_tree->lock);
em = search_extent_mapping(em_tree, start, num_bytes);
if (em) {
/*
* if block start isn't an actual block number then find the
* first block in this inode and use that as a hint. If that
* block is also bogus then just don't worry about it.
*/
if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
free_extent_map(em);
em = search_extent_mapping(em_tree, 0, 0);
if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
alloc_hint = em->block_start;
if (em)
free_extent_map(em);
} else {
alloc_hint = em->block_start;
free_extent_map(em);
}
}
read_unlock(&em_tree->lock);
return alloc_hint;
}
/*
* when extent_io.c finds a delayed allocation range in the file,
* the call backs end up in this code. The basic idea is to
* allocate extents on disk for the range, and create ordered data structs
* in ram to track those extents.
*
* locked_page is the page that writepage had locked already. We use
* it to make sure we don't do extra locks or unlocks.
*
* *page_started is set to one if we unlock locked_page and do everything
* required to start IO on it. It may be clean and already done with
* IO when we return.
*/
static noinline int cow_file_range(struct inode *inode,
struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written,
int unlock)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
u64 alloc_hint = 0;
u64 num_bytes;
unsigned long ram_size;
u64 disk_num_bytes;
u64 cur_alloc_size;
u64 blocksize = root->sectorsize;
struct btrfs_key ins;
struct extent_map *em;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
int ret = 0;
BUG_ON(btrfs_is_free_space_inode(root, inode));
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
extent_clear_unlock_delalloc(inode,
&BTRFS_I(inode)->io_tree,
start, end, NULL,
EXTENT_CLEAR_UNLOCK_PAGE |
EXTENT_CLEAR_UNLOCK |
EXTENT_CLEAR_DELALLOC |
EXTENT_CLEAR_DIRTY |
EXTENT_SET_WRITEBACK |
EXTENT_END_WRITEBACK);
return PTR_ERR(trans);
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
num_bytes = (end - start + blocksize) & ~(blocksize - 1);
num_bytes = max(blocksize, num_bytes);
disk_num_bytes = num_bytes;
ret = 0;
/* if this is a small write inside eof, kick off defrag */
if (num_bytes < 64 * 1024 &&
(start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
btrfs_add_inode_defrag(trans, inode);
if (start == 0) {
/* lets try to make an inline extent */
ret = cow_file_range_inline(trans, root, inode,
start, end, 0, 0, NULL);
if (ret == 0) {
extent_clear_unlock_delalloc(inode,
&BTRFS_I(inode)->io_tree,
start, end, NULL,
EXTENT_CLEAR_UNLOCK_PAGE |
EXTENT_CLEAR_UNLOCK |
EXTENT_CLEAR_DELALLOC |
EXTENT_CLEAR_DIRTY |
EXTENT_SET_WRITEBACK |
EXTENT_END_WRITEBACK);
*nr_written = *nr_written +
(end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
*page_started = 1;
goto out;
} else if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto out_unlock;
}
}
BUG_ON(disk_num_bytes >
btrfs_super_total_bytes(root->fs_info->super_copy));
alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
while (disk_num_bytes > 0) {
unsigned long op;
cur_alloc_size = disk_num_bytes;
ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
root->sectorsize, 0, alloc_hint,
&ins, 1);
if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto out_unlock;
}
em = alloc_extent_map();
BUG_ON(!em); /* -ENOMEM */
em->start = start;
em->orig_start = em->start;
ram_size = ins.offset;
em->len = ins.offset;
em->block_start = ins.objectid;
em->block_len = ins.offset;
em->bdev = root->fs_info->fs_devices->latest_bdev;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
while (1) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em);
write_unlock(&em_tree->lock);
if (ret != -EEXIST) {
free_extent_map(em);
break;
}
btrfs_drop_extent_cache(inode, start,
start + ram_size - 1, 0);
}
cur_alloc_size = ins.offset;
ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
ram_size, cur_alloc_size, 0);
BUG_ON(ret); /* -ENOMEM */
if (root->root_key.objectid ==
BTRFS_DATA_RELOC_TREE_OBJECTID) {
ret = btrfs_reloc_clone_csums(inode, start,
cur_alloc_size);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_unlock;
}
}
if (disk_num_bytes < cur_alloc_size)
break;
/* we're not doing compressed IO, don't unlock the first
* page (which the caller expects to stay locked), don't
* clear any dirty bits and don't set any writeback bits
*
* Do set the Private2 bit so we know this page was properly
* setup for writepage
*/
op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
EXTENT_SET_PRIVATE2;
extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
start, start + ram_size - 1,
locked_page, op);
disk_num_bytes -= cur_alloc_size;
num_bytes -= cur_alloc_size;
alloc_hint = ins.objectid + ins.offset;
start += cur_alloc_size;
}
ret = 0;
out:
btrfs_end_transaction(trans, root);
return ret;
out_unlock:
extent_clear_unlock_delalloc(inode,
&BTRFS_I(inode)->io_tree,
start, end, NULL,
EXTENT_CLEAR_UNLOCK_PAGE |
EXTENT_CLEAR_UNLOCK |
EXTENT_CLEAR_DELALLOC |
EXTENT_CLEAR_DIRTY |
EXTENT_SET_WRITEBACK |
EXTENT_END_WRITEBACK);
goto out;
}
/*
* work queue call back to started compression on a file and pages
*/
static noinline void async_cow_start(struct btrfs_work *work)
{
struct async_cow *async_cow;
int num_added = 0;
async_cow = container_of(work, struct async_cow, work);
compress_file_range(async_cow->inode, async_cow->locked_page,
async_cow->start, async_cow->end, async_cow,
&num_added);
if (num_added == 0)
async_cow->inode = NULL;
}
/*
* work queue call back to submit previously compressed pages
*/
static noinline void async_cow_submit(struct btrfs_work *work)
{
struct async_cow *async_cow;
struct btrfs_root *root;
unsigned long nr_pages;
async_cow = container_of(work, struct async_cow, work);
root = async_cow->root;
nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
PAGE_CACHE_SHIFT;
atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
if (atomic_read(&root->fs_info->async_delalloc_pages) <
5 * 1042 * 1024 &&
waitqueue_active(&root->fs_info->async_submit_wait))
wake_up(&root->fs_info->async_submit_wait);
if (async_cow->inode)
submit_compressed_extents(async_cow->inode, async_cow);
}
static noinline void async_cow_free(struct btrfs_work *work)
{
struct async_cow *async_cow;
async_cow = container_of(work, struct async_cow, work);
kfree(async_cow);
}
static int cow_file_range_async(struct inode *inode, struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written)
{
struct async_cow *async_cow;
struct btrfs_root *root = BTRFS_I(inode)->root;
unsigned long nr_pages;
u64 cur_end;
int limit = 10 * 1024 * 1042;
clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1, 0, NULL, GFP_NOFS);
while (start < end) {
async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
BUG_ON(!async_cow); /* -ENOMEM */
async_cow->inode = inode;
async_cow->root = root;
async_cow->locked_page = locked_page;
async_cow->start = start;
if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
cur_end = end;
else
cur_end = min(end, start + 512 * 1024 - 1);
async_cow->end = cur_end;
INIT_LIST_HEAD(&async_cow->extents);
async_cow->work.func = async_cow_start;
async_cow->work.ordered_func = async_cow_submit;
async_cow->work.ordered_free = async_cow_free;
async_cow->work.flags = 0;
nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
PAGE_CACHE_SHIFT;
atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
btrfs_queue_worker(&root->fs_info->delalloc_workers,
&async_cow->work);
if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
wait_event(root->fs_info->async_submit_wait,
(atomic_read(&root->fs_info->async_delalloc_pages) <
limit));
}
while (atomic_read(&root->fs_info->async_submit_draining) &&
atomic_read(&root->fs_info->async_delalloc_pages)) {
wait_event(root->fs_info->async_submit_wait,
(atomic_read(&root->fs_info->async_delalloc_pages) ==
0));
}
*nr_written += nr_pages;
start = cur_end + 1;
}
*page_started = 1;
return 0;
}
static noinline int csum_exist_in_range(struct btrfs_root *root,
u64 bytenr, u64 num_bytes)
{
int ret;
struct btrfs_ordered_sum *sums;
LIST_HEAD(list);
ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
bytenr + num_bytes - 1, &list, 0);
if (ret == 0 && list_empty(&list))
return 0;
while (!list_empty(&list)) {
sums = list_entry(list.next, struct btrfs_ordered_sum, list);
list_del(&sums->list);
kfree(sums);
}
return 1;
}
/*
* when nowcow writeback call back. This checks for snapshots or COW copies
* of the extents that exist in the file, and COWs the file as required.
*
* If no cow copies or snapshots exist, we write directly to the existing
* blocks on disk
*/
static noinline int run_delalloc_nocow(struct inode *inode,
struct page *locked_page,
u64 start, u64 end, int *page_started, int force,
unsigned long *nr_written)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
struct extent_buffer *leaf;
struct btrfs_path *path;
struct btrfs_file_extent_item *fi;
struct btrfs_key found_key;
u64 cow_start;
u64 cur_offset;
u64 extent_end;
u64 extent_offset;
u64 disk_bytenr;
u64 num_bytes;
int extent_type;
int ret, err;
int type;
int nocow;
int check_prev = 1;
bool nolock;
u64 ino = btrfs_ino(inode);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
nolock = btrfs_is_free_space_inode(root, inode);
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
btrfs_free_path(path);
return PTR_ERR(trans);
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
cow_start = (u64)-1;
cur_offset = start;
while (1) {
ret = btrfs_lookup_file_extent(trans, root, path, ino,
cur_offset, 0);
if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto error;
}
if (ret > 0 && path->slots[0] > 0 && check_prev) {
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key,
path->slots[0] - 1);
if (found_key.objectid == ino &&
found_key.type == BTRFS_EXTENT_DATA_KEY)
path->slots[0]--;
}
check_prev = 0;
next_slot:
leaf = path->nodes[0];
if (path->slots[0] >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto error;
}
if (ret > 0)
break;
leaf = path->nodes[0];
}
nocow = 0;
disk_bytenr = 0;
num_bytes = 0;
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
if (found_key.objectid > ino ||
found_key.type > BTRFS_EXTENT_DATA_KEY ||
found_key.offset > end)
break;
if (found_key.offset > cur_offset) {
extent_end = found_key.offset;
extent_type = 0;
goto out_check;
}
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_type = btrfs_file_extent_type(leaf, fi);
if (extent_type == BTRFS_FILE_EXTENT_REG ||
extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
extent_offset = btrfs_file_extent_offset(leaf, fi);
extent_end = found_key.offset +
btrfs_file_extent_num_bytes(leaf, fi);
if (extent_end <= start) {
path->slots[0]++;
goto next_slot;
}
if (disk_bytenr == 0)
goto out_check;
if (btrfs_file_extent_compression(leaf, fi) ||
btrfs_file_extent_encryption(leaf, fi) ||
btrfs_file_extent_other_encoding(leaf, fi))
goto out_check;
if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
goto out_check;
if (btrfs_extent_readonly(root, disk_bytenr))
goto out_check;
if (btrfs_cross_ref_exist(trans, root, ino,
found_key.offset -
extent_offset, disk_bytenr))
goto out_check;
disk_bytenr += extent_offset;
disk_bytenr += cur_offset - found_key.offset;
num_bytes = min(end + 1, extent_end) - cur_offset;
/*
* force cow if csum exists in the range.
* this ensure that csum for a given extent are
* either valid or do not exist.
*/
if (csum_exist_in_range(root, disk_bytenr, num_bytes))
goto out_check;
nocow = 1;
} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
extent_end = found_key.offset +
btrfs_file_extent_inline_len(leaf, fi);
extent_end = ALIGN(extent_end, root->sectorsize);
} else {
BUG_ON(1);
}
out_check:
if (extent_end <= start) {
path->slots[0]++;
goto next_slot;
}
if (!nocow) {
if (cow_start == (u64)-1)
cow_start = cur_offset;
cur_offset = extent_end;
if (cur_offset > end)
break;
path->slots[0]++;
goto next_slot;
}
btrfs_release_path(path);
if (cow_start != (u64)-1) {
ret = cow_file_range(inode, locked_page, cow_start,
found_key.offset - 1, page_started,
nr_written, 1);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto error;
}
cow_start = (u64)-1;
}
if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
struct extent_map *em;
struct extent_map_tree *em_tree;
em_tree = &BTRFS_I(inode)->extent_tree;
em = alloc_extent_map();
BUG_ON(!em); /* -ENOMEM */
em->start = cur_offset;
em->orig_start = em->start;
em->len = num_bytes;
em->block_len = num_bytes;
em->block_start = disk_bytenr;
em->bdev = root->fs_info->fs_devices->latest_bdev;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
while (1) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em);
write_unlock(&em_tree->lock);
if (ret != -EEXIST) {
free_extent_map(em);
break;
}
btrfs_drop_extent_cache(inode, em->start,
em->start + em->len - 1, 0);
}
type = BTRFS_ORDERED_PREALLOC;
} else {
type = BTRFS_ORDERED_NOCOW;
}
ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
num_bytes, num_bytes, type);
BUG_ON(ret); /* -ENOMEM */
if (root->root_key.objectid ==
BTRFS_DATA_RELOC_TREE_OBJECTID) {
ret = btrfs_reloc_clone_csums(inode, cur_offset,
num_bytes);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto error;
}
}
extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
cur_offset, cur_offset + num_bytes - 1,
locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
EXTENT_SET_PRIVATE2);
cur_offset = extent_end;
if (cur_offset > end)
break;
}
btrfs_release_path(path);
if (cur_offset <= end && cow_start == (u64)-1)
cow_start = cur_offset;
if (cow_start != (u64)-1) {
ret = cow_file_range(inode, locked_page, cow_start, end,
page_started, nr_written, 1);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto error;
}
}
error:
if (nolock) {
err = btrfs_end_transaction_nolock(trans, root);
} else {
err = btrfs_end_transaction(trans, root);
}
if (!ret)
ret = err;
btrfs_free_path(path);
return ret;
}
/*
* extent_io.c call back to do delayed allocation processing
*/
static int run_delalloc_range(struct inode *inode, struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written)
{
int ret;
struct btrfs_root *root = BTRFS_I(inode)->root;
if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
ret = run_delalloc_nocow(inode, locked_page, start, end,
page_started, 1, nr_written);
else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
ret = run_delalloc_nocow(inode, locked_page, start, end,
page_started, 0, nr_written);
else if (!btrfs_test_opt(root, COMPRESS) &&
!(BTRFS_I(inode)->force_compress) &&
!(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
ret = cow_file_range(inode, locked_page, start, end,
page_started, nr_written, 1);
else
ret = cow_file_range_async(inode, locked_page, start, end,
page_started, nr_written);
return ret;
}
static void btrfs_split_extent_hook(struct inode *inode,
struct extent_state *orig, u64 split)
{
/* not delalloc, ignore it */
if (!(orig->state & EXTENT_DELALLOC))
return;
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents++;
spin_unlock(&BTRFS_I(inode)->lock);
}
/*
* extent_io.c merge_extent_hook, used to track merged delayed allocation
* extents so we can keep track of new extents that are just merged onto old
* extents, such as when we are doing sequential writes, so we can properly
* account for the metadata space we'll need.
*/
static void btrfs_merge_extent_hook(struct inode *inode,
struct extent_state *new,
struct extent_state *other)
{
/* not delalloc, ignore it */
if (!(other->state & EXTENT_DELALLOC))
return;
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents--;
spin_unlock(&BTRFS_I(inode)->lock);
}
/*
* extent_io.c set_bit_hook, used to track delayed allocation
* bytes in this file, and to maintain the list of inodes that
* have pending delalloc work to be done.
*/
static void btrfs_set_bit_hook(struct inode *inode,
struct extent_state *state, int *bits)
{
/*
* set_bit and clear bit hooks normally require _irqsave/restore
* but in this case, we are only testing for the DELALLOC
* bit, which is only set or cleared with irqs on
*/
if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 len = state->end + 1 - state->start;
bool do_list = !btrfs_is_free_space_inode(root, inode);
if (*bits & EXTENT_FIRST_DELALLOC) {
*bits &= ~EXTENT_FIRST_DELALLOC;
} else {
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents++;
spin_unlock(&BTRFS_I(inode)->lock);
}
spin_lock(&root->fs_info->delalloc_lock);
BTRFS_I(inode)->delalloc_bytes += len;
root->fs_info->delalloc_bytes += len;
if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
&root->fs_info->delalloc_inodes);
}
spin_unlock(&root->fs_info->delalloc_lock);
}
}
/*
* extent_io.c clear_bit_hook, see set_bit_hook for why
*/
static void btrfs_clear_bit_hook(struct inode *inode,
struct extent_state *state, int *bits)
{
/*
* set_bit and clear bit hooks normally require _irqsave/restore
* but in this case, we are only testing for the DELALLOC
* bit, which is only set or cleared with irqs on
*/
if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 len = state->end + 1 - state->start;
bool do_list = !btrfs_is_free_space_inode(root, inode);
if (*bits & EXTENT_FIRST_DELALLOC) {
*bits &= ~EXTENT_FIRST_DELALLOC;
} else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents--;
spin_unlock(&BTRFS_I(inode)->lock);
}
if (*bits & EXTENT_DO_ACCOUNTING)
btrfs_delalloc_release_metadata(inode, len);
if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
&& do_list)
btrfs_free_reserved_data_space(inode, len);
spin_lock(&root->fs_info->delalloc_lock);
root->fs_info->delalloc_bytes -= len;
BTRFS_I(inode)->delalloc_bytes -= len;
if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
list_del_init(&BTRFS_I(inode)->delalloc_inodes);
}
spin_unlock(&root->fs_info->delalloc_lock);
}
}
/*
* extent_io.c merge_bio_hook, this must check the chunk tree to make sure
* we don't create bios that span stripes or chunks
*/
int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
size_t size, struct bio *bio,
unsigned long bio_flags)
{
struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
struct btrfs_mapping_tree *map_tree;
u64 logical = (u64)bio->bi_sector << 9;
u64 length = 0;
u64 map_length;
int ret;
if (bio_flags & EXTENT_BIO_COMPRESSED)
return 0;
length = bio->bi_size;
map_tree = &root->fs_info->mapping_tree;
map_length = length;
ret = btrfs_map_block(map_tree, READ, logical,
&map_length, NULL, 0);
/* Will always return 0 or 1 with map_multi == NULL */
BUG_ON(ret < 0);
if (map_length < length + size)
return 1;
return 0;
}
/*
* in order to insert checksums into the metadata in large chunks,
* we wait until bio submission time. All the pages in the bio are
* checksummed and sums are attached onto the ordered extent record.
*
* At IO completion time the cums attached on the ordered extent record
* are inserted into the btree
*/
static int __btrfs_submit_bio_start(struct inode *inode, int rw,
struct bio *bio, int mirror_num,
unsigned long bio_flags,
u64 bio_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret = 0;
ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
BUG_ON(ret); /* -ENOMEM */
return 0;
}
/*
* in order to insert checksums into the metadata in large chunks,
* we wait until bio submission time. All the pages in the bio are
* checksummed and sums are attached onto the ordered extent record.
*
* At IO completion time the cums attached on the ordered extent record
* are inserted into the btree
*/
static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
int mirror_num, unsigned long bio_flags,
u64 bio_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
return btrfs_map_bio(root, rw, bio, mirror_num, 1);
}
/*
* extent_io.c submission hook. This does the right thing for csum calculation
* on write, or reading the csums from the tree before a read
*/
static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
int mirror_num, unsigned long bio_flags,
u64 bio_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret = 0;
int skip_sum;
int metadata = 0;
skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
if (btrfs_is_free_space_inode(root, inode))
metadata = 2;
ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
if (ret)
return ret;
if (!(rw & REQ_WRITE)) {
if (bio_flags & EXTENT_BIO_COMPRESSED) {
return btrfs_submit_compressed_read(inode, bio,
mirror_num, bio_flags);
} else if (!skip_sum) {
ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
if (ret)
return ret;
}
goto mapit;
} else if (!skip_sum) {
/* csum items have already been cloned */
if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
goto mapit;
/* we're doing a write, do the async checksumming */
return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
inode, rw, bio, mirror_num,
bio_flags, bio_offset,
__btrfs_submit_bio_start,
__btrfs_submit_bio_done);
}
mapit:
return btrfs_map_bio(root, rw, bio, mirror_num, 0);
}
/*
* given a list of ordered sums record them in the inode. This happens
* at IO completion time based on sums calculated at bio submission time.
*/
static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
struct inode *inode, u64 file_offset,
struct list_head *list)
{
struct btrfs_ordered_sum *sum;
list_for_each_entry(sum, list, list) {
btrfs_csum_file_blocks(trans,
BTRFS_I(inode)->root->fs_info->csum_root, sum);
}
return 0;
}
int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
struct extent_state **cached_state)
{
if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
WARN_ON(1);
return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
cached_state, GFP_NOFS);
}
/* see btrfs_writepage_start_hook for details on why this is required */
struct btrfs_writepage_fixup {
struct page *page;
struct btrfs_work work;
};
static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
{
struct btrfs_writepage_fixup *fixup;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
struct page *page;
struct inode *inode;
u64 page_start;
u64 page_end;
int ret;
fixup = container_of(work, struct btrfs_writepage_fixup, work);
page = fixup->page;
again:
lock_page(page);
if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
ClearPageChecked(page);
goto out_page;
}
inode = page->mapping->host;
page_start = page_offset(page);
page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
&cached_state);
/* already ordered? We're done */
if (PagePrivate2(page))
goto out;
ordered = btrfs_lookup_ordered_extent(inode, page_start);
if (ordered) {
unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
page_end, &cached_state, GFP_NOFS);
unlock_page(page);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
goto again;
}
ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
if (ret) {
mapping_set_error(page->mapping, ret);
end_extent_writepage(page, ret, page_start, page_end);
ClearPageChecked(page);
goto out;
}
btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
ClearPageChecked(page);
set_page_dirty(page);
out:
unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
out_page:
unlock_page(page);
page_cache_release(page);
kfree(fixup);
}
/*
* There are a few paths in the higher layers of the kernel that directly
* set the page dirty bit without asking the filesystem if it is a
* good idea. This causes problems because we want to make sure COW
* properly happens and the data=ordered rules are followed.
*
* In our case any range that doesn't have the ORDERED bit set
* hasn't been properly setup for IO. We kick off an async process
* to fix it up. The async helper will wait for ordered extents, set
* the delalloc bit and make it safe to write the page.
*/
static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
{
struct inode *inode = page->mapping->host;
struct btrfs_writepage_fixup *fixup;
struct btrfs_root *root = BTRFS_I(inode)->root;
/* this page is properly in the ordered list */
if (TestClearPagePrivate2(page))
return 0;
if (PageChecked(page))
return -EAGAIN;
fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
if (!fixup)
return -EAGAIN;
SetPageChecked(page);
page_cache_get(page);
fixup->work.func = btrfs_writepage_fixup_worker;
fixup->page = page;
btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
return -EBUSY;
}
static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
struct inode *inode, u64 file_pos,
u64 disk_bytenr, u64 disk_num_bytes,
u64 num_bytes, u64 ram_bytes,
u8 compression, u8 encryption,
u16 other_encoding, int extent_type)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_file_extent_item *fi;
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_key ins;
u64 hint;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->leave_spinning = 1;
/*
* we may be replacing one extent in the tree with another.
* The new extent is pinned in the extent map, and we don't want
* to drop it from the cache until it is completely in the btree.
*
* So, tell btrfs_drop_extents to leave this extent in the cache.
* the caller is expected to unpin it and allow it to be merged
* with the others.
*/
ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
&hint, 0);
if (ret)
goto out;
ins.objectid = btrfs_ino(inode);
ins.offset = file_pos;
ins.type = BTRFS_EXTENT_DATA_KEY;
ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
if (ret)
goto out;
leaf = path->nodes[0];
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi, trans->transid);
btrfs_set_file_extent_type(leaf, fi, extent_type);
btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
btrfs_set_file_extent_offset(leaf, fi, 0);
btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
btrfs_set_file_extent_compression(leaf, fi, compression);
btrfs_set_file_extent_encryption(leaf, fi, encryption);
btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
btrfs_unlock_up_safe(path, 1);
btrfs_set_lock_blocking(leaf);
btrfs_mark_buffer_dirty(leaf);
inode_add_bytes(inode, num_bytes);
ins.objectid = disk_bytenr;
ins.offset = disk_num_bytes;
ins.type = BTRFS_EXTENT_ITEM_KEY;
ret = btrfs_alloc_reserved_file_extent(trans, root,
root->root_key.objectid,
btrfs_ino(inode), file_pos, &ins);
out:
btrfs_free_path(path);
return ret;
}
/*
* helper function for btrfs_finish_ordered_io, this
* just reads in some of the csum leaves to prime them into ram
* before we start the transaction. It limits the amount of btree
* reads required while inside the transaction.
*/
/* as ordered data IO finishes, this gets called so we can finish
* an ordered extent if the range of bytes in the file it covers are
* fully written.
*/
static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans = NULL;
struct btrfs_ordered_extent *ordered_extent = NULL;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct extent_state *cached_state = NULL;
int compress_type = 0;
int ret;
bool nolock;
ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
end - start + 1);
if (!ret)
return 0;
BUG_ON(!ordered_extent); /* Logic error */
nolock = btrfs_is_free_space_inode(root, inode);
if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
if (!ret) {
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return PTR_ERR(trans);
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
ret = btrfs_update_inode_fallback(trans, root, inode);
if (ret) /* -ENOMEM or corruption */
btrfs_abort_transaction(trans, root, ret);
}
goto out;
}
lock_extent_bits(io_tree, ordered_extent->file_offset,
ordered_extent->file_offset + ordered_extent->len - 1,
0, &cached_state);
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
trans = NULL;
goto out_unlock;
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
compress_type = ordered_extent->compress_type;
if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
BUG_ON(compress_type);
ret = btrfs_mark_extent_written(trans, inode,
ordered_extent->file_offset,
ordered_extent->file_offset +
ordered_extent->len);
} else {
BUG_ON(root == root->fs_info->tree_root);
ret = insert_reserved_file_extent(trans, inode,
ordered_extent->file_offset,
ordered_extent->start,
ordered_extent->disk_len,
ordered_extent->len,
ordered_extent->len,
compress_type, 0, 0,
BTRFS_FILE_EXTENT_REG);
unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
ordered_extent->file_offset,
ordered_extent->len);
}
unlock_extent_cached(io_tree, ordered_extent->file_offset,
ordered_extent->file_offset +
ordered_extent->len - 1, &cached_state, GFP_NOFS);
if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
add_pending_csums(trans, inode, ordered_extent->file_offset,
&ordered_extent->list);
ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
ret = btrfs_update_inode_fallback(trans, root, inode);
if (ret) { /* -ENOMEM or corruption */
btrfs_abort_transaction(trans, root, ret);
goto out;
}
}
ret = 0;
out:
if (root != root->fs_info->tree_root)
btrfs_delalloc_release_metadata(inode, ordered_extent->len);
if (trans) {
if (nolock)
btrfs_end_transaction_nolock(trans, root);
else
btrfs_end_transaction(trans, root);
}
/* once for us */
btrfs_put_ordered_extent(ordered_extent);
/* once for the tree */
btrfs_put_ordered_extent(ordered_extent);
return 0;
out_unlock:
unlock_extent_cached(io_tree, ordered_extent->file_offset,
ordered_extent->file_offset +
ordered_extent->len - 1, &cached_state, GFP_NOFS);
goto out;
}
static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
struct extent_state *state, int uptodate)
{
trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
ClearPagePrivate2(page);
return btrfs_finish_ordered_io(page->mapping->host, start, end);
}
/*
* when reads are done, we need to check csums to verify the data is correct
* if there's a match, we allow the bio to finish. If not, the code in
* extent_io.c will try to find good copies for us.
*/
static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
struct extent_state *state, int mirror)
{
size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
struct inode *inode = page->mapping->host;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
char *kaddr;
u64 private = ~(u32)0;
int ret;
struct btrfs_root *root = BTRFS_I(inode)->root;
u32 csum = ~(u32)0;
if (PageChecked(page)) {
ClearPageChecked(page);
goto good;
}
if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
goto good;
if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
GFP_NOFS);
return 0;
}
if (state && state->start == start) {
private = state->private;
ret = 0;
} else {
ret = get_state_private(io_tree, start, &private);
}
kaddr = kmap_atomic(page);
if (ret)
goto zeroit;
csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
btrfs_csum_final(csum, (char *)&csum);
if (csum != private)
goto zeroit;
kunmap_atomic(kaddr);
good:
return 0;
zeroit:
printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
"private %llu\n",
(unsigned long long)btrfs_ino(page->mapping->host),
(unsigned long long)start, csum,
(unsigned long long)private);
memset(kaddr + offset, 1, end - start + 1);
flush_dcache_page(page);
kunmap_atomic(kaddr);
if (private == 0)
return 0;
return -EIO;
}
struct delayed_iput {
struct list_head list;
struct inode *inode;
};
/* JDM: If this is fs-wide, why can't we add a pointer to
* btrfs_inode instead and avoid the allocation? */
void btrfs_add_delayed_iput(struct inode *inode)
{
struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
struct delayed_iput *delayed;
if (atomic_add_unless(&inode->i_count, -1, 1))
return;
delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
delayed->inode = inode;
spin_lock(&fs_info->delayed_iput_lock);
list_add_tail(&delayed->list, &fs_info->delayed_iputs);
spin_unlock(&fs_info->delayed_iput_lock);
}
void btrfs_run_delayed_iputs(struct btrfs_root *root)
{
LIST_HEAD(list);
struct btrfs_fs_info *fs_info = root->fs_info;
struct delayed_iput *delayed;
int empty;
spin_lock(&fs_info->delayed_iput_lock);
empty = list_empty(&fs_info->delayed_iputs);
spin_unlock(&fs_info->delayed_iput_lock);
if (empty)
return;
down_read(&root->fs_info->cleanup_work_sem);
spin_lock(&fs_info->delayed_iput_lock);
list_splice_init(&fs_info->delayed_iputs, &list);
spin_unlock(&fs_info->delayed_iput_lock);
while (!list_empty(&list)) {
delayed = list_entry(list.next, struct delayed_iput, list);
list_del(&delayed->list);
iput(delayed->inode);
kfree(delayed);
}
up_read(&root->fs_info->cleanup_work_sem);
}
enum btrfs_orphan_cleanup_state {
ORPHAN_CLEANUP_STARTED = 1,
ORPHAN_CLEANUP_DONE = 2,
};
/*
* This is called in transaction commit time. If there are no orphan
* files in the subvolume, it removes orphan item and frees block_rsv
* structure.
*/
void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_block_rsv *block_rsv;
int ret;
if (!list_empty(&root->orphan_list) ||
root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
return;
spin_lock(&root->orphan_lock);
if (!list_empty(&root->orphan_list)) {
spin_unlock(&root->orphan_lock);
return;
}
if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
spin_unlock(&root->orphan_lock);
return;
}
block_rsv = root->orphan_block_rsv;
root->orphan_block_rsv = NULL;
spin_unlock(&root->orphan_lock);
if (root->orphan_item_inserted &&
btrfs_root_refs(&root->root_item) > 0) {
ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
root->root_key.objectid);
BUG_ON(ret);
root->orphan_item_inserted = 0;
}
if (block_rsv) {
WARN_ON(block_rsv->size > 0);
btrfs_free_block_rsv(root, block_rsv);
}
}
/*
* This creates an orphan entry for the given inode in case something goes
* wrong in the middle of an unlink/truncate.
*
* NOTE: caller of this function should reserve 5 units of metadata for
* this function.
*/
int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_block_rsv *block_rsv = NULL;
int reserve = 0;
int insert = 0;
int ret;
if (!root->orphan_block_rsv) {
block_rsv = btrfs_alloc_block_rsv(root);
if (!block_rsv)
return -ENOMEM;
}
spin_lock(&root->orphan_lock);
if (!root->orphan_block_rsv) {
root->orphan_block_rsv = block_rsv;
} else if (block_rsv) {
btrfs_free_block_rsv(root, block_rsv);
block_rsv = NULL;
}
if (list_empty(&BTRFS_I(inode)->i_orphan)) {
list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
#if 0
/*
* For proper ENOSPC handling, we should do orphan
* cleanup when mounting. But this introduces backward
* compatibility issue.
*/
if (!xchg(&root->orphan_item_inserted, 1))
insert = 2;
else
insert = 1;
#endif
insert = 1;
}
if (!BTRFS_I(inode)->orphan_meta_reserved) {
BTRFS_I(inode)->orphan_meta_reserved = 1;
reserve = 1;
}
spin_unlock(&root->orphan_lock);
/* grab metadata reservation from transaction handle */
if (reserve) {
ret = btrfs_orphan_reserve_metadata(trans, inode);
BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
}
/* insert an orphan item to track this unlinked/truncated file */
if (insert >= 1) {
ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
if (ret && ret != -EEXIST) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
ret = 0;
}
/* insert an orphan item to track subvolume contains orphan files */
if (insert >= 2) {
ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
root->root_key.objectid);
if (ret && ret != -EEXIST) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
}
return 0;
}
/*
* We have done the truncate/delete so we can go ahead and remove the orphan
* item for this particular inode.
*/
int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int delete_item = 0;
int release_rsv = 0;
int ret = 0;
spin_lock(&root->orphan_lock);
if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
list_del_init(&BTRFS_I(inode)->i_orphan);
delete_item = 1;
}
if (BTRFS_I(inode)->orphan_meta_reserved) {
BTRFS_I(inode)->orphan_meta_reserved = 0;
release_rsv = 1;
}
spin_unlock(&root->orphan_lock);
if (trans && delete_item) {
ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
}
if (release_rsv)
btrfs_orphan_release_metadata(inode);
return 0;
}
/*
* this cleans up any orphans that may be left on the list from the last use
* of this root.
*/
int btrfs_orphan_cleanup(struct btrfs_root *root)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_key key, found_key;
struct btrfs_trans_handle *trans;
struct inode *inode;
u64 last_objectid = 0;
int ret = 0, nr_unlink = 0, nr_truncate = 0;
if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
return 0;
path = btrfs_alloc_path();
if (!path) {
ret = -ENOMEM;
goto out;
}
path->reada = -1;
key.objectid = BTRFS_ORPHAN_OBJECTID;
btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
key.offset = (u64)-1;
while (1) {
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto out;
/*
* if ret == 0 means we found what we were searching for, which
* is weird, but possible, so only screw with path if we didn't
* find the key and see if we have stuff that matches
*/
if (ret > 0) {
ret = 0;
if (path->slots[0] == 0)
break;
path->slots[0]--;
}
/* pull out the item */
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
/* make sure the item matches what we want */
if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
break;
if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
break;
/* release the path since we're done with it */
btrfs_release_path(path);
/*
* this is where we are basically btrfs_lookup, without the
* crossing root thing. we store the inode number in the
* offset of the orphan item.
*/
if (found_key.offset == last_objectid) {
printk(KERN_ERR "btrfs: Error removing orphan entry, "
"stopping orphan cleanup\n");
ret = -EINVAL;
goto out;
}
last_objectid = found_key.offset;
found_key.objectid = found_key.offset;
found_key.type = BTRFS_INODE_ITEM_KEY;
found_key.offset = 0;
inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
ret = PTR_RET(inode);
if (ret && ret != -ESTALE)
goto out;
if (ret == -ESTALE && root == root->fs_info->tree_root) {
struct btrfs_root *dead_root;
struct btrfs_fs_info *fs_info = root->fs_info;
int is_dead_root = 0;
/*
* this is an orphan in the tree root. Currently these
* could come from 2 sources:
* a) a snapshot deletion in progress
* b) a free space cache inode
* We need to distinguish those two, as the snapshot
* orphan must not get deleted.
* find_dead_roots already ran before us, so if this
* is a snapshot deletion, we should find the root
* in the dead_roots list
*/
spin_lock(&fs_info->trans_lock);
list_for_each_entry(dead_root, &fs_info->dead_roots,
root_list) {
if (dead_root->root_key.objectid ==
found_key.objectid) {
is_dead_root = 1;
break;
}
}
spin_unlock(&fs_info->trans_lock);
if (is_dead_root) {
/* prevent this orphan from being found again */
key.offset = found_key.objectid - 1;
continue;
}
}
/*
* Inode is already gone but the orphan item is still there,
* kill the orphan item.
*/
if (ret == -ESTALE) {
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto out;
}
ret = btrfs_del_orphan_item(trans, root,
found_key.objectid);
BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
btrfs_end_transaction(trans, root);
continue;
}
/*
* add this inode to the orphan list so btrfs_orphan_del does
* the proper thing when we hit it
*/
spin_lock(&root->orphan_lock);
list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
spin_unlock(&root->orphan_lock);
/* if we have links, this was a truncate, lets do that */
if (inode->i_nlink) {
if (!S_ISREG(inode->i_mode)) {
WARN_ON(1);
iput(inode);
continue;
}
nr_truncate++;
ret = btrfs_truncate(inode);
} else {
nr_unlink++;
}
/* this will do delete_inode and everything for us */
iput(inode);
if (ret)
goto out;
}
/* release the path since we're done with it */
btrfs_release_path(path);
root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
if (root->orphan_block_rsv)
btrfs_block_rsv_release(root, root->orphan_block_rsv,
(u64)-1);
if (root->orphan_block_rsv || root->orphan_item_inserted) {
trans = btrfs_join_transaction(root);
if (!IS_ERR(trans))
btrfs_end_transaction(trans, root);
}
if (nr_unlink)
printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
if (nr_truncate)
printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
out:
if (ret)
printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
btrfs_free_path(path);
return ret;
}
/*
* very simple check to peek ahead in the leaf looking for xattrs. If we
* don't find any xattrs, we know there can't be any acls.
*
* slot is the slot the inode is in, objectid is the objectid of the inode
*/
static noinline int acls_after_inode_item(struct extent_buffer *leaf,
int slot, u64 objectid)
{
u32 nritems = btrfs_header_nritems(leaf);
struct btrfs_key found_key;
int scanned = 0;
slot++;
while (slot < nritems) {
btrfs_item_key_to_cpu(leaf, &found_key, slot);
/* we found a different objectid, there must not be acls */
if (found_key.objectid != objectid)
return 0;
/* we found an xattr, assume we've got an acl */
if (found_key.type == BTRFS_XATTR_ITEM_KEY)
return 1;
/*
* we found a key greater than an xattr key, there can't
* be any acls later on
*/
if (found_key.type > BTRFS_XATTR_ITEM_KEY)
return 0;
slot++;
scanned++;
/*
* it goes inode, inode backrefs, xattrs, extents,
* so if there are a ton of hard links to an inode there can
* be a lot of backrefs. Don't waste time searching too hard,
* this is just an optimization
*/
if (scanned >= 8)
break;
}
/* we hit the end of the leaf before we found an xattr or
* something larger than an xattr. We have to assume the inode
* has acls
*/
return 1;
}
/*
* read an inode from the btree into the in-memory inode
*/
static void btrfs_read_locked_inode(struct inode *inode)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_inode_item *inode_item;
struct btrfs_timespec *tspec;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_key location;
int maybe_acls;
u32 rdev;
int ret;
bool filled = false;
ret = btrfs_fill_inode(inode, &rdev);
if (!ret)
filled = true;
path = btrfs_alloc_path();
if (!path)
goto make_bad;
path->leave_spinning = 1;
memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
if (ret)
goto make_bad;
leaf = path->nodes[0];
if (filled)
goto cache_acl;
inode_item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_inode_item);
inode->i_mode = btrfs_inode_mode(leaf, inode_item);
set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
inode->i_uid = btrfs_inode_uid(leaf, inode_item);
inode->i_gid = btrfs_inode_gid(leaf, inode_item);
btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
tspec = btrfs_inode_atime(inode_item);
inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
tspec = btrfs_inode_mtime(inode_item);
inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
tspec = btrfs_inode_ctime(inode_item);
inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
inode->i_generation = BTRFS_I(inode)->generation;
inode->i_rdev = 0;
rdev = btrfs_inode_rdev(leaf, inode_item);
BTRFS_I(inode)->index_cnt = (u64)-1;
BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
cache_acl:
/*
* try to precache a NULL acl entry for files that don't have
* any xattrs or acls
*/
maybe_acls = acls_after_inode_item(leaf, path->slots[0],
btrfs_ino(inode));
if (!maybe_acls)
cache_no_acl(inode);
btrfs_free_path(path);
switch (inode->i_mode & S_IFMT) {
case S_IFREG:
inode->i_mapping->a_ops = &btrfs_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
inode->i_fop = &btrfs_file_operations;
inode->i_op = &btrfs_file_inode_operations;
break;
case S_IFDIR:
inode->i_fop = &btrfs_dir_file_operations;
if (root == root->fs_info->tree_root)
inode->i_op = &btrfs_dir_ro_inode_operations;
else
inode->i_op = &btrfs_dir_inode_operations;
break;
case S_IFLNK:
inode->i_op = &btrfs_symlink_inode_operations;
inode->i_mapping->a_ops = &btrfs_symlink_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
break;
default:
inode->i_op = &btrfs_special_inode_operations;
init_special_inode(inode, inode->i_mode, rdev);
break;
}
btrfs_update_iflags(inode);
return;
make_bad:
btrfs_free_path(path);
make_bad_inode(inode);
}
/*
* given a leaf and an inode, copy the inode fields into the leaf
*/
static void fill_inode_item(struct btrfs_trans_handle *trans,
struct extent_buffer *leaf,
struct btrfs_inode_item *item,
struct inode *inode)
{
btrfs_set_inode_uid(leaf, item, inode->i_uid);
btrfs_set_inode_gid(leaf, item, inode->i_gid);
btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
btrfs_set_inode_mode(leaf, item, inode->i_mode);
btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
inode->i_atime.tv_sec);
btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
inode->i_atime.tv_nsec);
btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
inode->i_mtime.tv_sec);
btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
inode->i_mtime.tv_nsec);
btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
inode->i_ctime.tv_sec);
btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
inode->i_ctime.tv_nsec);
btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
btrfs_set_inode_transid(leaf, item, trans->transid);
btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
btrfs_set_inode_block_group(leaf, item, 0);
}
/*
* copy everything in the in-memory inode into the btree.
*/
static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode)
{
struct btrfs_inode_item *inode_item;
struct btrfs_path *path;
struct extent_buffer *leaf;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->leave_spinning = 1;
ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
1);
if (ret) {
if (ret > 0)
ret = -ENOENT;
goto failed;
}
btrfs_unlock_up_safe(path, 1);
leaf = path->nodes[0];
inode_item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_inode_item);
fill_inode_item(trans, leaf, inode_item, inode);
btrfs_mark_buffer_dirty(leaf);
btrfs_set_inode_last_trans(trans, inode);
ret = 0;
failed:
btrfs_free_path(path);
return ret;
}
/*
* copy everything in the in-memory inode into the btree.
*/
noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode)
{
int ret;
/*
* If the inode is a free space inode, we can deadlock during commit
* if we put it into the delayed code.
*
* The data relocation inode should also be directly updated
* without delay
*/
if (!btrfs_is_free_space_inode(root, inode)
&& root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
ret = btrfs_delayed_update_inode(trans, root, inode);
if (!ret)
btrfs_set_inode_last_trans(trans, inode);
return ret;
}
return btrfs_update_inode_item(trans, root, inode);
}
static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode)
{
int ret;
ret = btrfs_update_inode(trans, root, inode);
if (ret == -ENOSPC)
return btrfs_update_inode_item(trans, root, inode);
return ret;
}
/*
* unlink helper that gets used here in inode.c and in the tree logging
* recovery code. It remove a link in a directory with a given name, and
* also drops the back refs in the inode to the directory
*/
static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir, struct inode *inode,
const char *name, int name_len)
{
struct btrfs_path *path;
int ret = 0;
struct extent_buffer *leaf;
struct btrfs_dir_item *di;
struct btrfs_key key;
u64 index;
u64 ino = btrfs_ino(inode);
u64 dir_ino = btrfs_ino(dir);
path = btrfs_alloc_path();
if (!path) {
ret = -ENOMEM;
goto out;
}
path->leave_spinning = 1;
di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
name, name_len, -1);
if (IS_ERR(di)) {
ret = PTR_ERR(di);
goto err;
}
if (!di) {
ret = -ENOENT;
goto err;
}
leaf = path->nodes[0];
btrfs_dir_item_key_to_cpu(leaf, di, &key);
ret = btrfs_delete_one_dir_name(trans, root, path, di);
if (ret)
goto err;
btrfs_release_path(path);
ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
dir_ino, &index);
if (ret) {
printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
"inode %llu parent %llu\n", name_len, name,
(unsigned long long)ino, (unsigned long long)dir_ino);
btrfs_abort_transaction(trans, root, ret);
goto err;
}
ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto err;
}
ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
inode, dir_ino);
if (ret != 0 && ret != -ENOENT) {
btrfs_abort_transaction(trans, root, ret);
goto err;
}
ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
dir, index);
if (ret == -ENOENT)
ret = 0;
err:
btrfs_free_path(path);
if (ret)
goto out;
btrfs_i_size_write(dir, dir->i_size - name_len * 2);
inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
btrfs_update_inode(trans, root, dir);
out:
return ret;
}
int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir, struct inode *inode,
const char *name, int name_len)
{
int ret;
ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
if (!ret) {
btrfs_drop_nlink(inode);
ret = btrfs_update_inode(trans, root, inode);
}
return ret;
}
/* helper to check if there is any shared block in the path */
static int check_path_shared(struct btrfs_root *root,
struct btrfs_path *path)
{
struct extent_buffer *eb;
int level;
u64 refs = 1;
for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
int ret;
if (!path->nodes[level])
break;
eb = path->nodes[level];
if (!btrfs_block_can_be_shared(root, eb))
continue;
ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
&refs, NULL);
if (refs > 1)
return 1;
}
return 0;
}
/*
* helper to start transaction for unlink and rmdir.
*
* unlink and rmdir are special in btrfs, they do not always free space.
* so in enospc case, we should make sure they will free space before
* allowing them to use the global metadata reservation.
*/
static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
struct dentry *dentry)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_path *path;
struct btrfs_inode_ref *ref;
struct btrfs_dir_item *di;
struct inode *inode = dentry->d_inode;
u64 index;
int check_link = 1;
int err = -ENOSPC;
int ret;
u64 ino = btrfs_ino(inode);
u64 dir_ino = btrfs_ino(dir);
/*
* 1 for the possible orphan item
* 1 for the dir item
* 1 for the dir index
* 1 for the inode ref
* 1 for the inode ref in the tree log
* 2 for the dir entries in the log
* 1 for the inode
*/
trans = btrfs_start_transaction(root, 8);
if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
return trans;
if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
return ERR_PTR(-ENOSPC);
/* check if there is someone else holds reference */
if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
return ERR_PTR(-ENOSPC);
if (atomic_read(&inode->i_count) > 2)
return ERR_PTR(-ENOSPC);
if (xchg(&root->fs_info->enospc_unlink, 1))
return ERR_PTR(-ENOSPC);
path = btrfs_alloc_path();
if (!path) {
root->fs_info->enospc_unlink = 0;
return ERR_PTR(-ENOMEM);
}
/* 1 for the orphan item */
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans)) {
btrfs_free_path(path);
root->fs_info->enospc_unlink = 0;
return trans;
}
path->skip_locking = 1;
path->search_commit_root = 1;
ret = btrfs_lookup_inode(trans, root, path,
&BTRFS_I(dir)->location, 0);
if (ret < 0) {
err = ret;
goto out;
}
if (ret == 0) {
if (check_path_shared(root, path))
goto out;
} else {
check_link = 0;
}
btrfs_release_path(path);
ret = btrfs_lookup_inode(trans, root, path,
&BTRFS_I(inode)->location, 0);
if (ret < 0) {
err = ret;
goto out;
}
if (ret == 0) {
if (check_path_shared(root, path))
goto out;
} else {
check_link = 0;
}
btrfs_release_path(path);
if (ret == 0 && S_ISREG(inode->i_mode)) {
ret = btrfs_lookup_file_extent(trans, root, path,
ino, (u64)-1, 0);
if (ret < 0) {
err = ret;
goto out;
}
BUG_ON(ret == 0); /* Corruption */
if (check_path_shared(root, path))
goto out;
btrfs_release_path(path);
}
if (!check_link) {
err = 0;
goto out;
}
di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
dentry->d_name.name, dentry->d_name.len, 0);
if (IS_ERR(di)) {
err = PTR_ERR(di);
goto out;
}
if (di) {
if (check_path_shared(root, path))
goto out;
} else {
err = 0;
goto out;
}
btrfs_release_path(path);
ref = btrfs_lookup_inode_ref(trans, root, path,
dentry->d_name.name, dentry->d_name.len,
ino, dir_ino, 0);
if (IS_ERR(ref)) {
err = PTR_ERR(ref);
goto out;
}
BUG_ON(!ref); /* Logic error */
if (check_path_shared(root, path))
goto out;
index = btrfs_inode_ref_index(path->nodes[0], ref);
btrfs_release_path(path);
/*
* This is a commit root search, if we can lookup inode item and other
* relative items in the commit root, it means the transaction of
* dir/file creation has been committed, and the dir index item that we
* delay to insert has also been inserted into the commit root. So
* we needn't worry about the delayed insertion of the dir index item
* here.
*/
di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
dentry->d_name.name, dentry->d_name.len, 0);
if (IS_ERR(di)) {
err = PTR_ERR(di);
goto out;
}
BUG_ON(ret == -ENOENT);
if (check_path_shared(root, path))
goto out;
err = 0;
out:
btrfs_free_path(path);
/* Migrate the orphan reservation over */
if (!err)
err = btrfs_block_rsv_migrate(trans->block_rsv,
&root->fs_info->global_block_rsv,
trans->bytes_reserved);
if (err) {
btrfs_end_transaction(trans, root);
root->fs_info->enospc_unlink = 0;
return ERR_PTR(err);
}
trans->block_rsv = &root->fs_info->global_block_rsv;
return trans;
}
static void __unlink_end_trans(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
if (trans->block_rsv == &root->fs_info->global_block_rsv) {
btrfs_block_rsv_release(root, trans->block_rsv,
trans->bytes_reserved);
trans->block_rsv = &root->fs_info->trans_block_rsv;
BUG_ON(!root->fs_info->enospc_unlink);
root->fs_info->enospc_unlink = 0;
}
btrfs_end_transaction(trans, root);
}
static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
{
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_trans_handle *trans;
struct inode *inode = dentry->d_inode;
int ret;
unsigned long nr = 0;
trans = __unlink_start_trans(dir, dentry);
if (IS_ERR(trans))
return PTR_ERR(trans);
btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
dentry->d_name.name, dentry->d_name.len);
if (ret)
goto out;
if (inode->i_nlink == 0) {
ret = btrfs_orphan_add(trans, inode);
if (ret)
goto out;
}
out:
nr = trans->blocks_used;
__unlink_end_trans(trans, root);
btrfs_btree_balance_dirty(root, nr);
return ret;
}
int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir, u64 objectid,
const char *name, int name_len)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_dir_item *di;
struct btrfs_key key;
u64 index;
int ret;
u64 dir_ino = btrfs_ino(dir);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
name, name_len, -1);
if (IS_ERR_OR_NULL(di)) {
if (!di)
ret = -ENOENT;
else
ret = PTR_ERR(di);
goto out;
}
leaf = path->nodes[0];
btrfs_dir_item_key_to_cpu(leaf, di, &key);
WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
ret = btrfs_delete_one_dir_name(trans, root, path, di);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
btrfs_release_path(path);
ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
objectid, root->root_key.objectid,
dir_ino, &index, name, name_len);
if (ret < 0) {
if (ret != -ENOENT) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
di = btrfs_search_dir_index_item(root, path, dir_ino,
name, name_len);
if (IS_ERR_OR_NULL(di)) {
if (!di)
ret = -ENOENT;
else
ret = PTR_ERR(di);
btrfs_abort_transaction(trans, root, ret);
goto out;
}
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
btrfs_release_path(path);
index = key.offset;
}
btrfs_release_path(path);
ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
btrfs_i_size_write(dir, dir->i_size - name_len * 2);
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode(trans, root, dir);
if (ret)
btrfs_abort_transaction(trans, root, ret);
out:
btrfs_free_path(path);
return ret;
}
static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
int err = 0;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_trans_handle *trans;
unsigned long nr = 0;
if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
return -ENOTEMPTY;
trans = __unlink_start_trans(dir, dentry);
if (IS_ERR(trans))
return PTR_ERR(trans);
if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
err = btrfs_unlink_subvol(trans, root, dir,
BTRFS_I(inode)->location.objectid,
dentry->d_name.name,
dentry->d_name.len);
goto out;
}
err = btrfs_orphan_add(trans, inode);
if (err)
goto out;
/* now the directory is empty */
err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
dentry->d_name.name, dentry->d_name.len);
if (!err)
btrfs_i_size_write(inode, 0);
out:
nr = trans->blocks_used;
__unlink_end_trans(trans, root);
btrfs_btree_balance_dirty(root, nr);
return err;
}
/*
* this can truncate away extent items, csum items and directory items.
* It starts at a high offset and removes keys until it can't find
* any higher than new_size
*
* csum items that cross the new i_size are truncated to the new size
* as well.
*
* min_type is the minimum key type to truncate down to. If set to 0, this
* will kill all the items on this inode, including the INODE_ITEM_KEY.
*/
int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *inode,
u64 new_size, u32 min_type)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
struct btrfs_key found_key;
u64 extent_start = 0;
u64 extent_num_bytes = 0;
u64 extent_offset = 0;
u64 item_end = 0;
u64 mask = root->sectorsize - 1;
u32 found_type = (u8)-1;
int found_extent;
int del_item;
int pending_del_nr = 0;
int pending_del_slot = 0;
int extent_type = -1;
int ret;
int err = 0;
u64 ino = btrfs_ino(inode);
BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->reada = -1;
if (root->ref_cows || root == root->fs_info->tree_root)
btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
/*
* This function is also used to drop the items in the log tree before
* we relog the inode, so if root != BTRFS_I(inode)->root, it means
* it is used to drop the loged items. So we shouldn't kill the delayed
* items.
*/
if (min_type == 0 && root == BTRFS_I(inode)->root)
btrfs_kill_delayed_inode_items(inode);
key.objectid = ino;
key.offset = (u64)-1;
key.type = (u8)-1;
search_again:
path->leave_spinning = 1;
ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
if (ret < 0) {
err = ret;
goto out;
}
if (ret > 0) {
/* there are no items in the tree for us to truncate, we're
* done
*/
if (path->slots[0] == 0)
goto out;
path->slots[0]--;
}
while (1) {
fi = NULL;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
found_type = btrfs_key_type(&found_key);
if (found_key.objectid != ino)
break;
if (found_type < min_type)
break;
item_end = found_key.offset;
if (found_type == BTRFS_EXTENT_DATA_KEY) {
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_type = btrfs_file_extent_type(leaf, fi);
if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
item_end +=
btrfs_file_extent_num_bytes(leaf, fi);
} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
item_end += btrfs_file_extent_inline_len(leaf,
fi);
}
item_end--;
}
if (found_type > min_type) {
del_item = 1;
} else {
if (item_end < new_size)
break;
if (found_key.offset >= new_size)
del_item = 1;
else
del_item = 0;
}
found_extent = 0;
/* FIXME, shrink the extent if the ref count is only 1 */
if (found_type != BTRFS_EXTENT_DATA_KEY)
goto delete;
if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
u64 num_dec;
extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
if (!del_item) {
u64 orig_num_bytes =
btrfs_file_extent_num_bytes(leaf, fi);
extent_num_bytes = new_size -
found_key.offset + root->sectorsize - 1;
extent_num_bytes = extent_num_bytes &
~((u64)root->sectorsize - 1);
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_num_bytes);
num_dec = (orig_num_bytes -
extent_num_bytes);
if (root->ref_cows && extent_start != 0)
inode_sub_bytes(inode, num_dec);
btrfs_mark_buffer_dirty(leaf);
} else {
extent_num_bytes =
btrfs_file_extent_disk_num_bytes(leaf,
fi);
extent_offset = found_key.offset -
btrfs_file_extent_offset(leaf, fi);
/* FIXME blocksize != 4096 */
num_dec = btrfs_file_extent_num_bytes(leaf, fi);
if (extent_start != 0) {
found_extent = 1;
if (root->ref_cows)
inode_sub_bytes(inode, num_dec);
}
}
} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
/*
* we can't truncate inline items that have had
* special encodings
*/
if (!del_item &&
btrfs_file_extent_compression(leaf, fi) == 0 &&
btrfs_file_extent_encryption(leaf, fi) == 0 &&
btrfs_file_extent_other_encoding(leaf, fi) == 0) {
u32 size = new_size - found_key.offset;
if (root->ref_cows) {
inode_sub_bytes(inode, item_end + 1 -
new_size);
}
size =
btrfs_file_extent_calc_inline_size(size);
btrfs_truncate_item(trans, root, path,
size, 1);
} else if (root->ref_cows) {
inode_sub_bytes(inode, item_end + 1 -
found_key.offset);
}
}
delete:
if (del_item) {
if (!pending_del_nr) {
/* no pending yet, add ourselves */
pending_del_slot = path->slots[0];
pending_del_nr = 1;
} else if (pending_del_nr &&
path->slots[0] + 1 == pending_del_slot) {
/* hop on the pending chunk */
pending_del_nr++;
pending_del_slot = path->slots[0];
} else {
BUG();
}
} else {
break;
}
if (found_extent && (root->ref_cows ||
root == root->fs_info->tree_root)) {
btrfs_set_path_blocking(path);
ret = btrfs_free_extent(trans, root, extent_start,
extent_num_bytes, 0,
btrfs_header_owner(leaf),
ino, extent_offset, 0);
BUG_ON(ret);
}
if (found_type == BTRFS_INODE_ITEM_KEY)
break;
if (path->slots[0] == 0 ||
path->slots[0] != pending_del_slot) {
if (root->ref_cows &&
BTRFS_I(inode)->location.objectid !=
BTRFS_FREE_INO_OBJECTID) {
err = -EAGAIN;
goto out;
}
if (pending_del_nr) {
ret = btrfs_del_items(trans, root, path,
pending_del_slot,
pending_del_nr);
if (ret) {
btrfs_abort_transaction(trans,
root, ret);
goto error;
}
pending_del_nr = 0;
}
btrfs_release_path(path);
goto search_again;
} else {
path->slots[0]--;
}
}
out:
if (pending_del_nr) {
ret = btrfs_del_items(trans, root, path, pending_del_slot,
pending_del_nr);
if (ret)
btrfs_abort_transaction(trans, root, ret);
}
error:
btrfs_free_path(path);
return err;
}
/*
* taken from block_truncate_page, but does cow as it zeros out
* any bytes left in the last page in the file.
*/
static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
{
struct inode *inode = mapping->host;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
char *kaddr;
u32 blocksize = root->sectorsize;
pgoff_t index = from >> PAGE_CACHE_SHIFT;
unsigned offset = from & (PAGE_CACHE_SIZE-1);
struct page *page;
gfp_t mask = btrfs_alloc_write_mask(mapping);
int ret = 0;
u64 page_start;
u64 page_end;
if ((offset & (blocksize - 1)) == 0)
goto out;
ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
if (ret)
goto out;
ret = -ENOMEM;
again:
page = find_or_create_page(mapping, index, mask);
if (!page) {
btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
goto out;
}
page_start = page_offset(page);
page_end = page_start + PAGE_CACHE_SIZE - 1;
if (!PageUptodate(page)) {
ret = btrfs_readpage(NULL, page);
lock_page(page);
if (page->mapping != mapping) {
unlock_page(page);
page_cache_release(page);
goto again;
}
if (!PageUptodate(page)) {
ret = -EIO;
goto out_unlock;
}
}
wait_on_page_writeback(page);
lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
set_page_extent_mapped(page);
ordered = btrfs_lookup_ordered_extent(inode, page_start);
if (ordered) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
unlock_page(page);
page_cache_release(page);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
goto again;
}
clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
0, 0, &cached_state, GFP_NOFS);
ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
&cached_state);
if (ret) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
goto out_unlock;
}
ret = 0;
if (offset != PAGE_CACHE_SIZE) {
kaddr = kmap(page);
memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
flush_dcache_page(page);
kunmap(page);
}
ClearPageChecked(page);
set_page_dirty(page);
unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
GFP_NOFS);
out_unlock:
if (ret)
btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
unlock_page(page);
page_cache_release(page);
out:
return ret;
}
/*
* This function puts in dummy file extents for the area we're creating a hole
* for. So if we are truncating this file to a larger size we need to insert
* these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
* the range between oldsize and size
*/
int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct extent_map *em = NULL;
struct extent_state *cached_state = NULL;
u64 mask = root->sectorsize - 1;
u64 hole_start = (oldsize + mask) & ~mask;
u64 block_end = (size + mask) & ~mask;
u64 last_byte;
u64 cur_offset;
u64 hole_size;
int err = 0;
if (size <= hole_start)
return 0;
while (1) {
struct btrfs_ordered_extent *ordered;
btrfs_wait_ordered_range(inode, hole_start,
block_end - hole_start);
lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
&cached_state);
ordered = btrfs_lookup_ordered_extent(inode, hole_start);
if (!ordered)
break;
unlock_extent_cached(io_tree, hole_start, block_end - 1,
&cached_state, GFP_NOFS);
btrfs_put_ordered_extent(ordered);
}
cur_offset = hole_start;
while (1) {
em = btrfs_get_extent(inode, NULL, 0, cur_offset,
block_end - cur_offset, 0);
if (IS_ERR(em)) {
err = PTR_ERR(em);
break;
}
last_byte = min(extent_map_end(em), block_end);
last_byte = (last_byte + mask) & ~mask;
if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
u64 hint_byte = 0;
hole_size = last_byte - cur_offset;
trans = btrfs_start_transaction(root, 3);
if (IS_ERR(trans)) {
err = PTR_ERR(trans);
break;
}
err = btrfs_drop_extents(trans, inode, cur_offset,
cur_offset + hole_size,
&hint_byte, 1);
if (err) {
btrfs_abort_transaction(trans, root, err);
btrfs_end_transaction(trans, root);
break;
}
err = btrfs_insert_file_extent(trans, root,
btrfs_ino(inode), cur_offset, 0,
0, hole_size, 0, hole_size,
0, 0, 0);
if (err) {
btrfs_abort_transaction(trans, root, err);
btrfs_end_transaction(trans, root);
break;
}
btrfs_drop_extent_cache(inode, hole_start,
last_byte - 1, 0);
btrfs_update_inode(trans, root, inode);
btrfs_end_transaction(trans, root);
}
free_extent_map(em);
em = NULL;
cur_offset = last_byte;
if (cur_offset >= block_end)
break;
}
free_extent_map(em);
unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
GFP_NOFS);
return err;
}
static int btrfs_setsize(struct inode *inode, loff_t newsize)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
loff_t oldsize = i_size_read(inode);
int ret;
if (newsize == oldsize)
return 0;
if (newsize > oldsize) {
truncate_pagecache(inode, oldsize, newsize);
ret = btrfs_cont_expand(inode, oldsize, newsize);
if (ret)
return ret;
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans))
return PTR_ERR(trans);
i_size_write(inode, newsize);
btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
ret = btrfs_update_inode(trans, root, inode);
btrfs_end_transaction(trans, root);
} else {
/*
* We're truncating a file that used to have good data down to
* zero. Make sure it gets into the ordered flush list so that
* any new writes get down to disk quickly.
*/
if (newsize == 0)
BTRFS_I(inode)->ordered_data_close = 1;
/* we don't support swapfiles, so vmtruncate shouldn't fail */
truncate_setsize(inode, newsize);
ret = btrfs_truncate(inode);
}
return ret;
}
static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = dentry->d_inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
int err;
if (btrfs_root_readonly(root))
return -EROFS;
err = inode_change_ok(inode, attr);
if (err)
return err;
if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
err = btrfs_setsize(inode, attr->ia_size);
if (err)
return err;
}
if (attr->ia_valid) {
setattr_copy(inode, attr);
err = btrfs_dirty_inode(inode);
if (!err && attr->ia_valid & ATTR_MODE)
err = btrfs_acl_chmod(inode);
}
return err;
}
void btrfs_evict_inode(struct inode *inode)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_block_rsv *rsv, *global_rsv;
u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
unsigned long nr;
int ret;
trace_btrfs_inode_evict(inode);
truncate_inode_pages(&inode->i_data, 0);
if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
btrfs_is_free_space_inode(root, inode)))
goto no_delete;
if (is_bad_inode(inode)) {
btrfs_orphan_del(NULL, inode);
goto no_delete;
}
/* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
btrfs_wait_ordered_range(inode, 0, (u64)-1);
if (root->fs_info->log_root_recovering) {
BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
goto no_delete;
}
if (inode->i_nlink > 0) {
BUG_ON(btrfs_root_refs(&root->root_item) != 0);
goto no_delete;
}
rsv = btrfs_alloc_block_rsv(root);
if (!rsv) {
btrfs_orphan_del(NULL, inode);
goto no_delete;
}
rsv->size = min_size;
global_rsv = &root->fs_info->global_block_rsv;
btrfs_i_size_write(inode, 0);
/*
* This is a bit simpler than btrfs_truncate since
*
* 1) We've already reserved our space for our orphan item in the
* unlink.
* 2) We're going to delete the inode item, so we don't need to update
* it at all.
*
* So we just need to reserve some slack space in case we add bytes when
* doing the truncate.
*/
while (1) {
ret = btrfs_block_rsv_refill_noflush(root, rsv, min_size);
/*
* Try and steal from the global reserve since we will
* likely not use this space anyway, we want to try as
* hard as possible to get this to work.
*/
if (ret)
ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
if (ret) {
printk(KERN_WARNING "Could not get space for a "
"delete, will truncate on mount %d\n", ret);
btrfs_orphan_del(NULL, inode);
btrfs_free_block_rsv(root, rsv);
goto no_delete;
}
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans)) {
btrfs_orphan_del(NULL, inode);
btrfs_free_block_rsv(root, rsv);
goto no_delete;
}
trans->block_rsv = rsv;
ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
if (ret != -EAGAIN)
break;
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
trans = NULL;
btrfs_btree_balance_dirty(root, nr);
}
btrfs_free_block_rsv(root, rsv);
if (ret == 0) {
trans->block_rsv = root->orphan_block_rsv;
ret = btrfs_orphan_del(trans, inode);
BUG_ON(ret);
}
trans->block_rsv = &root->fs_info->trans_block_rsv;
if (!(root == root->fs_info->tree_root ||
root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
btrfs_return_ino(root, btrfs_ino(inode));
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root, nr);
no_delete:
end_writeback(inode);
return;
}
/*
* this returns the key found in the dir entry in the location pointer.
* If no dir entries were found, location->objectid is 0.
*/
static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
struct btrfs_key *location)
{
const char *name = dentry->d_name.name;
int namelen = dentry->d_name.len;
struct btrfs_dir_item *di;
struct btrfs_path *path;
struct btrfs_root *root = BTRFS_I(dir)->root;
int ret = 0;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
namelen, 0);
if (IS_ERR(di))
ret = PTR_ERR(di);
if (IS_ERR_OR_NULL(di))
goto out_err;
btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
out:
btrfs_free_path(path);
return ret;
out_err:
location->objectid = 0;
goto out;
}
/*
* when we hit a tree root in a directory, the btrfs part of the inode
* needs to be changed to reflect the root directory of the tree root. This
* is kind of like crossing a mount point.
*/
static int fixup_tree_root_location(struct btrfs_root *root,
struct inode *dir,
struct dentry *dentry,
struct btrfs_key *location,
struct btrfs_root **sub_root)
{
struct btrfs_path *path;
struct btrfs_root *new_root;
struct btrfs_root_ref *ref;
struct extent_buffer *leaf;
int ret;
int err = 0;
path = btrfs_alloc_path();
if (!path) {
err = -ENOMEM;
goto out;
}
err = -ENOENT;
ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
BTRFS_I(dir)->root->root_key.objectid,
location->objectid);
if (ret) {
if (ret < 0)
err = ret;
goto out;
}
leaf = path->nodes[0];
ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
goto out;
ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
(unsigned long)(ref + 1),
dentry->d_name.len);
if (ret)
goto out;
btrfs_release_path(path);
new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
if (IS_ERR(new_root)) {
err = PTR_ERR(new_root);
goto out;
}
if (btrfs_root_refs(&new_root->root_item) == 0) {
err = -ENOENT;
goto out;
}
*sub_root = new_root;
location->objectid = btrfs_root_dirid(&new_root->root_item);
location->type = BTRFS_INODE_ITEM_KEY;
location->offset = 0;
err = 0;
out:
btrfs_free_path(path);
return err;
}
static void inode_tree_add(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_inode *entry;
struct rb_node **p;
struct rb_node *parent;
u64 ino = btrfs_ino(inode);
again:
p = &root->inode_tree.rb_node;
parent = NULL;
if (inode_unhashed(inode))
return;
spin_lock(&root->inode_lock);
while (*p) {
parent = *p;
entry = rb_entry(parent, struct btrfs_inode, rb_node);
if (ino < btrfs_ino(&entry->vfs_inode))
p = &parent->rb_left;
else if (ino > btrfs_ino(&entry->vfs_inode))
p = &parent->rb_right;
else {
WARN_ON(!(entry->vfs_inode.i_state &
(I_WILL_FREE | I_FREEING)));
rb_erase(parent, &root->inode_tree);
RB_CLEAR_NODE(parent);
spin_unlock(&root->inode_lock);
goto again;
}
}
rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
spin_unlock(&root->inode_lock);
}
static void inode_tree_del(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int empty = 0;
spin_lock(&root->inode_lock);
if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
empty = RB_EMPTY_ROOT(&root->inode_tree);
}
spin_unlock(&root->inode_lock);
/*
* Free space cache has inodes in the tree root, but the tree root has a
* root_refs of 0, so this could end up dropping the tree root as a
* snapshot, so we need the extra !root->fs_info->tree_root check to
* make sure we don't drop it.
*/
if (empty && btrfs_root_refs(&root->root_item) == 0 &&
root != root->fs_info->tree_root) {
synchronize_srcu(&root->fs_info->subvol_srcu);
spin_lock(&root->inode_lock);
empty = RB_EMPTY_ROOT(&root->inode_tree);
spin_unlock(&root->inode_lock);
if (empty)
btrfs_add_dead_root(root);
}
}
void btrfs_invalidate_inodes(struct btrfs_root *root)
{
struct rb_node *node;
struct rb_node *prev;
struct btrfs_inode *entry;
struct inode *inode;
u64 objectid = 0;
WARN_ON(btrfs_root_refs(&root->root_item) != 0);
spin_lock(&root->inode_lock);
again:
node = root->inode_tree.rb_node;
prev = NULL;
while (node) {
prev = node;
entry = rb_entry(node, struct btrfs_inode, rb_node);
if (objectid < btrfs_ino(&entry->vfs_inode))
node = node->rb_left;
else if (objectid > btrfs_ino(&entry->vfs_inode))
node = node->rb_right;
else
break;
}
if (!node) {
while (prev) {
entry = rb_entry(prev, struct btrfs_inode, rb_node);
if (objectid <= btrfs_ino(&entry->vfs_inode)) {
node = prev;
break;
}
prev = rb_next(prev);
}
}
while (node) {
entry = rb_entry(node, struct btrfs_inode, rb_node);
objectid = btrfs_ino(&entry->vfs_inode) + 1;
inode = igrab(&entry->vfs_inode);
if (inode) {
spin_unlock(&root->inode_lock);
if (atomic_read(&inode->i_count) > 1)
d_prune_aliases(inode);
/*
* btrfs_drop_inode will have it removed from
* the inode cache when its usage count
* hits zero.
*/
iput(inode);
cond_resched();
spin_lock(&root->inode_lock);
goto again;
}
if (cond_resched_lock(&root->inode_lock))
goto again;
node = rb_next(node);
}
spin_unlock(&root->inode_lock);
}
static int btrfs_init_locked_inode(struct inode *inode, void *p)
{
struct btrfs_iget_args *args = p;
inode->i_ino = args->ino;
BTRFS_I(inode)->root = args->root;
btrfs_set_inode_space_info(args->root, inode);
return 0;
}
static int btrfs_find_actor(struct inode *inode, void *opaque)
{
struct btrfs_iget_args *args = opaque;
return args->ino == btrfs_ino(inode) &&
args->root == BTRFS_I(inode)->root;
}
static struct inode *btrfs_iget_locked(struct super_block *s,
u64 objectid,
struct btrfs_root *root)
{
struct inode *inode;
struct btrfs_iget_args args;
args.ino = objectid;
args.root = root;
inode = iget5_locked(s, objectid, btrfs_find_actor,
btrfs_init_locked_inode,
(void *)&args);
return inode;
}
/* Get an inode object given its location and corresponding root.
* Returns in *is_new if the inode was read from disk
*/
struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
struct btrfs_root *root, int *new)
{
struct inode *inode;
inode = btrfs_iget_locked(s, location->objectid, root);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
BTRFS_I(inode)->root = root;
memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
btrfs_read_locked_inode(inode);
if (!is_bad_inode(inode)) {
inode_tree_add(inode);
unlock_new_inode(inode);
if (new)
*new = 1;
} else {
unlock_new_inode(inode);
iput(inode);
inode = ERR_PTR(-ESTALE);
}
}
return inode;
}
static struct inode *new_simple_dir(struct super_block *s,
struct btrfs_key *key,
struct btrfs_root *root)
{
struct inode *inode = new_inode(s);
if (!inode)
return ERR_PTR(-ENOMEM);
BTRFS_I(inode)->root = root;
memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
BTRFS_I(inode)->dummy_inode = 1;
inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
inode->i_op = &btrfs_dir_ro_inode_operations;
inode->i_fop = &simple_dir_operations;
inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
return inode;
}
struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
{
struct inode *inode;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_root *sub_root = root;
struct btrfs_key location;
int index;
int ret = 0;
if (dentry->d_name.len > BTRFS_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
if (unlikely(d_need_lookup(dentry))) {
memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
kfree(dentry->d_fsdata);
dentry->d_fsdata = NULL;
/* This thing is hashed, drop it for now */
d_drop(dentry);
} else {
ret = btrfs_inode_by_name(dir, dentry, &location);
}
if (ret < 0)
return ERR_PTR(ret);
if (location.objectid == 0)
return NULL;
if (location.type == BTRFS_INODE_ITEM_KEY) {
inode = btrfs_iget(dir->i_sb, &location, root, NULL);
return inode;
}
BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
index = srcu_read_lock(&root->fs_info->subvol_srcu);
ret = fixup_tree_root_location(root, dir, dentry,
&location, &sub_root);
if (ret < 0) {
if (ret != -ENOENT)
inode = ERR_PTR(ret);
else
inode = new_simple_dir(dir->i_sb, &location, sub_root);
} else {
inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
}
srcu_read_unlock(&root->fs_info->subvol_srcu, index);
if (!IS_ERR(inode) && root != sub_root) {
down_read(&root->fs_info->cleanup_work_sem);
if (!(inode->i_sb->s_flags & MS_RDONLY))
ret = btrfs_orphan_cleanup(sub_root);
up_read(&root->fs_info->cleanup_work_sem);
if (ret)
inode = ERR_PTR(ret);
}
return inode;
}
static int btrfs_dentry_delete(const struct dentry *dentry)
{
struct btrfs_root *root;
struct inode *inode = dentry->d_inode;
if (!inode && !IS_ROOT(dentry))
inode = dentry->d_parent->d_inode;
if (inode) {
root = BTRFS_I(inode)->root;
if (btrfs_root_refs(&root->root_item) == 0)
return 1;
if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
return 1;
}
return 0;
}
static void btrfs_dentry_release(struct dentry *dentry)
{
if (dentry->d_fsdata)
kfree(dentry->d_fsdata);
}
static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
struct nameidata *nd)
{
struct dentry *ret;
ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
if (unlikely(d_need_lookup(dentry))) {
spin_lock(&dentry->d_lock);
dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
spin_unlock(&dentry->d_lock);
}
return ret;
}
unsigned char btrfs_filetype_table[] = {
DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
};
static int btrfs_real_readdir(struct file *filp, void *dirent,
filldir_t filldir)
{
struct inode *inode = filp->f_dentry->d_inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_item *item;
struct btrfs_dir_item *di;
struct btrfs_key key;
struct btrfs_key found_key;
struct btrfs_path *path;
struct list_head ins_list;
struct list_head del_list;
int ret;
struct extent_buffer *leaf;
int slot;
unsigned char d_type;
int over = 0;
u32 di_cur;
u32 di_total;
u32 di_len;
int key_type = BTRFS_DIR_INDEX_KEY;
char tmp_name[32];
char *name_ptr;
int name_len;
int is_curr = 0; /* filp->f_pos points to the current index? */
/* FIXME, use a real flag for deciding about the key type */
if (root->fs_info->tree_root == root)
key_type = BTRFS_DIR_ITEM_KEY;
/* special case for "." */
if (filp->f_pos == 0) {
over = filldir(dirent, ".", 1,
filp->f_pos, btrfs_ino(inode), DT_DIR);
if (over)
return 0;
filp->f_pos = 1;
}
/* special case for .., just use the back ref */
if (filp->f_pos == 1) {
u64 pino = parent_ino(filp->f_path.dentry);
over = filldir(dirent, "..", 2,
filp->f_pos, pino, DT_DIR);
if (over)
return 0;
filp->f_pos = 2;
}
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->reada = 1;
if (key_type == BTRFS_DIR_INDEX_KEY) {
INIT_LIST_HEAD(&ins_list);
INIT_LIST_HEAD(&del_list);
btrfs_get_delayed_items(inode, &ins_list, &del_list);
}
btrfs_set_key_type(&key, key_type);
key.offset = filp->f_pos;
key.objectid = btrfs_ino(inode);
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto err;
while (1) {
leaf = path->nodes[0];
slot = path->slots[0];
if (slot >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0)
goto err;
else if (ret > 0)
break;
continue;
}
item = btrfs_item_nr(leaf, slot);
btrfs_item_key_to_cpu(leaf, &found_key, slot);
if (found_key.objectid != key.objectid)
break;
if (btrfs_key_type(&found_key) != key_type)
break;
if (found_key.offset < filp->f_pos)
goto next;
if (key_type == BTRFS_DIR_INDEX_KEY &&
btrfs_should_delete_dir_index(&del_list,
found_key.offset))
goto next;
filp->f_pos = found_key.offset;
is_curr = 1;
di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
di_cur = 0;
di_total = btrfs_item_size(leaf, item);
while (di_cur < di_total) {
struct btrfs_key location;
if (verify_dir_item(root, leaf, di))
break;
name_len = btrfs_dir_name_len(leaf, di);
if (name_len <= sizeof(tmp_name)) {
name_ptr = tmp_name;
} else {
name_ptr = kmalloc(name_len, GFP_NOFS);
if (!name_ptr) {
ret = -ENOMEM;
goto err;
}
}
read_extent_buffer(leaf, name_ptr,
(unsigned long)(di + 1), name_len);
d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
btrfs_dir_item_key_to_cpu(leaf, di, &location);
/* is this a reference to our own snapshot? If so
* skip it.
*
* In contrast to old kernels, we insert the snapshot's
* dir item and dir index after it has been created, so
* we won't find a reference to our own snapshot. We
* still keep the following code for backward
* compatibility.
*/
if (location.type == BTRFS_ROOT_ITEM_KEY &&
location.objectid == root->root_key.objectid) {
over = 0;
goto skip;
}
over = filldir(dirent, name_ptr, name_len,
found_key.offset, location.objectid,
d_type);
skip:
if (name_ptr != tmp_name)
kfree(name_ptr);
if (over)
goto nopos;
di_len = btrfs_dir_name_len(leaf, di) +
btrfs_dir_data_len(leaf, di) + sizeof(*di);
di_cur += di_len;
di = (struct btrfs_dir_item *)((char *)di + di_len);
}
next:
path->slots[0]++;
}
if (key_type == BTRFS_DIR_INDEX_KEY) {
if (is_curr)
filp->f_pos++;
ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
&ins_list);
if (ret)
goto nopos;
}
/* Reached end of directory/root. Bump pos past the last item. */
if (key_type == BTRFS_DIR_INDEX_KEY)
/*
* 32-bit glibc will use getdents64, but then strtol -
* so the last number we can serve is this.
*/
filp->f_pos = 0x7fffffff;
else
filp->f_pos++;
nopos:
ret = 0;
err:
if (key_type == BTRFS_DIR_INDEX_KEY)
btrfs_put_delayed_items(&ins_list, &del_list);
btrfs_free_path(path);
return ret;
}
int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
int ret = 0;
bool nolock = false;
if (BTRFS_I(inode)->dummy_inode)
return 0;
if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(root, inode))
nolock = true;
if (wbc->sync_mode == WB_SYNC_ALL) {
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return PTR_ERR(trans);
if (nolock)
ret = btrfs_end_transaction_nolock(trans, root);
else
ret = btrfs_commit_transaction(trans, root);
}
return ret;
}
/*
* This is somewhat expensive, updating the tree every time the
* inode changes. But, it is most likely to find the inode in cache.
* FIXME, needs more benchmarking...there are no reasons other than performance
* to keep or drop this code.
*/
int btrfs_dirty_inode(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
int ret;
if (BTRFS_I(inode)->dummy_inode)
return 0;
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return PTR_ERR(trans);
ret = btrfs_update_inode(trans, root, inode);
if (ret && ret == -ENOSPC) {
/* whoops, lets try again with the full transaction */
btrfs_end_transaction(trans, root);
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans))
return PTR_ERR(trans);
ret = btrfs_update_inode(trans, root, inode);
}
btrfs_end_transaction(trans, root);
if (BTRFS_I(inode)->delayed_node)
btrfs_balance_delayed_items(root);
return ret;
}
/*
* This is a copy of file_update_time. We need this so we can return error on
* ENOSPC for updating the inode in the case of file write and mmap writes.
*/
int btrfs_update_time(struct file *file)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct timespec now;
int ret;
enum { S_MTIME = 1, S_CTIME = 2, S_VERSION = 4 } sync_it = 0;
/* First try to exhaust all avenues to not sync */
if (IS_NOCMTIME(inode))
return 0;
now = current_fs_time(inode->i_sb);
if (!timespec_equal(&inode->i_mtime, &now))
sync_it = S_MTIME;
if (!timespec_equal(&inode->i_ctime, &now))
sync_it |= S_CTIME;
if (IS_I_VERSION(inode))
sync_it |= S_VERSION;
if (!sync_it)
return 0;
/* Finally allowed to write? Takes lock. */
if (mnt_want_write_file(file))
return 0;
/* Only change inode inside the lock region */
if (sync_it & S_VERSION)
inode_inc_iversion(inode);
if (sync_it & S_CTIME)
inode->i_ctime = now;
if (sync_it & S_MTIME)
inode->i_mtime = now;
ret = btrfs_dirty_inode(inode);
if (!ret)
mark_inode_dirty_sync(inode);
mnt_drop_write(file->f_path.mnt);
return ret;
}
/*
* find the highest existing sequence number in a directory
* and then set the in-memory index_cnt variable to reflect
* free sequence numbers
*/
static int btrfs_set_inode_index_count(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_key key, found_key;
struct btrfs_path *path;
struct extent_buffer *leaf;
int ret;
key.objectid = btrfs_ino(inode);
btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
key.offset = (u64)-1;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto out;
/* FIXME: we should be able to handle this */
if (ret == 0)
goto out;
ret = 0;
/*
* MAGIC NUMBER EXPLANATION:
* since we search a directory based on f_pos we have to start at 2
* since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
* else has to start at 2
*/
if (path->slots[0] == 0) {
BTRFS_I(inode)->index_cnt = 2;
goto out;
}
path->slots[0]--;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
if (found_key.objectid != btrfs_ino(inode) ||
btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
BTRFS_I(inode)->index_cnt = 2;
goto out;
}
BTRFS_I(inode)->index_cnt = found_key.offset + 1;
out:
btrfs_free_path(path);
return ret;
}
/*
* helper to find a free sequence number in a given directory. This current
* code is very simple, later versions will do smarter things in the btree
*/
int btrfs_set_inode_index(struct inode *dir, u64 *index)
{
int ret = 0;
if (BTRFS_I(dir)->index_cnt == (u64)-1) {
ret = btrfs_inode_delayed_dir_index_count(dir);
if (ret) {
ret = btrfs_set_inode_index_count(dir);
if (ret)
return ret;
}
}
*index = BTRFS_I(dir)->index_cnt;
BTRFS_I(dir)->index_cnt++;
return ret;
}
static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir,
const char *name, int name_len,
u64 ref_objectid, u64 objectid,
umode_t mode, u64 *index)
{
struct inode *inode;
struct btrfs_inode_item *inode_item;
struct btrfs_key *location;
struct btrfs_path *path;
struct btrfs_inode_ref *ref;
struct btrfs_key key[2];
u32 sizes[2];
unsigned long ptr;
int ret;
int owner;
path = btrfs_alloc_path();
if (!path)
return ERR_PTR(-ENOMEM);
inode = new_inode(root->fs_info->sb);
if (!inode) {
btrfs_free_path(path);
return ERR_PTR(-ENOMEM);
}
/*
* we have to initialize this early, so we can reclaim the inode
* number if we fail afterwards in this function.
*/
inode->i_ino = objectid;
if (dir) {
trace_btrfs_inode_request(dir);
ret = btrfs_set_inode_index(dir, index);
if (ret) {
btrfs_free_path(path);
iput(inode);
return ERR_PTR(ret);
}
}
/*
* index_cnt is ignored for everything but a dir,
* btrfs_get_inode_index_count has an explanation for the magic
* number
*/
BTRFS_I(inode)->index_cnt = 2;
BTRFS_I(inode)->root = root;
BTRFS_I(inode)->generation = trans->transid;
inode->i_generation = BTRFS_I(inode)->generation;
btrfs_set_inode_space_info(root, inode);
if (S_ISDIR(mode))
owner = 0;
else
owner = 1;
key[0].objectid = objectid;
btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
key[0].offset = 0;
key[1].objectid = objectid;
btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
key[1].offset = ref_objectid;
sizes[0] = sizeof(struct btrfs_inode_item);
sizes[1] = name_len + sizeof(*ref);
path->leave_spinning = 1;
ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
if (ret != 0)
goto fail;
inode_init_owner(inode, dir, mode);
inode_set_bytes(inode, 0);
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_inode_item);
fill_inode_item(trans, path->nodes[0], inode_item, inode);
ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
struct btrfs_inode_ref);
btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
ptr = (unsigned long)(ref + 1);
write_extent_buffer(path->nodes[0], name, ptr, name_len);
btrfs_mark_buffer_dirty(path->nodes[0]);
btrfs_free_path(path);
location = &BTRFS_I(inode)->location;
location->objectid = objectid;
location->offset = 0;
btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
btrfs_inherit_iflags(inode, dir);
if (S_ISREG(mode)) {
if (btrfs_test_opt(root, NODATASUM))
BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
if (btrfs_test_opt(root, NODATACOW) ||
(BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
}
insert_inode_hash(inode);
inode_tree_add(inode);
trace_btrfs_inode_new(inode);
btrfs_set_inode_last_trans(trans, inode);
return inode;
fail:
if (dir)
BTRFS_I(dir)->index_cnt--;
btrfs_free_path(path);
iput(inode);
return ERR_PTR(ret);
}
static inline u8 btrfs_inode_type(struct inode *inode)
{
return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
}
/*
* utility function to add 'inode' into 'parent_inode' with
* a give name and a given sequence number.
* if 'add_backref' is true, also insert a backref from the
* inode to the parent directory.
*/
int btrfs_add_link(struct btrfs_trans_handle *trans,
struct inode *parent_inode, struct inode *inode,
const char *name, int name_len, int add_backref, u64 index)
{
int ret = 0;
struct btrfs_key key;
struct btrfs_root *root = BTRFS_I(parent_inode)->root;
u64 ino = btrfs_ino(inode);
u64 parent_ino = btrfs_ino(parent_inode);
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
} else {
key.objectid = ino;
btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
key.offset = 0;
}
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, index, name, name_len);
} else if (add_backref) {
ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
parent_ino, index);
}
/* Nothing to clean up yet */
if (ret)
return ret;
ret = btrfs_insert_dir_item(trans, root, name, name_len,
parent_inode, &key,
btrfs_inode_type(inode), index);
if (ret == -EEXIST)
goto fail_dir_item;
else if (ret) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
btrfs_i_size_write(parent_inode, parent_inode->i_size +
name_len * 2);
parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode(trans, root, parent_inode);
if (ret)
btrfs_abort_transaction(trans, root, ret);
return ret;
fail_dir_item:
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
u64 local_index;
int err;
err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, &local_index, name, name_len);
} else if (add_backref) {
u64 local_index;
int err;
err = btrfs_del_inode_ref(trans, root, name, name_len,
ino, parent_ino, &local_index);
}
return ret;
}
static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
struct inode *dir, struct dentry *dentry,
struct inode *inode, int backref, u64 index)
{
int err = btrfs_add_link(trans, dir, inode,
dentry->d_name.name, dentry->d_name.len,
backref, index);
if (err > 0)
err = -EEXIST;
return err;
}
static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t rdev)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct inode *inode = NULL;
int err;
int drop_inode = 0;
u64 objectid;
unsigned long nr = 0;
u64 index = 0;
if (!new_valid_dev(rdev))
return -EINVAL;
/*
* 2 for inode item and ref
* 2 for dir items
* 1 for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_unlock;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
mode, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_unlock;
}
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err) {
drop_inode = 1;
goto out_unlock;
}
/*
* If the active LSM wants to access the inode during
* d_instantiate it needs these. Smack checks to see
* if the filesystem supports xattrs by looking at the
* ops vector.
*/
inode->i_op = &btrfs_special_inode_operations;
err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
if (err)
drop_inode = 1;
else {
init_special_inode(inode, inode->i_mode, rdev);
btrfs_update_inode(trans, root, inode);
d_instantiate(dentry, inode);
}
out_unlock:
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root, nr);
if (drop_inode) {
inode_dec_link_count(inode);
iput(inode);
}
return err;
}
static int btrfs_create(struct inode *dir, struct dentry *dentry,
umode_t mode, struct nameidata *nd)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct inode *inode = NULL;
int drop_inode = 0;
int err;
unsigned long nr = 0;
u64 objectid;
u64 index = 0;
/*
* 2 for inode item and ref
* 2 for dir items
* 1 for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_unlock;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
mode, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_unlock;
}
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err) {
drop_inode = 1;
goto out_unlock;
}
/*
* If the active LSM wants to access the inode during
* d_instantiate it needs these. Smack checks to see
* if the filesystem supports xattrs by looking at the
* ops vector.
*/
inode->i_fop = &btrfs_file_operations;
inode->i_op = &btrfs_file_inode_operations;
err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
if (err)
drop_inode = 1;
else {
inode->i_mapping->a_ops = &btrfs_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
d_instantiate(dentry, inode);
}
out_unlock:
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
if (drop_inode) {
inode_dec_link_count(inode);
iput(inode);
}
btrfs_btree_balance_dirty(root, nr);
return err;
}
static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct inode *inode = old_dentry->d_inode;
u64 index;
unsigned long nr = 0;
int err;
int drop_inode = 0;
/* do not allow sys_link's with other subvols of the same device */
if (root->objectid != BTRFS_I(inode)->root->objectid)
return -EXDEV;
if (inode->i_nlink == ~0U)
return -EMLINK;
err = btrfs_set_inode_index(dir, &index);
if (err)
goto fail;
/*
* 2 items for inode and inode ref
* 2 items for dir items
* 1 item for parent inode
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans)) {
err = PTR_ERR(trans);
goto fail;
}
btrfs_inc_nlink(inode);
inode->i_ctime = CURRENT_TIME;
ihold(inode);
err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
if (err) {
drop_inode = 1;
} else {
struct dentry *parent = dentry->d_parent;
err = btrfs_update_inode(trans, root, inode);
if (err)
goto fail;
d_instantiate(dentry, inode);
btrfs_log_new_name(trans, inode, NULL, parent);
}
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
fail:
if (drop_inode) {
inode_dec_link_count(inode);
iput(inode);
}
btrfs_btree_balance_dirty(root, nr);
return err;
}
static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
struct inode *inode = NULL;
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
int err = 0;
int drop_on_err = 0;
u64 objectid = 0;
u64 index = 0;
unsigned long nr = 1;
/*
* 2 items for inode and ref
* 2 items for dir items
* 1 for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_fail;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
S_IFDIR | mode, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_fail;
}
drop_on_err = 1;
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err)
goto out_fail;
inode->i_op = &btrfs_dir_inode_operations;
inode->i_fop = &btrfs_dir_file_operations;
btrfs_i_size_write(inode, 0);
err = btrfs_update_inode(trans, root, inode);
if (err)
goto out_fail;
err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
dentry->d_name.len, 0, index);
if (err)
goto out_fail;
d_instantiate(dentry, inode);
drop_on_err = 0;
out_fail:
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
if (drop_on_err)
iput(inode);
btrfs_btree_balance_dirty(root, nr);
return err;
}
/* helper for btfs_get_extent. Given an existing extent in the tree,
* and an extent that you want to insert, deal with overlap and insert
* the new extent into the tree.
*/
static int merge_extent_mapping(struct extent_map_tree *em_tree,
struct extent_map *existing,
struct extent_map *em,
u64 map_start, u64 map_len)
{
u64 start_diff;
BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
start_diff = map_start - em->start;
em->start = map_start;
em->len = map_len;
if (em->block_start < EXTENT_MAP_LAST_BYTE &&
!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
em->block_start += start_diff;
em->block_len -= start_diff;
}
return add_extent_mapping(em_tree, em);
}
static noinline int uncompress_inline(struct btrfs_path *path,
struct inode *inode, struct page *page,
size_t pg_offset, u64 extent_offset,
struct btrfs_file_extent_item *item)
{
int ret;
struct extent_buffer *leaf = path->nodes[0];
char *tmp;
size_t max_size;
unsigned long inline_size;
unsigned long ptr;
int compress_type;
WARN_ON(pg_offset != 0);
compress_type = btrfs_file_extent_compression(leaf, item);
max_size = btrfs_file_extent_ram_bytes(leaf, item);
inline_size = btrfs_file_extent_inline_item_len(leaf,
btrfs_item_nr(leaf, path->slots[0]));
tmp = kmalloc(inline_size, GFP_NOFS);
if (!tmp)
return -ENOMEM;
ptr = btrfs_file_extent_inline_start(item);
read_extent_buffer(leaf, tmp, ptr, inline_size);
max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
ret = btrfs_decompress(compress_type, tmp, page,
extent_offset, inline_size, max_size);
if (ret) {
char *kaddr = kmap_atomic(page);
unsigned long copy_size = min_t(u64,
PAGE_CACHE_SIZE - pg_offset,
max_size - extent_offset);
memset(kaddr + pg_offset, 0, copy_size);
kunmap_atomic(kaddr);
}
kfree(tmp);
return 0;
}
/*
* a bit scary, this does extent mapping from logical file offset to the disk.
* the ugly parts come from merging extents from the disk with the in-ram
* representation. This gets more complex because of the data=ordered code,
* where the in-ram extents might be locked pending data=ordered completion.
*
* This also copies inline extents directly into the page.
*/
struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
size_t pg_offset, u64 start, u64 len,
int create)
{
int ret;
int err = 0;
u64 bytenr;
u64 extent_start = 0;
u64 extent_end = 0;
u64 objectid = btrfs_ino(inode);
u32 found_type;
struct btrfs_path *path = NULL;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_file_extent_item *item;
struct extent_buffer *leaf;
struct btrfs_key found_key;
struct extent_map *em = NULL;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct btrfs_trans_handle *trans = NULL;
int compress_type;
again:
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, start, len);
if (em)
em->bdev = root->fs_info->fs_devices->latest_bdev;
read_unlock(&em_tree->lock);
if (em) {
if (em->start > start || em->start + em->len <= start)
free_extent_map(em);
else if (em->block_start == EXTENT_MAP_INLINE && page)
free_extent_map(em);
else
goto out;
}
em = alloc_extent_map();
if (!em) {
err = -ENOMEM;
goto out;
}
em->bdev = root->fs_info->fs_devices->latest_bdev;
em->start = EXTENT_MAP_HOLE;
em->orig_start = EXTENT_MAP_HOLE;
em->len = (u64)-1;
em->block_len = (u64)-1;
if (!path) {
path = btrfs_alloc_path();
if (!path) {
err = -ENOMEM;
goto out;
}
/*
* Chances are we'll be called again, so go ahead and do
* readahead
*/
path->reada = 1;
}
ret = btrfs_lookup_file_extent(trans, root, path,
objectid, start, trans != NULL);
if (ret < 0) {
err = ret;
goto out;
}
if (ret != 0) {
if (path->slots[0] == 0)
goto not_found;
path->slots[0]--;
}
leaf = path->nodes[0];
item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
/* are we inside the extent that was found? */
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
found_type = btrfs_key_type(&found_key);
if (found_key.objectid != objectid ||
found_type != BTRFS_EXTENT_DATA_KEY) {
goto not_found;
}
found_type = btrfs_file_extent_type(leaf, item);
extent_start = found_key.offset;
compress_type = btrfs_file_extent_compression(leaf, item);
if (found_type == BTRFS_FILE_EXTENT_REG ||
found_type == BTRFS_FILE_EXTENT_PREALLOC) {
extent_end = extent_start +
btrfs_file_extent_num_bytes(leaf, item);
} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
size_t size;
size = btrfs_file_extent_inline_len(leaf, item);
extent_end = (extent_start + size + root->sectorsize - 1) &
~((u64)root->sectorsize - 1);
}
if (start >= extent_end) {
path->slots[0]++;
if (path->slots[0] >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0) {
err = ret;
goto out;
}
if (ret > 0)
goto not_found;
leaf = path->nodes[0];
}
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
if (found_key.objectid != objectid ||
found_key.type != BTRFS_EXTENT_DATA_KEY)
goto not_found;
if (start + len <= found_key.offset)
goto not_found;
em->start = start;
em->len = found_key.offset - start;
goto not_found_em;
}
if (found_type == BTRFS_FILE_EXTENT_REG ||
found_type == BTRFS_FILE_EXTENT_PREALLOC) {
em->start = extent_start;
em->len = extent_end - extent_start;
em->orig_start = extent_start -
btrfs_file_extent_offset(leaf, item);
bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
if (bytenr == 0) {
em->block_start = EXTENT_MAP_HOLE;
goto insert;
}
if (compress_type != BTRFS_COMPRESS_NONE) {
set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
em->compress_type = compress_type;
em->block_start = bytenr;
em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
item);
} else {
bytenr += btrfs_file_extent_offset(leaf, item);
em->block_start = bytenr;
em->block_len = em->len;
if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
}
goto insert;
} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
unsigned long ptr;
char *map;
size_t size;
size_t extent_offset;
size_t copy_size;
em->block_start = EXTENT_MAP_INLINE;
if (!page || create) {
em->start = extent_start;
em->len = extent_end - extent_start;
goto out;
}
size = btrfs_file_extent_inline_len(leaf, item);
extent_offset = page_offset(page) + pg_offset - extent_start;
copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
size - extent_offset);
em->start = extent_start + extent_offset;
em->len = (copy_size + root->sectorsize - 1) &
~((u64)root->sectorsize - 1);
em->orig_start = EXTENT_MAP_INLINE;
if (compress_type) {
set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
em->compress_type = compress_type;
}
ptr = btrfs_file_extent_inline_start(item) + extent_offset;
if (create == 0 && !PageUptodate(page)) {
if (btrfs_file_extent_compression(leaf, item) !=
BTRFS_COMPRESS_NONE) {
ret = uncompress_inline(path, inode, page,
pg_offset,
extent_offset, item);
BUG_ON(ret); /* -ENOMEM */
} else {
map = kmap(page);
read_extent_buffer(leaf, map + pg_offset, ptr,
copy_size);
if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
memset(map + pg_offset + copy_size, 0,
PAGE_CACHE_SIZE - pg_offset -
copy_size);
}
kunmap(page);
}
flush_dcache_page(page);
} else if (create && PageUptodate(page)) {
BUG();
if (!trans) {
kunmap(page);
free_extent_map(em);
em = NULL;
btrfs_release_path(path);
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return ERR_CAST(trans);
goto again;
}
map = kmap(page);
write_extent_buffer(leaf, map + pg_offset, ptr,
copy_size);
kunmap(page);
btrfs_mark_buffer_dirty(leaf);
}
set_extent_uptodate(io_tree, em->start,
extent_map_end(em) - 1, NULL, GFP_NOFS);
goto insert;
} else {
printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
WARN_ON(1);
}
not_found:
em->start = start;
em->len = len;
not_found_em:
em->block_start = EXTENT_MAP_HOLE;
set_bit(EXTENT_FLAG_VACANCY, &em->flags);
insert:
btrfs_release_path(path);
if (em->start > start || extent_map_end(em) <= start) {
printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
"[%llu %llu]\n", (unsigned long long)em->start,
(unsigned long long)em->len,
(unsigned long long)start,
(unsigned long long)len);
err = -EIO;
goto out;
}
err = 0;
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em);
/* it is possible that someone inserted the extent into the tree
* while we had the lock dropped. It is also possible that
* an overlapping map exists in the tree
*/
if (ret == -EEXIST) {
struct extent_map *existing;
ret = 0;
existing = lookup_extent_mapping(em_tree, start, len);
if (existing && (existing->start > start ||
existing->start + existing->len <= start)) {
free_extent_map(existing);
existing = NULL;
}
if (!existing) {
existing = lookup_extent_mapping(em_tree, em->start,
em->len);
if (existing) {
err = merge_extent_mapping(em_tree, existing,
em, start,
root->sectorsize);
free_extent_map(existing);
if (err) {
free_extent_map(em);
em = NULL;
}
} else {
err = -EIO;
free_extent_map(em);
em = NULL;
}
} else {
free_extent_map(em);
em = existing;
err = 0;
}
}
write_unlock(&em_tree->lock);
out:
trace_btrfs_get_extent(root, em);
if (path)
btrfs_free_path(path);
if (trans) {
ret = btrfs_end_transaction(trans, root);
if (!err)
err = ret;
}
if (err) {
free_extent_map(em);
return ERR_PTR(err);
}
BUG_ON(!em); /* Error is always set */
return em;
}
struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
size_t pg_offset, u64 start, u64 len,
int create)
{
struct extent_map *em;
struct extent_map *hole_em = NULL;
u64 range_start = start;
u64 end;
u64 found;
u64 found_end;
int err = 0;
em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
if (IS_ERR(em))
return em;
if (em) {
/*
* if our em maps to a hole, there might
* actually be delalloc bytes behind it
*/
if (em->block_start != EXTENT_MAP_HOLE)
return em;
else
hole_em = em;
}
/* check to see if we've wrapped (len == -1 or similar) */
end = start + len;
if (end < start)
end = (u64)-1;
else
end -= 1;
em = NULL;
/* ok, we didn't find anything, lets look for delalloc */
found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
end, len, EXTENT_DELALLOC, 1);
found_end = range_start + found;
if (found_end < range_start)
found_end = (u64)-1;
/*
* we didn't find anything useful, return
* the original results from get_extent()
*/
if (range_start > end || found_end <= start) {
em = hole_em;
hole_em = NULL;
goto out;
}
/* adjust the range_start to make sure it doesn't
* go backwards from the start they passed in
*/
range_start = max(start,range_start);
found = found_end - range_start;
if (found > 0) {
u64 hole_start = start;
u64 hole_len = len;
em = alloc_extent_map();
if (!em) {
err = -ENOMEM;
goto out;
}
/*
* when btrfs_get_extent can't find anything it
* returns one huge hole
*
* make sure what it found really fits our range, and
* adjust to make sure it is based on the start from
* the caller
*/
if (hole_em) {
u64 calc_end = extent_map_end(hole_em);
if (calc_end <= start || (hole_em->start > end)) {
free_extent_map(hole_em);
hole_em = NULL;
} else {
hole_start = max(hole_em->start, start);
hole_len = calc_end - hole_start;
}
}
em->bdev = NULL;
if (hole_em && range_start > hole_start) {
/* our hole starts before our delalloc, so we
* have to return just the parts of the hole
* that go until the delalloc starts
*/
em->len = min(hole_len,
range_start - hole_start);
em->start = hole_start;
em->orig_start = hole_start;
/*
* don't adjust block start at all,
* it is fixed at EXTENT_MAP_HOLE
*/
em->block_start = hole_em->block_start;
em->block_len = hole_len;
} else {
em->start = range_start;
em->len = found;
em->orig_start = range_start;
em->block_start = EXTENT_MAP_DELALLOC;
em->block_len = found;
}
} else if (hole_em) {
return hole_em;
}
out:
free_extent_map(hole_em);
if (err) {
free_extent_map(em);
return ERR_PTR(err);
}
return em;
}
static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
struct extent_map *em,
u64 start, u64 len)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct btrfs_key ins;
u64 alloc_hint;
int ret;
bool insert = false;
/*
* Ok if the extent map we looked up is a hole and is for the exact
* range we want, there is no reason to allocate a new one, however if
* it is not right then we need to free this one and drop the cache for
* our range.
*/
if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
em->len != len) {
free_extent_map(em);
em = NULL;
insert = true;
btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
}
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return ERR_CAST(trans);
if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
btrfs_add_inode_defrag(trans, inode);
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
alloc_hint = get_extent_allocation_hint(inode, start, len);
ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
alloc_hint, &ins, 1);
if (ret) {
em = ERR_PTR(ret);
goto out;
}
if (!em) {
em = alloc_extent_map();
if (!em) {
em = ERR_PTR(-ENOMEM);
goto out;
}
}
em->start = start;
em->orig_start = em->start;
em->len = ins.offset;
em->block_start = ins.objectid;
em->block_len = ins.offset;
em->bdev = root->fs_info->fs_devices->latest_bdev;
/*
* We need to do this because if we're using the original em we searched
* for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
*/
em->flags = 0;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
while (insert) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em);
write_unlock(&em_tree->lock);
if (ret != -EEXIST)
break;
btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
}
ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
ins.offset, ins.offset, 0);
if (ret) {
btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
em = ERR_PTR(ret);
}
out:
btrfs_end_transaction(trans, root);
return em;
}
/*
* returns 1 when the nocow is safe, < 1 on error, 0 if the
* block must be cow'd
*/
static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
struct inode *inode, u64 offset, u64 len)
{
struct btrfs_path *path;
int ret;
struct extent_buffer *leaf;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
u64 disk_bytenr;
u64 backref_offset;
u64 extent_end;
u64 num_bytes;
int slot;
int found_type;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
offset, 0);
if (ret < 0)
goto out;
slot = path->slots[0];
if (ret == 1) {
if (slot == 0) {
/* can't find the item, must cow */
ret = 0;
goto out;
}
slot--;
}
ret = 0;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, slot);
if (key.objectid != btrfs_ino(inode) ||
key.type != BTRFS_EXTENT_DATA_KEY) {
/* not our file or wrong item type, must cow */
goto out;
}
if (key.offset > offset) {
/* Wrong offset, must cow */
goto out;
}
fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
found_type = btrfs_file_extent_type(leaf, fi);
if (found_type != BTRFS_FILE_EXTENT_REG &&
found_type != BTRFS_FILE_EXTENT_PREALLOC) {
/* not a regular extent, must cow */
goto out;
}
disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
backref_offset = btrfs_file_extent_offset(leaf, fi);
extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
if (extent_end < offset + len) {
/* extent doesn't include our full range, must cow */
goto out;
}
if (btrfs_extent_readonly(root, disk_bytenr))
goto out;
/*
* look for other files referencing this extent, if we
* find any we must cow
*/
if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
key.offset - backref_offset, disk_bytenr))
goto out;
/*
* adjust disk_bytenr and num_bytes to cover just the bytes
* in this extent we are about to write. If there
* are any csums in that range we have to cow in order
* to keep the csums correct
*/
disk_bytenr += backref_offset;
disk_bytenr += offset - key.offset;
num_bytes = min(offset + len, extent_end) - offset;
if (csum_exist_in_range(root, disk_bytenr, num_bytes))
goto out;
/*
* all of the above have passed, it is safe to overwrite this extent
* without cow
*/
ret = 1;
out:
btrfs_free_path(path);
return ret;
}
static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
struct extent_map *em;
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 start = iblock << inode->i_blkbits;
u64 len = bh_result->b_size;
struct btrfs_trans_handle *trans;
em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
if (IS_ERR(em))
return PTR_ERR(em);
/*
* Ok for INLINE and COMPRESSED extents we need to fallback on buffered
* io. INLINE is special, and we could probably kludge it in here, but
* it's still buffered so for safety lets just fall back to the generic
* buffered path.
*
* For COMPRESSED we _have_ to read the entire extent in so we can
* decompress it, so there will be buffering required no matter what we
* do, so go ahead and fallback to buffered.
*
* We return -ENOTBLK because thats what makes DIO go ahead and go back
* to buffered IO. Don't blame me, this is the price we pay for using
* the generic code.
*/
if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
em->block_start == EXTENT_MAP_INLINE) {
free_extent_map(em);
return -ENOTBLK;
}
/* Just a good old fashioned hole, return */
if (!create && (em->block_start == EXTENT_MAP_HOLE ||
test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
free_extent_map(em);
/* DIO will do one hole at a time, so just unlock a sector */
unlock_extent(&BTRFS_I(inode)->io_tree, start,
start + root->sectorsize - 1);
return 0;
}
/*
* We don't allocate a new extent in the following cases
*
* 1) The inode is marked as NODATACOW. In this case we'll just use the
* existing extent.
* 2) The extent is marked as PREALLOC. We're good to go here and can
* just use the extent.
*
*/
if (!create) {
len = em->len - (start - em->start);
goto map;
}
if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
em->block_start != EXTENT_MAP_HOLE)) {
int type;
int ret;
u64 block_start;
if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
type = BTRFS_ORDERED_PREALLOC;
else
type = BTRFS_ORDERED_NOCOW;
len = min(len, em->len - (start - em->start));
block_start = em->block_start + (start - em->start);
/*
* we're not going to log anything, but we do need
* to make sure the current transaction stays open
* while we look for nocow cross refs
*/
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
goto must_cow;
if (can_nocow_odirect(trans, inode, start, len) == 1) {
ret = btrfs_add_ordered_extent_dio(inode, start,
block_start, len, len, type);
btrfs_end_transaction(trans, root);
if (ret) {
free_extent_map(em);
return ret;
}
goto unlock;
}
btrfs_end_transaction(trans, root);
}
must_cow:
/*
* this will cow the extent, reset the len in case we changed
* it above
*/
len = bh_result->b_size;
em = btrfs_new_extent_direct(inode, em, start, len);
if (IS_ERR(em))
return PTR_ERR(em);
len = min(len, em->len - (start - em->start));
unlock:
clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
0, NULL, GFP_NOFS);
map:
bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
inode->i_blkbits;
bh_result->b_size = len;
bh_result->b_bdev = em->bdev;
set_buffer_mapped(bh_result);
if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
set_buffer_new(bh_result);
free_extent_map(em);
return 0;
}
struct btrfs_dio_private {
struct inode *inode;
u64 logical_offset;
u64 disk_bytenr;
u64 bytes;
u32 *csums;
void *private;
/* number of bios pending for this dio */
atomic_t pending_bios;
/* IO errors */
int errors;
struct bio *orig_bio;
};
static void btrfs_endio_direct_read(struct bio *bio, int err)
{
struct btrfs_dio_private *dip = bio->bi_private;
struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
struct bio_vec *bvec = bio->bi_io_vec;
struct inode *inode = dip->inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 start;
u32 *private = dip->csums;
start = dip->logical_offset;
do {
if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
struct page *page = bvec->bv_page;
char *kaddr;
u32 csum = ~(u32)0;
unsigned long flags;
local_irq_save(flags);
kaddr = kmap_atomic(page);
csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
csum, bvec->bv_len);
btrfs_csum_final(csum, (char *)&csum);
kunmap_atomic(kaddr);
local_irq_restore(flags);
flush_dcache_page(bvec->bv_page);
if (csum != *private) {
printk(KERN_ERR "btrfs csum failed ino %llu off"
" %llu csum %u private %u\n",
(unsigned long long)btrfs_ino(inode),
(unsigned long long)start,
csum, *private);
err = -EIO;
}
}
start += bvec->bv_len;
private++;
bvec++;
} while (bvec <= bvec_end);
unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
dip->logical_offset + dip->bytes - 1);
bio->bi_private = dip->private;
kfree(dip->csums);
kfree(dip);
/* If we had a csum failure make sure to clear the uptodate flag */
if (err)
clear_bit(BIO_UPTODATE, &bio->bi_flags);
dio_end_io(bio, err);
}
static void btrfs_endio_direct_write(struct bio *bio, int err)
{
struct btrfs_dio_private *dip = bio->bi_private;
struct inode *inode = dip->inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
struct btrfs_ordered_extent *ordered = NULL;
struct extent_state *cached_state = NULL;
u64 ordered_offset = dip->logical_offset;
u64 ordered_bytes = dip->bytes;
int ret;
if (err)
goto out_done;
again:
ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
&ordered_offset,
ordered_bytes);
if (!ret)
goto out_test;
BUG_ON(!ordered);
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
err = -ENOMEM;
goto out;
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
ret = btrfs_ordered_update_i_size(inode, 0, ordered);
if (!ret)
err = btrfs_update_inode_fallback(trans, root, inode);
goto out;
}
lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
ordered->file_offset + ordered->len - 1, 0,
&cached_state);
if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
ret = btrfs_mark_extent_written(trans, inode,
ordered->file_offset,
ordered->file_offset +
ordered->len);
if (ret) {
err = ret;
goto out_unlock;
}
} else {
ret = insert_reserved_file_extent(trans, inode,
ordered->file_offset,
ordered->start,
ordered->disk_len,
ordered->len,
ordered->len,
0, 0, 0,
BTRFS_FILE_EXTENT_REG);
unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
ordered->file_offset, ordered->len);
if (ret) {
err = ret;
WARN_ON(1);
goto out_unlock;
}
}
add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
ret = btrfs_ordered_update_i_size(inode, 0, ordered);
if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags))
btrfs_update_inode_fallback(trans, root, inode);
ret = 0;
out_unlock:
unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
ordered->file_offset + ordered->len - 1,
&cached_state, GFP_NOFS);
out:
btrfs_delalloc_release_metadata(inode, ordered->len);
btrfs_end_transaction(trans, root);
ordered_offset = ordered->file_offset + ordered->len;
btrfs_put_ordered_extent(ordered);
btrfs_put_ordered_extent(ordered);
out_test:
/*
* our bio might span multiple ordered extents. If we haven't
* completed the accounting for the whole dio, go back and try again
*/
if (ordered_offset < dip->logical_offset + dip->bytes) {
ordered_bytes = dip->logical_offset + dip->bytes -
ordered_offset;
goto again;
}
out_done:
bio->bi_private = dip->private;
kfree(dip->csums);
kfree(dip);
/* If we had an error make sure to clear the uptodate flag */
if (err)
clear_bit(BIO_UPTODATE, &bio->bi_flags);
dio_end_io(bio, err);
}
static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
struct bio *bio, int mirror_num,
unsigned long bio_flags, u64 offset)
{
int ret;
struct btrfs_root *root = BTRFS_I(inode)->root;
ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
BUG_ON(ret); /* -ENOMEM */
return 0;
}
static void btrfs_end_dio_bio(struct bio *bio, int err)
{
struct btrfs_dio_private *dip = bio->bi_private;
if (err) {
printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
"sector %#Lx len %u err no %d\n",
(unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
(unsigned long long)bio->bi_sector, bio->bi_size, err);
dip->errors = 1;
/*
* before atomic variable goto zero, we must make sure
* dip->errors is perceived to be set.
*/
smp_mb__before_atomic_dec();
}
/* if there are more bios still pending for this dio, just exit */
if (!atomic_dec_and_test(&dip->pending_bios))
goto out;
if (dip->errors)
bio_io_error(dip->orig_bio);
else {
set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
bio_endio(dip->orig_bio, 0);
}
out:
bio_put(bio);
}
static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
u64 first_sector, gfp_t gfp_flags)
{
int nr_vecs = bio_get_nr_vecs(bdev);
return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
}
static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
int rw, u64 file_offset, int skip_sum,
u32 *csums, int async_submit)
{
int write = rw & REQ_WRITE;
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret;
bio_get(bio);
ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
if (ret)
goto err;
if (skip_sum)
goto map;
if (write && async_submit) {
ret = btrfs_wq_submit_bio(root->fs_info,
inode, rw, bio, 0, 0,
file_offset,
__btrfs_submit_bio_start_direct_io,
__btrfs_submit_bio_done);
goto err;
} else if (write) {
/*
* If we aren't doing async submit, calculate the csum of the
* bio now.
*/
ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
if (ret)
goto err;
} else if (!skip_sum) {
ret = btrfs_lookup_bio_sums_dio(root, inode, bio,
file_offset, csums);
if (ret)
goto err;
}
map:
ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
err:
bio_put(bio);
return ret;
}
static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
int skip_sum)
{
struct inode *inode = dip->inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
struct bio *bio;
struct bio *orig_bio = dip->orig_bio;
struct bio_vec *bvec = orig_bio->bi_io_vec;
u64 start_sector = orig_bio->bi_sector;
u64 file_offset = dip->logical_offset;
u64 submit_len = 0;
u64 map_length;
int nr_pages = 0;
u32 *csums = dip->csums;
int ret = 0;
int async_submit = 0;
int write = rw & REQ_WRITE;
map_length = orig_bio->bi_size;
ret = btrfs_map_block(map_tree, READ, start_sector << 9,
&map_length, NULL, 0);
if (ret) {
bio_put(orig_bio);
return -EIO;
}
if (map_length >= orig_bio->bi_size) {
bio = orig_bio;
goto submit;
}
async_submit = 1;
bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
if (!bio)
return -ENOMEM;
bio->bi_private = dip;
bio->bi_end_io = btrfs_end_dio_bio;
atomic_inc(&dip->pending_bios);
while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
if (unlikely(map_length < submit_len + bvec->bv_len ||
bio_add_page(bio, bvec->bv_page, bvec->bv_len,
bvec->bv_offset) < bvec->bv_len)) {
/*
* inc the count before we submit the bio so
* we know the end IO handler won't happen before
* we inc the count. Otherwise, the dip might get freed
* before we're done setting it up
*/
atomic_inc(&dip->pending_bios);
ret = __btrfs_submit_dio_bio(bio, inode, rw,
file_offset, skip_sum,
csums, async_submit);
if (ret) {
bio_put(bio);
atomic_dec(&dip->pending_bios);
goto out_err;
}
/* Write's use the ordered csums */
if (!write && !skip_sum)
csums = csums + nr_pages;
start_sector += submit_len >> 9;
file_offset += submit_len;
submit_len = 0;
nr_pages = 0;
bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
start_sector, GFP_NOFS);
if (!bio)
goto out_err;
bio->bi_private = dip;
bio->bi_end_io = btrfs_end_dio_bio;
map_length = orig_bio->bi_size;
ret = btrfs_map_block(map_tree, READ, start_sector << 9,
&map_length, NULL, 0);
if (ret) {
bio_put(bio);
goto out_err;
}
} else {
submit_len += bvec->bv_len;
nr_pages ++;
bvec++;
}
}
submit:
ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
csums, async_submit);
if (!ret)
return 0;
bio_put(bio);
out_err:
dip->errors = 1;
/*
* before atomic variable goto zero, we must
* make sure dip->errors is perceived to be set.
*/
smp_mb__before_atomic_dec();
if (atomic_dec_and_test(&dip->pending_bios))
bio_io_error(dip->orig_bio);
/* bio_end_io() will handle error, so we needn't return it */
return 0;
}
static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
loff_t file_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_dio_private *dip;
struct bio_vec *bvec = bio->bi_io_vec;
int skip_sum;
int write = rw & REQ_WRITE;
int ret = 0;
skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
dip = kmalloc(sizeof(*dip), GFP_NOFS);
if (!dip) {
ret = -ENOMEM;
goto free_ordered;
}
dip->csums = NULL;
/* Write's use the ordered csum stuff, so we don't need dip->csums */
if (!write && !skip_sum) {
dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
if (!dip->csums) {
kfree(dip);
ret = -ENOMEM;
goto free_ordered;
}
}
dip->private = bio->bi_private;
dip->inode = inode;
dip->logical_offset = file_offset;
dip->bytes = 0;
do {
dip->bytes += bvec->bv_len;
bvec++;
} while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
dip->disk_bytenr = (u64)bio->bi_sector << 9;
bio->bi_private = dip;
dip->errors = 0;
dip->orig_bio = bio;
atomic_set(&dip->pending_bios, 0);
if (write)
bio->bi_end_io = btrfs_endio_direct_write;
else
bio->bi_end_io = btrfs_endio_direct_read;
ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
if (!ret)
return;
free_ordered:
/*
* If this is a write, we need to clean up the reserved space and kill
* the ordered extent.
*/
if (write) {
struct btrfs_ordered_extent *ordered;
ordered = btrfs_lookup_ordered_extent(inode, file_offset);
if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
!test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
btrfs_free_reserved_extent(root, ordered->start,
ordered->disk_len);
btrfs_put_ordered_extent(ordered);
btrfs_put_ordered_extent(ordered);
}
bio_endio(bio, ret);
}
static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
int seg;
int i;
size_t size;
unsigned long addr;
unsigned blocksize_mask = root->sectorsize - 1;
ssize_t retval = -EINVAL;
loff_t end = offset;
if (offset & blocksize_mask)
goto out;
/* Check the memory alignment. Blocks cannot straddle pages */
for (seg = 0; seg < nr_segs; seg++) {
addr = (unsigned long)iov[seg].iov_base;
size = iov[seg].iov_len;
end += size;
if ((addr & blocksize_mask) || (size & blocksize_mask))
goto out;
/* If this is a write we don't need to check anymore */
if (rw & WRITE)
continue;
/*
* Check to make sure we don't have duplicate iov_base's in this
* iovec, if so return EINVAL, otherwise we'll get csum errors
* when reading back.
*/
for (i = seg + 1; i < nr_segs; i++) {
if (iov[seg].iov_base == iov[i].iov_base)
goto out;
}
}
retval = 0;
out:
return retval;
}
static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
u64 lockstart, lockend;
ssize_t ret;
int writing = rw & WRITE;
int write_bits = 0;
size_t count = iov_length(iov, nr_segs);
if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
offset, nr_segs)) {
return 0;
}
lockstart = offset;
lockend = offset + count - 1;
if (writing) {
ret = btrfs_delalloc_reserve_space(inode, count);
if (ret)
goto out;
}
while (1) {
lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
0, &cached_state);
/*
* We're concerned with the entire range that we're going to be
* doing DIO to, so we need to make sure theres no ordered
* extents in this range.
*/
ordered = btrfs_lookup_ordered_range(inode, lockstart,
lockend - lockstart + 1);
if (!ordered)
break;
unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
&cached_state, GFP_NOFS);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
cond_resched();
}
/*
* we don't use btrfs_set_extent_delalloc because we don't want
* the dirty or uptodate bits
*/
if (writing) {
write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
EXTENT_DELALLOC, NULL, &cached_state,
GFP_NOFS);
if (ret) {
clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
lockend, EXTENT_LOCKED | write_bits,
1, 0, &cached_state, GFP_NOFS);
goto out;
}
}
free_extent_state(cached_state);
cached_state = NULL;
ret = __blockdev_direct_IO(rw, iocb, inode,
BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
btrfs_submit_direct, 0);
if (ret < 0 && ret != -EIOCBQUEUED) {
clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
offset + iov_length(iov, nr_segs) - 1,
EXTENT_LOCKED | write_bits, 1, 0,
&cached_state, GFP_NOFS);
} else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
/*
* We're falling back to buffered, unlock the section we didn't
* do IO on.
*/
clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
offset + iov_length(iov, nr_segs) - 1,
EXTENT_LOCKED | write_bits, 1, 0,
&cached_state, GFP_NOFS);
}
out:
free_extent_state(cached_state);
return ret;
}
static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len)
{
return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
}
int btrfs_readpage(struct file *file, struct page *page)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(page->mapping->host)->io_tree;
return extent_read_full_page(tree, page, btrfs_get_extent, 0);
}
static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
{
struct extent_io_tree *tree;
if (current->flags & PF_MEMALLOC) {
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
tree = &BTRFS_I(page->mapping->host)->io_tree;
return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
}
int btrfs_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(mapping->host)->io_tree;
return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
}
static int
btrfs_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(mapping->host)->io_tree;
return extent_readpages(tree, mapping, pages, nr_pages,
btrfs_get_extent);
}
static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
{
struct extent_io_tree *tree;
struct extent_map_tree *map;
int ret;
tree = &BTRFS_I(page->mapping->host)->io_tree;
map = &BTRFS_I(page->mapping->host)->extent_tree;
ret = try_release_extent_mapping(map, tree, page, gfp_flags);
if (ret == 1) {
ClearPagePrivate(page);
set_page_private(page, 0);
page_cache_release(page);
}
return ret;
}
static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
{
if (PageWriteback(page) || PageDirty(page))
return 0;
return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
}
static void btrfs_invalidatepage(struct page *page, unsigned long offset)
{
struct extent_io_tree *tree;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
u64 page_start = page_offset(page);
u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
/*
* we have the page locked, so new writeback can't start,
* and the dirty bit won't be cleared while we are here.
*
* Wait for IO on this page so that we can safely clear
* the PagePrivate2 bit and do ordered accounting
*/
wait_on_page_writeback(page);
tree = &BTRFS_I(page->mapping->host)->io_tree;
if (offset) {
btrfs_releasepage(page, GFP_NOFS);
return;
}
lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
ordered = btrfs_lookup_ordered_extent(page->mapping->host,
page_offset(page));
if (ordered) {
/*
* IO on this page will never be started, so we need
* to account for any ordered extents now
*/
clear_extent_bit(tree, page_start, page_end,
EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
&cached_state, GFP_NOFS);
/*
* whoever cleared the private bit is responsible
* for the finish_ordered_io
*/
if (TestClearPagePrivate2(page)) {
btrfs_finish_ordered_io(page->mapping->host,
page_start, page_end);
}
btrfs_put_ordered_extent(ordered);
cached_state = NULL;
lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
}
clear_extent_bit(tree, page_start, page_end,
EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
__btrfs_releasepage(page, GFP_NOFS);
ClearPageChecked(page);
if (PagePrivate(page)) {
ClearPagePrivate(page);
set_page_private(page, 0);
page_cache_release(page);
}
}
/*
* btrfs_page_mkwrite() is not allowed to change the file size as it gets
* called from a page fault handler when a page is first dirtied. Hence we must
* be careful to check for EOF conditions here. We set the page up correctly
* for a written page which means we get ENOSPC checking when writing into
* holes and correct delalloc and unwritten extent mapping on filesystems that
* support these features.
*
* We are not allowed to take the i_mutex here so we have to play games to
* protect against truncate races as the page could now be beyond EOF. Because
* vmtruncate() writes the inode size before removing pages, once we have the
* page lock we can determine safely if the page is beyond EOF. If it is not
* beyond EOF, then the page is guaranteed safe against truncation until we
* unlock the page.
*/
int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page = vmf->page;
struct inode *inode = fdentry(vma->vm_file)->d_inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
char *kaddr;
unsigned long zero_start;
loff_t size;
int ret;
int reserved = 0;
u64 page_start;
u64 page_end;
ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
if (!ret) {
ret = btrfs_update_time(vma->vm_file);
reserved = 1;
}
if (ret) {
if (ret == -ENOMEM)
ret = VM_FAULT_OOM;
else /* -ENOSPC, -EIO, etc */
ret = VM_FAULT_SIGBUS;
if (reserved)
goto out;
goto out_noreserve;
}
ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
again:
lock_page(page);
size = i_size_read(inode);
page_start = page_offset(page);
page_end = page_start + PAGE_CACHE_SIZE - 1;
if ((page->mapping != inode->i_mapping) ||
(page_start >= size)) {
/* page got truncated out from underneath us */
goto out_unlock;
}
wait_on_page_writeback(page);
lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
set_page_extent_mapped(page);
/*
* we can't set the delalloc bits if there are pending ordered
* extents. Drop our locks and wait for them to finish
*/
ordered = btrfs_lookup_ordered_extent(inode, page_start);
if (ordered) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
unlock_page(page);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
goto again;
}
/*
* XXX - page_mkwrite gets called every time the page is dirtied, even
* if it was already dirty, so for space accounting reasons we need to
* clear any delalloc bits for the range we are fixing to save. There
* is probably a better way to do this, but for now keep consistent with
* prepare_pages in the normal write path.
*/
clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
0, 0, &cached_state, GFP_NOFS);
ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
&cached_state);
if (ret) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
ret = VM_FAULT_SIGBUS;
goto out_unlock;
}
ret = 0;
/* page is wholly or partially inside EOF */
if (page_start + PAGE_CACHE_SIZE > size)
zero_start = size & ~PAGE_CACHE_MASK;
else
zero_start = PAGE_CACHE_SIZE;
if (zero_start != PAGE_CACHE_SIZE) {
kaddr = kmap(page);
memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
flush_dcache_page(page);
kunmap(page);
}
ClearPageChecked(page);
set_page_dirty(page);
SetPageUptodate(page);
BTRFS_I(inode)->last_trans = root->fs_info->generation;
BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
out_unlock:
if (!ret)
return VM_FAULT_LOCKED;
unlock_page(page);
out:
btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
out_noreserve:
return ret;
}
static int btrfs_truncate(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_block_rsv *rsv;
int ret;
int err = 0;
struct btrfs_trans_handle *trans;
unsigned long nr;
u64 mask = root->sectorsize - 1;
u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
if (ret)
return ret;
btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
/*
* Yes ladies and gentelment, this is indeed ugly. The fact is we have
* 3 things going on here
*
* 1) We need to reserve space for our orphan item and the space to
* delete our orphan item. Lord knows we don't want to have a dangling
* orphan item because we didn't reserve space to remove it.
*
* 2) We need to reserve space to update our inode.
*
* 3) We need to have something to cache all the space that is going to
* be free'd up by the truncate operation, but also have some slack
* space reserved in case it uses space during the truncate (thank you
* very much snapshotting).
*
* And we need these to all be seperate. The fact is we can use alot of
* space doing the truncate, and we have no earthly idea how much space
* we will use, so we need the truncate reservation to be seperate so it
* doesn't end up using space reserved for updating the inode or
* removing the orphan item. We also need to be able to stop the
* transaction and start a new one, which means we need to be able to
* update the inode several times, and we have no idea of knowing how
* many times that will be, so we can't just reserve 1 item for the
* entirety of the opration, so that has to be done seperately as well.
* Then there is the orphan item, which does indeed need to be held on
* to for the whole operation, and we need nobody to touch this reserved
* space except the orphan code.
*
* So that leaves us with
*
* 1) root->orphan_block_rsv - for the orphan deletion.
* 2) rsv - for the truncate reservation, which we will steal from the
* transaction reservation.
* 3) fs_info->trans_block_rsv - this will have 1 items worth left for
* updating the inode.
*/
rsv = btrfs_alloc_block_rsv(root);
if (!rsv)
return -ENOMEM;
rsv->size = min_size;
/*
* 1 for the truncate slack space
* 1 for the orphan item we're going to add
* 1 for the orphan item deletion
* 1 for updating the inode.
*/
trans = btrfs_start_transaction(root, 4);
if (IS_ERR(trans)) {
err = PTR_ERR(trans);
goto out;
}
/* Migrate the slack space for the truncate to our reserve */
ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
min_size);
BUG_ON(ret);
ret = btrfs_orphan_add(trans, inode);
if (ret) {
btrfs_end_transaction(trans, root);
goto out;
}
/*
* setattr is responsible for setting the ordered_data_close flag,
* but that is only tested during the last file release. That
* could happen well after the next commit, leaving a great big
* window where new writes may get lost if someone chooses to write
* to this file after truncating to zero
*
* The inode doesn't have any dirty data here, and so if we commit
* this is a noop. If someone immediately starts writing to the inode
* it is very likely we'll catch some of their writes in this
* transaction, and the commit will find this file on the ordered
* data list with good things to send down.
*
* This is a best effort solution, there is still a window where
* using truncate to replace the contents of the file will
* end up with a zero length file after a crash.
*/
if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
btrfs_add_ordered_operation(trans, root, inode);
while (1) {
ret = btrfs_block_rsv_refill(root, rsv, min_size);
if (ret) {
/*
* This can only happen with the original transaction we
* started above, every other time we shouldn't have a
* transaction started yet.
*/
if (ret == -EAGAIN)
goto end_trans;
err = ret;
break;
}
if (!trans) {
/* Just need the 1 for updating the inode */
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans)) {
ret = err = PTR_ERR(trans);
trans = NULL;
break;
}
}
trans->block_rsv = rsv;
ret = btrfs_truncate_inode_items(trans, root, inode,
inode->i_size,
BTRFS_EXTENT_DATA_KEY);
if (ret != -EAGAIN) {
err = ret;
break;
}
trans->block_rsv = &root->fs_info->trans_block_rsv;
ret = btrfs_update_inode(trans, root, inode);
if (ret) {
err = ret;
break;
}
end_trans:
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
trans = NULL;
btrfs_btree_balance_dirty(root, nr);
}
if (ret == 0 && inode->i_nlink > 0) {
trans->block_rsv = root->orphan_block_rsv;
ret = btrfs_orphan_del(trans, inode);
if (ret)
err = ret;
} else if (ret && inode->i_nlink > 0) {
/*
* Failed to do the truncate, remove us from the in memory
* orphan list.
*/
ret = btrfs_orphan_del(NULL, inode);
}
if (trans) {
trans->block_rsv = &root->fs_info->trans_block_rsv;
ret = btrfs_update_inode(trans, root, inode);
if (ret && !err)
err = ret;
nr = trans->blocks_used;
ret = btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root, nr);
}
out:
btrfs_free_block_rsv(root, rsv);
if (ret && !err)
err = ret;
return err;
}
/*
* create a new subvolume directory/inode (helper for the ioctl).
*/
int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
struct btrfs_root *new_root, u64 new_dirid)
{
struct inode *inode;
int err;
u64 index = 0;
inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
new_dirid, new_dirid,
S_IFDIR | (~current_umask() & S_IRWXUGO),
&index);
if (IS_ERR(inode))
return PTR_ERR(inode);
inode->i_op = &btrfs_dir_inode_operations;
inode->i_fop = &btrfs_dir_file_operations;
set_nlink(inode, 1);
btrfs_i_size_write(inode, 0);
err = btrfs_update_inode(trans, new_root, inode);
iput(inode);
return err;
}
struct inode *btrfs_alloc_inode(struct super_block *sb)
{
struct btrfs_inode *ei;
struct inode *inode;
ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->root = NULL;
ei->space_info = NULL;
ei->generation = 0;
ei->sequence = 0;
ei->last_trans = 0;
ei->last_sub_trans = 0;
ei->logged_trans = 0;
ei->delalloc_bytes = 0;
ei->disk_i_size = 0;
ei->flags = 0;
ei->csum_bytes = 0;
ei->index_cnt = (u64)-1;
ei->last_unlink_trans = 0;
spin_lock_init(&ei->lock);
ei->outstanding_extents = 0;
ei->reserved_extents = 0;
ei->ordered_data_close = 0;
ei->orphan_meta_reserved = 0;
ei->dummy_inode = 0;
ei->in_defrag = 0;
ei->delalloc_meta_reserved = 0;
ei->force_compress = BTRFS_COMPRESS_NONE;
ei->delayed_node = NULL;
inode = &ei->vfs_inode;
extent_map_tree_init(&ei->extent_tree);
extent_io_tree_init(&ei->io_tree, &inode->i_data);
extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
ei->io_tree.track_uptodate = 1;
ei->io_failure_tree.track_uptodate = 1;
mutex_init(&ei->log_mutex);
mutex_init(&ei->delalloc_mutex);
btrfs_ordered_inode_tree_init(&ei->ordered_tree);
INIT_LIST_HEAD(&ei->i_orphan);
INIT_LIST_HEAD(&ei->delalloc_inodes);
INIT_LIST_HEAD(&ei->ordered_operations);
RB_CLEAR_NODE(&ei->rb_node);
return inode;
}
static void btrfs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
}
void btrfs_destroy_inode(struct inode *inode)
{
struct btrfs_ordered_extent *ordered;
struct btrfs_root *root = BTRFS_I(inode)->root;
WARN_ON(!list_empty(&inode->i_dentry));
WARN_ON(inode->i_data.nrpages);
WARN_ON(BTRFS_I(inode)->outstanding_extents);
WARN_ON(BTRFS_I(inode)->reserved_extents);
WARN_ON(BTRFS_I(inode)->delalloc_bytes);
WARN_ON(BTRFS_I(inode)->csum_bytes);
/*
* This can happen where we create an inode, but somebody else also
* created the same inode and we need to destroy the one we already
* created.
*/
if (!root)
goto free;
/*
* Make sure we're properly removed from the ordered operation
* lists.
*/
smp_mb();
if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
spin_lock(&root->fs_info->ordered_extent_lock);
list_del_init(&BTRFS_I(inode)->ordered_operations);
spin_unlock(&root->fs_info->ordered_extent_lock);
}
spin_lock(&root->orphan_lock);
if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
(unsigned long long)btrfs_ino(inode));
list_del_init(&BTRFS_I(inode)->i_orphan);
}
spin_unlock(&root->orphan_lock);
while (1) {
ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
if (!ordered)
break;
else {
printk(KERN_ERR "btrfs found ordered "
"extent %llu %llu on inode cleanup\n",
(unsigned long long)ordered->file_offset,
(unsigned long long)ordered->len);
btrfs_remove_ordered_extent(inode, ordered);
btrfs_put_ordered_extent(ordered);
btrfs_put_ordered_extent(ordered);
}
}
inode_tree_del(inode);
btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
free:
btrfs_remove_delayed_node(inode);
call_rcu(&inode->i_rcu, btrfs_i_callback);
}
int btrfs_drop_inode(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
if (btrfs_root_refs(&root->root_item) == 0 &&
!btrfs_is_free_space_inode(root, inode))
return 1;
else
return generic_drop_inode(inode);
}
static void init_once(void *foo)
{
struct btrfs_inode *ei = (struct btrfs_inode *) foo;
inode_init_once(&ei->vfs_inode);
}
void btrfs_destroy_cachep(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
if (btrfs_inode_cachep)
kmem_cache_destroy(btrfs_inode_cachep);
if (btrfs_trans_handle_cachep)
kmem_cache_destroy(btrfs_trans_handle_cachep);
if (btrfs_transaction_cachep)
kmem_cache_destroy(btrfs_transaction_cachep);
if (btrfs_path_cachep)
kmem_cache_destroy(btrfs_path_cachep);
if (btrfs_free_space_cachep)
kmem_cache_destroy(btrfs_free_space_cachep);
}
int btrfs_init_cachep(void)
{
btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
sizeof(struct btrfs_inode), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
if (!btrfs_inode_cachep)
goto fail;
btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
sizeof(struct btrfs_trans_handle), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_trans_handle_cachep)
goto fail;
btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
sizeof(struct btrfs_transaction), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_transaction_cachep)
goto fail;
btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
sizeof(struct btrfs_path), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_path_cachep)
goto fail;
btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
sizeof(struct btrfs_free_space), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_free_space_cachep)
goto fail;
return 0;
fail:
btrfs_destroy_cachep();
return -ENOMEM;
}
static int btrfs_getattr(struct vfsmount *mnt,
struct dentry *dentry, struct kstat *stat)
{
struct inode *inode = dentry->d_inode;
u32 blocksize = inode->i_sb->s_blocksize;
generic_fillattr(inode, stat);
stat->dev = BTRFS_I(inode)->root->anon_dev;
stat->blksize = PAGE_CACHE_SIZE;
stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
return 0;
}
/*
* If a file is moved, it will inherit the cow and compression flags of the new
* directory.
*/
static void fixup_inode_flags(struct inode *dir, struct inode *inode)
{
struct btrfs_inode *b_dir = BTRFS_I(dir);
struct btrfs_inode *b_inode = BTRFS_I(inode);
if (b_dir->flags & BTRFS_INODE_NODATACOW)
b_inode->flags |= BTRFS_INODE_NODATACOW;
else
b_inode->flags &= ~BTRFS_INODE_NODATACOW;
if (b_dir->flags & BTRFS_INODE_COMPRESS)
b_inode->flags |= BTRFS_INODE_COMPRESS;
else
b_inode->flags &= ~BTRFS_INODE_COMPRESS;
}
static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(old_dir)->root;
struct btrfs_root *dest = BTRFS_I(new_dir)->root;
struct inode *new_inode = new_dentry->d_inode;
struct inode *old_inode = old_dentry->d_inode;
struct timespec ctime = CURRENT_TIME;
u64 index = 0;
u64 root_objectid;
int ret;
u64 old_ino = btrfs_ino(old_inode);
if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
return -EPERM;
/* we only allow rename subvolume link between subvolumes */
if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
return -EXDEV;
if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
(new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
return -ENOTEMPTY;
if (S_ISDIR(old_inode->i_mode) && new_inode &&
new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
return -ENOTEMPTY;
/*
* we're using rename to replace one file with another.
* and the replacement file is large. Start IO on it now so
* we don't add too much work to the end of the transaction
*/
if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
filemap_flush(old_inode->i_mapping);
/* close the racy window with snapshot create/destroy ioctl */
if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
down_read(&root->fs_info->subvol_sem);
/*
* We want to reserve the absolute worst case amount of items. So if
* both inodes are subvols and we need to unlink them then that would
* require 4 item modifications, but if they are both normal inodes it
* would require 5 item modifications, so we'll assume their normal
* inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
* should cover the worst case number of items we'll modify.
*/
trans = btrfs_start_transaction(root, 20);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto out_notrans;
}
if (dest != root)
btrfs_record_root_in_trans(trans, dest);
ret = btrfs_set_inode_index(new_dir, &index);
if (ret)
goto out_fail;
if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
/* force full log commit if subvolume involved. */
root->fs_info->last_trans_log_full_commit = trans->transid;
} else {
ret = btrfs_insert_inode_ref(trans, dest,
new_dentry->d_name.name,
new_dentry->d_name.len,
old_ino,
btrfs_ino(new_dir), index);
if (ret)
goto out_fail;
/*
* this is an ugly little race, but the rename is required
* to make sure that if we crash, the inode is either at the
* old name or the new one. pinning the log transaction lets
* us make sure we don't allow a log commit to come in after
* we unlink the name but before we add the new name back in.
*/
btrfs_pin_log_trans(root);
}
/*
* make sure the inode gets flushed if it is replacing
* something.
*/
if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
btrfs_add_ordered_operation(trans, root, old_inode);
old_dir->i_ctime = old_dir->i_mtime = ctime;
new_dir->i_ctime = new_dir->i_mtime = ctime;
old_inode->i_ctime = ctime;
if (old_dentry->d_parent != new_dentry->d_parent)
btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
old_dentry->d_name.name,
old_dentry->d_name.len);
} else {
ret = __btrfs_unlink_inode(trans, root, old_dir,
old_dentry->d_inode,
old_dentry->d_name.name,
old_dentry->d_name.len);
if (!ret)
ret = btrfs_update_inode(trans, root, old_inode);
}
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
if (new_inode) {
new_inode->i_ctime = CURRENT_TIME;
if (unlikely(btrfs_ino(new_inode) ==
BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
root_objectid = BTRFS_I(new_inode)->location.objectid;
ret = btrfs_unlink_subvol(trans, dest, new_dir,
root_objectid,
new_dentry->d_name.name,
new_dentry->d_name.len);
BUG_ON(new_inode->i_nlink == 0);
} else {
ret = btrfs_unlink_inode(trans, dest, new_dir,
new_dentry->d_inode,
new_dentry->d_name.name,
new_dentry->d_name.len);
}
if (!ret && new_inode->i_nlink == 0) {
ret = btrfs_orphan_add(trans, new_dentry->d_inode);
BUG_ON(ret);
}
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
}
fixup_inode_flags(new_dir, old_inode);
ret = btrfs_add_link(trans, new_dir, old_inode,
new_dentry->d_name.name,
new_dentry->d_name.len, 0, index);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
struct dentry *parent = new_dentry->d_parent;
btrfs_log_new_name(trans, old_inode, old_dir, parent);
btrfs_end_log_trans(root);
}
out_fail:
btrfs_end_transaction(trans, root);
out_notrans:
if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
up_read(&root->fs_info->subvol_sem);
return ret;
}
/*
* some fairly slow code that needs optimization. This walks the list
* of all the inodes with pending delalloc and forces them to disk.
*/
int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
{
struct list_head *head = &root->fs_info->delalloc_inodes;
struct btrfs_inode *binode;
struct inode *inode;
if (root->fs_info->sb->s_flags & MS_RDONLY)
return -EROFS;
spin_lock(&root->fs_info->delalloc_lock);
while (!list_empty(head)) {
binode = list_entry(head->next, struct btrfs_inode,
delalloc_inodes);
inode = igrab(&binode->vfs_inode);
if (!inode)
list_del_init(&binode->delalloc_inodes);
spin_unlock(&root->fs_info->delalloc_lock);
if (inode) {
filemap_flush(inode->i_mapping);
if (delay_iput)
btrfs_add_delayed_iput(inode);
else
iput(inode);
}
cond_resched();
spin_lock(&root->fs_info->delalloc_lock);
}
spin_unlock(&root->fs_info->delalloc_lock);
/* the filemap_flush will queue IO into the worker threads, but
* we have to make sure the IO is actually started and that
* ordered extents get created before we return
*/
atomic_inc(&root->fs_info->async_submit_draining);
while (atomic_read(&root->fs_info->nr_async_submits) ||
atomic_read(&root->fs_info->async_delalloc_pages)) {
wait_event(root->fs_info->async_submit_wait,
(atomic_read(&root->fs_info->nr_async_submits) == 0 &&
atomic_read(&root->fs_info->async_delalloc_pages) == 0));
}
atomic_dec(&root->fs_info->async_submit_draining);
return 0;
}
static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
const char *symname)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_path *path;
struct btrfs_key key;
struct inode *inode = NULL;
int err;
int drop_inode = 0;
u64 objectid;
u64 index = 0 ;
int name_len;
int datasize;
unsigned long ptr;
struct btrfs_file_extent_item *ei;
struct extent_buffer *leaf;
unsigned long nr = 0;
name_len = strlen(symname) + 1;
if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
return -ENAMETOOLONG;
/*
* 2 items for inode item and ref
* 2 items for dir items
* 1 item for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_unlock;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
S_IFLNK|S_IRWXUGO, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_unlock;
}
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err) {
drop_inode = 1;
goto out_unlock;
}
/*
* If the active LSM wants to access the inode during
* d_instantiate it needs these. Smack checks to see
* if the filesystem supports xattrs by looking at the
* ops vector.
*/
inode->i_fop = &btrfs_file_operations;
inode->i_op = &btrfs_file_inode_operations;
err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
if (err)
drop_inode = 1;
else {
inode->i_mapping->a_ops = &btrfs_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
}
if (drop_inode)
goto out_unlock;
path = btrfs_alloc_path();
if (!path) {
err = -ENOMEM;
drop_inode = 1;
goto out_unlock;
}
key.objectid = btrfs_ino(inode);
key.offset = 0;
btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
datasize = btrfs_file_extent_calc_inline_size(name_len);
err = btrfs_insert_empty_item(trans, root, path, &key,
datasize);
if (err) {
drop_inode = 1;
btrfs_free_path(path);
goto out_unlock;
}
leaf = path->nodes[0];
ei = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, ei, trans->transid);
btrfs_set_file_extent_type(leaf, ei,
BTRFS_FILE_EXTENT_INLINE);
btrfs_set_file_extent_encryption(leaf, ei, 0);
btrfs_set_file_extent_compression(leaf, ei, 0);
btrfs_set_file_extent_other_encoding(leaf, ei, 0);
btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
ptr = btrfs_file_extent_inline_start(ei);
write_extent_buffer(leaf, symname, ptr, name_len);
btrfs_mark_buffer_dirty(leaf);
btrfs_free_path(path);
inode->i_op = &btrfs_symlink_inode_operations;
inode->i_mapping->a_ops = &btrfs_symlink_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
inode_set_bytes(inode, name_len);
btrfs_i_size_write(inode, name_len - 1);
err = btrfs_update_inode(trans, root, inode);
if (err)
drop_inode = 1;
out_unlock:
if (!err)
d_instantiate(dentry, inode);
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
if (drop_inode) {
inode_dec_link_count(inode);
iput(inode);
}
btrfs_btree_balance_dirty(root, nr);
return err;
}
static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
u64 start, u64 num_bytes, u64 min_size,
loff_t actual_len, u64 *alloc_hint,
struct btrfs_trans_handle *trans)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_key ins;
u64 cur_offset = start;
u64 i_size;
int ret = 0;
bool own_trans = true;
if (trans)
own_trans = false;
while (num_bytes > 0) {
if (own_trans) {
trans = btrfs_start_transaction(root, 3);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
break;
}
}
ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
0, *alloc_hint, &ins, 1);
if (ret) {
if (own_trans)
btrfs_end_transaction(trans, root);
break;
}
ret = insert_reserved_file_extent(trans, inode,
cur_offset, ins.objectid,
ins.offset, ins.offset,
ins.offset, 0, 0, 0,
BTRFS_FILE_EXTENT_PREALLOC);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
if (own_trans)
btrfs_end_transaction(trans, root);
break;
}
btrfs_drop_extent_cache(inode, cur_offset,
cur_offset + ins.offset -1, 0);
num_bytes -= ins.offset;
cur_offset += ins.offset;
*alloc_hint = ins.objectid + ins.offset;
inode->i_ctime = CURRENT_TIME;
BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(actual_len > inode->i_size) &&
(cur_offset > inode->i_size)) {
if (cur_offset > actual_len)
i_size = actual_len;
else
i_size = cur_offset;
i_size_write(inode, i_size);
btrfs_ordered_update_i_size(inode, i_size, NULL);
}
ret = btrfs_update_inode(trans, root, inode);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
if (own_trans)
btrfs_end_transaction(trans, root);
break;
}
if (own_trans)
btrfs_end_transaction(trans, root);
}
return ret;
}
int btrfs_prealloc_file_range(struct inode *inode, int mode,
u64 start, u64 num_bytes, u64 min_size,
loff_t actual_len, u64 *alloc_hint)
{
return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
min_size, actual_len, alloc_hint,
NULL);
}
int btrfs_prealloc_file_range_trans(struct inode *inode,
struct btrfs_trans_handle *trans, int mode,
u64 start, u64 num_bytes, u64 min_size,
loff_t actual_len, u64 *alloc_hint)
{
return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
min_size, actual_len, alloc_hint, trans);
}
static int btrfs_set_page_dirty(struct page *page)
{
return __set_page_dirty_nobuffers(page);
}
static int btrfs_permission(struct inode *inode, int mask)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
umode_t mode = inode->i_mode;
if (mask & MAY_WRITE &&
(S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
if (btrfs_root_readonly(root))
return -EROFS;
if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
return -EACCES;
}
return generic_permission(inode, mask);
}
static const struct inode_operations btrfs_dir_inode_operations = {
.getattr = btrfs_getattr,
.lookup = btrfs_lookup,
.create = btrfs_create,
.unlink = btrfs_unlink,
.link = btrfs_link,
.mkdir = btrfs_mkdir,
.rmdir = btrfs_rmdir,
.rename = btrfs_rename,
.symlink = btrfs_symlink,
.setattr = btrfs_setattr,
.mknod = btrfs_mknod,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.permission = btrfs_permission,
.get_acl = btrfs_get_acl,
};
static const struct inode_operations btrfs_dir_ro_inode_operations = {
.lookup = btrfs_lookup,
.permission = btrfs_permission,
.get_acl = btrfs_get_acl,
};
static const struct file_operations btrfs_dir_file_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.readdir = btrfs_real_readdir,
.unlocked_ioctl = btrfs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = btrfs_ioctl,
#endif
.release = btrfs_release_file,
.fsync = btrfs_sync_file,
};
static struct extent_io_ops btrfs_extent_io_ops = {
.fill_delalloc = run_delalloc_range,
.submit_bio_hook = btrfs_submit_bio_hook,
.merge_bio_hook = btrfs_merge_bio_hook,
.readpage_end_io_hook = btrfs_readpage_end_io_hook,
.writepage_end_io_hook = btrfs_writepage_end_io_hook,
.writepage_start_hook = btrfs_writepage_start_hook,
.set_bit_hook = btrfs_set_bit_hook,
.clear_bit_hook = btrfs_clear_bit_hook,
.merge_extent_hook = btrfs_merge_extent_hook,
.split_extent_hook = btrfs_split_extent_hook,
};
/*
* btrfs doesn't support the bmap operation because swapfiles
* use bmap to make a mapping of extents in the file. They assume
* these extents won't change over the life of the file and they
* use the bmap result to do IO directly to the drive.
*
* the btrfs bmap call would return logical addresses that aren't
* suitable for IO and they also will change frequently as COW
* operations happen. So, swapfile + btrfs == corruption.
*
* For now we're avoiding this by dropping bmap.
*/
static const struct address_space_operations btrfs_aops = {
.readpage = btrfs_readpage,
.writepage = btrfs_writepage,
.writepages = btrfs_writepages,
.readpages = btrfs_readpages,
.direct_IO = btrfs_direct_IO,
.invalidatepage = btrfs_invalidatepage,
.releasepage = btrfs_releasepage,
.set_page_dirty = btrfs_set_page_dirty,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations btrfs_symlink_aops = {
.readpage = btrfs_readpage,
.writepage = btrfs_writepage,
.invalidatepage = btrfs_invalidatepage,
.releasepage = btrfs_releasepage,
};
static const struct inode_operations btrfs_file_inode_operations = {
.getattr = btrfs_getattr,
.setattr = btrfs_setattr,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.permission = btrfs_permission,
.fiemap = btrfs_fiemap,
.get_acl = btrfs_get_acl,
};
static const struct inode_operations btrfs_special_inode_operations = {
.getattr = btrfs_getattr,
.setattr = btrfs_setattr,
.permission = btrfs_permission,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.get_acl = btrfs_get_acl,
};
static const struct inode_operations btrfs_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
.getattr = btrfs_getattr,
.setattr = btrfs_setattr,
.permission = btrfs_permission,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.get_acl = btrfs_get_acl,
};
const struct dentry_operations btrfs_dentry_operations = {
.d_delete = btrfs_dentry_delete,
.d_release = btrfs_dentry_release,
};
| gpl-2.0 |
ByteInternet/linux-grsec | drivers/usb/gadget/f_phonet.c | 29 | 15134 | /*
* f_phonet.c -- USB CDC Phonet function
*
* Copyright (C) 2007-2008 Nokia Corporation. All rights reserved.
*
* Author: Rémi Denis-Courmont
*
* 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/mm.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/netdevice.h>
#include <linux/if_ether.h>
#include <linux/if_phonet.h>
#include <linux/if_arp.h>
#include <linux/usb/ch9.h>
#include <linux/usb/cdc.h>
#include <linux/usb/composite.h>
#include "u_phonet.h"
#define PN_MEDIA_USB 0x1B
#define MAXPACKET 512
#if (PAGE_SIZE % MAXPACKET)
#error MAXPACKET must divide PAGE_SIZE!
#endif
/*-------------------------------------------------------------------------*/
struct phonet_port {
struct f_phonet *usb;
spinlock_t lock;
};
struct f_phonet {
struct usb_function function;
struct {
struct sk_buff *skb;
spinlock_t lock;
} rx;
struct net_device *dev;
struct usb_ep *in_ep, *out_ep;
struct usb_request *in_req;
struct usb_request *out_reqv[0];
};
static int phonet_rxq_size = 17;
static inline struct f_phonet *func_to_pn(struct usb_function *f)
{
return container_of(f, struct f_phonet, function);
}
/*-------------------------------------------------------------------------*/
#define USB_CDC_SUBCLASS_PHONET 0xfe
#define USB_CDC_PHONET_TYPE 0xab
static struct usb_interface_descriptor
pn_control_intf_desc = {
.bLength = sizeof pn_control_intf_desc,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC, */
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_PHONET,
};
static const struct usb_cdc_header_desc
pn_header_desc = {
.bLength = sizeof pn_header_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static const struct usb_cdc_header_desc
pn_phonet_desc = {
.bLength = sizeof pn_phonet_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_PHONET_TYPE,
.bcdCDC = cpu_to_le16(0x1505), /* ??? */
};
static struct usb_cdc_union_desc
pn_union_desc = {
.bLength = sizeof pn_union_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC, */
/* .bSlaveInterface0 = DYNAMIC, */
};
static struct usb_interface_descriptor
pn_data_nop_intf_desc = {
.bLength = sizeof pn_data_nop_intf_desc,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC, */
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_CDC_DATA,
};
static struct usb_interface_descriptor
pn_data_intf_desc = {
.bLength = sizeof pn_data_intf_desc,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC, */
.bAlternateSetting = 1,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
};
static struct usb_endpoint_descriptor
pn_fs_sink_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor
pn_hs_sink_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(MAXPACKET),
};
static struct usb_endpoint_descriptor
pn_fs_source_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor
pn_hs_source_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *fs_pn_function[] = {
(struct usb_descriptor_header *) &pn_control_intf_desc,
(struct usb_descriptor_header *) &pn_header_desc,
(struct usb_descriptor_header *) &pn_phonet_desc,
(struct usb_descriptor_header *) &pn_union_desc,
(struct usb_descriptor_header *) &pn_data_nop_intf_desc,
(struct usb_descriptor_header *) &pn_data_intf_desc,
(struct usb_descriptor_header *) &pn_fs_sink_desc,
(struct usb_descriptor_header *) &pn_fs_source_desc,
NULL,
};
static struct usb_descriptor_header *hs_pn_function[] = {
(struct usb_descriptor_header *) &pn_control_intf_desc,
(struct usb_descriptor_header *) &pn_header_desc,
(struct usb_descriptor_header *) &pn_phonet_desc,
(struct usb_descriptor_header *) &pn_union_desc,
(struct usb_descriptor_header *) &pn_data_nop_intf_desc,
(struct usb_descriptor_header *) &pn_data_intf_desc,
(struct usb_descriptor_header *) &pn_hs_sink_desc,
(struct usb_descriptor_header *) &pn_hs_source_desc,
NULL,
};
/*-------------------------------------------------------------------------*/
static int pn_net_open(struct net_device *dev)
{
netif_wake_queue(dev);
return 0;
}
static int pn_net_close(struct net_device *dev)
{
netif_stop_queue(dev);
return 0;
}
static void pn_tx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_phonet *fp = ep->driver_data;
struct net_device *dev = fp->dev;
struct sk_buff *skb = req->context;
switch (req->status) {
case 0:
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
break;
case -ESHUTDOWN: /* disconnected */
case -ECONNRESET: /* disabled */
dev->stats.tx_aborted_errors++;
default:
dev->stats.tx_errors++;
}
dev_kfree_skb_any(skb);
netif_wake_queue(dev);
}
static int pn_net_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct phonet_port *port = netdev_priv(dev);
struct f_phonet *fp;
struct usb_request *req;
unsigned long flags;
if (skb->protocol != htons(ETH_P_PHONET))
goto out;
spin_lock_irqsave(&port->lock, flags);
fp = port->usb;
if (unlikely(!fp)) /* race with carrier loss */
goto out_unlock;
req = fp->in_req;
req->buf = skb->data;
req->length = skb->len;
req->complete = pn_tx_complete;
req->zero = 1;
req->context = skb;
if (unlikely(usb_ep_queue(fp->in_ep, req, GFP_ATOMIC)))
goto out_unlock;
netif_stop_queue(dev);
skb = NULL;
out_unlock:
spin_unlock_irqrestore(&port->lock, flags);
out:
if (unlikely(skb)) {
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
}
return NETDEV_TX_OK;
}
static int pn_net_mtu(struct net_device *dev, int new_mtu)
{
if ((new_mtu < PHONET_MIN_MTU) || (new_mtu > PHONET_MAX_MTU))
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
static const struct net_device_ops pn_netdev_ops = {
.ndo_open = pn_net_open,
.ndo_stop = pn_net_close,
.ndo_start_xmit = pn_net_xmit,
.ndo_change_mtu = pn_net_mtu,
};
static void pn_net_setup(struct net_device *dev)
{
dev->features = 0;
dev->type = ARPHRD_PHONET;
dev->flags = IFF_POINTOPOINT | IFF_NOARP;
dev->mtu = PHONET_DEV_MTU;
dev->hard_header_len = 1;
dev->dev_addr[0] = PN_MEDIA_USB;
dev->addr_len = 1;
dev->tx_queue_len = 1;
dev->netdev_ops = &pn_netdev_ops;
dev->destructor = free_netdev;
dev->header_ops = &phonet_header_ops;
}
/*-------------------------------------------------------------------------*/
/*
* Queue buffer for data from the host
*/
static int
pn_rx_submit(struct f_phonet *fp, struct usb_request *req, gfp_t gfp_flags)
{
struct net_device *dev = fp->dev;
struct page *page;
int err;
page = __netdev_alloc_page(dev, gfp_flags);
if (!page)
return -ENOMEM;
req->buf = page_address(page);
req->length = PAGE_SIZE;
req->context = page;
err = usb_ep_queue(fp->out_ep, req, gfp_flags);
if (unlikely(err))
netdev_free_page(dev, page);
return err;
}
static void pn_rx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_phonet *fp = ep->driver_data;
struct net_device *dev = fp->dev;
struct page *page = req->context;
struct sk_buff *skb;
unsigned long flags;
int status = req->status;
switch (status) {
case 0:
spin_lock_irqsave(&fp->rx.lock, flags);
skb = fp->rx.skb;
if (!skb)
skb = fp->rx.skb = netdev_alloc_skb(dev, 12);
if (req->actual < req->length) /* Last fragment */
fp->rx.skb = NULL;
spin_unlock_irqrestore(&fp->rx.lock, flags);
if (unlikely(!skb))
break;
if (skb->len == 0) { /* First fragment */
skb->protocol = htons(ETH_P_PHONET);
skb_reset_mac_header(skb);
/* Can't use pskb_pull() on page in IRQ */
memcpy(skb_put(skb, 1), page_address(page), 1);
}
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page,
skb->len <= 1, req->actual);
page = NULL;
if (req->actual < req->length) { /* Last fragment */
skb->dev = dev;
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;
netif_rx(skb);
}
break;
/* Do not resubmit in these cases: */
case -ESHUTDOWN: /* disconnect */
case -ECONNABORTED: /* hw reset */
case -ECONNRESET: /* dequeued (unlink or netif down) */
req = NULL;
break;
/* Do resubmit in these cases: */
case -EOVERFLOW: /* request buffer overflow */
dev->stats.rx_over_errors++;
default:
dev->stats.rx_errors++;
break;
}
if (page)
netdev_free_page(dev, page);
if (req)
pn_rx_submit(fp, req, GFP_ATOMIC);
}
/*-------------------------------------------------------------------------*/
static void __pn_reset(struct usb_function *f)
{
struct f_phonet *fp = func_to_pn(f);
struct net_device *dev = fp->dev;
struct phonet_port *port = netdev_priv(dev);
netif_carrier_off(dev);
port->usb = NULL;
usb_ep_disable(fp->out_ep);
usb_ep_disable(fp->in_ep);
if (fp->rx.skb) {
dev_kfree_skb_irq(fp->rx.skb);
fp->rx.skb = NULL;
}
}
static int pn_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_phonet *fp = func_to_pn(f);
struct usb_gadget *gadget = fp->function.config->cdev->gadget;
if (intf == pn_control_intf_desc.bInterfaceNumber)
/* control interface, no altsetting */
return (alt > 0) ? -EINVAL : 0;
if (intf == pn_data_intf_desc.bInterfaceNumber) {
struct net_device *dev = fp->dev;
struct phonet_port *port = netdev_priv(dev);
/* data intf (0: inactive, 1: active) */
if (alt > 1)
return -EINVAL;
spin_lock(&port->lock);
__pn_reset(f);
if (alt == 1) {
int i;
if (config_ep_by_speed(gadget, f, fp->in_ep) ||
config_ep_by_speed(gadget, f, fp->out_ep)) {
fp->in_ep->desc = NULL;
fp->out_ep->desc = NULL;
spin_unlock(&port->lock);
return -EINVAL;
}
usb_ep_enable(fp->out_ep);
usb_ep_enable(fp->in_ep);
port->usb = fp;
fp->out_ep->driver_data = fp;
fp->in_ep->driver_data = fp;
netif_carrier_on(dev);
for (i = 0; i < phonet_rxq_size; i++)
pn_rx_submit(fp, fp->out_reqv[i], GFP_ATOMIC);
}
spin_unlock(&port->lock);
return 0;
}
return -EINVAL;
}
static int pn_get_alt(struct usb_function *f, unsigned intf)
{
struct f_phonet *fp = func_to_pn(f);
if (intf == pn_control_intf_desc.bInterfaceNumber)
return 0;
if (intf == pn_data_intf_desc.bInterfaceNumber) {
struct phonet_port *port = netdev_priv(fp->dev);
u8 alt;
spin_lock(&port->lock);
alt = port->usb != NULL;
spin_unlock(&port->lock);
return alt;
}
return -EINVAL;
}
static void pn_disconnect(struct usb_function *f)
{
struct f_phonet *fp = func_to_pn(f);
struct phonet_port *port = netdev_priv(fp->dev);
unsigned long flags;
/* remain disabled until set_alt */
spin_lock_irqsave(&port->lock, flags);
__pn_reset(f);
spin_unlock_irqrestore(&port->lock, flags);
}
/*-------------------------------------------------------------------------*/
static __init
int pn_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct usb_gadget *gadget = cdev->gadget;
struct f_phonet *fp = func_to_pn(f);
struct usb_ep *ep;
int status, i;
/* Reserve interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto err;
pn_control_intf_desc.bInterfaceNumber = status;
pn_union_desc.bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto err;
pn_data_nop_intf_desc.bInterfaceNumber = status;
pn_data_intf_desc.bInterfaceNumber = status;
pn_union_desc.bSlaveInterface0 = status;
/* Reserve endpoints */
status = -ENODEV;
ep = usb_ep_autoconfig(gadget, &pn_fs_sink_desc);
if (!ep)
goto err;
fp->out_ep = ep;
ep->driver_data = fp; /* Claim */
ep = usb_ep_autoconfig(gadget, &pn_fs_source_desc);
if (!ep)
goto err;
fp->in_ep = ep;
ep->driver_data = fp; /* Claim */
pn_hs_sink_desc.bEndpointAddress =
pn_fs_sink_desc.bEndpointAddress;
pn_hs_source_desc.bEndpointAddress =
pn_fs_source_desc.bEndpointAddress;
/* Do not try to bind Phonet twice... */
fp->function.descriptors = fs_pn_function;
fp->function.hs_descriptors = hs_pn_function;
/* Incoming USB requests */
status = -ENOMEM;
for (i = 0; i < phonet_rxq_size; i++) {
struct usb_request *req;
req = usb_ep_alloc_request(fp->out_ep, GFP_KERNEL);
if (!req)
goto err_req;
req->complete = pn_rx_complete;
fp->out_reqv[i] = req;
}
/* Outgoing USB requests */
fp->in_req = usb_ep_alloc_request(fp->in_ep, GFP_KERNEL);
if (!fp->in_req)
goto err_req;
INFO(cdev, "USB CDC Phonet function\n");
INFO(cdev, "using %s, OUT %s, IN %s\n", cdev->gadget->name,
fp->out_ep->name, fp->in_ep->name);
return 0;
err_req:
for (i = 0; i < phonet_rxq_size && fp->out_reqv[i]; i++)
usb_ep_free_request(fp->out_ep, fp->out_reqv[i]);
err:
if (fp->out_ep)
fp->out_ep->driver_data = NULL;
if (fp->in_ep)
fp->in_ep->driver_data = NULL;
ERROR(cdev, "USB CDC Phonet: cannot autoconfigure\n");
return status;
}
static void
pn_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_phonet *fp = func_to_pn(f);
int i;
/* We are already disconnected */
if (fp->in_req)
usb_ep_free_request(fp->in_ep, fp->in_req);
for (i = 0; i < phonet_rxq_size; i++)
if (fp->out_reqv[i])
usb_ep_free_request(fp->out_ep, fp->out_reqv[i]);
kfree(fp);
}
/*-------------------------------------------------------------------------*/
static struct net_device *dev;
int __init phonet_bind_config(struct usb_configuration *c)
{
struct f_phonet *fp;
int err, size;
size = sizeof(*fp) + (phonet_rxq_size * sizeof(struct usb_request *));
fp = kzalloc(size, GFP_KERNEL);
if (!fp)
return -ENOMEM;
fp->dev = dev;
fp->function.name = "phonet";
fp->function.bind = pn_bind;
fp->function.unbind = pn_unbind;
fp->function.set_alt = pn_set_alt;
fp->function.get_alt = pn_get_alt;
fp->function.disable = pn_disconnect;
spin_lock_init(&fp->rx.lock);
err = usb_add_function(c, &fp->function);
if (err)
kfree(fp);
return err;
}
int __init gphonet_setup(struct usb_gadget *gadget)
{
struct phonet_port *port;
int err;
/* Create net device */
BUG_ON(dev);
dev = alloc_netdev(sizeof(*port), "upnlink%d", pn_net_setup);
if (!dev)
return -ENOMEM;
port = netdev_priv(dev);
spin_lock_init(&port->lock);
netif_carrier_off(dev);
SET_NETDEV_DEV(dev, &gadget->dev);
err = register_netdev(dev);
if (err)
free_netdev(dev);
return err;
}
void gphonet_cleanup(void)
{
unregister_netdev(dev);
}
| gpl-2.0 |
bigzz/linux-linaro-lsk | arch/h8300/mm/init.c | 1053 | 4538 | /*
* linux/arch/h8300/mm/init.c
*
* Copyright (C) 1998 D. Jeff Dionne <jeff@lineo.ca>,
* Kenneth Albanowski <kjahds@kjahds.com>,
* Copyright (C) 2000 Lineo, Inc. (www.lineo.com)
*
* Based on:
*
* linux/arch/m68knommu/mm/init.c
* linux/arch/m68k/mm/init.c
*
* Copyright (C) 1995 Hamish Macdonald
*
* JAN/1999 -- hacked to support ColdFire (gerg@snapgear.com)
* DEC/2000 -- linux 2.4 support <davidm@snapgear.com>
*/
#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/init.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/bootmem.h>
#include <linux/gfp.h>
#include <asm/setup.h>
#include <asm/segment.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/sections.h>
#undef DEBUG
/*
* BAD_PAGE is the page that is used for page faults when linux
* is out-of-memory. Older versions of linux just did a
* do_exit(), but using this instead means there is less risk
* for a process dying in kernel mode, possibly leaving a inode
* unused etc..
*
* BAD_PAGETABLE is the accompanying page-table: it is initialized
* to point to BAD_PAGE entries.
*
* ZERO_PAGE is a special page that is used for zero-initialized
* data and COW.
*/
static unsigned long empty_bad_page_table;
static unsigned long empty_bad_page;
unsigned long empty_zero_page;
extern unsigned long rom_length;
extern unsigned long memory_start;
extern unsigned long memory_end;
/*
* paging_init() continues the virtual memory environment setup which
* was begun by the code in arch/head.S.
* The parameters are pointers to where to stick the starting and ending
* addresses of available kernel virtual memory.
*/
void __init paging_init(void)
{
/*
* Make sure start_mem is page aligned, otherwise bootmem and
* page_alloc get different views og the world.
*/
#ifdef DEBUG
unsigned long start_mem = PAGE_ALIGN(memory_start);
#endif
unsigned long end_mem = memory_end & PAGE_MASK;
#ifdef DEBUG
printk ("start_mem is %#lx\nvirtual_end is %#lx\n",
start_mem, end_mem);
#endif
/*
* Initialize the bad page table and bad page to point
* to a couple of allocated pages.
*/
empty_bad_page_table = (unsigned long)alloc_bootmem_pages(PAGE_SIZE);
empty_bad_page = (unsigned long)alloc_bootmem_pages(PAGE_SIZE);
empty_zero_page = (unsigned long)alloc_bootmem_pages(PAGE_SIZE);
memset((void *)empty_zero_page, 0, PAGE_SIZE);
/*
* Set up SFC/DFC registers (user data space).
*/
set_fs (USER_DS);
#ifdef DEBUG
printk ("before free_area_init\n");
printk ("free_area_init -> start_mem is %#lx\nvirtual_end is %#lx\n",
start_mem, end_mem);
#endif
{
unsigned long zones_size[MAX_NR_ZONES] = {0, };
zones_size[ZONE_DMA] = 0 >> PAGE_SHIFT;
zones_size[ZONE_NORMAL] = (end_mem - PAGE_OFFSET) >> PAGE_SHIFT;
#ifdef CONFIG_HIGHMEM
zones_size[ZONE_HIGHMEM] = 0;
#endif
free_area_init(zones_size);
}
}
void __init mem_init(void)
{
int codek = 0, datak = 0, initk = 0;
/* DAVIDM look at setup memory map generically with reserved area */
unsigned long tmp;
extern unsigned long _ramend, _ramstart;
unsigned long len = &_ramend - &_ramstart;
unsigned long start_mem = memory_start; /* DAVIDM - these must start at end of kernel */
unsigned long end_mem = memory_end; /* DAVIDM - this must not include kernel stack at top */
#ifdef DEBUG
printk(KERN_DEBUG "Mem_init: start=%lx, end=%lx\n", start_mem, end_mem);
#endif
end_mem &= PAGE_MASK;
high_memory = (void *) end_mem;
start_mem = PAGE_ALIGN(start_mem);
max_mapnr = num_physpages = MAP_NR(high_memory);
/* this will put all low memory onto the freelists */
totalram_pages = free_all_bootmem();
codek = (_etext - _stext) >> 10;
datak = (__bss_stop - _sdata) >> 10;
initk = (__init_begin - __init_end) >> 10;
tmp = nr_free_pages() << PAGE_SHIFT;
printk(KERN_INFO "Memory available: %luk/%luk RAM, %luk/%luk ROM (%dk kernel code, %dk data)\n",
tmp >> 10,
len >> 10,
(rom_length > 0) ? ((rom_length >> 10) - codek) : 0,
rom_length >> 10,
codek,
datak
);
}
#ifdef CONFIG_BLK_DEV_INITRD
void free_initrd_mem(unsigned long start, unsigned long end)
{
free_reserved_area(start, end, 0, "initrd");
}
#endif
void
free_initmem(void)
{
#ifdef CONFIG_RAMKERNEL
free_initmem_default(0);
#endif
}
| gpl-2.0 |
lanniaoershi/android_kernel_oneplus_msm8994 | drivers/net/wireless/ath/wil6210/wil_platform_msm.c | 1053 | 7046 | /*
* Copyright (c) 2014 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/of.h>
#include <linux/slab.h>
#include <linux/msm-bus.h>
#include "wil_platform.h"
#include "wil_platform_msm.h"
/**
* struct wil_platform_msm - wil6210 msm platform module info
*
* @dev: device object
* @msm_bus_handle: handle for using msm_bus API
* @pdata: bus scale info retrieved from DT
*/
struct wil_platform_msm {
struct device *dev;
uint32_t msm_bus_handle;
struct msm_bus_scale_pdata *pdata;
};
#define KBTOB(a) (a * 1000ULL)
/**
* wil_platform_get_pdata() - Generate bus client data from device tree
* provided by clients.
*
* dev: device object
* of_node: Device tree node to extract information from
*
* The function returns a valid pointer to the allocated bus-scale-pdata
* if the vectors were correctly read from the client's device node.
* Any error in reading or parsing the device node will return NULL
* to the caller.
*/
static struct msm_bus_scale_pdata *wil_platform_get_pdata(
struct device *dev,
struct device_node *of_node)
{
struct msm_bus_scale_pdata *pdata;
struct msm_bus_paths *usecase;
int i, j, ret, len;
unsigned int num_usecases, num_paths, mem_size;
const uint32_t *vec_arr;
struct msm_bus_vectors *vectors;
/* first read num_usecases and num_paths so we can calculate
* amount of memory to allocate
*/
ret = of_property_read_u32(of_node, "qcom,msm-bus,num-cases",
&num_usecases);
if (ret) {
dev_err(dev, "Error: num-usecases not found\n");
return NULL;
}
ret = of_property_read_u32(of_node, "qcom,msm-bus,num-paths",
&num_paths);
if (ret) {
dev_err(dev, "Error: num_paths not found\n");
return NULL;
}
/* pdata memory layout:
* msm_bus_scale_pdata
* msm_bus_paths[num_usecases]
* msm_bus_vectors[num_usecases][num_paths]
*/
mem_size = sizeof(struct msm_bus_scale_pdata) +
sizeof(struct msm_bus_paths) * num_usecases +
sizeof(struct msm_bus_vectors) * num_usecases * num_paths;
pdata = kzalloc(mem_size, GFP_KERNEL);
if (!pdata)
return NULL;
ret = of_property_read_string(of_node, "qcom,msm-bus,name",
&pdata->name);
if (ret) {
dev_err(dev, "Error: Client name not found\n");
goto err;
}
if (of_property_read_bool(of_node, "qcom,msm-bus,active-only")) {
pdata->active_only = 1;
} else {
dev_info(dev, "active_only flag absent.\n");
dev_info(dev, "Using dual context by default\n");
}
pdata->num_usecases = num_usecases;
pdata->usecase = (struct msm_bus_paths *)(pdata + 1);
vec_arr = of_get_property(of_node, "qcom,msm-bus,vectors-KBps", &len);
if (vec_arr == NULL) {
dev_err(dev, "Error: Vector array not found\n");
goto err;
}
if (len != num_usecases * num_paths * sizeof(uint32_t) * 4) {
dev_err(dev, "Error: Length-error on getting vectors\n");
goto err;
}
vectors = (struct msm_bus_vectors *)(pdata->usecase + num_usecases);
for (i = 0; i < num_usecases; i++) {
usecase = &pdata->usecase[i];
usecase->num_paths = num_paths;
usecase->vectors = &vectors[i];
for (j = 0; j < num_paths; j++) {
int index = ((i * num_paths) + j) * 4;
usecase->vectors[j].src = be32_to_cpu(vec_arr[index]);
usecase->vectors[j].dst =
be32_to_cpu(vec_arr[index + 1]);
usecase->vectors[j].ab = (uint64_t)
KBTOB(be32_to_cpu(vec_arr[index + 2]));
usecase->vectors[j].ib = (uint64_t)
KBTOB(be32_to_cpu(vec_arr[index + 3]));
}
}
return pdata;
err:
kfree(pdata);
return NULL;
}
/* wil_platform API (callbacks) */
static int wil_platform_bus_request(void *handle,
uint32_t kbps /* KBytes/Sec */)
{
int rc, i;
struct wil_platform_msm *msm = (struct wil_platform_msm *)handle;
int vote = 0; /* vote 0 in case requested kbps cannot be satisfied */
struct msm_bus_paths *usecase;
uint32_t usecase_kbps;
uint32_t min_kbps = ~0;
/* find the lowest usecase that is bigger than requested kbps */
for (i = 0; i < msm->pdata->num_usecases; i++) {
usecase = &msm->pdata->usecase[i];
/* assume we have single path (vectors[0]). If we ever
* have multiple paths, need to define the behavior */
usecase_kbps = div64_u64(usecase->vectors[0].ib, 1000);
if (usecase_kbps >= kbps && usecase_kbps < min_kbps) {
min_kbps = usecase_kbps;
vote = i;
}
}
rc = msm_bus_scale_client_update_request(msm->msm_bus_handle, vote);
if (rc)
dev_err(msm->dev, "Failed msm_bus voting. kbps=%d vote=%d, rc=%d\n",
kbps, vote, rc);
else
/* TOOD: remove */
dev_info(msm->dev, "msm_bus_scale_client_update_request succeeded. kbps=%d vote=%d\n",
kbps, vote);
return rc;
}
static void wil_platform_uninit(void *handle)
{
struct wil_platform_msm *msm = (struct wil_platform_msm *)handle;
dev_info(msm->dev, "wil_platform_uninit\n");
if (msm->msm_bus_handle)
msm_bus_scale_unregister_client(msm->msm_bus_handle);
kfree(msm->pdata);
kfree(msm);
}
static int wil_platform_msm_bus_register(struct wil_platform_msm *msm,
struct device_node *node)
{
msm->pdata = wil_platform_get_pdata(msm->dev, node);
if (!msm->pdata) {
dev_err(msm->dev, "Failed getting DT info\n");
return -EINVAL;
}
msm->msm_bus_handle = msm_bus_scale_register_client(msm->pdata);
if (!msm->msm_bus_handle) {
dev_err(msm->dev, "Failed msm_bus registration\n");
return -EINVAL;
}
dev_info(msm->dev, "msm_bus registration succeeded! handle 0x%x\n",
msm->msm_bus_handle);
return 0;
}
/**
* wil_platform_msm_init() - wil6210 msm platform module init
*
* The function must be called before all other functions in this module.
* It returns a handle which is used with the rest of the API
*
*/
void *wil_platform_msm_init(struct device *dev, struct wil_platform_ops *ops)
{
struct device_node *of_node;
struct wil_platform_msm *msm;
int rc;
of_node = of_find_compatible_node(NULL, NULL, "qcom,wil6210");
if (!of_node) {
/* this could mean non-msm platform */
dev_err(dev, "DT node not found\n");
return NULL;
}
msm = kzalloc(sizeof(*msm), GFP_KERNEL);
if (!msm)
return NULL;
msm->dev = dev;
/* register with msm_bus module for scaling requests */
rc = wil_platform_msm_bus_register(msm, of_node);
if (rc)
goto cleanup;
memset(ops, 0, sizeof(*ops));
ops->bus_request = wil_platform_bus_request;
ops->uninit = wil_platform_uninit;
return (void *)msm;
cleanup:
kfree(msm);
return NULL;
}
| gpl-2.0 |
vigor/vigor_aosp_kernel | arch/mips/alchemy/devboards/pb1500/board_setup.c | 2589 | 5048 | /*
* Copyright 2000, 2008 MontaVista Software Inc.
* Author: MontaVista Software, Inc. <source@mvista.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <asm/mach-au1x00/au1000.h>
#include <asm/mach-db1x00/bcsr.h>
#include <prom.h>
char irq_tab_alchemy[][5] __initdata = {
[12] = { -1, AU1500_PCI_INTA, 0xff, 0xff, 0xff }, /* IDSEL 12 - HPT370 */
[13] = { -1, AU1500_PCI_INTA, AU1500_PCI_INTB, AU1500_PCI_INTC, AU1500_PCI_INTD }, /* IDSEL 13 - PCI slot */
};
const char *get_system_type(void)
{
return "Alchemy Pb1500";
}
void __init board_setup(void)
{
u32 pin_func;
u32 sys_freqctrl, sys_clksrc;
bcsr_init(DB1000_BCSR_PHYS_ADDR,
DB1000_BCSR_PHYS_ADDR + DB1000_BCSR_HEXLED_OFS);
sys_clksrc = sys_freqctrl = pin_func = 0;
/* Set AUX clock to 12 MHz * 8 = 96 MHz */
au_writel(8, SYS_AUXPLL);
alchemy_gpio1_input_enable();
udelay(100);
/* GPIO201 is input for PCMCIA card detect */
/* GPIO203 is input for PCMCIA interrupt request */
alchemy_gpio_direction_input(201);
alchemy_gpio_direction_input(203);
#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
/* Zero and disable FREQ2 */
sys_freqctrl = au_readl(SYS_FREQCTRL0);
sys_freqctrl &= ~0xFFF00000;
au_writel(sys_freqctrl, SYS_FREQCTRL0);
/* zero and disable USBH/USBD clocks */
sys_clksrc = au_readl(SYS_CLKSRC);
sys_clksrc &= ~(SYS_CS_CUD | SYS_CS_DUD | SYS_CS_MUD_MASK |
SYS_CS_CUH | SYS_CS_DUH | SYS_CS_MUH_MASK);
au_writel(sys_clksrc, SYS_CLKSRC);
sys_freqctrl = au_readl(SYS_FREQCTRL0);
sys_freqctrl &= ~0xFFF00000;
sys_clksrc = au_readl(SYS_CLKSRC);
sys_clksrc &= ~(SYS_CS_CUD | SYS_CS_DUD | SYS_CS_MUD_MASK |
SYS_CS_CUH | SYS_CS_DUH | SYS_CS_MUH_MASK);
/* FREQ2 = aux/2 = 48 MHz */
sys_freqctrl |= (0 << SYS_FC_FRDIV2_BIT) | SYS_FC_FE2 | SYS_FC_FS2;
au_writel(sys_freqctrl, SYS_FREQCTRL0);
/*
* Route 48MHz FREQ2 into USB Host and/or Device
*/
sys_clksrc |= SYS_CS_MUX_FQ2 << SYS_CS_MUH_BIT;
au_writel(sys_clksrc, SYS_CLKSRC);
pin_func = au_readl(SYS_PINFUNC) & ~SYS_PF_USB;
/* 2nd USB port is USB host */
pin_func |= SYS_PF_USB;
au_writel(pin_func, SYS_PINFUNC);
#endif /* defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE) */
#ifdef CONFIG_PCI
/* Setup PCI bus controller */
au_writel(0, Au1500_PCI_CMEM);
au_writel(0x00003fff, Au1500_CFG_BASE);
#if defined(__MIPSEB__)
au_writel(0xf | (2 << 6) | (1 << 4), Au1500_PCI_CFG);
#else
au_writel(0xf, Au1500_PCI_CFG);
#endif
au_writel(0xf0000000, Au1500_PCI_MWMASK_DEV);
au_writel(0, Au1500_PCI_MWBASE_REV_CCL);
au_writel(0x02a00356, Au1500_PCI_STATCMD);
au_writel(0x00003c04, Au1500_PCI_HDRTYPE);
au_writel(0x00000008, Au1500_PCI_MBAR);
au_sync();
#endif
/* Enable sys bus clock divider when IDLE state or no bus activity. */
au_writel(au_readl(SYS_POWERCTRL) | (0x3 << 5), SYS_POWERCTRL);
/* Enable the RTC if not already enabled */
if (!(au_readl(0xac000028) & 0x20)) {
printk(KERN_INFO "enabling clock ...\n");
au_writel((au_readl(0xac000028) | 0x20), 0xac000028);
}
/* Put the clock in BCD mode */
if (au_readl(0xac00002c) & 0x4) { /* reg B */
au_writel(au_readl(0xac00002c) & ~0x4, 0xac00002c);
au_sync();
}
}
static int __init pb1500_init_irq(void)
{
irq_set_irq_type(AU1500_GPIO9_INT, IRQF_TRIGGER_LOW); /* CD0# */
irq_set_irq_type(AU1500_GPIO10_INT, IRQF_TRIGGER_LOW); /* CARD0 */
irq_set_irq_type(AU1500_GPIO11_INT, IRQF_TRIGGER_LOW); /* STSCHG0# */
irq_set_irq_type(AU1500_GPIO204_INT, IRQF_TRIGGER_HIGH);
irq_set_irq_type(AU1500_GPIO201_INT, IRQF_TRIGGER_LOW);
irq_set_irq_type(AU1500_GPIO202_INT, IRQF_TRIGGER_LOW);
irq_set_irq_type(AU1500_GPIO203_INT, IRQF_TRIGGER_LOW);
irq_set_irq_type(AU1500_GPIO205_INT, IRQF_TRIGGER_LOW);
return 0;
}
arch_initcall(pb1500_init_irq);
| gpl-2.0 |
morristech/GT-I9300-JB-3.0.y | scripts/kconfig/conf.c | 2589 | 13502 | /*
* Copyright (C) 2002 Roman Zippel <zippel@linux-m68k.org>
* Released under the terms of the GNU GPL v2.0.
*/
#include <locale.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/time.h>
#define LKC_DIRECT_LINK
#include "lkc.h"
static void conf(struct menu *menu);
static void check_conf(struct menu *menu);
enum input_mode {
oldaskconfig,
silentoldconfig,
oldconfig,
allnoconfig,
allyesconfig,
allmodconfig,
alldefconfig,
randconfig,
defconfig,
savedefconfig,
listnewconfig,
oldnoconfig,
} input_mode = oldaskconfig;
char *defconfig_file;
static int indent = 1;
static int valid_stdin = 1;
static int sync_kconfig;
static int conf_cnt;
static char line[128];
static struct menu *rootEntry;
static void print_help(struct menu *menu)
{
struct gstr help = str_new();
menu_get_ext_help(menu, &help);
printf("\n%s\n", str_get(&help));
str_free(&help);
}
static void strip(char *str)
{
char *p = str;
int l;
while ((isspace(*p)))
p++;
l = strlen(p);
if (p != str)
memmove(str, p, l + 1);
if (!l)
return;
p = str + l - 1;
while ((isspace(*p)))
*p-- = 0;
}
static void check_stdin(void)
{
if (!valid_stdin) {
printf(_("aborted!\n\n"));
printf(_("Console input/output is redirected. "));
printf(_("Run 'make oldconfig' to update configuration.\n\n"));
exit(1);
}
}
static int conf_askvalue(struct symbol *sym, const char *def)
{
enum symbol_type type = sym_get_type(sym);
if (!sym_has_value(sym))
printf(_("(NEW) "));
line[0] = '\n';
line[1] = 0;
if (!sym_is_changable(sym)) {
printf("%s\n", def);
line[0] = '\n';
line[1] = 0;
return 0;
}
switch (input_mode) {
case oldconfig:
case silentoldconfig:
if (sym_has_value(sym)) {
printf("%s\n", def);
return 0;
}
check_stdin();
case oldaskconfig:
fflush(stdout);
xfgets(line, 128, stdin);
return 1;
default:
break;
}
switch (type) {
case S_INT:
case S_HEX:
case S_STRING:
printf("%s\n", def);
return 1;
default:
;
}
printf("%s", line);
return 1;
}
static int conf_string(struct menu *menu)
{
struct symbol *sym = menu->sym;
const char *def;
while (1) {
printf("%*s%s ", indent - 1, "", _(menu->prompt->text));
printf("(%s) ", sym->name);
def = sym_get_string_value(sym);
if (sym_get_string_value(sym))
printf("[%s] ", def);
if (!conf_askvalue(sym, def))
return 0;
switch (line[0]) {
case '\n':
break;
case '?':
/* print help */
if (line[1] == '\n') {
print_help(menu);
def = NULL;
break;
}
default:
line[strlen(line)-1] = 0;
def = line;
}
if (def && sym_set_string_value(sym, def))
return 0;
}
}
static int conf_sym(struct menu *menu)
{
struct symbol *sym = menu->sym;
tristate oldval, newval;
while (1) {
printf("%*s%s ", indent - 1, "", _(menu->prompt->text));
if (sym->name)
printf("(%s) ", sym->name);
putchar('[');
oldval = sym_get_tristate_value(sym);
switch (oldval) {
case no:
putchar('N');
break;
case mod:
putchar('M');
break;
case yes:
putchar('Y');
break;
}
if (oldval != no && sym_tristate_within_range(sym, no))
printf("/n");
if (oldval != mod && sym_tristate_within_range(sym, mod))
printf("/m");
if (oldval != yes && sym_tristate_within_range(sym, yes))
printf("/y");
if (menu_has_help(menu))
printf("/?");
printf("] ");
if (!conf_askvalue(sym, sym_get_string_value(sym)))
return 0;
strip(line);
switch (line[0]) {
case 'n':
case 'N':
newval = no;
if (!line[1] || !strcmp(&line[1], "o"))
break;
continue;
case 'm':
case 'M':
newval = mod;
if (!line[1])
break;
continue;
case 'y':
case 'Y':
newval = yes;
if (!line[1] || !strcmp(&line[1], "es"))
break;
continue;
case 0:
newval = oldval;
break;
case '?':
goto help;
default:
continue;
}
if (sym_set_tristate_value(sym, newval))
return 0;
help:
print_help(menu);
}
}
static int conf_choice(struct menu *menu)
{
struct symbol *sym, *def_sym;
struct menu *child;
bool is_new;
sym = menu->sym;
is_new = !sym_has_value(sym);
if (sym_is_changable(sym)) {
conf_sym(menu);
sym_calc_value(sym);
switch (sym_get_tristate_value(sym)) {
case no:
return 1;
case mod:
return 0;
case yes:
break;
}
} else {
switch (sym_get_tristate_value(sym)) {
case no:
return 1;
case mod:
printf("%*s%s\n", indent - 1, "", _(menu_get_prompt(menu)));
return 0;
case yes:
break;
}
}
while (1) {
int cnt, def;
printf("%*s%s\n", indent - 1, "", _(menu_get_prompt(menu)));
def_sym = sym_get_choice_value(sym);
cnt = def = 0;
line[0] = 0;
for (child = menu->list; child; child = child->next) {
if (!menu_is_visible(child))
continue;
if (!child->sym) {
printf("%*c %s\n", indent, '*', _(menu_get_prompt(child)));
continue;
}
cnt++;
if (child->sym == def_sym) {
def = cnt;
printf("%*c", indent, '>');
} else
printf("%*c", indent, ' ');
printf(" %d. %s", cnt, _(menu_get_prompt(child)));
if (child->sym->name)
printf(" (%s)", child->sym->name);
if (!sym_has_value(child->sym))
printf(_(" (NEW)"));
printf("\n");
}
printf(_("%*schoice"), indent - 1, "");
if (cnt == 1) {
printf("[1]: 1\n");
goto conf_childs;
}
printf("[1-%d", cnt);
if (menu_has_help(menu))
printf("?");
printf("]: ");
switch (input_mode) {
case oldconfig:
case silentoldconfig:
if (!is_new) {
cnt = def;
printf("%d\n", cnt);
break;
}
check_stdin();
case oldaskconfig:
fflush(stdout);
xfgets(line, 128, stdin);
strip(line);
if (line[0] == '?') {
print_help(menu);
continue;
}
if (!line[0])
cnt = def;
else if (isdigit(line[0]))
cnt = atoi(line);
else
continue;
break;
default:
break;
}
conf_childs:
for (child = menu->list; child; child = child->next) {
if (!child->sym || !menu_is_visible(child))
continue;
if (!--cnt)
break;
}
if (!child)
continue;
if (line[0] && line[strlen(line) - 1] == '?') {
print_help(child);
continue;
}
sym_set_choice_value(sym, child->sym);
for (child = child->list; child; child = child->next) {
indent += 2;
conf(child);
indent -= 2;
}
return 1;
}
}
static void conf(struct menu *menu)
{
struct symbol *sym;
struct property *prop;
struct menu *child;
if (!menu_is_visible(menu))
return;
sym = menu->sym;
prop = menu->prompt;
if (prop) {
const char *prompt;
switch (prop->type) {
case P_MENU:
if ((input_mode == silentoldconfig ||
input_mode == listnewconfig ||
input_mode == oldnoconfig) &&
rootEntry != menu) {
check_conf(menu);
return;
}
case P_COMMENT:
prompt = menu_get_prompt(menu);
if (prompt)
printf("%*c\n%*c %s\n%*c\n",
indent, '*',
indent, '*', _(prompt),
indent, '*');
default:
;
}
}
if (!sym)
goto conf_childs;
if (sym_is_choice(sym)) {
conf_choice(menu);
if (sym->curr.tri != mod)
return;
goto conf_childs;
}
switch (sym->type) {
case S_INT:
case S_HEX:
case S_STRING:
conf_string(menu);
break;
default:
conf_sym(menu);
break;
}
conf_childs:
if (sym)
indent += 2;
for (child = menu->list; child; child = child->next)
conf(child);
if (sym)
indent -= 2;
}
static void check_conf(struct menu *menu)
{
struct symbol *sym;
struct menu *child;
if (!menu_is_visible(menu))
return;
sym = menu->sym;
if (sym && !sym_has_value(sym)) {
if (sym_is_changable(sym) ||
(sym_is_choice(sym) && sym_get_tristate_value(sym) == yes)) {
if (input_mode == listnewconfig) {
if (sym->name && !sym_is_choice_value(sym)) {
printf("%s%s\n", CONFIG_, sym->name);
}
} else if (input_mode != oldnoconfig) {
if (!conf_cnt++)
printf(_("*\n* Restart config...\n*\n"));
rootEntry = menu_get_parent_menu(menu);
conf(rootEntry);
}
}
}
for (child = menu->list; child; child = child->next)
check_conf(child);
}
static struct option long_opts[] = {
{"oldaskconfig", no_argument, NULL, oldaskconfig},
{"oldconfig", no_argument, NULL, oldconfig},
{"silentoldconfig", no_argument, NULL, silentoldconfig},
{"defconfig", optional_argument, NULL, defconfig},
{"savedefconfig", required_argument, NULL, savedefconfig},
{"allnoconfig", no_argument, NULL, allnoconfig},
{"allyesconfig", no_argument, NULL, allyesconfig},
{"allmodconfig", no_argument, NULL, allmodconfig},
{"alldefconfig", no_argument, NULL, alldefconfig},
{"randconfig", no_argument, NULL, randconfig},
{"listnewconfig", no_argument, NULL, listnewconfig},
{"oldnoconfig", no_argument, NULL, oldnoconfig},
{NULL, 0, NULL, 0}
};
int main(int ac, char **av)
{
int opt;
const char *name;
struct stat tmpstat;
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
while ((opt = getopt_long(ac, av, "", long_opts, NULL)) != -1) {
input_mode = (enum input_mode)opt;
switch (opt) {
case silentoldconfig:
sync_kconfig = 1;
break;
case defconfig:
case savedefconfig:
defconfig_file = optarg;
break;
case randconfig:
{
struct timeval now;
unsigned int seed;
/*
* Use microseconds derived seed,
* compensate for systems where it may be zero
*/
gettimeofday(&now, NULL);
seed = (unsigned int)((now.tv_sec + 1) * (now.tv_usec + 1));
srand(seed);
break;
}
case '?':
fprintf(stderr, _("See README for usage info\n"));
exit(1);
break;
}
}
if (ac == optind) {
printf(_("%s: Kconfig file missing\n"), av[0]);
exit(1);
}
name = av[optind];
conf_parse(name);
//zconfdump(stdout);
if (sync_kconfig) {
name = conf_get_configname();
if (stat(name, &tmpstat)) {
fprintf(stderr, _("***\n"
"*** Configuration file \"%s\" not found!\n"
"***\n"
"*** Please run some configurator (e.g. \"make oldconfig\" or\n"
"*** \"make menuconfig\" or \"make xconfig\").\n"
"***\n"), name);
exit(1);
}
}
switch (input_mode) {
case defconfig:
if (!defconfig_file)
defconfig_file = conf_get_default_confname();
if (conf_read(defconfig_file)) {
printf(_("***\n"
"*** Can't find default configuration \"%s\"!\n"
"***\n"), defconfig_file);
exit(1);
}
break;
case savedefconfig:
case silentoldconfig:
case oldaskconfig:
case oldconfig:
case listnewconfig:
case oldnoconfig:
conf_read(NULL);
break;
case allnoconfig:
case allyesconfig:
case allmodconfig:
case alldefconfig:
case randconfig:
name = getenv("KCONFIG_ALLCONFIG");
if (name && !stat(name, &tmpstat)) {
conf_read_simple(name, S_DEF_USER);
break;
}
switch (input_mode) {
case allnoconfig: name = "allno.config"; break;
case allyesconfig: name = "allyes.config"; break;
case allmodconfig: name = "allmod.config"; break;
case alldefconfig: name = "alldef.config"; break;
case randconfig: name = "allrandom.config"; break;
default: break;
}
if (!stat(name, &tmpstat))
conf_read_simple(name, S_DEF_USER);
else if (!stat("all.config", &tmpstat))
conf_read_simple("all.config", S_DEF_USER);
break;
default:
break;
}
if (sync_kconfig) {
if (conf_get_changed()) {
name = getenv("KCONFIG_NOSILENTUPDATE");
if (name && *name) {
fprintf(stderr,
_("\n*** The configuration requires explicit update.\n\n"));
return 1;
}
}
valid_stdin = isatty(0) && isatty(1) && isatty(2);
}
switch (input_mode) {
case allnoconfig:
conf_set_all_new_symbols(def_no);
break;
case allyesconfig:
conf_set_all_new_symbols(def_yes);
break;
case allmodconfig:
conf_set_all_new_symbols(def_mod);
break;
case alldefconfig:
conf_set_all_new_symbols(def_default);
break;
case randconfig:
conf_set_all_new_symbols(def_random);
break;
case defconfig:
conf_set_all_new_symbols(def_default);
break;
case savedefconfig:
break;
case oldaskconfig:
rootEntry = &rootmenu;
conf(&rootmenu);
input_mode = silentoldconfig;
/* fall through */
case oldconfig:
case listnewconfig:
case oldnoconfig:
case silentoldconfig:
/* Update until a loop caused no more changes */
do {
conf_cnt = 0;
check_conf(&rootmenu);
} while (conf_cnt &&
(input_mode != listnewconfig &&
input_mode != oldnoconfig));
break;
}
if (sync_kconfig) {
/* silentoldconfig is used during the build so we shall update autoconf.
* All other commands are only used to generate a config.
*/
if (conf_get_changed() && conf_write(NULL)) {
fprintf(stderr, _("\n*** Error during writing of the configuration.\n\n"));
exit(1);
}
if (conf_write_autoconf()) {
fprintf(stderr, _("\n*** Error during update of the configuration.\n\n"));
return 1;
}
} else if (input_mode == savedefconfig) {
if (conf_write_defconfig(defconfig_file)) {
fprintf(stderr, _("n*** Error while saving defconfig to: %s\n\n"),
defconfig_file);
return 1;
}
} else if (input_mode != listnewconfig) {
if (conf_write(NULL)) {
fprintf(stderr, _("\n*** Error during writing of the configuration.\n\n"));
exit(1);
}
}
return 0;
}
/*
* Helper function to facilitate fgets() by Jean Sacren.
*/
void xfgets(str, size, in)
char *str;
int size;
FILE *in;
{
if (fgets(str, size, in) == NULL)
fprintf(stderr, "\nError in reading or end of file.\n");
}
| gpl-2.0 |
jgcaaprom/f2fs | 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 |
paul-chambers/netgear-r7800 | git_home/linux.git/sourcecode/arch/powerpc/platforms/83xx/mpc837x_rdb.c | 4637 | 2124 | /*
* arch/powerpc/platforms/83xx/mpc837x_rdb.c
*
* Copyright (C) 2007 Freescale Semicondutor, Inc. All rights reserved.
*
* MPC837x RDB board specific routines
*
* 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/pci.h>
#include <linux/of_platform.h>
#include <asm/time.h>
#include <asm/ipic.h>
#include <asm/udbg.h>
#include <sysdev/fsl_soc.h>
#include <sysdev/fsl_pci.h>
#include "mpc83xx.h"
static void mpc837x_rdb_sd_cfg(void)
{
void __iomem *im;
im = ioremap(get_immrbase(), 0x1000);
if (!im) {
WARN_ON(1);
return;
}
/*
* On RDB boards (in contrast to MDS) USBB pins are used for SD only,
* so we can safely mux them away from the USB block.
*/
clrsetbits_be32(im + MPC83XX_SICRL_OFFS, MPC837X_SICRL_USBB_MASK,
MPC837X_SICRL_SD);
clrsetbits_be32(im + MPC83XX_SICRH_OFFS, MPC837X_SICRH_SPI_MASK,
MPC837X_SICRH_SD);
iounmap(im);
}
/* ************************************************************************
*
* Setup the architecture
*
*/
static void __init mpc837x_rdb_setup_arch(void)
{
if (ppc_md.progress)
ppc_md.progress("mpc837x_rdb_setup_arch()", 0);
mpc83xx_setup_pci();
mpc837x_usb_cfg();
mpc837x_rdb_sd_cfg();
}
machine_device_initcall(mpc837x_rdb, mpc83xx_declare_of_platform_devices);
static const char *board[] __initdata = {
"fsl,mpc8377rdb",
"fsl,mpc8378rdb",
"fsl,mpc8379rdb",
"fsl,mpc8377wlan",
NULL
};
/*
* Called very early, MMU is off, device-tree isn't unflattened
*/
static int __init mpc837x_rdb_probe(void)
{
return of_flat_dt_match(of_get_flat_dt_root(), board);
}
define_machine(mpc837x_rdb) {
.name = "MPC837x RDB/WLAN",
.probe = mpc837x_rdb_probe,
.setup_arch = mpc837x_rdb_setup_arch,
.init_IRQ = mpc83xx_ipic_init_IRQ,
.get_irq = ipic_get_irq,
.restart = mpc83xx_restart,
.time_init = mpc83xx_time_init,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
};
| gpl-2.0 |
XirXes/android_kernel_htc_pyramid | sound/drivers/opl4/opl4_synth.c | 10013 | 23398 | /*
* OPL4 MIDI synthesizer functions
*
* Copyright (c) 2003 by Clemens Ladisch <clemens@ladisch.de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Alternatively, this software may be distributed and/or modified under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "opl4_local.h"
#include <linux/delay.h>
#include <asm/io.h>
#include <sound/asoundef.h>
/* GM2 controllers */
#ifndef MIDI_CTL_RELEASE_TIME
#define MIDI_CTL_RELEASE_TIME 0x48
#define MIDI_CTL_ATTACK_TIME 0x49
#define MIDI_CTL_DECAY_TIME 0x4b
#define MIDI_CTL_VIBRATO_RATE 0x4c
#define MIDI_CTL_VIBRATO_DEPTH 0x4d
#define MIDI_CTL_VIBRATO_DELAY 0x4e
#endif
/*
* This table maps 100/128 cents to F_NUMBER.
*/
static const s16 snd_opl4_pitch_map[0x600] = {
0x000,0x000,0x001,0x001,0x002,0x002,0x003,0x003,
0x004,0x004,0x005,0x005,0x006,0x006,0x006,0x007,
0x007,0x008,0x008,0x009,0x009,0x00a,0x00a,0x00b,
0x00b,0x00c,0x00c,0x00d,0x00d,0x00d,0x00e,0x00e,
0x00f,0x00f,0x010,0x010,0x011,0x011,0x012,0x012,
0x013,0x013,0x014,0x014,0x015,0x015,0x015,0x016,
0x016,0x017,0x017,0x018,0x018,0x019,0x019,0x01a,
0x01a,0x01b,0x01b,0x01c,0x01c,0x01d,0x01d,0x01e,
0x01e,0x01e,0x01f,0x01f,0x020,0x020,0x021,0x021,
0x022,0x022,0x023,0x023,0x024,0x024,0x025,0x025,
0x026,0x026,0x027,0x027,0x028,0x028,0x029,0x029,
0x029,0x02a,0x02a,0x02b,0x02b,0x02c,0x02c,0x02d,
0x02d,0x02e,0x02e,0x02f,0x02f,0x030,0x030,0x031,
0x031,0x032,0x032,0x033,0x033,0x034,0x034,0x035,
0x035,0x036,0x036,0x037,0x037,0x038,0x038,0x038,
0x039,0x039,0x03a,0x03a,0x03b,0x03b,0x03c,0x03c,
0x03d,0x03d,0x03e,0x03e,0x03f,0x03f,0x040,0x040,
0x041,0x041,0x042,0x042,0x043,0x043,0x044,0x044,
0x045,0x045,0x046,0x046,0x047,0x047,0x048,0x048,
0x049,0x049,0x04a,0x04a,0x04b,0x04b,0x04c,0x04c,
0x04d,0x04d,0x04e,0x04e,0x04f,0x04f,0x050,0x050,
0x051,0x051,0x052,0x052,0x053,0x053,0x054,0x054,
0x055,0x055,0x056,0x056,0x057,0x057,0x058,0x058,
0x059,0x059,0x05a,0x05a,0x05b,0x05b,0x05c,0x05c,
0x05d,0x05d,0x05e,0x05e,0x05f,0x05f,0x060,0x060,
0x061,0x061,0x062,0x062,0x063,0x063,0x064,0x064,
0x065,0x065,0x066,0x066,0x067,0x067,0x068,0x068,
0x069,0x069,0x06a,0x06a,0x06b,0x06b,0x06c,0x06c,
0x06d,0x06d,0x06e,0x06e,0x06f,0x06f,0x070,0x071,
0x071,0x072,0x072,0x073,0x073,0x074,0x074,0x075,
0x075,0x076,0x076,0x077,0x077,0x078,0x078,0x079,
0x079,0x07a,0x07a,0x07b,0x07b,0x07c,0x07c,0x07d,
0x07d,0x07e,0x07e,0x07f,0x07f,0x080,0x081,0x081,
0x082,0x082,0x083,0x083,0x084,0x084,0x085,0x085,
0x086,0x086,0x087,0x087,0x088,0x088,0x089,0x089,
0x08a,0x08a,0x08b,0x08b,0x08c,0x08d,0x08d,0x08e,
0x08e,0x08f,0x08f,0x090,0x090,0x091,0x091,0x092,
0x092,0x093,0x093,0x094,0x094,0x095,0x096,0x096,
0x097,0x097,0x098,0x098,0x099,0x099,0x09a,0x09a,
0x09b,0x09b,0x09c,0x09c,0x09d,0x09d,0x09e,0x09f,
0x09f,0x0a0,0x0a0,0x0a1,0x0a1,0x0a2,0x0a2,0x0a3,
0x0a3,0x0a4,0x0a4,0x0a5,0x0a6,0x0a6,0x0a7,0x0a7,
0x0a8,0x0a8,0x0a9,0x0a9,0x0aa,0x0aa,0x0ab,0x0ab,
0x0ac,0x0ad,0x0ad,0x0ae,0x0ae,0x0af,0x0af,0x0b0,
0x0b0,0x0b1,0x0b1,0x0b2,0x0b2,0x0b3,0x0b4,0x0b4,
0x0b5,0x0b5,0x0b6,0x0b6,0x0b7,0x0b7,0x0b8,0x0b8,
0x0b9,0x0ba,0x0ba,0x0bb,0x0bb,0x0bc,0x0bc,0x0bd,
0x0bd,0x0be,0x0be,0x0bf,0x0c0,0x0c0,0x0c1,0x0c1,
0x0c2,0x0c2,0x0c3,0x0c3,0x0c4,0x0c4,0x0c5,0x0c6,
0x0c6,0x0c7,0x0c7,0x0c8,0x0c8,0x0c9,0x0c9,0x0ca,
0x0cb,0x0cb,0x0cc,0x0cc,0x0cd,0x0cd,0x0ce,0x0ce,
0x0cf,0x0d0,0x0d0,0x0d1,0x0d1,0x0d2,0x0d2,0x0d3,
0x0d3,0x0d4,0x0d5,0x0d5,0x0d6,0x0d6,0x0d7,0x0d7,
0x0d8,0x0d8,0x0d9,0x0da,0x0da,0x0db,0x0db,0x0dc,
0x0dc,0x0dd,0x0de,0x0de,0x0df,0x0df,0x0e0,0x0e0,
0x0e1,0x0e1,0x0e2,0x0e3,0x0e3,0x0e4,0x0e4,0x0e5,
0x0e5,0x0e6,0x0e7,0x0e7,0x0e8,0x0e8,0x0e9,0x0e9,
0x0ea,0x0eb,0x0eb,0x0ec,0x0ec,0x0ed,0x0ed,0x0ee,
0x0ef,0x0ef,0x0f0,0x0f0,0x0f1,0x0f1,0x0f2,0x0f3,
0x0f3,0x0f4,0x0f4,0x0f5,0x0f5,0x0f6,0x0f7,0x0f7,
0x0f8,0x0f8,0x0f9,0x0f9,0x0fa,0x0fb,0x0fb,0x0fc,
0x0fc,0x0fd,0x0fd,0x0fe,0x0ff,0x0ff,0x100,0x100,
0x101,0x101,0x102,0x103,0x103,0x104,0x104,0x105,
0x106,0x106,0x107,0x107,0x108,0x108,0x109,0x10a,
0x10a,0x10b,0x10b,0x10c,0x10c,0x10d,0x10e,0x10e,
0x10f,0x10f,0x110,0x111,0x111,0x112,0x112,0x113,
0x114,0x114,0x115,0x115,0x116,0x116,0x117,0x118,
0x118,0x119,0x119,0x11a,0x11b,0x11b,0x11c,0x11c,
0x11d,0x11e,0x11e,0x11f,0x11f,0x120,0x120,0x121,
0x122,0x122,0x123,0x123,0x124,0x125,0x125,0x126,
0x126,0x127,0x128,0x128,0x129,0x129,0x12a,0x12b,
0x12b,0x12c,0x12c,0x12d,0x12e,0x12e,0x12f,0x12f,
0x130,0x131,0x131,0x132,0x132,0x133,0x134,0x134,
0x135,0x135,0x136,0x137,0x137,0x138,0x138,0x139,
0x13a,0x13a,0x13b,0x13b,0x13c,0x13d,0x13d,0x13e,
0x13e,0x13f,0x140,0x140,0x141,0x141,0x142,0x143,
0x143,0x144,0x144,0x145,0x146,0x146,0x147,0x148,
0x148,0x149,0x149,0x14a,0x14b,0x14b,0x14c,0x14c,
0x14d,0x14e,0x14e,0x14f,0x14f,0x150,0x151,0x151,
0x152,0x153,0x153,0x154,0x154,0x155,0x156,0x156,
0x157,0x157,0x158,0x159,0x159,0x15a,0x15b,0x15b,
0x15c,0x15c,0x15d,0x15e,0x15e,0x15f,0x160,0x160,
0x161,0x161,0x162,0x163,0x163,0x164,0x165,0x165,
0x166,0x166,0x167,0x168,0x168,0x169,0x16a,0x16a,
0x16b,0x16b,0x16c,0x16d,0x16d,0x16e,0x16f,0x16f,
0x170,0x170,0x171,0x172,0x172,0x173,0x174,0x174,
0x175,0x175,0x176,0x177,0x177,0x178,0x179,0x179,
0x17a,0x17a,0x17b,0x17c,0x17c,0x17d,0x17e,0x17e,
0x17f,0x180,0x180,0x181,0x181,0x182,0x183,0x183,
0x184,0x185,0x185,0x186,0x187,0x187,0x188,0x188,
0x189,0x18a,0x18a,0x18b,0x18c,0x18c,0x18d,0x18e,
0x18e,0x18f,0x190,0x190,0x191,0x191,0x192,0x193,
0x193,0x194,0x195,0x195,0x196,0x197,0x197,0x198,
0x199,0x199,0x19a,0x19a,0x19b,0x19c,0x19c,0x19d,
0x19e,0x19e,0x19f,0x1a0,0x1a0,0x1a1,0x1a2,0x1a2,
0x1a3,0x1a4,0x1a4,0x1a5,0x1a6,0x1a6,0x1a7,0x1a8,
0x1a8,0x1a9,0x1a9,0x1aa,0x1ab,0x1ab,0x1ac,0x1ad,
0x1ad,0x1ae,0x1af,0x1af,0x1b0,0x1b1,0x1b1,0x1b2,
0x1b3,0x1b3,0x1b4,0x1b5,0x1b5,0x1b6,0x1b7,0x1b7,
0x1b8,0x1b9,0x1b9,0x1ba,0x1bb,0x1bb,0x1bc,0x1bd,
0x1bd,0x1be,0x1bf,0x1bf,0x1c0,0x1c1,0x1c1,0x1c2,
0x1c3,0x1c3,0x1c4,0x1c5,0x1c5,0x1c6,0x1c7,0x1c7,
0x1c8,0x1c9,0x1c9,0x1ca,0x1cb,0x1cb,0x1cc,0x1cd,
0x1cd,0x1ce,0x1cf,0x1cf,0x1d0,0x1d1,0x1d1,0x1d2,
0x1d3,0x1d3,0x1d4,0x1d5,0x1d5,0x1d6,0x1d7,0x1d7,
0x1d8,0x1d9,0x1d9,0x1da,0x1db,0x1db,0x1dc,0x1dd,
0x1dd,0x1de,0x1df,0x1df,0x1e0,0x1e1,0x1e1,0x1e2,
0x1e3,0x1e4,0x1e4,0x1e5,0x1e6,0x1e6,0x1e7,0x1e8,
0x1e8,0x1e9,0x1ea,0x1ea,0x1eb,0x1ec,0x1ec,0x1ed,
0x1ee,0x1ee,0x1ef,0x1f0,0x1f0,0x1f1,0x1f2,0x1f3,
0x1f3,0x1f4,0x1f5,0x1f5,0x1f6,0x1f7,0x1f7,0x1f8,
0x1f9,0x1f9,0x1fa,0x1fb,0x1fb,0x1fc,0x1fd,0x1fe,
0x1fe,0x1ff,0x200,0x200,0x201,0x202,0x202,0x203,
0x204,0x205,0x205,0x206,0x207,0x207,0x208,0x209,
0x209,0x20a,0x20b,0x20b,0x20c,0x20d,0x20e,0x20e,
0x20f,0x210,0x210,0x211,0x212,0x212,0x213,0x214,
0x215,0x215,0x216,0x217,0x217,0x218,0x219,0x21a,
0x21a,0x21b,0x21c,0x21c,0x21d,0x21e,0x21e,0x21f,
0x220,0x221,0x221,0x222,0x223,0x223,0x224,0x225,
0x226,0x226,0x227,0x228,0x228,0x229,0x22a,0x22b,
0x22b,0x22c,0x22d,0x22d,0x22e,0x22f,0x230,0x230,
0x231,0x232,0x232,0x233,0x234,0x235,0x235,0x236,
0x237,0x237,0x238,0x239,0x23a,0x23a,0x23b,0x23c,
0x23c,0x23d,0x23e,0x23f,0x23f,0x240,0x241,0x241,
0x242,0x243,0x244,0x244,0x245,0x246,0x247,0x247,
0x248,0x249,0x249,0x24a,0x24b,0x24c,0x24c,0x24d,
0x24e,0x24f,0x24f,0x250,0x251,0x251,0x252,0x253,
0x254,0x254,0x255,0x256,0x257,0x257,0x258,0x259,
0x259,0x25a,0x25b,0x25c,0x25c,0x25d,0x25e,0x25f,
0x25f,0x260,0x261,0x262,0x262,0x263,0x264,0x265,
0x265,0x266,0x267,0x267,0x268,0x269,0x26a,0x26a,
0x26b,0x26c,0x26d,0x26d,0x26e,0x26f,0x270,0x270,
0x271,0x272,0x273,0x273,0x274,0x275,0x276,0x276,
0x277,0x278,0x279,0x279,0x27a,0x27b,0x27c,0x27c,
0x27d,0x27e,0x27f,0x27f,0x280,0x281,0x282,0x282,
0x283,0x284,0x285,0x285,0x286,0x287,0x288,0x288,
0x289,0x28a,0x28b,0x28b,0x28c,0x28d,0x28e,0x28e,
0x28f,0x290,0x291,0x291,0x292,0x293,0x294,0x294,
0x295,0x296,0x297,0x298,0x298,0x299,0x29a,0x29b,
0x29b,0x29c,0x29d,0x29e,0x29e,0x29f,0x2a0,0x2a1,
0x2a1,0x2a2,0x2a3,0x2a4,0x2a5,0x2a5,0x2a6,0x2a7,
0x2a8,0x2a8,0x2a9,0x2aa,0x2ab,0x2ab,0x2ac,0x2ad,
0x2ae,0x2af,0x2af,0x2b0,0x2b1,0x2b2,0x2b2,0x2b3,
0x2b4,0x2b5,0x2b5,0x2b6,0x2b7,0x2b8,0x2b9,0x2b9,
0x2ba,0x2bb,0x2bc,0x2bc,0x2bd,0x2be,0x2bf,0x2c0,
0x2c0,0x2c1,0x2c2,0x2c3,0x2c4,0x2c4,0x2c5,0x2c6,
0x2c7,0x2c7,0x2c8,0x2c9,0x2ca,0x2cb,0x2cb,0x2cc,
0x2cd,0x2ce,0x2ce,0x2cf,0x2d0,0x2d1,0x2d2,0x2d2,
0x2d3,0x2d4,0x2d5,0x2d6,0x2d6,0x2d7,0x2d8,0x2d9,
0x2da,0x2da,0x2db,0x2dc,0x2dd,0x2dd,0x2de,0x2df,
0x2e0,0x2e1,0x2e1,0x2e2,0x2e3,0x2e4,0x2e5,0x2e5,
0x2e6,0x2e7,0x2e8,0x2e9,0x2e9,0x2ea,0x2eb,0x2ec,
0x2ed,0x2ed,0x2ee,0x2ef,0x2f0,0x2f1,0x2f1,0x2f2,
0x2f3,0x2f4,0x2f5,0x2f5,0x2f6,0x2f7,0x2f8,0x2f9,
0x2f9,0x2fa,0x2fb,0x2fc,0x2fd,0x2fd,0x2fe,0x2ff,
0x300,0x301,0x302,0x302,0x303,0x304,0x305,0x306,
0x306,0x307,0x308,0x309,0x30a,0x30a,0x30b,0x30c,
0x30d,0x30e,0x30f,0x30f,0x310,0x311,0x312,0x313,
0x313,0x314,0x315,0x316,0x317,0x318,0x318,0x319,
0x31a,0x31b,0x31c,0x31c,0x31d,0x31e,0x31f,0x320,
0x321,0x321,0x322,0x323,0x324,0x325,0x326,0x326,
0x327,0x328,0x329,0x32a,0x32a,0x32b,0x32c,0x32d,
0x32e,0x32f,0x32f,0x330,0x331,0x332,0x333,0x334,
0x334,0x335,0x336,0x337,0x338,0x339,0x339,0x33a,
0x33b,0x33c,0x33d,0x33e,0x33e,0x33f,0x340,0x341,
0x342,0x343,0x343,0x344,0x345,0x346,0x347,0x348,
0x349,0x349,0x34a,0x34b,0x34c,0x34d,0x34e,0x34e,
0x34f,0x350,0x351,0x352,0x353,0x353,0x354,0x355,
0x356,0x357,0x358,0x359,0x359,0x35a,0x35b,0x35c,
0x35d,0x35e,0x35f,0x35f,0x360,0x361,0x362,0x363,
0x364,0x364,0x365,0x366,0x367,0x368,0x369,0x36a,
0x36a,0x36b,0x36c,0x36d,0x36e,0x36f,0x370,0x370,
0x371,0x372,0x373,0x374,0x375,0x376,0x377,0x377,
0x378,0x379,0x37a,0x37b,0x37c,0x37d,0x37d,0x37e,
0x37f,0x380,0x381,0x382,0x383,0x383,0x384,0x385,
0x386,0x387,0x388,0x389,0x38a,0x38a,0x38b,0x38c,
0x38d,0x38e,0x38f,0x390,0x391,0x391,0x392,0x393,
0x394,0x395,0x396,0x397,0x398,0x398,0x399,0x39a,
0x39b,0x39c,0x39d,0x39e,0x39f,0x39f,0x3a0,0x3a1,
0x3a2,0x3a3,0x3a4,0x3a5,0x3a6,0x3a7,0x3a7,0x3a8,
0x3a9,0x3aa,0x3ab,0x3ac,0x3ad,0x3ae,0x3ae,0x3af,
0x3b0,0x3b1,0x3b2,0x3b3,0x3b4,0x3b5,0x3b6,0x3b6,
0x3b7,0x3b8,0x3b9,0x3ba,0x3bb,0x3bc,0x3bd,0x3be,
0x3bf,0x3bf,0x3c0,0x3c1,0x3c2,0x3c3,0x3c4,0x3c5,
0x3c6,0x3c7,0x3c7,0x3c8,0x3c9,0x3ca,0x3cb,0x3cc,
0x3cd,0x3ce,0x3cf,0x3d0,0x3d1,0x3d1,0x3d2,0x3d3,
0x3d4,0x3d5,0x3d6,0x3d7,0x3d8,0x3d9,0x3da,0x3da,
0x3db,0x3dc,0x3dd,0x3de,0x3df,0x3e0,0x3e1,0x3e2,
0x3e3,0x3e4,0x3e4,0x3e5,0x3e6,0x3e7,0x3e8,0x3e9,
0x3ea,0x3eb,0x3ec,0x3ed,0x3ee,0x3ef,0x3ef,0x3f0,
0x3f1,0x3f2,0x3f3,0x3f4,0x3f5,0x3f6,0x3f7,0x3f8,
0x3f9,0x3fa,0x3fa,0x3fb,0x3fc,0x3fd,0x3fe,0x3ff
};
/*
* Attenuation according to GM recommendations, in -0.375 dB units.
* table[v] = 40 * log(v / 127) / -0.375
*/
static unsigned char snd_opl4_volume_table[128] = {
255,224,192,173,160,150,141,134,
128,122,117,113,109,105,102, 99,
96, 93, 90, 88, 85, 83, 81, 79,
77, 75, 73, 71, 70, 68, 67, 65,
64, 62, 61, 59, 58, 57, 56, 54,
53, 52, 51, 50, 49, 48, 47, 46,
45, 44, 43, 42, 41, 40, 39, 39,
38, 37, 36, 35, 34, 34, 33, 32,
31, 31, 30, 29, 29, 28, 27, 27,
26, 25, 25, 24, 24, 23, 22, 22,
21, 21, 20, 19, 19, 18, 18, 17,
17, 16, 16, 15, 15, 14, 14, 13,
13, 12, 12, 11, 11, 10, 10, 9,
9, 9, 8, 8, 7, 7, 6, 6,
6, 5, 5, 4, 4, 4, 3, 3,
2, 2, 2, 1, 1, 0, 0, 0
};
/*
* Initializes all voices.
*/
void snd_opl4_synth_reset(struct snd_opl4 *opl4)
{
unsigned long flags;
int i;
spin_lock_irqsave(&opl4->reg_lock, flags);
for (i = 0; i < OPL4_MAX_VOICES; i++)
snd_opl4_write(opl4, OPL4_REG_MISC + i, OPL4_DAMP_BIT);
spin_unlock_irqrestore(&opl4->reg_lock, flags);
INIT_LIST_HEAD(&opl4->off_voices);
INIT_LIST_HEAD(&opl4->on_voices);
memset(opl4->voices, 0, sizeof(opl4->voices));
for (i = 0; i < OPL4_MAX_VOICES; i++) {
opl4->voices[i].number = i;
list_add_tail(&opl4->voices[i].list, &opl4->off_voices);
}
snd_midi_channel_set_clear(opl4->chset);
}
/*
* Shuts down all voices.
*/
void snd_opl4_synth_shutdown(struct snd_opl4 *opl4)
{
unsigned long flags;
int i;
spin_lock_irqsave(&opl4->reg_lock, flags);
for (i = 0; i < OPL4_MAX_VOICES; i++)
snd_opl4_write(opl4, OPL4_REG_MISC + i,
opl4->voices[i].reg_misc & ~OPL4_KEY_ON_BIT);
spin_unlock_irqrestore(&opl4->reg_lock, flags);
}
/*
* Executes the callback for all voices playing the specified note.
*/
static void snd_opl4_do_for_note(struct snd_opl4 *opl4, int note, struct snd_midi_channel *chan,
void (*func)(struct snd_opl4 *opl4, struct opl4_voice *voice))
{
int i;
unsigned long flags;
struct opl4_voice *voice;
spin_lock_irqsave(&opl4->reg_lock, flags);
for (i = 0; i < OPL4_MAX_VOICES; i++) {
voice = &opl4->voices[i];
if (voice->chan == chan && voice->note == note) {
func(opl4, voice);
}
}
spin_unlock_irqrestore(&opl4->reg_lock, flags);
}
/*
* Executes the callback for all voices of to the specified channel.
*/
static void snd_opl4_do_for_channel(struct snd_opl4 *opl4,
struct snd_midi_channel *chan,
void (*func)(struct snd_opl4 *opl4, struct opl4_voice *voice))
{
int i;
unsigned long flags;
struct opl4_voice *voice;
spin_lock_irqsave(&opl4->reg_lock, flags);
for (i = 0; i < OPL4_MAX_VOICES; i++) {
voice = &opl4->voices[i];
if (voice->chan == chan) {
func(opl4, voice);
}
}
spin_unlock_irqrestore(&opl4->reg_lock, flags);
}
/*
* Executes the callback for all active voices.
*/
static void snd_opl4_do_for_all(struct snd_opl4 *opl4,
void (*func)(struct snd_opl4 *opl4, struct opl4_voice *voice))
{
int i;
unsigned long flags;
struct opl4_voice *voice;
spin_lock_irqsave(&opl4->reg_lock, flags);
for (i = 0; i < OPL4_MAX_VOICES; i++) {
voice = &opl4->voices[i];
if (voice->chan)
func(opl4, voice);
}
spin_unlock_irqrestore(&opl4->reg_lock, flags);
}
static void snd_opl4_update_volume(struct snd_opl4 *opl4, struct opl4_voice *voice)
{
int att;
att = voice->sound->tone_attenuate;
att += snd_opl4_volume_table[opl4->chset->gs_master_volume & 0x7f];
att += snd_opl4_volume_table[voice->chan->gm_volume & 0x7f];
att += snd_opl4_volume_table[voice->chan->gm_expression & 0x7f];
att += snd_opl4_volume_table[voice->velocity];
att = 0x7f - (0x7f - att) * (voice->sound->volume_factor) / 0xfe - volume_boost;
if (att < 0)
att = 0;
else if (att > 0x7e)
att = 0x7e;
snd_opl4_write(opl4, OPL4_REG_LEVEL + voice->number,
(att << 1) | voice->level_direct);
voice->level_direct = 0;
}
static void snd_opl4_update_pan(struct snd_opl4 *opl4, struct opl4_voice *voice)
{
int pan = voice->sound->panpot;
if (!voice->chan->drum_channel)
pan += (voice->chan->control[MIDI_CTL_MSB_PAN] - 0x40) >> 3;
if (pan < -7)
pan = -7;
else if (pan > 7)
pan = 7;
voice->reg_misc = (voice->reg_misc & ~OPL4_PAN_POT_MASK)
| (pan & OPL4_PAN_POT_MASK);
snd_opl4_write(opl4, OPL4_REG_MISC + voice->number, voice->reg_misc);
}
static void snd_opl4_update_vibrato_depth(struct snd_opl4 *opl4,
struct opl4_voice *voice)
{
int depth;
if (voice->chan->drum_channel)
return;
depth = (7 - voice->sound->vibrato)
* (voice->chan->control[MIDI_CTL_VIBRATO_DEPTH] & 0x7f);
depth = (depth >> 7) + voice->sound->vibrato;
voice->reg_lfo_vibrato &= ~OPL4_VIBRATO_DEPTH_MASK;
voice->reg_lfo_vibrato |= depth & OPL4_VIBRATO_DEPTH_MASK;
snd_opl4_write(opl4, OPL4_REG_LFO_VIBRATO + voice->number,
voice->reg_lfo_vibrato);
}
static void snd_opl4_update_pitch(struct snd_opl4 *opl4,
struct opl4_voice *voice)
{
struct snd_midi_channel *chan = voice->chan;
int note, pitch, octave;
note = chan->drum_channel ? 60 : voice->note;
/*
* pitch is in 100/128 cents, so 0x80 is one semitone and
* 0x600 is one octave.
*/
pitch = ((note - 60) << 7) * voice->sound->key_scaling / 100 + (60 << 7);
pitch += voice->sound->pitch_offset;
if (!chan->drum_channel)
pitch += chan->gm_rpn_coarse_tuning;
pitch += chan->gm_rpn_fine_tuning >> 7;
pitch += chan->midi_pitchbend * chan->gm_rpn_pitch_bend_range / 0x2000;
if (pitch < 0)
pitch = 0;
else if (pitch >= 0x6000)
pitch = 0x5fff;
octave = pitch / 0x600 - 8;
pitch = snd_opl4_pitch_map[pitch % 0x600];
snd_opl4_write(opl4, OPL4_REG_OCTAVE + voice->number,
(octave << 4) | ((pitch >> 7) & OPL4_F_NUMBER_HIGH_MASK));
voice->reg_f_number = (voice->reg_f_number & OPL4_TONE_NUMBER_BIT8)
| ((pitch << 1) & OPL4_F_NUMBER_LOW_MASK);
snd_opl4_write(opl4, OPL4_REG_F_NUMBER + voice->number, voice->reg_f_number);
}
static void snd_opl4_update_tone_parameters(struct snd_opl4 *opl4,
struct opl4_voice *voice)
{
snd_opl4_write(opl4, OPL4_REG_ATTACK_DECAY1 + voice->number,
voice->sound->reg_attack_decay1);
snd_opl4_write(opl4, OPL4_REG_LEVEL_DECAY2 + voice->number,
voice->sound->reg_level_decay2);
snd_opl4_write(opl4, OPL4_REG_RELEASE_CORRECTION + voice->number,
voice->sound->reg_release_correction);
snd_opl4_write(opl4, OPL4_REG_TREMOLO + voice->number,
voice->sound->reg_tremolo);
}
/* allocate one voice */
static struct opl4_voice *snd_opl4_get_voice(struct snd_opl4 *opl4)
{
/* first, try to get the oldest key-off voice */
if (!list_empty(&opl4->off_voices))
return list_entry(opl4->off_voices.next, struct opl4_voice, list);
/* then get the oldest key-on voice */
snd_BUG_ON(list_empty(&opl4->on_voices));
return list_entry(opl4->on_voices.next, struct opl4_voice, list);
}
static void snd_opl4_wait_for_wave_headers(struct snd_opl4 *opl4)
{
int timeout = 200;
while ((inb(opl4->fm_port) & OPL4_STATUS_LOAD) && --timeout > 0)
udelay(10);
}
void snd_opl4_note_on(void *private_data, int note, int vel, struct snd_midi_channel *chan)
{
struct snd_opl4 *opl4 = private_data;
const struct opl4_region_ptr *regions;
struct opl4_voice *voice[2];
const struct opl4_sound *sound[2];
int voices = 0, i;
unsigned long flags;
/* determine the number of voices and voice parameters */
i = chan->drum_channel ? 0x80 : (chan->midi_program & 0x7f);
regions = &snd_yrw801_regions[i];
for (i = 0; i < regions->count; i++) {
if (note >= regions->regions[i].key_min &&
note <= regions->regions[i].key_max) {
sound[voices] = ®ions->regions[i].sound;
if (++voices >= 2)
break;
}
}
/* allocate and initialize the needed voices */
spin_lock_irqsave(&opl4->reg_lock, flags);
for (i = 0; i < voices; i++) {
voice[i] = snd_opl4_get_voice(opl4);
list_del(&voice[i]->list);
list_add_tail(&voice[i]->list, &opl4->on_voices);
voice[i]->chan = chan;
voice[i]->note = note;
voice[i]->velocity = vel & 0x7f;
voice[i]->sound = sound[i];
}
/* set tone number (triggers header loading) */
for (i = 0; i < voices; i++) {
voice[i]->reg_f_number =
(sound[i]->tone >> 8) & OPL4_TONE_NUMBER_BIT8;
snd_opl4_write(opl4, OPL4_REG_F_NUMBER + voice[i]->number,
voice[i]->reg_f_number);
snd_opl4_write(opl4, OPL4_REG_TONE_NUMBER + voice[i]->number,
sound[i]->tone & 0xff);
}
/* set parameters which can be set while loading */
for (i = 0; i < voices; i++) {
voice[i]->reg_misc = OPL4_LFO_RESET_BIT;
snd_opl4_update_pan(opl4, voice[i]);
snd_opl4_update_pitch(opl4, voice[i]);
voice[i]->level_direct = OPL4_LEVEL_DIRECT_BIT;
snd_opl4_update_volume(opl4, voice[i]);
}
spin_unlock_irqrestore(&opl4->reg_lock, flags);
/* wait for completion of loading */
snd_opl4_wait_for_wave_headers(opl4);
/* set remaining parameters */
spin_lock_irqsave(&opl4->reg_lock, flags);
for (i = 0; i < voices; i++) {
snd_opl4_update_tone_parameters(opl4, voice[i]);
voice[i]->reg_lfo_vibrato = voice[i]->sound->reg_lfo_vibrato;
snd_opl4_update_vibrato_depth(opl4, voice[i]);
}
/* finally, switch on all voices */
for (i = 0; i < voices; i++) {
voice[i]->reg_misc =
(voice[i]->reg_misc & 0x1f) | OPL4_KEY_ON_BIT;
snd_opl4_write(opl4, OPL4_REG_MISC + voice[i]->number,
voice[i]->reg_misc);
}
spin_unlock_irqrestore(&opl4->reg_lock, flags);
}
static void snd_opl4_voice_off(struct snd_opl4 *opl4, struct opl4_voice *voice)
{
list_del(&voice->list);
list_add_tail(&voice->list, &opl4->off_voices);
voice->reg_misc &= ~OPL4_KEY_ON_BIT;
snd_opl4_write(opl4, OPL4_REG_MISC + voice->number, voice->reg_misc);
}
void snd_opl4_note_off(void *private_data, int note, int vel, struct snd_midi_channel *chan)
{
struct snd_opl4 *opl4 = private_data;
snd_opl4_do_for_note(opl4, note, chan, snd_opl4_voice_off);
}
static void snd_opl4_terminate_voice(struct snd_opl4 *opl4, struct opl4_voice *voice)
{
list_del(&voice->list);
list_add_tail(&voice->list, &opl4->off_voices);
voice->reg_misc = (voice->reg_misc & ~OPL4_KEY_ON_BIT) | OPL4_DAMP_BIT;
snd_opl4_write(opl4, OPL4_REG_MISC + voice->number, voice->reg_misc);
}
void snd_opl4_terminate_note(void *private_data, int note, struct snd_midi_channel *chan)
{
struct snd_opl4 *opl4 = private_data;
snd_opl4_do_for_note(opl4, note, chan, snd_opl4_terminate_voice);
}
void snd_opl4_control(void *private_data, int type, struct snd_midi_channel *chan)
{
struct snd_opl4 *opl4 = private_data;
switch (type) {
case MIDI_CTL_MSB_MODWHEEL:
chan->control[MIDI_CTL_VIBRATO_DEPTH] = chan->control[MIDI_CTL_MSB_MODWHEEL];
snd_opl4_do_for_channel(opl4, chan, snd_opl4_update_vibrato_depth);
break;
case MIDI_CTL_MSB_MAIN_VOLUME:
snd_opl4_do_for_channel(opl4, chan, snd_opl4_update_volume);
break;
case MIDI_CTL_MSB_PAN:
snd_opl4_do_for_channel(opl4, chan, snd_opl4_update_pan);
break;
case MIDI_CTL_MSB_EXPRESSION:
snd_opl4_do_for_channel(opl4, chan, snd_opl4_update_volume);
break;
case MIDI_CTL_VIBRATO_RATE:
/* not yet supported */
break;
case MIDI_CTL_VIBRATO_DEPTH:
snd_opl4_do_for_channel(opl4, chan, snd_opl4_update_vibrato_depth);
break;
case MIDI_CTL_VIBRATO_DELAY:
/* not yet supported */
break;
case MIDI_CTL_E1_REVERB_DEPTH:
/*
* Each OPL4 voice has a bit called "Pseudo-Reverb", but
* IMHO _not_ using it enhances the listening experience.
*/
break;
case MIDI_CTL_PITCHBEND:
snd_opl4_do_for_channel(opl4, chan, snd_opl4_update_pitch);
break;
}
}
void snd_opl4_sysex(void *private_data, unsigned char *buf, int len,
int parsed, struct snd_midi_channel_set *chset)
{
struct snd_opl4 *opl4 = private_data;
if (parsed == SNDRV_MIDI_SYSEX_GS_MASTER_VOLUME)
snd_opl4_do_for_all(opl4, snd_opl4_update_volume);
}
| gpl-2.0 |
Team-Blackout/AOZP_Blackout_edition | drivers/video/aty/radeon_pm.c | 10525 | 89387 | /*
* drivers/video/aty/radeon_pm.c
*
* Copyright 2003,2004 Ben. Herrenschmidt <benh@kernel.crashing.org>
* Copyright 2004 Paul Mackerras <paulus@samba.org>
*
* This is the power management code for ATI radeon chipsets. It contains
* some dynamic clock PM enable/disable code similar to what X.org does,
* some D2-state (APM-style) sleep/wakeup code for use on some PowerMacs,
* and the necessary bits to re-initialize from scratch a few chips found
* on PowerMacs as well. The later could be extended to more platforms
* provided the memory controller configuration code be made more generic,
* and you can get the proper mode register commands for your RAMs.
* Those things may be found in the BIOS image...
*/
#include "radeonfb.h"
#include <linux/console.h>
#include <linux/agp_backend.h>
#ifdef CONFIG_PPC_PMAC
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/pmac_feature.h>
#endif
#include "ati_ids.h"
/*
* Workarounds for bugs in PC laptops:
* - enable D2 sleep in some IBM Thinkpads
* - special case for Samsung P35
*
* Whitelist by subsystem vendor/device because
* its the subsystem vendor's fault!
*/
#if defined(CONFIG_PM) && defined(CONFIG_X86)
static void radeon_reinitialize_M10(struct radeonfb_info *rinfo);
struct radeon_device_id {
const char *ident; /* (arbitrary) Name */
const unsigned short subsystem_vendor; /* Subsystem Vendor ID */
const unsigned short subsystem_device; /* Subsystem Device ID */
const enum radeon_pm_mode pm_mode_modifier; /* modify pm_mode */
const reinit_function_ptr new_reinit_func; /* changed reinit_func */
};
#define BUGFIX(model, sv, sd, pm, fn) { \
.ident = model, \
.subsystem_vendor = sv, \
.subsystem_device = sd, \
.pm_mode_modifier = pm, \
.new_reinit_func = fn \
}
static struct radeon_device_id radeon_workaround_list[] = {
BUGFIX("IBM Thinkpad R32",
PCI_VENDOR_ID_IBM, 0x1905,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad R40",
PCI_VENDOR_ID_IBM, 0x0526,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad R40",
PCI_VENDOR_ID_IBM, 0x0527,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad R50/R51/T40/T41",
PCI_VENDOR_ID_IBM, 0x0531,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad R51/T40/T41/T42",
PCI_VENDOR_ID_IBM, 0x0530,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad T30",
PCI_VENDOR_ID_IBM, 0x0517,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad T40p",
PCI_VENDOR_ID_IBM, 0x054d,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad T42",
PCI_VENDOR_ID_IBM, 0x0550,
radeon_pm_d2, NULL),
BUGFIX("IBM Thinkpad X31/X32",
PCI_VENDOR_ID_IBM, 0x052f,
radeon_pm_d2, NULL),
BUGFIX("Samsung P35",
PCI_VENDOR_ID_SAMSUNG, 0xc00c,
radeon_pm_off, radeon_reinitialize_M10),
BUGFIX("Acer Aspire 2010",
PCI_VENDOR_ID_AI, 0x0061,
radeon_pm_off, radeon_reinitialize_M10),
BUGFIX("Acer Travelmate 290D/292LMi",
PCI_VENDOR_ID_AI, 0x005a,
radeon_pm_off, radeon_reinitialize_M10),
{ .ident = NULL }
};
static int radeon_apply_workarounds(struct radeonfb_info *rinfo)
{
struct radeon_device_id *id;
for (id = radeon_workaround_list; id->ident != NULL; id++ )
if ((id->subsystem_vendor == rinfo->pdev->subsystem_vendor ) &&
(id->subsystem_device == rinfo->pdev->subsystem_device )) {
/* we found a device that requires workaround */
printk(KERN_DEBUG "radeonfb: %s detected"
", enabling workaround\n", id->ident);
rinfo->pm_mode |= id->pm_mode_modifier;
if (id->new_reinit_func != NULL)
rinfo->reinit_func = id->new_reinit_func;
return 1;
}
return 0; /* not found */
}
#else /* defined(CONFIG_PM) && defined(CONFIG_X86) */
static inline int radeon_apply_workarounds(struct radeonfb_info *rinfo)
{
return 0;
}
#endif /* defined(CONFIG_PM) && defined(CONFIG_X86) */
static void radeon_pm_disable_dynamic_mode(struct radeonfb_info *rinfo)
{
u32 tmp;
/* RV100 */
if ((rinfo->family == CHIP_FAMILY_RV100) && (!rinfo->is_mobility)) {
if (rinfo->has_CRTC2) {
tmp = INPLL(pllSCLK_CNTL);
tmp &= ~SCLK_CNTL__DYN_STOP_LAT_MASK;
tmp |= SCLK_CNTL__CP_MAX_DYN_STOP_LAT | SCLK_CNTL__FORCEON_MASK;
OUTPLL(pllSCLK_CNTL, tmp);
}
tmp = INPLL(pllMCLK_CNTL);
tmp |= (MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_MCLKB |
MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB |
MCLK_CNTL__FORCE_AIC |
MCLK_CNTL__FORCE_MC);
OUTPLL(pllMCLK_CNTL, tmp);
return;
}
/* R100 */
if (!rinfo->has_CRTC2) {
tmp = INPLL(pllSCLK_CNTL);
tmp |= (SCLK_CNTL__FORCE_CP | SCLK_CNTL__FORCE_HDP |
SCLK_CNTL__FORCE_DISP1 | SCLK_CNTL__FORCE_TOP |
SCLK_CNTL__FORCE_E2 | SCLK_CNTL__FORCE_SE |
SCLK_CNTL__FORCE_IDCT | SCLK_CNTL__FORCE_VIP |
SCLK_CNTL__FORCE_RE | SCLK_CNTL__FORCE_PB |
SCLK_CNTL__FORCE_TAM | SCLK_CNTL__FORCE_TDM |
SCLK_CNTL__FORCE_RB);
OUTPLL(pllSCLK_CNTL, tmp);
return;
}
/* RV350 (M10/M11) */
if (rinfo->family == CHIP_FAMILY_RV350) {
/* for RV350/M10/M11, no delays are required. */
tmp = INPLL(pllSCLK_CNTL2);
tmp |= (SCLK_CNTL2__R300_FORCE_TCL |
SCLK_CNTL2__R300_FORCE_GA |
SCLK_CNTL2__R300_FORCE_CBA);
OUTPLL(pllSCLK_CNTL2, tmp);
tmp = INPLL(pllSCLK_CNTL);
tmp |= (SCLK_CNTL__FORCE_DISP2 | SCLK_CNTL__FORCE_CP |
SCLK_CNTL__FORCE_HDP | SCLK_CNTL__FORCE_DISP1 |
SCLK_CNTL__FORCE_TOP | SCLK_CNTL__FORCE_E2 |
SCLK_CNTL__R300_FORCE_VAP | SCLK_CNTL__FORCE_IDCT |
SCLK_CNTL__FORCE_VIP | SCLK_CNTL__R300_FORCE_SR |
SCLK_CNTL__R300_FORCE_PX | SCLK_CNTL__R300_FORCE_TX |
SCLK_CNTL__R300_FORCE_US | SCLK_CNTL__FORCE_TV_SCLK |
SCLK_CNTL__R300_FORCE_SU | SCLK_CNTL__FORCE_OV0);
OUTPLL(pllSCLK_CNTL, tmp);
tmp = INPLL(pllSCLK_MORE_CNTL);
tmp |= (SCLK_MORE_CNTL__FORCE_DISPREGS | SCLK_MORE_CNTL__FORCE_MC_GUI |
SCLK_MORE_CNTL__FORCE_MC_HOST);
OUTPLL(pllSCLK_MORE_CNTL, tmp);
tmp = INPLL(pllMCLK_CNTL);
tmp |= (MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_MCLKB |
MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB |
MCLK_CNTL__FORCE_MC);
OUTPLL(pllMCLK_CNTL, tmp);
tmp = INPLL(pllVCLK_ECP_CNTL);
tmp &= ~(VCLK_ECP_CNTL__PIXCLK_ALWAYS_ONb |
VCLK_ECP_CNTL__PIXCLK_DAC_ALWAYS_ONb |
VCLK_ECP_CNTL__R300_DISP_DAC_PIXCLK_DAC_BLANK_OFF);
OUTPLL(pllVCLK_ECP_CNTL, tmp);
tmp = INPLL(pllPIXCLKS_CNTL);
tmp &= ~(PIXCLKS_CNTL__PIX2CLK_ALWAYS_ONb |
PIXCLKS_CNTL__PIX2CLK_DAC_ALWAYS_ONb |
PIXCLKS_CNTL__DISP_TVOUT_PIXCLK_TV_ALWAYS_ONb |
PIXCLKS_CNTL__R300_DVOCLK_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_BLEND_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_GV_ALWAYS_ONb |
PIXCLKS_CNTL__R300_PIXCLK_DVO_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_LVDS_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_TMDS_ALWAYS_ONb |
PIXCLKS_CNTL__R300_PIXCLK_TRANS_ALWAYS_ONb |
PIXCLKS_CNTL__R300_PIXCLK_TVO_ALWAYS_ONb |
PIXCLKS_CNTL__R300_P2G2CLK_ALWAYS_ONb |
PIXCLKS_CNTL__R300_DISP_DAC_PIXCLK_DAC2_BLANK_OFF);
OUTPLL(pllPIXCLKS_CNTL, tmp);
return;
}
/* Default */
/* Force Core Clocks */
tmp = INPLL(pllSCLK_CNTL);
tmp |= (SCLK_CNTL__FORCE_CP | SCLK_CNTL__FORCE_E2);
/* XFree doesn't do that case, but we had this code from Apple and it
* seem necessary for proper suspend/resume operations
*/
if (rinfo->is_mobility) {
tmp |= SCLK_CNTL__FORCE_HDP|
SCLK_CNTL__FORCE_DISP1|
SCLK_CNTL__FORCE_DISP2|
SCLK_CNTL__FORCE_TOP|
SCLK_CNTL__FORCE_SE|
SCLK_CNTL__FORCE_IDCT|
SCLK_CNTL__FORCE_VIP|
SCLK_CNTL__FORCE_PB|
SCLK_CNTL__FORCE_RE|
SCLK_CNTL__FORCE_TAM|
SCLK_CNTL__FORCE_TDM|
SCLK_CNTL__FORCE_RB|
SCLK_CNTL__FORCE_TV_SCLK|
SCLK_CNTL__FORCE_SUBPIC|
SCLK_CNTL__FORCE_OV0;
}
else if (rinfo->family == CHIP_FAMILY_R300 ||
rinfo->family == CHIP_FAMILY_R350) {
tmp |= SCLK_CNTL__FORCE_HDP |
SCLK_CNTL__FORCE_DISP1 |
SCLK_CNTL__FORCE_DISP2 |
SCLK_CNTL__FORCE_TOP |
SCLK_CNTL__FORCE_IDCT |
SCLK_CNTL__FORCE_VIP;
}
OUTPLL(pllSCLK_CNTL, tmp);
radeon_msleep(16);
if (rinfo->family == CHIP_FAMILY_R300 || rinfo->family == CHIP_FAMILY_R350) {
tmp = INPLL(pllSCLK_CNTL2);
tmp |= SCLK_CNTL2__R300_FORCE_TCL |
SCLK_CNTL2__R300_FORCE_GA |
SCLK_CNTL2__R300_FORCE_CBA;
OUTPLL(pllSCLK_CNTL2, tmp);
radeon_msleep(16);
}
tmp = INPLL(pllCLK_PIN_CNTL);
tmp &= ~CLK_PIN_CNTL__SCLK_DYN_START_CNTL;
OUTPLL(pllCLK_PIN_CNTL, tmp);
radeon_msleep(15);
if (rinfo->is_IGP) {
/* Weird ... X is _un_ forcing clocks here, I think it's
* doing backward. Imitate it for now...
*/
tmp = INPLL(pllMCLK_CNTL);
tmp &= ~(MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_YCLKA);
OUTPLL(pllMCLK_CNTL, tmp);
radeon_msleep(16);
}
/* Hrm... same shit, X doesn't do that but I have to */
else if (rinfo->is_mobility) {
tmp = INPLL(pllMCLK_CNTL);
tmp |= (MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_MCLKB |
MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB);
OUTPLL(pllMCLK_CNTL, tmp);
radeon_msleep(16);
tmp = INPLL(pllMCLK_MISC);
tmp &= ~(MCLK_MISC__MC_MCLK_MAX_DYN_STOP_LAT|
MCLK_MISC__IO_MCLK_MAX_DYN_STOP_LAT|
MCLK_MISC__MC_MCLK_DYN_ENABLE|
MCLK_MISC__IO_MCLK_DYN_ENABLE);
OUTPLL(pllMCLK_MISC, tmp);
radeon_msleep(15);
}
if (rinfo->is_mobility) {
tmp = INPLL(pllSCLK_MORE_CNTL);
tmp |= SCLK_MORE_CNTL__FORCE_DISPREGS|
SCLK_MORE_CNTL__FORCE_MC_GUI|
SCLK_MORE_CNTL__FORCE_MC_HOST;
OUTPLL(pllSCLK_MORE_CNTL, tmp);
radeon_msleep(16);
}
tmp = INPLL(pllPIXCLKS_CNTL);
tmp &= ~(PIXCLKS_CNTL__PIXCLK_GV_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_BLEND_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_DIG_TMDS_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_LVDS_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_TMDS_ALWAYS_ONb|
PIXCLKS_CNTL__PIX2CLK_ALWAYS_ONb|
PIXCLKS_CNTL__PIX2CLK_DAC_ALWAYS_ONb);
OUTPLL(pllPIXCLKS_CNTL, tmp);
radeon_msleep(16);
tmp = INPLL( pllVCLK_ECP_CNTL);
tmp &= ~(VCLK_ECP_CNTL__PIXCLK_ALWAYS_ONb |
VCLK_ECP_CNTL__PIXCLK_DAC_ALWAYS_ONb);
OUTPLL( pllVCLK_ECP_CNTL, tmp);
radeon_msleep(16);
}
static void radeon_pm_enable_dynamic_mode(struct radeonfb_info *rinfo)
{
u32 tmp;
/* R100 */
if (!rinfo->has_CRTC2) {
tmp = INPLL(pllSCLK_CNTL);
if ((INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK) > CFG_ATI_REV_A13)
tmp &= ~(SCLK_CNTL__FORCE_CP | SCLK_CNTL__FORCE_RB);
tmp &= ~(SCLK_CNTL__FORCE_HDP | SCLK_CNTL__FORCE_DISP1 |
SCLK_CNTL__FORCE_TOP | SCLK_CNTL__FORCE_SE |
SCLK_CNTL__FORCE_IDCT | SCLK_CNTL__FORCE_RE |
SCLK_CNTL__FORCE_PB | SCLK_CNTL__FORCE_TAM |
SCLK_CNTL__FORCE_TDM);
OUTPLL(pllSCLK_CNTL, tmp);
return;
}
/* M10/M11 */
if (rinfo->family == CHIP_FAMILY_RV350) {
tmp = INPLL(pllSCLK_CNTL2);
tmp &= ~(SCLK_CNTL2__R300_FORCE_TCL |
SCLK_CNTL2__R300_FORCE_GA |
SCLK_CNTL2__R300_FORCE_CBA);
tmp |= (SCLK_CNTL2__R300_TCL_MAX_DYN_STOP_LAT |
SCLK_CNTL2__R300_GA_MAX_DYN_STOP_LAT |
SCLK_CNTL2__R300_CBA_MAX_DYN_STOP_LAT);
OUTPLL(pllSCLK_CNTL2, tmp);
tmp = INPLL(pllSCLK_CNTL);
tmp &= ~(SCLK_CNTL__FORCE_DISP2 | SCLK_CNTL__FORCE_CP |
SCLK_CNTL__FORCE_HDP | SCLK_CNTL__FORCE_DISP1 |
SCLK_CNTL__FORCE_TOP | SCLK_CNTL__FORCE_E2 |
SCLK_CNTL__R300_FORCE_VAP | SCLK_CNTL__FORCE_IDCT |
SCLK_CNTL__FORCE_VIP | SCLK_CNTL__R300_FORCE_SR |
SCLK_CNTL__R300_FORCE_PX | SCLK_CNTL__R300_FORCE_TX |
SCLK_CNTL__R300_FORCE_US | SCLK_CNTL__FORCE_TV_SCLK |
SCLK_CNTL__R300_FORCE_SU | SCLK_CNTL__FORCE_OV0);
tmp |= SCLK_CNTL__DYN_STOP_LAT_MASK;
OUTPLL(pllSCLK_CNTL, tmp);
tmp = INPLL(pllSCLK_MORE_CNTL);
tmp &= ~SCLK_MORE_CNTL__FORCEON;
tmp |= SCLK_MORE_CNTL__DISPREGS_MAX_DYN_STOP_LAT |
SCLK_MORE_CNTL__MC_GUI_MAX_DYN_STOP_LAT |
SCLK_MORE_CNTL__MC_HOST_MAX_DYN_STOP_LAT;
OUTPLL(pllSCLK_MORE_CNTL, tmp);
tmp = INPLL(pllVCLK_ECP_CNTL);
tmp |= (VCLK_ECP_CNTL__PIXCLK_ALWAYS_ONb |
VCLK_ECP_CNTL__PIXCLK_DAC_ALWAYS_ONb);
OUTPLL(pllVCLK_ECP_CNTL, tmp);
tmp = INPLL(pllPIXCLKS_CNTL);
tmp |= (PIXCLKS_CNTL__PIX2CLK_ALWAYS_ONb |
PIXCLKS_CNTL__PIX2CLK_DAC_ALWAYS_ONb |
PIXCLKS_CNTL__DISP_TVOUT_PIXCLK_TV_ALWAYS_ONb |
PIXCLKS_CNTL__R300_DVOCLK_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_BLEND_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_GV_ALWAYS_ONb |
PIXCLKS_CNTL__R300_PIXCLK_DVO_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_LVDS_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_TMDS_ALWAYS_ONb |
PIXCLKS_CNTL__R300_PIXCLK_TRANS_ALWAYS_ONb |
PIXCLKS_CNTL__R300_PIXCLK_TVO_ALWAYS_ONb |
PIXCLKS_CNTL__R300_P2G2CLK_ALWAYS_ONb |
PIXCLKS_CNTL__R300_P2G2CLK_DAC_ALWAYS_ONb);
OUTPLL(pllPIXCLKS_CNTL, tmp);
tmp = INPLL(pllMCLK_MISC);
tmp |= (MCLK_MISC__MC_MCLK_DYN_ENABLE |
MCLK_MISC__IO_MCLK_DYN_ENABLE);
OUTPLL(pllMCLK_MISC, tmp);
tmp = INPLL(pllMCLK_CNTL);
tmp |= (MCLK_CNTL__FORCE_MCLKA | MCLK_CNTL__FORCE_MCLKB);
tmp &= ~(MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB |
MCLK_CNTL__FORCE_MC);
/* Some releases of vbios have set DISABLE_MC_MCLKA
* and DISABLE_MC_MCLKB bits in the vbios table. Setting these
* bits will cause H/W hang when reading video memory with dynamic
* clocking enabled.
*/
if ((tmp & MCLK_CNTL__R300_DISABLE_MC_MCLKA) &&
(tmp & MCLK_CNTL__R300_DISABLE_MC_MCLKB)) {
/* If both bits are set, then check the active channels */
tmp = INPLL(pllMCLK_CNTL);
if (rinfo->vram_width == 64) {
if (INREG(MEM_CNTL) & R300_MEM_USE_CD_CH_ONLY)
tmp &= ~MCLK_CNTL__R300_DISABLE_MC_MCLKB;
else
tmp &= ~MCLK_CNTL__R300_DISABLE_MC_MCLKA;
} else {
tmp &= ~(MCLK_CNTL__R300_DISABLE_MC_MCLKA |
MCLK_CNTL__R300_DISABLE_MC_MCLKB);
}
}
OUTPLL(pllMCLK_CNTL, tmp);
return;
}
/* R300 */
if (rinfo->family == CHIP_FAMILY_R300 || rinfo->family == CHIP_FAMILY_R350) {
tmp = INPLL(pllSCLK_CNTL);
tmp &= ~(SCLK_CNTL__R300_FORCE_VAP);
tmp |= SCLK_CNTL__FORCE_CP;
OUTPLL(pllSCLK_CNTL, tmp);
radeon_msleep(15);
tmp = INPLL(pllSCLK_CNTL2);
tmp &= ~(SCLK_CNTL2__R300_FORCE_TCL |
SCLK_CNTL2__R300_FORCE_GA |
SCLK_CNTL2__R300_FORCE_CBA);
OUTPLL(pllSCLK_CNTL2, tmp);
}
/* Others */
tmp = INPLL( pllCLK_PWRMGT_CNTL);
tmp &= ~(CLK_PWRMGT_CNTL__ACTIVE_HILO_LAT_MASK|
CLK_PWRMGT_CNTL__DISP_DYN_STOP_LAT_MASK|
CLK_PWRMGT_CNTL__DYN_STOP_MODE_MASK);
tmp |= CLK_PWRMGT_CNTL__ENGINE_DYNCLK_MODE_MASK |
(0x01 << CLK_PWRMGT_CNTL__ACTIVE_HILO_LAT__SHIFT);
OUTPLL( pllCLK_PWRMGT_CNTL, tmp);
radeon_msleep(15);
tmp = INPLL(pllCLK_PIN_CNTL);
tmp |= CLK_PIN_CNTL__SCLK_DYN_START_CNTL;
OUTPLL(pllCLK_PIN_CNTL, tmp);
radeon_msleep(15);
/* When DRI is enabled, setting DYN_STOP_LAT to zero can cause some R200
* to lockup randomly, leave them as set by BIOS.
*/
tmp = INPLL(pllSCLK_CNTL);
tmp &= ~SCLK_CNTL__FORCEON_MASK;
/*RAGE_6::A11 A12 A12N1 A13, RV250::A11 A12, R300*/
if ((rinfo->family == CHIP_FAMILY_RV250 &&
((INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK) < CFG_ATI_REV_A13)) ||
((rinfo->family == CHIP_FAMILY_RV100) &&
((INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK) <= CFG_ATI_REV_A13))) {
tmp |= SCLK_CNTL__FORCE_CP;
tmp |= SCLK_CNTL__FORCE_VIP;
}
OUTPLL(pllSCLK_CNTL, tmp);
radeon_msleep(15);
if ((rinfo->family == CHIP_FAMILY_RV200) ||
(rinfo->family == CHIP_FAMILY_RV250) ||
(rinfo->family == CHIP_FAMILY_RV280)) {
tmp = INPLL(pllSCLK_MORE_CNTL);
tmp &= ~SCLK_MORE_CNTL__FORCEON;
/* RV200::A11 A12 RV250::A11 A12 */
if (((rinfo->family == CHIP_FAMILY_RV200) ||
(rinfo->family == CHIP_FAMILY_RV250)) &&
((INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK) < CFG_ATI_REV_A13))
tmp |= SCLK_MORE_CNTL__FORCEON;
OUTPLL(pllSCLK_MORE_CNTL, tmp);
radeon_msleep(15);
}
/* RV200::A11 A12, RV250::A11 A12 */
if (((rinfo->family == CHIP_FAMILY_RV200) ||
(rinfo->family == CHIP_FAMILY_RV250)) &&
((INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK) < CFG_ATI_REV_A13)) {
tmp = INPLL(pllPLL_PWRMGT_CNTL);
tmp |= PLL_PWRMGT_CNTL__TCL_BYPASS_DISABLE;
OUTPLL(pllPLL_PWRMGT_CNTL, tmp);
radeon_msleep(15);
}
tmp = INPLL(pllPIXCLKS_CNTL);
tmp |= PIXCLKS_CNTL__PIX2CLK_ALWAYS_ONb |
PIXCLKS_CNTL__PIX2CLK_DAC_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_BLEND_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_GV_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_DIG_TMDS_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_LVDS_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_TMDS_ALWAYS_ONb;
OUTPLL(pllPIXCLKS_CNTL, tmp);
radeon_msleep(15);
tmp = INPLL(pllVCLK_ECP_CNTL);
tmp |= VCLK_ECP_CNTL__PIXCLK_ALWAYS_ONb |
VCLK_ECP_CNTL__PIXCLK_DAC_ALWAYS_ONb;
OUTPLL(pllVCLK_ECP_CNTL, tmp);
/* X doesn't do that ... hrm, we do on mobility && Macs */
#ifdef CONFIG_PPC_OF
if (rinfo->is_mobility) {
tmp = INPLL(pllMCLK_CNTL);
tmp &= ~(MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_MCLKB |
MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB);
OUTPLL(pllMCLK_CNTL, tmp);
radeon_msleep(15);
tmp = INPLL(pllMCLK_MISC);
tmp |= MCLK_MISC__MC_MCLK_MAX_DYN_STOP_LAT|
MCLK_MISC__IO_MCLK_MAX_DYN_STOP_LAT|
MCLK_MISC__MC_MCLK_DYN_ENABLE|
MCLK_MISC__IO_MCLK_DYN_ENABLE;
OUTPLL(pllMCLK_MISC, tmp);
radeon_msleep(15);
}
#endif /* CONFIG_PPC_OF */
}
#ifdef CONFIG_PM
static void OUTMC( struct radeonfb_info *rinfo, u8 indx, u32 value)
{
OUTREG( MC_IND_INDEX, indx | MC_IND_INDEX__MC_IND_WR_EN);
OUTREG( MC_IND_DATA, value);
}
static u32 INMC(struct radeonfb_info *rinfo, u8 indx)
{
OUTREG( MC_IND_INDEX, indx);
return INREG( MC_IND_DATA);
}
static void radeon_pm_save_regs(struct radeonfb_info *rinfo, int saving_for_d3)
{
rinfo->save_regs[0] = INPLL(PLL_PWRMGT_CNTL);
rinfo->save_regs[1] = INPLL(CLK_PWRMGT_CNTL);
rinfo->save_regs[2] = INPLL(MCLK_CNTL);
rinfo->save_regs[3] = INPLL(SCLK_CNTL);
rinfo->save_regs[4] = INPLL(CLK_PIN_CNTL);
rinfo->save_regs[5] = INPLL(VCLK_ECP_CNTL);
rinfo->save_regs[6] = INPLL(PIXCLKS_CNTL);
rinfo->save_regs[7] = INPLL(MCLK_MISC);
rinfo->save_regs[8] = INPLL(P2PLL_CNTL);
rinfo->save_regs[9] = INREG(DISP_MISC_CNTL);
rinfo->save_regs[10] = INREG(DISP_PWR_MAN);
rinfo->save_regs[11] = INREG(LVDS_GEN_CNTL);
rinfo->save_regs[13] = INREG(TV_DAC_CNTL);
rinfo->save_regs[14] = INREG(BUS_CNTL1);
rinfo->save_regs[15] = INREG(CRTC_OFFSET_CNTL);
rinfo->save_regs[16] = INREG(AGP_CNTL);
rinfo->save_regs[17] = (INREG(CRTC_GEN_CNTL) & 0xfdffffff) | 0x04000000;
rinfo->save_regs[18] = (INREG(CRTC2_GEN_CNTL) & 0xfdffffff) | 0x04000000;
rinfo->save_regs[19] = INREG(GPIOPAD_A);
rinfo->save_regs[20] = INREG(GPIOPAD_EN);
rinfo->save_regs[21] = INREG(GPIOPAD_MASK);
rinfo->save_regs[22] = INREG(ZV_LCDPAD_A);
rinfo->save_regs[23] = INREG(ZV_LCDPAD_EN);
rinfo->save_regs[24] = INREG(ZV_LCDPAD_MASK);
rinfo->save_regs[25] = INREG(GPIO_VGA_DDC);
rinfo->save_regs[26] = INREG(GPIO_DVI_DDC);
rinfo->save_regs[27] = INREG(GPIO_MONID);
rinfo->save_regs[28] = INREG(GPIO_CRT2_DDC);
rinfo->save_regs[29] = INREG(SURFACE_CNTL);
rinfo->save_regs[30] = INREG(MC_FB_LOCATION);
rinfo->save_regs[31] = INREG(DISPLAY_BASE_ADDR);
rinfo->save_regs[32] = INREG(MC_AGP_LOCATION);
rinfo->save_regs[33] = INREG(CRTC2_DISPLAY_BASE_ADDR);
rinfo->save_regs[34] = INPLL(SCLK_MORE_CNTL);
rinfo->save_regs[35] = INREG(MEM_SDRAM_MODE_REG);
rinfo->save_regs[36] = INREG(BUS_CNTL);
rinfo->save_regs[39] = INREG(RBBM_CNTL);
rinfo->save_regs[40] = INREG(DAC_CNTL);
rinfo->save_regs[41] = INREG(HOST_PATH_CNTL);
rinfo->save_regs[37] = INREG(MPP_TB_CONFIG);
rinfo->save_regs[38] = INREG(FCP_CNTL);
if (rinfo->is_mobility) {
rinfo->save_regs[12] = INREG(LVDS_PLL_CNTL);
rinfo->save_regs[43] = INPLL(pllSSPLL_CNTL);
rinfo->save_regs[44] = INPLL(pllSSPLL_REF_DIV);
rinfo->save_regs[45] = INPLL(pllSSPLL_DIV_0);
rinfo->save_regs[90] = INPLL(pllSS_INT_CNTL);
rinfo->save_regs[91] = INPLL(pllSS_TST_CNTL);
rinfo->save_regs[81] = INREG(LVDS_GEN_CNTL);
}
if (rinfo->family >= CHIP_FAMILY_RV200) {
rinfo->save_regs[42] = INREG(MEM_REFRESH_CNTL);
rinfo->save_regs[46] = INREG(MC_CNTL);
rinfo->save_regs[47] = INREG(MC_INIT_GFX_LAT_TIMER);
rinfo->save_regs[48] = INREG(MC_INIT_MISC_LAT_TIMER);
rinfo->save_regs[49] = INREG(MC_TIMING_CNTL);
rinfo->save_regs[50] = INREG(MC_READ_CNTL_AB);
rinfo->save_regs[51] = INREG(MC_IOPAD_CNTL);
rinfo->save_regs[52] = INREG(MC_CHIP_IO_OE_CNTL_AB);
rinfo->save_regs[53] = INREG(MC_DEBUG);
}
rinfo->save_regs[54] = INREG(PAMAC0_DLY_CNTL);
rinfo->save_regs[55] = INREG(PAMAC1_DLY_CNTL);
rinfo->save_regs[56] = INREG(PAD_CTLR_MISC);
rinfo->save_regs[57] = INREG(FW_CNTL);
if (rinfo->family >= CHIP_FAMILY_R300) {
rinfo->save_regs[58] = INMC(rinfo, ixR300_MC_MC_INIT_WR_LAT_TIMER);
rinfo->save_regs[59] = INMC(rinfo, ixR300_MC_IMP_CNTL);
rinfo->save_regs[60] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_C0);
rinfo->save_regs[61] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_C1);
rinfo->save_regs[62] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_D0);
rinfo->save_regs[63] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_D1);
rinfo->save_regs[64] = INMC(rinfo, ixR300_MC_BIST_CNTL_3);
rinfo->save_regs[65] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_A0);
rinfo->save_regs[66] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_A1);
rinfo->save_regs[67] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_B0);
rinfo->save_regs[68] = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_B1);
rinfo->save_regs[69] = INMC(rinfo, ixR300_MC_DEBUG_CNTL);
rinfo->save_regs[70] = INMC(rinfo, ixR300_MC_DLL_CNTL);
rinfo->save_regs[71] = INMC(rinfo, ixR300_MC_IMP_CNTL_0);
rinfo->save_regs[72] = INMC(rinfo, ixR300_MC_ELPIDA_CNTL);
rinfo->save_regs[96] = INMC(rinfo, ixR300_MC_READ_CNTL_CD);
} else {
rinfo->save_regs[59] = INMC(rinfo, ixMC_IMP_CNTL);
rinfo->save_regs[65] = INMC(rinfo, ixMC_CHP_IO_CNTL_A0);
rinfo->save_regs[66] = INMC(rinfo, ixMC_CHP_IO_CNTL_A1);
rinfo->save_regs[67] = INMC(rinfo, ixMC_CHP_IO_CNTL_B0);
rinfo->save_regs[68] = INMC(rinfo, ixMC_CHP_IO_CNTL_B1);
rinfo->save_regs[71] = INMC(rinfo, ixMC_IMP_CNTL_0);
}
rinfo->save_regs[73] = INPLL(pllMPLL_CNTL);
rinfo->save_regs[74] = INPLL(pllSPLL_CNTL);
rinfo->save_regs[75] = INPLL(pllMPLL_AUX_CNTL);
rinfo->save_regs[76] = INPLL(pllSPLL_AUX_CNTL);
rinfo->save_regs[77] = INPLL(pllM_SPLL_REF_FB_DIV);
rinfo->save_regs[78] = INPLL(pllAGP_PLL_CNTL);
rinfo->save_regs[79] = INREG(PAMAC2_DLY_CNTL);
rinfo->save_regs[80] = INREG(OV0_BASE_ADDR);
rinfo->save_regs[82] = INREG(FP_GEN_CNTL);
rinfo->save_regs[83] = INREG(FP2_GEN_CNTL);
rinfo->save_regs[84] = INREG(TMDS_CNTL);
rinfo->save_regs[85] = INREG(TMDS_TRANSMITTER_CNTL);
rinfo->save_regs[86] = INREG(DISP_OUTPUT_CNTL);
rinfo->save_regs[87] = INREG(DISP_HW_DEBUG);
rinfo->save_regs[88] = INREG(TV_MASTER_CNTL);
rinfo->save_regs[89] = INPLL(pllP2PLL_REF_DIV);
rinfo->save_regs[92] = INPLL(pllPPLL_DIV_0);
rinfo->save_regs[93] = INPLL(pllPPLL_CNTL);
rinfo->save_regs[94] = INREG(GRPH_BUFFER_CNTL);
rinfo->save_regs[95] = INREG(GRPH2_BUFFER_CNTL);
rinfo->save_regs[96] = INREG(HDP_DEBUG);
rinfo->save_regs[97] = INPLL(pllMDLL_CKO);
rinfo->save_regs[98] = INPLL(pllMDLL_RDCKA);
rinfo->save_regs[99] = INPLL(pllMDLL_RDCKB);
}
static void radeon_pm_restore_regs(struct radeonfb_info *rinfo)
{
OUTPLL(P2PLL_CNTL, rinfo->save_regs[8] & 0xFFFFFFFE); /* First */
OUTPLL(PLL_PWRMGT_CNTL, rinfo->save_regs[0]);
OUTPLL(CLK_PWRMGT_CNTL, rinfo->save_regs[1]);
OUTPLL(MCLK_CNTL, rinfo->save_regs[2]);
OUTPLL(SCLK_CNTL, rinfo->save_regs[3]);
OUTPLL(CLK_PIN_CNTL, rinfo->save_regs[4]);
OUTPLL(VCLK_ECP_CNTL, rinfo->save_regs[5]);
OUTPLL(PIXCLKS_CNTL, rinfo->save_regs[6]);
OUTPLL(MCLK_MISC, rinfo->save_regs[7]);
if (rinfo->family == CHIP_FAMILY_RV350)
OUTPLL(SCLK_MORE_CNTL, rinfo->save_regs[34]);
OUTREG(SURFACE_CNTL, rinfo->save_regs[29]);
OUTREG(MC_FB_LOCATION, rinfo->save_regs[30]);
OUTREG(DISPLAY_BASE_ADDR, rinfo->save_regs[31]);
OUTREG(MC_AGP_LOCATION, rinfo->save_regs[32]);
OUTREG(CRTC2_DISPLAY_BASE_ADDR, rinfo->save_regs[33]);
OUTREG(CNFG_MEMSIZE, rinfo->video_ram);
OUTREG(DISP_MISC_CNTL, rinfo->save_regs[9]);
OUTREG(DISP_PWR_MAN, rinfo->save_regs[10]);
OUTREG(LVDS_GEN_CNTL, rinfo->save_regs[11]);
OUTREG(LVDS_PLL_CNTL,rinfo->save_regs[12]);
OUTREG(TV_DAC_CNTL, rinfo->save_regs[13]);
OUTREG(BUS_CNTL1, rinfo->save_regs[14]);
OUTREG(CRTC_OFFSET_CNTL, rinfo->save_regs[15]);
OUTREG(AGP_CNTL, rinfo->save_regs[16]);
OUTREG(CRTC_GEN_CNTL, rinfo->save_regs[17]);
OUTREG(CRTC2_GEN_CNTL, rinfo->save_regs[18]);
OUTPLL(P2PLL_CNTL, rinfo->save_regs[8]);
OUTREG(GPIOPAD_A, rinfo->save_regs[19]);
OUTREG(GPIOPAD_EN, rinfo->save_regs[20]);
OUTREG(GPIOPAD_MASK, rinfo->save_regs[21]);
OUTREG(ZV_LCDPAD_A, rinfo->save_regs[22]);
OUTREG(ZV_LCDPAD_EN, rinfo->save_regs[23]);
OUTREG(ZV_LCDPAD_MASK, rinfo->save_regs[24]);
OUTREG(GPIO_VGA_DDC, rinfo->save_regs[25]);
OUTREG(GPIO_DVI_DDC, rinfo->save_regs[26]);
OUTREG(GPIO_MONID, rinfo->save_regs[27]);
OUTREG(GPIO_CRT2_DDC, rinfo->save_regs[28]);
}
static void radeon_pm_disable_iopad(struct radeonfb_info *rinfo)
{
OUTREG(GPIOPAD_MASK, 0x0001ffff);
OUTREG(GPIOPAD_EN, 0x00000400);
OUTREG(GPIOPAD_A, 0x00000000);
OUTREG(ZV_LCDPAD_MASK, 0x00000000);
OUTREG(ZV_LCDPAD_EN, 0x00000000);
OUTREG(ZV_LCDPAD_A, 0x00000000);
OUTREG(GPIO_VGA_DDC, 0x00030000);
OUTREG(GPIO_DVI_DDC, 0x00000000);
OUTREG(GPIO_MONID, 0x00030000);
OUTREG(GPIO_CRT2_DDC, 0x00000000);
}
static void radeon_pm_program_v2clk(struct radeonfb_info *rinfo)
{
/* Set v2clk to 65MHz */
if (rinfo->family <= CHIP_FAMILY_RV280) {
OUTPLL(pllPIXCLKS_CNTL,
__INPLL(rinfo, pllPIXCLKS_CNTL)
& ~PIXCLKS_CNTL__PIX2CLK_SRC_SEL_MASK);
OUTPLL(pllP2PLL_REF_DIV, 0x0000000c);
OUTPLL(pllP2PLL_CNTL, 0x0000bf00);
} else {
OUTPLL(pllP2PLL_REF_DIV, 0x0000000c);
INPLL(pllP2PLL_REF_DIV);
OUTPLL(pllP2PLL_CNTL, 0x0000a700);
}
OUTPLL(pllP2PLL_DIV_0, 0x00020074 | P2PLL_DIV_0__P2PLL_ATOMIC_UPDATE_W);
OUTPLL(pllP2PLL_CNTL, INPLL(pllP2PLL_CNTL) & ~P2PLL_CNTL__P2PLL_SLEEP);
mdelay(1);
OUTPLL(pllP2PLL_CNTL, INPLL(pllP2PLL_CNTL) & ~P2PLL_CNTL__P2PLL_RESET);
mdelay( 1);
OUTPLL(pllPIXCLKS_CNTL,
(INPLL(pllPIXCLKS_CNTL) & ~PIXCLKS_CNTL__PIX2CLK_SRC_SEL_MASK)
| (0x03 << PIXCLKS_CNTL__PIX2CLK_SRC_SEL__SHIFT));
mdelay( 1);
}
static void radeon_pm_low_current(struct radeonfb_info *rinfo)
{
u32 reg;
reg = INREG(BUS_CNTL1);
if (rinfo->family <= CHIP_FAMILY_RV280) {
reg &= ~BUS_CNTL1_MOBILE_PLATFORM_SEL_MASK;
reg |= BUS_CNTL1_AGPCLK_VALID | (1<<BUS_CNTL1_MOBILE_PLATFORM_SEL_SHIFT);
} else {
reg |= 0x4080;
}
OUTREG(BUS_CNTL1, reg);
reg = INPLL(PLL_PWRMGT_CNTL);
reg |= PLL_PWRMGT_CNTL_SPLL_TURNOFF | PLL_PWRMGT_CNTL_PPLL_TURNOFF |
PLL_PWRMGT_CNTL_P2PLL_TURNOFF | PLL_PWRMGT_CNTL_TVPLL_TURNOFF;
reg &= ~PLL_PWRMGT_CNTL_SU_MCLK_USE_BCLK;
reg &= ~PLL_PWRMGT_CNTL_MOBILE_SU;
OUTPLL(PLL_PWRMGT_CNTL, reg);
reg = INREG(TV_DAC_CNTL);
reg &= ~(TV_DAC_CNTL_BGADJ_MASK |TV_DAC_CNTL_DACADJ_MASK);
reg |=TV_DAC_CNTL_BGSLEEP | TV_DAC_CNTL_RDACPD | TV_DAC_CNTL_GDACPD |
TV_DAC_CNTL_BDACPD |
(8<<TV_DAC_CNTL_BGADJ__SHIFT) | (8<<TV_DAC_CNTL_DACADJ__SHIFT);
OUTREG(TV_DAC_CNTL, reg);
reg = INREG(TMDS_TRANSMITTER_CNTL);
reg &= ~(TMDS_PLL_EN | TMDS_PLLRST);
OUTREG(TMDS_TRANSMITTER_CNTL, reg);
reg = INREG(DAC_CNTL);
reg &= ~DAC_CMP_EN;
OUTREG(DAC_CNTL, reg);
reg = INREG(DAC_CNTL2);
reg &= ~DAC2_CMP_EN;
OUTREG(DAC_CNTL2, reg);
reg = INREG(TV_DAC_CNTL);
reg &= ~TV_DAC_CNTL_DETECT;
OUTREG(TV_DAC_CNTL, reg);
}
static void radeon_pm_setup_for_suspend(struct radeonfb_info *rinfo)
{
u32 sclk_cntl, mclk_cntl, sclk_more_cntl;
u32 pll_pwrmgt_cntl;
u32 clk_pwrmgt_cntl;
u32 clk_pin_cntl;
u32 vclk_ecp_cntl;
u32 pixclks_cntl;
u32 disp_mis_cntl;
u32 disp_pwr_man;
u32 tmp;
/* Force Core Clocks */
sclk_cntl = INPLL( pllSCLK_CNTL);
sclk_cntl |= SCLK_CNTL__IDCT_MAX_DYN_STOP_LAT|
SCLK_CNTL__VIP_MAX_DYN_STOP_LAT|
SCLK_CNTL__RE_MAX_DYN_STOP_LAT|
SCLK_CNTL__PB_MAX_DYN_STOP_LAT|
SCLK_CNTL__TAM_MAX_DYN_STOP_LAT|
SCLK_CNTL__TDM_MAX_DYN_STOP_LAT|
SCLK_CNTL__RB_MAX_DYN_STOP_LAT|
SCLK_CNTL__FORCE_DISP2|
SCLK_CNTL__FORCE_CP|
SCLK_CNTL__FORCE_HDP|
SCLK_CNTL__FORCE_DISP1|
SCLK_CNTL__FORCE_TOP|
SCLK_CNTL__FORCE_E2|
SCLK_CNTL__FORCE_SE|
SCLK_CNTL__FORCE_IDCT|
SCLK_CNTL__FORCE_VIP|
SCLK_CNTL__FORCE_PB|
SCLK_CNTL__FORCE_TAM|
SCLK_CNTL__FORCE_TDM|
SCLK_CNTL__FORCE_RB|
SCLK_CNTL__FORCE_TV_SCLK|
SCLK_CNTL__FORCE_SUBPIC|
SCLK_CNTL__FORCE_OV0;
if (rinfo->family <= CHIP_FAMILY_RV280)
sclk_cntl |= SCLK_CNTL__FORCE_RE;
else
sclk_cntl |= SCLK_CNTL__SE_MAX_DYN_STOP_LAT |
SCLK_CNTL__E2_MAX_DYN_STOP_LAT |
SCLK_CNTL__TV_MAX_DYN_STOP_LAT |
SCLK_CNTL__HDP_MAX_DYN_STOP_LAT |
SCLK_CNTL__CP_MAX_DYN_STOP_LAT;
OUTPLL( pllSCLK_CNTL, sclk_cntl);
sclk_more_cntl = INPLL(pllSCLK_MORE_CNTL);
sclk_more_cntl |= SCLK_MORE_CNTL__FORCE_DISPREGS |
SCLK_MORE_CNTL__FORCE_MC_GUI |
SCLK_MORE_CNTL__FORCE_MC_HOST;
OUTPLL(pllSCLK_MORE_CNTL, sclk_more_cntl);
mclk_cntl = INPLL( pllMCLK_CNTL);
mclk_cntl &= ~( MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_MCLKB |
MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB |
MCLK_CNTL__FORCE_MC
);
OUTPLL( pllMCLK_CNTL, mclk_cntl);
/* Force Display clocks */
vclk_ecp_cntl = INPLL( pllVCLK_ECP_CNTL);
vclk_ecp_cntl &= ~(VCLK_ECP_CNTL__PIXCLK_ALWAYS_ONb
| VCLK_ECP_CNTL__PIXCLK_DAC_ALWAYS_ONb);
vclk_ecp_cntl |= VCLK_ECP_CNTL__ECP_FORCE_ON;
OUTPLL( pllVCLK_ECP_CNTL, vclk_ecp_cntl);
pixclks_cntl = INPLL( pllPIXCLKS_CNTL);
pixclks_cntl &= ~( PIXCLKS_CNTL__PIXCLK_GV_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_BLEND_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_DIG_TMDS_ALWAYS_ONb |
PIXCLKS_CNTL__PIXCLK_LVDS_ALWAYS_ONb|
PIXCLKS_CNTL__PIXCLK_TMDS_ALWAYS_ONb|
PIXCLKS_CNTL__PIX2CLK_ALWAYS_ONb|
PIXCLKS_CNTL__PIX2CLK_DAC_ALWAYS_ONb);
OUTPLL( pllPIXCLKS_CNTL, pixclks_cntl);
/* Switch off LVDS interface */
OUTREG(LVDS_GEN_CNTL, INREG(LVDS_GEN_CNTL) &
~(LVDS_BLON | LVDS_EN | LVDS_ON | LVDS_DIGON));
/* Enable System power management */
pll_pwrmgt_cntl = INPLL( pllPLL_PWRMGT_CNTL);
pll_pwrmgt_cntl |= PLL_PWRMGT_CNTL__SPLL_TURNOFF |
PLL_PWRMGT_CNTL__MPLL_TURNOFF|
PLL_PWRMGT_CNTL__PPLL_TURNOFF|
PLL_PWRMGT_CNTL__P2PLL_TURNOFF|
PLL_PWRMGT_CNTL__TVPLL_TURNOFF;
OUTPLL( pllPLL_PWRMGT_CNTL, pll_pwrmgt_cntl);
clk_pwrmgt_cntl = INPLL( pllCLK_PWRMGT_CNTL);
clk_pwrmgt_cntl &= ~( CLK_PWRMGT_CNTL__MPLL_PWRMGT_OFF|
CLK_PWRMGT_CNTL__SPLL_PWRMGT_OFF|
CLK_PWRMGT_CNTL__PPLL_PWRMGT_OFF|
CLK_PWRMGT_CNTL__P2PLL_PWRMGT_OFF|
CLK_PWRMGT_CNTL__MCLK_TURNOFF|
CLK_PWRMGT_CNTL__SCLK_TURNOFF|
CLK_PWRMGT_CNTL__PCLK_TURNOFF|
CLK_PWRMGT_CNTL__P2CLK_TURNOFF|
CLK_PWRMGT_CNTL__TVPLL_PWRMGT_OFF|
CLK_PWRMGT_CNTL__GLOBAL_PMAN_EN|
CLK_PWRMGT_CNTL__ENGINE_DYNCLK_MODE|
CLK_PWRMGT_CNTL__ACTIVE_HILO_LAT_MASK|
CLK_PWRMGT_CNTL__CG_NO1_DEBUG_MASK
);
clk_pwrmgt_cntl |= CLK_PWRMGT_CNTL__GLOBAL_PMAN_EN
| CLK_PWRMGT_CNTL__DISP_PM;
OUTPLL( pllCLK_PWRMGT_CNTL, clk_pwrmgt_cntl);
clk_pin_cntl = INPLL( pllCLK_PIN_CNTL);
clk_pin_cntl &= ~CLK_PIN_CNTL__ACCESS_REGS_IN_SUSPEND;
/* because both INPLL and OUTPLL take the same lock, that's why. */
tmp = INPLL( pllMCLK_MISC) | MCLK_MISC__EN_MCLK_TRISTATE_IN_SUSPEND;
OUTPLL( pllMCLK_MISC, tmp);
/* BUS_CNTL1__MOBILE_PLATORM_SEL setting is northbridge chipset
* and radeon chip dependent. Thus we only enable it on Mac for
* now (until we get more info on how to compute the correct
* value for various X86 bridges).
*/
#ifdef CONFIG_PPC_PMAC
if (machine_is(powermac)) {
/* AGP PLL control */
if (rinfo->family <= CHIP_FAMILY_RV280) {
OUTREG(BUS_CNTL1, INREG(BUS_CNTL1) | BUS_CNTL1__AGPCLK_VALID);
OUTREG(BUS_CNTL1,
(INREG(BUS_CNTL1) & ~BUS_CNTL1__MOBILE_PLATFORM_SEL_MASK)
| (2<<BUS_CNTL1__MOBILE_PLATFORM_SEL__SHIFT)); // 440BX
} else {
OUTREG(BUS_CNTL1, INREG(BUS_CNTL1));
OUTREG(BUS_CNTL1, (INREG(BUS_CNTL1) & ~0x4000) | 0x8000);
}
}
#endif
OUTREG(CRTC_OFFSET_CNTL, (INREG(CRTC_OFFSET_CNTL)
& ~CRTC_OFFSET_CNTL__CRTC_STEREO_SYNC_OUT_EN));
clk_pin_cntl &= ~CLK_PIN_CNTL__CG_CLK_TO_OUTPIN;
clk_pin_cntl |= CLK_PIN_CNTL__XTALIN_ALWAYS_ONb;
OUTPLL( pllCLK_PIN_CNTL, clk_pin_cntl);
/* Solano2M */
OUTREG(AGP_CNTL,
(INREG(AGP_CNTL) & ~(AGP_CNTL__MAX_IDLE_CLK_MASK))
| (0x20<<AGP_CNTL__MAX_IDLE_CLK__SHIFT));
/* ACPI mode */
/* because both INPLL and OUTPLL take the same lock, that's why. */
tmp = INPLL( pllPLL_PWRMGT_CNTL) & ~PLL_PWRMGT_CNTL__PM_MODE_SEL;
OUTPLL( pllPLL_PWRMGT_CNTL, tmp);
disp_mis_cntl = INREG(DISP_MISC_CNTL);
disp_mis_cntl &= ~( DISP_MISC_CNTL__SOFT_RESET_GRPH_PP |
DISP_MISC_CNTL__SOFT_RESET_SUBPIC_PP |
DISP_MISC_CNTL__SOFT_RESET_OV0_PP |
DISP_MISC_CNTL__SOFT_RESET_GRPH_SCLK|
DISP_MISC_CNTL__SOFT_RESET_SUBPIC_SCLK|
DISP_MISC_CNTL__SOFT_RESET_OV0_SCLK|
DISP_MISC_CNTL__SOFT_RESET_GRPH2_PP|
DISP_MISC_CNTL__SOFT_RESET_GRPH2_SCLK|
DISP_MISC_CNTL__SOFT_RESET_LVDS|
DISP_MISC_CNTL__SOFT_RESET_TMDS|
DISP_MISC_CNTL__SOFT_RESET_DIG_TMDS|
DISP_MISC_CNTL__SOFT_RESET_TV);
OUTREG(DISP_MISC_CNTL, disp_mis_cntl);
disp_pwr_man = INREG(DISP_PWR_MAN);
disp_pwr_man &= ~( DISP_PWR_MAN__DISP_PWR_MAN_D3_CRTC_EN |
DISP_PWR_MAN__DISP2_PWR_MAN_D3_CRTC2_EN |
DISP_PWR_MAN__DISP_PWR_MAN_DPMS_MASK|
DISP_PWR_MAN__DISP_D3_RST|
DISP_PWR_MAN__DISP_D3_REG_RST
);
disp_pwr_man |= DISP_PWR_MAN__DISP_D3_GRPH_RST|
DISP_PWR_MAN__DISP_D3_SUBPIC_RST|
DISP_PWR_MAN__DISP_D3_OV0_RST|
DISP_PWR_MAN__DISP_D1D2_GRPH_RST|
DISP_PWR_MAN__DISP_D1D2_SUBPIC_RST|
DISP_PWR_MAN__DISP_D1D2_OV0_RST|
DISP_PWR_MAN__DIG_TMDS_ENABLE_RST|
DISP_PWR_MAN__TV_ENABLE_RST|
// DISP_PWR_MAN__AUTO_PWRUP_EN|
0;
OUTREG(DISP_PWR_MAN, disp_pwr_man);
clk_pwrmgt_cntl = INPLL( pllCLK_PWRMGT_CNTL);
pll_pwrmgt_cntl = INPLL( pllPLL_PWRMGT_CNTL) ;
clk_pin_cntl = INPLL( pllCLK_PIN_CNTL);
disp_pwr_man = INREG(DISP_PWR_MAN);
/* D2 */
clk_pwrmgt_cntl |= CLK_PWRMGT_CNTL__DISP_PM;
pll_pwrmgt_cntl |= PLL_PWRMGT_CNTL__MOBILE_SU | PLL_PWRMGT_CNTL__SU_SCLK_USE_BCLK;
clk_pin_cntl |= CLK_PIN_CNTL__XTALIN_ALWAYS_ONb;
disp_pwr_man &= ~(DISP_PWR_MAN__DISP_PWR_MAN_D3_CRTC_EN_MASK
| DISP_PWR_MAN__DISP2_PWR_MAN_D3_CRTC2_EN_MASK);
OUTPLL( pllCLK_PWRMGT_CNTL, clk_pwrmgt_cntl);
OUTPLL( pllPLL_PWRMGT_CNTL, pll_pwrmgt_cntl);
OUTPLL( pllCLK_PIN_CNTL, clk_pin_cntl);
OUTREG(DISP_PWR_MAN, disp_pwr_man);
/* disable display request & disable display */
OUTREG( CRTC_GEN_CNTL, (INREG( CRTC_GEN_CNTL) & ~CRTC_GEN_CNTL__CRTC_EN)
| CRTC_GEN_CNTL__CRTC_DISP_REQ_EN_B);
OUTREG( CRTC2_GEN_CNTL, (INREG( CRTC2_GEN_CNTL) & ~CRTC2_GEN_CNTL__CRTC2_EN)
| CRTC2_GEN_CNTL__CRTC2_DISP_REQ_EN_B);
mdelay(17);
}
static void radeon_pm_yclk_mclk_sync(struct radeonfb_info *rinfo)
{
u32 mc_chp_io_cntl_a1, mc_chp_io_cntl_b1;
mc_chp_io_cntl_a1 = INMC( rinfo, ixMC_CHP_IO_CNTL_A1)
& ~MC_CHP_IO_CNTL_A1__MEM_SYNC_ENA_MASK;
mc_chp_io_cntl_b1 = INMC( rinfo, ixMC_CHP_IO_CNTL_B1)
& ~MC_CHP_IO_CNTL_B1__MEM_SYNC_ENB_MASK;
OUTMC( rinfo, ixMC_CHP_IO_CNTL_A1, mc_chp_io_cntl_a1
| (1<<MC_CHP_IO_CNTL_A1__MEM_SYNC_ENA__SHIFT));
OUTMC( rinfo, ixMC_CHP_IO_CNTL_B1, mc_chp_io_cntl_b1
| (1<<MC_CHP_IO_CNTL_B1__MEM_SYNC_ENB__SHIFT));
OUTMC( rinfo, ixMC_CHP_IO_CNTL_A1, mc_chp_io_cntl_a1);
OUTMC( rinfo, ixMC_CHP_IO_CNTL_B1, mc_chp_io_cntl_b1);
mdelay( 1);
}
static void radeon_pm_yclk_mclk_sync_m10(struct radeonfb_info *rinfo)
{
u32 mc_chp_io_cntl_a1, mc_chp_io_cntl_b1;
mc_chp_io_cntl_a1 = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_A1)
& ~MC_CHP_IO_CNTL_A1__MEM_SYNC_ENA_MASK;
mc_chp_io_cntl_b1 = INMC(rinfo, ixR300_MC_CHP_IO_CNTL_B1)
& ~MC_CHP_IO_CNTL_B1__MEM_SYNC_ENB_MASK;
OUTMC( rinfo, ixR300_MC_CHP_IO_CNTL_A1,
mc_chp_io_cntl_a1 | (1<<MC_CHP_IO_CNTL_A1__MEM_SYNC_ENA__SHIFT));
OUTMC( rinfo, ixR300_MC_CHP_IO_CNTL_B1,
mc_chp_io_cntl_b1 | (1<<MC_CHP_IO_CNTL_B1__MEM_SYNC_ENB__SHIFT));
OUTMC( rinfo, ixR300_MC_CHP_IO_CNTL_A1, mc_chp_io_cntl_a1);
OUTMC( rinfo, ixR300_MC_CHP_IO_CNTL_B1, mc_chp_io_cntl_b1);
mdelay( 1);
}
static void radeon_pm_program_mode_reg(struct radeonfb_info *rinfo, u16 value,
u8 delay_required)
{
u32 mem_sdram_mode;
mem_sdram_mode = INREG( MEM_SDRAM_MODE_REG);
mem_sdram_mode &= ~MEM_SDRAM_MODE_REG__MEM_MODE_REG_MASK;
mem_sdram_mode |= (value<<MEM_SDRAM_MODE_REG__MEM_MODE_REG__SHIFT)
| MEM_SDRAM_MODE_REG__MEM_CFG_TYPE;
OUTREG( MEM_SDRAM_MODE_REG, mem_sdram_mode);
if (delay_required >= 2)
mdelay(1);
mem_sdram_mode |= MEM_SDRAM_MODE_REG__MEM_SDRAM_RESET;
OUTREG( MEM_SDRAM_MODE_REG, mem_sdram_mode);
if (delay_required >= 2)
mdelay(1);
mem_sdram_mode &= ~MEM_SDRAM_MODE_REG__MEM_SDRAM_RESET;
OUTREG( MEM_SDRAM_MODE_REG, mem_sdram_mode);
if (delay_required >= 2)
mdelay(1);
if (delay_required) {
do {
if (delay_required >= 2)
mdelay(1);
} while ((INREG(MC_STATUS)
& (MC_STATUS__MEM_PWRUP_COMPL_A |
MC_STATUS__MEM_PWRUP_COMPL_B)) == 0);
}
}
static void radeon_pm_m10_program_mode_wait(struct radeonfb_info *rinfo)
{
int cnt;
for (cnt = 0; cnt < 100; ++cnt) {
mdelay(1);
if (INREG(MC_STATUS) & (MC_STATUS__MEM_PWRUP_COMPL_A
| MC_STATUS__MEM_PWRUP_COMPL_B))
break;
}
}
static void radeon_pm_enable_dll(struct radeonfb_info *rinfo)
{
#define DLL_RESET_DELAY 5
#define DLL_SLEEP_DELAY 1
u32 cko = INPLL(pllMDLL_CKO) | MDLL_CKO__MCKOA_SLEEP
| MDLL_CKO__MCKOA_RESET;
u32 cka = INPLL(pllMDLL_RDCKA) | MDLL_RDCKA__MRDCKA0_SLEEP
| MDLL_RDCKA__MRDCKA1_SLEEP | MDLL_RDCKA__MRDCKA0_RESET
| MDLL_RDCKA__MRDCKA1_RESET;
u32 ckb = INPLL(pllMDLL_RDCKB) | MDLL_RDCKB__MRDCKB0_SLEEP
| MDLL_RDCKB__MRDCKB1_SLEEP | MDLL_RDCKB__MRDCKB0_RESET
| MDLL_RDCKB__MRDCKB1_RESET;
/* Setting up the DLL range for write */
OUTPLL(pllMDLL_CKO, cko);
OUTPLL(pllMDLL_RDCKA, cka);
OUTPLL(pllMDLL_RDCKB, ckb);
mdelay(DLL_RESET_DELAY*2);
cko &= ~(MDLL_CKO__MCKOA_SLEEP | MDLL_CKO__MCKOB_SLEEP);
OUTPLL(pllMDLL_CKO, cko);
mdelay(DLL_SLEEP_DELAY);
cko &= ~(MDLL_CKO__MCKOA_RESET | MDLL_CKO__MCKOB_RESET);
OUTPLL(pllMDLL_CKO, cko);
mdelay(DLL_RESET_DELAY);
cka &= ~(MDLL_RDCKA__MRDCKA0_SLEEP | MDLL_RDCKA__MRDCKA1_SLEEP);
OUTPLL(pllMDLL_RDCKA, cka);
mdelay(DLL_SLEEP_DELAY);
cka &= ~(MDLL_RDCKA__MRDCKA0_RESET | MDLL_RDCKA__MRDCKA1_RESET);
OUTPLL(pllMDLL_RDCKA, cka);
mdelay(DLL_RESET_DELAY);
ckb &= ~(MDLL_RDCKB__MRDCKB0_SLEEP | MDLL_RDCKB__MRDCKB1_SLEEP);
OUTPLL(pllMDLL_RDCKB, ckb);
mdelay(DLL_SLEEP_DELAY);
ckb &= ~(MDLL_RDCKB__MRDCKB0_RESET | MDLL_RDCKB__MRDCKB1_RESET);
OUTPLL(pllMDLL_RDCKB, ckb);
mdelay(DLL_RESET_DELAY);
#undef DLL_RESET_DELAY
#undef DLL_SLEEP_DELAY
}
static void radeon_pm_enable_dll_m10(struct radeonfb_info *rinfo)
{
u32 dll_value;
u32 dll_sleep_mask = 0;
u32 dll_reset_mask = 0;
u32 mc;
#define DLL_RESET_DELAY 5
#define DLL_SLEEP_DELAY 1
OUTMC(rinfo, ixR300_MC_DLL_CNTL, rinfo->save_regs[70]);
mc = INREG(MC_CNTL);
/* Check which channels are enabled */
switch (mc & 0x3) {
case 1:
if (mc & 0x4)
break;
case 2:
dll_sleep_mask |= MDLL_R300_RDCK__MRDCKB_SLEEP;
dll_reset_mask |= MDLL_R300_RDCK__MRDCKB_RESET;
case 0:
dll_sleep_mask |= MDLL_R300_RDCK__MRDCKA_SLEEP;
dll_reset_mask |= MDLL_R300_RDCK__MRDCKA_RESET;
}
switch (mc & 0x3) {
case 1:
if (!(mc & 0x4))
break;
case 2:
dll_sleep_mask |= MDLL_R300_RDCK__MRDCKD_SLEEP;
dll_reset_mask |= MDLL_R300_RDCK__MRDCKD_RESET;
dll_sleep_mask |= MDLL_R300_RDCK__MRDCKC_SLEEP;
dll_reset_mask |= MDLL_R300_RDCK__MRDCKC_RESET;
}
dll_value = INPLL(pllMDLL_RDCKA);
/* Power Up */
dll_value &= ~(dll_sleep_mask);
OUTPLL(pllMDLL_RDCKA, dll_value);
mdelay( DLL_SLEEP_DELAY);
dll_value &= ~(dll_reset_mask);
OUTPLL(pllMDLL_RDCKA, dll_value);
mdelay( DLL_RESET_DELAY);
#undef DLL_RESET_DELAY
#undef DLL_SLEEP_DELAY
}
static void radeon_pm_full_reset_sdram(struct radeonfb_info *rinfo)
{
u32 crtcGenCntl, crtcGenCntl2, memRefreshCntl, crtc_more_cntl,
fp_gen_cntl, fp2_gen_cntl;
crtcGenCntl = INREG( CRTC_GEN_CNTL);
crtcGenCntl2 = INREG( CRTC2_GEN_CNTL);
crtc_more_cntl = INREG( CRTC_MORE_CNTL);
fp_gen_cntl = INREG( FP_GEN_CNTL);
fp2_gen_cntl = INREG( FP2_GEN_CNTL);
OUTREG( CRTC_MORE_CNTL, 0);
OUTREG( FP_GEN_CNTL, 0);
OUTREG( FP2_GEN_CNTL,0);
OUTREG( CRTC_GEN_CNTL, (crtcGenCntl | CRTC_GEN_CNTL__CRTC_DISP_REQ_EN_B) );
OUTREG( CRTC2_GEN_CNTL, (crtcGenCntl2 | CRTC2_GEN_CNTL__CRTC2_DISP_REQ_EN_B) );
/* This is the code for the Aluminium PowerBooks M10 / iBooks M11 */
if (rinfo->family == CHIP_FAMILY_RV350) {
u32 sdram_mode_reg = rinfo->save_regs[35];
static const u32 default_mrtable[] =
{ 0x21320032,
0x21321000, 0xa1321000, 0x21321000, 0xffffffff,
0x21320032, 0xa1320032, 0x21320032, 0xffffffff,
0x21321002, 0xa1321002, 0x21321002, 0xffffffff,
0x21320132, 0xa1320132, 0x21320132, 0xffffffff,
0x21320032, 0xa1320032, 0x21320032, 0xffffffff,
0x31320032 };
const u32 *mrtable = default_mrtable;
int i, mrtable_size = ARRAY_SIZE(default_mrtable);
mdelay(30);
/* Disable refresh */
memRefreshCntl = INREG( MEM_REFRESH_CNTL)
& ~MEM_REFRESH_CNTL__MEM_REFRESH_DIS;
OUTREG( MEM_REFRESH_CNTL, memRefreshCntl
| MEM_REFRESH_CNTL__MEM_REFRESH_DIS);
/* Configure and enable M & SPLLs */
radeon_pm_enable_dll_m10(rinfo);
radeon_pm_yclk_mclk_sync_m10(rinfo);
#ifdef CONFIG_PPC_OF
if (rinfo->of_node != NULL) {
int size;
mrtable = of_get_property(rinfo->of_node, "ATY,MRT", &size);
if (mrtable)
mrtable_size = size >> 2;
else
mrtable = default_mrtable;
}
#endif /* CONFIG_PPC_OF */
/* Program the SDRAM */
sdram_mode_reg = mrtable[0];
OUTREG(MEM_SDRAM_MODE_REG, sdram_mode_reg);
for (i = 0; i < mrtable_size; i++) {
if (mrtable[i] == 0xffffffffu)
radeon_pm_m10_program_mode_wait(rinfo);
else {
sdram_mode_reg &= ~(MEM_SDRAM_MODE_REG__MEM_MODE_REG_MASK
| MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE
| MEM_SDRAM_MODE_REG__MEM_SDRAM_RESET);
sdram_mode_reg |= mrtable[i];
OUTREG(MEM_SDRAM_MODE_REG, sdram_mode_reg);
mdelay(1);
}
}
/* Restore memory refresh */
OUTREG(MEM_REFRESH_CNTL, memRefreshCntl);
mdelay(30);
}
/* Here come the desktop RV200 "QW" card */
else if (!rinfo->is_mobility && rinfo->family == CHIP_FAMILY_RV200) {
/* Disable refresh */
memRefreshCntl = INREG( MEM_REFRESH_CNTL)
& ~MEM_REFRESH_CNTL__MEM_REFRESH_DIS;
OUTREG(MEM_REFRESH_CNTL, memRefreshCntl
| MEM_REFRESH_CNTL__MEM_REFRESH_DIS);
mdelay(30);
/* Reset memory */
OUTREG(MEM_SDRAM_MODE_REG,
INREG( MEM_SDRAM_MODE_REG) & ~MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
radeon_pm_program_mode_reg(rinfo, 0x2002, 2);
radeon_pm_program_mode_reg(rinfo, 0x0132, 2);
radeon_pm_program_mode_reg(rinfo, 0x0032, 2);
OUTREG(MEM_SDRAM_MODE_REG,
INREG(MEM_SDRAM_MODE_REG) | MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
OUTREG( MEM_REFRESH_CNTL, memRefreshCntl);
}
/* The M6 */
else if (rinfo->is_mobility && rinfo->family == CHIP_FAMILY_RV100) {
/* Disable refresh */
memRefreshCntl = INREG(EXT_MEM_CNTL) & ~(1 << 20);
OUTREG( EXT_MEM_CNTL, memRefreshCntl | (1 << 20));
/* Reset memory */
OUTREG( MEM_SDRAM_MODE_REG,
INREG( MEM_SDRAM_MODE_REG)
& ~MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
/* DLL */
radeon_pm_enable_dll(rinfo);
/* MLCK / YCLK sync */
radeon_pm_yclk_mclk_sync(rinfo);
/* Program Mode Register */
radeon_pm_program_mode_reg(rinfo, 0x2000, 1);
radeon_pm_program_mode_reg(rinfo, 0x2001, 1);
radeon_pm_program_mode_reg(rinfo, 0x2002, 1);
radeon_pm_program_mode_reg(rinfo, 0x0132, 1);
radeon_pm_program_mode_reg(rinfo, 0x0032, 1);
/* Complete & re-enable refresh */
OUTREG( MEM_SDRAM_MODE_REG,
INREG( MEM_SDRAM_MODE_REG) | MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
OUTREG(EXT_MEM_CNTL, memRefreshCntl);
}
/* And finally, the M7..M9 models, including M9+ (RV280) */
else if (rinfo->is_mobility) {
/* Disable refresh */
memRefreshCntl = INREG( MEM_REFRESH_CNTL)
& ~MEM_REFRESH_CNTL__MEM_REFRESH_DIS;
OUTREG( MEM_REFRESH_CNTL, memRefreshCntl
| MEM_REFRESH_CNTL__MEM_REFRESH_DIS);
/* Reset memory */
OUTREG( MEM_SDRAM_MODE_REG,
INREG( MEM_SDRAM_MODE_REG)
& ~MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
/* DLL */
radeon_pm_enable_dll(rinfo);
/* MLCK / YCLK sync */
radeon_pm_yclk_mclk_sync(rinfo);
/* M6, M7 and M9 so far ... */
if (rinfo->family <= CHIP_FAMILY_RV250) {
radeon_pm_program_mode_reg(rinfo, 0x2000, 1);
radeon_pm_program_mode_reg(rinfo, 0x2001, 1);
radeon_pm_program_mode_reg(rinfo, 0x2002, 1);
radeon_pm_program_mode_reg(rinfo, 0x0132, 1);
radeon_pm_program_mode_reg(rinfo, 0x0032, 1);
}
/* M9+ (iBook G4) */
else if (rinfo->family == CHIP_FAMILY_RV280) {
radeon_pm_program_mode_reg(rinfo, 0x2000, 1);
radeon_pm_program_mode_reg(rinfo, 0x0132, 1);
radeon_pm_program_mode_reg(rinfo, 0x0032, 1);
}
/* Complete & re-enable refresh */
OUTREG( MEM_SDRAM_MODE_REG,
INREG( MEM_SDRAM_MODE_REG) | MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
OUTREG( MEM_REFRESH_CNTL, memRefreshCntl);
}
OUTREG( CRTC_GEN_CNTL, crtcGenCntl);
OUTREG( CRTC2_GEN_CNTL, crtcGenCntl2);
OUTREG( FP_GEN_CNTL, fp_gen_cntl);
OUTREG( FP2_GEN_CNTL, fp2_gen_cntl);
OUTREG( CRTC_MORE_CNTL, crtc_more_cntl);
mdelay( 15);
}
static void radeon_pm_reset_pad_ctlr_strength(struct radeonfb_info *rinfo)
{
u32 tmp, tmp2;
int i,j;
/* Reset the PAD_CTLR_STRENGTH & wait for it to be stable */
INREG(PAD_CTLR_STRENGTH);
OUTREG(PAD_CTLR_STRENGTH, INREG(PAD_CTLR_STRENGTH) & ~PAD_MANUAL_OVERRIDE);
tmp = INREG(PAD_CTLR_STRENGTH);
for (i = j = 0; i < 65; ++i) {
mdelay(1);
tmp2 = INREG(PAD_CTLR_STRENGTH);
if (tmp != tmp2) {
tmp = tmp2;
i = 0;
j++;
if (j > 10) {
printk(KERN_WARNING "radeon: PAD_CTLR_STRENGTH doesn't "
"stabilize !\n");
break;
}
}
}
}
static void radeon_pm_all_ppls_off(struct radeonfb_info *rinfo)
{
u32 tmp;
tmp = INPLL(pllPPLL_CNTL);
OUTPLL(pllPPLL_CNTL, tmp | 0x3);
tmp = INPLL(pllP2PLL_CNTL);
OUTPLL(pllP2PLL_CNTL, tmp | 0x3);
tmp = INPLL(pllSPLL_CNTL);
OUTPLL(pllSPLL_CNTL, tmp | 0x3);
tmp = INPLL(pllMPLL_CNTL);
OUTPLL(pllMPLL_CNTL, tmp | 0x3);
}
static void radeon_pm_start_mclk_sclk(struct radeonfb_info *rinfo)
{
u32 tmp;
/* Switch SPLL to PCI source */
tmp = INPLL(pllSCLK_CNTL);
OUTPLL(pllSCLK_CNTL, tmp & ~SCLK_CNTL__SCLK_SRC_SEL_MASK);
/* Reconfigure SPLL charge pump, VCO gain, duty cycle */
tmp = INPLL(pllSPLL_CNTL);
OUTREG8(CLOCK_CNTL_INDEX, pllSPLL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA + 1, (tmp >> 8) & 0xff);
radeon_pll_errata_after_data(rinfo);
/* Set SPLL feedback divider */
tmp = INPLL(pllM_SPLL_REF_FB_DIV);
tmp = (tmp & 0xff00fffful) | (rinfo->save_regs[77] & 0x00ff0000ul);
OUTPLL(pllM_SPLL_REF_FB_DIV, tmp);
/* Power up SPLL */
tmp = INPLL(pllSPLL_CNTL);
OUTPLL(pllSPLL_CNTL, tmp & ~1);
(void)INPLL(pllSPLL_CNTL);
mdelay(10);
/* Release SPLL reset */
tmp = INPLL(pllSPLL_CNTL);
OUTPLL(pllSPLL_CNTL, tmp & ~0x2);
(void)INPLL(pllSPLL_CNTL);
mdelay(10);
/* Select SCLK source */
tmp = INPLL(pllSCLK_CNTL);
tmp &= ~SCLK_CNTL__SCLK_SRC_SEL_MASK;
tmp |= rinfo->save_regs[3] & SCLK_CNTL__SCLK_SRC_SEL_MASK;
OUTPLL(pllSCLK_CNTL, tmp);
(void)INPLL(pllSCLK_CNTL);
mdelay(10);
/* Reconfigure MPLL charge pump, VCO gain, duty cycle */
tmp = INPLL(pllMPLL_CNTL);
OUTREG8(CLOCK_CNTL_INDEX, pllMPLL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA + 1, (tmp >> 8) & 0xff);
radeon_pll_errata_after_data(rinfo);
/* Set MPLL feedback divider */
tmp = INPLL(pllM_SPLL_REF_FB_DIV);
tmp = (tmp & 0xffff00fful) | (rinfo->save_regs[77] & 0x0000ff00ul);
OUTPLL(pllM_SPLL_REF_FB_DIV, tmp);
/* Power up MPLL */
tmp = INPLL(pllMPLL_CNTL);
OUTPLL(pllMPLL_CNTL, tmp & ~0x2);
(void)INPLL(pllMPLL_CNTL);
mdelay(10);
/* Un-reset MPLL */
tmp = INPLL(pllMPLL_CNTL);
OUTPLL(pllMPLL_CNTL, tmp & ~0x1);
(void)INPLL(pllMPLL_CNTL);
mdelay(10);
/* Select source for MCLK */
tmp = INPLL(pllMCLK_CNTL);
tmp |= rinfo->save_regs[2] & 0xffff;
OUTPLL(pllMCLK_CNTL, tmp);
(void)INPLL(pllMCLK_CNTL);
mdelay(10);
}
static void radeon_pm_m10_disable_spread_spectrum(struct radeonfb_info *rinfo)
{
u32 r2ec;
/* GACK ! I though we didn't have a DDA on Radeon's anymore
* here we rewrite with the same value, ... I suppose we clear
* some bits that are already clear ? Or maybe this 0x2ec
* register is something new ?
*/
mdelay(20);
r2ec = INREG(VGA_DDA_ON_OFF);
OUTREG(VGA_DDA_ON_OFF, r2ec);
mdelay(1);
/* Spread spectrum PLLL off */
OUTPLL(pllSSPLL_CNTL, 0xbf03);
/* Spread spectrum disabled */
OUTPLL(pllSS_INT_CNTL, rinfo->save_regs[90] & ~3);
/* The trace shows read & rewrite of LVDS_PLL_CNTL here with same
* value, not sure what for...
*/
r2ec |= 0x3f0;
OUTREG(VGA_DDA_ON_OFF, r2ec);
mdelay(1);
}
static void radeon_pm_m10_enable_lvds_spread_spectrum(struct radeonfb_info *rinfo)
{
u32 r2ec, tmp;
/* GACK (bis) ! I though we didn't have a DDA on Radeon's anymore
* here we rewrite with the same value, ... I suppose we clear/set
* some bits that are already clear/set ?
*/
r2ec = INREG(VGA_DDA_ON_OFF);
OUTREG(VGA_DDA_ON_OFF, r2ec);
mdelay(1);
/* Enable spread spectrum */
OUTPLL(pllSSPLL_CNTL, rinfo->save_regs[43] | 3);
mdelay(3);
OUTPLL(pllSSPLL_REF_DIV, rinfo->save_regs[44]);
OUTPLL(pllSSPLL_DIV_0, rinfo->save_regs[45]);
tmp = INPLL(pllSSPLL_CNTL);
OUTPLL(pllSSPLL_CNTL, tmp & ~0x2);
mdelay(6);
tmp = INPLL(pllSSPLL_CNTL);
OUTPLL(pllSSPLL_CNTL, tmp & ~0x1);
mdelay(5);
OUTPLL(pllSS_INT_CNTL, rinfo->save_regs[90]);
r2ec |= 8;
OUTREG(VGA_DDA_ON_OFF, r2ec);
mdelay(20);
/* Enable LVDS interface */
tmp = INREG(LVDS_GEN_CNTL);
OUTREG(LVDS_GEN_CNTL, tmp | LVDS_EN);
/* Enable LVDS_PLL */
tmp = INREG(LVDS_PLL_CNTL);
tmp &= ~0x30000;
tmp |= 0x10000;
OUTREG(LVDS_PLL_CNTL, tmp);
OUTPLL(pllSCLK_MORE_CNTL, rinfo->save_regs[34]);
OUTPLL(pllSS_TST_CNTL, rinfo->save_regs[91]);
/* The trace reads that one here, waiting for something to settle down ? */
INREG(RBBM_STATUS);
/* Ugh ? SS_TST_DEC is supposed to be a read register in the
* R300 register spec at least...
*/
tmp = INPLL(pllSS_TST_CNTL);
tmp |= 0x00400000;
OUTPLL(pllSS_TST_CNTL, tmp);
}
static void radeon_pm_restore_pixel_pll(struct radeonfb_info *rinfo)
{
u32 tmp;
OUTREG8(CLOCK_CNTL_INDEX, pllHTOTAL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA, 0);
radeon_pll_errata_after_data(rinfo);
tmp = INPLL(pllVCLK_ECP_CNTL);
OUTPLL(pllVCLK_ECP_CNTL, tmp | 0x80);
mdelay(5);
tmp = INPLL(pllPPLL_REF_DIV);
tmp = (tmp & ~PPLL_REF_DIV_MASK) | rinfo->pll.ref_div;
OUTPLL(pllPPLL_REF_DIV, tmp);
INPLL(pllPPLL_REF_DIV);
/* Reconfigure SPLL charge pump, VCO gain, duty cycle,
* probably useless since we already did it ...
*/
tmp = INPLL(pllPPLL_CNTL);
OUTREG8(CLOCK_CNTL_INDEX, pllSPLL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA + 1, (tmp >> 8) & 0xff);
radeon_pll_errata_after_data(rinfo);
/* Restore our "reference" PPLL divider set by firmware
* according to proper spread spectrum calculations
*/
OUTPLL(pllPPLL_DIV_0, rinfo->save_regs[92]);
tmp = INPLL(pllPPLL_CNTL);
OUTPLL(pllPPLL_CNTL, tmp & ~0x2);
mdelay(5);
tmp = INPLL(pllPPLL_CNTL);
OUTPLL(pllPPLL_CNTL, tmp & ~0x1);
mdelay(5);
tmp = INPLL(pllVCLK_ECP_CNTL);
OUTPLL(pllVCLK_ECP_CNTL, tmp | 3);
mdelay(5);
tmp = INPLL(pllVCLK_ECP_CNTL);
OUTPLL(pllVCLK_ECP_CNTL, tmp | 3);
mdelay(5);
/* Switch pixel clock to firmware default div 0 */
OUTREG8(CLOCK_CNTL_INDEX+1, 0);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
}
static void radeon_pm_m10_reconfigure_mc(struct radeonfb_info *rinfo)
{
OUTREG(MC_CNTL, rinfo->save_regs[46]);
OUTREG(MC_INIT_GFX_LAT_TIMER, rinfo->save_regs[47]);
OUTREG(MC_INIT_MISC_LAT_TIMER, rinfo->save_regs[48]);
OUTREG(MEM_SDRAM_MODE_REG,
rinfo->save_regs[35] & ~MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
OUTREG(MC_TIMING_CNTL, rinfo->save_regs[49]);
OUTREG(MEM_REFRESH_CNTL, rinfo->save_regs[42]);
OUTREG(MC_READ_CNTL_AB, rinfo->save_regs[50]);
OUTREG(MC_CHIP_IO_OE_CNTL_AB, rinfo->save_regs[52]);
OUTREG(MC_IOPAD_CNTL, rinfo->save_regs[51]);
OUTREG(MC_DEBUG, rinfo->save_regs[53]);
OUTMC(rinfo, ixR300_MC_MC_INIT_WR_LAT_TIMER, rinfo->save_regs[58]);
OUTMC(rinfo, ixR300_MC_IMP_CNTL, rinfo->save_regs[59]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_C0, rinfo->save_regs[60]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_C1, rinfo->save_regs[61]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_D0, rinfo->save_regs[62]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_D1, rinfo->save_regs[63]);
OUTMC(rinfo, ixR300_MC_BIST_CNTL_3, rinfo->save_regs[64]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_A0, rinfo->save_regs[65]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_A1, rinfo->save_regs[66]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_B0, rinfo->save_regs[67]);
OUTMC(rinfo, ixR300_MC_CHP_IO_CNTL_B1, rinfo->save_regs[68]);
OUTMC(rinfo, ixR300_MC_DEBUG_CNTL, rinfo->save_regs[69]);
OUTMC(rinfo, ixR300_MC_DLL_CNTL, rinfo->save_regs[70]);
OUTMC(rinfo, ixR300_MC_IMP_CNTL_0, rinfo->save_regs[71]);
OUTMC(rinfo, ixR300_MC_ELPIDA_CNTL, rinfo->save_regs[72]);
OUTMC(rinfo, ixR300_MC_READ_CNTL_CD, rinfo->save_regs[96]);
OUTREG(MC_IND_INDEX, 0);
}
static void radeon_reinitialize_M10(struct radeonfb_info *rinfo)
{
u32 tmp, i;
/* Restore a bunch of registers first */
OUTREG(MC_AGP_LOCATION, rinfo->save_regs[32]);
OUTREG(DISPLAY_BASE_ADDR, rinfo->save_regs[31]);
OUTREG(CRTC2_DISPLAY_BASE_ADDR, rinfo->save_regs[33]);
OUTREG(MC_FB_LOCATION, rinfo->save_regs[30]);
OUTREG(OV0_BASE_ADDR, rinfo->save_regs[80]);
OUTREG(CNFG_MEMSIZE, rinfo->video_ram);
OUTREG(BUS_CNTL, rinfo->save_regs[36]);
OUTREG(BUS_CNTL1, rinfo->save_regs[14]);
OUTREG(MPP_TB_CONFIG, rinfo->save_regs[37]);
OUTREG(FCP_CNTL, rinfo->save_regs[38]);
OUTREG(RBBM_CNTL, rinfo->save_regs[39]);
OUTREG(DAC_CNTL, rinfo->save_regs[40]);
OUTREG(DAC_MACRO_CNTL, (INREG(DAC_MACRO_CNTL) & ~0x6) | 8);
OUTREG(DAC_MACRO_CNTL, (INREG(DAC_MACRO_CNTL) & ~0x6) | 8);
/* Hrm... */
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) | DAC2_EXPAND_MODE);
/* Reset the PAD CTLR */
radeon_pm_reset_pad_ctlr_strength(rinfo);
/* Some PLLs are Read & written identically in the trace here...
* I suppose it's actually to switch them all off & reset,
* let's assume off is what we want. I'm just doing that for all major PLLs now.
*/
radeon_pm_all_ppls_off(rinfo);
/* Clear tiling, reset swappers */
INREG(SURFACE_CNTL);
OUTREG(SURFACE_CNTL, 0);
/* Some black magic with TV_DAC_CNTL, we should restore those from backups
* rather than hard coding...
*/
tmp = INREG(TV_DAC_CNTL) & ~TV_DAC_CNTL_BGADJ_MASK;
tmp |= 8 << TV_DAC_CNTL_BGADJ__SHIFT;
OUTREG(TV_DAC_CNTL, tmp);
tmp = INREG(TV_DAC_CNTL) & ~TV_DAC_CNTL_DACADJ_MASK;
tmp |= 7 << TV_DAC_CNTL_DACADJ__SHIFT;
OUTREG(TV_DAC_CNTL, tmp);
/* More registers restored */
OUTREG(AGP_CNTL, rinfo->save_regs[16]);
OUTREG(HOST_PATH_CNTL, rinfo->save_regs[41]);
OUTREG(DISP_MISC_CNTL, rinfo->save_regs[9]);
/* Hrmmm ... What is that ? */
tmp = rinfo->save_regs[1]
& ~(CLK_PWRMGT_CNTL__ACTIVE_HILO_LAT_MASK |
CLK_PWRMGT_CNTL__MC_BUSY);
OUTPLL(pllCLK_PWRMGT_CNTL, tmp);
OUTREG(PAD_CTLR_MISC, rinfo->save_regs[56]);
OUTREG(FW_CNTL, rinfo->save_regs[57]);
OUTREG(HDP_DEBUG, rinfo->save_regs[96]);
OUTREG(PAMAC0_DLY_CNTL, rinfo->save_regs[54]);
OUTREG(PAMAC1_DLY_CNTL, rinfo->save_regs[55]);
OUTREG(PAMAC2_DLY_CNTL, rinfo->save_regs[79]);
/* Restore Memory Controller configuration */
radeon_pm_m10_reconfigure_mc(rinfo);
/* Make sure CRTC's dont touch memory */
OUTREG(CRTC_GEN_CNTL, INREG(CRTC_GEN_CNTL)
| CRTC_GEN_CNTL__CRTC_DISP_REQ_EN_B);
OUTREG(CRTC2_GEN_CNTL, INREG(CRTC2_GEN_CNTL)
| CRTC2_GEN_CNTL__CRTC2_DISP_REQ_EN_B);
mdelay(30);
/* Disable SDRAM refresh */
OUTREG(MEM_REFRESH_CNTL, INREG(MEM_REFRESH_CNTL)
| MEM_REFRESH_CNTL__MEM_REFRESH_DIS);
/* Restore XTALIN routing (CLK_PIN_CNTL) */
OUTPLL(pllCLK_PIN_CNTL, rinfo->save_regs[4]);
/* Switch MCLK, YCLK and SCLK PLLs to PCI source & force them ON */
tmp = rinfo->save_regs[2] & 0xff000000;
tmp |= MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_MCLKB |
MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB |
MCLK_CNTL__FORCE_MC;
OUTPLL(pllMCLK_CNTL, tmp);
/* Force all clocks on in SCLK */
tmp = INPLL(pllSCLK_CNTL);
tmp |= SCLK_CNTL__FORCE_DISP2|
SCLK_CNTL__FORCE_CP|
SCLK_CNTL__FORCE_HDP|
SCLK_CNTL__FORCE_DISP1|
SCLK_CNTL__FORCE_TOP|
SCLK_CNTL__FORCE_E2|
SCLK_CNTL__FORCE_SE|
SCLK_CNTL__FORCE_IDCT|
SCLK_CNTL__FORCE_VIP|
SCLK_CNTL__FORCE_PB|
SCLK_CNTL__FORCE_TAM|
SCLK_CNTL__FORCE_TDM|
SCLK_CNTL__FORCE_RB|
SCLK_CNTL__FORCE_TV_SCLK|
SCLK_CNTL__FORCE_SUBPIC|
SCLK_CNTL__FORCE_OV0;
tmp |= SCLK_CNTL__CP_MAX_DYN_STOP_LAT |
SCLK_CNTL__HDP_MAX_DYN_STOP_LAT |
SCLK_CNTL__TV_MAX_DYN_STOP_LAT |
SCLK_CNTL__E2_MAX_DYN_STOP_LAT |
SCLK_CNTL__SE_MAX_DYN_STOP_LAT |
SCLK_CNTL__IDCT_MAX_DYN_STOP_LAT|
SCLK_CNTL__VIP_MAX_DYN_STOP_LAT |
SCLK_CNTL__RE_MAX_DYN_STOP_LAT |
SCLK_CNTL__PB_MAX_DYN_STOP_LAT |
SCLK_CNTL__TAM_MAX_DYN_STOP_LAT |
SCLK_CNTL__TDM_MAX_DYN_STOP_LAT |
SCLK_CNTL__RB_MAX_DYN_STOP_LAT;
OUTPLL(pllSCLK_CNTL, tmp);
OUTPLL(pllVCLK_ECP_CNTL, 0);
OUTPLL(pllPIXCLKS_CNTL, 0);
OUTPLL(pllMCLK_MISC,
MCLK_MISC__MC_MCLK_MAX_DYN_STOP_LAT |
MCLK_MISC__IO_MCLK_MAX_DYN_STOP_LAT);
mdelay(5);
/* Restore the M_SPLL_REF_FB_DIV, MPLL_AUX_CNTL and SPLL_AUX_CNTL values */
OUTPLL(pllM_SPLL_REF_FB_DIV, rinfo->save_regs[77]);
OUTPLL(pllMPLL_AUX_CNTL, rinfo->save_regs[75]);
OUTPLL(pllSPLL_AUX_CNTL, rinfo->save_regs[76]);
/* Now restore the major PLLs settings, keeping them off & reset though */
OUTPLL(pllPPLL_CNTL, rinfo->save_regs[93] | 0x3);
OUTPLL(pllP2PLL_CNTL, rinfo->save_regs[8] | 0x3);
OUTPLL(pllMPLL_CNTL, rinfo->save_regs[73] | 0x03);
OUTPLL(pllSPLL_CNTL, rinfo->save_regs[74] | 0x03);
/* Restore MC DLL state and switch it off/reset too */
OUTMC(rinfo, ixR300_MC_DLL_CNTL, rinfo->save_regs[70]);
/* Switch MDLL off & reset */
OUTPLL(pllMDLL_RDCKA, rinfo->save_regs[98] | 0xff);
mdelay(5);
/* Setup some black magic bits in PLL_PWRMGT_CNTL. Hrm... we saved
* 0xa1100007... and MacOS writes 0xa1000007 ..
*/
OUTPLL(pllPLL_PWRMGT_CNTL, rinfo->save_regs[0]);
/* Restore more stuffs */
OUTPLL(pllHTOTAL_CNTL, 0);
OUTPLL(pllHTOTAL2_CNTL, 0);
/* More PLL initial configuration */
tmp = INPLL(pllSCLK_CNTL2); /* What for ? */
OUTPLL(pllSCLK_CNTL2, tmp);
tmp = INPLL(pllSCLK_MORE_CNTL);
tmp |= SCLK_MORE_CNTL__FORCE_DISPREGS | /* a guess */
SCLK_MORE_CNTL__FORCE_MC_GUI |
SCLK_MORE_CNTL__FORCE_MC_HOST;
OUTPLL(pllSCLK_MORE_CNTL, tmp);
/* Now we actually start MCLK and SCLK */
radeon_pm_start_mclk_sclk(rinfo);
/* Full reset sdrams, this also re-inits the MDLL */
radeon_pm_full_reset_sdram(rinfo);
/* Fill palettes */
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) | 0x20);
for (i=0; i<256; i++)
OUTREG(PALETTE_30_DATA, 0x15555555);
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) & ~20);
udelay(20);
for (i=0; i<256; i++)
OUTREG(PALETTE_30_DATA, 0x15555555);
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) & ~0x20);
mdelay(3);
/* Restore TMDS */
OUTREG(FP_GEN_CNTL, rinfo->save_regs[82]);
OUTREG(FP2_GEN_CNTL, rinfo->save_regs[83]);
/* Set LVDS registers but keep interface & pll down */
OUTREG(LVDS_GEN_CNTL, rinfo->save_regs[11] &
~(LVDS_EN | LVDS_ON | LVDS_DIGON | LVDS_BLON | LVDS_BL_MOD_EN));
OUTREG(LVDS_PLL_CNTL, (rinfo->save_regs[12] & ~0xf0000) | 0x20000);
OUTREG(DISP_OUTPUT_CNTL, rinfo->save_regs[86]);
/* Restore GPIOPAD state */
OUTREG(GPIOPAD_A, rinfo->save_regs[19]);
OUTREG(GPIOPAD_EN, rinfo->save_regs[20]);
OUTREG(GPIOPAD_MASK, rinfo->save_regs[21]);
/* write some stuff to the framebuffer... */
for (i = 0; i < 0x8000; ++i)
writeb(0, rinfo->fb_base + i);
mdelay(40);
OUTREG(LVDS_GEN_CNTL, INREG(LVDS_GEN_CNTL) | LVDS_DIGON | LVDS_ON);
mdelay(40);
/* Restore a few more things */
OUTREG(GRPH_BUFFER_CNTL, rinfo->save_regs[94]);
OUTREG(GRPH2_BUFFER_CNTL, rinfo->save_regs[95]);
/* Take care of spread spectrum & PPLLs now */
radeon_pm_m10_disable_spread_spectrum(rinfo);
radeon_pm_restore_pixel_pll(rinfo);
/* GRRRR... I can't figure out the proper LVDS power sequence, and the
* code I have for blank/unblank doesn't quite work on some laptop models
* it seems ... Hrm. What I have here works most of the time ...
*/
radeon_pm_m10_enable_lvds_spread_spectrum(rinfo);
}
#ifdef CONFIG_PPC_OF
static void radeon_pm_m9p_reconfigure_mc(struct radeonfb_info *rinfo)
{
OUTREG(MC_CNTL, rinfo->save_regs[46]);
OUTREG(MC_INIT_GFX_LAT_TIMER, rinfo->save_regs[47]);
OUTREG(MC_INIT_MISC_LAT_TIMER, rinfo->save_regs[48]);
OUTREG(MEM_SDRAM_MODE_REG,
rinfo->save_regs[35] & ~MEM_SDRAM_MODE_REG__MC_INIT_COMPLETE);
OUTREG(MC_TIMING_CNTL, rinfo->save_regs[49]);
OUTREG(MC_READ_CNTL_AB, rinfo->save_regs[50]);
OUTREG(MEM_REFRESH_CNTL, rinfo->save_regs[42]);
OUTREG(MC_IOPAD_CNTL, rinfo->save_regs[51]);
OUTREG(MC_DEBUG, rinfo->save_regs[53]);
OUTREG(MC_CHIP_IO_OE_CNTL_AB, rinfo->save_regs[52]);
OUTMC(rinfo, ixMC_IMP_CNTL, rinfo->save_regs[59] /*0x00f460d6*/);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_A0, rinfo->save_regs[65] /*0xfecfa666*/);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_A1, rinfo->save_regs[66] /*0x141555ff*/);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_B0, rinfo->save_regs[67] /*0xfecfa666*/);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_B1, rinfo->save_regs[68] /*0x141555ff*/);
OUTMC(rinfo, ixMC_IMP_CNTL_0, rinfo->save_regs[71] /*0x00009249*/);
OUTREG(MC_IND_INDEX, 0);
OUTREG(CNFG_MEMSIZE, rinfo->video_ram);
mdelay(20);
}
static void radeon_reinitialize_M9P(struct radeonfb_info *rinfo)
{
u32 tmp, i;
/* Restore a bunch of registers first */
OUTREG(SURFACE_CNTL, rinfo->save_regs[29]);
OUTREG(MC_AGP_LOCATION, rinfo->save_regs[32]);
OUTREG(DISPLAY_BASE_ADDR, rinfo->save_regs[31]);
OUTREG(CRTC2_DISPLAY_BASE_ADDR, rinfo->save_regs[33]);
OUTREG(MC_FB_LOCATION, rinfo->save_regs[30]);
OUTREG(OV0_BASE_ADDR, rinfo->save_regs[80]);
OUTREG(BUS_CNTL, rinfo->save_regs[36]);
OUTREG(BUS_CNTL1, rinfo->save_regs[14]);
OUTREG(MPP_TB_CONFIG, rinfo->save_regs[37]);
OUTREG(FCP_CNTL, rinfo->save_regs[38]);
OUTREG(RBBM_CNTL, rinfo->save_regs[39]);
OUTREG(DAC_CNTL, rinfo->save_regs[40]);
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) | DAC2_EXPAND_MODE);
/* Reset the PAD CTLR */
radeon_pm_reset_pad_ctlr_strength(rinfo);
/* Some PLLs are Read & written identically in the trace here...
* I suppose it's actually to switch them all off & reset,
* let's assume off is what we want. I'm just doing that for all major PLLs now.
*/
radeon_pm_all_ppls_off(rinfo);
/* Clear tiling, reset swappers */
INREG(SURFACE_CNTL);
OUTREG(SURFACE_CNTL, 0);
/* Some black magic with TV_DAC_CNTL, we should restore those from backups
* rather than hard coding...
*/
tmp = INREG(TV_DAC_CNTL) & ~TV_DAC_CNTL_BGADJ_MASK;
tmp |= 6 << TV_DAC_CNTL_BGADJ__SHIFT;
OUTREG(TV_DAC_CNTL, tmp);
tmp = INREG(TV_DAC_CNTL) & ~TV_DAC_CNTL_DACADJ_MASK;
tmp |= 6 << TV_DAC_CNTL_DACADJ__SHIFT;
OUTREG(TV_DAC_CNTL, tmp);
OUTPLL(pllAGP_PLL_CNTL, rinfo->save_regs[78]);
OUTREG(PAMAC0_DLY_CNTL, rinfo->save_regs[54]);
OUTREG(PAMAC1_DLY_CNTL, rinfo->save_regs[55]);
OUTREG(PAMAC2_DLY_CNTL, rinfo->save_regs[79]);
OUTREG(AGP_CNTL, rinfo->save_regs[16]);
OUTREG(HOST_PATH_CNTL, rinfo->save_regs[41]); /* MacOS sets that to 0 !!! */
OUTREG(DISP_MISC_CNTL, rinfo->save_regs[9]);
tmp = rinfo->save_regs[1]
& ~(CLK_PWRMGT_CNTL__ACTIVE_HILO_LAT_MASK |
CLK_PWRMGT_CNTL__MC_BUSY);
OUTPLL(pllCLK_PWRMGT_CNTL, tmp);
OUTREG(FW_CNTL, rinfo->save_regs[57]);
/* Disable SDRAM refresh */
OUTREG(MEM_REFRESH_CNTL, INREG(MEM_REFRESH_CNTL)
| MEM_REFRESH_CNTL__MEM_REFRESH_DIS);
/* Restore XTALIN routing (CLK_PIN_CNTL) */
OUTPLL(pllCLK_PIN_CNTL, rinfo->save_regs[4]);
/* Force MCLK to be PCI sourced and forced ON */
tmp = rinfo->save_regs[2] & 0xff000000;
tmp |= MCLK_CNTL__FORCE_MCLKA |
MCLK_CNTL__FORCE_MCLKB |
MCLK_CNTL__FORCE_YCLKA |
MCLK_CNTL__FORCE_YCLKB |
MCLK_CNTL__FORCE_MC |
MCLK_CNTL__FORCE_AIC;
OUTPLL(pllMCLK_CNTL, tmp);
/* Force SCLK to be PCI sourced with a bunch forced */
tmp = 0 |
SCLK_CNTL__FORCE_DISP2|
SCLK_CNTL__FORCE_CP|
SCLK_CNTL__FORCE_HDP|
SCLK_CNTL__FORCE_DISP1|
SCLK_CNTL__FORCE_TOP|
SCLK_CNTL__FORCE_E2|
SCLK_CNTL__FORCE_SE|
SCLK_CNTL__FORCE_IDCT|
SCLK_CNTL__FORCE_VIP|
SCLK_CNTL__FORCE_RE|
SCLK_CNTL__FORCE_PB|
SCLK_CNTL__FORCE_TAM|
SCLK_CNTL__FORCE_TDM|
SCLK_CNTL__FORCE_RB;
OUTPLL(pllSCLK_CNTL, tmp);
/* Clear VCLK_ECP_CNTL & PIXCLKS_CNTL */
OUTPLL(pllVCLK_ECP_CNTL, 0);
OUTPLL(pllPIXCLKS_CNTL, 0);
/* Setup MCLK_MISC, non dynamic mode */
OUTPLL(pllMCLK_MISC,
MCLK_MISC__MC_MCLK_MAX_DYN_STOP_LAT |
MCLK_MISC__IO_MCLK_MAX_DYN_STOP_LAT);
mdelay(5);
/* Set back the default clock dividers */
OUTPLL(pllM_SPLL_REF_FB_DIV, rinfo->save_regs[77]);
OUTPLL(pllMPLL_AUX_CNTL, rinfo->save_regs[75]);
OUTPLL(pllSPLL_AUX_CNTL, rinfo->save_regs[76]);
/* PPLL and P2PLL default values & off */
OUTPLL(pllPPLL_CNTL, rinfo->save_regs[93] | 0x3);
OUTPLL(pllP2PLL_CNTL, rinfo->save_regs[8] | 0x3);
/* S and M PLLs are reset & off, configure them */
OUTPLL(pllMPLL_CNTL, rinfo->save_regs[73] | 0x03);
OUTPLL(pllSPLL_CNTL, rinfo->save_regs[74] | 0x03);
/* Default values for MDLL ... fixme */
OUTPLL(pllMDLL_CKO, 0x9c009c);
OUTPLL(pllMDLL_RDCKA, 0x08830883);
OUTPLL(pllMDLL_RDCKB, 0x08830883);
mdelay(5);
/* Restore PLL_PWRMGT_CNTL */ // XXXX
tmp = rinfo->save_regs[0];
tmp &= ~PLL_PWRMGT_CNTL_SU_SCLK_USE_BCLK;
tmp |= PLL_PWRMGT_CNTL_SU_MCLK_USE_BCLK;
OUTPLL(PLL_PWRMGT_CNTL, tmp);
/* Clear HTOTAL_CNTL & HTOTAL2_CNTL */
OUTPLL(pllHTOTAL_CNTL, 0);
OUTPLL(pllHTOTAL2_CNTL, 0);
/* All outputs off */
OUTREG(CRTC_GEN_CNTL, 0x04000000);
OUTREG(CRTC2_GEN_CNTL, 0x04000000);
OUTREG(FP_GEN_CNTL, 0x00004008);
OUTREG(FP2_GEN_CNTL, 0x00000008);
OUTREG(LVDS_GEN_CNTL, 0x08000008);
/* Restore Memory Controller configuration */
radeon_pm_m9p_reconfigure_mc(rinfo);
/* Now we actually start MCLK and SCLK */
radeon_pm_start_mclk_sclk(rinfo);
/* Full reset sdrams, this also re-inits the MDLL */
radeon_pm_full_reset_sdram(rinfo);
/* Fill palettes */
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) | 0x20);
for (i=0; i<256; i++)
OUTREG(PALETTE_30_DATA, 0x15555555);
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) & ~20);
udelay(20);
for (i=0; i<256; i++)
OUTREG(PALETTE_30_DATA, 0x15555555);
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) & ~0x20);
mdelay(3);
/* Restore TV stuff, make sure TV DAC is down */
OUTREG(TV_MASTER_CNTL, rinfo->save_regs[88]);
OUTREG(TV_DAC_CNTL, rinfo->save_regs[13] | 0x07000000);
/* Restore GPIOS. MacOS does some magic here with one of the GPIO bits,
* possibly related to the weird PLL related workarounds and to the
* fact that CLK_PIN_CNTL is tweaked in ways I don't fully understand,
* but we keep things the simple way here
*/
OUTREG(GPIOPAD_A, rinfo->save_regs[19]);
OUTREG(GPIOPAD_EN, rinfo->save_regs[20]);
OUTREG(GPIOPAD_MASK, rinfo->save_regs[21]);
/* Now do things with SCLK_MORE_CNTL. Force bits are already set, copy
* high bits from backup
*/
tmp = INPLL(pllSCLK_MORE_CNTL) & 0x0000ffff;
tmp |= rinfo->save_regs[34] & 0xffff0000;
tmp |= SCLK_MORE_CNTL__FORCE_DISPREGS;
OUTPLL(pllSCLK_MORE_CNTL, tmp);
tmp = INPLL(pllSCLK_MORE_CNTL) & 0x0000ffff;
tmp |= rinfo->save_regs[34] & 0xffff0000;
tmp |= SCLK_MORE_CNTL__FORCE_DISPREGS;
OUTPLL(pllSCLK_MORE_CNTL, tmp);
OUTREG(LVDS_GEN_CNTL, rinfo->save_regs[11] &
~(LVDS_EN | LVDS_ON | LVDS_DIGON | LVDS_BLON | LVDS_BL_MOD_EN));
OUTREG(LVDS_GEN_CNTL, INREG(LVDS_GEN_CNTL) | LVDS_BLON);
OUTREG(LVDS_PLL_CNTL, (rinfo->save_regs[12] & ~0xf0000) | 0x20000);
mdelay(20);
/* write some stuff to the framebuffer... */
for (i = 0; i < 0x8000; ++i)
writeb(0, rinfo->fb_base + i);
OUTREG(0x2ec, 0x6332a020);
OUTPLL(pllSSPLL_REF_DIV, rinfo->save_regs[44] /*0x3f */);
OUTPLL(pllSSPLL_DIV_0, rinfo->save_regs[45] /*0x000081bb */);
tmp = INPLL(pllSSPLL_CNTL);
tmp &= ~2;
OUTPLL(pllSSPLL_CNTL, tmp);
mdelay(6);
tmp &= ~1;
OUTPLL(pllSSPLL_CNTL, tmp);
mdelay(5);
tmp |= 3;
OUTPLL(pllSSPLL_CNTL, tmp);
mdelay(5);
OUTPLL(pllSS_INT_CNTL, rinfo->save_regs[90] & ~3);/*0x0020300c*/
OUTREG(0x2ec, 0x6332a3f0);
mdelay(17);
OUTPLL(pllPPLL_REF_DIV, rinfo->pll.ref_div);
OUTPLL(pllPPLL_DIV_0, rinfo->save_regs[92]);
mdelay(40);
OUTREG(LVDS_GEN_CNTL, INREG(LVDS_GEN_CNTL) | LVDS_DIGON | LVDS_ON);
mdelay(40);
/* Restore a few more things */
OUTREG(GRPH_BUFFER_CNTL, rinfo->save_regs[94]);
OUTREG(GRPH2_BUFFER_CNTL, rinfo->save_regs[95]);
/* Restore PPLL, spread spectrum & LVDS */
radeon_pm_m10_disable_spread_spectrum(rinfo);
radeon_pm_restore_pixel_pll(rinfo);
radeon_pm_m10_enable_lvds_spread_spectrum(rinfo);
}
#if 0 /* Not ready yet */
static void radeon_reinitialize_QW(struct radeonfb_info *rinfo)
{
int i;
u32 tmp, tmp2;
u32 cko, cka, ckb;
u32 cgc, cec, c2gc;
OUTREG(MC_AGP_LOCATION, rinfo->save_regs[32]);
OUTREG(DISPLAY_BASE_ADDR, rinfo->save_regs[31]);
OUTREG(CRTC2_DISPLAY_BASE_ADDR, rinfo->save_regs[33]);
OUTREG(MC_FB_LOCATION, rinfo->save_regs[30]);
OUTREG(BUS_CNTL, rinfo->save_regs[36]);
OUTREG(RBBM_CNTL, rinfo->save_regs[39]);
INREG(PAD_CTLR_STRENGTH);
OUTREG(PAD_CTLR_STRENGTH, INREG(PAD_CTLR_STRENGTH) & ~0x10000);
for (i = 0; i < 65; ++i) {
mdelay(1);
INREG(PAD_CTLR_STRENGTH);
}
OUTREG(DISP_TEST_DEBUG_CNTL, INREG(DISP_TEST_DEBUG_CNTL) | 0x10000000);
OUTREG(OV0_FLAG_CNTRL, INREG(OV0_FLAG_CNTRL) | 0x100);
OUTREG(CRTC_GEN_CNTL, INREG(CRTC_GEN_CNTL));
OUTREG(DAC_CNTL, 0xff00410a);
OUTREG(CRTC2_GEN_CNTL, INREG(CRTC2_GEN_CNTL));
OUTREG(DAC_CNTL2, INREG(DAC_CNTL2) | 0x4000);
OUTREG(SURFACE_CNTL, rinfo->save_regs[29]);
OUTREG(AGP_CNTL, rinfo->save_regs[16]);
OUTREG(HOST_PATH_CNTL, rinfo->save_regs[41]);
OUTREG(DISP_MISC_CNTL, rinfo->save_regs[9]);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_A0, 0xf7bb4433);
OUTREG(MC_IND_INDEX, 0);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_B0, 0xf7bb4433);
OUTREG(MC_IND_INDEX, 0);
OUTREG(CRTC_MORE_CNTL, INREG(CRTC_MORE_CNTL));
tmp = INPLL(pllVCLK_ECP_CNTL);
OUTPLL(pllVCLK_ECP_CNTL, tmp);
tmp = INPLL(pllPIXCLKS_CNTL);
OUTPLL(pllPIXCLKS_CNTL, tmp);
OUTPLL(MCLK_CNTL, 0xaa3f0000);
OUTPLL(SCLK_CNTL, 0xffff0000);
OUTPLL(pllMPLL_AUX_CNTL, 6);
OUTPLL(pllSPLL_AUX_CNTL, 1);
OUTPLL(MDLL_CKO, 0x9f009f);
OUTPLL(MDLL_RDCKA, 0x830083);
OUTPLL(pllMDLL_RDCKB, 0x830083);
OUTPLL(PPLL_CNTL, 0xa433);
OUTPLL(P2PLL_CNTL, 0xa433);
OUTPLL(MPLL_CNTL, 0x0400a403);
OUTPLL(SPLL_CNTL, 0x0400a433);
tmp = INPLL(M_SPLL_REF_FB_DIV);
OUTPLL(M_SPLL_REF_FB_DIV, tmp);
tmp = INPLL(M_SPLL_REF_FB_DIV);
OUTPLL(M_SPLL_REF_FB_DIV, tmp | 0xc);
INPLL(M_SPLL_REF_FB_DIV);
tmp = INPLL(MPLL_CNTL);
OUTREG8(CLOCK_CNTL_INDEX, MPLL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA + 1, (tmp >> 8) & 0xff);
radeon_pll_errata_after_data(rinfo);
tmp = INPLL(M_SPLL_REF_FB_DIV);
OUTPLL(M_SPLL_REF_FB_DIV, tmp | 0x5900);
tmp = INPLL(MPLL_CNTL);
OUTPLL(MPLL_CNTL, tmp & ~0x2);
mdelay(1);
tmp = INPLL(MPLL_CNTL);
OUTPLL(MPLL_CNTL, tmp & ~0x1);
mdelay(10);
OUTPLL(MCLK_CNTL, 0xaa3f1212);
mdelay(1);
INPLL(M_SPLL_REF_FB_DIV);
INPLL(MCLK_CNTL);
INPLL(M_SPLL_REF_FB_DIV);
tmp = INPLL(SPLL_CNTL);
OUTREG8(CLOCK_CNTL_INDEX, SPLL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA + 1, (tmp >> 8) & 0xff);
radeon_pll_errata_after_data(rinfo);
tmp = INPLL(M_SPLL_REF_FB_DIV);
OUTPLL(M_SPLL_REF_FB_DIV, tmp | 0x780000);
tmp = INPLL(SPLL_CNTL);
OUTPLL(SPLL_CNTL, tmp & ~0x1);
mdelay(1);
tmp = INPLL(SPLL_CNTL);
OUTPLL(SPLL_CNTL, tmp & ~0x2);
mdelay(10);
tmp = INPLL(SCLK_CNTL);
OUTPLL(SCLK_CNTL, tmp | 2);
mdelay(1);
cko = INPLL(pllMDLL_CKO);
cka = INPLL(pllMDLL_RDCKA);
ckb = INPLL(pllMDLL_RDCKB);
cko &= ~(MDLL_CKO__MCKOA_SLEEP | MDLL_CKO__MCKOB_SLEEP);
OUTPLL(pllMDLL_CKO, cko);
mdelay(1);
cko &= ~(MDLL_CKO__MCKOA_RESET | MDLL_CKO__MCKOB_RESET);
OUTPLL(pllMDLL_CKO, cko);
mdelay(5);
cka &= ~(MDLL_RDCKA__MRDCKA0_SLEEP | MDLL_RDCKA__MRDCKA1_SLEEP);
OUTPLL(pllMDLL_RDCKA, cka);
mdelay(1);
cka &= ~(MDLL_RDCKA__MRDCKA0_RESET | MDLL_RDCKA__MRDCKA1_RESET);
OUTPLL(pllMDLL_RDCKA, cka);
mdelay(5);
ckb &= ~(MDLL_RDCKB__MRDCKB0_SLEEP | MDLL_RDCKB__MRDCKB1_SLEEP);
OUTPLL(pllMDLL_RDCKB, ckb);
mdelay(1);
ckb &= ~(MDLL_RDCKB__MRDCKB0_RESET | MDLL_RDCKB__MRDCKB1_RESET);
OUTPLL(pllMDLL_RDCKB, ckb);
mdelay(5);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_A1, 0x151550ff);
OUTREG(MC_IND_INDEX, 0);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_B1, 0x151550ff);
OUTREG(MC_IND_INDEX, 0);
mdelay(1);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_A1, 0x141550ff);
OUTREG(MC_IND_INDEX, 0);
OUTMC(rinfo, ixMC_CHP_IO_CNTL_B1, 0x141550ff);
OUTREG(MC_IND_INDEX, 0);
mdelay(1);
OUTPLL(pllHTOTAL_CNTL, 0);
OUTPLL(pllHTOTAL2_CNTL, 0);
OUTREG(MEM_CNTL, 0x29002901);
OUTREG(MEM_SDRAM_MODE_REG, 0x45320032); /* XXX use save_regs[35]? */
OUTREG(EXT_MEM_CNTL, 0x1a394333);
OUTREG(MEM_IO_CNTL_A1, 0x0aac0aac);
OUTREG(MEM_INIT_LATENCY_TIMER, 0x34444444);
OUTREG(MEM_REFRESH_CNTL, 0x1f1f7218); /* XXX or save_regs[42]? */
OUTREG(MC_DEBUG, 0);
OUTREG(MEM_IO_OE_CNTL, 0x04300430);
OUTMC(rinfo, ixMC_IMP_CNTL, 0x00f460d6);
OUTREG(MC_IND_INDEX, 0);
OUTMC(rinfo, ixMC_IMP_CNTL_0, 0x00009249);
OUTREG(MC_IND_INDEX, 0);
OUTREG(CNFG_MEMSIZE, rinfo->video_ram);
radeon_pm_full_reset_sdram(rinfo);
INREG(FP_GEN_CNTL);
OUTREG(TMDS_CNTL, 0x01000000); /* XXX ? */
tmp = INREG(FP_GEN_CNTL);
tmp |= FP_CRTC_DONT_SHADOW_HEND | FP_CRTC_DONT_SHADOW_VPAR | 0x200;
OUTREG(FP_GEN_CNTL, tmp);
tmp = INREG(DISP_OUTPUT_CNTL);
tmp &= ~0x400;
OUTREG(DISP_OUTPUT_CNTL, tmp);
OUTPLL(CLK_PIN_CNTL, rinfo->save_regs[4]);
OUTPLL(CLK_PWRMGT_CNTL, rinfo->save_regs[1]);
OUTPLL(PLL_PWRMGT_CNTL, rinfo->save_regs[0]);
tmp = INPLL(MCLK_MISC);
tmp |= MCLK_MISC__MC_MCLK_DYN_ENABLE | MCLK_MISC__IO_MCLK_DYN_ENABLE;
OUTPLL(MCLK_MISC, tmp);
tmp = INPLL(SCLK_CNTL);
OUTPLL(SCLK_CNTL, tmp);
OUTREG(CRTC_MORE_CNTL, 0);
OUTREG8(CRTC_GEN_CNTL+1, 6);
OUTREG8(CRTC_GEN_CNTL+3, 1);
OUTREG(CRTC_PITCH, 32);
tmp = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL, tmp);
tmp = INPLL(PPLL_CNTL);
OUTPLL(PPLL_CNTL, tmp);
/* palette stuff and BIOS_1_SCRATCH... */
tmp = INREG(FP_GEN_CNTL);
tmp2 = INREG(TMDS_TRANSMITTER_CNTL);
tmp |= 2;
OUTREG(FP_GEN_CNTL, tmp);
mdelay(5);
OUTREG(FP_GEN_CNTL, tmp);
mdelay(5);
OUTREG(TMDS_TRANSMITTER_CNTL, tmp2);
OUTREG(CRTC_MORE_CNTL, 0);
mdelay(20);
tmp = INREG(CRTC_MORE_CNTL);
OUTREG(CRTC_MORE_CNTL, tmp);
cgc = INREG(CRTC_GEN_CNTL);
cec = INREG(CRTC_EXT_CNTL);
c2gc = INREG(CRTC2_GEN_CNTL);
OUTREG(CRTC_H_SYNC_STRT_WID, 0x008e0580);
OUTREG(CRTC_H_TOTAL_DISP, 0x009f00d2);
OUTREG8(CLOCK_CNTL_INDEX, HTOTAL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA, 0);
radeon_pll_errata_after_data(rinfo);
OUTREG(CRTC_V_SYNC_STRT_WID, 0x00830403);
OUTREG(CRTC_V_TOTAL_DISP, 0x03ff0429);
OUTREG(FP_CRTC_H_TOTAL_DISP, 0x009f0033);
OUTREG(FP_H_SYNC_STRT_WID, 0x008e0080);
OUTREG(CRT_CRTC_H_SYNC_STRT_WID, 0x008e0080);
OUTREG(FP_CRTC_V_TOTAL_DISP, 0x03ff002a);
OUTREG(FP_V_SYNC_STRT_WID, 0x00830004);
OUTREG(CRT_CRTC_V_SYNC_STRT_WID, 0x00830004);
OUTREG(FP_HORZ_VERT_ACTIVE, 0x009f03ff);
OUTREG(FP_HORZ_STRETCH, 0);
OUTREG(FP_VERT_STRETCH, 0);
OUTREG(OVR_CLR, 0);
OUTREG(OVR_WID_LEFT_RIGHT, 0);
OUTREG(OVR_WID_TOP_BOTTOM, 0);
tmp = INPLL(PPLL_REF_DIV);
tmp = (tmp & ~PPLL_REF_DIV_MASK) | rinfo->pll.ref_div;
OUTPLL(PPLL_REF_DIV, tmp);
INPLL(PPLL_REF_DIV);
OUTREG8(CLOCK_CNTL_INDEX, PPLL_CNTL + PLL_WR_EN);
radeon_pll_errata_after_index(rinfo);
OUTREG8(CLOCK_CNTL_DATA + 1, 0xbc);
radeon_pll_errata_after_data(rinfo);
tmp = INREG(CLOCK_CNTL_INDEX);
radeon_pll_errata_after_index(rinfo);
OUTREG(CLOCK_CNTL_INDEX, tmp & 0xff);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
OUTPLL(PPLL_DIV_0, 0x48090);
tmp = INPLL(PPLL_CNTL);
OUTPLL(PPLL_CNTL, tmp & ~0x2);
mdelay(1);
tmp = INPLL(PPLL_CNTL);
OUTPLL(PPLL_CNTL, tmp & ~0x1);
mdelay(10);
tmp = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL, tmp | 3);
mdelay(1);
tmp = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL, tmp);
c2gc |= CRTC2_DISP_REQ_EN_B;
OUTREG(CRTC2_GEN_CNTL, c2gc);
cgc |= CRTC_EN;
OUTREG(CRTC_GEN_CNTL, cgc);
OUTREG(CRTC_EXT_CNTL, cec);
OUTREG(CRTC_PITCH, 0xa0);
OUTREG(CRTC_OFFSET, 0);
OUTREG(CRTC_OFFSET_CNTL, 0);
OUTREG(GRPH_BUFFER_CNTL, 0x20117c7c);
OUTREG(GRPH2_BUFFER_CNTL, 0x00205c5c);
tmp2 = INREG(FP_GEN_CNTL);
tmp = INREG(TMDS_TRANSMITTER_CNTL);
OUTREG(0x2a8, 0x0000061b);
tmp |= TMDS_PLL_EN;
OUTREG(TMDS_TRANSMITTER_CNTL, tmp);
mdelay(1);
tmp &= ~TMDS_PLLRST;
OUTREG(TMDS_TRANSMITTER_CNTL, tmp);
tmp2 &= ~2;
tmp2 |= FP_TMDS_EN;
OUTREG(FP_GEN_CNTL, tmp2);
mdelay(5);
tmp2 |= FP_FPON;
OUTREG(FP_GEN_CNTL, tmp2);
OUTREG(CUR_HORZ_VERT_OFF, CUR_LOCK | 1);
cgc = INREG(CRTC_GEN_CNTL);
OUTREG(CUR_HORZ_VERT_POSN, 0xbfff0fff);
cgc |= 0x10000;
OUTREG(CUR_OFFSET, 0);
}
#endif /* 0 */
#endif /* CONFIG_PPC_OF */
static void radeonfb_whack_power_state(struct radeonfb_info *rinfo, pci_power_t state)
{
u16 pwr_cmd;
for (;;) {
pci_read_config_word(rinfo->pdev,
rinfo->pm_reg+PCI_PM_CTRL,
&pwr_cmd);
if (pwr_cmd & 2)
break;
pwr_cmd = (pwr_cmd & ~PCI_PM_CTRL_STATE_MASK) | 2;
pci_write_config_word(rinfo->pdev,
rinfo->pm_reg+PCI_PM_CTRL,
pwr_cmd);
msleep(500);
}
rinfo->pdev->current_state = state;
}
static void radeon_set_suspend(struct radeonfb_info *rinfo, int suspend)
{
u32 tmp;
if (!rinfo->pm_reg)
return;
/* Set the chip into appropriate suspend mode (we use D2,
* D3 would require a compete re-initialization of the chip,
* including PCI config registers, clocks, AGP conf, ...)
*/
if (suspend) {
printk(KERN_DEBUG "radeonfb (%s): switching to D2 state...\n",
pci_name(rinfo->pdev));
/* Disable dynamic power management of clocks for the
* duration of the suspend/resume process
*/
radeon_pm_disable_dynamic_mode(rinfo);
/* Save some registers */
radeon_pm_save_regs(rinfo, 0);
/* Prepare mobility chips for suspend.
*/
if (rinfo->is_mobility) {
/* Program V2CLK */
radeon_pm_program_v2clk(rinfo);
/* Disable IO PADs */
radeon_pm_disable_iopad(rinfo);
/* Set low current */
radeon_pm_low_current(rinfo);
/* Prepare chip for power management */
radeon_pm_setup_for_suspend(rinfo);
if (rinfo->family <= CHIP_FAMILY_RV280) {
/* Reset the MDLL */
/* because both INPLL and OUTPLL take the same
* lock, that's why. */
tmp = INPLL( pllMDLL_CKO) | MDLL_CKO__MCKOA_RESET
| MDLL_CKO__MCKOB_RESET;
OUTPLL( pllMDLL_CKO, tmp );
}
}
/* Switch PCI power management to D2. */
pci_disable_device(rinfo->pdev);
pci_save_state(rinfo->pdev);
/* The chip seems to need us to whack the PM register
* repeatedly until it sticks. We do that -prior- to
* calling pci_set_power_state()
*/
radeonfb_whack_power_state(rinfo, PCI_D2);
__pci_complete_power_transition(rinfo->pdev, PCI_D2);
} else {
printk(KERN_DEBUG "radeonfb (%s): switching to D0 state...\n",
pci_name(rinfo->pdev));
if (rinfo->family <= CHIP_FAMILY_RV250) {
/* Reset the SDRAM controller */
radeon_pm_full_reset_sdram(rinfo);
/* Restore some registers */
radeon_pm_restore_regs(rinfo);
} else {
/* Restore registers first */
radeon_pm_restore_regs(rinfo);
/* init sdram controller */
radeon_pm_full_reset_sdram(rinfo);
}
}
}
int radeonfb_pci_suspend(struct pci_dev *pdev, pm_message_t mesg)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
if (mesg.event == pdev->dev.power.power_state.event)
return 0;
printk(KERN_DEBUG "radeonfb (%s): suspending for event: %d...\n",
pci_name(pdev), mesg.event);
/* For suspend-to-disk, we cheat here. We don't suspend anything and
* let fbcon continue drawing until we are all set. That shouldn't
* really cause any problem at this point, provided that the wakeup
* code knows that any state in memory may not match the HW
*/
switch (mesg.event) {
case PM_EVENT_FREEZE: /* about to take snapshot */
case PM_EVENT_PRETHAW: /* before restoring snapshot */
goto done;
}
console_lock();
fb_set_suspend(info, 1);
if (!(info->flags & FBINFO_HWACCEL_DISABLED)) {
/* Make sure engine is reset */
radeon_engine_idle();
radeonfb_engine_reset(rinfo);
radeon_engine_idle();
}
/* Blank display and LCD */
radeon_screen_blank(rinfo, FB_BLANK_POWERDOWN, 1);
/* Sleep */
rinfo->asleep = 1;
rinfo->lock_blank = 1;
del_timer_sync(&rinfo->lvds_timer);
#ifdef CONFIG_PPC_PMAC
/* On powermac, we have hooks to properly suspend/resume AGP now,
* use them here. We'll ultimately need some generic support here,
* but the generic code isn't quite ready for that yet
*/
pmac_suspend_agp_for_card(pdev);
#endif /* CONFIG_PPC_PMAC */
/* It's unclear whether or when the generic code will do that, so let's
* do it ourselves. We save state before we do any power management
*/
pci_save_state(pdev);
/* If we support wakeup from poweroff, we save all regs we can including cfg
* space
*/
if (rinfo->pm_mode & radeon_pm_off) {
/* Always disable dynamic clocks or weird things are happening when
* the chip goes off (basically the panel doesn't shut down properly
* and we crash on wakeup),
* also, we want the saved regs context to have no dynamic clocks in
* it, we'll restore the dynamic clocks state on wakeup
*/
radeon_pm_disable_dynamic_mode(rinfo);
mdelay(50);
radeon_pm_save_regs(rinfo, 1);
if (rinfo->is_mobility && !(rinfo->pm_mode & radeon_pm_d2)) {
/* Switch off LVDS interface */
mdelay(1);
OUTREG(LVDS_GEN_CNTL, INREG(LVDS_GEN_CNTL) & ~(LVDS_BL_MOD_EN));
mdelay(1);
OUTREG(LVDS_GEN_CNTL, INREG(LVDS_GEN_CNTL) & ~(LVDS_EN | LVDS_ON));
OUTREG(LVDS_PLL_CNTL, (INREG(LVDS_PLL_CNTL) & ~30000) | 0x20000);
mdelay(20);
OUTREG(LVDS_GEN_CNTL, INREG(LVDS_GEN_CNTL) & ~(LVDS_DIGON));
}
pci_disable_device(pdev);
}
/* If we support D2, we go to it (should be fixed later with a flag forcing
* D3 only for some laptops)
*/
if (rinfo->pm_mode & radeon_pm_d2)
radeon_set_suspend(rinfo, 1);
console_unlock();
done:
pdev->dev.power.power_state = mesg;
return 0;
}
static int radeon_check_power_loss(struct radeonfb_info *rinfo)
{
return rinfo->save_regs[4] != INPLL(CLK_PIN_CNTL) ||
rinfo->save_regs[2] != INPLL(MCLK_CNTL) ||
rinfo->save_regs[3] != INPLL(SCLK_CNTL);
}
int radeonfb_pci_resume(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
int rc = 0;
if (pdev->dev.power.power_state.event == PM_EVENT_ON)
return 0;
if (rinfo->no_schedule) {
if (!console_trylock())
return 0;
} else
console_lock();
printk(KERN_DEBUG "radeonfb (%s): resuming from state: %d...\n",
pci_name(pdev), pdev->dev.power.power_state.event);
/* PCI state will have been restored by the core, so
* we should be in D0 now with our config space fully
* restored
*/
if (pdev->dev.power.power_state.event == PM_EVENT_SUSPEND) {
/* Wakeup chip */
if ((rinfo->pm_mode & radeon_pm_off) && radeon_check_power_loss(rinfo)) {
if (rinfo->reinit_func != NULL)
rinfo->reinit_func(rinfo);
else {
printk(KERN_ERR "radeonfb (%s): can't resume radeon from"
" D3 cold, need softboot !", pci_name(pdev));
rc = -EIO;
goto bail;
}
}
/* If we support D2, try to resume... we should check what was our
* state though... (were we really in D2 state ?). Right now, this code
* is only enable on Macs so it's fine.
*/
else if (rinfo->pm_mode & radeon_pm_d2)
radeon_set_suspend(rinfo, 0);
rinfo->asleep = 0;
} else
radeon_engine_idle();
/* Restore display & engine */
radeon_write_mode (rinfo, &rinfo->state, 1);
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
radeonfb_engine_init (rinfo);
fb_pan_display(info, &info->var);
fb_set_cmap(&info->cmap, info);
/* Refresh */
fb_set_suspend(info, 0);
/* Unblank */
rinfo->lock_blank = 0;
radeon_screen_blank(rinfo, FB_BLANK_UNBLANK, 1);
#ifdef CONFIG_PPC_PMAC
/* On powermac, we have hooks to properly suspend/resume AGP now,
* use them here. We'll ultimately need some generic support here,
* but the generic code isn't quite ready for that yet
*/
pmac_resume_agp_for_card(pdev);
#endif /* CONFIG_PPC_PMAC */
/* Check status of dynclk */
if (rinfo->dynclk == 1)
radeon_pm_enable_dynamic_mode(rinfo);
else if (rinfo->dynclk == 0)
radeon_pm_disable_dynamic_mode(rinfo);
pdev->dev.power.power_state = PMSG_ON;
bail:
console_unlock();
return rc;
}
#ifdef CONFIG_PPC_OF__disabled
static void radeonfb_early_resume(void *data)
{
struct radeonfb_info *rinfo = data;
rinfo->no_schedule = 1;
pci_restore_state(rinfo->pdev);
radeonfb_pci_resume(rinfo->pdev);
rinfo->no_schedule = 0;
}
#endif /* CONFIG_PPC_OF */
#endif /* CONFIG_PM */
void radeonfb_pm_init(struct radeonfb_info *rinfo, int dynclk, int ignore_devlist, int force_sleep)
{
/* Find PM registers in config space if any*/
rinfo->pm_reg = pci_find_capability(rinfo->pdev, PCI_CAP_ID_PM);
/* Enable/Disable dynamic clocks: TODO add sysfs access */
if (rinfo->family == CHIP_FAMILY_RS480)
rinfo->dynclk = -1;
else
rinfo->dynclk = dynclk;
if (rinfo->dynclk == 1) {
radeon_pm_enable_dynamic_mode(rinfo);
printk("radeonfb: Dynamic Clock Power Management enabled\n");
} else if (rinfo->dynclk == 0) {
radeon_pm_disable_dynamic_mode(rinfo);
printk("radeonfb: Dynamic Clock Power Management disabled\n");
}
#if defined(CONFIG_PM)
#if defined(CONFIG_PPC_PMAC)
/* Check if we can power manage on suspend/resume. We can do
* D2 on M6, M7 and M9, and we can resume from D3 cold a few other
* "Mac" cards, but that's all. We need more infos about what the
* BIOS does tho. Right now, all this PM stuff is pmac-only for that
* reason. --BenH
*/
if (machine_is(powermac) && rinfo->of_node) {
if (rinfo->is_mobility && rinfo->pm_reg &&
rinfo->family <= CHIP_FAMILY_RV250)
rinfo->pm_mode |= radeon_pm_d2;
/* We can restart Jasper (M10 chip in albooks), BlueStone (7500 chip
* in some desktop G4s), Via (M9+ chip on iBook G4) and
* Snowy (M11 chip on iBook G4 manufactured after July 2005)
*/
if (!strcmp(rinfo->of_node->name, "ATY,JasperParent") ||
!strcmp(rinfo->of_node->name, "ATY,SnowyParent")) {
rinfo->reinit_func = radeon_reinitialize_M10;
rinfo->pm_mode |= radeon_pm_off;
}
#if 0 /* Not ready yet */
if (!strcmp(rinfo->of_node->name, "ATY,BlueStoneParent")) {
rinfo->reinit_func = radeon_reinitialize_QW;
rinfo->pm_mode |= radeon_pm_off;
}
#endif
if (!strcmp(rinfo->of_node->name, "ATY,ViaParent")) {
rinfo->reinit_func = radeon_reinitialize_M9P;
rinfo->pm_mode |= radeon_pm_off;
}
/* If any of the above is set, we assume the machine can sleep/resume.
* It's a bit of a "shortcut" but will work fine. Ideally, we need infos
* from the platform about what happens to the chip...
* Now we tell the platform about our capability
*/
if (rinfo->pm_mode != radeon_pm_none) {
pmac_call_feature(PMAC_FTR_DEVICE_CAN_WAKE, rinfo->of_node, 0, 1);
#if 0 /* Disable the early video resume hack for now as it's causing problems, among
* others we now rely on the PCI core restoring the config space for us, which
* isn't the case with that hack, and that code path causes various things to
* be called with interrupts off while they shouldn't. I'm leaving the code in
* as it can be useful for debugging purposes
*/
pmac_set_early_video_resume(radeonfb_early_resume, rinfo);
#endif
}
#if 0
/* Power down TV DAC, that saves a significant amount of power,
* we'll have something better once we actually have some TVOut
* support
*/
OUTREG(TV_DAC_CNTL, INREG(TV_DAC_CNTL) | 0x07000000);
#endif
}
#endif /* defined(CONFIG_PPC_PMAC) */
#endif /* defined(CONFIG_PM) */
if (ignore_devlist)
printk(KERN_DEBUG
"radeonfb: skipping test for device workarounds\n");
else
radeon_apply_workarounds(rinfo);
if (force_sleep) {
printk(KERN_DEBUG
"radeonfb: forcefully enabling D2 sleep mode\n");
rinfo->pm_mode |= radeon_pm_d2;
}
}
void radeonfb_pm_exit(struct radeonfb_info *rinfo)
{
#if defined(CONFIG_PM) && defined(CONFIG_PPC_PMAC)
if (rinfo->pm_mode != radeon_pm_none)
pmac_set_early_video_resume(NULL, NULL);
#endif
}
| gpl-2.0 |
yuhc/linux-3.6.5-for-gxen | drivers/staging/cxt1e1/functions.c | 10525 | 8461 | /* Copyright (C) 2003-2005 SBE, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include <linux/netdevice.h>
#include <linux/delay.h>
#include <linux/hdlc.h>
#include "pmcc4_sysdep.h"
#include "sbecom_inline_linux.h"
#include "libsbew.h"
#include "pmcc4.h"
#ifdef SBE_INCLUDE_SYMBOLS
#define STATIC
#else
#define STATIC static
#endif
#if defined(CONFIG_SBE_HDLC_V7) || defined(CONFIG_SBE_WAN256T3_HDLC_V7) || \
defined(CONFIG_SBE_HDLC_V7_MODULE) || defined(CONFIG_SBE_WAN256T3_HDLC_V7_MODULE)
#define _v7_hdlc_ 1
#else
#define _v7_hdlc_ 0
#endif
#if _v7_hdlc_
#define V7(x) (x ## _v7)
extern int hdlc_netif_rx_v7 (hdlc_device *, struct sk_buff *);
extern int register_hdlc_device_v7 (hdlc_device *);
extern int unregister_hdlc_device_v7 (hdlc_device *);
#else
#define V7(x) x
#endif
#ifndef USE_MAX_INT_DELAY
static int dummy = 0;
#endif
extern int cxt1e1_log_level;
extern int drvr_state;
#if 1
u_int32_t
pci_read_32 (u_int32_t *p)
{
#ifdef FLOW_DEBUG
u_int32_t v;
FLUSH_PCI_READ ();
v = le32_to_cpu (*p);
if (cxt1e1_log_level >= LOG_DEBUG)
pr_info("pci_read : %x = %x\n", (u_int32_t) p, v);
return v;
#else
FLUSH_PCI_READ (); /* */
return le32_to_cpu (*p);
#endif
}
void
pci_write_32 (u_int32_t *p, u_int32_t v)
{
#ifdef FLOW_DEBUG
if (cxt1e1_log_level >= LOG_DEBUG)
pr_info("pci_write: %x = %x\n", (u_int32_t) p, v);
#endif
*p = cpu_to_le32 (v);
FLUSH_PCI_WRITE (); /* This routine is called from routines
* which do multiple register writes
* which themselves need flushing between
* writes in order to guarantee write
* ordering. It is less code-cumbersome
* to flush here-in then to investigate
* and code the many other register
* writing routines. */
}
#endif
void
pci_flush_write (ci_t * ci)
{
volatile u_int32_t v;
/* issue a PCI read to flush PCI write thru bridge */
v = *(u_int32_t *) &ci->reg->glcd; /* any address would do */
/*
* return nothing, this just reads PCI bridge interface to flush
* previously written data
*/
}
STATIC void
watchdog_func (unsigned long arg)
{
struct watchdog *wd = (void *) arg;
if (drvr_state != SBE_DRVR_AVAILABLE)
{
if (cxt1e1_log_level >= LOG_MONITOR)
pr_warning("%s: drvr not available (%x)\n", __func__, drvr_state);
return;
}
schedule_work (&wd->work);
mod_timer (&wd->h, jiffies + wd->ticks);
}
int OS_init_watchdog(struct watchdog *wdp, void (*f) (void *), void *c, int usec)
{
wdp->func = f;
wdp->softc = c;
wdp->ticks = (HZ) * (usec / 1000) / 1000;
INIT_WORK(&wdp->work, (void *)f);
init_timer (&wdp->h);
{
ci_t *ci = (ci_t *) c;
wdp->h.data = (unsigned long) &ci->wd;
}
wdp->h.function = watchdog_func;
return 0;
}
void
OS_uwait (int usec, char *description)
{
int tmp;
if (usec >= 1000)
{
mdelay (usec / 1000);
/* now delay residual */
tmp = (usec / 1000) * 1000; /* round */
tmp = usec - tmp; /* residual */
if (tmp)
{ /* wait on residual */
udelay (tmp);
}
} else
{
udelay (usec);
}
}
/* dummy short delay routine called as a subroutine so that compiler
* does not optimize/remove its intent (a short delay)
*/
void
OS_uwait_dummy (void)
{
#ifndef USE_MAX_INT_DELAY
dummy++;
#else
udelay (1);
#endif
}
void
OS_sem_init (void *sem, int state)
{
switch (state)
{
case SEM_TAKEN:
sema_init((struct semaphore *) sem, 0);
break;
case SEM_AVAILABLE:
sema_init((struct semaphore *) sem, 1);
break;
default: /* otherwise, set sem.count to state's
* value */
sema_init (sem, state);
break;
}
}
int
sd_line_is_ok (void *user)
{
struct net_device *ndev = (struct net_device *) user;
return (netif_carrier_ok (ndev));
}
void
sd_line_is_up (void *user)
{
struct net_device *ndev = (struct net_device *) user;
netif_carrier_on (ndev);
return;
}
void
sd_line_is_down (void *user)
{
struct net_device *ndev = (struct net_device *) user;
netif_carrier_off (ndev);
return;
}
void
sd_disable_xmit (void *user)
{
struct net_device *dev = (struct net_device *) user;
netif_stop_queue (dev);
return;
}
void
sd_enable_xmit (void *user)
{
struct net_device *dev = (struct net_device *) user;
netif_wake_queue (dev);
return;
}
int
sd_queue_stopped (void *user)
{
struct net_device *ndev = (struct net_device *) user;
return (netif_queue_stopped (ndev));
}
void sd_recv_consume(void *token, size_t len, void *user)
{
struct net_device *ndev = user;
struct sk_buff *skb = token;
skb->dev = ndev;
skb_put (skb, len);
skb->protocol = hdlc_type_trans(skb, ndev);
netif_rx(skb);
}
/**
** Read some reserved location w/in the COMET chip as a usable
** VMETRO trigger point or other trace marking event.
**/
#include "comet.h"
extern ci_t *CI; /* dummy pointer to board ZERO's data */
void
VMETRO_TRACE (void *x)
{
u_int32_t y = (u_int32_t) x;
pci_write_32 ((u_int32_t *) &CI->cpldbase->leds, y);
}
void
VMETRO_TRIGGER (ci_t * ci, int x)
{
comet_t *comet;
volatile u_int32_t data;
comet = ci->port[0].cometbase; /* default to COMET # 0 */
switch (x)
{
default:
case 0:
data = pci_read_32 ((u_int32_t *) &comet->__res24); /* 0x90 */
break;
case 1:
data = pci_read_32 ((u_int32_t *) &comet->__res25); /* 0x94 */
break;
case 2:
data = pci_read_32 ((u_int32_t *) &comet->__res26); /* 0x98 */
break;
case 3:
data = pci_read_32 ((u_int32_t *) &comet->__res27); /* 0x9C */
break;
case 4:
data = pci_read_32 ((u_int32_t *) &comet->__res88); /* 0x220 */
break;
case 5:
data = pci_read_32 ((u_int32_t *) &comet->__res89); /* 0x224 */
break;
case 6:
data = pci_read_32 ((u_int32_t *) &comet->__res8A); /* 0x228 */
break;
case 7:
data = pci_read_32 ((u_int32_t *) &comet->__res8B); /* 0x22C */
break;
case 8:
data = pci_read_32 ((u_int32_t *) &comet->__resA0); /* 0x280 */
break;
case 9:
data = pci_read_32 ((u_int32_t *) &comet->__resA1); /* 0x284 */
break;
case 10:
data = pci_read_32 ((u_int32_t *) &comet->__resA2); /* 0x288 */
break;
case 11:
data = pci_read_32 ((u_int32_t *) &comet->__resA3); /* 0x28C */
break;
case 12:
data = pci_read_32 ((u_int32_t *) &comet->__resA4); /* 0x290 */
break;
case 13:
data = pci_read_32 ((u_int32_t *) &comet->__resA5); /* 0x294 */
break;
case 14:
data = pci_read_32 ((u_int32_t *) &comet->__resA6); /* 0x298 */
break;
case 15:
data = pci_read_32 ((u_int32_t *) &comet->__resA7); /* 0x29C */
break;
case 16:
data = pci_read_32 ((u_int32_t *) &comet->__res74); /* 0x1D0 */
break;
case 17:
data = pci_read_32 ((u_int32_t *) &comet->__res75); /* 0x1D4 */
break;
case 18:
data = pci_read_32 ((u_int32_t *) &comet->__res76); /* 0x1D8 */
break;
case 19:
data = pci_read_32 ((u_int32_t *) &comet->__res77); /* 0x1DC */
break;
}
}
/*** End-of-File ***/
| gpl-2.0 |
RealDigitalMediaAndroid/linux-imx6 | drivers/video/output.c | 11549 | 3547 | /*
* output.c - Display Output Switch driver
*
* Copyright (C) 2006 Luming Yu <luming.yu@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/module.h>
#include <linux/video_output.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/ctype.h>
MODULE_DESCRIPTION("Display Output Switcher Lowlevel Control Abstraction");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Luming Yu <luming.yu@intel.com>");
static ssize_t video_output_show_state(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t ret_size = 0;
struct output_device *od = to_output_device(dev);
if (od->props)
ret_size = sprintf(buf,"%.8x\n",od->props->get_status(od));
return ret_size;
}
static ssize_t video_output_store_state(struct device *dev,
struct device_attribute *attr,
const char *buf,size_t count)
{
char *endp;
struct output_device *od = to_output_device(dev);
int request_state = simple_strtoul(buf,&endp,0);
size_t size = endp - buf;
if (isspace(*endp))
size++;
if (size != count)
return -EINVAL;
if (od->props) {
od->request_state = request_state;
od->props->set_state(od);
}
return count;
}
static void video_output_release(struct device *dev)
{
struct output_device *od = to_output_device(dev);
kfree(od);
}
static struct device_attribute video_output_attributes[] = {
__ATTR(state, 0644, video_output_show_state, video_output_store_state),
__ATTR_NULL,
};
static struct class video_output_class = {
.name = "video_output",
.dev_release = video_output_release,
.dev_attrs = video_output_attributes,
};
struct output_device *video_output_register(const char *name,
struct device *dev,
void *devdata,
struct output_properties *op)
{
struct output_device *new_dev;
int ret_code = 0;
new_dev = kzalloc(sizeof(struct output_device),GFP_KERNEL);
if (!new_dev) {
ret_code = -ENOMEM;
goto error_return;
}
new_dev->props = op;
new_dev->dev.class = &video_output_class;
new_dev->dev.parent = dev;
dev_set_name(&new_dev->dev, name);
dev_set_drvdata(&new_dev->dev, devdata);
ret_code = device_register(&new_dev->dev);
if (ret_code) {
kfree(new_dev);
goto error_return;
}
return new_dev;
error_return:
return ERR_PTR(ret_code);
}
EXPORT_SYMBOL(video_output_register);
void video_output_unregister(struct output_device *dev)
{
if (!dev)
return;
device_unregister(&dev->dev);
}
EXPORT_SYMBOL(video_output_unregister);
static void __exit video_output_class_exit(void)
{
class_unregister(&video_output_class);
}
static int __init video_output_class_init(void)
{
return class_register(&video_output_class);
}
postcore_initcall(video_output_class_init);
module_exit(video_output_class_exit);
| gpl-2.0 |
Benzonat0r/android_kernel_samsung_golden | net/ieee802154/nl_policy.c | 12061 | 2258 | /*
* nl802154.h
*
* Copyright (C) 2007, 2008 Siemens AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/kernel.h>
#include <net/netlink.h>
#include <linux/nl802154.h>
#define NLA_HW_ADDR NLA_U64
const struct nla_policy ieee802154_policy[IEEE802154_ATTR_MAX + 1] = {
[IEEE802154_ATTR_DEV_NAME] = { .type = NLA_STRING, },
[IEEE802154_ATTR_DEV_INDEX] = { .type = NLA_U32, },
[IEEE802154_ATTR_PHY_NAME] = { .type = NLA_STRING, },
[IEEE802154_ATTR_STATUS] = { .type = NLA_U8, },
[IEEE802154_ATTR_SHORT_ADDR] = { .type = NLA_U16, },
[IEEE802154_ATTR_HW_ADDR] = { .type = NLA_HW_ADDR, },
[IEEE802154_ATTR_PAN_ID] = { .type = NLA_U16, },
[IEEE802154_ATTR_CHANNEL] = { .type = NLA_U8, },
[IEEE802154_ATTR_PAGE] = { .type = NLA_U8, },
[IEEE802154_ATTR_COORD_SHORT_ADDR] = { .type = NLA_U16, },
[IEEE802154_ATTR_COORD_HW_ADDR] = { .type = NLA_HW_ADDR, },
[IEEE802154_ATTR_COORD_PAN_ID] = { .type = NLA_U16, },
[IEEE802154_ATTR_SRC_SHORT_ADDR] = { .type = NLA_U16, },
[IEEE802154_ATTR_SRC_HW_ADDR] = { .type = NLA_HW_ADDR, },
[IEEE802154_ATTR_SRC_PAN_ID] = { .type = NLA_U16, },
[IEEE802154_ATTR_DEST_SHORT_ADDR] = { .type = NLA_U16, },
[IEEE802154_ATTR_DEST_HW_ADDR] = { .type = NLA_HW_ADDR, },
[IEEE802154_ATTR_DEST_PAN_ID] = { .type = NLA_U16, },
[IEEE802154_ATTR_CAPABILITY] = { .type = NLA_U8, },
[IEEE802154_ATTR_REASON] = { .type = NLA_U8, },
[IEEE802154_ATTR_SCAN_TYPE] = { .type = NLA_U8, },
[IEEE802154_ATTR_CHANNELS] = { .type = NLA_U32, },
[IEEE802154_ATTR_DURATION] = { .type = NLA_U8, },
[IEEE802154_ATTR_ED_LIST] = { .len = 27 },
[IEEE802154_ATTR_CHANNEL_PAGE_LIST] = { .len = 32 * 4, },
};
| gpl-2.0 |
cooldroid/android_kernel_oneplus_msm8974 | 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 |
WarheadsSE/OX820-2.6-linux | arch/sparc/lib/user_fixup.c | 13597 | 1805 | /* user_fixup.c: Fix up user copy faults.
*
* Copyright (C) 2004 David S. Miller <davem@redhat.com>
*/
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <asm/uaccess.h>
/* Calculating the exact fault address when using
* block loads and stores can be very complicated.
*
* Instead of trying to be clever and handling all
* of the cases, just fix things up simply here.
*/
static unsigned long compute_size(unsigned long start, unsigned long size, unsigned long *offset)
{
unsigned long fault_addr = current_thread_info()->fault_address;
unsigned long end = start + size;
if (fault_addr < start || fault_addr >= end) {
*offset = 0;
} else {
*offset = fault_addr - start;
size = end - fault_addr;
}
return size;
}
unsigned long copy_from_user_fixup(void *to, const void __user *from, unsigned long size)
{
unsigned long offset;
size = compute_size((unsigned long) from, size, &offset);
if (likely(size))
memset(to + offset, 0, size);
return size;
}
EXPORT_SYMBOL(copy_from_user_fixup);
unsigned long copy_to_user_fixup(void __user *to, const void *from, unsigned long size)
{
unsigned long offset;
return compute_size((unsigned long) to, size, &offset);
}
EXPORT_SYMBOL(copy_to_user_fixup);
unsigned long copy_in_user_fixup(void __user *to, void __user *from, unsigned long size)
{
unsigned long fault_addr = current_thread_info()->fault_address;
unsigned long start = (unsigned long) to;
unsigned long end = start + size;
if (fault_addr >= start && fault_addr < end)
return end - fault_addr;
start = (unsigned long) from;
end = start + size;
if (fault_addr >= start && fault_addr < end)
return end - fault_addr;
return size;
}
EXPORT_SYMBOL(copy_in_user_fixup);
| gpl-2.0 |
jmarshallnz/xbmc | xbmc/input/InputManager.cpp | 30 | 26578 | /*
* Copyright (C) 2005-2014 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <math.h>
#include "Application.h"
#include "InputManager.h"
#include "input/Key.h"
#include "messaging/ApplicationMessenger.h"
#include "guilib/Geometry.h"
#include "guilib/GUIAudioManager.h"
#include "guilib/GUIControl.h"
#include "guilib/GUIWindow.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/GUIMessage.h"
#ifdef HAS_EVENT_SERVER
#include "network/EventServer.h"
#endif
#ifdef HAS_LIRC
#include "input/linux/LIRC.h"
#endif
#ifdef HAS_IRSERVERSUITE
#include "input/windows/IRServerSuite.h"
#endif
#if HAVE_SDL_VERSION == 1
#include <SDL/SDL.h>
#elif HAVE_SDL_VERSION == 2
#include <SDL2/SDL.h>
#endif
#if defined(TARGET_WINDOWS)
#include "input/windows/WINJoystick.h"
#elif defined(HAS_SDL_JOYSTICK) || defined(HAS_EVENT_SERVER)
#include "input/SDLJoystick.h"
#endif
#include "ButtonTranslator.h"
#include "peripherals/Peripherals.h"
#include "peripherals/devices/PeripheralImon.h"
#include "XBMC_vkeys.h"
#include "utils/log.h"
#include "utils/StringUtils.h"
#include "Util.h"
#include "settings/Settings.h"
#ifdef HAS_PERFORMANCE_SAMPLE
#include "utils/PerformanceSample.h"
#else
#define MEASURE_FUNCTION
#endif
#ifdef HAS_EVENT_SERVER
using EVENTSERVER::CEventServer;
#endif
using namespace KODI::MESSAGING;
using PERIPHERALS::CPeripherals;
CInputManager& CInputManager::GetInstance()
{
static CInputManager inputManager;
return inputManager;
}
void CInputManager::InitializeInputs()
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
m_RemoteControl.Initialize();
#endif
#ifdef HAS_SDL_JOYSTICK
// Pass the mapping of axis to triggers to m_Joystick
m_Joystick.Initialize();
#endif
m_Keyboard.Initialize();
m_Mouse.Initialize();
m_Mouse.SetEnabled(CSettings::GetInstance().GetBool(CSettings::SETTING_INPUT_ENABLEMOUSE));
}
void CInputManager::ReInitializeJoystick()
{
#ifdef HAS_SDL_JOYSTICK
m_Joystick.Reinitialize();
#endif
}
void CInputManager::SetEnabledJoystick(bool enabled /* = true */)
{
#ifdef HAS_SDL_JOYSTICK
m_Joystick.SetEnabled(enabled);
#endif
}
#if defined(HAS_SDL_JOYSTICK) && !defined(TARGET_WINDOWS)
void CInputManager::UpdateJoystick(SDL_Event& joyEvent)
{
m_Joystick.Update(joyEvent);
}
#endif
bool CInputManager::ProcessGamepad(int windowId)
{
#ifdef HAS_SDL_JOYSTICK
if (!g_application.IsAppFocused())
return false;
int keymapId, joyId;
m_Joystick.Update();
std::string joyName;
if (m_Joystick.GetButton(joyName, joyId))
{
g_application.ResetSystemIdleTimer();
g_application.ResetScreenSaver();
if (g_application.WakeUpScreenSaverAndDPMS())
{
m_Joystick.Reset();
return true;
}
int actionID;
std::string actionName;
bool fullrange;
keymapId = joyId + 1;
if (CButtonTranslator::GetInstance().TranslateJoystickString(windowId, joyName, keymapId, JACTIVE_BUTTON, actionID, actionName, fullrange))
{
CAction action(actionID, 1.0f, 0.0f, actionName);
m_Mouse.SetActive(false);
return ExecuteInputAction(action);
}
}
std::list<std::pair<std::string, int> > usedAxes;
if (m_Joystick.GetAxes(usedAxes))
{
bool compoundReturn = false;
for (std::list<std::pair<std::string, int> >::iterator it = usedAxes.begin();
it != usedAxes.end();
++it)
{
joyName = it->first;
joyId = it->second;
keymapId = joyId + 1;
if (m_Joystick.GetAmount(joyName, joyId) < 0)
{
keymapId = -keymapId;
}
int actionID;
std::string actionName;
bool fullrange;
if (CButtonTranslator::GetInstance().TranslateJoystickString(windowId, joyName, keymapId, JACTIVE_AXIS, actionID, actionName, fullrange))
{
g_application.ResetScreenSaver();
if (g_application.WakeUpScreenSaverAndDPMS())
{
return true;
}
float amount = m_Joystick.GetAmount(joyName, joyId);
amount = fullrange ? (amount + 1.0f) / 2.0f : amount;
CAction action(actionID, amount, 0.0f, actionName);
m_Mouse.SetActive(false);
compoundReturn |= ExecuteInputAction(action);
}
}
return compoundReturn;
}
int position = 0;
if (m_Joystick.GetHat(joyName, joyId, position))
{
keymapId = joyId + 1;
// reset Idle Timer
g_application.ResetSystemIdleTimer();
g_application.ResetScreenSaver();
if (g_application.WakeUpScreenSaverAndDPMS())
{
m_Joystick.Reset();
return true;
}
int actionID;
std::string actionName;
bool fullrange;
keymapId = position << 16 | keymapId;
if (keymapId && CButtonTranslator::GetInstance().TranslateJoystickString(windowId, joyName, keymapId, JACTIVE_HAT, actionID, actionName, fullrange))
{
CAction action(actionID, 1.0f, 0.0f, actionName);
m_Mouse.SetActive(false);
return ExecuteInputAction(action);
}
}
#endif
return false;
}
bool CInputManager::ProcessRemote(int windowId)
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
if (m_RemoteControl.GetButton())
{
CKey key(m_RemoteControl.GetButton(), m_RemoteControl.GetHoldTime());
m_RemoteControl.Reset();
return OnKey(key);
}
#endif
return false;
}
bool CInputManager::ProcessPeripherals(float frameTime)
{
CKey key;
if (g_peripherals.GetNextKeypress(frameTime, key))
return OnKey(key);
return false;
}
bool CInputManager::ProcessMouse(int windowId)
{
MEASURE_FUNCTION;
if (!m_Mouse.IsActive() || !g_application.IsAppFocused())
return false;
// Get the mouse command ID
uint32_t mousekey = m_Mouse.GetKey();
if (mousekey == KEY_MOUSE_NOOP)
return true;
// Reset the screensaver and idle timers
g_application.ResetSystemIdleTimer();
g_application.ResetScreenSaver();
if (g_application.WakeUpScreenSaverAndDPMS())
return true;
// Retrieve the corresponding action
CKey key(mousekey, (unsigned int)0);
CAction mouseaction = CButtonTranslator::GetInstance().GetAction(windowId, key);
// Deactivate mouse if non-mouse action
if (!mouseaction.IsMouse())
m_Mouse.SetActive(false);
// Consume ACTION_NOOP.
// Some views or dialogs gets closed after any ACTION and
// a sensitive mouse might cause problems.
if (mouseaction.GetID() == ACTION_NOOP)
return false;
// If we couldn't find an action return false to indicate we have not
// handled this mouse action
if (!mouseaction.GetID())
{
CLog::LogF(LOGDEBUG, "unknown mouse command %d", mousekey);
return false;
}
// Log mouse actions except for move and noop
if (mouseaction.GetID() != ACTION_MOUSE_MOVE && mouseaction.GetID() != ACTION_NOOP)
CLog::LogF(LOGDEBUG, "trying mouse action %s", mouseaction.GetName().c_str());
// The action might not be a mouse action. For example wheel moves might
// be mapped to volume up/down in mouse.xml. In this case we do not want
// the mouse position saved in the action.
if (!mouseaction.IsMouse())
return g_application.OnAction(mouseaction);
// This is a mouse action so we need to record the mouse position
return g_application.OnAction(CAction(mouseaction.GetID(),
m_Mouse.GetHold(MOUSE_LEFT_BUTTON),
(float)m_Mouse.GetX(),
(float)m_Mouse.GetY(),
(float)m_Mouse.GetDX(),
(float)m_Mouse.GetDY(),
mouseaction.GetName()));
}
bool CInputManager::ProcessEventServer(int windowId, float frameTime)
{
#ifdef HAS_EVENT_SERVER
CEventServer* es = CEventServer::GetInstance();
if (!es || !es->Running() || es->GetNumberOfClients() == 0)
return false;
// process any queued up actions
if (es->ExecuteNextAction())
{
// reset idle timers
g_application.ResetSystemIdleTimer();
g_application.ResetScreenSaver();
g_application.WakeUpScreenSaverAndDPMS();
}
// now handle any buttons or axis
std::string joystickName;
bool isAxis = false;
float fAmount = 0.0;
// es->ExecuteNextAction() invalidates the ref to the CEventServer instance
// when the action exits XBMC
es = CEventServer::GetInstance();
if (!es || !es->Running() || es->GetNumberOfClients() == 0)
return false;
unsigned int wKeyID = es->GetButtonCode(joystickName, isAxis, fAmount);
if (wKeyID)
{
if (joystickName.length() > 0)
{
if (isAxis == true)
{
if (fabs(fAmount) >= 0.08)
m_lastAxisMap[joystickName][wKeyID] = fAmount;
else
m_lastAxisMap[joystickName].erase(wKeyID);
}
return ProcessJoystickEvent(windowId, joystickName, wKeyID, isAxis ? JACTIVE_AXIS : JACTIVE_BUTTON, fAmount);
}
else
{
CKey key;
if (wKeyID & ES_FLAG_UNICODE)
{
key = CKey((uint8_t)0, wKeyID & ~ES_FLAG_UNICODE, 0, 0, 0);
return OnKey(key);
}
if (wKeyID == KEY_BUTTON_LEFT_ANALOG_TRIGGER)
key = CKey(wKeyID, (BYTE)(255 * fAmount), 0, 0.0, 0.0, 0.0, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_RIGHT_ANALOG_TRIGGER)
key = CKey(wKeyID, 0, (BYTE)(255 * fAmount), 0.0, 0.0, 0.0, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_LEFT)
key = CKey(wKeyID, 0, 0, -fAmount, 0.0, 0.0, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_RIGHT)
key = CKey(wKeyID, 0, 0, fAmount, 0.0, 0.0, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_UP)
key = CKey(wKeyID, 0, 0, 0.0, fAmount, 0.0, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_LEFT_THUMB_STICK_DOWN)
key = CKey(wKeyID, 0, 0, 0.0, -fAmount, 0.0, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_LEFT)
key = CKey(wKeyID, 0, 0, 0.0, 0.0, -fAmount, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_RIGHT)
key = CKey(wKeyID, 0, 0, 0.0, 0.0, fAmount, 0.0, frameTime);
else if (wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_UP)
key = CKey(wKeyID, 0, 0, 0.0, 0.0, 0.0, fAmount, frameTime);
else if (wKeyID == KEY_BUTTON_RIGHT_THUMB_STICK_DOWN)
key = CKey(wKeyID, 0, 0, 0.0, 0.0, 0.0, -fAmount, frameTime);
else
key = CKey(wKeyID);
key.SetFromService(true);
return OnKey(key);
}
}
if (!m_lastAxisMap.empty())
{
// Process all the stored axis.
for (std::map<std::string, std::map<int, float> >::iterator iter = m_lastAxisMap.begin(); iter != m_lastAxisMap.end(); ++iter)
{
for (std::map<int, float>::iterator iterAxis = (*iter).second.begin(); iterAxis != (*iter).second.end(); ++iterAxis)
ProcessJoystickEvent(windowId, (*iter).first, (*iterAxis).first, JACTIVE_AXIS, (*iterAxis).second);
}
}
{
CPoint pos;
if (es->GetMousePos(pos.x, pos.y) && m_Mouse.IsEnabled())
{
XBMC_Event newEvent;
newEvent.type = XBMC_MOUSEMOTION;
newEvent.motion.xrel = 0;
newEvent.motion.yrel = 0;
newEvent.motion.state = 0;
newEvent.motion.which = 0x10; // just a different value to distinguish between mouse and event client device.
newEvent.motion.x = (uint16_t)pos.x;
newEvent.motion.y = (uint16_t)pos.y;
g_application.OnEvent(newEvent); // had to call this to update g_Mouse position
return g_application.OnAction(CAction(ACTION_MOUSE_MOVE, pos.x, pos.y));
}
}
#endif
return false;
}
bool CInputManager::Process(int windowId, float frameTime)
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
// Read the input from a remote
m_RemoteControl.Update();
#endif
// process input actions
ProcessRemote(windowId);
ProcessGamepad(windowId);
ProcessEventServer(windowId, frameTime);
ProcessPeripherals(frameTime);
return true;
}
bool CInputManager::ProcessJoystickEvent(int windowId, const std::string& joystickName, int wKeyID, short inputType, float fAmount, unsigned int holdTime /*=0*/)
{
#if defined(HAS_EVENT_SERVER)
g_application.ResetSystemIdleTimer();
g_application.ResetScreenSaver();
if (g_application.WakeUpScreenSaverAndDPMS())
return true;
m_Mouse.SetActive(false);
int actionID;
std::string actionName;
bool fullRange = false;
// Translate using regular joystick translator.
if (CButtonTranslator::GetInstance().TranslateJoystickString(windowId, joystickName, wKeyID, inputType, actionID, actionName, fullRange))
return ExecuteInputAction(CAction(actionID, fAmount, 0.0f, actionName, holdTime));
else
CLog::Log(LOGDEBUG, "ERROR mapping joystick action. Joystick: %s %i", joystickName.c_str(), wKeyID);
#endif
return false;
}
bool CInputManager::OnEvent(XBMC_Event& newEvent)
{
switch (newEvent.type)
{
case XBMC_KEYDOWN:
{
m_Keyboard.ProcessKeyDown(newEvent.key.keysym);
CKey key = m_Keyboard.TranslateKey(newEvent.key.keysym);
if (!CButtonTranslator::GetInstance().HasLonpressMapping(g_windowManager.GetActiveWindowID(), key))
{
m_LastKey.Reset();
OnKey(key);
}
else
{
if (key.GetButtonCode() != m_LastKey.GetButtonCode() && key.GetButtonCode() & CKey::MODIFIER_LONG)
{
m_LastKey = key; // OnKey is reentrant; need to do this before entering
OnKey(key);
}
m_LastKey = key;
}
break;
}
case XBMC_KEYUP:
m_Keyboard.ProcessKeyUp();
if (m_LastKey.GetButtonCode() != KEY_INVALID && !(m_LastKey.GetButtonCode() & CKey::MODIFIER_LONG))
OnKey(m_LastKey);
m_LastKey.Reset();
break;
case XBMC_MOUSEBUTTONDOWN:
case XBMC_MOUSEBUTTONUP:
case XBMC_MOUSEMOTION:
m_Mouse.HandleEvent(newEvent);
ProcessMouse(g_windowManager.GetActiveWindowID());
break;
case XBMC_TOUCH:
{
if (newEvent.touch.action == ACTION_TOUCH_TAP)
{ // Send a mouse motion event with no dx,dy for getting the current guiitem selected
g_application.OnAction(CAction(ACTION_MOUSE_MOVE, 0, newEvent.touch.x, newEvent.touch.y, 0, 0));
}
int actionId = 0;
std::string actionString;
if (newEvent.touch.action == ACTION_GESTURE_BEGIN || newEvent.touch.action == ACTION_GESTURE_END)
actionId = newEvent.touch.action;
else
{
int iWin = g_windowManager.GetActiveWindowID();
CButtonTranslator::GetInstance().TranslateTouchAction(iWin, newEvent.touch.action, newEvent.touch.pointers, actionId, actionString);
}
if (actionId <= 0)
return false;
if ((actionId >= ACTION_TOUCH_TAP && actionId <= ACTION_GESTURE_END)
|| (actionId >= ACTION_MOUSE_START && actionId <= ACTION_MOUSE_END))
{
auto action = new CAction(actionId, 0, newEvent.touch.x, newEvent.touch.y, newEvent.touch.x2, newEvent.touch.y2);
CApplicationMessenger::GetInstance().PostMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(action));
}
else
{
if (actionId == ACTION_BUILT_IN_FUNCTION && !actionString.empty())
CApplicationMessenger::GetInstance().PostMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(new CAction(actionId, actionString)));
else
CApplicationMessenger::GetInstance().PostMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(new CAction(actionId)));
}
// Post an unfocus message for touch device after the action.
if (newEvent.touch.action == ACTION_GESTURE_END || newEvent.touch.action == ACTION_TOUCH_TAP)
{
CGUIMessage msg(GUI_MSG_UNFOCUS_ALL, 0, 0, 0, 0);
CApplicationMessenger::GetInstance().SendGUIMessage(msg);
}
break;
} //case
}//switch
return true;
}
// OnKey() translates the key into a CAction which is sent on to our Window Manager.
// The window manager will return true if the event is processed, false otherwise.
// If not already processed, this routine handles global keypresses. It returns
// true if the key has been processed, false otherwise.
bool CInputManager::OnKey(const CKey& key)
{
// Turn the mouse off, as we've just got a keypress from controller or remote
m_Mouse.SetActive(false);
// get the current active window
int iWin = g_windowManager.GetActiveWindowID();
// this will be checked for certain keycodes that need
// special handling if the screensaver is active
CAction action = CButtonTranslator::GetInstance().GetAction(iWin, key);
// a key has been pressed.
// reset Idle Timer
g_application.ResetSystemIdleTimer();
bool processKey = AlwaysProcess(action);
if (StringUtils::StartsWithNoCase(action.GetName(), "CECToggleState") || StringUtils::StartsWithNoCase(action.GetName(), "CECStandby"))
{
// do not wake up the screensaver right after switching off the playing device
if (StringUtils::StartsWithNoCase(action.GetName(), "CECToggleState"))
{
CLog::LogF(LOGDEBUG, "action %s [%d], toggling state of playing device", action.GetName().c_str(), action.GetID());
bool result;
CApplicationMessenger::GetInstance().SendMsg(TMSG_CECTOGGLESTATE, 0, 0, static_cast<void*>(&result));
if (!result)
return true;
}
else
{
CApplicationMessenger::GetInstance().PostMsg(TMSG_CECSTANDBY);
return true;
}
}
g_application.ResetScreenSaver();
// allow some keys to be processed while the screensaver is active
if (g_application.WakeUpScreenSaverAndDPMS(processKey) && !processKey)
{
CLog::LogF(LOGDEBUG, "%s pressed, screen saver/dpms woken up", m_Keyboard.GetKeyName((int)key.GetButtonCode()).c_str());
return true;
}
if (iWin != WINDOW_FULLSCREEN_VIDEO)
{
// current active window isnt the fullscreen window
// just use corresponding section from keymap.xml
// to map key->action
// first determine if we should use keyboard input directly
bool useKeyboard = key.FromKeyboard() && (iWin == WINDOW_DIALOG_KEYBOARD || iWin == WINDOW_DIALOG_NUMERIC);
CGUIWindow *window = g_windowManager.GetWindow(iWin);
if (window)
{
CGUIControl *control = window->GetFocusedControl();
if (control)
{
// If this is an edit control set usekeyboard to true. This causes the
// keypress to be processed directly not through the key mappings.
if (control->GetControlType() == CGUIControl::GUICONTROL_EDIT)
useKeyboard = true;
// If the key pressed is shift-A to shift-Z set usekeyboard to true.
// This causes the keypress to be used for list navigation.
if (control->IsContainer() && key.GetModifiers() == CKey::MODIFIER_SHIFT && key.GetVKey() >= XBMCVK_A && key.GetVKey() <= XBMCVK_Z)
useKeyboard = true;
}
}
if (useKeyboard)
{
// use the virtualkeyboard section of the keymap, and send keyboard-specific or navigation
// actions through if that's what they are
CAction action = CButtonTranslator::GetInstance().GetAction(WINDOW_DIALOG_KEYBOARD, key);
if (!(action.GetID() == ACTION_MOVE_LEFT ||
action.GetID() == ACTION_MOVE_RIGHT ||
action.GetID() == ACTION_MOVE_UP ||
action.GetID() == ACTION_MOVE_DOWN ||
action.GetID() == ACTION_SELECT_ITEM ||
action.GetID() == ACTION_ENTER ||
action.GetID() == ACTION_PREVIOUS_MENU ||
action.GetID() == ACTION_NAV_BACK))
{
// the action isn't plain navigation - check for a keyboard-specific keymap
action = CButtonTranslator::GetInstance().GetAction(WINDOW_DIALOG_KEYBOARD, key, false);
if (!(action.GetID() >= REMOTE_0 && action.GetID() <= REMOTE_9) ||
action.GetID() == ACTION_BACKSPACE ||
action.GetID() == ACTION_SHIFT ||
action.GetID() == ACTION_SYMBOLS ||
action.GetID() == ACTION_CURSOR_LEFT ||
action.GetID() == ACTION_CURSOR_RIGHT)
action = CAction(0); // don't bother with this action
}
// else pass the keys through directly
if (!action.GetID())
{
if (key.GetFromService())
action = CAction(key.GetButtonCode() != KEY_INVALID ? key.GetButtonCode() : 0, key.GetUnicode());
else
{
// Check for paste keypress
#ifdef TARGET_WINDOWS
// In Windows paste is ctrl-V
if (key.GetVKey() == XBMCVK_V && key.GetModifiers() == CKey::MODIFIER_CTRL)
#elif defined(TARGET_LINUX)
// In Linux paste is ctrl-V
if (key.GetVKey() == XBMCVK_V && key.GetModifiers() == CKey::MODIFIER_CTRL)
#elif defined(TARGET_DARWIN_OSX)
// In OSX paste is cmd-V
if (key.GetVKey() == XBMCVK_V && key.GetModifiers() == CKey::MODIFIER_META)
#else
// Placeholder for other operating systems
if (false)
#endif
action = CAction(ACTION_PASTE);
// If the unicode is non-zero the keypress is a non-printing character
else if (key.GetUnicode())
action = CAction(key.GetAscii() | KEY_ASCII, key.GetUnicode());
// The keypress is a non-printing character
else
action = CAction(key.GetVKey() | KEY_VKEY);
}
}
CLog::LogF(LOGDEBUG, "%s pressed, trying keyboard action %x", m_Keyboard.GetKeyName((int)key.GetButtonCode()).c_str(), action.GetID());
if (g_application.OnAction(action))
return true;
// failed to handle the keyboard action, drop down through to standard action
}
if (key.GetFromService())
{
if (key.GetButtonCode() != KEY_INVALID)
action = CButtonTranslator::GetInstance().GetAction(iWin, key);
}
else
action = CButtonTranslator::GetInstance().GetAction(iWin, key);
}
if (!key.IsAnalogButton())
CLog::LogF(LOGDEBUG, "%s pressed, action is %s", m_Keyboard.GetKeyName((int)key.GetButtonCode()).c_str(), action.GetName().c_str());
return ExecuteInputAction(action);
}
bool CInputManager::AlwaysProcess(const CAction& action)
{
// check if this button is mapped to a built-in function
if (!action.GetName().empty())
{
std::string builtInFunction;
std::vector<std::string> params;
CUtil::SplitExecFunction(action.GetName(), builtInFunction, params);
StringUtils::ToLower(builtInFunction);
// should this button be handled normally or just cancel the screensaver?
if (builtInFunction == "powerdown"
|| builtInFunction == "reboot"
|| builtInFunction == "restart"
|| builtInFunction == "restartapp"
|| builtInFunction == "suspend"
|| builtInFunction == "hibernate"
|| builtInFunction == "quit"
|| builtInFunction == "shutdown")
{
return true;
}
}
return false;
}
bool CInputManager::ExecuteInputAction(const CAction &action)
{
bool bResult = false;
// play sound before the action unless the button is held,
// where we execute after the action as held actions aren't fired every time.
if (action.GetHoldTime())
{
bResult = g_application.OnAction(action);
if (bResult)
g_audioManager.PlayActionSound(action);
}
else
{
g_audioManager.PlayActionSound(action);
bResult = g_application.OnAction(action);
}
return bResult;
}
int CInputManager::ExecuteBuiltin(const std::string& execute, const std::vector<std::string>& params)
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
if (execute == "lirc.stop")
{
m_RemoteControl.Disconnect();
m_RemoteControl.SetEnabled(false);
}
else if (execute == "lirc.start")
{
m_RemoteControl.SetEnabled(true);
m_RemoteControl.Initialize();
}
else if (execute == "lirc.send")
{
std::string command;
for (int i = 0; i < (int)params.size(); i++)
{
command += params[i];
if (i < (int)params.size() - 1)
command += ' ';
}
m_RemoteControl.AddSendCommand(command);
}
else
return -1;
#endif
return 0;
}
void CInputManager::SetMouseActive(bool active /* = true */)
{
m_Mouse.SetActive(active);
}
void CInputManager::SetMouseEnabled(bool mouseEnabled /* = true */)
{
m_Mouse.SetEnabled(mouseEnabled);
}
bool CInputManager::IsMouseActive()
{
return m_Mouse.IsActive();
}
MOUSE_STATE CInputManager::GetMouseState()
{
return m_Mouse.GetState();
}
MousePosition CInputManager::GetMousePosition()
{
return m_Mouse.GetPosition();
}
void CInputManager::SetMouseResolution(int maxX, int maxY, float speedX, float speedY)
{
m_Mouse.SetResolution(maxX, maxY, speedX, speedY);
}
void CInputManager::SetMouseState(MOUSE_STATE mouseState)
{
m_Mouse.SetState(mouseState);
}
bool CInputManager::IsRemoteControlEnabled()
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
return m_RemoteControl.IsInUse();
#else
return false;
#endif
}
bool CInputManager::IsRemoteControlInitialized()
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
return m_RemoteControl.IsInitialized();
#else
return false;
#endif
}
void CInputManager::EnableRemoteControl()
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
m_RemoteControl.SetEnabled(true);
if (!m_RemoteControl.IsInitialized())
{
m_RemoteControl.Initialize();
}
#endif
}
void CInputManager::DisableRemoteControl()
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
m_RemoteControl.Disconnect();
m_RemoteControl.SetEnabled(false);
#endif
}
void CInputManager::InitializeRemoteControl()
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
if (!m_RemoteControl.IsInitialized())
m_RemoteControl.Initialize();
#endif
}
void CInputManager::SetRemoteControlName(const std::string& name)
{
#if defined(HAS_LIRC) || defined(HAS_IRSERVERSUITE)
m_RemoteControl.SetDeviceName(name);
#endif
}
void CInputManager::OnSettingChanged(const CSetting *setting)
{
if (setting == nullptr)
return;
const std::string &settingId = setting->GetId();
if (settingId == CSettings::SETTING_INPUT_ENABLEMOUSE)
m_Mouse.SetEnabled(dynamic_cast<const CSettingBool*>(setting)->GetValue());
#if defined(HAS_SDL_JOYSTICK)
if (settingId == CSettings::SETTING_INPUT_ENABLEJOYSTICK)
m_Joystick.SetEnabled(dynamic_cast<const CSettingBool*>(setting)->GetValue() &&
PERIPHERALS::CPeripheralImon::GetCountOfImonsConflictWithDInput() == 0);
#endif
}
| gpl-2.0 |
hannesweisbach/linux-atlas | drivers/net/ethernet/netronome/nfp/bpf/verifier.c | 30 | 4910 | /*
* Copyright (C) 2016 Netronome Systems, Inc.
*
* This software is dual licensed under the GNU General License Version 2,
* June 1991 as shown in the file COPYING in the top-level directory of this
* source tree or the BSD 2-Clause License provided below. You have the
* option to license this software under the complete terms of either license.
*
* The BSD 2-Clause License:
*
* 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.
*
* 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.
*/
#define pr_fmt(fmt) "NFP net bpf: " fmt
#include <linux/bpf.h>
#include <linux/bpf_verifier.h>
#include <linux/kernel.h>
#include <linux/pkt_cls.h>
#include "main.h"
/* Analyzer/verifier definitions */
struct nfp_bpf_analyzer_priv {
struct nfp_prog *prog;
struct nfp_insn_meta *meta;
};
static struct nfp_insn_meta *
nfp_bpf_goto_meta(struct nfp_prog *nfp_prog, struct nfp_insn_meta *meta,
unsigned int insn_idx, unsigned int n_insns)
{
unsigned int forward, backward, i;
backward = meta->n - insn_idx;
forward = insn_idx - meta->n;
if (min(forward, backward) > n_insns - insn_idx - 1) {
backward = n_insns - insn_idx - 1;
meta = nfp_prog_last_meta(nfp_prog);
}
if (min(forward, backward) > insn_idx && backward > insn_idx) {
forward = insn_idx;
meta = nfp_prog_first_meta(nfp_prog);
}
if (forward < backward)
for (i = 0; i < forward; i++)
meta = nfp_meta_next(meta);
else
for (i = 0; i < backward; i++)
meta = nfp_meta_prev(meta);
return meta;
}
static int
nfp_bpf_check_exit(struct nfp_prog *nfp_prog,
const struct bpf_verifier_env *env)
{
const struct bpf_reg_state *reg0 = &env->cur_state.regs[0];
if (nfp_prog->act == NN_ACT_XDP)
return 0;
if (reg0->type != CONST_IMM) {
pr_info("unsupported exit state: %d, imm: %llx\n",
reg0->type, reg0->imm);
return -EINVAL;
}
if (nfp_prog->act != NN_ACT_DIRECT &&
reg0->imm != 0 && (reg0->imm & ~0U) != ~0U) {
pr_info("unsupported exit state: %d, imm: %llx\n",
reg0->type, reg0->imm);
return -EINVAL;
}
if (nfp_prog->act == NN_ACT_DIRECT && reg0->imm <= TC_ACT_REDIRECT &&
reg0->imm != TC_ACT_SHOT && reg0->imm != TC_ACT_STOLEN &&
reg0->imm != TC_ACT_QUEUED) {
pr_info("unsupported exit state: %d, imm: %llx\n",
reg0->type, reg0->imm);
return -EINVAL;
}
return 0;
}
static int
nfp_bpf_check_ctx_ptr(struct nfp_prog *nfp_prog,
const struct bpf_verifier_env *env, u8 reg)
{
if (env->cur_state.regs[reg].type != PTR_TO_CTX)
return -EINVAL;
return 0;
}
static int
nfp_verify_insn(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx)
{
struct nfp_bpf_analyzer_priv *priv = env->analyzer_priv;
struct nfp_insn_meta *meta = priv->meta;
meta = nfp_bpf_goto_meta(priv->prog, meta, insn_idx, env->prog->len);
priv->meta = meta;
if (meta->insn.src_reg == BPF_REG_10 ||
meta->insn.dst_reg == BPF_REG_10) {
pr_err("stack not yet supported\n");
return -EINVAL;
}
if (meta->insn.src_reg >= MAX_BPF_REG ||
meta->insn.dst_reg >= MAX_BPF_REG) {
pr_err("program uses extended registers - jit hardening?\n");
return -EINVAL;
}
if (meta->insn.code == (BPF_JMP | BPF_EXIT))
return nfp_bpf_check_exit(priv->prog, env);
if ((meta->insn.code & ~BPF_SIZE_MASK) == (BPF_LDX | BPF_MEM))
return nfp_bpf_check_ctx_ptr(priv->prog, env,
meta->insn.src_reg);
if ((meta->insn.code & ~BPF_SIZE_MASK) == (BPF_STX | BPF_MEM))
return nfp_bpf_check_ctx_ptr(priv->prog, env,
meta->insn.dst_reg);
return 0;
}
static const struct bpf_ext_analyzer_ops nfp_bpf_analyzer_ops = {
.insn_hook = nfp_verify_insn,
};
int nfp_prog_verify(struct nfp_prog *nfp_prog, struct bpf_prog *prog)
{
struct nfp_bpf_analyzer_priv *priv;
int ret;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->prog = nfp_prog;
priv->meta = nfp_prog_first_meta(nfp_prog);
ret = bpf_analyzer(prog, &nfp_bpf_analyzer_ops, priv);
kfree(priv);
return ret;
}
| gpl-2.0 |
krichter722/gcc | gcc/testsuite/gcc.target/s390/target-attribute/tattr-m64-6.c | 30 | 18073 | /* Functional tests for the "target" attribute and pragma. */
/* { dg-do assemble { target { lp64 } } } */
/* { dg-require-effective-target target_attribute } */
/* { dg-options "-save-temps -mdebug -m64 -march=z10 -mtune=z13 -mstack-size=2048 -mstack-guard=16 -mbranch-cost=1 -mwarn-framesize=512 -mno-hard-dfp -mbackchain -msoft-float -mno-vx -mno-htm -mno-packed-stack -msmall-exec -mno-zvector -mmvcle -mzarch -mno-warn-dynamicstack" } */
/**
**
** Start
**
**/
void fn_default_start (void) { }
/* { dg-final { scan-assembler "fn:fn_default_start ar6" } } */
/* { dg-final { scan-assembler "fn:fn_default_start tu9" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_default_start sg16" } } */
/* { dg-final { scan-assembler "fn:fn_default_start bc1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start wf512" } } */
/* { dg-final { scan-assembler "fn:fn_default_start hd0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ba1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start hf0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start vx0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ht0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start ps0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start se1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start zv0" } } */
/* { dg-final { scan-assembler "fn:fn_default_start mv1" } } */
/* { dg-final { scan-assembler "fn:fn_default_start wd0" } } */
/**
**
** Attribute
**
**/
__attribute__ ((target ("stack-size=2048")))
void fn_att_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_att_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 se1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0 wd0" } } */
void fn_att_0_default (void) { }
__attribute__ ((target ("stack-size=4096")))
void fn_att_1 (void) { }
/* { dg-final { scan-assembler "fn:fn_att_1 ss4096" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 se1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1 wd0" } } */
void fn_att_1_default (void) { }
__attribute__ ((target ("stack-size=4096,stack-size=2048")))
void fn_att_1_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_att_1_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 se1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_att_1_0 wd0" } } */
__attribute__ ((target ("stack-size=2048,stack-size=4096")))
void fn_att_0_1 (void) { }
/* { dg-final { scan-assembler "fn:fn_att_0_1 ss4096" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 se1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_att_0_1 wd0" } } */
/**
**
** Pragma
**
**/
#pragma GCC target ("stack-size=2048")
void fn_pragma_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0 wd0" } } */
#pragma GCC reset_options
void fn_pragma_0_default (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_0_default ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_default wd0" } } */
#pragma GCC target ("stack-size=4096")
void fn_pragma_1 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_1 ss4096" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1 wd0" } } */
#pragma GCC reset_options
void fn_pragma_1_default (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_1_default ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_default wd0" } } */
#pragma GCC target ("stack-size=4096")
#pragma GCC target ("stack-size=2048")
void fn_pragma_1_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_0 wd0" } } */
#pragma GCC reset_options
#pragma GCC target ("stack-size=2048")
#pragma GCC target ("stack-size=4096")
void fn_pragma_0_1 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 ss4096" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_1 wd0" } } */
#pragma GCC reset_options
/**
**
** Pragma and attribute
**
**/
#pragma GCC target ("stack-size=2048")
__attribute__ ((target ("stack-size=2048")))
void fn_pragma_0_att_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_0 wd0" } } */
#pragma GCC reset_options
#pragma GCC target ("stack-size=2048")
__attribute__ ((target ("stack-size=2048")))
void fn_pragma_1_att_0 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_0 wd0" } } */
#pragma GCC reset_options
#pragma GCC target ("stack-size=2048")
__attribute__ ((target ("stack-size=4096")))
void fn_pragma_0_att_1 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ss4096" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_0_att_1 wd0" } } */
#pragma GCC reset_options
#pragma GCC target ("stack-size=2048")
__attribute__ ((target ("stack-size=4096")))
void fn_pragma_1_att_1 (void) { }
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ss4096" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ar6" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 tu9" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 sg16" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 bc1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 wf512" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 hd0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ba1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 hf0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 vx0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ht0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 ps0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 se1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 zv0" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 mv1" } } */
/* { dg-final { scan-assembler "fn:fn_pragma_1_att_1 wd0" } } */
#pragma GCC reset_options
/**
**
** End
**
**/
void fn_default_end (void) { }
/* { dg-final { scan-assembler "fn:fn_default_end ar6" } } */
/* { dg-final { scan-assembler "fn:fn_default_end tu9" } } */
/* { dg-final { scan-assembler "fn:fn_default_end ss2048" } } */
/* { dg-final { scan-assembler "fn:fn_default_end sg16" } } */
/* { dg-final { scan-assembler "fn:fn_default_end bc1" } } */
/* { dg-final { scan-assembler "fn:fn_default_end wf512" } } */
/* { dg-final { scan-assembler "fn:fn_default_end hd0" } } */
/* { dg-final { scan-assembler "fn:fn_default_end ba1" } } */
/* { dg-final { scan-assembler "fn:fn_default_end hf0" } } */
/* { dg-final { scan-assembler "fn:fn_default_end vx0" } } */
/* { dg-final { scan-assembler "fn:fn_default_end ht0" } } */
/* { dg-final { scan-assembler "fn:fn_default_end ps0" } } */
/* { dg-final { scan-assembler "fn:fn_default_end se1" } } */
/* { dg-final { scan-assembler "fn:fn_default_end zv0" } } */
/* { dg-final { scan-assembler "fn:fn_default_end mv1" } } */
/* { dg-final { scan-assembler "fn:fn_default_end wd0" } } */
| gpl-2.0 |
0xD34D/kernel_amazon_otter | arch/arm/mach-omap2/powerdomain44xx.c | 286 | 7143 | /*
* OMAP4 powerdomain control
*
* Copyright (C) 2009-2010 Texas Instruments, Inc.
* Copyright (C) 2007-2009 Nokia Corporation
*
* Derived from mach-omap2/powerdomain.c written by Paul Walmsley
* Rajendra Nayak <rnayak@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/io.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include "powerdomain.h"
#include <plat/prcm.h>
#include "prm2xxx_3xxx.h"
#include "cminst44xx.h"
#include "prm44xx.h"
#include "prcm44xx.h"
#include "prminst44xx.h"
#include "prm-regbits-44xx.h"
#include "cm-regbits-44xx.h"
#include "cm2_44xx.h"
static int omap4_pwrdm_set_next_pwrst(struct powerdomain *pwrdm, u8 pwrst)
{
omap4_prminst_rmw_inst_reg_bits(OMAP_POWERSTATE_MASK,
(pwrst << OMAP_POWERSTATE_SHIFT),
pwrdm->prcm_partition,
pwrdm->prcm_offs, OMAP4_PM_PWSTCTRL);
return 0;
}
static int omap4_pwrdm_read_next_pwrst(struct powerdomain *pwrdm)
{
u32 v;
v = omap4_prminst_read_inst_reg(pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTCTRL);
v &= OMAP_POWERSTATE_MASK;
v >>= OMAP_POWERSTATE_SHIFT;
return v;
}
static int omap4_pwrdm_read_pwrst(struct powerdomain *pwrdm)
{
u32 v;
v = omap4_prminst_read_inst_reg(pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTST);
v &= OMAP_POWERSTATEST_MASK;
v >>= OMAP_POWERSTATEST_SHIFT;
return v;
}
static int omap4_pwrdm_read_prev_pwrst(struct powerdomain *pwrdm)
{
u32 v;
v = omap4_prminst_read_inst_reg(pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTST);
v &= OMAP4430_LASTPOWERSTATEENTERED_MASK;
v >>= OMAP4430_LASTPOWERSTATEENTERED_SHIFT;
return v;
}
static int omap4_pwrdm_set_lowpwrstchange(struct powerdomain *pwrdm)
{
omap4_prminst_rmw_inst_reg_bits(OMAP4430_LOWPOWERSTATECHANGE_MASK,
(1 << OMAP4430_LOWPOWERSTATECHANGE_SHIFT),
pwrdm->prcm_partition,
pwrdm->prcm_offs, OMAP4_PM_PWSTCTRL);
return 0;
}
static int omap4_pwrdm_clear_all_prev_pwrst(struct powerdomain *pwrdm)
{
omap4_prminst_rmw_inst_reg_bits(OMAP4430_LASTPOWERSTATEENTERED_MASK,
OMAP4430_LASTPOWERSTATEENTERED_MASK,
pwrdm->prcm_partition,
pwrdm->prcm_offs, OMAP4_PM_PWSTST);
return 0;
}
static int omap4_pwrdm_set_logic_retst(struct powerdomain *pwrdm, u8 pwrst)
{
u32 v;
v = pwrst << __ffs(OMAP4430_LOGICRETSTATE_MASK);
omap4_prminst_rmw_inst_reg_bits(OMAP4430_LOGICRETSTATE_MASK, v,
pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTCTRL);
return 0;
}
static int omap4_pwrdm_set_mem_onst(struct powerdomain *pwrdm, u8 bank,
u8 pwrst)
{
u32 m;
m = omap2_pwrdm_get_mem_bank_onstate_mask(bank);
omap4_prminst_rmw_inst_reg_bits(m, (pwrst << __ffs(m)),
pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTCTRL);
return 0;
}
static int omap4_pwrdm_set_mem_retst(struct powerdomain *pwrdm, u8 bank,
u8 pwrst)
{
u32 m;
m = omap2_pwrdm_get_mem_bank_retst_mask(bank);
omap4_prminst_rmw_inst_reg_bits(m, (pwrst << __ffs(m)),
pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTCTRL);
return 0;
}
static int omap4_pwrdm_read_logic_pwrst(struct powerdomain *pwrdm)
{
u32 v;
v = omap4_prminst_read_inst_reg(pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTST);
v &= OMAP4430_LOGICSTATEST_MASK;
v >>= OMAP4430_LOGICSTATEST_SHIFT;
return v;
}
static int omap4_pwrdm_read_logic_retst(struct powerdomain *pwrdm)
{
u32 v;
v = omap4_prminst_read_inst_reg(pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTCTRL);
v &= OMAP4430_LOGICRETSTATE_MASK;
v >>= OMAP4430_LOGICRETSTATE_SHIFT;
return v;
}
static int omap4_pwrdm_read_mem_pwrst(struct powerdomain *pwrdm, u8 bank)
{
u32 m, v;
m = omap2_pwrdm_get_mem_bank_stst_mask(bank);
v = omap4_prminst_read_inst_reg(pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTST);
v &= m;
v >>= __ffs(m);
return v;
}
static int omap4_pwrdm_read_mem_retst(struct powerdomain *pwrdm, u8 bank)
{
u32 m, v;
m = omap2_pwrdm_get_mem_bank_retst_mask(bank);
v = omap4_prminst_read_inst_reg(pwrdm->prcm_partition, pwrdm->prcm_offs,
OMAP4_PM_PWSTCTRL);
v &= m;
v >>= __ffs(m);
return v;
}
static int omap4_pwrdm_wait_transition(struct powerdomain *pwrdm)
{
u32 c = 0;
/*
* REVISIT: pwrdm_wait_transition() may be better implemented
* via a callback and a periodic timer check -- how long do we expect
* powerdomain transitions to take?
*/
/* XXX Is this udelay() value meaningful? */
while ((omap4_prminst_read_inst_reg(pwrdm->prcm_partition,
pwrdm->prcm_offs,
OMAP4_PM_PWSTST) &
OMAP_INTRANSITION_MASK) &&
(c++ < PWRDM_TRANSITION_BAILOUT))
udelay(1);
if (c > PWRDM_TRANSITION_BAILOUT) {
printk(KERN_ERR "powerdomain: waited too long for "
"powerdomain %s to complete transition\n", pwrdm->name);
return -EAGAIN;
}
pr_debug("powerdomain: completed transition in %d loops\n", c);
return 0;
}
static int omap4_pwrdm_enable_hdwr_sar(struct powerdomain *pwrdm)
{
/*
* FIXME: This should be fixed right way by moving it into HWMOD
* or clock framework since sar control is moved to module level
*/
omap4_cminst_rmw_inst_reg_bits(OMAP4430_SAR_MODE_MASK,
1 << OMAP4430_SAR_MODE_SHIFT, OMAP4430_CM2_PARTITION,
OMAP4430_CM2_L3INIT_INST,
OMAP4_CM_L3INIT_USB_HOST_CLKCTRL_OFFSET);
omap4_cminst_rmw_inst_reg_bits(OMAP4430_SAR_MODE_MASK,
1 << OMAP4430_SAR_MODE_SHIFT, OMAP4430_CM2_PARTITION,
OMAP4430_CM2_L3INIT_INST,
OMAP4_CM_L3INIT_USB_TLL_CLKCTRL_OFFSET);
return 0;
}
static int omap4_pwrdm_disable_hdwr_sar(struct powerdomain *pwrdm)
{
/*
* FIXME: This should be fixed right way by moving it into HWMOD
* or clock framework since sar control is moved to module level
*/
omap4_cminst_rmw_inst_reg_bits(OMAP4430_SAR_MODE_MASK,
0 << OMAP4430_SAR_MODE_SHIFT, OMAP4430_CM2_PARTITION,
OMAP4430_CM2_L3INIT_INST,
OMAP4_CM_L3INIT_USB_HOST_CLKCTRL_OFFSET);
omap4_cminst_rmw_inst_reg_bits(OMAP4430_SAR_MODE_MASK,
0 << OMAP4430_SAR_MODE_SHIFT, OMAP4430_CM2_PARTITION,
OMAP4430_CM2_L3INIT_INST,
OMAP4_CM_L3INIT_USB_TLL_CLKCTRL_OFFSET);
return 0;
}
struct pwrdm_ops omap4_pwrdm_operations = {
.pwrdm_set_next_pwrst = omap4_pwrdm_set_next_pwrst,
.pwrdm_read_next_pwrst = omap4_pwrdm_read_next_pwrst,
.pwrdm_read_pwrst = omap4_pwrdm_read_pwrst,
.pwrdm_read_prev_pwrst = omap4_pwrdm_read_prev_pwrst,
.pwrdm_set_lowpwrstchange = omap4_pwrdm_set_lowpwrstchange,
.pwrdm_clear_all_prev_pwrst = omap4_pwrdm_clear_all_prev_pwrst,
.pwrdm_set_logic_retst = omap4_pwrdm_set_logic_retst,
.pwrdm_read_logic_pwrst = omap4_pwrdm_read_logic_pwrst,
.pwrdm_read_logic_retst = omap4_pwrdm_read_logic_retst,
.pwrdm_read_mem_pwrst = omap4_pwrdm_read_mem_pwrst,
.pwrdm_read_mem_retst = omap4_pwrdm_read_mem_retst,
.pwrdm_set_mem_onst = omap4_pwrdm_set_mem_onst,
.pwrdm_set_mem_retst = omap4_pwrdm_set_mem_retst,
.pwrdm_wait_transition = omap4_pwrdm_wait_transition,
.pwrdm_enable_hdwr_sar = omap4_pwrdm_enable_hdwr_sar,
.pwrdm_disable_hdwr_sar = omap4_pwrdm_disable_hdwr_sar,
};
| gpl-2.0 |
myjang0507/updatesource | net/ipv4/netfilter/ip_tables.c | 542 | 56244 | /*
* Packet matching code.
*
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
* Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
* Copyright (C) 2006-2010 Patrick McHardy <kaber@trash.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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/cache.h>
#include <linux/capability.h>
#include <linux/skbuff.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/icmp.h>
#include <net/ip.h>
#include <net/compat.h>
#include <asm/uaccess.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/err.h>
#include <linux/cpumask.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <net/netfilter/nf_log.h>
#include "../../netfilter/xt_repldata.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
MODULE_DESCRIPTION("IPv4 packet filter");
/*#define DEBUG_IP_FIREWALL*/
/*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */
/*#define DEBUG_IP_FIREWALL_USER*/
#ifdef DEBUG_IP_FIREWALL
#define dprintf(format, args...) pr_info(format , ## args)
#else
#define dprintf(format, args...)
#endif
#ifdef DEBUG_IP_FIREWALL_USER
#define duprintf(format, args...) pr_info(format , ## args)
#else
#define duprintf(format, args...)
#endif
#ifdef CONFIG_NETFILTER_DEBUG
#define IP_NF_ASSERT(x) WARN_ON(!(x))
#else
#define IP_NF_ASSERT(x)
#endif
#if 0
/* All the better to debug you with... */
#define static
#define inline
#endif
void *ipt_alloc_initial_table(const struct xt_table *info)
{
return xt_alloc_initial_table(ipt, IPT);
}
EXPORT_SYMBOL_GPL(ipt_alloc_initial_table);
/* Returns whether matches rule or not. */
/* Performance critical - called for every packet */
static inline bool
ip_packet_match(const struct iphdr *ip,
const char *indev,
const char *outdev,
const struct ipt_ip *ipinfo,
int isfrag)
{
unsigned long ret;
#define FWINV(bool, invflg) ((bool) ^ !!(ipinfo->invflags & (invflg)))
if (FWINV((ip->saddr&ipinfo->smsk.s_addr) != ipinfo->src.s_addr,
IPT_INV_SRCIP) ||
FWINV((ip->daddr&ipinfo->dmsk.s_addr) != ipinfo->dst.s_addr,
IPT_INV_DSTIP)) {
dprintf("Source or dest mismatch.\n");
dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n",
&ip->saddr, &ipinfo->smsk.s_addr, &ipinfo->src.s_addr,
ipinfo->invflags & IPT_INV_SRCIP ? " (INV)" : "");
dprintf("DST: %pI4 Mask: %pI4 Target: %pI4.%s\n",
&ip->daddr, &ipinfo->dmsk.s_addr, &ipinfo->dst.s_addr,
ipinfo->invflags & IPT_INV_DSTIP ? " (INV)" : "");
return false;
}
ret = ifname_compare_aligned(indev, ipinfo->iniface, ipinfo->iniface_mask);
if (FWINV(ret != 0, IPT_INV_VIA_IN)) {
dprintf("VIA in mismatch (%s vs %s).%s\n",
indev, ipinfo->iniface,
ipinfo->invflags&IPT_INV_VIA_IN ?" (INV)":"");
return false;
}
ret = ifname_compare_aligned(outdev, ipinfo->outiface, ipinfo->outiface_mask);
if (FWINV(ret != 0, IPT_INV_VIA_OUT)) {
dprintf("VIA out mismatch (%s vs %s).%s\n",
outdev, ipinfo->outiface,
ipinfo->invflags&IPT_INV_VIA_OUT ?" (INV)":"");
return false;
}
/* Check specific protocol */
if (ipinfo->proto &&
FWINV(ip->protocol != ipinfo->proto, IPT_INV_PROTO)) {
dprintf("Packet protocol %hi does not match %hi.%s\n",
ip->protocol, ipinfo->proto,
ipinfo->invflags&IPT_INV_PROTO ? " (INV)":"");
return false;
}
/* If we have a fragment rule but the packet is not a fragment
* then we return zero */
if (FWINV((ipinfo->flags&IPT_F_FRAG) && !isfrag, IPT_INV_FRAG)) {
dprintf("Fragment rule but not fragment.%s\n",
ipinfo->invflags & IPT_INV_FRAG ? " (INV)" : "");
return false;
}
return true;
}
static bool
ip_checkentry(const struct ipt_ip *ip)
{
if (ip->flags & ~IPT_F_MASK) {
duprintf("Unknown flag bits set: %08X\n",
ip->flags & ~IPT_F_MASK);
return false;
}
if (ip->invflags & ~IPT_INV_MASK) {
duprintf("Unknown invflag bits set: %08X\n",
ip->invflags & ~IPT_INV_MASK);
return false;
}
return true;
}
static unsigned int
ipt_error(struct sk_buff *skb, const struct xt_action_param *par)
{
net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo);
return NF_DROP;
}
/* Performance critical */
static inline struct ipt_entry *
get_entry(const void *base, unsigned int offset)
{
return (struct ipt_entry *)(base + offset);
}
/* All zeroes == unconditional rule. */
/* Mildly perf critical (only if packet tracing is on) */
static inline bool unconditional(const struct ipt_ip *ip)
{
static const struct ipt_ip uncond;
return memcmp(ip, &uncond, sizeof(uncond)) == 0;
#undef FWINV
}
/* for const-correctness */
static inline const struct xt_entry_target *
ipt_get_target_c(const struct ipt_entry *e)
{
return ipt_get_target((struct ipt_entry *)e);
}
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
static const char *const hooknames[] = {
[NF_INET_PRE_ROUTING] = "PREROUTING",
[NF_INET_LOCAL_IN] = "INPUT",
[NF_INET_FORWARD] = "FORWARD",
[NF_INET_LOCAL_OUT] = "OUTPUT",
[NF_INET_POST_ROUTING] = "POSTROUTING",
};
enum nf_ip_trace_comments {
NF_IP_TRACE_COMMENT_RULE,
NF_IP_TRACE_COMMENT_RETURN,
NF_IP_TRACE_COMMENT_POLICY,
};
static const char *const comments[] = {
[NF_IP_TRACE_COMMENT_RULE] = "rule",
[NF_IP_TRACE_COMMENT_RETURN] = "return",
[NF_IP_TRACE_COMMENT_POLICY] = "policy",
};
static struct nf_loginfo trace_loginfo = {
.type = NF_LOG_TYPE_LOG,
.u = {
.log = {
.level = 4,
.logflags = NF_LOG_MASK,
},
},
};
/* Mildly perf critical (only if packet tracing is on) */
static inline int
get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e,
const char *hookname, const char **chainname,
const char **comment, unsigned int *rulenum)
{
const struct xt_standard_target *t = (void *)ipt_get_target_c(s);
if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
/* Head of user chain: ERROR target with chainname */
*chainname = t->target.data;
(*rulenum) = 0;
} else if (s == e) {
(*rulenum)++;
if (s->target_offset == sizeof(struct ipt_entry) &&
strcmp(t->target.u.kernel.target->name,
XT_STANDARD_TARGET) == 0 &&
t->verdict < 0 &&
unconditional(&s->ip)) {
/* Tail of chains: STANDARD target (return/policy) */
*comment = *chainname == hookname
? comments[NF_IP_TRACE_COMMENT_POLICY]
: comments[NF_IP_TRACE_COMMENT_RETURN];
}
return 1;
} else
(*rulenum)++;
return 0;
}
static void trace_packet(const struct sk_buff *skb,
unsigned int hook,
const struct net_device *in,
const struct net_device *out,
const char *tablename,
const struct xt_table_info *private,
const struct ipt_entry *e)
{
const void *table_base;
const struct ipt_entry *root;
const char *hookname, *chainname, *comment;
const struct ipt_entry *iter;
unsigned int rulenum = 0;
struct net *net = dev_net(in ? in : out);
table_base = private->entries[smp_processor_id()];
root = get_entry(table_base, private->hook_entry[hook]);
hookname = chainname = hooknames[hook];
comment = comments[NF_IP_TRACE_COMMENT_RULE];
xt_entry_foreach(iter, root, private->size - private->hook_entry[hook])
if (get_chainname_rulenum(iter, e, hookname,
&chainname, &comment, &rulenum) != 0)
break;
nf_log_packet(net, AF_INET, hook, skb, in, out, &trace_loginfo,
"TRACE: %s:%s:%s:%u ",
tablename, chainname, comment, rulenum);
}
#endif
static inline __pure
struct ipt_entry *ipt_next_entry(const struct ipt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Returns one of the generic firewall policies, like NF_ACCEPT. */
unsigned int
ipt_do_table(struct sk_buff *skb,
unsigned int hook,
const struct net_device *in,
const struct net_device *out,
struct xt_table *table)
{
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
const struct iphdr *ip;
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ipt_entry *e, **jumpstack;
unsigned int *stackptr, origptr, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
ip = ip_hdr(skb);
indev = in ? in->name : nulldevname;
outdev = out ? out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET;
acpar.thoff = ip_hdrlen(skb);
acpar.hotdrop = false;
acpar.in = in;
acpar.out = out;
acpar.family = NFPROTO_IPV4;
acpar.hooknum = hook;
IP_NF_ASSERT(table->valid_hooks & (1 << hook));
local_bh_disable();
addend = xt_write_recseq_begin();
private = table->private;
cpu = smp_processor_id();
table_base = private->entries[cpu];
jumpstack = (struct ipt_entry **)private->jumpstack[cpu];
stackptr = per_cpu_ptr(private->stackptr, cpu);
origptr = *stackptr;
e = get_entry(table_base, private->hook_entry[hook]);
pr_debug("Entering %s(hook %u); sp at %u (UF %p)\n",
table->name, hook, origptr,
get_entry(table_base, private->underflow[hook]));
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
IP_NF_ASSERT(e);
if (!ip_packet_match(ip, indev, outdev,
&e->ip, acpar.fragoff)) {
no_match:
e = ipt_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
ADD_COUNTER(e->counters, skb->len, 1);
t = ipt_get_target(e);
IP_NF_ASSERT(t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(skb, hook, in, out,
table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (*stackptr <= origptr) {
e = get_entry(table_base,
private->underflow[hook]);
pr_debug("Underflow (this is normal) "
"to %p\n", e);
} else {
e = jumpstack[--*stackptr];
pr_debug("Pulled %p out from pos %u\n",
e, *stackptr);
e = ipt_next_entry(e);
}
continue;
}
if (table_base + v != ipt_next_entry(e) &&
!(e->ip.flags & IPT_F_GOTO)) {
if (*stackptr >= private->stacksize) {
verdict = NF_DROP;
break;
}
jumpstack[(*stackptr)++] = e;
pr_debug("Pushed %p into pos %u\n",
e, *stackptr - 1);
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
/* Target might have changed stuff. */
ip = ip_hdr(skb);
if (verdict == XT_CONTINUE)
e = ipt_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
pr_debug("Exiting %s; resetting sp from %u to %u\n",
__func__, *stackptr, origptr);
*stackptr = origptr;
xt_write_recseq_end(addend);
local_bh_enable();
#ifdef DEBUG_ALLOW_ALL
return NF_ACCEPT;
#else
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
#endif
}
/* Figures out from what hook each rule can be called: returns 0 if
there are loops. Puts hook bitmask in comefrom. */
static int
mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
to 0 as we leave), and comefrom to save source hook bitmask */
for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)ipt_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
pr_err("iptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct ipt_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 && unconditional(&e->ip)) ||
visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
big jump. */
do {
e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
if (e->comefrom
& (1 << NF_INET_NUMHOOKS)) {
duprintf("Back unset "
"on hook %u "
"rule %u\n",
hook, pos);
}
#endif
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct ipt_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct ipt_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct ipt_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct ipt_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
static void cleanup_match(struct xt_entry_match *m, struct net *net)
{
struct xt_mtdtor_param par;
par.net = net;
par.match = m->u.kernel.match;
par.matchinfo = m->data;
par.family = NFPROTO_IPV4;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
}
static int
check_entry(const struct ipt_entry *e, const char *name)
{
const struct xt_entry_target *t;
if (!ip_checkentry(&e->ip)) {
duprintf("ip check failed %p %s.\n", e, name);
return -EINVAL;
}
if (e->target_offset + sizeof(struct xt_entry_target) >
e->next_offset)
return -EINVAL;
t = ipt_get_target_c(e);
if (e->target_offset + t->u.target_size > e->next_offset)
return -EINVAL;
return 0;
}
static int
check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
const struct ipt_ip *ip = par->entryinfo;
int ret;
par->match = m->u.kernel.match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->u.match_size - sizeof(*m),
ip->proto, ip->invflags & IPT_INV_PROTO);
if (ret < 0) {
duprintf("check failed for `%s'.\n", par->match->name);
return ret;
}
return 0;
}
static int
find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
struct xt_match *match;
int ret;
match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("find_check_match: `%s' not found\n", m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
ret = check_match(m, par);
if (ret)
goto err;
return 0;
err:
module_put(m->u.kernel.match->me);
return ret;
}
static int check_target(struct ipt_entry *e, struct net *net, const char *name)
{
struct xt_entry_target *t = ipt_get_target(e);
struct xt_tgchk_param par = {
.net = net,
.table = name,
.entryinfo = e,
.target = t->u.kernel.target,
.targinfo = t->data,
.hook_mask = e->comefrom,
.family = NFPROTO_IPV4,
};
int ret;
ret = xt_check_target(&par, t->u.target_size - sizeof(*t),
e->ip.proto, e->ip.invflags & IPT_INV_PROTO);
if (ret < 0) {
duprintf("check failed for `%s'.\n",
t->u.kernel.target->name);
return ret;
}
return 0;
}
static int
find_check_entry(struct ipt_entry *e, struct net *net, const char *name,
unsigned int size)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
unsigned int j;
struct xt_mtchk_param mtpar;
struct xt_entry_match *ematch;
ret = check_entry(e, name);
if (ret)
return ret;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ip;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV4;
xt_ematch_foreach(ematch, e) {
ret = find_check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
t = ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("find_check_entry: `%s' not found\n", t->u.user.name);
ret = PTR_ERR(target);
goto cleanup_matches;
}
t->u.kernel.target = target;
ret = check_target(e, net, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
return ret;
}
static bool check_underflow(const struct ipt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->ip))
return false;
t = ipt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
static int
check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
static void
cleanup_entry(struct ipt_entry *e, struct net *net)
{
struct xt_tgdtor_param par;
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
cleanup_match(ematch, net);
t = ipt_get_target(e);
par.net = net;
par.target = t->u.kernel.target;
par.targinfo = t->data;
par.family = NFPROTO_IPV4;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
}
/* Checks and translates the user-supplied table segment (held in
newinfo) */
static int
translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0,
const struct ipt_replace *repl)
{
struct ipt_entry *iter;
unsigned int i;
int ret = 0;
newinfo->size = repl->size;
newinfo->number = repl->num_entries;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = 0xFFFFFFFF;
newinfo->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_table: size %u\n", newinfo->size);
i = 0;
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = check_entry_size_and_hooks(iter, newinfo, entry0,
entry0 + repl->size,
repl->hook_entry,
repl->underflow,
repl->valid_hooks);
if (ret != 0)
return ret;
++i;
if (strcmp(ipt_get_target(iter)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (i != repl->num_entries) {
duprintf("translate_table: %u not %u entries\n",
i, repl->num_entries);
return -EINVAL;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(repl->valid_hooks & (1 << i)))
continue;
if (newinfo->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, repl->hook_entry[i]);
return -EINVAL;
}
if (newinfo->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, repl->underflow[i]);
return -EINVAL;
}
}
if (!mark_source_chains(newinfo, repl->valid_hooks, entry0))
return -ELOOP;
/* Finally, each sanity check must pass */
i = 0;
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = find_check_entry(iter, net, repl->name, repl->size);
if (ret != 0)
break;
++i;
}
if (ret != 0) {
xt_entry_foreach(iter, entry0, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter, net);
}
return ret;
}
/* And one copy for every other CPU */
for_each_possible_cpu(i) {
if (newinfo->entries[i] && newinfo->entries[i] != entry0)
memcpy(newinfo->entries[i], entry0, newinfo->size);
}
return ret;
}
static void
get_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct ipt_entry *iter;
unsigned int cpu;
unsigned int i;
for_each_possible_cpu(cpu) {
seqcount_t *s = &per_cpu(xt_recseq, cpu);
i = 0;
xt_entry_foreach(iter, t->entries[cpu], t->size) {
u64 bcnt, pcnt;
unsigned int start;
do {
start = read_seqcount_begin(s);
bcnt = iter->counters.bcnt;
pcnt = iter->counters.pcnt;
} while (read_seqcount_retry(s, start));
ADD_COUNTER(counters[i], bcnt, pcnt);
++i; /* macro does multi eval of i */
}
}
}
static struct xt_counters *alloc_counters(const struct xt_table *table)
{
unsigned int countersize;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
/* We need atomic snapshot of counters: rest doesn't change
(other than comefrom, which userspace doesn't care
about). */
countersize = sizeof(struct xt_counters) * private->number;
counters = vzalloc(countersize);
if (counters == NULL)
return ERR_PTR(-ENOMEM);
get_counters(private, counters);
return counters;
}
static int
copy_entries_to_user(unsigned int total_size,
const struct xt_table *table,
void __user *userptr)
{
unsigned int off, num;
const struct ipt_entry *e;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
int ret = 0;
const void *loc_cpu_entry;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
/* choose the copy that is on our node/cpu, ...
* This choice is lazy (because current thread is
* allowed to migrate to another cpu)
*/
loc_cpu_entry = private->entries[raw_smp_processor_id()];
if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
ret = -EFAULT;
goto free_counters;
}
/* FIXME: use iterator macros --RR */
/* ... then go back and fix counters and names */
for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
unsigned int i;
const struct xt_entry_match *m;
const struct xt_entry_target *t;
e = (struct ipt_entry *)(loc_cpu_entry + off);
if (copy_to_user(userptr + off
+ offsetof(struct ipt_entry, counters),
&counters[num],
sizeof(counters[num])) != 0) {
ret = -EFAULT;
goto free_counters;
}
for (i = sizeof(struct ipt_entry);
i < e->target_offset;
i += m->u.match_size) {
m = (void *)e + i;
if (copy_to_user(userptr + off + i
+ offsetof(struct xt_entry_match,
u.user.name),
m->u.kernel.match->name,
strlen(m->u.kernel.match->name)+1)
!= 0) {
ret = -EFAULT;
goto free_counters;
}
}
t = ipt_get_target_c(e);
if (copy_to_user(userptr + off + e->target_offset
+ offsetof(struct xt_entry_target,
u.user.name),
t->u.kernel.target->name,
strlen(t->u.kernel.target->name)+1) != 0) {
ret = -EFAULT;
goto free_counters;
}
}
free_counters:
vfree(counters);
return ret;
}
#ifdef CONFIG_COMPAT
static void compat_standard_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v > 0)
v += xt_compat_calc_jump(AF_INET, v);
memcpy(dst, &v, sizeof(v));
}
static int compat_standard_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv > 0)
cv -= xt_compat_calc_jump(AF_INET, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
static int compat_calc_entry(const struct ipt_entry *e,
const struct xt_table_info *info,
const void *base, struct xt_table_info *newinfo)
{
const struct xt_entry_match *ematch;
const struct xt_entry_target *t;
unsigned int entry_offset;
int off, i, ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - base;
xt_ematch_foreach(ematch, e)
off += xt_compat_match_offset(ematch->u.kernel.match);
t = ipt_get_target_c(e);
off += xt_compat_target_offset(t->u.kernel.target);
newinfo->size -= off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
if (info->hook_entry[i] &&
(e < (struct ipt_entry *)(base + info->hook_entry[i])))
newinfo->hook_entry[i] -= off;
if (info->underflow[i] &&
(e < (struct ipt_entry *)(base + info->underflow[i])))
newinfo->underflow[i] -= off;
}
return 0;
}
static int compat_table_info(const struct xt_table_info *info,
struct xt_table_info *newinfo)
{
struct ipt_entry *iter;
void *loc_cpu_entry;
int ret;
if (!newinfo || !info)
return -EINVAL;
/* we dont care about newinfo->entries[] */
memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
newinfo->initial_entries = 0;
loc_cpu_entry = info->entries[raw_smp_processor_id()];
xt_compat_init_offsets(AF_INET, info->number);
xt_entry_foreach(iter, loc_cpu_entry, info->size) {
ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
if (ret != 0)
return ret;
}
return 0;
}
#endif
static int get_info(struct net *net, void __user *user,
const int *len, int compat)
{
char name[XT_TABLE_MAXNAMELEN];
struct xt_table *t;
int ret;
if (*len != sizeof(struct ipt_getinfo)) {
duprintf("length %u != %zu\n", *len,
sizeof(struct ipt_getinfo));
return -EINVAL;
}
if (copy_from_user(name, user, sizeof(name)) != 0)
return -EFAULT;
name[XT_TABLE_MAXNAMELEN-1] = '\0';
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_lock(AF_INET);
#endif
t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
"iptable_%s", name);
if (!IS_ERR_OR_NULL(t)) {
struct ipt_getinfo info;
const struct xt_table_info *private = t->private;
#ifdef CONFIG_COMPAT
struct xt_table_info tmp;
if (compat) {
ret = compat_table_info(private, &tmp);
xt_compat_flush_offsets(AF_INET);
private = &tmp;
}
#endif
memset(&info, 0, sizeof(info));
info.valid_hooks = t->valid_hooks;
memcpy(info.hook_entry, private->hook_entry,
sizeof(info.hook_entry));
memcpy(info.underflow, private->underflow,
sizeof(info.underflow));
info.num_entries = private->number;
info.size = private->size;
strcpy(info.name, name);
if (copy_to_user(user, &info, *len) != 0)
ret = -EFAULT;
else
ret = 0;
xt_table_unlock(t);
module_put(t->me);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_unlock(AF_INET);
#endif
return ret;
}
static int
get_entries(struct net *net, struct ipt_get_entries __user *uptr,
const int *len)
{
int ret;
struct ipt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct ipt_get_entries) + get.size) {
duprintf("get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
t = xt_find_table_lock(net, AF_INET, get.name);
if (!IS_ERR_OR_NULL(t)) {
const struct xt_table_info *private = t->private;
duprintf("t->private->number = %u\n", private->number);
if (get.size == private->size)
ret = copy_entries_to_user(private->size,
t, uptr->entrytable);
else {
duprintf("get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
return ret;
}
static int
__do_replace(struct net *net, const char *name, unsigned int valid_hooks,
struct xt_table_info *newinfo, unsigned int num_counters,
void __user *counters_ptr)
{
int ret;
struct xt_table *t;
struct xt_table_info *oldinfo;
struct xt_counters *counters;
void *loc_cpu_old_entry;
struct ipt_entry *iter;
ret = 0;
counters = vzalloc(num_counters * sizeof(struct xt_counters));
if (!counters) {
ret = -ENOMEM;
goto out;
}
t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
"iptable_%s", name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free_newinfo_counters_untrans;
}
/* You lied! */
if (valid_hooks != t->valid_hooks) {
duprintf("Valid hook crap: %08X vs %08X\n",
valid_hooks, t->valid_hooks);
ret = -EINVAL;
goto put_module;
}
oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
if (!oldinfo)
goto put_module;
/* Update module usage count based on number of rules */
duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n",
oldinfo->number, oldinfo->initial_entries, newinfo->number);
if ((oldinfo->number > oldinfo->initial_entries) ||
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
if ((oldinfo->number > oldinfo->initial_entries) &&
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
/* Get the old counters, and synchronize with replace */
get_counters(oldinfo, counters);
/* Decrease module usage counts and free resource */
loc_cpu_old_entry = oldinfo->entries[raw_smp_processor_id()];
xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size)
cleanup_entry(iter, net);
xt_free_table_info(oldinfo);
if (copy_to_user(counters_ptr, counters,
sizeof(struct xt_counters) * num_counters) != 0)
ret = -EFAULT;
vfree(counters);
xt_table_unlock(t);
return ret;
put_module:
module_put(t->me);
xt_table_unlock(t);
free_newinfo_counters_untrans:
vfree(counters);
out:
return ret;
}
static int
do_replace(struct net *net, const void __user *user, unsigned int len)
{
int ret;
struct ipt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ipt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
/* choose the copy that is on our node/cpu */
loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_table(net, newinfo, loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
duprintf("Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, tmp.counters);
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
do_add_counters(struct net *net, const void __user *user,
unsigned int len, int compat)
{
unsigned int i, curcpu;
struct xt_counters_info tmp;
struct xt_counters *paddc;
unsigned int num_counters;
const char *name;
int size;
void *ptmp;
struct xt_table *t;
const struct xt_table_info *private;
int ret = 0;
void *loc_cpu_entry;
struct ipt_entry *iter;
unsigned int addend;
#ifdef CONFIG_COMPAT
struct compat_xt_counters_info compat_tmp;
if (compat) {
ptmp = &compat_tmp;
size = sizeof(struct compat_xt_counters_info);
} else
#endif
{
ptmp = &tmp;
size = sizeof(struct xt_counters_info);
}
if (copy_from_user(ptmp, user, size) != 0)
return -EFAULT;
#ifdef CONFIG_COMPAT
if (compat) {
num_counters = compat_tmp.num_counters;
name = compat_tmp.name;
} else
#endif
{
num_counters = tmp.num_counters;
name = tmp.name;
}
if (len != size + num_counters * sizeof(struct xt_counters))
return -EINVAL;
paddc = vmalloc(len - size);
if (!paddc)
return -ENOMEM;
if (copy_from_user(paddc, user + size, len - size) != 0) {
ret = -EFAULT;
goto free;
}
t = xt_find_table_lock(net, AF_INET, name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free;
}
local_bh_disable();
private = t->private;
if (private->number != num_counters) {
ret = -EINVAL;
goto unlock_up_free;
}
i = 0;
/* Choose the copy that is on our node */
curcpu = smp_processor_id();
loc_cpu_entry = private->entries[curcpu];
addend = xt_write_recseq_begin();
xt_entry_foreach(iter, loc_cpu_entry, private->size) {
ADD_COUNTER(iter->counters, paddc[i].bcnt, paddc[i].pcnt);
++i;
}
xt_write_recseq_end(addend);
unlock_up_free:
local_bh_enable();
xt_table_unlock(t);
module_put(t->me);
free:
vfree(paddc);
return ret;
}
#ifdef CONFIG_COMPAT
struct compat_ipt_replace {
char name[XT_TABLE_MAXNAMELEN];
u32 valid_hooks;
u32 num_entries;
u32 size;
u32 hook_entry[NF_INET_NUMHOOKS];
u32 underflow[NF_INET_NUMHOOKS];
u32 num_counters;
compat_uptr_t counters; /* struct xt_counters * */
struct compat_ipt_entry entries[0];
};
static int
compat_copy_entry_to_user(struct ipt_entry *e, void __user **dstptr,
unsigned int *size, struct xt_counters *counters,
unsigned int i)
{
struct xt_entry_target *t;
struct compat_ipt_entry __user *ce;
u_int16_t target_offset, next_offset;
compat_uint_t origsize;
const struct xt_entry_match *ematch;
int ret = 0;
origsize = *size;
ce = (struct compat_ipt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(struct ipt_entry)) != 0 ||
copy_to_user(&ce->counters, &counters[i],
sizeof(counters[i])) != 0)
return -EFAULT;
*dstptr += sizeof(struct compat_ipt_entry);
*size -= sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_to_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
target_offset = e->target_offset - (origsize - *size);
t = ipt_get_target(e);
ret = xt_compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(target_offset, &ce->target_offset) != 0 ||
put_user(next_offset, &ce->next_offset) != 0)
return -EFAULT;
return 0;
}
static int
compat_find_calc_match(struct xt_entry_match *m,
const char *name,
const struct ipt_ip *ip,
unsigned int hookmask,
int *size)
{
struct xt_match *match;
match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("compat_check_calc_match: `%s' not found\n",
m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
*size += xt_compat_match_offset(match);
return 0;
}
static void compat_release_entry(struct compat_ipt_entry *e)
{
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
module_put(ematch->u.kernel.match->me);
t = compat_ipt_get_target(e);
module_put(t->u.kernel.target->me);
}
static int
check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e, name);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name,
&e->ip, e->comefrom, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
static int
compat_copy_entry_from_user(struct compat_ipt_entry *e, void **dstptr,
unsigned int *size, const char *name,
struct xt_table_info *newinfo, unsigned char *base)
{
struct xt_entry_target *t;
struct xt_target *target;
struct ipt_entry *de;
unsigned int origsize;
int ret, h;
struct xt_entry_match *ematch;
ret = 0;
origsize = *size;
de = (struct ipt_entry *)*dstptr;
memcpy(de, e, sizeof(struct ipt_entry));
memcpy(&de->counters, &e->counters, sizeof(e->counters));
*dstptr += sizeof(struct ipt_entry);
*size += sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_from_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
de->target_offset = e->target_offset - (origsize - *size);
t = compat_ipt_get_target(e);
target = t->u.kernel.target;
xt_compat_target_from_user(t, dstptr, size);
de->next_offset = e->next_offset - (origsize - *size);
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)de - base < newinfo->hook_entry[h])
newinfo->hook_entry[h] -= origsize - *size;
if ((unsigned char *)de - base < newinfo->underflow[h])
newinfo->underflow[h] -= origsize - *size;
}
return ret;
}
static int
compat_check_entry(struct ipt_entry *e, struct net *net, const char *name)
{
struct xt_entry_match *ematch;
struct xt_mtchk_param mtpar;
unsigned int j;
int ret = 0;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ip;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV4;
xt_ematch_foreach(ematch, e) {
ret = check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
ret = check_target(e, net, name);
if (ret)
goto cleanup_matches;
return 0;
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
return ret;
}
static int
translate_compat_table(struct net *net,
const char *name,
unsigned int valid_hooks,
struct xt_table_info **pinfo,
void **pentry0,
unsigned int total_size,
unsigned int number,
unsigned int *hook_entries,
unsigned int *underflows)
{
unsigned int i, j;
struct xt_table_info *newinfo, *info;
void *pos, *entry0, *entry1;
struct compat_ipt_entry *iter0;
struct ipt_entry *iter1;
unsigned int size;
int ret;
info = *pinfo;
entry0 = *pentry0;
size = total_size;
info->number = number;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
info->hook_entry[i] = 0xFFFFFFFF;
info->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_compat_table: size %u\n", info->size);
j = 0;
xt_compat_lock(AF_INET);
xt_compat_init_offsets(AF_INET, number);
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter0, entry0, total_size) {
ret = check_compat_entry_size_and_hooks(iter0, info, &size,
entry0,
entry0 + total_size,
hook_entries,
underflows,
name);
if (ret != 0)
goto out_unlock;
++j;
}
ret = -EINVAL;
if (j != number) {
duprintf("translate_compat_table: %u not %u entries\n",
j, number);
goto out_unlock;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(valid_hooks & (1 << i)))
continue;
if (info->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, hook_entries[i]);
goto out_unlock;
}
if (info->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, underflows[i]);
goto out_unlock;
}
}
ret = -ENOMEM;
newinfo = xt_alloc_table_info(size);
if (!newinfo)
goto out_unlock;
newinfo->number = number;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = info->hook_entry[i];
newinfo->underflow[i] = info->underflow[i];
}
entry1 = newinfo->entries[raw_smp_processor_id()];
pos = entry1;
size = total_size;
xt_entry_foreach(iter0, entry0, total_size) {
ret = compat_copy_entry_from_user(iter0, &pos, &size,
name, newinfo, entry1);
if (ret != 0)
break;
}
xt_compat_flush_offsets(AF_INET);
xt_compat_unlock(AF_INET);
if (ret)
goto free_newinfo;
ret = -ELOOP;
if (!mark_source_chains(newinfo, valid_hooks, entry1))
goto free_newinfo;
i = 0;
xt_entry_foreach(iter1, entry1, newinfo->size) {
ret = compat_check_entry(iter1, net, name);
if (ret != 0)
break;
++i;
if (strcmp(ipt_get_target(iter1)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (ret) {
/*
* The first i matches need cleanup_entry (calls ->destroy)
* because they had called ->check already. The other j-i
* entries need only release.
*/
int skip = i;
j -= i;
xt_entry_foreach(iter0, entry0, newinfo->size) {
if (skip-- > 0)
continue;
if (j-- == 0)
break;
compat_release_entry(iter0);
}
xt_entry_foreach(iter1, entry1, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter1, net);
}
xt_free_table_info(newinfo);
return ret;
}
/* And one copy for every other CPU */
for_each_possible_cpu(i)
if (newinfo->entries[i] && newinfo->entries[i] != entry1)
memcpy(newinfo->entries[i], entry1, newinfo->size);
*pinfo = newinfo;
*pentry0 = entry1;
xt_free_table_info(info);
return 0;
free_newinfo:
xt_free_table_info(newinfo);
out:
xt_entry_foreach(iter0, entry0, total_size) {
if (j-- == 0)
break;
compat_release_entry(iter0);
}
return ret;
out_unlock:
xt_compat_flush_offsets(AF_INET);
xt_compat_unlock(AF_INET);
goto out;
}
static int
compat_do_replace(struct net *net, void __user *user, unsigned int len)
{
int ret;
struct compat_ipt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ipt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.size >= INT_MAX / num_possible_cpus())
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
/* choose the copy that is on our node/cpu */
loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_compat_table(net, tmp.name, tmp.valid_hooks,
&newinfo, &loc_cpu_entry, tmp.size,
tmp.num_entries, tmp.hook_entry,
tmp.underflow);
if (ret != 0)
goto free_newinfo;
duprintf("compat_do_replace: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, compat_ptr(tmp.counters));
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
compat_do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user,
unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case IPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
duprintf("do_ipt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
struct compat_ipt_get_entries {
char name[XT_TABLE_MAXNAMELEN];
compat_uint_t size;
struct compat_ipt_entry entrytable[0];
};
static int
compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table,
void __user *userptr)
{
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
void __user *pos;
unsigned int size;
int ret = 0;
const void *loc_cpu_entry;
unsigned int i = 0;
struct ipt_entry *iter;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
/* choose the copy that is on our node/cpu, ...
* This choice is lazy (because current thread is
* allowed to migrate to another cpu)
*/
loc_cpu_entry = private->entries[raw_smp_processor_id()];
pos = userptr;
size = total_size;
xt_entry_foreach(iter, loc_cpu_entry, total_size) {
ret = compat_copy_entry_to_user(iter, &pos,
&size, counters, i++);
if (ret != 0)
break;
}
vfree(counters);
return ret;
}
static int
compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr,
int *len)
{
int ret;
struct compat_ipt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct compat_ipt_get_entries) + get.size) {
duprintf("compat_get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
xt_compat_lock(AF_INET);
t = xt_find_table_lock(net, AF_INET, get.name);
if (!IS_ERR_OR_NULL(t)) {
const struct xt_table_info *private = t->private;
struct xt_table_info info;
duprintf("t->private->number = %u\n", private->number);
ret = compat_table_info(private, &info);
if (!ret && get.size == info.size) {
ret = compat_copy_entries_to_user(private->size,
t, uptr->entrytable);
} else if (!ret) {
duprintf("compat_get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
xt_compat_flush_offsets(AF_INET);
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
xt_compat_unlock(AF_INET);
return ret;
}
static int do_ipt_get_ctl(struct sock *, int, void __user *, int *);
static int
compat_do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 1);
break;
case IPT_SO_GET_ENTRIES:
ret = compat_get_entries(sock_net(sk), user, len);
break;
default:
ret = do_ipt_get_ctl(sk, cmd, user, len);
}
return ret;
}
#endif
static int
do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_SET_REPLACE:
ret = do_replace(sock_net(sk), user, len);
break;
case IPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 0);
break;
default:
duprintf("do_ipt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int
do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 0);
break;
case IPT_SO_GET_ENTRIES:
ret = get_entries(sock_net(sk), user, len);
break;
case IPT_SO_GET_REVISION_MATCH:
case IPT_SO_GET_REVISION_TARGET: {
struct xt_get_revision rev;
int target;
if (*len != sizeof(rev)) {
ret = -EINVAL;
break;
}
if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
ret = -EFAULT;
break;
}
rev.name[sizeof(rev.name)-1] = 0;
if (cmd == IPT_SO_GET_REVISION_TARGET)
target = 1;
else
target = 0;
try_then_request_module(xt_find_revision(AF_INET, rev.name,
rev.revision,
target, &ret),
"ipt_%s", rev.name);
break;
}
default:
duprintf("do_ipt_get_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
struct xt_table *ipt_register_table(struct net *net,
const struct xt_table *table,
const struct ipt_replace *repl)
{
int ret;
struct xt_table_info *newinfo;
struct xt_table_info bootstrap = {0};
void *loc_cpu_entry;
struct xt_table *new_table;
newinfo = xt_alloc_table_info(repl->size);
if (!newinfo) {
ret = -ENOMEM;
goto out;
}
/* choose the copy on our node/cpu, but dont care about preemption */
loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
memcpy(loc_cpu_entry, repl->entries, repl->size);
ret = translate_table(net, newinfo, loc_cpu_entry, repl);
if (ret != 0)
goto out_free;
new_table = xt_register_table(net, table, &bootstrap, newinfo);
if (IS_ERR(new_table)) {
ret = PTR_ERR(new_table);
goto out_free;
}
return new_table;
out_free:
xt_free_table_info(newinfo);
out:
return ERR_PTR(ret);
}
void ipt_unregister_table(struct net *net, struct xt_table *table)
{
struct xt_table_info *private;
void *loc_cpu_entry;
struct module *table_owner = table->me;
struct ipt_entry *iter;
private = xt_unregister_table(table);
/* Decrease module usage counts and free resources */
loc_cpu_entry = private->entries[raw_smp_processor_id()];
xt_entry_foreach(iter, loc_cpu_entry, private->size)
cleanup_entry(iter, net);
if (private->number > private->initial_entries)
module_put(table_owner);
xt_free_table_info(private);
}
/* Returns 1 if the type and code is matched by the range, 0 otherwise */
static inline bool
icmp_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code,
u_int8_t type, u_int8_t code,
bool invert)
{
return ((test_type == 0xFF) ||
(type == test_type && code >= min_code && code <= max_code))
^ invert;
}
static bool
icmp_match(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct icmphdr *ic;
struct icmphdr _icmph;
const struct ipt_icmp *icmpinfo = par->matchinfo;
/* Must not be a fragment. */
if (par->fragoff != 0)
return false;
ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph);
if (ic == NULL) {
/* We've been asked to examine this packet, and we
* can't. Hence, no choice but to drop.
*/
duprintf("Dropping evil ICMP tinygram.\n");
par->hotdrop = true;
return false;
}
return icmp_type_code_match(icmpinfo->type,
icmpinfo->code[0],
icmpinfo->code[1],
ic->type, ic->code,
!!(icmpinfo->invflags&IPT_ICMP_INV));
}
static int icmp_checkentry(const struct xt_mtchk_param *par)
{
const struct ipt_icmp *icmpinfo = par->matchinfo;
/* Must specify no unknown invflags */
return (icmpinfo->invflags & ~IPT_ICMP_INV) ? -EINVAL : 0;
}
static struct xt_target ipt_builtin_tg[] __read_mostly = {
{
.name = XT_STANDARD_TARGET,
.targetsize = sizeof(int),
.family = NFPROTO_IPV4,
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = compat_standard_from_user,
.compat_to_user = compat_standard_to_user,
#endif
},
{
.name = XT_ERROR_TARGET,
.target = ipt_error,
.targetsize = XT_FUNCTION_MAXNAMELEN,
.family = NFPROTO_IPV4,
},
};
static struct nf_sockopt_ops ipt_sockopts = {
.pf = PF_INET,
.set_optmin = IPT_BASE_CTL,
.set_optmax = IPT_SO_SET_MAX+1,
.set = do_ipt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ipt_set_ctl,
#endif
.get_optmin = IPT_BASE_CTL,
.get_optmax = IPT_SO_GET_MAX+1,
.get = do_ipt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ipt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static struct xt_match ipt_builtin_mt[] __read_mostly = {
{
.name = "icmp",
.match = icmp_match,
.matchsize = sizeof(struct ipt_icmp),
.checkentry = icmp_checkentry,
.proto = IPPROTO_ICMP,
.family = NFPROTO_IPV4,
},
};
static int __net_init ip_tables_net_init(struct net *net)
{
return xt_proto_init(net, NFPROTO_IPV4);
}
static void __net_exit ip_tables_net_exit(struct net *net)
{
xt_proto_fini(net, NFPROTO_IPV4);
}
static struct pernet_operations ip_tables_net_ops = {
.init = ip_tables_net_init,
.exit = ip_tables_net_exit,
};
static int __init ip_tables_init(void)
{
int ret;
ret = register_pernet_subsys(&ip_tables_net_ops);
if (ret < 0)
goto err1;
/* No one else will be downing sem now, so we won't sleep */
ret = xt_register_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
if (ret < 0)
goto err2;
ret = xt_register_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
if (ret < 0)
goto err4;
/* Register setsockopt */
ret = nf_register_sockopt(&ipt_sockopts);
if (ret < 0)
goto err5;
pr_info("(C) 2000-2006 Netfilter Core Team\n");
return 0;
err5:
xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
err4:
xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
err2:
unregister_pernet_subsys(&ip_tables_net_ops);
err1:
return ret;
}
static void __exit ip_tables_fini(void)
{
nf_unregister_sockopt(&ipt_sockopts);
xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
unregister_pernet_subsys(&ip_tables_net_ops);
}
EXPORT_SYMBOL(ipt_register_table);
EXPORT_SYMBOL(ipt_unregister_table);
EXPORT_SYMBOL(ipt_do_table);
module_init(ip_tables_init);
module_exit(ip_tables_fini);
| gpl-2.0 |
PDWMorpheus/paradox | dep/acelite/ace/Local_Name_Space.cpp | 542 | 3703 | // $Id: Local_Name_Space.cpp 91287 2010-08-05 10:30:49Z johnnyw $
#include "ace/Local_Name_Space.h"
#include "ace/ACE.h"
#include "ace/RW_Process_Mutex.h"
#include "ace/SString.h"
#include "ace/OS_NS_string.h"
#include "ace/Truncate.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_NS_String::~ACE_NS_String (void)
{
if (this->delete_rep_)
delete [] this->rep_;
}
ACE_WCHAR_T *
ACE_NS_String::fast_rep (void) const
{
ACE_TRACE ("ACE_NS_String::fast_rep");
return this->rep_;
}
ACE_NS_String::operator ACE_NS_WString () const
{
ACE_TRACE ("ACE_NS_String::operator ACE_NS_WString");
return ACE_NS_WString (this->rep_,
(this->len_ / sizeof (ACE_WCHAR_T)) - 1);
}
size_t
ACE_NS_String::len (void) const
{
ACE_TRACE ("ACE_NS_String::len");
return this->len_;
}
char *
ACE_NS_String::char_rep (void) const
{
ACE_TRACE ("ACE_NS_String::char_rep");
ACE_NS_WString w_string (this->rep_,
(this->len_ / sizeof (ACE_WCHAR_T)) - 1);
return w_string.char_rep ();
}
ACE_NS_String::ACE_NS_String (void)
: len_ (0),
rep_ (0),
delete_rep_ (false)
{
ACE_TRACE ("ACE_NS_String::ACE_NS_String");
}
ACE_NS_String::ACE_NS_String (const ACE_NS_WString &s)
: len_ ((s.length () + 1) * sizeof (ACE_WCHAR_T)),
rep_ (s.rep ()),
delete_rep_ (true)
{
ACE_TRACE ("ACE_NS_String::ACE_NS_String");
}
int
ACE_NS_String::strstr (const ACE_NS_String &s) const
{
ACE_TRACE ("ACE_NS_String::strstr");
if (this->len_ < s.len_)
// If they're larger than we are they can't be a substring of us!
return -1;
else if (this->len_ == s.len_)
// Check if we're equal.
return *this == s ? 0 : -1;
else
{
// They're smaller than we are...
const size_t len = (this->len_ - s.len_) / sizeof (ACE_WCHAR_T);
const size_t pat_len = s.len_ / sizeof (ACE_WCHAR_T) - 1;
for (size_t i = 0; i <= len; ++i)
{
size_t j;
for (j = 0; j < pat_len; ++j)
if (this->rep_[i + j] != s.rep_[j])
break;
if (j == pat_len)
// Found a match! Return the index.
return ACE_Utils::truncate_cast<int> (i);
}
return -1;
}
}
bool
ACE_NS_String::operator == (const ACE_NS_String &s) const
{
ACE_TRACE ("ACE_NS_String::operator ==");
return this->len_ == s.len_
&& ACE_OS::memcmp ((void *) this->rep_,
(void *) s.rep_, this->len_) == 0;
}
bool
ACE_NS_String::operator != (const ACE_NS_String &s) const
{
ACE_TRACE ("ACE_NS_String::operator !=");
return !this->operator == (s);
}
ACE_NS_String::ACE_NS_String (ACE_WCHAR_T *dst,
const ACE_WCHAR_T *src,
size_t bytes)
: len_ (bytes),
rep_ (dst),
delete_rep_ (false)
{
ACE_TRACE ("ACE_NS_String::ACE_NS_String");
ACE_OS::memcpy (this->rep_, src, bytes);
}
u_long
ACE_NS_String::hash (void) const
{
return ACE::hash_pjw
(reinterpret_cast<char *> (const_cast<ACE_WCHAR_T *> (this->rep_)),
this->len_);
}
ACE_NS_Internal::ACE_NS_Internal (void)
: value_ (),
type_ ()
{
}
ACE_NS_Internal::ACE_NS_Internal (ACE_NS_String &value, const char *type)
: value_ (value),
type_ (type)
{
ACE_TRACE ("ACE_NS_Internal::ACE_NS_Internal");
}
bool
ACE_NS_Internal::operator == (const ACE_NS_Internal &s) const
{
ACE_TRACE ("ACE_NS_Internal::operator ==");
return this->value_ == s.value_;
}
ACE_NS_String
ACE_NS_Internal::value (void)
{
ACE_TRACE ("ACE_NS_Internal::value");
return this->value_;
}
const char *
ACE_NS_Internal::type (void)
{
ACE_TRACE ("ACE_NS_Internal::type");
return this->type_;
}
ACE_END_VERSIONED_NAMESPACE_DECL
| gpl-2.0 |
dimon2242/Neuro_kernel | arch/x86/kernel/acpi/boot.c | 1054 | 40722 | /*
* boot.c - Architecture-Specific Low-Level ACPI Boot Support
*
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
* Copyright (C) 2001 Jun Nakajima <jun.nakajima@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/acpi_pmtmr.h>
#include <linux/efi.h>
#include <linux/cpumask.h>
#include <linux/module.h>
#include <linux/dmi.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/bootmem.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <asm/pci_x86.h>
#include <asm/pgtable.h>
#include <asm/io_apic.h>
#include <asm/apic.h>
#include <asm/io.h>
#include <asm/mpspec.h>
#include <asm/smp.h>
static int __initdata acpi_force = 0;
u32 acpi_rsdt_forced;
int acpi_disabled;
EXPORT_SYMBOL(acpi_disabled);
#ifdef CONFIG_X86_64
# include <asm/proto.h>
# include <asm/numa_64.h>
#endif /* X86 */
#define BAD_MADT_ENTRY(entry, end) ( \
(!entry) || (unsigned long)entry + sizeof(*entry) > end || \
((struct acpi_subtable_header *)entry)->length < sizeof(*entry))
#define PREFIX "ACPI: "
int acpi_noirq; /* skip ACPI IRQ initialization */
int acpi_pci_disabled; /* skip ACPI PCI scan and IRQ initialization */
EXPORT_SYMBOL(acpi_pci_disabled);
int acpi_lapic;
int acpi_ioapic;
int acpi_strict;
u8 acpi_sci_flags __initdata;
int acpi_sci_override_gsi __initdata;
int acpi_skip_timer_override __initdata;
int acpi_use_timer_override __initdata;
int acpi_fix_pin2_polarity __initdata;
#ifdef CONFIG_X86_LOCAL_APIC
static u64 acpi_lapic_addr __initdata = APIC_DEFAULT_PHYS_BASE;
#endif
#ifndef __HAVE_ARCH_CMPXCHG
#warning ACPI uses CMPXCHG, i486 and later hardware
#endif
/* --------------------------------------------------------------------------
Boot-time Configuration
-------------------------------------------------------------------------- */
/*
* The default interrupt routing model is PIC (8259). This gets
* overridden if IOAPICs are enumerated (below).
*/
enum acpi_irq_model_id acpi_irq_model = ACPI_IRQ_MODEL_PIC;
/*
* ISA irqs by default are the first 16 gsis but can be
* any gsi as specified by an interrupt source override.
*/
static u32 isa_irq_to_gsi[NR_IRQS_LEGACY] __read_mostly = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
};
static unsigned int gsi_to_irq(unsigned int gsi)
{
unsigned int irq = gsi + NR_IRQS_LEGACY;
unsigned int i;
for (i = 0; i < NR_IRQS_LEGACY; i++) {
if (isa_irq_to_gsi[i] == gsi) {
return i;
}
}
/* Provide an identity mapping of gsi == irq
* except on truly weird platforms that have
* non isa irqs in the first 16 gsis.
*/
if (gsi >= NR_IRQS_LEGACY)
irq = gsi;
else
irq = gsi_top + gsi;
return irq;
}
static u32 irq_to_gsi(int irq)
{
unsigned int gsi;
if (irq < NR_IRQS_LEGACY)
gsi = isa_irq_to_gsi[irq];
else if (irq < gsi_top)
gsi = irq;
else if (irq < (gsi_top + NR_IRQS_LEGACY))
gsi = irq - gsi_top;
else
gsi = 0xffffffff;
return gsi;
}
/*
* Temporarily use the virtual area starting from FIX_IO_APIC_BASE_END,
* to map the target physical address. The problem is that set_fixmap()
* provides a single page, and it is possible that the page is not
* sufficient.
* By using this area, we can map up to MAX_IO_APICS pages temporarily,
* i.e. until the next __va_range() call.
*
* Important Safety Note: The fixed I/O APIC page numbers are *subtracted*
* from the fixed base. That's why we start at FIX_IO_APIC_BASE_END and
* count idx down while incrementing the phys address.
*/
char *__init __acpi_map_table(unsigned long phys, unsigned long size)
{
if (!phys || !size)
return NULL;
return early_ioremap(phys, size);
}
void __init __acpi_unmap_table(char *map, unsigned long size)
{
if (!map || !size)
return;
early_iounmap(map, size);
}
#ifdef CONFIG_X86_LOCAL_APIC
static int __init acpi_parse_madt(struct acpi_table_header *table)
{
struct acpi_table_madt *madt = NULL;
if (!cpu_has_apic)
return -EINVAL;
madt = (struct acpi_table_madt *)table;
if (!madt) {
printk(KERN_WARNING PREFIX "Unable to map MADT\n");
return -ENODEV;
}
if (madt->address) {
acpi_lapic_addr = (u64) madt->address;
printk(KERN_DEBUG PREFIX "Local APIC address 0x%08x\n",
madt->address);
}
default_acpi_madt_oem_check(madt->header.oem_id,
madt->header.oem_table_id);
return 0;
}
static void __cpuinit acpi_register_lapic(int id, u8 enabled)
{
unsigned int ver = 0;
if (id >= (MAX_LOCAL_APIC-1)) {
printk(KERN_INFO PREFIX "skipped apicid that is too big\n");
return;
}
if (!enabled) {
++disabled_cpus;
return;
}
if (boot_cpu_physical_apicid != -1U)
ver = apic_version[boot_cpu_physical_apicid];
generic_processor_info(id, ver);
}
static int __init
acpi_parse_x2apic(struct acpi_subtable_header *header, const unsigned long end)
{
struct acpi_madt_local_x2apic *processor = NULL;
processor = (struct acpi_madt_local_x2apic *)header;
if (BAD_MADT_ENTRY(processor, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
#ifdef CONFIG_X86_X2APIC
/*
* We need to register disabled CPU as well to permit
* counting disabled CPUs. This allows us to size
* cpus_possible_map more accurately, to permit
* to not preallocating memory for all NR_CPUS
* when we use CPU hotplug.
*/
acpi_register_lapic(processor->local_apic_id, /* APIC ID */
processor->lapic_flags & ACPI_MADT_ENABLED);
#else
printk(KERN_WARNING PREFIX "x2apic entry ignored\n");
#endif
return 0;
}
static int __init
acpi_parse_lapic(struct acpi_subtable_header * header, const unsigned long end)
{
struct acpi_madt_local_apic *processor = NULL;
processor = (struct acpi_madt_local_apic *)header;
if (BAD_MADT_ENTRY(processor, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
/*
* We need to register disabled CPU as well to permit
* counting disabled CPUs. This allows us to size
* cpus_possible_map more accurately, to permit
* to not preallocating memory for all NR_CPUS
* when we use CPU hotplug.
*/
acpi_register_lapic(processor->id, /* APIC ID */
processor->lapic_flags & ACPI_MADT_ENABLED);
return 0;
}
static int __init
acpi_parse_sapic(struct acpi_subtable_header *header, const unsigned long end)
{
struct acpi_madt_local_sapic *processor = NULL;
processor = (struct acpi_madt_local_sapic *)header;
if (BAD_MADT_ENTRY(processor, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
acpi_register_lapic((processor->id << 8) | processor->eid,/* APIC ID */
processor->lapic_flags & ACPI_MADT_ENABLED);
return 0;
}
static int __init
acpi_parse_lapic_addr_ovr(struct acpi_subtable_header * header,
const unsigned long end)
{
struct acpi_madt_local_apic_override *lapic_addr_ovr = NULL;
lapic_addr_ovr = (struct acpi_madt_local_apic_override *)header;
if (BAD_MADT_ENTRY(lapic_addr_ovr, end))
return -EINVAL;
acpi_lapic_addr = lapic_addr_ovr->address;
return 0;
}
static int __init
acpi_parse_x2apic_nmi(struct acpi_subtable_header *header,
const unsigned long end)
{
struct acpi_madt_local_x2apic_nmi *x2apic_nmi = NULL;
x2apic_nmi = (struct acpi_madt_local_x2apic_nmi *)header;
if (BAD_MADT_ENTRY(x2apic_nmi, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
if (x2apic_nmi->lint != 1)
printk(KERN_WARNING PREFIX "NMI not connected to LINT 1!\n");
return 0;
}
static int __init
acpi_parse_lapic_nmi(struct acpi_subtable_header * header, const unsigned long end)
{
struct acpi_madt_local_apic_nmi *lapic_nmi = NULL;
lapic_nmi = (struct acpi_madt_local_apic_nmi *)header;
if (BAD_MADT_ENTRY(lapic_nmi, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
if (lapic_nmi->lint != 1)
printk(KERN_WARNING PREFIX "NMI not connected to LINT 1!\n");
return 0;
}
#endif /*CONFIG_X86_LOCAL_APIC */
#ifdef CONFIG_X86_IO_APIC
static int __init
acpi_parse_ioapic(struct acpi_subtable_header * header, const unsigned long end)
{
struct acpi_madt_io_apic *ioapic = NULL;
ioapic = (struct acpi_madt_io_apic *)header;
if (BAD_MADT_ENTRY(ioapic, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
mp_register_ioapic(ioapic->id,
ioapic->address, ioapic->global_irq_base);
return 0;
}
/*
* Parse Interrupt Source Override for the ACPI SCI
*/
static void __init acpi_sci_ioapic_setup(u8 bus_irq, u16 polarity, u16 trigger, u32 gsi)
{
if (trigger == 0) /* compatible SCI trigger is level */
trigger = 3;
if (polarity == 0) /* compatible SCI polarity is low */
polarity = 3;
/* Command-line over-ride via acpi_sci= */
if (acpi_sci_flags & ACPI_MADT_TRIGGER_MASK)
trigger = (acpi_sci_flags & ACPI_MADT_TRIGGER_MASK) >> 2;
if (acpi_sci_flags & ACPI_MADT_POLARITY_MASK)
polarity = acpi_sci_flags & ACPI_MADT_POLARITY_MASK;
/*
* mp_config_acpi_legacy_irqs() already setup IRQs < 16
* If GSI is < 16, this will update its flags,
* else it will create a new mp_irqs[] entry.
*/
mp_override_legacy_irq(bus_irq, polarity, trigger, gsi);
/*
* stash over-ride to indicate we've been here
* and for later update of acpi_gbl_FADT
*/
acpi_sci_override_gsi = gsi;
return;
}
static int __init
acpi_parse_int_src_ovr(struct acpi_subtable_header * header,
const unsigned long end)
{
struct acpi_madt_interrupt_override *intsrc = NULL;
intsrc = (struct acpi_madt_interrupt_override *)header;
if (BAD_MADT_ENTRY(intsrc, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
if (intsrc->source_irq == acpi_gbl_FADT.sci_interrupt) {
acpi_sci_ioapic_setup(intsrc->source_irq,
intsrc->inti_flags & ACPI_MADT_POLARITY_MASK,
(intsrc->inti_flags & ACPI_MADT_TRIGGER_MASK) >> 2,
intsrc->global_irq);
return 0;
}
if (intsrc->source_irq == 0) {
if (acpi_skip_timer_override) {
printk(PREFIX "BIOS IRQ0 override ignored.\n");
return 0;
}
if ((intsrc->global_irq == 2) && acpi_fix_pin2_polarity
&& (intsrc->inti_flags & ACPI_MADT_POLARITY_MASK)) {
intsrc->inti_flags &= ~ACPI_MADT_POLARITY_MASK;
printk(PREFIX "BIOS IRQ0 pin2 override: forcing polarity to high active.\n");
}
}
mp_override_legacy_irq(intsrc->source_irq,
intsrc->inti_flags & ACPI_MADT_POLARITY_MASK,
(intsrc->inti_flags & ACPI_MADT_TRIGGER_MASK) >> 2,
intsrc->global_irq);
return 0;
}
static int __init
acpi_parse_nmi_src(struct acpi_subtable_header * header, const unsigned long end)
{
struct acpi_madt_nmi_source *nmi_src = NULL;
nmi_src = (struct acpi_madt_nmi_source *)header;
if (BAD_MADT_ENTRY(nmi_src, end))
return -EINVAL;
acpi_table_print_madt_entry(header);
/* TBD: Support nimsrc entries? */
return 0;
}
#endif /* CONFIG_X86_IO_APIC */
/*
* acpi_pic_sci_set_trigger()
*
* use ELCR to set PIC-mode trigger type for SCI
*
* If a PIC-mode SCI is not recognized or gives spurious IRQ7's
* it may require Edge Trigger -- use "acpi_sci=edge"
*
* Port 0x4d0-4d1 are ECLR1 and ECLR2, the Edge/Level Control Registers
* for the 8259 PIC. bit[n] = 1 means irq[n] is Level, otherwise Edge.
* ECLR1 is IRQs 0-7 (IRQ 0, 1, 2 must be 0)
* ECLR2 is IRQs 8-15 (IRQ 8, 13 must be 0)
*/
void __init acpi_pic_sci_set_trigger(unsigned int irq, u16 trigger)
{
unsigned int mask = 1 << irq;
unsigned int old, new;
/* Real old ELCR mask */
old = inb(0x4d0) | (inb(0x4d1) << 8);
/*
* If we use ACPI to set PCI IRQs, then we should clear ELCR
* since we will set it correctly as we enable the PCI irq
* routing.
*/
new = acpi_noirq ? old : 0;
/*
* Update SCI information in the ELCR, it isn't in the PCI
* routing tables..
*/
switch (trigger) {
case 1: /* Edge - clear */
new &= ~mask;
break;
case 3: /* Level - set */
new |= mask;
break;
}
if (old == new)
return;
printk(PREFIX "setting ELCR to %04x (from %04x)\n", new, old);
outb(new, 0x4d0);
outb(new >> 8, 0x4d1);
}
int acpi_gsi_to_irq(u32 gsi, unsigned int *irq)
{
*irq = gsi_to_irq(gsi);
#ifdef CONFIG_X86_IO_APIC
if (acpi_irq_model == ACPI_IRQ_MODEL_IOAPIC)
setup_IO_APIC_irq_extra(gsi);
#endif
return 0;
}
EXPORT_SYMBOL_GPL(acpi_gsi_to_irq);
int acpi_isa_irq_to_gsi(unsigned isa_irq, u32 *gsi)
{
if (isa_irq >= 16)
return -1;
*gsi = irq_to_gsi(isa_irq);
return 0;
}
static int acpi_register_gsi_pic(struct device *dev, u32 gsi,
int trigger, int polarity)
{
#ifdef CONFIG_PCI
/*
* Make sure all (legacy) PCI IRQs are set as level-triggered.
*/
if (trigger == ACPI_LEVEL_SENSITIVE)
eisa_set_level_irq(gsi);
#endif
return gsi;
}
static int acpi_register_gsi_ioapic(struct device *dev, u32 gsi,
int trigger, int polarity)
{
#ifdef CONFIG_X86_IO_APIC
gsi = mp_register_gsi(dev, gsi, trigger, polarity);
#endif
return gsi;
}
int (*__acpi_register_gsi)(struct device *dev, u32 gsi,
int trigger, int polarity) = acpi_register_gsi_pic;
/*
* success: return IRQ number (>=0)
* failure: return < 0
*/
int acpi_register_gsi(struct device *dev, u32 gsi, int trigger, int polarity)
{
unsigned int irq;
unsigned int plat_gsi = gsi;
plat_gsi = (*__acpi_register_gsi)(dev, gsi, trigger, polarity);
irq = gsi_to_irq(plat_gsi);
return irq;
}
void __init acpi_set_irq_model_pic(void)
{
acpi_irq_model = ACPI_IRQ_MODEL_PIC;
__acpi_register_gsi = acpi_register_gsi_pic;
acpi_ioapic = 0;
}
void __init acpi_set_irq_model_ioapic(void)
{
acpi_irq_model = ACPI_IRQ_MODEL_IOAPIC;
__acpi_register_gsi = acpi_register_gsi_ioapic;
acpi_ioapic = 1;
}
/*
* ACPI based hotplug support for CPU
*/
#ifdef CONFIG_ACPI_HOTPLUG_CPU
#include <acpi/processor.h>
static void acpi_map_cpu2node(acpi_handle handle, int cpu, int physid)
{
#ifdef CONFIG_ACPI_NUMA
int nid;
nid = acpi_get_node(handle);
if (nid == -1 || !node_online(nid))
return;
set_apicid_to_node(physid, nid);
numa_set_node(cpu, nid);
#endif
}
static int __cpuinit _acpi_map_lsapic(acpi_handle handle, int *pcpu)
{
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *obj;
struct acpi_madt_local_apic *lapic;
cpumask_var_t tmp_map, new_map;
u8 physid;
int cpu;
int retval = -ENOMEM;
if (ACPI_FAILURE(acpi_evaluate_object(handle, "_MAT", NULL, &buffer)))
return -EINVAL;
if (!buffer.length || !buffer.pointer)
return -EINVAL;
obj = buffer.pointer;
if (obj->type != ACPI_TYPE_BUFFER ||
obj->buffer.length < sizeof(*lapic)) {
kfree(buffer.pointer);
return -EINVAL;
}
lapic = (struct acpi_madt_local_apic *)obj->buffer.pointer;
if (lapic->header.type != ACPI_MADT_TYPE_LOCAL_APIC ||
!(lapic->lapic_flags & ACPI_MADT_ENABLED)) {
kfree(buffer.pointer);
return -EINVAL;
}
physid = lapic->id;
kfree(buffer.pointer);
buffer.length = ACPI_ALLOCATE_BUFFER;
buffer.pointer = NULL;
if (!alloc_cpumask_var(&tmp_map, GFP_KERNEL))
goto out;
if (!alloc_cpumask_var(&new_map, GFP_KERNEL))
goto free_tmp_map;
cpumask_copy(tmp_map, cpu_present_mask);
acpi_register_lapic(physid, lapic->lapic_flags & ACPI_MADT_ENABLED);
/*
* If mp_register_lapic successfully generates a new logical cpu
* number, then the following will get us exactly what was mapped
*/
cpumask_andnot(new_map, cpu_present_mask, tmp_map);
if (cpumask_empty(new_map)) {
printk ("Unable to map lapic to logical cpu number\n");
retval = -EINVAL;
goto free_new_map;
}
acpi_processor_set_pdc(handle);
cpu = cpumask_first(new_map);
acpi_map_cpu2node(handle, cpu, physid);
*pcpu = cpu;
retval = 0;
free_new_map:
free_cpumask_var(new_map);
free_tmp_map:
free_cpumask_var(tmp_map);
out:
return retval;
}
/* wrapper to silence section mismatch warning */
int __ref acpi_map_lsapic(acpi_handle handle, int *pcpu)
{
return _acpi_map_lsapic(handle, pcpu);
}
EXPORT_SYMBOL(acpi_map_lsapic);
int acpi_unmap_lsapic(int cpu)
{
per_cpu(x86_cpu_to_apicid, cpu) = -1;
set_cpu_present(cpu, false);
num_processors--;
return (0);
}
EXPORT_SYMBOL(acpi_unmap_lsapic);
#endif /* CONFIG_ACPI_HOTPLUG_CPU */
int acpi_register_ioapic(acpi_handle handle, u64 phys_addr, u32 gsi_base)
{
/* TBD */
return -EINVAL;
}
EXPORT_SYMBOL(acpi_register_ioapic);
int acpi_unregister_ioapic(acpi_handle handle, u32 gsi_base)
{
/* TBD */
return -EINVAL;
}
EXPORT_SYMBOL(acpi_unregister_ioapic);
static int __init acpi_parse_sbf(struct acpi_table_header *table)
{
struct acpi_table_boot *sb;
sb = (struct acpi_table_boot *)table;
if (!sb) {
printk(KERN_WARNING PREFIX "Unable to map SBF\n");
return -ENODEV;
}
sbf_port = sb->cmos_index; /* Save CMOS port */
return 0;
}
#ifdef CONFIG_HPET_TIMER
#include <asm/hpet.h>
static struct __initdata resource *hpet_res;
static int __init acpi_parse_hpet(struct acpi_table_header *table)
{
struct acpi_table_hpet *hpet_tbl;
hpet_tbl = (struct acpi_table_hpet *)table;
if (!hpet_tbl) {
printk(KERN_WARNING PREFIX "Unable to map HPET\n");
return -ENODEV;
}
if (hpet_tbl->address.space_id != ACPI_SPACE_MEM) {
printk(KERN_WARNING PREFIX "HPET timers must be located in "
"memory.\n");
return -1;
}
hpet_address = hpet_tbl->address.address;
hpet_blockid = hpet_tbl->sequence;
/*
* Some broken BIOSes advertise HPET at 0x0. We really do not
* want to allocate a resource there.
*/
if (!hpet_address) {
printk(KERN_WARNING PREFIX
"HPET id: %#x base: %#lx is invalid\n",
hpet_tbl->id, hpet_address);
return 0;
}
#ifdef CONFIG_X86_64
/*
* Some even more broken BIOSes advertise HPET at
* 0xfed0000000000000 instead of 0xfed00000. Fix it up and add
* some noise:
*/
if (hpet_address == 0xfed0000000000000UL) {
if (!hpet_force_user) {
printk(KERN_WARNING PREFIX "HPET id: %#x "
"base: 0xfed0000000000000 is bogus\n "
"try hpet=force on the kernel command line to "
"fix it up to 0xfed00000.\n", hpet_tbl->id);
hpet_address = 0;
return 0;
}
printk(KERN_WARNING PREFIX
"HPET id: %#x base: 0xfed0000000000000 fixed up "
"to 0xfed00000.\n", hpet_tbl->id);
hpet_address >>= 32;
}
#endif
printk(KERN_INFO PREFIX "HPET id: %#x base: %#lx\n",
hpet_tbl->id, hpet_address);
/*
* Allocate and initialize the HPET firmware resource for adding into
* the resource tree during the lateinit timeframe.
*/
#define HPET_RESOURCE_NAME_SIZE 9
hpet_res = alloc_bootmem(sizeof(*hpet_res) + HPET_RESOURCE_NAME_SIZE);
hpet_res->name = (void *)&hpet_res[1];
hpet_res->flags = IORESOURCE_MEM;
snprintf((char *)hpet_res->name, HPET_RESOURCE_NAME_SIZE, "HPET %u",
hpet_tbl->sequence);
hpet_res->start = hpet_address;
hpet_res->end = hpet_address + (1 * 1024) - 1;
return 0;
}
/*
* hpet_insert_resource inserts the HPET resources used into the resource
* tree.
*/
static __init int hpet_insert_resource(void)
{
if (!hpet_res)
return 1;
return insert_resource(&iomem_resource, hpet_res);
}
late_initcall(hpet_insert_resource);
#else
#define acpi_parse_hpet NULL
#endif
static int __init acpi_parse_fadt(struct acpi_table_header *table)
{
#ifdef CONFIG_X86_PM_TIMER
/* detect the location of the ACPI PM Timer */
if (acpi_gbl_FADT.header.revision >= FADT2_REVISION_ID) {
/* FADT rev. 2 */
if (acpi_gbl_FADT.xpm_timer_block.space_id !=
ACPI_ADR_SPACE_SYSTEM_IO)
return 0;
pmtmr_ioport = acpi_gbl_FADT.xpm_timer_block.address;
/*
* "X" fields are optional extensions to the original V1.0
* fields, so we must selectively expand V1.0 fields if the
* corresponding X field is zero.
*/
if (!pmtmr_ioport)
pmtmr_ioport = acpi_gbl_FADT.pm_timer_block;
} else {
/* FADT rev. 1 */
pmtmr_ioport = acpi_gbl_FADT.pm_timer_block;
}
if (pmtmr_ioport)
printk(KERN_INFO PREFIX "PM-Timer IO Port: %#x\n",
pmtmr_ioport);
#endif
return 0;
}
#ifdef CONFIG_X86_LOCAL_APIC
/*
* Parse LAPIC entries in MADT
* returns 0 on success, < 0 on error
*/
static int __init early_acpi_parse_madt_lapic_addr_ovr(void)
{
int count;
if (!cpu_has_apic)
return -ENODEV;
/*
* Note that the LAPIC address is obtained from the MADT (32-bit value)
* and (optionally) overriden by a LAPIC_ADDR_OVR entry (64-bit value).
*/
count =
acpi_table_parse_madt(ACPI_MADT_TYPE_LOCAL_APIC_OVERRIDE,
acpi_parse_lapic_addr_ovr, 0);
if (count < 0) {
printk(KERN_ERR PREFIX
"Error parsing LAPIC address override entry\n");
return count;
}
register_lapic_address(acpi_lapic_addr);
return count;
}
static int __init acpi_parse_madt_lapic_entries(void)
{
int count;
int x2count = 0;
if (!cpu_has_apic)
return -ENODEV;
/*
* Note that the LAPIC address is obtained from the MADT (32-bit value)
* and (optionally) overriden by a LAPIC_ADDR_OVR entry (64-bit value).
*/
count =
acpi_table_parse_madt(ACPI_MADT_TYPE_LOCAL_APIC_OVERRIDE,
acpi_parse_lapic_addr_ovr, 0);
if (count < 0) {
printk(KERN_ERR PREFIX
"Error parsing LAPIC address override entry\n");
return count;
}
register_lapic_address(acpi_lapic_addr);
count = acpi_table_parse_madt(ACPI_MADT_TYPE_LOCAL_SAPIC,
acpi_parse_sapic, MAX_LOCAL_APIC);
if (!count) {
x2count = acpi_table_parse_madt(ACPI_MADT_TYPE_LOCAL_X2APIC,
acpi_parse_x2apic, MAX_LOCAL_APIC);
count = acpi_table_parse_madt(ACPI_MADT_TYPE_LOCAL_APIC,
acpi_parse_lapic, MAX_LOCAL_APIC);
}
if (!count && !x2count) {
printk(KERN_ERR PREFIX "No LAPIC entries present\n");
/* TBD: Cleanup to allow fallback to MPS */
return -ENODEV;
} else if (count < 0 || x2count < 0) {
printk(KERN_ERR PREFIX "Error parsing LAPIC entry\n");
/* TBD: Cleanup to allow fallback to MPS */
return count;
}
x2count =
acpi_table_parse_madt(ACPI_MADT_TYPE_LOCAL_X2APIC_NMI,
acpi_parse_x2apic_nmi, 0);
count =
acpi_table_parse_madt(ACPI_MADT_TYPE_LOCAL_APIC_NMI, acpi_parse_lapic_nmi, 0);
if (count < 0 || x2count < 0) {
printk(KERN_ERR PREFIX "Error parsing LAPIC NMI entry\n");
/* TBD: Cleanup to allow fallback to MPS */
return count;
}
return 0;
}
#endif /* CONFIG_X86_LOCAL_APIC */
#ifdef CONFIG_X86_IO_APIC
#define MP_ISA_BUS 0
#ifdef CONFIG_X86_ES7000
extern int es7000_plat;
#endif
void __init mp_override_legacy_irq(u8 bus_irq, u8 polarity, u8 trigger, u32 gsi)
{
int ioapic;
int pin;
struct mpc_intsrc mp_irq;
/*
* Convert 'gsi' to 'ioapic.pin'.
*/
ioapic = mp_find_ioapic(gsi);
if (ioapic < 0)
return;
pin = mp_find_ioapic_pin(ioapic, gsi);
/*
* TBD: This check is for faulty timer entries, where the override
* erroneously sets the trigger to level, resulting in a HUGE
* increase of timer interrupts!
*/
if ((bus_irq == 0) && (trigger == 3))
trigger = 1;
mp_irq.type = MP_INTSRC;
mp_irq.irqtype = mp_INT;
mp_irq.irqflag = (trigger << 2) | polarity;
mp_irq.srcbus = MP_ISA_BUS;
mp_irq.srcbusirq = bus_irq; /* IRQ */
mp_irq.dstapic = mpc_ioapic_id(ioapic); /* APIC ID */
mp_irq.dstirq = pin; /* INTIN# */
mp_save_irq(&mp_irq);
isa_irq_to_gsi[bus_irq] = gsi;
}
void __init mp_config_acpi_legacy_irqs(void)
{
int i;
struct mpc_intsrc mp_irq;
#if defined (CONFIG_MCA) || defined (CONFIG_EISA)
/*
* Fabricate the legacy ISA bus (bus #31).
*/
mp_bus_id_to_type[MP_ISA_BUS] = MP_BUS_ISA;
#endif
set_bit(MP_ISA_BUS, mp_bus_not_pci);
pr_debug("Bus #%d is ISA\n", MP_ISA_BUS);
#ifdef CONFIG_X86_ES7000
/*
* Older generations of ES7000 have no legacy identity mappings
*/
if (es7000_plat == 1)
return;
#endif
/*
* Use the default configuration for the IRQs 0-15. Unless
* overridden by (MADT) interrupt source override entries.
*/
for (i = 0; i < 16; i++) {
int ioapic, pin;
unsigned int dstapic;
int idx;
u32 gsi;
/* Locate the gsi that irq i maps to. */
if (acpi_isa_irq_to_gsi(i, &gsi))
continue;
/*
* Locate the IOAPIC that manages the ISA IRQ.
*/
ioapic = mp_find_ioapic(gsi);
if (ioapic < 0)
continue;
pin = mp_find_ioapic_pin(ioapic, gsi);
dstapic = mpc_ioapic_id(ioapic);
for (idx = 0; idx < mp_irq_entries; idx++) {
struct mpc_intsrc *irq = mp_irqs + idx;
/* Do we already have a mapping for this ISA IRQ? */
if (irq->srcbus == MP_ISA_BUS && irq->srcbusirq == i)
break;
/* Do we already have a mapping for this IOAPIC pin */
if (irq->dstapic == dstapic && irq->dstirq == pin)
break;
}
if (idx != mp_irq_entries) {
printk(KERN_DEBUG "ACPI: IRQ%d used by override.\n", i);
continue; /* IRQ already used */
}
mp_irq.type = MP_INTSRC;
mp_irq.irqflag = 0; /* Conforming */
mp_irq.srcbus = MP_ISA_BUS;
mp_irq.dstapic = dstapic;
mp_irq.irqtype = mp_INT;
mp_irq.srcbusirq = i; /* Identity mapped */
mp_irq.dstirq = pin;
mp_save_irq(&mp_irq);
}
}
static int mp_config_acpi_gsi(struct device *dev, u32 gsi, int trigger,
int polarity)
{
#ifdef CONFIG_X86_MPPARSE
struct mpc_intsrc mp_irq;
struct pci_dev *pdev;
unsigned char number;
unsigned int devfn;
int ioapic;
u8 pin;
if (!acpi_ioapic)
return 0;
if (!dev)
return 0;
if (dev->bus != &pci_bus_type)
return 0;
pdev = to_pci_dev(dev);
number = pdev->bus->number;
devfn = pdev->devfn;
pin = pdev->pin;
/* print the entry should happen on mptable identically */
mp_irq.type = MP_INTSRC;
mp_irq.irqtype = mp_INT;
mp_irq.irqflag = (trigger == ACPI_EDGE_SENSITIVE ? 4 : 0x0c) |
(polarity == ACPI_ACTIVE_HIGH ? 1 : 3);
mp_irq.srcbus = number;
mp_irq.srcbusirq = (((devfn >> 3) & 0x1f) << 2) | ((pin - 1) & 3);
ioapic = mp_find_ioapic(gsi);
mp_irq.dstapic = mpc_ioapic_id(ioapic);
mp_irq.dstirq = mp_find_ioapic_pin(ioapic, gsi);
mp_save_irq(&mp_irq);
#endif
return 0;
}
int mp_register_gsi(struct device *dev, u32 gsi, int trigger, int polarity)
{
int ioapic;
int ioapic_pin;
struct io_apic_irq_attr irq_attr;
if (acpi_irq_model != ACPI_IRQ_MODEL_IOAPIC)
return gsi;
/* Don't set up the ACPI SCI because it's already set up */
if (acpi_gbl_FADT.sci_interrupt == gsi)
return gsi;
ioapic = mp_find_ioapic(gsi);
if (ioapic < 0) {
printk(KERN_WARNING "No IOAPIC for GSI %u\n", gsi);
return gsi;
}
ioapic_pin = mp_find_ioapic_pin(ioapic, gsi);
if (ioapic_pin > MP_MAX_IOAPIC_PIN) {
printk(KERN_ERR "Invalid reference to IOAPIC pin "
"%d-%d\n", mpc_ioapic_id(ioapic),
ioapic_pin);
return gsi;
}
if (enable_update_mptable)
mp_config_acpi_gsi(dev, gsi, trigger, polarity);
set_io_apic_irq_attr(&irq_attr, ioapic, ioapic_pin,
trigger == ACPI_EDGE_SENSITIVE ? 0 : 1,
polarity == ACPI_ACTIVE_HIGH ? 0 : 1);
io_apic_set_pci_routing(dev, gsi_to_irq(gsi), &irq_attr);
return gsi;
}
/*
* Parse IOAPIC related entries in MADT
* returns 0 on success, < 0 on error
*/
static int __init acpi_parse_madt_ioapic_entries(void)
{
int count;
/*
* ACPI interpreter is required to complete interrupt setup,
* so if it is off, don't enumerate the io-apics with ACPI.
* If MPS is present, it will handle them,
* otherwise the system will stay in PIC mode
*/
if (acpi_disabled || acpi_noirq)
return -ENODEV;
if (!cpu_has_apic)
return -ENODEV;
/*
* if "noapic" boot option, don't look for IO-APICs
*/
if (skip_ioapic_setup) {
printk(KERN_INFO PREFIX "Skipping IOAPIC probe "
"due to 'noapic' option.\n");
return -ENODEV;
}
count =
acpi_table_parse_madt(ACPI_MADT_TYPE_IO_APIC, acpi_parse_ioapic,
MAX_IO_APICS);
if (!count) {
printk(KERN_ERR PREFIX "No IOAPIC entries present\n");
return -ENODEV;
} else if (count < 0) {
printk(KERN_ERR PREFIX "Error parsing IOAPIC entry\n");
return count;
}
count =
acpi_table_parse_madt(ACPI_MADT_TYPE_INTERRUPT_OVERRIDE, acpi_parse_int_src_ovr,
nr_irqs);
if (count < 0) {
printk(KERN_ERR PREFIX
"Error parsing interrupt source overrides entry\n");
/* TBD: Cleanup to allow fallback to MPS */
return count;
}
/*
* If BIOS did not supply an INT_SRC_OVR for the SCI
* pretend we got one so we can set the SCI flags.
*/
if (!acpi_sci_override_gsi)
acpi_sci_ioapic_setup(acpi_gbl_FADT.sci_interrupt, 0, 0,
acpi_gbl_FADT.sci_interrupt);
/* Fill in identity legacy mappings where no override */
mp_config_acpi_legacy_irqs();
count =
acpi_table_parse_madt(ACPI_MADT_TYPE_NMI_SOURCE, acpi_parse_nmi_src,
nr_irqs);
if (count < 0) {
printk(KERN_ERR PREFIX "Error parsing NMI SRC entry\n");
/* TBD: Cleanup to allow fallback to MPS */
return count;
}
return 0;
}
#else
static inline int acpi_parse_madt_ioapic_entries(void)
{
return -1;
}
#endif /* !CONFIG_X86_IO_APIC */
static void __init early_acpi_process_madt(void)
{
#ifdef CONFIG_X86_LOCAL_APIC
int error;
if (!acpi_table_parse(ACPI_SIG_MADT, acpi_parse_madt)) {
/*
* Parse MADT LAPIC entries
*/
error = early_acpi_parse_madt_lapic_addr_ovr();
if (!error) {
acpi_lapic = 1;
smp_found_config = 1;
}
if (error == -EINVAL) {
/*
* Dell Precision Workstation 410, 610 come here.
*/
printk(KERN_ERR PREFIX
"Invalid BIOS MADT, disabling ACPI\n");
disable_acpi();
}
}
#endif
}
static void __init acpi_process_madt(void)
{
#ifdef CONFIG_X86_LOCAL_APIC
int error;
if (!acpi_table_parse(ACPI_SIG_MADT, acpi_parse_madt)) {
/*
* Parse MADT LAPIC entries
*/
error = acpi_parse_madt_lapic_entries();
if (!error) {
acpi_lapic = 1;
/*
* Parse MADT IO-APIC entries
*/
error = acpi_parse_madt_ioapic_entries();
if (!error) {
acpi_set_irq_model_ioapic();
smp_found_config = 1;
}
}
if (error == -EINVAL) {
/*
* Dell Precision Workstation 410, 610 come here.
*/
printk(KERN_ERR PREFIX
"Invalid BIOS MADT, disabling ACPI\n");
disable_acpi();
}
} else {
/*
* ACPI found no MADT, and so ACPI wants UP PIC mode.
* In the event an MPS table was found, forget it.
* Boot with "acpi=off" to use MPS on such a system.
*/
if (smp_found_config) {
printk(KERN_WARNING PREFIX
"No APIC-table, disabling MPS\n");
smp_found_config = 0;
}
}
/*
* ACPI supports both logical (e.g. Hyper-Threading) and physical
* processors, where MPS only supports physical.
*/
if (acpi_lapic && acpi_ioapic)
printk(KERN_INFO "Using ACPI (MADT) for SMP configuration "
"information\n");
else if (acpi_lapic)
printk(KERN_INFO "Using ACPI for processor (LAPIC) "
"configuration information\n");
#endif
return;
}
static int __init disable_acpi_irq(const struct dmi_system_id *d)
{
if (!acpi_force) {
printk(KERN_NOTICE "%s detected: force use of acpi=noirq\n",
d->ident);
acpi_noirq_set();
}
return 0;
}
static int __init disable_acpi_pci(const struct dmi_system_id *d)
{
if (!acpi_force) {
printk(KERN_NOTICE "%s detected: force use of pci=noacpi\n",
d->ident);
acpi_disable_pci();
}
return 0;
}
static int __init dmi_disable_acpi(const struct dmi_system_id *d)
{
if (!acpi_force) {
printk(KERN_NOTICE "%s detected: acpi off\n", d->ident);
disable_acpi();
} else {
printk(KERN_NOTICE
"Warning: DMI blacklist says broken, but acpi forced\n");
}
return 0;
}
/*
* Force ignoring BIOS IRQ0 override
*/
static int __init dmi_ignore_irq0_timer_override(const struct dmi_system_id *d)
{
if (!acpi_skip_timer_override) {
pr_notice("%s detected: Ignoring BIOS IRQ0 override\n",
d->ident);
acpi_skip_timer_override = 1;
}
return 0;
}
/*
* If your system is blacklisted here, but you find that acpi=force
* works for you, please contact linux-acpi@vger.kernel.org
*/
static struct dmi_system_id __initdata acpi_dmi_table[] = {
/*
* Boxes that need ACPI disabled
*/
{
.callback = dmi_disable_acpi,
.ident = "IBM Thinkpad",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "IBM"),
DMI_MATCH(DMI_BOARD_NAME, "2629H1G"),
},
},
/*
* Boxes that need ACPI PCI IRQ routing disabled
*/
{
.callback = disable_acpi_irq,
.ident = "ASUS A7V",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC"),
DMI_MATCH(DMI_BOARD_NAME, "<A7V>"),
/* newer BIOS, Revision 1011, does work */
DMI_MATCH(DMI_BIOS_VERSION,
"ASUS A7V ACPI BIOS Revision 1007"),
},
},
{
/*
* Latest BIOS for IBM 600E (1.16) has bad pcinum
* for LPC bridge, which is needed for the PCI
* interrupt links to work. DSDT fix is in bug 5966.
* 2645, 2646 model numbers are shared with 600/600E/600X
*/
.callback = disable_acpi_irq,
.ident = "IBM Thinkpad 600 Series 2645",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "IBM"),
DMI_MATCH(DMI_BOARD_NAME, "2645"),
},
},
{
.callback = disable_acpi_irq,
.ident = "IBM Thinkpad 600 Series 2646",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "IBM"),
DMI_MATCH(DMI_BOARD_NAME, "2646"),
},
},
/*
* Boxes that need ACPI PCI IRQ routing and PCI scan disabled
*/
{ /* _BBN 0 bug */
.callback = disable_acpi_pci,
.ident = "ASUS PR-DLS",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "PR-DLS"),
DMI_MATCH(DMI_BIOS_VERSION,
"ASUS PR-DLS ACPI BIOS Revision 1010"),
DMI_MATCH(DMI_BIOS_DATE, "03/21/2003")
},
},
{
.callback = disable_acpi_pci,
.ident = "Acer TravelMate 36x Laptop",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Acer"),
DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 360"),
},
},
{}
};
/* second table for DMI checks that should run after early-quirks */
static struct dmi_system_id __initdata acpi_dmi_table_late[] = {
/*
* HP laptops which use a DSDT reporting as HP/SB400/10000,
* which includes some code which overrides all temperature
* trip points to 16C if the INTIN2 input of the I/O APIC
* is enabled. This input is incorrectly designated the
* ISA IRQ 0 via an interrupt source override even though
* it is wired to the output of the master 8259A and INTIN0
* is not connected at all. Force ignoring BIOS IRQ0
* override in that cases.
*/
{
.callback = dmi_ignore_irq0_timer_override,
.ident = "HP nx6115 laptop",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq nx6115"),
},
},
{
.callback = dmi_ignore_irq0_timer_override,
.ident = "HP NX6125 laptop",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq nx6125"),
},
},
{
.callback = dmi_ignore_irq0_timer_override,
.ident = "HP NX6325 laptop",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq nx6325"),
},
},
{
.callback = dmi_ignore_irq0_timer_override,
.ident = "HP 6715b laptop",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq 6715b"),
},
},
{
.callback = dmi_ignore_irq0_timer_override,
.ident = "FUJITSU SIEMENS",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO PRO V2030"),
},
},
{}
};
/*
* acpi_boot_table_init() and acpi_boot_init()
* called from setup_arch(), always.
* 1. checksums all tables
* 2. enumerates lapics
* 3. enumerates io-apics
*
* acpi_table_init() is separate to allow reading SRAT without
* other side effects.
*
* side effects of acpi_boot_init:
* acpi_lapic = 1 if LAPIC found
* acpi_ioapic = 1 if IOAPIC found
* if (acpi_lapic && acpi_ioapic) smp_found_config = 1;
* if acpi_blacklisted() acpi_disabled = 1;
* acpi_irq_model=...
* ...
*/
void __init acpi_boot_table_init(void)
{
dmi_check_system(acpi_dmi_table);
/*
* If acpi_disabled, bail out
*/
if (acpi_disabled)
return;
/*
* Initialize the ACPI boot-time table parser.
*/
if (acpi_table_init()) {
disable_acpi();
return;
}
acpi_table_parse(ACPI_SIG_BOOT, acpi_parse_sbf);
/*
* blacklist may disable ACPI entirely
*/
if (acpi_blacklisted()) {
if (acpi_force) {
printk(KERN_WARNING PREFIX "acpi=force override\n");
} else {
printk(KERN_WARNING PREFIX "Disabling ACPI support\n");
disable_acpi();
return;
}
}
}
int __init early_acpi_boot_init(void)
{
/*
* If acpi_disabled, bail out
*/
if (acpi_disabled)
return 1;
/*
* Process the Multiple APIC Description Table (MADT), if present
*/
early_acpi_process_madt();
return 0;
}
int __init acpi_boot_init(void)
{
/* those are executed after early-quirks are executed */
dmi_check_system(acpi_dmi_table_late);
/*
* If acpi_disabled, bail out
*/
if (acpi_disabled)
return 1;
acpi_table_parse(ACPI_SIG_BOOT, acpi_parse_sbf);
/*
* set sci_int and PM timer address
*/
acpi_table_parse(ACPI_SIG_FADT, acpi_parse_fadt);
/*
* Process the Multiple APIC Description Table (MADT), if present
*/
acpi_process_madt();
acpi_table_parse(ACPI_SIG_HPET, acpi_parse_hpet);
if (!acpi_noirq)
x86_init.pci.init = pci_acpi_init;
return 0;
}
static int __init parse_acpi(char *arg)
{
if (!arg)
return -EINVAL;
/* "acpi=off" disables both ACPI table parsing and interpreter */
if (strcmp(arg, "off") == 0) {
disable_acpi();
}
/* acpi=force to over-ride black-list */
else if (strcmp(arg, "force") == 0) {
acpi_force = 1;
acpi_disabled = 0;
}
/* acpi=strict disables out-of-spec workarounds */
else if (strcmp(arg, "strict") == 0) {
acpi_strict = 1;
}
/* acpi=rsdt use RSDT instead of XSDT */
else if (strcmp(arg, "rsdt") == 0) {
acpi_rsdt_forced = 1;
}
/* "acpi=noirq" disables ACPI interrupt routing */
else if (strcmp(arg, "noirq") == 0) {
acpi_noirq_set();
}
/* "acpi=copy_dsdt" copys DSDT */
else if (strcmp(arg, "copy_dsdt") == 0) {
acpi_gbl_copy_dsdt_locally = 1;
} else {
/* Core will printk when we return error. */
return -EINVAL;
}
return 0;
}
early_param("acpi", parse_acpi);
/* FIXME: Using pci= for an ACPI parameter is a travesty. */
static int __init parse_pci(char *arg)
{
if (arg && strcmp(arg, "noacpi") == 0)
acpi_disable_pci();
return 0;
}
early_param("pci", parse_pci);
int __init acpi_mps_check(void)
{
#if defined(CONFIG_X86_LOCAL_APIC) && !defined(CONFIG_X86_MPPARSE)
/* mptable code is not built-in*/
if (acpi_disabled || acpi_noirq) {
printk(KERN_WARNING "MPS support code is not built-in.\n"
"Using acpi=off or acpi=noirq or pci=noacpi "
"may have problem\n");
return 1;
}
#endif
return 0;
}
#ifdef CONFIG_X86_IO_APIC
static int __init parse_acpi_skip_timer_override(char *arg)
{
acpi_skip_timer_override = 1;
return 0;
}
early_param("acpi_skip_timer_override", parse_acpi_skip_timer_override);
static int __init parse_acpi_use_timer_override(char *arg)
{
acpi_use_timer_override = 1;
return 0;
}
early_param("acpi_use_timer_override", parse_acpi_use_timer_override);
#endif /* CONFIG_X86_IO_APIC */
static int __init setup_acpi_sci(char *s)
{
if (!s)
return -EINVAL;
if (!strcmp(s, "edge"))
acpi_sci_flags = ACPI_MADT_TRIGGER_EDGE |
(acpi_sci_flags & ~ACPI_MADT_TRIGGER_MASK);
else if (!strcmp(s, "level"))
acpi_sci_flags = ACPI_MADT_TRIGGER_LEVEL |
(acpi_sci_flags & ~ACPI_MADT_TRIGGER_MASK);
else if (!strcmp(s, "high"))
acpi_sci_flags = ACPI_MADT_POLARITY_ACTIVE_HIGH |
(acpi_sci_flags & ~ACPI_MADT_POLARITY_MASK);
else if (!strcmp(s, "low"))
acpi_sci_flags = ACPI_MADT_POLARITY_ACTIVE_LOW |
(acpi_sci_flags & ~ACPI_MADT_POLARITY_MASK);
else
return -EINVAL;
return 0;
}
early_param("acpi_sci", setup_acpi_sci);
int __acpi_acquire_global_lock(unsigned int *lock)
{
unsigned int old, new, val;
do {
old = *lock;
new = (((old & ~0x3) + 2) + ((old >> 1) & 0x1));
val = cmpxchg(lock, old, new);
} while (unlikely (val != old));
return (new < 3) ? -1 : 0;
}
int __acpi_release_global_lock(unsigned int *lock)
{
unsigned int old, new, val;
do {
old = *lock;
new = old & ~0x3;
val = cmpxchg(lock, old, new);
} while (unlikely (val != old));
return old & 0x1;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.