repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
showp1984/bricked-hammerhead | drivers/media/dvb/frontends/cx24113.c | 9603 | 14761 | /*
* Driver for Conexant CX24113/CX24128 Tuner (Satellite)
*
* Copyright (C) 2007-8 Patrick Boettcher <pb@linuxtv.org>
*
* Developed for BBTI / Technisat
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include "dvb_frontend.h"
#include "cx24113.h"
static int debug;
#define cx_info(args...) do { printk(KERN_INFO "CX24113: " args); } while (0)
#define cx_err(args...) do { printk(KERN_ERR "CX24113: " args); } while (0)
#define dprintk(args...) \
do { \
if (debug) { \
printk(KERN_DEBUG "CX24113: %s: ", __func__); \
printk(args); \
} \
} while (0)
struct cx24113_state {
struct i2c_adapter *i2c;
const struct cx24113_config *config;
#define REV_CX24113 0x23
u8 rev;
u8 ver;
u8 icp_mode:1;
#define ICP_LEVEL1 0
#define ICP_LEVEL2 1
#define ICP_LEVEL3 2
#define ICP_LEVEL4 3
u8 icp_man:2;
u8 icp_auto_low:2;
u8 icp_auto_mlow:2;
u8 icp_auto_mhi:2;
u8 icp_auto_hi:2;
u8 icp_dig;
#define LNA_MIN_GAIN 0
#define LNA_MID_GAIN 1
#define LNA_MAX_GAIN 2
u8 lna_gain:2;
u8 acp_on:1;
u8 vco_mode:2;
u8 vco_shift:1;
#define VCOBANDSEL_6 0x80
#define VCOBANDSEL_5 0x01
#define VCOBANDSEL_4 0x02
#define VCOBANDSEL_3 0x04
#define VCOBANDSEL_2 0x08
#define VCOBANDSEL_1 0x10
u8 vco_band;
#define VCODIV4 4
#define VCODIV2 2
u8 vcodiv;
u8 bs_delay:4;
u16 bs_freqcnt:13;
u16 bs_rdiv;
u8 prescaler_mode:1;
u8 rfvga_bias_ctrl;
s16 tuner_gain_thres;
u8 gain_level;
u32 frequency;
u8 refdiv;
u8 Fwindow_enabled;
};
static int cx24113_writereg(struct cx24113_state *state, int reg, int data)
{
u8 buf[] = { reg, data };
struct i2c_msg msg = { .addr = state->config->i2c_addr,
.flags = 0, .buf = buf, .len = 2 };
int err = i2c_transfer(state->i2c, &msg, 1);
if (err != 1) {
printk(KERN_DEBUG "%s: writereg error(err == %i, reg == 0x%02x,"
" data == 0x%02x)\n", __func__, err, reg, data);
return err;
}
return 0;
}
static int cx24113_readreg(struct cx24113_state *state, u8 reg)
{
int ret;
u8 b;
struct i2c_msg msg[] = {
{ .addr = state->config->i2c_addr,
.flags = 0, .buf = ®, .len = 1 },
{ .addr = state->config->i2c_addr,
.flags = I2C_M_RD, .buf = &b, .len = 1 }
};
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
printk(KERN_DEBUG "%s: reg=0x%x (error=%d)\n",
__func__, reg, ret);
return ret;
}
return b;
}
static void cx24113_set_parameters(struct cx24113_state *state)
{
u8 r;
r = cx24113_readreg(state, 0x10) & 0x82;
r |= state->icp_mode;
r |= state->icp_man << 4;
r |= state->icp_dig << 2;
r |= state->prescaler_mode << 5;
cx24113_writereg(state, 0x10, r);
r = (state->icp_auto_low << 0) | (state->icp_auto_mlow << 2)
| (state->icp_auto_mhi << 4) | (state->icp_auto_hi << 6);
cx24113_writereg(state, 0x11, r);
if (state->rev == REV_CX24113) {
r = cx24113_readreg(state, 0x20) & 0xec;
r |= state->lna_gain;
r |= state->rfvga_bias_ctrl << 4;
cx24113_writereg(state, 0x20, r);
}
r = cx24113_readreg(state, 0x12) & 0x03;
r |= state->acp_on << 2;
r |= state->bs_delay << 4;
cx24113_writereg(state, 0x12, r);
r = cx24113_readreg(state, 0x18) & 0x40;
r |= state->vco_shift;
if (state->vco_band == VCOBANDSEL_6)
r |= (1 << 7);
else
r |= (state->vco_band << 1);
cx24113_writereg(state, 0x18, r);
r = cx24113_readreg(state, 0x14) & 0x20;
r |= (state->vco_mode << 6) | ((state->bs_freqcnt >> 8) & 0x1f);
cx24113_writereg(state, 0x14, r);
cx24113_writereg(state, 0x15, (state->bs_freqcnt & 0xff));
cx24113_writereg(state, 0x16, (state->bs_rdiv >> 4) & 0xff);
r = (cx24113_readreg(state, 0x17) & 0x0f) |
((state->bs_rdiv & 0x0f) << 4);
cx24113_writereg(state, 0x17, r);
}
#define VGA_0 0x00
#define VGA_1 0x04
#define VGA_2 0x02
#define VGA_3 0x06
#define VGA_4 0x01
#define VGA_5 0x05
#define VGA_6 0x03
#define VGA_7 0x07
#define RFVGA_0 0x00
#define RFVGA_1 0x01
#define RFVGA_2 0x02
#define RFVGA_3 0x03
static int cx24113_set_gain_settings(struct cx24113_state *state,
s16 power_estimation)
{
u8 ampout = cx24113_readreg(state, 0x1d) & 0xf0,
vga = cx24113_readreg(state, 0x1f) & 0x3f,
rfvga = cx24113_readreg(state, 0x20) & 0xf3;
u8 gain_level = power_estimation >= state->tuner_gain_thres;
dprintk("power estimation: %d, thres: %d, gain_level: %d/%d\n",
power_estimation, state->tuner_gain_thres,
state->gain_level, gain_level);
if (gain_level == state->gain_level)
return 0; /* nothing to be done */
ampout |= 0xf;
if (gain_level) {
rfvga |= RFVGA_0 << 2;
vga |= (VGA_7 << 3) | VGA_7;
} else {
rfvga |= RFVGA_2 << 2;
vga |= (VGA_6 << 3) | VGA_2;
}
state->gain_level = gain_level;
cx24113_writereg(state, 0x1d, ampout);
cx24113_writereg(state, 0x1f, vga);
cx24113_writereg(state, 0x20, rfvga);
return 1; /* did something */
}
static int cx24113_set_Fref(struct cx24113_state *state, u8 high)
{
u8 xtal = cx24113_readreg(state, 0x02);
if (state->rev == 0x43 && state->vcodiv == VCODIV4)
high = 1;
xtal &= ~0x2;
if (high)
xtal |= high << 1;
return cx24113_writereg(state, 0x02, xtal);
}
static int cx24113_enable(struct cx24113_state *state, u8 enable)
{
u8 r21 = (cx24113_readreg(state, 0x21) & 0xc0) | enable;
if (state->rev == REV_CX24113)
r21 |= (1 << 1);
return cx24113_writereg(state, 0x21, r21);
}
static int cx24113_set_bandwidth(struct cx24113_state *state, u32 bandwidth_khz)
{
u8 r;
if (bandwidth_khz <= 19000)
r = 0x03 << 6;
else if (bandwidth_khz <= 25000)
r = 0x02 << 6;
else
r = 0x01 << 6;
dprintk("bandwidth to be set: %d\n", bandwidth_khz);
bandwidth_khz *= 10;
bandwidth_khz -= 10000;
bandwidth_khz /= 1000;
bandwidth_khz += 5;
bandwidth_khz /= 10;
dprintk("bandwidth: %d %d\n", r >> 6, bandwidth_khz);
r |= bandwidth_khz & 0x3f;
return cx24113_writereg(state, 0x1e, r);
}
static int cx24113_set_clk_inversion(struct cx24113_state *state, u8 on)
{
u8 r = (cx24113_readreg(state, 0x10) & 0x7f) | ((on & 0x1) << 7);
return cx24113_writereg(state, 0x10, r);
}
static int cx24113_get_status(struct dvb_frontend *fe, u32 *status)
{
struct cx24113_state *state = fe->tuner_priv;
u8 r = (cx24113_readreg(state, 0x10) & 0x02) >> 1;
if (r)
*status |= TUNER_STATUS_LOCKED;
dprintk("PLL locked: %d\n", r);
return 0;
}
static u8 cx24113_set_ref_div(struct cx24113_state *state, u8 refdiv)
{
if (state->rev == 0x43 && state->vcodiv == VCODIV4)
refdiv = 2;
return state->refdiv = refdiv;
}
static void cx24113_calc_pll_nf(struct cx24113_state *state, u16 *n, s32 *f)
{
s32 N;
s64 F;
u64 dividend;
u8 R, r;
u8 vcodiv;
u8 factor;
s32 freq_hz = state->frequency * 1000;
if (state->config->xtal_khz < 20000)
factor = 1;
else
factor = 2;
if (state->rev == REV_CX24113) {
if (state->frequency >= 1100000)
vcodiv = VCODIV2;
else
vcodiv = VCODIV4;
} else {
if (state->frequency >= 1165000)
vcodiv = VCODIV2;
else
vcodiv = VCODIV4;
}
state->vcodiv = vcodiv;
dprintk("calculating N/F for %dHz with vcodiv %d\n", freq_hz, vcodiv);
R = 0;
do {
R = cx24113_set_ref_div(state, R + 1);
/* calculate tuner PLL settings: */
N = (freq_hz / 100 * vcodiv) * R;
N /= (state->config->xtal_khz) * factor * 2;
N += 5; /* For round up. */
N /= 10;
N -= 32;
} while (N < 6 && R < 3);
if (N < 6) {
cx_err("strange frequency: N < 6\n");
return;
}
F = freq_hz;
F *= (u64) (R * vcodiv * 262144);
dprintk("1 N: %d, F: %lld, R: %d\n", N, (long long)F, R);
/* do_div needs an u64 as first argument */
dividend = F;
do_div(dividend, state->config->xtal_khz * 1000 * factor * 2);
F = dividend;
dprintk("2 N: %d, F: %lld, R: %d\n", N, (long long)F, R);
F -= (N + 32) * 262144;
dprintk("3 N: %d, F: %lld, R: %d\n", N, (long long)F, R);
if (state->Fwindow_enabled) {
if (F > (262144 / 2 - 1638))
F = 262144 / 2 - 1638;
if (F < (-262144 / 2 + 1638))
F = -262144 / 2 + 1638;
if ((F < 3277 && F > 0) || (F > -3277 && F < 0)) {
F = 0;
r = cx24113_readreg(state, 0x10);
cx24113_writereg(state, 0x10, r | (1 << 6));
}
}
dprintk("4 N: %d, F: %lld, R: %d\n", N, (long long)F, R);
*n = (u16) N;
*f = (s32) F;
}
static void cx24113_set_nfr(struct cx24113_state *state, u16 n, s32 f, u8 r)
{
u8 reg;
cx24113_writereg(state, 0x19, (n >> 1) & 0xff);
reg = ((n & 0x1) << 7) | ((f >> 11) & 0x7f);
cx24113_writereg(state, 0x1a, reg);
cx24113_writereg(state, 0x1b, (f >> 3) & 0xff);
reg = cx24113_readreg(state, 0x1c) & 0x1f;
cx24113_writereg(state, 0x1c, reg | ((f & 0x7) << 5));
cx24113_set_Fref(state, r - 1);
}
static int cx24113_set_frequency(struct cx24113_state *state, u32 frequency)
{
u8 r = 1; /* or 2 */
u16 n = 6;
s32 f = 0;
r = cx24113_readreg(state, 0x14);
cx24113_writereg(state, 0x14, r & 0x3f);
r = cx24113_readreg(state, 0x10);
cx24113_writereg(state, 0x10, r & 0xbf);
state->frequency = frequency;
dprintk("tuning to frequency: %d\n", frequency);
cx24113_calc_pll_nf(state, &n, &f);
cx24113_set_nfr(state, n, f, state->refdiv);
r = cx24113_readreg(state, 0x18) & 0xbf;
if (state->vcodiv != VCODIV2)
r |= 1 << 6;
cx24113_writereg(state, 0x18, r);
/* The need for this sleep is not clear. But helps in some cases */
msleep(5);
r = cx24113_readreg(state, 0x1c) & 0xef;
cx24113_writereg(state, 0x1c, r | (1 << 4));
return 0;
}
static int cx24113_init(struct dvb_frontend *fe)
{
struct cx24113_state *state = fe->tuner_priv;
int ret;
state->tuner_gain_thres = -50;
state->gain_level = 255; /* to force a gain-setting initialization */
state->icp_mode = 0;
if (state->config->xtal_khz < 11000) {
state->icp_auto_hi = ICP_LEVEL4;
state->icp_auto_mhi = ICP_LEVEL4;
state->icp_auto_mlow = ICP_LEVEL3;
state->icp_auto_low = ICP_LEVEL3;
} else {
state->icp_auto_hi = ICP_LEVEL4;
state->icp_auto_mhi = ICP_LEVEL4;
state->icp_auto_mlow = ICP_LEVEL3;
state->icp_auto_low = ICP_LEVEL2;
}
state->icp_dig = ICP_LEVEL3;
state->icp_man = ICP_LEVEL1;
state->acp_on = 1;
state->vco_mode = 0;
state->vco_shift = 0;
state->vco_band = VCOBANDSEL_1;
state->bs_delay = 8;
state->bs_freqcnt = 0x0fff;
state->bs_rdiv = 0x0fff;
state->prescaler_mode = 0;
state->lna_gain = LNA_MAX_GAIN;
state->rfvga_bias_ctrl = 1;
state->Fwindow_enabled = 1;
cx24113_set_Fref(state, 0);
cx24113_enable(state, 0x3d);
cx24113_set_parameters(state);
cx24113_set_gain_settings(state, -30);
cx24113_set_bandwidth(state, 18025);
cx24113_set_clk_inversion(state, 1);
if (state->config->xtal_khz >= 40000)
ret = cx24113_writereg(state, 0x02,
(cx24113_readreg(state, 0x02) & 0xfb) | (1 << 2));
else
ret = cx24113_writereg(state, 0x02,
(cx24113_readreg(state, 0x02) & 0xfb) | (0 << 2));
return ret;
}
static int cx24113_set_params(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct cx24113_state *state = fe->tuner_priv;
/* for a ROLL-OFF factor of 0.35, 0.2: 600, 0.25: 625 */
u32 roll_off = 675;
u32 bw;
bw = ((c->symbol_rate/100) * roll_off) / 1000;
bw += (10000000/100) + 5;
bw /= 10;
bw += 1000;
cx24113_set_bandwidth(state, bw);
cx24113_set_frequency(state, c->frequency);
msleep(5);
return cx24113_get_status(fe, &bw);
}
static s8 cx24113_agc_table[2][10] = {
{-54, -41, -35, -30, -25, -21, -16, -10, -6, -2},
{-39, -35, -30, -25, -19, -15, -11, -5, 1, 9},
};
void cx24113_agc_callback(struct dvb_frontend *fe)
{
struct cx24113_state *state = fe->tuner_priv;
s16 s, i;
if (!fe->ops.read_signal_strength)
return;
do {
/* this only works with the current CX24123 implementation */
fe->ops.read_signal_strength(fe, (u16 *) &s);
s >>= 8;
dprintk("signal strength: %d\n", s);
for (i = 0; i < sizeof(cx24113_agc_table[0]); i++)
if (cx24113_agc_table[state->gain_level][i] > s)
break;
s = -25 - i*5;
} while (cx24113_set_gain_settings(state, s));
}
EXPORT_SYMBOL(cx24113_agc_callback);
static int cx24113_get_frequency(struct dvb_frontend *fe, u32 *frequency)
{
struct cx24113_state *state = fe->tuner_priv;
*frequency = state->frequency;
return 0;
}
static int cx24113_release(struct dvb_frontend *fe)
{
struct cx24113_state *state = fe->tuner_priv;
dprintk("\n");
fe->tuner_priv = NULL;
kfree(state);
return 0;
}
static const struct dvb_tuner_ops cx24113_tuner_ops = {
.info = {
.name = "Conexant CX24113",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_step = 125,
},
.release = cx24113_release,
.init = cx24113_init,
.set_params = cx24113_set_params,
.get_frequency = cx24113_get_frequency,
.get_status = cx24113_get_status,
};
struct dvb_frontend *cx24113_attach(struct dvb_frontend *fe,
const struct cx24113_config *config, struct i2c_adapter *i2c)
{
/* allocate memory for the internal state */
struct cx24113_state *state =
kzalloc(sizeof(struct cx24113_state), GFP_KERNEL);
int rc;
if (state == NULL) {
cx_err("Unable to kzalloc\n");
goto error;
}
/* setup the state */
state->config = config;
state->i2c = i2c;
cx_info("trying to detect myself\n");
/* making a dummy read, because of some expected troubles
* after power on */
cx24113_readreg(state, 0x00);
rc = cx24113_readreg(state, 0x00);
if (rc < 0) {
cx_info("CX24113 not found.\n");
goto error;
}
state->rev = rc;
switch (rc) {
case 0x43:
cx_info("detected CX24113 variant\n");
break;
case REV_CX24113:
cx_info("successfully detected\n");
break;
default:
cx_err("unsupported device id: %x\n", state->rev);
goto error;
}
state->ver = cx24113_readreg(state, 0x01);
cx_info("version: %x\n", state->ver);
/* create dvb_frontend */
memcpy(&fe->ops.tuner_ops, &cx24113_tuner_ops,
sizeof(struct dvb_tuner_ops));
fe->tuner_priv = state;
return fe;
error:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(cx24113_attach);
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Activates frontend debugging (default:0)");
MODULE_AUTHOR("Patrick Boettcher <pb@linuxtv.org>");
MODULE_DESCRIPTION("DVB Frontend module for Conexant CX24113/CX24128hardware");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jollaman999/jolla-kernel_G_v30a-Stock | arch/mips/netlogic/common/time.c | 132 | 2009 | /*
* Copyright 2003-2011 NetLogic Microsystems, Inc. (NetLogic). 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 NetLogic
* license below:
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY NETLOGIC ``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 NETLOGIC 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/init.h>
#include <asm/time.h>
#include <asm/netlogic/interrupt.h>
#include <asm/netlogic/common.h>
unsigned int get_c0_compare_int(void)
{
return IRQ_TIMER;
}
void __init plat_time_init(void)
{
mips_hpt_frequency = nlm_get_cpu_frequency();
pr_info("MIPS counter frequency [%ld]\n",
(unsigned long)mips_hpt_frequency);
}
| gpl-2.0 |
DutchDanny/kernel_kk443_sense_m8ace | drivers/i2c/chips/akm8963_doe_plus.c | 132 | 39912 | /* drivers/misc/akm8963.c - akm8963 compass driver
*
* Copyright (C) 2007-2008 HTC Corporation.
* Author: Hou-Kun Chen <houkun.chen@gmail.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/akm8963_doe_plus.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/freezer.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/workqueue.h>
#include <linux/export.h>
#include <linux/module.h>
#include <linux/of_gpio.h>
#include <mach/rpm-regulator.h>
#define AKM_DEBUG_IF 0
#define AKM_HAS_RESET 1
#define AKM_INPUT_DEVICE_NAME "compass"
#define AKM_DRDY_TIMEOUT_MS 100
#define AKM_BASE_NUM 10
#define D(x...) printk(KERN_DEBUG "[COMP][AKM8963 DOE Plus] " x)
#define I(x...) printk(KERN_INFO "[COMP][AKM8963 DOE Plus] " x)
#define E(x...) printk(KERN_ERR "[COMP][AKM8963 DOE Plus ERR] " x)
struct akm_compass_data {
struct i2c_client *i2c;
struct input_dev *input;
struct device *class_dev;
struct class *compass;
wait_queue_head_t drdy_wq;
wait_queue_head_t open_wq;
uint8_t sense_info[AKM_SENSOR_INFO_SIZE];
uint8_t sense_conf[AKM_SENSOR_CONF_SIZE];
struct mutex sensor_mutex;
uint8_t sense_data[AKM_SENSOR_DATA_SIZE];
struct mutex accel_mutex;
int16_t accel_data[3];
int8_t is_busy;
struct mutex val_mutex;
uint32_t enable_flag;
int64_t delay[AKM_NUM_SENSORS];
atomic_t active;
atomic_t drdy;
char layout;
int irq;
int gpio_rstn;
int (*power_LPM)(int on);
struct regulator *sr_1v8;
struct regulator *sr_2v85;
};
static struct akm_compass_data *s_akm;
static int akm_i2c_rxdata(
struct i2c_client *i2c,
uint8_t *rxData,
int length)
{
int ret;
struct i2c_msg msgs[] = {
{
.addr = i2c->addr,
.flags = 0,
.len = 1,
.buf = rxData,
},
{
.addr = i2c->addr,
.flags = I2C_M_RD,
.len = length,
.buf = rxData,
},
};
uint8_t addr = rxData[0];
ret = i2c_transfer(i2c->adapter, msgs, ARRAY_SIZE(msgs));
if (ret < 0) {
dev_err(&i2c->dev, "%s: transfer failed.", __func__);
return ret;
} else if (ret != ARRAY_SIZE(msgs)) {
dev_err(&i2c->dev, "%s: transfer failed(size error).\n",
__func__);
return -ENXIO;
}
dev_vdbg(&i2c->dev, "RxData: len=%02x, addr=%02x, data=%02x",
length, addr, rxData[0]);
return 0;
}
static int akm_i2c_txdata(
struct i2c_client *i2c,
uint8_t *txData,
int length)
{
int ret;
struct i2c_msg msg[] = {
{
.addr = i2c->addr,
.flags = 0,
.len = length,
.buf = txData,
},
};
ret = i2c_transfer(i2c->adapter, msg, ARRAY_SIZE(msg));
if (ret < 0) {
dev_err(&i2c->dev, "%s: transfer failed.", __func__);
return ret;
} else if (ret != ARRAY_SIZE(msg)) {
dev_err(&i2c->dev, "%s: transfer failed(size error).",
__func__);
return -ENXIO;
}
dev_vdbg(&i2c->dev, "TxData: len=%02x, addr=%02x data=%02x",
length, txData[0], txData[1]);
return 0;
}
static int AKECS_Set_CNTL(
struct akm_compass_data *akm,
uint8_t mode)
{
uint8_t buffer[2];
int err;
mutex_lock(&akm->sensor_mutex);
if (akm->is_busy > 0) {
dev_err(&akm->i2c->dev,
"%s: device is busy.", __func__);
err = -EBUSY;
} else {
buffer[0] = AKM_REG_MODE;
buffer[1] = mode;
err = akm_i2c_txdata(akm->i2c, buffer, 2);
if (err < 0) {
dev_err(&akm->i2c->dev,
"%s: Can not set CNTL.", __func__);
} else {
dev_vdbg(&akm->i2c->dev,
"Mode is set to (%d).", mode);
akm->is_busy = 1;
atomic_set(&akm->drdy, 0);
udelay(100);
}
}
mutex_unlock(&akm->sensor_mutex);
return err;
}
static int AKECS_Set_PowerDown(
struct akm_compass_data *akm)
{
uint8_t buffer[2];
int err;
mutex_lock(&akm->sensor_mutex);
buffer[0] = AKM_REG_MODE;
buffer[1] = AKM_MODE_POWERDOWN;
err = akm_i2c_txdata(akm->i2c, buffer, 2);
if (err < 0) {
dev_err(&akm->i2c->dev,
"%s: Can not set to powerdown mode.", __func__);
} else {
dev_dbg(&akm->i2c->dev, "Powerdown mode is set.");
udelay(100);
}
akm->is_busy = 0;
atomic_set(&akm->drdy, 0);
mutex_unlock(&akm->sensor_mutex);
return err;
}
static int AKECS_Reset(
struct akm_compass_data *akm,
int hard)
{
int err;
#if AKM_HAS_RESET
uint8_t buffer[2];
mutex_lock(&akm->sensor_mutex);
if (hard != 0) {
gpio_set_value(akm->gpio_rstn, 0);
udelay(5);
gpio_set_value(akm->gpio_rstn, 1);
err = 0;
} else {
buffer[0] = AKM_REG_RESET;
buffer[1] = AKM_RESET_DATA;
err = akm_i2c_txdata(akm->i2c, buffer, 2);
if (err < 0) {
dev_err(&akm->i2c->dev,
"%s: Can not set SRST bit.", __func__);
} else {
dev_dbg(&akm->i2c->dev, "Soft reset is done.");
}
}
udelay(100);
akm->is_busy = 0;
atomic_set(&akm->drdy, 0);
mutex_unlock(&akm->sensor_mutex);
#else
err = AKECS_Set_PowerDown(akm);
#endif
return err;
}
static int AKECS_SetMode(
struct akm_compass_data *akm,
uint8_t mode)
{
int err;
switch (mode & 0x1F) {
case AKM_MODE_SNG_MEASURE:
case AKM_MODE_SELF_TEST:
case AKM_MODE_FUSE_ACCESS:
err = AKECS_Set_CNTL(akm, mode);
break;
case AKM_MODE_POWERDOWN:
err = AKECS_Set_PowerDown(akm);
break;
default:
dev_err(&akm->i2c->dev,
"%s: Unknown mode(%d).", __func__, mode);
return -EINVAL;
}
return err;
}
static void AKECS_SetYPR(
struct akm_compass_data *akm,
int *rbuf)
{
uint32_t ready;
dev_vdbg(&akm->i2c->dev, "%s: flag =0x%X", __func__, rbuf[0]);
dev_vdbg(&akm->input->dev, " Acc [LSB] : %6d,%6d,%6d stat=%d",
rbuf[1], rbuf[2], rbuf[3], rbuf[4]);
dev_vdbg(&akm->input->dev, " Geo [LSB] : %6d,%6d,%6d stat=%d",
rbuf[5], rbuf[6], rbuf[7], rbuf[8]);
dev_vdbg(&akm->input->dev, " Orientation : %6d,%6d,%6d",
rbuf[9], rbuf[10], rbuf[11]);
dev_vdbg(&akm->input->dev, " Rotation V : %6d,%6d,%6d,%6d",
rbuf[12], rbuf[13], rbuf[14], rbuf[15]);
if (!rbuf[0]) {
dev_dbg(&akm->i2c->dev, "Don't waste a time.");
return;
}
mutex_lock(&akm->val_mutex);
ready = (akm->enable_flag & (uint32_t)rbuf[0]);
mutex_unlock(&akm->val_mutex);
if (ready & ACC_DATA_READY) {
input_report_abs(akm->input, ABS_X, rbuf[1]);
input_report_abs(akm->input, ABS_Y, rbuf[2]);
input_report_abs(akm->input, ABS_Z, rbuf[3]);
}
if (ready & MAG_DATA_READY) {
input_report_abs(akm->input, ABS_RX, rbuf[5]);
input_report_abs(akm->input, ABS_RY, rbuf[6]);
input_report_abs(akm->input, ABS_RZ, rbuf[7]);
input_report_abs(akm->input, ABS_RUDDER, rbuf[8]);
}
if (ready & FUSION_DATA_READY) {
input_report_abs(akm->input, ABS_HAT0X, rbuf[9]);
input_report_abs(akm->input, ABS_HAT0Y, rbuf[10]);
input_report_abs(akm->input, ABS_HAT1X, rbuf[11]);
input_report_abs(akm->input, ABS_HAT1Y, rbuf[4]);
input_report_abs(akm->input, ABS_TILT_X, rbuf[12]);
input_report_abs(akm->input, ABS_TILT_Y, rbuf[13]);
input_report_abs(akm->input, ABS_TOOL_WIDTH, rbuf[14]);
input_report_abs(akm->input, ABS_VOLUME, rbuf[15]);
}
input_sync(akm->input);
}
static int AKECS_GetData(
struct akm_compass_data *akm,
uint8_t *rbuf,
int size)
{
int err;
err = wait_event_interruptible_timeout(
akm->drdy_wq,
atomic_read(&akm->drdy),
msecs_to_jiffies(AKM_DRDY_TIMEOUT_MS));
if (err < 0) {
dev_err(&akm->i2c->dev,
"%s: wait_event failed (%d).", __func__, err);
return err;
}
if (!atomic_read(&akm->drdy)) {
I("%s: DRDY is not set.\n", __func__);
return -ENODATA;
}
mutex_lock(&akm->sensor_mutex);
memcpy(rbuf, akm->sense_data, size);
atomic_set(&akm->drdy, 0);
mutex_unlock(&akm->sensor_mutex);
return 0;
}
static int AKECS_GetData_Poll(
struct akm_compass_data *akm,
uint8_t *rbuf,
int size)
{
uint8_t buffer[AKM_SENSOR_DATA_SIZE];
int err;
buffer[0] = AKM_REG_STATUS;
err = akm_i2c_rxdata(akm->i2c, buffer, 1);
if (err < 0) {
dev_err(&akm->i2c->dev, "%s failed.", __func__);
return err;
}
if (!(AKM_DRDY_IS_HIGH(buffer[0])))
return -EAGAIN;
buffer[1] = AKM_REG_STATUS + 1;
err = akm_i2c_rxdata(akm->i2c, &(buffer[1]), AKM_SENSOR_DATA_SIZE-1);
if (err < 0) {
dev_err(&akm->i2c->dev, "%s failed.", __func__);
return err;
}
memcpy(rbuf, buffer, size);
atomic_set(&akm->drdy, 0);
mutex_lock(&akm->sensor_mutex);
akm->is_busy = 0;
mutex_unlock(&akm->sensor_mutex);
return 0;
}
static int akm8963_sr_ldo_init(int init)
{
int rc = 0;
struct akm_compass_data *akm8963 = s_akm;
if (akm8963 == NULL) {
E("%s: akm8963 == NULL\n", __func__);
return -1;
}
if (!init) {
regulator_set_voltage(akm8963->sr_1v8, 0, 1800000);
regulator_set_voltage(akm8963->sr_2v85, 0, 2850000);
return 0;
}
akm8963->sr_2v85 = devm_regulator_get(&akm8963->i2c->dev, "SR_2v85");
if (IS_ERR(akm8963->sr_2v85)) {
akm8963->sr_2v85 = NULL;
akm8963->sr_1v8 = NULL;
E("%s: Unable to get sr 2v85\n", __func__);
return PTR_ERR(akm8963->sr_2v85);
}
I("%s: akm8963->sr_2v85 = 0x%p\n", __func__, akm8963->sr_2v85);
rc = regulator_set_voltage(akm8963->sr_2v85, 2850000, 2850000);
if (rc) {
E("%s: unable to set voltage for sr 2v85\n", __func__);
return rc;
}
akm8963->sr_1v8 = devm_regulator_get(&akm8963->i2c->dev, "SR_1v8");
if (IS_ERR(akm8963->sr_1v8)) {
E("%s: unable to get sr 1v8\n", __func__);
rc = PTR_ERR(akm8963->sr_1v8);
akm8963->sr_1v8 = NULL;
goto devote_2v85;
}
rc = regulator_set_voltage(akm8963->sr_1v8, 1800000, 1800000);
if (rc) {
E("%s: unable to set voltage for sr 1v8\n", __func__);
goto devote_2v85;
}
I("%s: akm8963->sr_1v8 = 0x%p\n", __func__, akm8963->sr_1v8);
return 0;
devote_2v85:
regulator_set_voltage(akm8963->sr_2v85, 0, 2850000);
return rc;
}
static int akm8963_sr_lpm(int on)
{
int rc = 0;
struct akm_compass_data *akm8963 = s_akm;
D("%s++: vreg (%s)\n", __func__, on ? "LPM" : "HPM");
if (akm8963 == NULL) {
E("%s: akm8963 == NULL\n", __func__);
return -1;
}
if ((akm8963->sr_1v8 == NULL) || (akm8963->sr_2v85 == NULL)) {
I("%s: Regulator not available, return!!\n", __func__);
return 0;
}
if (on) {
rc = regulator_set_optimum_mode(akm8963->sr_1v8, 100);
if (rc < 0)
E("Unable to set LPM of regulator sr_1v8\n");
rc = regulator_enable(akm8963->sr_1v8);
if (rc)
E("Unable to enable sr_1v8 111\n");
D("%s: Set SR_1v8 to LPM--\n", __func__);
rc = regulator_set_optimum_mode(akm8963->sr_2v85, 100);
if (rc < 0)
E("Unable to set LPM of regulator sr_2v85\n");
rc = regulator_enable(akm8963->sr_2v85);
if (rc)
E("Unable to enable sr_2v85 111\n");
D("%s: Set SR_2v85 to LPM--\n", __func__);
} else {
rc = regulator_set_optimum_mode(akm8963->sr_1v8, 100000);
if (rc < 0)
E("Unable to set HPM of regulator sr_1v8\n");
rc = regulator_enable(akm8963->sr_1v8);
if (rc)
E("Unable to enable sr_1v8 222\n");
D("%s: Set SR_1v8 to HPM--\n", __func__);
rc = regulator_set_optimum_mode(akm8963->sr_2v85, 100000);
if (rc < 0)
E("Unable to set HPM of regulator sr_2v85\n");
rc = regulator_enable(akm8963->sr_2v85);
if (rc)
E("Unable to enable sr_2v85 222\n");
D("%s: Set SR_2v85 to HPM--\n", __func__);
}
return rc < 0 ? rc : 0;
}
static int AKECS_GetOpenStatus(
struct akm_compass_data *akm)
{
D("%s++\n", __func__);
wait_event_interruptible(
akm->open_wq, (atomic_read(&akm->active) != 0));
D("%s\n", __func__);
if (s_akm->power_LPM)
s_akm->power_LPM(0);
return atomic_read(&akm->active);
}
static int AKECS_GetCloseStatus(
struct akm_compass_data *akm)
{
D("%s++\n", __func__);
wait_event_interruptible(
akm->open_wq, (atomic_read(&akm->active) <= 0));
D("%s\n", __func__);
if (s_akm->power_LPM)
s_akm->power_LPM(1);
return atomic_read(&akm->active);
}
static int AKECS_Open(struct inode *inode, struct file *file)
{
file->private_data = s_akm;
return nonseekable_open(inode, file);
}
static int AKECS_Release(struct inode *inode, struct file *file)
{
return 0;
}
static long
AKECS_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
struct akm_compass_data *akm = file->private_data;
uint8_t i2c_buf[AKM_RWBUF_SIZE] = {0};
uint8_t dat_buf[AKM_SENSOR_DATA_SIZE] = {0};
int32_t ypr_buf[AKM_YPR_DATA_SIZE] = {0};
int64_t delay[AKM_NUM_SENSORS] = {0};
int16_t acc_buf[3] = {0};
uint8_t mode = 0;
int status = 0;
int ret = 0;
switch (cmd) {
case ECS_IOCTL_READ:
case ECS_IOCTL_WRITE:
if (argp == NULL) {
dev_err(&akm->i2c->dev, "invalid argument.");
return -EINVAL;
}
if (copy_from_user(&i2c_buf, argp, sizeof(i2c_buf))) {
dev_err(&akm->i2c->dev, "copy_from_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_SET_MODE:
if (argp == NULL) {
dev_err(&akm->i2c->dev, "invalid argument.");
return -EINVAL;
}
if (copy_from_user(&mode, argp, sizeof(mode))) {
dev_err(&akm->i2c->dev, "copy_from_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_SET_YPR:
if (argp == NULL) {
dev_err(&akm->i2c->dev, "invalid argument.");
return -EINVAL;
}
if (copy_from_user(&ypr_buf, argp, sizeof(ypr_buf))) {
dev_err(&akm->i2c->dev, "copy_from_user failed.");
return -EFAULT;
}
case ECS_IOCTL_GET_INFO:
case ECS_IOCTL_GET_CONF:
case ECS_IOCTL_GET_DATA:
case ECS_IOCTL_GET_OPEN_STATUS:
case ECS_IOCTL_GET_CLOSE_STATUS:
case ECS_IOCTL_GET_DELAY:
case ECS_IOCTL_GET_LAYOUT:
case ECS_IOCTL_GET_ACCEL:
if (argp == NULL) {
dev_err(&akm->i2c->dev, "invalid argument.");
return -EINVAL;
}
break;
default:
break;
}
switch (cmd) {
case ECS_IOCTL_READ:
dev_vdbg(&akm->i2c->dev, "IOCTL_READ called.");
if ((i2c_buf[0] < 1) || (i2c_buf[0] > (AKM_RWBUF_SIZE-1))) {
dev_err(&akm->i2c->dev, "invalid argument.");
return -EINVAL;
}
ret = akm_i2c_rxdata(akm->i2c, &i2c_buf[1], i2c_buf[0]);
if (ret < 0)
return ret;
break;
case ECS_IOCTL_WRITE:
dev_vdbg(&akm->i2c->dev, "IOCTL_WRITE called.");
if ((i2c_buf[0] < 2) || (i2c_buf[0] > (AKM_RWBUF_SIZE-1))) {
dev_err(&akm->i2c->dev, "invalid argument.");
return -EINVAL;
}
ret = akm_i2c_txdata(akm->i2c, &i2c_buf[1], i2c_buf[0]);
if (ret < 0)
return ret;
break;
case ECS_IOCTL_RESET:
dev_vdbg(&akm->i2c->dev, "IOCTL_RESET called.");
ret = AKECS_Reset(akm, akm->gpio_rstn);
if (ret < 0)
return ret;
break;
case ECS_IOCTL_SET_MODE:
dev_vdbg(&akm->i2c->dev, "IOCTL_SET_MODE called.");
ret = AKECS_SetMode(akm, mode);
if (ret < 0)
return ret;
break;
case ECS_IOCTL_SET_YPR:
dev_vdbg(&akm->i2c->dev, "IOCTL_SET_YPR called.");
AKECS_SetYPR(akm, ypr_buf);
break;
case ECS_IOCTL_GET_DATA:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_DATA called.");
if (akm->irq)
ret = AKECS_GetData(akm, dat_buf, AKM_SENSOR_DATA_SIZE);
else
ret = AKECS_GetData_Poll(
akm, dat_buf, AKM_SENSOR_DATA_SIZE);
if (ret < 0)
return ret;
break;
case ECS_IOCTL_GET_OPEN_STATUS:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_OPEN_STATUS called.");
ret = AKECS_GetOpenStatus(akm);
if (ret < 0) {
dev_err(&akm->i2c->dev,
"Get Open returns error (%d).", ret);
return ret;
}
break;
case ECS_IOCTL_GET_CLOSE_STATUS:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_CLOSE_STATUS called.");
ret = AKECS_GetCloseStatus(akm);
if (ret < 0) {
dev_err(&akm->i2c->dev,
"Get Close returns error (%d).", ret);
return ret;
}
break;
case ECS_IOCTL_GET_DELAY:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_DELAY called.");
mutex_lock(&akm->val_mutex);
delay[0] = ((akm->enable_flag & ACC_DATA_READY) ?
akm->delay[0] : -1);
delay[1] = ((akm->enable_flag & MAG_DATA_READY) ?
akm->delay[1] : -1);
delay[2] = ((akm->enable_flag & FUSION_DATA_READY) ?
akm->delay[2] : -1);
mutex_unlock(&akm->val_mutex);
break;
case ECS_IOCTL_GET_INFO:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_INFO called.");
break;
case ECS_IOCTL_GET_CONF:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_CONF called.");
break;
case ECS_IOCTL_GET_LAYOUT:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_LAYOUT called.");
break;
case ECS_IOCTL_GET_ACCEL:
dev_vdbg(&akm->i2c->dev, "IOCTL_GET_ACCEL called.");
mutex_lock(&akm->accel_mutex);
acc_buf[0] = akm->accel_data[0];
acc_buf[1] = akm->accel_data[1];
acc_buf[2] = akm->accel_data[2];
mutex_unlock(&akm->accel_mutex);
break;
default:
return -ENOTTY;
}
switch (cmd) {
case ECS_IOCTL_READ:
if (copy_to_user(argp, &i2c_buf, i2c_buf[0]+1)) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_GET_INFO:
if (copy_to_user(argp, &akm->sense_info,
sizeof(akm->sense_info))) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_GET_CONF:
if (copy_to_user(argp, &akm->sense_conf,
sizeof(akm->sense_conf))) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_GET_DATA:
if (copy_to_user(argp, &dat_buf, sizeof(dat_buf))) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_GET_OPEN_STATUS:
case ECS_IOCTL_GET_CLOSE_STATUS:
status = atomic_read(&akm->active);
if (copy_to_user(argp, &status, sizeof(status))) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_GET_DELAY:
if (copy_to_user(argp, &delay, sizeof(delay))) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_GET_LAYOUT:
if (copy_to_user(argp, &akm->layout, sizeof(akm->layout))) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
case ECS_IOCTL_GET_ACCEL:
if (copy_to_user(argp, &acc_buf, sizeof(acc_buf))) {
dev_err(&akm->i2c->dev, "copy_to_user failed.");
return -EFAULT;
}
break;
default:
break;
}
return 0;
}
static const struct file_operations AKECS_fops = {
.owner = THIS_MODULE,
.open = AKECS_Open,
.release = AKECS_Release,
.unlocked_ioctl = AKECS_ioctl,
};
static struct miscdevice akm_compass_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = AKM_MISCDEV_NAME,
.fops = &AKECS_fops,
};
static int create_device_attributes(
struct device *dev,
struct device_attribute *attrs)
{
int i;
int err = 0;
for (i = 0 ; NULL != attrs[i].attr.name ; ++i) {
err = device_create_file(dev, &attrs[i]);
if (err)
break;
}
if (err) {
for (--i; i >= 0 ; --i)
device_remove_file(dev, &attrs[i]);
}
return err;
}
static void remove_device_attributes(
struct device *dev,
struct device_attribute *attrs)
{
int i;
for (i = 0 ; NULL != attrs[i].attr.name ; ++i)
device_remove_file(dev, &attrs[i]);
}
static int create_device_binary_attributes(
struct kobject *kobj,
struct bin_attribute *attrs)
{
int i;
int err = 0;
err = 0;
for (i = 0 ; NULL != attrs[i].attr.name ; ++i) {
err = sysfs_create_bin_file(kobj, &attrs[i]);
if (0 != err)
break;
}
if (0 != err) {
for (--i; i >= 0 ; --i)
sysfs_remove_bin_file(kobj, &attrs[i]);
}
return err;
}
static void remove_device_binary_attributes(
struct kobject *kobj,
struct bin_attribute *attrs)
{
int i;
for (i = 0 ; NULL != attrs[i].attr.name ; ++i)
sysfs_remove_bin_file(kobj, &attrs[i]);
}
static void akm_compass_sysfs_update_status(
struct akm_compass_data *akm)
{
uint32_t en;
mutex_lock(&akm->val_mutex);
en = akm->enable_flag;
mutex_unlock(&akm->val_mutex);
if (en == 0) {
if (atomic_cmpxchg(&akm->active, 1, 0) == 1) {
wake_up(&akm->open_wq);
dev_dbg(akm->class_dev, "Deactivated");
}
} else {
if (atomic_cmpxchg(&akm->active, 0, 1) == 0) {
wake_up(&akm->open_wq);
dev_dbg(akm->class_dev, "Activated");
}
}
dev_dbg(&akm->i2c->dev,
"Status updated: enable=0x%X, active=%d",
en, atomic_read(&akm->active));
}
static ssize_t akm_compass_sysfs_enable_show(
struct akm_compass_data *akm, char *buf, int pos)
{
int flag;
mutex_lock(&akm->val_mutex);
flag = ((akm->enable_flag >> pos) & 1);
mutex_unlock(&akm->val_mutex);
return scnprintf(buf, PAGE_SIZE, "%d\n", flag);
}
static ssize_t akm_compass_sysfs_enable_store(
struct akm_compass_data *akm, char const *buf, size_t count, int pos)
{
long en = 0;
if (NULL == buf)
return -EINVAL;
if (0 == count)
return 0;
if (strict_strtol(buf, AKM_BASE_NUM, &en))
return -EINVAL;
en = en ? 1 : 0;
mutex_lock(&akm->val_mutex);
akm->enable_flag &= ~(1<<pos);
akm->enable_flag |= ((uint32_t)(en))<<pos;
mutex_unlock(&akm->val_mutex);
akm_compass_sysfs_update_status(akm);
return count;
}
static ssize_t akm_enable_acc_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
return akm_compass_sysfs_enable_show(
dev_get_drvdata(dev), buf, ACC_DATA_FLAG);
}
static ssize_t akm_enable_acc_store(
struct device *dev, struct device_attribute *attr,
char const *buf, size_t count)
{
return akm_compass_sysfs_enable_store(
dev_get_drvdata(dev), buf, count, ACC_DATA_FLAG);
}
static ssize_t akm_enable_mag_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
return akm_compass_sysfs_enable_show(
dev_get_drvdata(dev), buf, MAG_DATA_FLAG);
}
static ssize_t akm_enable_mag_store(
struct device *dev, struct device_attribute *attr,
char const *buf, size_t count)
{
return akm_compass_sysfs_enable_store(
dev_get_drvdata(dev), buf, count, MAG_DATA_FLAG);
}
static ssize_t akm_enable_fusion_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
return akm_compass_sysfs_enable_show(
dev_get_drvdata(dev), buf, FUSION_DATA_FLAG);
}
static ssize_t akm_enable_fusion_store(
struct device *dev, struct device_attribute *attr,
char const *buf, size_t count)
{
return akm_compass_sysfs_enable_store(
dev_get_drvdata(dev), buf, count, FUSION_DATA_FLAG);
}
static ssize_t akm_compass_sysfs_delay_show(
struct akm_compass_data *akm, char *buf, int pos)
{
int64_t val;
mutex_lock(&akm->val_mutex);
val = akm->delay[pos];
mutex_unlock(&akm->val_mutex);
return scnprintf(buf, PAGE_SIZE, "%lld\n", val);
}
static ssize_t akm_compass_sysfs_delay_store(
struct akm_compass_data *akm, char const *buf, size_t count, int pos)
{
long long val = 0;
if (NULL == buf)
return -EINVAL;
if (0 == count)
return 0;
if (strict_strtoll(buf, AKM_BASE_NUM, &val))
return -EINVAL;
mutex_lock(&akm->val_mutex);
akm->delay[pos] = val;
mutex_unlock(&akm->val_mutex);
return count;
}
static ssize_t akm_delay_acc_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
return akm_compass_sysfs_delay_show(
dev_get_drvdata(dev), buf, ACC_DATA_FLAG);
}
static ssize_t akm_delay_acc_store(
struct device *dev, struct device_attribute *attr,
char const *buf, size_t count)
{
return akm_compass_sysfs_delay_store(
dev_get_drvdata(dev), buf, count, ACC_DATA_FLAG);
}
static ssize_t akm_delay_mag_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
return akm_compass_sysfs_delay_show(
dev_get_drvdata(dev), buf, MAG_DATA_FLAG);
}
static ssize_t akm_delay_mag_store(
struct device *dev, struct device_attribute *attr,
char const *buf, size_t count)
{
return akm_compass_sysfs_delay_store(
dev_get_drvdata(dev), buf, count, MAG_DATA_FLAG);
}
static ssize_t akm_delay_fusion_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
return akm_compass_sysfs_delay_show(
dev_get_drvdata(dev), buf, FUSION_DATA_FLAG);
}
static ssize_t akm_delay_fusion_store(
struct device *dev, struct device_attribute *attr,
char const *buf, size_t count)
{
return akm_compass_sysfs_delay_store(
dev_get_drvdata(dev), buf, count, FUSION_DATA_FLAG);
}
static ssize_t akm_bin_accel_write(
struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf,
loff_t pos,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct akm_compass_data *akm = dev_get_drvdata(dev);
int16_t *accel_data;
if (size == 0)
return 0;
accel_data = (int16_t *)buf;
mutex_lock(&akm->accel_mutex);
akm->accel_data[0] = accel_data[0];
akm->accel_data[1] = accel_data[1];
akm->accel_data[2] = accel_data[2];
mutex_unlock(&akm->accel_mutex);
dev_vdbg(&akm->i2c->dev, "accel:%d,%d,%d\n",
accel_data[0], accel_data[1], accel_data[2]);
return size;
}
#if AKM_DEBUG_IF
static ssize_t akm_sysfs_mode_store(
struct device *dev, struct device_attribute *attr,
char const *buf, size_t count)
{
struct akm_compass_data *akm = dev_get_drvdata(dev);
long mode = 0;
if (NULL == buf)
return -EINVAL;
if (0 == count)
return 0;
if (strict_strtol(buf, AKM_BASE_NUM, &mode))
return -EINVAL;
if (AKECS_SetMode(akm, (uint8_t)mode) < 0)
return -EINVAL;
return 1;
}
static ssize_t akm_buf_print(
char *buf, uint8_t *data, size_t num)
{
int sz, i;
char *cur;
size_t cur_len;
cur = buf;
cur_len = PAGE_SIZE;
sz = snprintf(cur, cur_len, "(HEX):");
if (sz < 0)
return sz;
cur += sz;
cur_len -= sz;
for (i = 0; i < num; i++) {
sz = snprintf(cur, cur_len, "%02X,", *data);
if (sz < 0)
return sz;
cur += sz;
cur_len -= sz;
data++;
}
sz = snprintf(cur, cur_len, "\n");
if (sz < 0)
return sz;
cur += sz;
return (ssize_t)(cur - buf);
}
static ssize_t akm_sysfs_bdata_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
struct akm_compass_data *akm = dev_get_drvdata(dev);
uint8_t rbuf[AKM_SENSOR_DATA_SIZE];
mutex_lock(&akm->sensor_mutex);
memcpy(&rbuf, akm->sense_data, sizeof(rbuf));
mutex_unlock(&akm->sensor_mutex);
return akm_buf_print(buf, rbuf, AKM_SENSOR_DATA_SIZE);
}
static ssize_t akm_sysfs_asa_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
struct akm_compass_data *akm = dev_get_drvdata(dev);
int err;
uint8_t asa[3];
err = AKECS_SetMode(akm, AKM_MODE_FUSE_ACCESS);
if (err < 0)
return err;
asa[0] = AKM_FUSE_1ST_ADDR;
err = akm_i2c_rxdata(akm->i2c, asa, 3);
if (err < 0)
return err;
err = AKECS_SetMode(akm, AKM_MODE_POWERDOWN);
if (err < 0)
return err;
return akm_buf_print(buf, asa, 3);
}
static ssize_t akm_sysfs_regs_show(
struct device *dev, struct device_attribute *attr, char *buf)
{
struct akm_compass_data *akm = dev_get_drvdata(dev);
int err;
uint8_t regs[AKM_REGS_SIZE];
regs[0] = AKM_REGS_1ST_ADDR;
err = akm_i2c_rxdata(akm->i2c, regs, AKM_REGS_SIZE);
if (err < 0)
return err;
return akm_buf_print(buf, regs, AKM_REGS_SIZE);
}
#endif
static struct device_attribute akm_compass_attributes[] = {
__ATTR(enable_acc, 0660, akm_enable_acc_show, akm_enable_acc_store),
__ATTR(enable_mag, 0660, akm_enable_mag_show, akm_enable_mag_store),
__ATTR(enable_fusion, 0660, akm_enable_fusion_show,
akm_enable_fusion_store),
__ATTR(delay_acc, 0660, akm_delay_acc_show, akm_delay_acc_store),
__ATTR(delay_mag, 0660, akm_delay_mag_show, akm_delay_mag_store),
__ATTR(delay_fusion, 0660, akm_delay_fusion_show,
akm_delay_fusion_store),
#if AKM_DEBUG_IF
__ATTR(mode, 0220, NULL, akm_sysfs_mode_store),
__ATTR(bdata, 0440, akm_sysfs_bdata_show, NULL),
__ATTR(asa, 0440, akm_sysfs_asa_show, NULL),
__ATTR(regs, 0440, akm_sysfs_regs_show, NULL),
#endif
__ATTR_NULL,
};
#define __BIN_ATTR(name_, mode_, size_, private_, read_, write_) \
{ \
.attr = { .name = __stringify(name_), .mode = mode_ }, \
.size = size_, \
.private = private_, \
.read = read_, \
.write = write_, \
}
#define __BIN_ATTR_NULL \
{ \
.attr = { .name = NULL }, \
}
static struct bin_attribute akm_compass_bin_attributes[] = {
__BIN_ATTR(accel, 0220, 6, NULL,
NULL, akm_bin_accel_write),
__BIN_ATTR_NULL
};
static char const *const device_link_name = "i2c";
static dev_t const akm_compass_device_dev_t = MKDEV(MISC_MAJOR, 240);
static int create_sysfs_interfaces(struct akm_compass_data *akm)
{
int err;
if (NULL == akm)
return -EINVAL;
err = 0;
akm->compass = class_create(THIS_MODULE, AKM_SYSCLS_NAME);
if (IS_ERR(akm->compass)) {
err = PTR_ERR(akm->compass);
goto exit_class_create_failed;
}
akm->class_dev = device_create(
akm->compass,
NULL,
akm_compass_device_dev_t,
akm,
AKM_SYSDEV_NAME);
if (IS_ERR(akm->class_dev)) {
err = PTR_ERR(akm->class_dev);
goto exit_class_device_create_failed;
}
err = sysfs_create_link(
&akm->class_dev->kobj,
&akm->i2c->dev.kobj,
device_link_name);
if (0 > err)
goto exit_sysfs_create_link_failed;
err = create_device_attributes(
akm->class_dev,
akm_compass_attributes);
if (0 > err)
goto exit_device_attributes_create_failed;
err = create_device_binary_attributes(
&akm->class_dev->kobj,
akm_compass_bin_attributes);
if (0 > err)
goto exit_device_binary_attributes_create_failed;
return err;
exit_device_binary_attributes_create_failed:
remove_device_attributes(akm->class_dev, akm_compass_attributes);
exit_device_attributes_create_failed:
sysfs_remove_link(&akm->class_dev->kobj, device_link_name);
exit_sysfs_create_link_failed:
device_destroy(akm->compass, akm_compass_device_dev_t);
exit_class_device_create_failed:
akm->class_dev = NULL;
class_destroy(akm->compass);
exit_class_create_failed:
akm->compass = NULL;
return err;
}
static void remove_sysfs_interfaces(struct akm_compass_data *akm)
{
if (NULL == akm)
return;
if (NULL != akm->class_dev) {
remove_device_binary_attributes(
&akm->class_dev->kobj,
akm_compass_bin_attributes);
remove_device_attributes(
akm->class_dev,
akm_compass_attributes);
sysfs_remove_link(
&akm->class_dev->kobj,
device_link_name);
akm->class_dev = NULL;
}
if (NULL != akm->compass) {
device_destroy(
akm->compass,
akm_compass_device_dev_t);
class_destroy(akm->compass);
akm->compass = NULL;
}
}
static int akm_compass_input_init(
struct input_dev **input)
{
int err = 0;
*input = input_allocate_device();
if (!*input)
return -ENOMEM;
set_bit(EV_ABS, (*input)->evbit);
input_set_abs_params(*input, ABS_X,
-11520, 11520, 0, 0);
input_set_abs_params(*input, ABS_Y,
-11520, 11520, 0, 0);
input_set_abs_params(*input, ABS_Z,
-11520, 11520, 0, 0);
input_set_abs_params(*input, ABS_RX,
0, 3, 0, 0);
input_set_abs_params(*input, ABS_RY,
-32768, 32767, 0, 0);
input_set_abs_params(*input, ABS_RZ,
-32768, 32767, 0, 0);
input_set_abs_params(*input, ABS_THROTTLE,
-32768, 32767, 0, 0);
input_set_abs_params(*input, ABS_RUDDER,
0, 3, 0, 0);
input_set_abs_params(*input, ABS_HAT0X,
0, 23040, 0, 0);
input_set_abs_params(*input, ABS_HAT0Y,
-11520, 11520, 0, 0);
input_set_abs_params(*input, ABS_HAT1X,
-5760, 5760, 0, 0);
input_set_abs_params(*input, ABS_HAT1Y,
0, 3, 0, 0);
input_set_abs_params(*input, ABS_TILT_X,
-16384, 16384, 0, 0);
input_set_abs_params(*input, ABS_TILT_Y,
-16384, 16384, 0, 0);
input_set_abs_params(*input, ABS_TOOL_WIDTH,
-16384, 16384, 0, 0);
input_set_abs_params(*input, ABS_VOLUME,
-16384, 16384, 0, 0);
(*input)->name = AKM_INPUT_DEVICE_NAME;
err = input_register_device(*input);
if (err) {
input_free_device(*input);
return err;
}
return err;
}
static irqreturn_t akm_compass_irq(int irq, void *handle)
{
struct akm_compass_data *akm = handle;
uint8_t buffer[AKM_SENSOR_DATA_SIZE];
int err;
memset(buffer, 0, sizeof(buffer));
mutex_lock(&akm->sensor_mutex);
buffer[0] = AKM_REG_STATUS;
err = akm_i2c_rxdata(akm->i2c, buffer, AKM_SENSOR_DATA_SIZE);
if (err < 0) {
dev_err(&akm->i2c->dev, "IRQ I2C error.");
akm->is_busy = 0;
mutex_unlock(&akm->sensor_mutex);
return IRQ_HANDLED;
}
if (!(AKM_DRDY_IS_HIGH(buffer[0])))
goto work_func_none;
memcpy(akm->sense_data, buffer, AKM_SENSOR_DATA_SIZE);
akm->is_busy = 0;
mutex_unlock(&akm->sensor_mutex);
atomic_set(&akm->drdy, 1);
wake_up(&akm->drdy_wq);
dev_vdbg(&akm->i2c->dev, "IRQ handled.");
return IRQ_HANDLED;
work_func_none:
mutex_unlock(&akm->sensor_mutex);
dev_vdbg(&akm->i2c->dev, "IRQ not handled.");
return IRQ_NONE;
}
static int akm_compass_suspend(struct device *dev)
{
if (s_akm && (s_akm->power_LPM))
s_akm->power_LPM(1);
return 0;
}
static int akm_compass_resume(struct device *dev)
{
return 0;
}
static int akm8963_i2c_check_device(
struct i2c_client *client)
{
struct akm_compass_data *akm = i2c_get_clientdata(client);
int err;
akm->sense_info[0] = AK8963_REG_WIA;
err = akm_i2c_rxdata(client, akm->sense_info, AKM_SENSOR_INFO_SIZE);
if (err < 0)
return err;
err = AKECS_SetMode(akm, AK8963_MODE_FUSE_ACCESS);
if (err < 0)
return err;
akm->sense_conf[0] = AK8963_FUSE_ASAX;
err = akm_i2c_rxdata(client, akm->sense_conf, AKM_SENSOR_CONF_SIZE);
if (err < 0)
return err;
err = AKECS_SetMode(akm, AK8963_MODE_POWERDOWN);
if (err < 0)
return err;
if (akm->sense_info[0] != AK8963_WIA_VALUE) {
dev_err(&client->dev,
"%s: The device is not AKM Compass.", __func__);
return -ENXIO;
}
return err;
}
static int akm8963_parse_dt(struct device *dev, struct akm8963_platform_data *pdata)
{
struct property *prop = NULL;
struct device_node *dt = dev->of_node;
u32 buf = 0;
uint32_t irq_gpio_flags = 0;
if (s_akm == NULL) {
E("%s: s_akm is NULL\n", __func__);
return -EINVAL;
}
prop = of_find_property(dt, "compass_akm8963,layout", NULL);
if (prop) {
of_property_read_u32(dt, "compass_akm8963,layout", &buf);
pdata->layout = buf;
I("%s: layout = %d", __func__, pdata->layout);
} else
I("%s: compass_akm8963,layout not found", __func__);
pdata->gpio_DRDY = of_get_named_gpio_flags(dt,
"compass_akm8963,gpio_DRDY",
0,
&irq_gpio_flags);
if (pdata->gpio_DRDY < 0) {
E("%s: of_get_named_gpio_flags fails: pdata->gpio_DRDY\n", __func__);
return -EINVAL;
}
I("%s: gpio_DRDY = %d", __func__, pdata->gpio_DRDY);
pdata->gpio_RSTN = of_get_named_gpio_flags(dt,
"compass_akm8963,gpio_RSTN",
0,
&irq_gpio_flags);
if (pdata->gpio_RSTN < 0) {
E("%s: of_get_named_gpio_flags fails: pdata->gpio_RSTN\n", __func__);
pdata->gpio_RSTN = 0;
}
I("%s: gpio_RSTN = %d", __func__, pdata->gpio_RSTN);
pdata->power_LPM = akm8963_sr_lpm;
return 0;
}
int __devinit akm_compass_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct akm8963_platform_data *pdata;
int err = 0;
int i;
dev_dbg(&client->dev, "start probing.");
I("AKM8963 DOE Plus compass driver: probe.\n");
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
dev_err(&client->dev,
"%s: check_functionality failed.", __func__);
err = -ENODEV;
goto exit0;
}
s_akm = kzalloc(sizeof(struct akm_compass_data), GFP_KERNEL);
if (!s_akm) {
dev_err(&client->dev,
"%s: memory allocation failed.", __func__);
err = -ENOMEM;
goto exit1;
}
init_waitqueue_head(&s_akm->drdy_wq);
init_waitqueue_head(&s_akm->open_wq);
mutex_init(&s_akm->sensor_mutex);
mutex_init(&s_akm->accel_mutex);
mutex_init(&s_akm->val_mutex);
atomic_set(&s_akm->active, 0);
atomic_set(&s_akm->drdy, 0);
s_akm->is_busy = 0;
s_akm->enable_flag = 0;
s_akm->accel_data[0] = 0;
s_akm->accel_data[1] = 0;
s_akm->accel_data[2] = 720;
for (i = 0; i < AKM_NUM_SENSORS; i++)
s_akm->delay[i] = -1;
if (client->dev.of_node) {
I("Device Tree parsing.");
pdata = kzalloc(sizeof(*pdata), GFP_KERNEL);
if (pdata == NULL) {
err = -ENOMEM;
dev_err(&client->dev, "%s: memory allocation "
"for pdata failed.",
__func__);
goto exit2;
}
err = akm8963_parse_dt(&client->dev, pdata);
if (err) {
dev_err(&client->dev, "%s: akm8963_parse_dt "
"for pdata failed. err = %d",
__func__, err);
err = -ENOMEM;
goto exit3;
}
client->irq = gpio_to_irq(pdata->gpio_DRDY);
I("%s: client->irq = %d\n", __func__, client->irq);
} else {
pdata = client->dev.platform_data;
}
if (pdata) {
s_akm->layout = pdata->layout;
s_akm->gpio_rstn = pdata->gpio_RSTN;
s_akm->power_LPM = pdata->power_LPM;
} else {
dev_dbg(&client->dev, "%s: No platform data.", __func__);
s_akm->layout = 0;
s_akm->gpio_rstn = 0;
s_akm->power_LPM = NULL;
}
s_akm->i2c = client;
i2c_set_clientdata(client, s_akm);
err = akm8963_i2c_check_device(client);
if (err < 0)
goto exit3;
err = akm_compass_input_init(&s_akm->input);
if (err) {
dev_err(&client->dev,
"%s: input_dev register failed", __func__);
goto exit4;
}
input_set_drvdata(s_akm->input, s_akm);
s_akm->irq = client->irq;
dev_dbg(&client->dev, "%s: IRQ is #%d.",
__func__, s_akm->irq);
if (s_akm->irq) {
err = request_threaded_irq(
s_akm->irq,
NULL,
akm_compass_irq,
IRQF_TRIGGER_HIGH|IRQF_ONESHOT,
dev_name(&client->dev),
s_akm);
if (err < 0) {
dev_err(&client->dev,
"%s: request irq failed.", __func__);
goto exit5;
}
}
err = misc_register(&akm_compass_dev);
if (err) {
dev_err(&client->dev,
"%s: akm_compass_dev register failed", __func__);
goto exit6;
}
err = akm8963_sr_ldo_init(1);
if (err) {
E("Sensor vreg configuration failed\n");
s_akm->power_LPM = NULL;
}
err = akm8963_sr_lpm(0);
if (err)
E("%s: akm8963_sr_lpm failed 111\n", __func__);
err = akm8963_sr_lpm(1);
if (err)
E("%s: akm8963_sr_lpm failed 222\n", __func__);
err = create_sysfs_interfaces(s_akm);
if (0 > err) {
dev_err(&client->dev,
"%s: create sysfs failed.", __func__);
goto exit7;
}
if (pdata) {
kfree(pdata);
pdata = NULL;
}
dev_info(&client->dev, "successfully probed.");
return 0;
exit7:
devm_regulator_put(s_akm->sr_1v8);
devm_regulator_put(s_akm->sr_2v85);
misc_deregister(&akm_compass_dev);
exit6:
if (s_akm->irq)
free_irq(s_akm->irq, s_akm);
exit5:
input_unregister_device(s_akm->input);
exit4:
exit3:
if (pdata) {
kfree(pdata);
pdata = NULL;
}
exit2:
if (s_akm)
kfree(s_akm);
exit1:
exit0:
return err;
}
static int akm_compass_remove(struct i2c_client *client)
{
struct akm_compass_data *akm = i2c_get_clientdata(client);
remove_sysfs_interfaces(akm);
if (misc_deregister(&akm_compass_dev) < 0)
dev_err(&client->dev, "misc deregister failed.");
if (akm->irq)
free_irq(akm->irq, akm);
input_unregister_device(akm->input);
kfree(akm);
dev_info(&client->dev, "successfully removed.");
return 0;
}
static const struct i2c_device_id akm_compass_id[] = {
{AKM_I2C_NAME, 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, akm_compass_id);
#ifdef CONFIG_OF
static struct of_device_id akm8963_match_table[] = {
{.compatible = "htc_compass,akm8963" },
{},
};
#else
#define akm8963_match_table NULL
#endif
static const struct dev_pm_ops akm_compass_pm_ops = {
#ifdef CONFIG_PM
.suspend = akm_compass_suspend,
.resume = akm_compass_resume,
#endif
};
static struct i2c_driver akm_compass_driver = {
#ifdef CONFIG_OF
.probe = akm_compass_probe,
.remove = akm_compass_remove,
.id_table = akm_compass_id,
.driver = {
.name = AKM_I2C_NAME,
.owner = THIS_MODULE,
.of_match_table = akm8963_match_table,
#ifdef CONFIG_PM
.pm = &akm_compass_pm_ops,
#endif
},
#else
.probe = akm_compass_probe,
.remove = akm_compass_remove,
.id_table = akm_compass_id,
.driver = {
.name = AKM_I2C_NAME,
.pm = &akm_compass_pm_ops,
},
#endif
};
#ifdef CONFIG_OF
module_i2c_driver(akm_compass_driver);
#else
static int __init akm_compass_init(void)
{
pr_info("AKM compass driver: initialize.");
return i2c_add_driver(&akm_compass_driver);
}
static void __exit akm_compass_exit(void)
{
pr_info("AKM compass driver: release.");
i2c_del_driver(&akm_compass_driver);
}
module_init(akm_compass_init);
module_exit(akm_compass_exit);
#endif
MODULE_DESCRIPTION("AKM compass driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jevinskie/ps3-gcc | gcc/testsuite/c-c++-common/pr60101.c | 132 | 6670 | /* PR c/60101 */
/* { dg-do compile } */
/* { dg-options "-O2 -Wall" } */
extern int *a, b, *c, *d;
void
foo (double _Complex *x, double _Complex *y, double _Complex *z, unsigned int l, int w)
{
unsigned int e = (unsigned int) a[3];
double _Complex (*v)[l][4][e][l][4] = (double _Complex (*)[l][4][e][l][4]) z;
double _Complex (*f)[l][b][l] = (double _Complex (*)[l][b][l]) y;
unsigned int g = c[0] * c[1] * c[2];
unsigned int h = d[0] + c[0] * (d[1] + c[1] * d[2]);
unsigned int i;
for (i = 0; i < e; i++)
{
int j = e * d[3] + i;
unsigned int n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11;
float _Complex s = 0.;
unsigned int t = 0;
for (n0 = 0; n0 < l; n0++)
for (n1 = 0; n1 < l; n1++)
for (n2 = 0; n2 < l; n2++)
for (n3 = 0; n3 < l; n3++)
for (n4 = 0; n4 < l; n4++)
for (n5 = 0; n5 < l; n5++)
for (n6 = 0; n6 < l; n6++)
for (n7 = 0; n7 < l; n7++)
for (n8 = 0; n8 < l; n8++)
for (n9 = 0; n9 < l; n9++)
for (n10 = 0; n10 < l; n10++)
for (n11 = 0; n11 < l; n11++)
{
if (t % g == h)
s
+= f[n0][n4][j][n8] * f[n1][n5][j][n9] * ~(f[n2][n6][w][n10]) * ~(f[n3][n7][w][n11])
* (+0.25 * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n10][0][i][n4][1]
* v[0][n7][1][i][n8][0] * v[0][n11][1][i][n1][0] * v[0][n6][1][i][n0][0]
+ 0.25 * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n10][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n7][1][i][n0][0]
- 0.5 * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n10][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n6][1][i][n0][0]
+ 0.25 * v[0][n2][0][i][n9][1] * v[0][n10][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n7][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n11][1][i][n0][0]
- 0.5 * v[0][n2][0][i][n9][1] * v[0][n10][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n7][1][i][n0][0]
+ 0.25 * v[0][n2][0][i][n9][1] * v[0][n10][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n6][1][i][n0][0]
+ 0.25 * v[0][n3][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n10][0][i][n4][1]
* v[0][n6][1][i][n8][0] * v[0][n11][1][i][n1][0] * v[0][n7][1][i][n0][0]
- 0.5 * v[0][n3][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n10][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n7][1][i][n0][0]
+ 0.25 * v[0][n3][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n10][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n6][1][i][n0][0]
+ 0.25 * v[0][n3][0][i][n9][1] * v[0][n10][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n6][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n11][1][i][n0][0]
+ 0.25 * v[0][n3][0][i][n9][1] * v[0][n10][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n7][1][i][n0][0]
- 0.5 * v[0][n3][0][i][n9][1] * v[0][n10][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n6][1][i][n0][0]
+ 0.25 * v[0][n10][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n6][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n11][1][i][n0][0]
- 0.5 * v[0][n10][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n6][1][i][n8][0] * v[0][n11][1][i][n1][0] * v[0][n7][1][i][n0][0]
- 0.5 * v[0][n10][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n7][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n11][1][i][n0][0]
+ 0.25 * v[0][n10][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n7][1][i][n8][0] * v[0][n11][1][i][n1][0] * v[0][n6][1][i][n0][0]
+ 1. * v[0][n10][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n7][1][i][n0][0]
- 0.5 * v[0][n10][0][i][n9][1] * v[0][n2][0][i][n5][1] * v[0][n3][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n6][1][i][n0][0]
- 0.5 * v[0][n10][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n6][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n11][1][i][n0][0]
+ 0.25 * v[0][n10][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n6][1][i][n8][0] * v[0][n11][1][i][n1][0] * v[0][n7][1][i][n0][0]
+ 0.25 * v[0][n10][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n7][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n11][1][i][n0][0]
- 0.5 * v[0][n10][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n7][1][i][n8][0] * v[0][n11][1][i][n1][0] * v[0][n6][1][i][n0][0]
- 0.5 * v[0][n10][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n6][1][i][n1][0] * v[0][n7][1][i][n0][0]
+ 1. * v[0][n10][0][i][n9][1] * v[0][n3][0][i][n5][1] * v[0][n2][0][i][n4][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n6][1][i][n0][0]
+ 0.5 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1]
* v[0][n7][1][i][n1][0] * v[0][n11][1][i][n0][0] * v[0][n10][0][i][n8][0]
- 0.25 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1]
* v[0][n11][1][i][n1][0] * v[0][n7][1][i][n0][0] * v[0][n10][0][i][n8][0]
- 0.25 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1]
* v[0][n7][1][i][n8][0] * v[0][n11][1][i][n0][0] * v[0][n10][0][i][n1][0]
+ 0.25 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1]
* v[0][n7][1][i][n8][0] * v[0][n11][1][i][n1][0] * v[0][n10][0][i][n0][0]
+ 0.25 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n0][0] * v[0][n10][0][i][n1][0]
- 0.5 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n3][0][i][n5][1]
* v[0][n11][1][i][n8][0] * v[0][n7][1][i][n1][0] * v[0][n10][0][i][n0][0]
- 0.25 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n10][0][i][n5][1]
* v[0][n7][1][i][n1][0] * v[0][n11][1][i][n0][0] * v[0][n3][0][i][n8][0]
- 0.25 * v[0][n6][1][i][n4][1] * v[0][n2][0][i][n9][1] * v[0][n10][0][i][n5][1]
* v[0][n7][1][i][n8][0] * v[0][n11][1][i][n0][0] * v[0][n3][0][i][n1][0]);
t++;
}
int u = (j - w + b) % b;
int q = (j >= w ? +1 : -1);
int r = q;
x[u] += r * s;
}
}
| gpl-2.0 |
novaspirit/tf101-nv-linux | drivers/hwmon/pmbus/max8688.c | 388 | 5767 | /*
* Hardware monitoring driver for Maxim MAX8688
*
* Copyright (c) 2011 Ericsson AB.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include "pmbus.h"
#define MAX8688_MFR_VOUT_PEAK 0xd4
#define MAX8688_MFR_IOUT_PEAK 0xd5
#define MAX8688_MFR_TEMPERATURE_PEAK 0xd6
#define MAX8688_MFG_STATUS 0xd8
#define MAX8688_STATUS_OC_FAULT (1 << 4)
#define MAX8688_STATUS_OV_FAULT (1 << 5)
#define MAX8688_STATUS_OV_WARNING (1 << 8)
#define MAX8688_STATUS_UV_FAULT (1 << 9)
#define MAX8688_STATUS_UV_WARNING (1 << 10)
#define MAX8688_STATUS_UC_FAULT (1 << 11)
#define MAX8688_STATUS_OC_WARNING (1 << 12)
#define MAX8688_STATUS_OT_FAULT (1 << 13)
#define MAX8688_STATUS_OT_WARNING (1 << 14)
static int max8688_read_word_data(struct i2c_client *client, int page, int reg)
{
int ret;
if (page)
return -EINVAL;
switch (reg) {
case PMBUS_VIRT_READ_VOUT_MAX:
ret = pmbus_read_word_data(client, 0, MAX8688_MFR_VOUT_PEAK);
break;
case PMBUS_VIRT_READ_IOUT_MAX:
ret = pmbus_read_word_data(client, 0, MAX8688_MFR_IOUT_PEAK);
break;
case PMBUS_VIRT_READ_TEMP_MAX:
ret = pmbus_read_word_data(client, 0,
MAX8688_MFR_TEMPERATURE_PEAK);
break;
case PMBUS_VIRT_RESET_VOUT_HISTORY:
case PMBUS_VIRT_RESET_IOUT_HISTORY:
case PMBUS_VIRT_RESET_TEMP_HISTORY:
ret = 0;
break;
default:
ret = -ENODATA;
break;
}
return ret;
}
static int max8688_write_word_data(struct i2c_client *client, int page, int reg,
u16 word)
{
int ret;
switch (reg) {
case PMBUS_VIRT_RESET_VOUT_HISTORY:
ret = pmbus_write_word_data(client, 0, MAX8688_MFR_VOUT_PEAK,
0);
break;
case PMBUS_VIRT_RESET_IOUT_HISTORY:
ret = pmbus_write_word_data(client, 0, MAX8688_MFR_IOUT_PEAK,
0);
break;
case PMBUS_VIRT_RESET_TEMP_HISTORY:
ret = pmbus_write_word_data(client, 0,
MAX8688_MFR_TEMPERATURE_PEAK,
0xffff);
break;
default:
ret = -ENODATA;
break;
}
return ret;
}
static int max8688_read_byte_data(struct i2c_client *client, int page, int reg)
{
int ret = 0;
int mfg_status;
if (page)
return -EINVAL;
switch (reg) {
case PMBUS_STATUS_VOUT:
mfg_status = pmbus_read_word_data(client, 0,
MAX8688_MFG_STATUS);
if (mfg_status < 0)
return mfg_status;
if (mfg_status & MAX8688_STATUS_UV_WARNING)
ret |= PB_VOLTAGE_UV_WARNING;
if (mfg_status & MAX8688_STATUS_UV_FAULT)
ret |= PB_VOLTAGE_UV_FAULT;
if (mfg_status & MAX8688_STATUS_OV_WARNING)
ret |= PB_VOLTAGE_OV_WARNING;
if (mfg_status & MAX8688_STATUS_OV_FAULT)
ret |= PB_VOLTAGE_OV_FAULT;
break;
case PMBUS_STATUS_IOUT:
mfg_status = pmbus_read_word_data(client, 0,
MAX8688_MFG_STATUS);
if (mfg_status < 0)
return mfg_status;
if (mfg_status & MAX8688_STATUS_UC_FAULT)
ret |= PB_IOUT_UC_FAULT;
if (mfg_status & MAX8688_STATUS_OC_WARNING)
ret |= PB_IOUT_OC_WARNING;
if (mfg_status & MAX8688_STATUS_OC_FAULT)
ret |= PB_IOUT_OC_FAULT;
break;
case PMBUS_STATUS_TEMPERATURE:
mfg_status = pmbus_read_word_data(client, 0,
MAX8688_MFG_STATUS);
if (mfg_status < 0)
return mfg_status;
if (mfg_status & MAX8688_STATUS_OT_WARNING)
ret |= PB_TEMP_OT_WARNING;
if (mfg_status & MAX8688_STATUS_OT_FAULT)
ret |= PB_TEMP_OT_FAULT;
break;
default:
ret = -ENODATA;
break;
}
return ret;
}
static struct pmbus_driver_info max8688_info = {
.pages = 1,
.format[PSC_VOLTAGE_IN] = direct,
.format[PSC_VOLTAGE_OUT] = direct,
.format[PSC_TEMPERATURE] = direct,
.format[PSC_CURRENT_OUT] = direct,
.m[PSC_VOLTAGE_IN] = 19995,
.b[PSC_VOLTAGE_IN] = 0,
.R[PSC_VOLTAGE_IN] = -1,
.m[PSC_VOLTAGE_OUT] = 19995,
.b[PSC_VOLTAGE_OUT] = 0,
.R[PSC_VOLTAGE_OUT] = -1,
.m[PSC_CURRENT_OUT] = 23109,
.b[PSC_CURRENT_OUT] = 0,
.R[PSC_CURRENT_OUT] = -2,
.m[PSC_TEMPERATURE] = -7612,
.b[PSC_TEMPERATURE] = 335,
.R[PSC_TEMPERATURE] = -3,
.func[0] = PMBUS_HAVE_VOUT | PMBUS_HAVE_IOUT | PMBUS_HAVE_TEMP
| PMBUS_HAVE_STATUS_VOUT | PMBUS_HAVE_STATUS_IOUT
| PMBUS_HAVE_STATUS_TEMP,
.read_byte_data = max8688_read_byte_data,
.read_word_data = max8688_read_word_data,
.write_word_data = max8688_write_word_data,
};
static int max8688_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
return pmbus_do_probe(client, id, &max8688_info);
}
static int max8688_remove(struct i2c_client *client)
{
return pmbus_do_remove(client);
}
static const struct i2c_device_id max8688_id[] = {
{"max8688", 0},
{ }
};
MODULE_DEVICE_TABLE(i2c, max8688_id);
/* This is the driver that will be inserted */
static struct i2c_driver max8688_driver = {
.driver = {
.name = "max8688",
},
.probe = max8688_probe,
.remove = max8688_remove,
.id_table = max8688_id,
};
static int __init max8688_init(void)
{
return i2c_add_driver(&max8688_driver);
}
static void __exit max8688_exit(void)
{
i2c_del_driver(&max8688_driver);
}
MODULE_AUTHOR("Guenter Roeck");
MODULE_DESCRIPTION("PMBus driver for Maxim MAX8688");
MODULE_LICENSE("GPL");
module_init(max8688_init);
module_exit(max8688_exit);
| gpl-2.0 |
Pesach85/ph85-p880-kernel-project | drivers/net/arm/ks8695net.c | 388 | 43603 | /*
* Micrel KS8695 (Centaur) Ethernet.
*
* 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.
*
* Copyright 2008 Simtec Electronics
* Daniel Silverstone <dsilvers@simtec.co.uk>
* Vincent Sanders <vince@simtec.co.uk>
*/
#include <linux/dma-mapping.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/crc32.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <asm/irq.h>
#include <mach/regs-switch.h>
#include <mach/regs-misc.h>
#include <asm/mach/irq.h>
#include <mach/regs-irq.h>
#include "ks8695net.h"
#define MODULENAME "ks8695_ether"
#define MODULEVERSION "1.02"
/*
* Transmit and device reset timeout, default 5 seconds.
*/
static int watchdog = 5000;
/* Hardware structures */
/**
* struct rx_ring_desc - Receive descriptor ring element
* @status: The status of the descriptor element (E.g. who owns it)
* @length: The number of bytes in the block pointed to by data_ptr
* @data_ptr: The physical address of the data block to receive into
* @next_desc: The physical address of the next descriptor element.
*/
struct rx_ring_desc {
__le32 status;
__le32 length;
__le32 data_ptr;
__le32 next_desc;
};
/**
* struct tx_ring_desc - Transmit descriptor ring element
* @owner: Who owns the descriptor
* @status: The number of bytes in the block pointed to by data_ptr
* @data_ptr: The physical address of the data block to receive into
* @next_desc: The physical address of the next descriptor element.
*/
struct tx_ring_desc {
__le32 owner;
__le32 status;
__le32 data_ptr;
__le32 next_desc;
};
/**
* struct ks8695_skbuff - sk_buff wrapper for rx/tx rings.
* @skb: The buffer in the ring
* @dma_ptr: The mapped DMA pointer of the buffer
* @length: The number of bytes mapped to dma_ptr
*/
struct ks8695_skbuff {
struct sk_buff *skb;
dma_addr_t dma_ptr;
u32 length;
};
/* Private device structure */
#define MAX_TX_DESC 8
#define MAX_TX_DESC_MASK 0x7
#define MAX_RX_DESC 16
#define MAX_RX_DESC_MASK 0xf
/*napi_weight have better more than rx DMA buffers*/
#define NAPI_WEIGHT 64
#define MAX_RXBUF_SIZE 0x700
#define TX_RING_DMA_SIZE (sizeof(struct tx_ring_desc) * MAX_TX_DESC)
#define RX_RING_DMA_SIZE (sizeof(struct rx_ring_desc) * MAX_RX_DESC)
#define RING_DMA_SIZE (TX_RING_DMA_SIZE + RX_RING_DMA_SIZE)
/**
* enum ks8695_dtype - Device type
* @KS8695_DTYPE_WAN: This device is a WAN interface
* @KS8695_DTYPE_LAN: This device is a LAN interface
* @KS8695_DTYPE_HPNA: This device is an HPNA interface
*/
enum ks8695_dtype {
KS8695_DTYPE_WAN,
KS8695_DTYPE_LAN,
KS8695_DTYPE_HPNA,
};
/**
* struct ks8695_priv - Private data for the KS8695 Ethernet
* @in_suspend: Flag to indicate if we're suspending/resuming
* @ndev: The net_device for this interface
* @dev: The platform device object for this interface
* @dtype: The type of this device
* @io_regs: The ioremapped registers for this interface
* @napi : Add support NAPI for Rx
* @rx_irq_name: The textual name of the RX IRQ from the platform data
* @tx_irq_name: The textual name of the TX IRQ from the platform data
* @link_irq_name: The textual name of the link IRQ from the
* platform data if available
* @rx_irq: The IRQ number for the RX IRQ
* @tx_irq: The IRQ number for the TX IRQ
* @link_irq: The IRQ number for the link IRQ if available
* @regs_req: The resource request for the registers region
* @phyiface_req: The resource request for the phy/switch region
* if available
* @phyiface_regs: The ioremapped registers for the phy/switch if available
* @ring_base: The base pointer of the dma coherent memory for the rings
* @ring_base_dma: The DMA mapped equivalent of ring_base
* @tx_ring: The pointer in ring_base of the TX ring
* @tx_ring_used: The number of slots in the TX ring which are occupied
* @tx_ring_next_slot: The next slot to fill in the TX ring
* @tx_ring_dma: The DMA mapped equivalent of tx_ring
* @tx_buffers: The sk_buff mappings for the TX ring
* @txq_lock: A lock to protect the tx_buffers tx_ring_used etc variables
* @rx_ring: The pointer in ring_base of the RX ring
* @rx_ring_dma: The DMA mapped equivalent of rx_ring
* @rx_buffers: The sk_buff mappings for the RX ring
* @next_rx_desc_read: The next RX descriptor to read from on IRQ
* @rx_lock: A lock to protect Rx irq function
* @msg_enable: The flags for which messages to emit
*/
struct ks8695_priv {
int in_suspend;
struct net_device *ndev;
struct device *dev;
enum ks8695_dtype dtype;
void __iomem *io_regs;
struct napi_struct napi;
const char *rx_irq_name, *tx_irq_name, *link_irq_name;
int rx_irq, tx_irq, link_irq;
struct resource *regs_req, *phyiface_req;
void __iomem *phyiface_regs;
void *ring_base;
dma_addr_t ring_base_dma;
struct tx_ring_desc *tx_ring;
int tx_ring_used;
int tx_ring_next_slot;
dma_addr_t tx_ring_dma;
struct ks8695_skbuff tx_buffers[MAX_TX_DESC];
spinlock_t txq_lock;
struct rx_ring_desc *rx_ring;
dma_addr_t rx_ring_dma;
struct ks8695_skbuff rx_buffers[MAX_RX_DESC];
int next_rx_desc_read;
spinlock_t rx_lock;
int msg_enable;
};
/* Register access */
/**
* ks8695_readreg - Read from a KS8695 ethernet register
* @ksp: The device to read from
* @reg: The register to read
*/
static inline u32
ks8695_readreg(struct ks8695_priv *ksp, int reg)
{
return readl(ksp->io_regs + reg);
}
/**
* ks8695_writereg - Write to a KS8695 ethernet register
* @ksp: The device to write to
* @reg: The register to write
* @value: The value to write to the register
*/
static inline void
ks8695_writereg(struct ks8695_priv *ksp, int reg, u32 value)
{
writel(value, ksp->io_regs + reg);
}
/* Utility functions */
/**
* ks8695_port_type - Retrieve port-type as user-friendly string
* @ksp: The device to return the type for
*
* Returns a string indicating which of the WAN, LAN or HPNA
* ports this device is likely to represent.
*/
static const char *
ks8695_port_type(struct ks8695_priv *ksp)
{
switch (ksp->dtype) {
case KS8695_DTYPE_LAN:
return "LAN";
case KS8695_DTYPE_WAN:
return "WAN";
case KS8695_DTYPE_HPNA:
return "HPNA";
}
return "UNKNOWN";
}
/**
* ks8695_update_mac - Update the MAC registers in the device
* @ksp: The device to update
*
* Updates the MAC registers in the KS8695 device from the address in the
* net_device structure associated with this interface.
*/
static void
ks8695_update_mac(struct ks8695_priv *ksp)
{
/* Update the HW with the MAC from the net_device */
struct net_device *ndev = ksp->ndev;
u32 machigh, maclow;
maclow = ((ndev->dev_addr[2] << 24) | (ndev->dev_addr[3] << 16) |
(ndev->dev_addr[4] << 8) | (ndev->dev_addr[5] << 0));
machigh = ((ndev->dev_addr[0] << 8) | (ndev->dev_addr[1] << 0));
ks8695_writereg(ksp, KS8695_MAL, maclow);
ks8695_writereg(ksp, KS8695_MAH, machigh);
}
/**
* ks8695_refill_rxbuffers - Re-fill the RX buffer ring
* @ksp: The device to refill
*
* Iterates the RX ring of the device looking for empty slots.
* For each empty slot, we allocate and map a new SKB and give it
* to the hardware.
* This can be called from interrupt context safely.
*/
static void
ks8695_refill_rxbuffers(struct ks8695_priv *ksp)
{
/* Run around the RX ring, filling in any missing sk_buff's */
int buff_n;
for (buff_n = 0; buff_n < MAX_RX_DESC; ++buff_n) {
if (!ksp->rx_buffers[buff_n].skb) {
struct sk_buff *skb = dev_alloc_skb(MAX_RXBUF_SIZE);
dma_addr_t mapping;
ksp->rx_buffers[buff_n].skb = skb;
if (skb == NULL) {
/* Failed to allocate one, perhaps
* we'll try again later.
*/
break;
}
mapping = dma_map_single(ksp->dev, skb->data,
MAX_RXBUF_SIZE,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(ksp->dev, mapping))) {
/* Failed to DMA map this SKB, try later */
dev_kfree_skb_irq(skb);
ksp->rx_buffers[buff_n].skb = NULL;
break;
}
ksp->rx_buffers[buff_n].dma_ptr = mapping;
skb->dev = ksp->ndev;
ksp->rx_buffers[buff_n].length = MAX_RXBUF_SIZE;
/* Record this into the DMA ring */
ksp->rx_ring[buff_n].data_ptr = cpu_to_le32(mapping);
ksp->rx_ring[buff_n].length =
cpu_to_le32(MAX_RXBUF_SIZE);
wmb();
/* And give ownership over to the hardware */
ksp->rx_ring[buff_n].status = cpu_to_le32(RDES_OWN);
}
}
}
/* Maximum number of multicast addresses which the KS8695 HW supports */
#define KS8695_NR_ADDRESSES 16
/**
* ks8695_init_partial_multicast - Init the mcast addr registers
* @ksp: The device to initialise
* @addr: The multicast address list to use
* @nr_addr: The number of addresses in the list
*
* This routine is a helper for ks8695_set_multicast - it writes
* the additional-address registers in the KS8695 ethernet device
* and cleans up any others left behind.
*/
static void
ks8695_init_partial_multicast(struct ks8695_priv *ksp,
struct net_device *ndev)
{
u32 low, high;
int i;
struct netdev_hw_addr *ha;
i = 0;
netdev_for_each_mc_addr(ha, ndev) {
/* Ran out of space in chip? */
BUG_ON(i == KS8695_NR_ADDRESSES);
low = (ha->addr[2] << 24) | (ha->addr[3] << 16) |
(ha->addr[4] << 8) | (ha->addr[5]);
high = (ha->addr[0] << 8) | (ha->addr[1]);
ks8695_writereg(ksp, KS8695_AAL_(i), low);
ks8695_writereg(ksp, KS8695_AAH_(i), AAH_E | high);
i++;
}
/* Clear the remaining Additional Station Addresses */
for (; i < KS8695_NR_ADDRESSES; i++) {
ks8695_writereg(ksp, KS8695_AAL_(i), 0);
ks8695_writereg(ksp, KS8695_AAH_(i), 0);
}
}
/* Interrupt handling */
/**
* ks8695_tx_irq - Transmit IRQ handler
* @irq: The IRQ which went off (ignored)
* @dev_id: The net_device for the interrupt
*
* Process the TX ring, clearing out any transmitted slots.
* Allows the net_device to pass us new packets once slots are
* freed.
*/
static irqreturn_t
ks8695_tx_irq(int irq, void *dev_id)
{
struct net_device *ndev = (struct net_device *)dev_id;
struct ks8695_priv *ksp = netdev_priv(ndev);
int buff_n;
for (buff_n = 0; buff_n < MAX_TX_DESC; ++buff_n) {
if (ksp->tx_buffers[buff_n].skb &&
!(ksp->tx_ring[buff_n].owner & cpu_to_le32(TDES_OWN))) {
rmb();
/* An SKB which is not owned by HW is present */
/* Update the stats for the net_device */
ndev->stats.tx_packets++;
ndev->stats.tx_bytes += ksp->tx_buffers[buff_n].length;
/* Free the packet from the ring */
ksp->tx_ring[buff_n].data_ptr = 0;
/* Free the sk_buff */
dma_unmap_single(ksp->dev,
ksp->tx_buffers[buff_n].dma_ptr,
ksp->tx_buffers[buff_n].length,
DMA_TO_DEVICE);
dev_kfree_skb_irq(ksp->tx_buffers[buff_n].skb);
ksp->tx_buffers[buff_n].skb = NULL;
ksp->tx_ring_used--;
}
}
netif_wake_queue(ndev);
return IRQ_HANDLED;
}
/**
* ks8695_get_rx_enable_bit - Get rx interrupt enable/status bit
* @ksp: Private data for the KS8695 Ethernet
*
* For KS8695 document:
* Interrupt Enable Register (offset 0xE204)
* Bit29 : WAN MAC Receive Interrupt Enable
* Bit16 : LAN MAC Receive Interrupt Enable
* Interrupt Status Register (Offset 0xF208)
* Bit29: WAN MAC Receive Status
* Bit16: LAN MAC Receive Status
* So, this Rx interrrupt enable/status bit number is equal
* as Rx IRQ number.
*/
static inline u32 ks8695_get_rx_enable_bit(struct ks8695_priv *ksp)
{
return ksp->rx_irq;
}
/**
* ks8695_rx_irq - Receive IRQ handler
* @irq: The IRQ which went off (ignored)
* @dev_id: The net_device for the interrupt
*
* Inform NAPI that packet reception needs to be scheduled
*/
static irqreturn_t
ks8695_rx_irq(int irq, void *dev_id)
{
struct net_device *ndev = (struct net_device *)dev_id;
struct ks8695_priv *ksp = netdev_priv(ndev);
spin_lock(&ksp->rx_lock);
if (napi_schedule_prep(&ksp->napi)) {
unsigned long status = readl(KS8695_IRQ_VA + KS8695_INTEN);
unsigned long mask_bit = 1 << ks8695_get_rx_enable_bit(ksp);
/*disable rx interrupt*/
status &= ~mask_bit;
writel(status , KS8695_IRQ_VA + KS8695_INTEN);
__napi_schedule(&ksp->napi);
}
spin_unlock(&ksp->rx_lock);
return IRQ_HANDLED;
}
/**
* ks8695_rx - Receive packets called by NAPI poll method
* @ksp: Private data for the KS8695 Ethernet
* @budget: Number of packets allowed to process
*/
static int ks8695_rx(struct ks8695_priv *ksp, int budget)
{
struct net_device *ndev = ksp->ndev;
struct sk_buff *skb;
int buff_n;
u32 flags;
int pktlen;
int received = 0;
buff_n = ksp->next_rx_desc_read;
while (received < budget
&& ksp->rx_buffers[buff_n].skb
&& (!(ksp->rx_ring[buff_n].status &
cpu_to_le32(RDES_OWN)))) {
rmb();
flags = le32_to_cpu(ksp->rx_ring[buff_n].status);
/* Found an SKB which we own, this means we
* received a packet
*/
if ((flags & (RDES_FS | RDES_LS)) !=
(RDES_FS | RDES_LS)) {
/* This packet is not the first and
* the last segment. Therefore it is
* a "spanning" packet and we can't
* handle it
*/
goto rx_failure;
}
if (flags & (RDES_ES | RDES_RE)) {
/* It's an error packet */
ndev->stats.rx_errors++;
if (flags & RDES_TL)
ndev->stats.rx_length_errors++;
if (flags & RDES_RF)
ndev->stats.rx_length_errors++;
if (flags & RDES_CE)
ndev->stats.rx_crc_errors++;
if (flags & RDES_RE)
ndev->stats.rx_missed_errors++;
goto rx_failure;
}
pktlen = flags & RDES_FLEN;
pktlen -= 4; /* Drop the CRC */
/* Retrieve the sk_buff */
skb = ksp->rx_buffers[buff_n].skb;
/* Clear it from the ring */
ksp->rx_buffers[buff_n].skb = NULL;
ksp->rx_ring[buff_n].data_ptr = 0;
/* Unmap the SKB */
dma_unmap_single(ksp->dev,
ksp->rx_buffers[buff_n].dma_ptr,
ksp->rx_buffers[buff_n].length,
DMA_FROM_DEVICE);
/* Relinquish the SKB to the network layer */
skb_put(skb, pktlen);
skb->protocol = eth_type_trans(skb, ndev);
netif_receive_skb(skb);
/* Record stats */
ndev->stats.rx_packets++;
ndev->stats.rx_bytes += pktlen;
goto rx_finished;
rx_failure:
/* This ring entry is an error, but we can
* re-use the skb
*/
/* Give the ring entry back to the hardware */
ksp->rx_ring[buff_n].status = cpu_to_le32(RDES_OWN);
rx_finished:
received++;
buff_n = (buff_n + 1) & MAX_RX_DESC_MASK;
}
/* And note which RX descriptor we last did */
ksp->next_rx_desc_read = buff_n;
/* And refill the buffers */
ks8695_refill_rxbuffers(ksp);
/* Kick the RX DMA engine, in case it became suspended */
ks8695_writereg(ksp, KS8695_DRSC, 0);
return received;
}
/**
* ks8695_poll - Receive packet by NAPI poll method
* @ksp: Private data for the KS8695 Ethernet
* @budget: The remaining number packets for network subsystem
*
* Invoked by the network core when it requests for new
* packets from the driver
*/
static int ks8695_poll(struct napi_struct *napi, int budget)
{
struct ks8695_priv *ksp = container_of(napi, struct ks8695_priv, napi);
unsigned long work_done;
unsigned long isr = readl(KS8695_IRQ_VA + KS8695_INTEN);
unsigned long mask_bit = 1 << ks8695_get_rx_enable_bit(ksp);
work_done = ks8695_rx(ksp, budget);
if (work_done < budget) {
unsigned long flags;
spin_lock_irqsave(&ksp->rx_lock, flags);
__napi_complete(napi);
/*enable rx interrupt*/
writel(isr | mask_bit, KS8695_IRQ_VA + KS8695_INTEN);
spin_unlock_irqrestore(&ksp->rx_lock, flags);
}
return work_done;
}
/**
* ks8695_link_irq - Link change IRQ handler
* @irq: The IRQ which went off (ignored)
* @dev_id: The net_device for the interrupt
*
* The WAN interface can generate an IRQ when the link changes,
* report this to the net layer and the user.
*/
static irqreturn_t
ks8695_link_irq(int irq, void *dev_id)
{
struct net_device *ndev = (struct net_device *)dev_id;
struct ks8695_priv *ksp = netdev_priv(ndev);
u32 ctrl;
ctrl = readl(ksp->phyiface_regs + KS8695_WMC);
if (ctrl & WMC_WLS) {
netif_carrier_on(ndev);
if (netif_msg_link(ksp))
dev_info(ksp->dev,
"%s: Link is now up (10%sMbps/%s-duplex)\n",
ndev->name,
(ctrl & WMC_WSS) ? "0" : "",
(ctrl & WMC_WDS) ? "Full" : "Half");
} else {
netif_carrier_off(ndev);
if (netif_msg_link(ksp))
dev_info(ksp->dev, "%s: Link is now down.\n",
ndev->name);
}
return IRQ_HANDLED;
}
/* KS8695 Device functions */
/**
* ks8695_reset - Reset a KS8695 ethernet interface
* @ksp: The interface to reset
*
* Perform an engine reset of the interface and re-program it
* with sensible defaults.
*/
static void
ks8695_reset(struct ks8695_priv *ksp)
{
int reset_timeout = watchdog;
/* Issue the reset via the TX DMA control register */
ks8695_writereg(ksp, KS8695_DTXC, DTXC_TRST);
while (reset_timeout--) {
if (!(ks8695_readreg(ksp, KS8695_DTXC) & DTXC_TRST))
break;
msleep(1);
}
if (reset_timeout < 0) {
dev_crit(ksp->dev,
"Timeout waiting for DMA engines to reset\n");
/* And blithely carry on */
}
/* Definitely wait long enough before attempting to program
* the engines
*/
msleep(10);
/* RX: unicast and broadcast */
ks8695_writereg(ksp, KS8695_DRXC, DRXC_RU | DRXC_RB);
/* TX: pad and add CRC */
ks8695_writereg(ksp, KS8695_DTXC, DTXC_TEP | DTXC_TAC);
}
/**
* ks8695_shutdown - Shut down a KS8695 ethernet interface
* @ksp: The interface to shut down
*
* This disables packet RX/TX, cleans up IRQs, drains the rings,
* and basically places the interface into a clean shutdown
* state.
*/
static void
ks8695_shutdown(struct ks8695_priv *ksp)
{
u32 ctrl;
int buff_n;
/* Disable packet transmission */
ctrl = ks8695_readreg(ksp, KS8695_DTXC);
ks8695_writereg(ksp, KS8695_DTXC, ctrl & ~DTXC_TE);
/* Disable packet reception */
ctrl = ks8695_readreg(ksp, KS8695_DRXC);
ks8695_writereg(ksp, KS8695_DRXC, ctrl & ~DRXC_RE);
/* Release the IRQs */
free_irq(ksp->rx_irq, ksp->ndev);
free_irq(ksp->tx_irq, ksp->ndev);
if (ksp->link_irq != -1)
free_irq(ksp->link_irq, ksp->ndev);
/* Throw away any pending TX packets */
for (buff_n = 0; buff_n < MAX_TX_DESC; ++buff_n) {
if (ksp->tx_buffers[buff_n].skb) {
/* Remove this SKB from the TX ring */
ksp->tx_ring[buff_n].owner = 0;
ksp->tx_ring[buff_n].status = 0;
ksp->tx_ring[buff_n].data_ptr = 0;
/* Unmap and bin this SKB */
dma_unmap_single(ksp->dev,
ksp->tx_buffers[buff_n].dma_ptr,
ksp->tx_buffers[buff_n].length,
DMA_TO_DEVICE);
dev_kfree_skb_irq(ksp->tx_buffers[buff_n].skb);
ksp->tx_buffers[buff_n].skb = NULL;
}
}
/* Purge the RX buffers */
for (buff_n = 0; buff_n < MAX_RX_DESC; ++buff_n) {
if (ksp->rx_buffers[buff_n].skb) {
/* Remove the SKB from the RX ring */
ksp->rx_ring[buff_n].status = 0;
ksp->rx_ring[buff_n].data_ptr = 0;
/* Unmap and bin the SKB */
dma_unmap_single(ksp->dev,
ksp->rx_buffers[buff_n].dma_ptr,
ksp->rx_buffers[buff_n].length,
DMA_FROM_DEVICE);
dev_kfree_skb_irq(ksp->rx_buffers[buff_n].skb);
ksp->rx_buffers[buff_n].skb = NULL;
}
}
}
/**
* ks8695_setup_irq - IRQ setup helper function
* @irq: The IRQ number to claim
* @irq_name: The name to give the IRQ claimant
* @handler: The function to call to handle the IRQ
* @ndev: The net_device to pass in as the dev_id argument to the handler
*
* Return 0 on success.
*/
static int
ks8695_setup_irq(int irq, const char *irq_name,
irq_handler_t handler, struct net_device *ndev)
{
int ret;
ret = request_irq(irq, handler, IRQF_SHARED, irq_name, ndev);
if (ret) {
dev_err(&ndev->dev, "failure to request IRQ %d\n", irq);
return ret;
}
return 0;
}
/**
* ks8695_init_net - Initialise a KS8695 ethernet interface
* @ksp: The interface to initialise
*
* This routine fills the RX ring, initialises the DMA engines,
* allocates the IRQs and then starts the packet TX and RX
* engines.
*/
static int
ks8695_init_net(struct ks8695_priv *ksp)
{
int ret;
u32 ctrl;
ks8695_refill_rxbuffers(ksp);
/* Initialise the DMA engines */
ks8695_writereg(ksp, KS8695_RDLB, (u32) ksp->rx_ring_dma);
ks8695_writereg(ksp, KS8695_TDLB, (u32) ksp->tx_ring_dma);
/* Request the IRQs */
ret = ks8695_setup_irq(ksp->rx_irq, ksp->rx_irq_name,
ks8695_rx_irq, ksp->ndev);
if (ret)
return ret;
ret = ks8695_setup_irq(ksp->tx_irq, ksp->tx_irq_name,
ks8695_tx_irq, ksp->ndev);
if (ret)
return ret;
if (ksp->link_irq != -1) {
ret = ks8695_setup_irq(ksp->link_irq, ksp->link_irq_name,
ks8695_link_irq, ksp->ndev);
if (ret)
return ret;
}
/* Set up the ring indices */
ksp->next_rx_desc_read = 0;
ksp->tx_ring_next_slot = 0;
ksp->tx_ring_used = 0;
/* Bring up transmission */
ctrl = ks8695_readreg(ksp, KS8695_DTXC);
/* Enable packet transmission */
ks8695_writereg(ksp, KS8695_DTXC, ctrl | DTXC_TE);
/* Bring up the reception */
ctrl = ks8695_readreg(ksp, KS8695_DRXC);
/* Enable packet reception */
ks8695_writereg(ksp, KS8695_DRXC, ctrl | DRXC_RE);
/* And start the DMA engine */
ks8695_writereg(ksp, KS8695_DRSC, 0);
/* All done */
return 0;
}
/**
* ks8695_release_device - HW resource release for KS8695 e-net
* @ksp: The device to be freed
*
* This unallocates io memory regions, dma-coherent regions etc
* which were allocated in ks8695_probe.
*/
static void
ks8695_release_device(struct ks8695_priv *ksp)
{
/* Unmap the registers */
iounmap(ksp->io_regs);
if (ksp->phyiface_regs)
iounmap(ksp->phyiface_regs);
/* And release the request */
release_resource(ksp->regs_req);
kfree(ksp->regs_req);
if (ksp->phyiface_req) {
release_resource(ksp->phyiface_req);
kfree(ksp->phyiface_req);
}
/* Free the ring buffers */
dma_free_coherent(ksp->dev, RING_DMA_SIZE,
ksp->ring_base, ksp->ring_base_dma);
}
/* Ethtool support */
/**
* ks8695_get_msglevel - Get the messages enabled for emission
* @ndev: The network device to read from
*/
static u32
ks8695_get_msglevel(struct net_device *ndev)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
return ksp->msg_enable;
}
/**
* ks8695_set_msglevel - Set the messages enabled for emission
* @ndev: The network device to configure
* @value: The messages to set for emission
*/
static void
ks8695_set_msglevel(struct net_device *ndev, u32 value)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
ksp->msg_enable = value;
}
/**
* ks8695_wan_get_settings - Get device-specific settings.
* @ndev: The network device to read settings from
* @cmd: The ethtool structure to read into
*/
static int
ks8695_wan_get_settings(struct net_device *ndev, struct ethtool_cmd *cmd)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
u32 ctrl;
/* All ports on the KS8695 support these... */
cmd->supported = (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
SUPPORTED_TP | SUPPORTED_MII);
cmd->transceiver = XCVR_INTERNAL;
cmd->advertising = ADVERTISED_TP | ADVERTISED_MII;
cmd->port = PORT_MII;
cmd->supported |= (SUPPORTED_Autoneg | SUPPORTED_Pause);
cmd->phy_address = 0;
ctrl = readl(ksp->phyiface_regs + KS8695_WMC);
if ((ctrl & WMC_WAND) == 0) {
/* auto-negotiation is enabled */
cmd->advertising |= ADVERTISED_Autoneg;
if (ctrl & WMC_WANA100F)
cmd->advertising |= ADVERTISED_100baseT_Full;
if (ctrl & WMC_WANA100H)
cmd->advertising |= ADVERTISED_100baseT_Half;
if (ctrl & WMC_WANA10F)
cmd->advertising |= ADVERTISED_10baseT_Full;
if (ctrl & WMC_WANA10H)
cmd->advertising |= ADVERTISED_10baseT_Half;
if (ctrl & WMC_WANAP)
cmd->advertising |= ADVERTISED_Pause;
cmd->autoneg = AUTONEG_ENABLE;
ethtool_cmd_speed_set(cmd,
(ctrl & WMC_WSS) ? SPEED_100 : SPEED_10);
cmd->duplex = (ctrl & WMC_WDS) ?
DUPLEX_FULL : DUPLEX_HALF;
} else {
/* auto-negotiation is disabled */
cmd->autoneg = AUTONEG_DISABLE;
ethtool_cmd_speed_set(cmd, ((ctrl & WMC_WANF100) ?
SPEED_100 : SPEED_10));
cmd->duplex = (ctrl & WMC_WANFF) ?
DUPLEX_FULL : DUPLEX_HALF;
}
return 0;
}
/**
* ks8695_wan_set_settings - Set device-specific settings.
* @ndev: The network device to configure
* @cmd: The settings to configure
*/
static int
ks8695_wan_set_settings(struct net_device *ndev, struct ethtool_cmd *cmd)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
u32 ctrl;
if ((cmd->speed != SPEED_10) && (cmd->speed != SPEED_100))
return -EINVAL;
if ((cmd->duplex != DUPLEX_HALF) && (cmd->duplex != DUPLEX_FULL))
return -EINVAL;
if (cmd->port != PORT_MII)
return -EINVAL;
if (cmd->transceiver != XCVR_INTERNAL)
return -EINVAL;
if ((cmd->autoneg != AUTONEG_DISABLE) &&
(cmd->autoneg != AUTONEG_ENABLE))
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE) {
if ((cmd->advertising & (ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full)) == 0)
return -EINVAL;
ctrl = readl(ksp->phyiface_regs + KS8695_WMC);
ctrl &= ~(WMC_WAND | WMC_WANA100F | WMC_WANA100H |
WMC_WANA10F | WMC_WANA10H);
if (cmd->advertising & ADVERTISED_100baseT_Full)
ctrl |= WMC_WANA100F;
if (cmd->advertising & ADVERTISED_100baseT_Half)
ctrl |= WMC_WANA100H;
if (cmd->advertising & ADVERTISED_10baseT_Full)
ctrl |= WMC_WANA10F;
if (cmd->advertising & ADVERTISED_10baseT_Half)
ctrl |= WMC_WANA10H;
/* force a re-negotiation */
ctrl |= WMC_WANR;
writel(ctrl, ksp->phyiface_regs + KS8695_WMC);
} else {
ctrl = readl(ksp->phyiface_regs + KS8695_WMC);
/* disable auto-negotiation */
ctrl |= WMC_WAND;
ctrl &= ~(WMC_WANF100 | WMC_WANFF);
if (cmd->speed == SPEED_100)
ctrl |= WMC_WANF100;
if (cmd->duplex == DUPLEX_FULL)
ctrl |= WMC_WANFF;
writel(ctrl, ksp->phyiface_regs + KS8695_WMC);
}
return 0;
}
/**
* ks8695_wan_nwayreset - Restart the autonegotiation on the port.
* @ndev: The network device to restart autoneotiation on
*/
static int
ks8695_wan_nwayreset(struct net_device *ndev)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
u32 ctrl;
ctrl = readl(ksp->phyiface_regs + KS8695_WMC);
if ((ctrl & WMC_WAND) == 0)
writel(ctrl | WMC_WANR,
ksp->phyiface_regs + KS8695_WMC);
else
/* auto-negotiation not enabled */
return -EINVAL;
return 0;
}
/**
* ks8695_wan_get_pause - Retrieve network pause/flow-control advertising
* @ndev: The device to retrieve settings from
* @param: The structure to fill out with the information
*/
static void
ks8695_wan_get_pause(struct net_device *ndev, struct ethtool_pauseparam *param)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
u32 ctrl;
ctrl = readl(ksp->phyiface_regs + KS8695_WMC);
/* advertise Pause */
param->autoneg = (ctrl & WMC_WANAP);
/* current Rx Flow-control */
ctrl = ks8695_readreg(ksp, KS8695_DRXC);
param->rx_pause = (ctrl & DRXC_RFCE);
/* current Tx Flow-control */
ctrl = ks8695_readreg(ksp, KS8695_DTXC);
param->tx_pause = (ctrl & DTXC_TFCE);
}
/**
* ks8695_get_drvinfo - Retrieve driver information
* @ndev: The network device to retrieve info about
* @info: The info structure to fill out.
*/
static void
ks8695_get_drvinfo(struct net_device *ndev, struct ethtool_drvinfo *info)
{
strlcpy(info->driver, MODULENAME, sizeof(info->driver));
strlcpy(info->version, MODULEVERSION, sizeof(info->version));
strlcpy(info->bus_info, dev_name(ndev->dev.parent),
sizeof(info->bus_info));
}
static const struct ethtool_ops ks8695_ethtool_ops = {
.get_msglevel = ks8695_get_msglevel,
.set_msglevel = ks8695_set_msglevel,
.get_drvinfo = ks8695_get_drvinfo,
};
static const struct ethtool_ops ks8695_wan_ethtool_ops = {
.get_msglevel = ks8695_get_msglevel,
.set_msglevel = ks8695_set_msglevel,
.get_settings = ks8695_wan_get_settings,
.set_settings = ks8695_wan_set_settings,
.nway_reset = ks8695_wan_nwayreset,
.get_link = ethtool_op_get_link,
.get_pauseparam = ks8695_wan_get_pause,
.get_drvinfo = ks8695_get_drvinfo,
};
/* Network device interface functions */
/**
* ks8695_set_mac - Update MAC in net dev and HW
* @ndev: The network device to update
* @addr: The new MAC address to set
*/
static int
ks8695_set_mac(struct net_device *ndev, void *addr)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
struct sockaddr *address = addr;
if (!is_valid_ether_addr(address->sa_data))
return -EADDRNOTAVAIL;
memcpy(ndev->dev_addr, address->sa_data, ndev->addr_len);
ks8695_update_mac(ksp);
dev_dbg(ksp->dev, "%s: Updated MAC address to %pM\n",
ndev->name, ndev->dev_addr);
return 0;
}
/**
* ks8695_set_multicast - Set up the multicast behaviour of the interface
* @ndev: The net_device to configure
*
* This routine, called by the net layer, configures promiscuity
* and multicast reception behaviour for the interface.
*/
static void
ks8695_set_multicast(struct net_device *ndev)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
u32 ctrl;
ctrl = ks8695_readreg(ksp, KS8695_DRXC);
if (ndev->flags & IFF_PROMISC) {
/* enable promiscuous mode */
ctrl |= DRXC_RA;
} else if (ndev->flags & ~IFF_PROMISC) {
/* disable promiscuous mode */
ctrl &= ~DRXC_RA;
}
if (ndev->flags & IFF_ALLMULTI) {
/* enable all multicast mode */
ctrl |= DRXC_RM;
} else if (netdev_mc_count(ndev) > KS8695_NR_ADDRESSES) {
/* more specific multicast addresses than can be
* handled in hardware
*/
ctrl |= DRXC_RM;
} else {
/* enable specific multicasts */
ctrl &= ~DRXC_RM;
ks8695_init_partial_multicast(ksp, ndev);
}
ks8695_writereg(ksp, KS8695_DRXC, ctrl);
}
/**
* ks8695_timeout - Handle a network tx/rx timeout.
* @ndev: The net_device which timed out.
*
* A network transaction timed out, reset the device.
*/
static void
ks8695_timeout(struct net_device *ndev)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
netif_stop_queue(ndev);
ks8695_shutdown(ksp);
ks8695_reset(ksp);
ks8695_update_mac(ksp);
/* We ignore the return from this since it managed to init
* before it probably will be okay to init again.
*/
ks8695_init_net(ksp);
/* Reconfigure promiscuity etc */
ks8695_set_multicast(ndev);
/* And start the TX queue once more */
netif_start_queue(ndev);
}
/**
* ks8695_start_xmit - Start a packet transmission
* @skb: The packet to transmit
* @ndev: The network device to send the packet on
*
* This routine, called by the net layer, takes ownership of the
* sk_buff and adds it to the TX ring. It then kicks the TX DMA
* engine to ensure transmission begins.
*/
static int
ks8695_start_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
int buff_n;
dma_addr_t dmap;
spin_lock_irq(&ksp->txq_lock);
if (ksp->tx_ring_used == MAX_TX_DESC) {
/* Somehow we got entered when we have no room */
spin_unlock_irq(&ksp->txq_lock);
return NETDEV_TX_BUSY;
}
buff_n = ksp->tx_ring_next_slot;
BUG_ON(ksp->tx_buffers[buff_n].skb);
dmap = dma_map_single(ksp->dev, skb->data, skb->len, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(ksp->dev, dmap))) {
/* Failed to DMA map this SKB, give it back for now */
spin_unlock_irq(&ksp->txq_lock);
dev_dbg(ksp->dev, "%s: Could not map DMA memory for "\
"transmission, trying later\n", ndev->name);
return NETDEV_TX_BUSY;
}
ksp->tx_buffers[buff_n].dma_ptr = dmap;
/* Mapped okay, store the buffer pointer and length for later */
ksp->tx_buffers[buff_n].skb = skb;
ksp->tx_buffers[buff_n].length = skb->len;
/* Fill out the TX descriptor */
ksp->tx_ring[buff_n].data_ptr =
cpu_to_le32(ksp->tx_buffers[buff_n].dma_ptr);
ksp->tx_ring[buff_n].status =
cpu_to_le32(TDES_IC | TDES_FS | TDES_LS |
(skb->len & TDES_TBS));
wmb();
/* Hand it over to the hardware */
ksp->tx_ring[buff_n].owner = cpu_to_le32(TDES_OWN);
if (++ksp->tx_ring_used == MAX_TX_DESC)
netif_stop_queue(ndev);
/* Kick the TX DMA in case it decided to go IDLE */
ks8695_writereg(ksp, KS8695_DTSC, 0);
/* And update the next ring slot */
ksp->tx_ring_next_slot = (buff_n + 1) & MAX_TX_DESC_MASK;
spin_unlock_irq(&ksp->txq_lock);
return NETDEV_TX_OK;
}
/**
* ks8695_stop - Stop (shutdown) a KS8695 ethernet interface
* @ndev: The net_device to stop
*
* This disables the TX queue and cleans up a KS8695 ethernet
* device.
*/
static int
ks8695_stop(struct net_device *ndev)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
netif_stop_queue(ndev);
napi_disable(&ksp->napi);
ks8695_shutdown(ksp);
return 0;
}
/**
* ks8695_open - Open (bring up) a KS8695 ethernet interface
* @ndev: The net_device to open
*
* This resets, configures the MAC, initialises the RX ring and
* DMA engines and starts the TX queue for a KS8695 ethernet
* device.
*/
static int
ks8695_open(struct net_device *ndev)
{
struct ks8695_priv *ksp = netdev_priv(ndev);
int ret;
if (!is_valid_ether_addr(ndev->dev_addr))
return -EADDRNOTAVAIL;
ks8695_reset(ksp);
ks8695_update_mac(ksp);
ret = ks8695_init_net(ksp);
if (ret) {
ks8695_shutdown(ksp);
return ret;
}
napi_enable(&ksp->napi);
netif_start_queue(ndev);
return 0;
}
/* Platform device driver */
/**
* ks8695_init_switch - Init LAN switch to known good defaults.
* @ksp: The device to initialise
*
* This initialises the LAN switch in the KS8695 to a known-good
* set of defaults.
*/
static void __devinit
ks8695_init_switch(struct ks8695_priv *ksp)
{
u32 ctrl;
/* Default value for SEC0 according to datasheet */
ctrl = 0x40819e00;
/* LED0 = Speed LED1 = Link/Activity */
ctrl &= ~(SEC0_LLED1S | SEC0_LLED0S);
ctrl |= (LLED0S_LINK | LLED1S_LINK_ACTIVITY);
/* Enable Switch */
ctrl |= SEC0_ENABLE;
writel(ctrl, ksp->phyiface_regs + KS8695_SEC0);
/* Defaults for SEC1 */
writel(0x9400100, ksp->phyiface_regs + KS8695_SEC1);
}
/**
* ks8695_init_wan_phy - Initialise the WAN PHY to sensible defaults
* @ksp: The device to initialise
*
* This initialises a KS8695's WAN phy to sensible values for
* autonegotiation etc.
*/
static void __devinit
ks8695_init_wan_phy(struct ks8695_priv *ksp)
{
u32 ctrl;
/* Support auto-negotiation */
ctrl = (WMC_WANAP | WMC_WANA100F | WMC_WANA100H |
WMC_WANA10F | WMC_WANA10H);
/* LED0 = Activity , LED1 = Link */
ctrl |= (WLED0S_ACTIVITY | WLED1S_LINK);
/* Restart Auto-negotiation */
ctrl |= WMC_WANR;
writel(ctrl, ksp->phyiface_regs + KS8695_WMC);
writel(0, ksp->phyiface_regs + KS8695_WPPM);
writel(0, ksp->phyiface_regs + KS8695_PPS);
}
static const struct net_device_ops ks8695_netdev_ops = {
.ndo_open = ks8695_open,
.ndo_stop = ks8695_stop,
.ndo_start_xmit = ks8695_start_xmit,
.ndo_tx_timeout = ks8695_timeout,
.ndo_set_mac_address = ks8695_set_mac,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_multicast_list = ks8695_set_multicast,
};
/**
* ks8695_probe - Probe and initialise a KS8695 ethernet interface
* @pdev: The platform device to probe
*
* Initialise a KS8695 ethernet device from platform data.
*
* This driver requires at least one IORESOURCE_MEM for the
* registers and two IORESOURCE_IRQ for the RX and TX IRQs
* respectively. It can optionally take an additional
* IORESOURCE_MEM for the switch or phy in the case of the lan or
* wan ports, and an IORESOURCE_IRQ for the link IRQ for the wan
* port.
*/
static int __devinit
ks8695_probe(struct platform_device *pdev)
{
struct ks8695_priv *ksp;
struct net_device *ndev;
struct resource *regs_res, *phyiface_res;
struct resource *rxirq_res, *txirq_res, *linkirq_res;
int ret = 0;
int buff_n;
u32 machigh, maclow;
/* Initialise a net_device */
ndev = alloc_etherdev(sizeof(struct ks8695_priv));
if (!ndev) {
dev_err(&pdev->dev, "could not allocate device.\n");
return -ENOMEM;
}
SET_NETDEV_DEV(ndev, &pdev->dev);
dev_dbg(&pdev->dev, "ks8695_probe() called\n");
/* Configure our private structure a little */
ksp = netdev_priv(ndev);
ksp->dev = &pdev->dev;
ksp->ndev = ndev;
ksp->msg_enable = NETIF_MSG_LINK;
/* Retrieve resources */
regs_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
phyiface_res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
rxirq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
txirq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 1);
linkirq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 2);
if (!(regs_res && rxirq_res && txirq_res)) {
dev_err(ksp->dev, "insufficient resources\n");
ret = -ENOENT;
goto failure;
}
ksp->regs_req = request_mem_region(regs_res->start,
resource_size(regs_res),
pdev->name);
if (!ksp->regs_req) {
dev_err(ksp->dev, "cannot claim register space\n");
ret = -EIO;
goto failure;
}
ksp->io_regs = ioremap(regs_res->start, resource_size(regs_res));
if (!ksp->io_regs) {
dev_err(ksp->dev, "failed to ioremap registers\n");
ret = -EINVAL;
goto failure;
}
if (phyiface_res) {
ksp->phyiface_req =
request_mem_region(phyiface_res->start,
resource_size(phyiface_res),
phyiface_res->name);
if (!ksp->phyiface_req) {
dev_err(ksp->dev,
"cannot claim switch register space\n");
ret = -EIO;
goto failure;
}
ksp->phyiface_regs = ioremap(phyiface_res->start,
resource_size(phyiface_res));
if (!ksp->phyiface_regs) {
dev_err(ksp->dev,
"failed to ioremap switch registers\n");
ret = -EINVAL;
goto failure;
}
}
ksp->rx_irq = rxirq_res->start;
ksp->rx_irq_name = rxirq_res->name ? rxirq_res->name : "Ethernet RX";
ksp->tx_irq = txirq_res->start;
ksp->tx_irq_name = txirq_res->name ? txirq_res->name : "Ethernet TX";
ksp->link_irq = (linkirq_res ? linkirq_res->start : -1);
ksp->link_irq_name = (linkirq_res && linkirq_res->name) ?
linkirq_res->name : "Ethernet Link";
/* driver system setup */
ndev->netdev_ops = &ks8695_netdev_ops;
ndev->watchdog_timeo = msecs_to_jiffies(watchdog);
netif_napi_add(ndev, &ksp->napi, ks8695_poll, NAPI_WEIGHT);
/* Retrieve the default MAC addr from the chip. */
/* The bootloader should have left it in there for us. */
machigh = ks8695_readreg(ksp, KS8695_MAH);
maclow = ks8695_readreg(ksp, KS8695_MAL);
ndev->dev_addr[0] = (machigh >> 8) & 0xFF;
ndev->dev_addr[1] = machigh & 0xFF;
ndev->dev_addr[2] = (maclow >> 24) & 0xFF;
ndev->dev_addr[3] = (maclow >> 16) & 0xFF;
ndev->dev_addr[4] = (maclow >> 8) & 0xFF;
ndev->dev_addr[5] = maclow & 0xFF;
if (!is_valid_ether_addr(ndev->dev_addr))
dev_warn(ksp->dev, "%s: Invalid ethernet MAC address. Please "
"set using ifconfig\n", ndev->name);
/* In order to be efficient memory-wise, we allocate both
* rings in one go.
*/
ksp->ring_base = dma_alloc_coherent(&pdev->dev, RING_DMA_SIZE,
&ksp->ring_base_dma, GFP_KERNEL);
if (!ksp->ring_base) {
ret = -ENOMEM;
goto failure;
}
/* Specify the TX DMA ring buffer */
ksp->tx_ring = ksp->ring_base;
ksp->tx_ring_dma = ksp->ring_base_dma;
/* And initialise the queue's lock */
spin_lock_init(&ksp->txq_lock);
spin_lock_init(&ksp->rx_lock);
/* Specify the RX DMA ring buffer */
ksp->rx_ring = ksp->ring_base + TX_RING_DMA_SIZE;
ksp->rx_ring_dma = ksp->ring_base_dma + TX_RING_DMA_SIZE;
/* Zero the descriptor rings */
memset(ksp->tx_ring, 0, TX_RING_DMA_SIZE);
memset(ksp->rx_ring, 0, RX_RING_DMA_SIZE);
/* Build the rings */
for (buff_n = 0; buff_n < MAX_TX_DESC; ++buff_n) {
ksp->tx_ring[buff_n].next_desc =
cpu_to_le32(ksp->tx_ring_dma +
(sizeof(struct tx_ring_desc) *
((buff_n + 1) & MAX_TX_DESC_MASK)));
}
for (buff_n = 0; buff_n < MAX_RX_DESC; ++buff_n) {
ksp->rx_ring[buff_n].next_desc =
cpu_to_le32(ksp->rx_ring_dma +
(sizeof(struct rx_ring_desc) *
((buff_n + 1) & MAX_RX_DESC_MASK)));
}
/* Initialise the port (physically) */
if (ksp->phyiface_regs && ksp->link_irq == -1) {
ks8695_init_switch(ksp);
ksp->dtype = KS8695_DTYPE_LAN;
SET_ETHTOOL_OPS(ndev, &ks8695_ethtool_ops);
} else if (ksp->phyiface_regs && ksp->link_irq != -1) {
ks8695_init_wan_phy(ksp);
ksp->dtype = KS8695_DTYPE_WAN;
SET_ETHTOOL_OPS(ndev, &ks8695_wan_ethtool_ops);
} else {
/* No initialisation since HPNA does not have a PHY */
ksp->dtype = KS8695_DTYPE_HPNA;
SET_ETHTOOL_OPS(ndev, &ks8695_ethtool_ops);
}
/* And bring up the net_device with the net core */
platform_set_drvdata(pdev, ndev);
ret = register_netdev(ndev);
if (ret == 0) {
dev_info(ksp->dev, "ks8695 ethernet (%s) MAC: %pM\n",
ks8695_port_type(ksp), ndev->dev_addr);
} else {
/* Report the failure to register the net_device */
dev_err(ksp->dev, "ks8695net: failed to register netdev.\n");
goto failure;
}
/* All is well */
return 0;
/* Error exit path */
failure:
ks8695_release_device(ksp);
free_netdev(ndev);
return ret;
}
/**
* ks8695_drv_suspend - Suspend a KS8695 ethernet platform device.
* @pdev: The device to suspend
* @state: The suspend state
*
* This routine detaches and shuts down a KS8695 ethernet device.
*/
static int
ks8695_drv_suspend(struct platform_device *pdev, pm_message_t state)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct ks8695_priv *ksp = netdev_priv(ndev);
ksp->in_suspend = 1;
if (netif_running(ndev)) {
netif_device_detach(ndev);
ks8695_shutdown(ksp);
}
return 0;
}
/**
* ks8695_drv_resume - Resume a KS8695 ethernet platform device.
* @pdev: The device to resume
*
* This routine re-initialises and re-attaches a KS8695 ethernet
* device.
*/
static int
ks8695_drv_resume(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct ks8695_priv *ksp = netdev_priv(ndev);
if (netif_running(ndev)) {
ks8695_reset(ksp);
ks8695_init_net(ksp);
ks8695_set_multicast(ndev);
netif_device_attach(ndev);
}
ksp->in_suspend = 0;
return 0;
}
/**
* ks8695_drv_remove - Remove a KS8695 net device on driver unload.
* @pdev: The platform device to remove
*
* This unregisters and releases a KS8695 ethernet device.
*/
static int __devexit
ks8695_drv_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct ks8695_priv *ksp = netdev_priv(ndev);
platform_set_drvdata(pdev, NULL);
netif_napi_del(&ksp->napi);
unregister_netdev(ndev);
ks8695_release_device(ksp);
free_netdev(ndev);
dev_dbg(&pdev->dev, "released and freed device\n");
return 0;
}
static struct platform_driver ks8695_driver = {
.driver = {
.name = MODULENAME,
.owner = THIS_MODULE,
},
.probe = ks8695_probe,
.remove = __devexit_p(ks8695_drv_remove),
.suspend = ks8695_drv_suspend,
.resume = ks8695_drv_resume,
};
/* Module interface */
static int __init
ks8695_init(void)
{
printk(KERN_INFO "%s Ethernet driver, V%s\n",
MODULENAME, MODULEVERSION);
return platform_driver_register(&ks8695_driver);
}
static void __exit
ks8695_cleanup(void)
{
platform_driver_unregister(&ks8695_driver);
}
module_init(ks8695_init);
module_exit(ks8695_cleanup);
MODULE_AUTHOR("Simtec Electronics");
MODULE_DESCRIPTION("Micrel KS8695 (Centaur) Ethernet driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" MODULENAME);
module_param(watchdog, int, 0400);
MODULE_PARM_DESC(watchdog, "transmit timeout in milliseconds");
| gpl-2.0 |
markgross/kernel | arch/x86/mm/hugetlbpage.c | 900 | 4395 | /*
* IA-32 Huge TLB Page Support for Kernel.
*
* Copyright (C) 2002, Rohit Seth <rohit.seth@intel.com>
*/
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/pagemap.h>
#include <linux/err.h>
#include <linux/sysctl.h>
#include <asm/mman.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/pgalloc.h>
#if 0 /* This is just for testing */
struct page *
follow_huge_addr(struct mm_struct *mm, unsigned long address, int write)
{
unsigned long start = address;
int length = 1;
int nr;
struct page *page;
struct vm_area_struct *vma;
vma = find_vma(mm, addr);
if (!vma || !is_vm_hugetlb_page(vma))
return ERR_PTR(-EINVAL);
pte = huge_pte_offset(mm, address);
/* hugetlb should be locked, and hence, prefaulted */
WARN_ON(!pte || pte_none(*pte));
page = &pte_page(*pte)[vpfn % (HPAGE_SIZE/PAGE_SIZE)];
WARN_ON(!PageHead(page));
return page;
}
int pmd_huge(pmd_t pmd)
{
return 0;
}
int pud_huge(pud_t pud)
{
return 0;
}
#else
/*
* pmd_huge() returns 1 if @pmd is hugetlb related entry, that is normal
* hugetlb entry or non-present (migration or hwpoisoned) hugetlb entry.
* Otherwise, returns 0.
*/
int pmd_huge(pmd_t pmd)
{
return !pmd_none(pmd) &&
(pmd_val(pmd) & (_PAGE_PRESENT|_PAGE_PSE)) != _PAGE_PRESENT;
}
int pud_huge(pud_t pud)
{
return !!(pud_val(pud) & _PAGE_PSE);
}
#endif
#ifdef CONFIG_HUGETLB_PAGE
static unsigned long hugetlb_get_unmapped_area_bottomup(struct file *file,
unsigned long addr, unsigned long len,
unsigned long pgoff, unsigned long flags)
{
struct hstate *h = hstate_file(file);
struct vm_unmapped_area_info info;
info.flags = 0;
info.length = len;
info.low_limit = current->mm->mmap_legacy_base;
info.high_limit = TASK_SIZE;
info.align_mask = PAGE_MASK & ~huge_page_mask(h);
info.align_offset = 0;
return vm_unmapped_area(&info);
}
static unsigned long hugetlb_get_unmapped_area_topdown(struct file *file,
unsigned long addr0, unsigned long len,
unsigned long pgoff, unsigned long flags)
{
struct hstate *h = hstate_file(file);
struct vm_unmapped_area_info info;
unsigned long addr;
info.flags = VM_UNMAPPED_AREA_TOPDOWN;
info.length = len;
info.low_limit = PAGE_SIZE;
info.high_limit = current->mm->mmap_base;
info.align_mask = PAGE_MASK & ~huge_page_mask(h);
info.align_offset = 0;
addr = vm_unmapped_area(&info);
/*
* A failed mmap() very likely causes application failure,
* so fall back to the bottom-up function here. This scenario
* can happen with large stack limits and large mmap()
* allocations.
*/
if (addr & ~PAGE_MASK) {
VM_BUG_ON(addr != -ENOMEM);
info.flags = 0;
info.low_limit = TASK_UNMAPPED_BASE;
info.high_limit = TASK_SIZE;
addr = vm_unmapped_area(&info);
}
return addr;
}
unsigned long
hugetlb_get_unmapped_area(struct file *file, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
struct hstate *h = hstate_file(file);
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
if (len & ~huge_page_mask(h))
return -EINVAL;
if (len > TASK_SIZE)
return -ENOMEM;
if (flags & MAP_FIXED) {
if (prepare_hugepage_range(file, addr, len))
return -EINVAL;
return addr;
}
if (addr) {
addr = ALIGN(addr, huge_page_size(h));
vma = find_vma(mm, addr);
if (TASK_SIZE - len >= addr &&
(!vma || addr + len <= vma->vm_start))
return addr;
}
if (mm->get_unmapped_area == arch_get_unmapped_area)
return hugetlb_get_unmapped_area_bottomup(file, addr, len,
pgoff, flags);
else
return hugetlb_get_unmapped_area_topdown(file, addr, len,
pgoff, flags);
}
#endif /* CONFIG_HUGETLB_PAGE */
#ifdef CONFIG_X86_64
static __init int setup_hugepagesz(char *opt)
{
unsigned long ps = memparse(opt, &opt);
if (ps == PMD_SIZE) {
hugetlb_add_hstate(PMD_SHIFT - PAGE_SHIFT);
} else if (ps == PUD_SIZE && cpu_has_gbpages) {
hugetlb_add_hstate(PUD_SHIFT - PAGE_SHIFT);
} else {
printk(KERN_ERR "hugepagesz: Unsupported page size %lu M\n",
ps >> 20);
return 0;
}
return 1;
}
__setup("hugepagesz=", setup_hugepagesz);
#ifdef CONFIG_CMA
static __init int gigantic_pages_init(void)
{
/* With CMA we can allocate gigantic pages at runtime */
if (cpu_has_gbpages && !size_to_hstate(1UL << PUD_SHIFT))
hugetlb_add_hstate(PUD_SHIFT - PAGE_SHIFT);
return 0;
}
arch_initcall(gigantic_pages_init);
#endif
#endif
| gpl-2.0 |
bood/htc-magic-kernel | fs/ceph/crush/crush.c | 900 | 3175 |
#ifdef __KERNEL__
# include <linux/slab.h>
#else
# include <stdlib.h>
# include <assert.h>
# define kfree(x) do { if (x) free(x); } while (0)
# define BUG_ON(x) assert(!(x))
#endif
#include "crush.h"
const char *crush_bucket_alg_name(int alg)
{
switch (alg) {
case CRUSH_BUCKET_UNIFORM: return "uniform";
case CRUSH_BUCKET_LIST: return "list";
case CRUSH_BUCKET_TREE: return "tree";
case CRUSH_BUCKET_STRAW: return "straw";
default: return "unknown";
}
}
/**
* crush_get_bucket_item_weight - Get weight of an item in given bucket
* @b: bucket pointer
* @p: item index in bucket
*/
int crush_get_bucket_item_weight(struct crush_bucket *b, int p)
{
if (p >= b->size)
return 0;
switch (b->alg) {
case CRUSH_BUCKET_UNIFORM:
return ((struct crush_bucket_uniform *)b)->item_weight;
case CRUSH_BUCKET_LIST:
return ((struct crush_bucket_list *)b)->item_weights[p];
case CRUSH_BUCKET_TREE:
if (p & 1)
return ((struct crush_bucket_tree *)b)->node_weights[p];
return 0;
case CRUSH_BUCKET_STRAW:
return ((struct crush_bucket_straw *)b)->item_weights[p];
}
return 0;
}
/**
* crush_calc_parents - Calculate parent vectors for the given crush map.
* @map: crush_map pointer
*/
void crush_calc_parents(struct crush_map *map)
{
int i, b, c;
for (b = 0; b < map->max_buckets; b++) {
if (map->buckets[b] == NULL)
continue;
for (i = 0; i < map->buckets[b]->size; i++) {
c = map->buckets[b]->items[i];
BUG_ON(c >= map->max_devices ||
c < -map->max_buckets);
if (c >= 0)
map->device_parents[c] = map->buckets[b]->id;
else
map->bucket_parents[-1-c] = map->buckets[b]->id;
}
}
}
void crush_destroy_bucket_uniform(struct crush_bucket_uniform *b)
{
kfree(b->h.perm);
kfree(b->h.items);
kfree(b);
}
void crush_destroy_bucket_list(struct crush_bucket_list *b)
{
kfree(b->item_weights);
kfree(b->sum_weights);
kfree(b->h.perm);
kfree(b->h.items);
kfree(b);
}
void crush_destroy_bucket_tree(struct crush_bucket_tree *b)
{
kfree(b->node_weights);
kfree(b);
}
void crush_destroy_bucket_straw(struct crush_bucket_straw *b)
{
kfree(b->straws);
kfree(b->item_weights);
kfree(b->h.perm);
kfree(b->h.items);
kfree(b);
}
void crush_destroy_bucket(struct crush_bucket *b)
{
switch (b->alg) {
case CRUSH_BUCKET_UNIFORM:
crush_destroy_bucket_uniform((struct crush_bucket_uniform *)b);
break;
case CRUSH_BUCKET_LIST:
crush_destroy_bucket_list((struct crush_bucket_list *)b);
break;
case CRUSH_BUCKET_TREE:
crush_destroy_bucket_tree((struct crush_bucket_tree *)b);
break;
case CRUSH_BUCKET_STRAW:
crush_destroy_bucket_straw((struct crush_bucket_straw *)b);
break;
}
}
/**
* crush_destroy - Destroy a crush_map
* @map: crush_map pointer
*/
void crush_destroy(struct crush_map *map)
{
int b;
/* buckets */
if (map->buckets) {
for (b = 0; b < map->max_buckets; b++) {
if (map->buckets[b] == NULL)
continue;
crush_destroy_bucket(map->buckets[b]);
}
kfree(map->buckets);
}
/* rules */
if (map->rules) {
for (b = 0; b < map->max_rules; b++)
kfree(map->rules[b]);
kfree(map->rules);
}
kfree(map->bucket_parents);
kfree(map->device_parents);
kfree(map);
}
| gpl-2.0 |
Pauliecoon/android_kernel_moto_shamu | drivers/platform/msm/qca1530.c | 1156 | 28389 | /* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "%s:%d] " fmt "\n", __func__, __LINE__
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/gpio.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/platform_device.h>
#include <linux/uaccess.h>
#include <linux/types.h>
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
/* RTC clock name for lookup */
#define QCA1530_RTC_CLK_ID "qca,rtc_clk"
/* TCXO clock name for lookup */
#define QCA1530_TCXO_CLK_ID "qca,tcxo_clk"
/* SoC power regulator prefix for DTS */
#define QCA1530_OF_PWR_REG_NAME "qca,pwr"
/* SoC optional power regulator prefix for DTS */
#define QCA1530_OF_PWR_OPT_REG_NAME "qca,pwr2"
/* SoC power regulator pin for DTS */
#define QCA1530_OF_PWR_GPIO_NAME "qca,pwr-gpio"
/* Reset power regulator prefix for DTS */
#define QCA1530_OF_RESET_REG_NAME "qca,reset"
/* Reset pin name for DTS */
#define QCA1530_OF_RESET_GPIO_NAME "qca,reset-gpio"
/* Clock pin name for DTS */
#define QCA1530_OF_CLK_GPIO_NAME "qca,clk-gpio"
/* xLNA power regulator prefix for DTS */
#define QCA1530_OF_XLNA_REG_NAME "qca,xlna"
/* xLNA voltage property name in DTS */
#define QCA1530_OF_XLNA_POWER_VOLTAGE "qca,xlna-voltage-level"
/* xLNA current property name in DTS */
#define QCA1530_OF_XLNA_POWER_CURRENT "qca,xlna-current-level"
/* xLNA pin name for DTS */
#define QCA1530_OF_XLNA_GPIO_NAME "qca,xlna-gpio"
#define QCA1530_ALL_FLG 0x0f
#define QCA1530_POWER_FLG 0x01
#define QCA1530_XLNA_FLG 0x02
#define QCA1530_CLK_FLG 0x04
#define QCA1530_RESET_FLG 0x08
#define GPIO_OPTIONAL_FLG 0x01
#define GPIO_EXPORT_FLG 0x02
#define GPIO_OUTDIR_FLG 0x04
#define SYSFS_NODE_NAME "qca1530"
/**
* struct qca1530_static - keeps all driver instance variables
* @pdev: Platform device data
* @reset_gpio: Number of GPIO pin for reset control, or -1
* @reset_reg: Handle to power regulator for reset control, or NULL
* @rtc_clk: RTC clock handle (32KHz)
* @rtc_clk_gpio: RTC clock gppio, or -1
* @tcxo_clk: TCXO clock handle
* @pwr_reg: Main SoC power regulator handle, or NULL
* @pwr_gpio: Main SoC power regulator GPIO, or -1
* @xlna_reg: xLNA power regulator handle, or NULL
* @xlna_gpio: xLNA power GPIO, or -1
*
* The structure contains all driver instance variables.
*/
struct qca1530_static {
struct platform_device *pdev;
int reset_gpio;
struct regulator *reset_reg;
struct clk *rtc_clk;
int rtc_clk_gpio;
struct clk *tcxo_clk;
struct regulator *pwr_reg;
struct regulator *pwr_opt_reg;
int pwr_gpio;
struct regulator *xlna_reg;
int xlna_gpio;
int chip_state;
};
/*
* qca1530_data - driver instance data
*/
static struct qca1530_static qca1530_data = {
.reset_gpio = -1,
.rtc_clk_gpio = -1,
.pwr_gpio = -1,
.xlna_gpio = -1,
.chip_state = 0,
};
/**
* qca1530_deinit_gpio() - release GPIO resource
* @pdev: platform device data
* @pgpio: pointer to GPIO handle
* @flags: flags showing how gpio was initialized
*
* Function releases GPIO handle allocated by the driver. By default the
* GPIO pin is removed from user space, switched to input direction and
* then released.
*
* GPIO handle is set to -1.
*/
static void qca1530_deinit_gpio(struct platform_device *pdev, int *pgpio,
int flags)
{
if (*pgpio >= 0) {
pr_debug("Releasing GPIO: %d, %d", *pgpio, flags);
if (flags & GPIO_EXPORT_FLG)
gpio_unexport(*pgpio);
gpio_direction_input(*pgpio);
devm_gpio_free(&pdev->dev, *pgpio);
*pgpio = -1;
}
}
/**
* qca1530_init_gpio() - initialize GPIO resource
* @pdev: platform device data
* @pgpio: pointer to GPIO handle
* @pgio_name: name of gpio in device tree
* @flags: flags to control export, direction, etc
*
* Function initializes gpio and returns 0 on sucess.
*
*/
static int qca1530_init_gpio(struct platform_device *pdev, int *pgpio,
const char *gpio_name, int flags)
{
int ret;
pr_debug("Initializing gpio %s, flags %d", gpio_name, flags);
ret = of_get_named_gpio(pdev->dev.of_node, gpio_name, 0);
if (ret == -ENOENT && (flags & GPIO_OPTIONAL_FLG)) {
*pgpio = -1;
pr_debug("Optional GPIO is not defined");
return 0;
} else if (ret < 0) {
pr_err("Error getting GPIO from config: %d", ret);
goto err_gpio_init;
}
*pgpio = ret;
ret = devm_gpio_request(&pdev->dev, *pgpio, gpio_name);
if (ret < 0) {
pr_err("failed to request gpio %d, %d", *pgpio, ret);
goto err_gpio_init;
}
if (flags & GPIO_OUTDIR_FLG) {
ret = gpio_direction_output(*pgpio, 0);
if (ret < 0) {
pr_err("failed to change direction for gpio %d, %d",
*pgpio, ret);
goto err_gpio_set_dir;
}
}
if (flags & GPIO_EXPORT_FLG) {
ret = gpio_export(*pgpio, false);
if (ret < 0) {
pr_err("failed to export gpio %d for user, %d",
*pgpio, ret);
goto err_gpio_export;
}
}
pr_debug("Initialized gpio %s: %d", gpio_name, *pgpio);
return 0;
err_gpio_export:
gpio_direction_input(*pgpio);
err_gpio_set_dir:
devm_gpio_free(&pdev->dev, *pgpio);
err_gpio_init:
*pgpio = -1;
return ret;
}
/**
* qca1530_deinit_regulator() - release power regulator resource
* @ppwr: pointer to power regulator handle
*
* Function releases power regulator and sets handle to NULL.
*/
static void qca1530_deinit_regulator(struct regulator **ppwr)
{
if (*ppwr) {
devm_regulator_put(*ppwr);
*ppwr = NULL;
}
}
/**
* qca1530_clk_prepare() - prepare or unprepare clock
* @clk: clock handle
* @mode: 0 to unprepare, 1 to prepare
*
* Function prepares or unprepares clock and logs the result.
*
* Return: 0 on success, error code on failure
*/
static int qca1530_clk_prepare(struct clk *clk, int mode)
{
int ret = 0;
if (mode)
ret = clk_prepare_enable(clk);
else
clk_disable_unprepare(clk);
pr_debug("Configured clock (%p): mode=%d ret=%d", clk, mode, ret);
return ret;
}
/**
* qca1530_clk_set_gpio() - enable or disable RTC GPIO pin
* @mode: 1 to enable, 0 to disable
*
* Function enables or disable clock GPIO pin and logs the result.
*/
static void qca1530_clk_set_gpio(int mode)
{
gpio_set_value(qca1530_data.rtc_clk_gpio, mode ? 1 : 0);
pr_debug("Set clk GPIO (%d): mode=%d", qca1530_data.rtc_clk_gpio, mode);
}
/**
* qca1530_clk_set() - start/stop initialized clocks
* @mode: 1 to start clocks, 0 to stop
*
* Function turns clocks on or off. Clock configuration is optional, however
* when configured, the following order is used: RTC GPIO pin, RTC clock,
* TCXO clock. When switching off, the order is reveresed.
*
* Return: 0 on success, error code on failure.
*/
static int qca1530_clk_set(int mode)
{
int ret = 0;
if (qca1530_data.rtc_clk_gpio < 0 &&
!qca1530_data.rtc_clk &&
!qca1530_data.tcxo_clk) {
ret = -ENOSYS;
} else {
if (qca1530_data.rtc_clk_gpio >= 0)
qca1530_clk_set_gpio(mode);
if (qca1530_data.rtc_clk)
ret = qca1530_clk_prepare(qca1530_data.rtc_clk, mode);
if (!ret && qca1530_data.tcxo_clk)
ret = qca1530_clk_prepare(qca1530_data.tcxo_clk, mode);
}
pr_debug("Configured clk: mode=%d ret=%d", mode, ret);
return ret;
}
/**
* qca1530_clk_release_clock() - release clocks
* @pdev: platform device data
* @clk_name: clock name
* @clk: pointer to clock handle pointer
*
* Function releases initialized clocks and sets clock handle
* pointer to NULL.
*/
static void qca1530_clk_release_clock(
struct platform_device *pdev,
const char *clk_name,
struct clk **clk)
{
if (*clk) {
pr_debug("Unregistering CLK: name=%s", clk_name);
devm_clk_put(&pdev->dev, *clk);
*clk = NULL;
}
}
/**
* qca1530_clk_release_clocks() - release clocks
* @pdev: platform device data
*
* Function releases initialized clocks and sets clock handle
* pointers to NULL.
*/
static void qca1530_clk_release_clocks(struct platform_device *pdev)
{
qca1530_deinit_gpio(pdev, &qca1530_data.rtc_clk_gpio,
GPIO_OPTIONAL_FLG | GPIO_OUTDIR_FLG);
qca1530_clk_release_clock(pdev, QCA1530_TCXO_CLK_ID,
&qca1530_data.tcxo_clk);
qca1530_clk_release_clock(pdev, QCA1530_RTC_CLK_ID,
&qca1530_data.rtc_clk);
}
/**
* qca1530_clk_init() - allocate and initialize clock input resources
* @pdev: platform device data
*
* Function tries to connect to RTC and TCXO clocks and obtain clock GPIO
* pin.
*
* Return: 0 on success, error code on failure.
*/
static int qca1530_clk_init(struct platform_device *pdev)
{
int ret;
pr_debug("Initializing clock");
qca1530_data.rtc_clk = devm_clk_get(&pdev->dev, QCA1530_RTC_CLK_ID);
if (IS_ERR(qca1530_data.rtc_clk)) {
ret = PTR_ERR(qca1530_data.rtc_clk);
qca1530_data.rtc_clk = NULL;
if (ret == -ENOENT) {
pr_debug("No RTC clock controller");
} else {
pr_err("Clock init error: device=%s clock=%s ret=%d",
dev_name(&pdev->dev), QCA1530_RTC_CLK_ID,
ret);
goto err_0;
}
} else
pr_debug("Ref to clock %s obtained: %p",
QCA1530_RTC_CLK_ID, qca1530_data.rtc_clk);
qca1530_data.tcxo_clk = devm_clk_get(&pdev->dev, QCA1530_TCXO_CLK_ID);
if (IS_ERR(qca1530_data.tcxo_clk)) {
ret = PTR_ERR(qca1530_data.tcxo_clk);
qca1530_data.tcxo_clk = NULL;
if (ret == -ENOENT) {
pr_debug("No TCXO clock controller");
} else {
pr_err("Clock init error: device=%s clock=%s ret=%d",
dev_name(&pdev->dev), QCA1530_TCXO_CLK_ID,
ret);
goto err_1;
}
} else
pr_debug("Ref to clock %s obtained: %p",
QCA1530_TCXO_CLK_ID, qca1530_data.tcxo_clk);
ret = qca1530_init_gpio(pdev, &qca1530_data.rtc_clk_gpio,
QCA1530_OF_CLK_GPIO_NAME, GPIO_OPTIONAL_FLG | GPIO_OUTDIR_FLG);
if (ret)
goto err_1;
ret = qca1530_clk_set(1);
if (ret < 0) {
pr_err("Clock set error: ret=%d", ret);
goto err_1;
}
pr_debug("Clock init done: GPIO=%s RTC=%s TCXO=%s",
qca1530_data.rtc_clk_gpio >= 0 ? "ok" : "unused",
qca1530_data.rtc_clk ? "ok" : "unused",
qca1530_data.tcxo_clk ? "ok" : "unused");
return 0;
err_1:
qca1530_clk_release_clocks(pdev);
err_0:
pr_err("init error: ret=%d", ret);
return ret;
}
/**
* qca1530_clk_deinit() - release clock control resources
* @pdev: platform device data
*
* Function disables clock control and releases GPIO and clock resources.
*/
static void qca1530_clk_deinit(struct platform_device *pdev)
{
qca1530_clk_set(0);
qca1530_deinit_gpio(pdev, &qca1530_data.rtc_clk_gpio,
GPIO_OPTIONAL_FLG | GPIO_OUTDIR_FLG);
qca1530_clk_release_clocks(pdev);
}
/**
* qca1530_pwr_set_gpio() - set power GPIO line
* @mode: 1 to enable, 0 to disable
*
* Function sets GPIO pin value and logs the result.
*/
static void qca1530_pwr_set_gpio(int mode)
{
gpio_set_value(qca1530_data.pwr_gpio, mode ? 1 : 0);
pr_debug("Configuring power(GPIO): mode=%d", mode);
}
/**
* qca1530_pwr_set_regulator() - control regulator and log results
* @reg: regulator to control
* @mode: 1 to enable, 0 to disable
*
* Function controls power regulator and logs results.
*
* Return: 0 on success, error code otherwise
*/
static int qca1530_pwr_set_regulator(struct regulator *reg, int mode)
{
int ret;
pr_debug("Setting regulator: mode=%d regulator=%p", mode, reg);
if (mode) {
ret = regulator_enable(reg);
if (ret)
pr_err("Failed to enable regulator, rc=%d", ret);
else
pr_debug("Regulator %p was enabled (%d)", reg, ret);
} else {
if (!regulator_is_enabled(reg)) {
ret = 0;
} else {
ret = regulator_disable(reg);
if (ret)
pr_err("Failed to disable regulator, rc=%d",
ret);
else
pr_debug("Regulator %p was disabled (%d)", reg,
ret);
}
}
pr_debug("Regulator set result: regulator=%p mode=%d ret=%d", reg, mode,
ret);
return ret;
}
/**
* qca1530_pwr_init_regulator() - initialize power regulator if configured
* @pdev: platform device data
* @name: regulator name prefix in DTS file
* @ppwr: pointer to resulting variable
*
* Function initializes power regulator if DTS configuration is present.
*
* Return: 0 on success, error code otherwise
*/
static int qca1530_pwr_init_regulator(
struct platform_device *pdev,
const char *name, struct regulator **ppwr)
{
int ret;
struct regulator *pwr;
pwr = devm_regulator_get(&pdev->dev, name);
if (IS_ERR_OR_NULL(pwr)) {
ret = PTR_ERR(pwr);
*ppwr = NULL;
if (ret == -ENODEV) {
pr_debug("Power regulator %s is not defined",
name);
ret = 0;
} else
pr_err("Failed to get regulator, ret=%d", ret);
} else {
pr_debug("Ref to regulator %s obtained: %p", name, pwr);
*ppwr = pwr;
ret = 0;
}
return ret;
}
/**
* qca1530_power_set() - enable or disable SoC power
* @mode: 1 to enable, 0 to disable
*
* Function enables or disables SoC power line.
*
* Return: 0 on success, error code otherwise
*/
static int qca1530_pwr_set(int mode)
{
int ret = 0;
if (!qca1530_data.pwr_reg &&
!qca1530_data.pwr_opt_reg &&
qca1530_data.pwr_gpio < 0) {
ret = -ENOSYS;
} else {
if (qca1530_data.pwr_reg)
ret = qca1530_pwr_set_regulator(
qca1530_data.pwr_reg, mode);
if (!ret && qca1530_data.pwr_opt_reg)
ret = qca1530_pwr_set_regulator(
qca1530_data.pwr_opt_reg, mode);
if (!ret && qca1530_data.pwr_gpio >= 0)
qca1530_pwr_set_gpio(mode);
}
return ret;
}
/**
* qca1530_pwr_deinit() - release main SoC power control
* @pdev: platform device data
*
* Function releases power regulator and power GPIO pin.
*/
static void qca1530_pwr_deinit(struct platform_device *pdev)
{
qca1530_pwr_set(0);
qca1530_deinit_gpio(pdev, &qca1530_data.pwr_gpio,
GPIO_OPTIONAL_FLG | GPIO_OUTDIR_FLG);
qca1530_deinit_regulator(&qca1530_data.pwr_opt_reg);
qca1530_deinit_regulator(&qca1530_data.pwr_reg);
}
/**
* qca1530_pwr_init() - allocate SoC power control
* @pdev: platform device data
*
* Function allocates and enables SoC power control.
*
* Return: 0 on success, error code otherwise
*/
static int qca1530_pwr_init(struct platform_device *pdev)
{
int ret = 0;
pr_debug("Initializing power control");
ret = qca1530_pwr_init_regulator(
pdev, QCA1530_OF_PWR_REG_NAME, &qca1530_data.pwr_reg);
if (ret)
goto err_0;
ret = qca1530_pwr_init_regulator(
pdev, QCA1530_OF_PWR_OPT_REG_NAME, &qca1530_data.pwr_opt_reg);
if (ret)
goto err_0;
ret = qca1530_init_gpio(pdev, &qca1530_data.pwr_gpio,
QCA1530_OF_PWR_GPIO_NAME, GPIO_OPTIONAL_FLG | GPIO_OUTDIR_FLG);
if (ret)
goto err_0;
if (qca1530_data.pwr_reg ||
qca1530_data.pwr_gpio >= 0 ||
qca1530_data.pwr_opt_reg) {
ret = qca1530_pwr_set(1);
if (ret) {
pr_err("Failed to enable power, rc=%d", ret);
goto err_0;
}
pr_debug("Configured: reg=%p gpio=%d",
qca1530_data.pwr_reg,
qca1530_data.pwr_gpio);
} else {
pr_debug("Power control is not available");
}
return ret;
err_0:
qca1530_pwr_deinit(pdev);
return ret;
}
/**
* qca1530_reset_deinit() - release reset control resources
* @pdev: platform device data
*
* Function releases reset line GPIO and switches off and releases power
* regulator.
*/
static void qca1530_reset_deinit(struct platform_device *pdev)
{
pr_debug("Releasing reset control");
qca1530_deinit_gpio(pdev, &qca1530_data.reset_gpio,
GPIO_OUTDIR_FLG);
if (qca1530_data.reset_reg) {
qca1530_pwr_set_regulator(qca1530_data.reset_reg, 0);
qca1530_deinit_regulator(&qca1530_data.reset_reg);
}
}
/**
* qca1530_reset_init() - initialize SoC reset line resources
* @pdev: platform device data
*
* Function initializes reset line resources, including configuration of GPIO
* pin and power regulator.
*
* Return: 0 on success, error code otherwise
*/
static int qca1530_reset_init(struct platform_device *pdev)
{
int ret;
pr_debug("Initializing reset control");
ret = qca1530_init_gpio(pdev, &qca1530_data.reset_gpio,
QCA1530_OF_RESET_GPIO_NAME, GPIO_OUTDIR_FLG);
if (ret < 0) {
goto err_0;
}
ret = qca1530_pwr_init_regulator(
pdev, QCA1530_OF_RESET_REG_NAME, &qca1530_data.reset_reg);
if (ret)
goto err_0;
if (qca1530_data.reset_reg) {
ret = qca1530_pwr_set_regulator(qca1530_data.reset_reg, 1);
if (ret) {
pr_err("failed to turn on reset regulator");
goto err_0;
}
}
return 0;
err_0:
qca1530_reset_deinit(pdev);
return ret;
}
/**
* qca1530_xlna_set() - enables and disables xLNA
* @mode: 0 to disable, 1 to enable
*
* Function controls xLNA. It configures power regulator and GPIO pin to
* enable or disable the amplifier.
*
* Return: 0 on success, error code on error
*/
static int qca1530_xlna_set(int mode)
{
int ret = 0;
if (!qca1530_data.xlna_reg && qca1530_data.xlna_gpio < 0)
ret = -ENOSYS;
else if (mode) {
if (qca1530_data.xlna_reg) {
ret = qca1530_pwr_set_regulator(
qca1530_data.xlna_reg, mode);
}
if (!ret && qca1530_data.xlna_gpio >= 0)
gpio_set_value(qca1530_data.xlna_gpio, 1);
} else {
if (qca1530_data.xlna_gpio >= 0)
gpio_set_value(qca1530_data.xlna_gpio, 0);
if (qca1530_data.xlna_reg)
ret = qca1530_pwr_set_regulator(
qca1530_data.xlna_reg, mode);
}
return ret;
}
/**
* qca1530_read_u32_arr_property() - read u32 values property
* @pdev: platform device data
* @pname: property name
* @num_values: array size
* @values: array to put results to
*
* Function reads property with given name. Filles passed array of
* u32 values.
*
* Return: 0 on successful read, error code on error.
*/
static int qca1530_read_u32_arr_property(struct platform_device *pdev,
const char *pname, const int num_values, u32 *values)
{
int len = 0;
int ret = 0;
if (pdev->dev.of_node) {
const void *rp = of_get_property(pdev->dev.of_node,
pname, &len);
if (NULL != rp && len == sizeof(u32)*num_values)
ret = of_property_read_u32_array(pdev->dev.of_node,
pname, values, num_values);
else
ret = -ENODATA;
} else{
ret = -EINVAL;
}
if (ret)
pr_err("Error reading property %s, ret:%d", pname, ret);
return ret;
}
/**
* qca1530_xlna_deinit() - release all xLNA resources
* @pdev: platform device data
*
* Function switches off xLNA and releases all allocated resources.
*/
static void qca1530_xlna_deinit(struct platform_device *pdev)
{
qca1530_xlna_set(0);
qca1530_deinit_gpio(pdev, &qca1530_data.xlna_gpio,
GPIO_OPTIONAL_FLG | GPIO_OUTDIR_FLG);
qca1530_deinit_regulator(&qca1530_data.xlna_reg);
}
/**
* qca1530_xlna_init() - allocates xLNA resources
* @pdev: platform device data
*
* Function allocates xLNA resources according to DTS configuration.
* When configured, the following facilities are used:
* - power regulator (optionally)
* - GPIO pin (optionally)
*
* After initialization, xLNA is enabled.
*
* Return: 0 on successful initialization, error code on error.
*/
static int qca1530_xlna_init(struct platform_device *pdev)
{
int ret = 0;
u32 tmp[2];
pr_debug("Initializing xLNA control");
ret = qca1530_pwr_init_regulator(
pdev, QCA1530_OF_XLNA_REG_NAME, &qca1530_data.xlna_reg);
if (ret)
goto err_0;
if (qca1530_data.xlna_reg) {
ret = qca1530_read_u32_arr_property(pdev,
QCA1530_OF_XLNA_POWER_VOLTAGE, 2, tmp);
if (!ret) {
ret = regulator_set_voltage(qca1530_data.xlna_reg,
tmp[0], tmp[1]);
if (ret)
pr_warn("Failed to set voltage, ret=%d", ret);
else
pr_debug("Regulator %p voltage was set (%d)",
qca1530_data.xlna_reg, ret);
}
ret = qca1530_read_u32_arr_property(pdev,
QCA1530_OF_XLNA_POWER_CURRENT, 2, tmp);
if (!ret) {
ret = regulator_set_optimum_mode(qca1530_data.xlna_reg,
tmp[0]);
if (ret < 0)
pr_warn("Failed to set optimum mode, ret=%d",
ret);
else
pr_debug("Optimum mode for %p was set (%d)",
qca1530_data.xlna_reg, ret);
}
}
ret = qca1530_init_gpio(pdev, &qca1530_data.xlna_gpio,
QCA1530_OF_XLNA_GPIO_NAME, GPIO_OPTIONAL_FLG | GPIO_OUTDIR_FLG);
if (ret)
goto err_0;
if (qca1530_data.xlna_reg || qca1530_data.xlna_gpio >= 0) {
ret = qca1530_xlna_set(1);
if (ret) {
pr_err("Failed to enable xLNA, rc=%d", ret);
goto err_0;
}
pr_debug("Configured: reg=%p gpio=%d",
qca1530_data.xlna_reg,
qca1530_data.xlna_gpio);
} else {
pr_debug("xLNA control is not available");
}
return ret;
err_0:
qca1530_xlna_deinit(pdev);
return ret;
}
/**
* qca1530_set_chip_state() - performs driver initialization
* @pdev: platform device data
* @on: target state, 1 - on, 0 - off
*
* The driver probing includes initialization of the subsystems in the
* following order:
* - reset control
* - RTC and TXCO Clock control
* - xLNA control
* - SoC power control
*/
static int qca1530_set_chip_state(struct platform_device *pdev,
const int on_mask)
{
int ret;
int on_req;
ret = 0;
on_req = on_mask;
pr_debug("on_mask=%d", on_mask);
pr_debug("Switching on");
if (!(qca1530_data.chip_state & QCA1530_RESET_FLG) &&
(on_req & QCA1530_RESET_FLG)) {
ret = qca1530_reset_init(pdev);
if (ret < 0) {
pr_err("failed to init reset: %d", ret);
on_req = 0;
goto switching_off;
} else {
qca1530_data.chip_state |= QCA1530_RESET_FLG;
}
}
if (!(qca1530_data.chip_state & QCA1530_CLK_FLG) &&
(on_req & QCA1530_CLK_FLG)) {
ret = qca1530_clk_init(pdev);
if (ret) {
pr_err("failed to initialize clock: %d", ret);
on_req = 0;
goto switching_off;
} else {
qca1530_data.chip_state |= QCA1530_CLK_FLG;
}
}
if (!(qca1530_data.chip_state & QCA1530_XLNA_FLG) &&
(on_req & QCA1530_XLNA_FLG)) {
ret = qca1530_xlna_init(pdev);
if (ret) {
pr_err("failed to initialize xLNA: %d", ret);
on_req = 0;
goto switching_off;
} else {
qca1530_data.chip_state |= QCA1530_XLNA_FLG;
}
}
if (!(qca1530_data.chip_state & QCA1530_POWER_FLG) &&
(on_req & QCA1530_POWER_FLG)) {
ret = qca1530_pwr_init(pdev);
if (ret < 0) {
pr_err("failed to init power: %d", ret);
on_req = 0;
goto switching_off;
} else {
qca1530_data.chip_state |= QCA1530_POWER_FLG;
}
}
pr_debug("Chip on section over, qca1530_data.chip_state=%d",
qca1530_data.chip_state);
switching_off:
pr_debug("Switching off");
if ((qca1530_data.chip_state & QCA1530_POWER_FLG) &&
!(on_req & QCA1530_POWER_FLG)) {
qca1530_pwr_deinit(pdev);
qca1530_data.chip_state &= ~QCA1530_POWER_FLG;
}
if ((qca1530_data.chip_state & QCA1530_XLNA_FLG) &&
!(on_req & QCA1530_XLNA_FLG)) {
qca1530_xlna_deinit(pdev);
qca1530_data.chip_state &= ~QCA1530_XLNA_FLG;
}
if ((qca1530_data.chip_state & QCA1530_CLK_FLG) &&
!(on_req & QCA1530_CLK_FLG)) {
qca1530_clk_deinit(pdev);
qca1530_data.chip_state &= ~QCA1530_CLK_FLG;
}
if ((qca1530_data.chip_state & QCA1530_RESET_FLG) &&
!(on_req & QCA1530_RESET_FLG)) {
qca1530_reset_deinit(pdev);
qca1530_data.chip_state &= ~QCA1530_RESET_FLG;
}
pr_debug("Chip off section over, qca1530_data.chip_state=%d",
qca1530_data.chip_state);
return ret;
}
/**
* qca1530_attr_chip_state_show() - provides current chip state through sysfs
*/
static ssize_t qca1530_attr_chip_state_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return snprintf(buf, 16, "%d\n", qca1530_data.chip_state);
}
/**
* qca1530_attr_chip_state_store() - sets new chip state
*/
static ssize_t qca1530_attr_chip_state_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
int retval;
int new_state;
sscanf(buf, "%d", &new_state);
pr_debug("new_state=%d", new_state);
if (count &&
((new_state <= QCA1530_ALL_FLG) && (new_state >= 0))) {
pr_debug("qca1530_data.chip_state=%d", qca1530_data.chip_state);
retval = qca1530_set_chip_state(qca1530_data.pdev, new_state);
pr_debug("qca1530_set_chip_state() returned %d", retval);
pr_debug("qca1530_data.chip_state=%d", qca1530_data.chip_state);
}
return count;
}
/**
* qca1530_attr_reset_show() - provides current reset state through sysfs
*/
static ssize_t qca1530_attr_reset_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
int v = -1;
if (qca1530_data.chip_state & QCA1530_RESET_FLG)
v = gpio_get_value(qca1530_data.reset_gpio);
return snprintf(buf, 16, "%d\n", v);
}
/**
* qca1530_attr_reset_store() - sets new reset state
*/
static ssize_t qca1530_attr_reset_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
int v;
if (sscanf(buf, "%d", &v) == 1
&& (qca1530_data.chip_state & QCA1530_RESET_FLG))
gpio_set_value(qca1530_data.reset_gpio, v ? 1 : 0);
return count;
}
/*
* qca1530_attributes - sysfs attribute definition array
*/
static struct kobj_attribute qca1530_attributes[] = {
__ATTR(chip_state,
S_IRUSR | S_IWUSR,
qca1530_attr_chip_state_show, qca1530_attr_chip_state_store),
__ATTR(reset,
S_IRUSR | S_IWUSR,
qca1530_attr_reset_show, qca1530_attr_reset_store),
};
/*
* qca1530_attrs - sysfs attributes for attribute group
*/
static struct attribute *qca1530_attrs[] = {
&qca1530_attributes[0].attr,
&qca1530_attributes[1].attr,
NULL,
};
/*
* qca1530_attr_group - driver sysfs attribute group
*/
static struct attribute_group qca1530_attr_group = {
.attrs = qca1530_attrs,
};
static struct kobject *qca1530_kobject;
/**
* qca1530_create_sysfs_node() - creates sysfs nodes for control
*
* Function exports two control nodes: for controlling chip control signals
* and for reset control.
*/
static int qca1530_create_sysfs_node(void)
{
int retval;
pr_debug("Creating sysfs node");
qca1530_kobject = kobject_create_and_add(SYSFS_NODE_NAME, kernel_kobj);
pr_debug("qca1530_kobject=%p", qca1530_kobject);
if (!qca1530_kobject)
return -ENOMEM;
retval = sysfs_create_group(qca1530_kobject, &qca1530_attr_group);
pr_debug("sysfs_create_group() returned %d", retval);
if (retval)
kobject_put(qca1530_kobject);
return retval;
}
/**
* qca1530_remove_sysfs_node() - removes sysfs nodes
*/
static void qca1530_remove_sysfs_node(void)
{
pr_debug("Removing sysfs node");
if (qca1530_kobject) {
sysfs_remove_group(qca1530_kobject, &qca1530_attr_group);
kobject_put(qca1530_kobject);
qca1530_kobject = NULL;
}
}
/**
* qca1530_probe() - performs driver initialization
* @pdev: platform device data
*
* Function tried to turn on all required signals.
* Refer to qca1530_set_chip_state() documentation for details.
*/
static int qca1530_probe(struct platform_device *pdev)
{
int retval;
pr_debug("Probing to install");
retval = qca1530_set_chip_state(pdev, QCA1530_ALL_FLG);
if (!retval) {
qca1530_data.pdev = pdev;
retval = qca1530_create_sysfs_node();
if (retval) {
qca1530_set_chip_state(pdev, 0);
qca1530_data.pdev = NULL;
pr_debug("qca1530_create_sysfs_node() returned %d",
retval);
}
} else
pr_debug("qca1530_set_chip_state() returned %d", retval);
return retval;
}
/**
* qca1530_remove() - releases all resources
* @pdev: platform device data
*
* Driver's removal stops subsystems in the following order:
* - Power control
* - xLNA control
* - RTC and TCXO clock control
* - Reset control
*/
static int qca1530_remove(struct platform_device *pdev)
{
int retval;
qca1530_remove_sysfs_node();
retval = qca1530_set_chip_state(pdev, 0);
qca1530_data.pdev = NULL;
return retval;
}
/*
* qca1530_of_match - DTS driver name
*/
static struct of_device_id qca1530_of_match[] = {
{.compatible = "qca,qca1530", },
{ },
};
/*
* qca1530_driver - driver registration data
*/
static struct platform_driver qca1530_driver = {
.probe = qca1530_probe,
.remove = qca1530_remove,
.driver = {
.name = "qca1530",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(qca1530_of_match),
},
};
/**
* qca1530_init() - registers the driver
*/
static int __init qca1530_init(void)
{
return platform_driver_register(&qca1530_driver);
}
/**
* qca1530_exit() - unregisters the driver
*/
static void __exit qca1530_exit(void)
{
platform_driver_unregister(&qca1530_driver);
}
module_init(qca1530_init);
module_exit(qca1530_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("qca1530 SoC chip driver");
MODULE_ALIAS("qca1530");
| gpl-2.0 |
loveboylion/android_kernel_yu_msm8916 | drivers/platform/msm/spss.c | 1156 | 4402 | /* Copyright (c) 2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <mach/msm_iomap.h>
#define CLOCK_CONTROL_REG 0x00
#define BUS_SMCBC_REG 0x04
#define PSCBC_BUS_REG 0x0C
#define PSCBC_GENI_REG 0x10
#define STANDBY_MODE 0x2
#define ACTIVE_MODE 0x1
#define ASYNC_SW_CLK_EN 0x2
struct msm_spss_dev_t {
void __iomem *base;
struct clk *clk;
};
static struct msm_spss_dev_t msm_spss_dev;
static int msm_spss_probe(struct platform_device *pdev)
{
struct resource *res;
int rc = 0;
msm_spss_dev.clk = clk_get(&pdev->dev, "iface_clk");
if (IS_ERR(msm_spss_dev.clk)) {
rc = PTR_ERR(msm_spss_dev.clk);
dev_err(&pdev->dev, "could not get ahb clk %d\n", rc);
goto err_clk_get;
}
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "base");
if (!res) {
dev_err(&pdev->dev, "missing memory resource\n");
rc = -EINVAL;
goto err_res;
}
msm_spss_dev.base = ioremap(res->start, resource_size(res));
if (!msm_spss_dev.base) {
dev_err(&pdev->dev, "ioremap failed\n");
rc = -ENOMEM;
goto err_ioremap;
}
rc = of_platform_populate(pdev->dev.of_node, NULL, NULL, &pdev->dev);
if (rc) {
dev_err(&pdev->dev, "of_platform_populate failed %d\n", rc);
goto err_of_plat_pop;
}
rc = clk_prepare_enable(msm_spss_dev.clk);
if (rc) {
dev_err(&pdev->dev, "ahb clk enable failed %d\n", rc);
goto err_clk_en;
}
writel_relaxed(ASYNC_SW_CLK_EN, (msm_spss_dev.base + BUS_SMCBC_REG));
writel_relaxed(ASYNC_SW_CLK_EN, (msm_spss_dev.base + PSCBC_BUS_REG));
writel_relaxed(ASYNC_SW_CLK_EN, (msm_spss_dev.base + PSCBC_GENI_REG));
clk_disable_unprepare(msm_spss_dev.clk);
return 0;
err_clk_en:
err_of_plat_pop:
iounmap(msm_spss_dev.base);
err_ioremap:
err_res:
clk_put(msm_spss_dev.clk);
err_clk_get:
return rc;
}
static int __exit msm_spss_remove(struct platform_device *pdev)
{
if (msm_spss_dev.base)
iounmap(msm_spss_dev.base);
if (msm_spss_dev.clk)
clk_put(msm_spss_dev.clk);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int msm_spss_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
int rc;
u32 val;
rc = clk_prepare_enable(msm_spss_dev.clk);
if (rc) {
dev_err(&pdev->dev, "ahb clk enable failed %d\n", rc);
return rc;
}
val = readl_relaxed(msm_spss_dev.base + CLOCK_CONTROL_REG);
val &= ~ACTIVE_MODE;
val |= STANDBY_MODE;
writel_relaxed(val, (msm_spss_dev.base + CLOCK_CONTROL_REG));
wmb();
clk_disable_unprepare(msm_spss_dev.clk);
return 0;
}
static int msm_spss_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
int rc;
u32 val;
rc = clk_prepare_enable(msm_spss_dev.clk);
if (rc) {
dev_err(&pdev->dev, "ahb clk enable failed %d\n", rc);
return rc;
}
val = readl_relaxed(msm_spss_dev.base + CLOCK_CONTROL_REG);
val &= ~STANDBY_MODE;
val |= ACTIVE_MODE;
writel_relaxed(val, (msm_spss_dev.base + CLOCK_CONTROL_REG));
wmb();
clk_disable_unprepare(msm_spss_dev.clk);
return 0;
}
#endif /* CONFIG_PM_SLEEP */
static const struct dev_pm_ops msm_spss_dev_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(
msm_spss_suspend,
msm_spss_resume
)
};
static struct of_device_id msm_spss_match[] = {
{ .compatible = "qcom,msm-spss",
},
{}
};
static struct platform_driver msm_spss_driver = {
.probe = msm_spss_probe,
.remove = msm_spss_remove,
.driver = {
.name = "msm_spss",
.owner = THIS_MODULE,
.pm = &msm_spss_dev_pm_ops,
.of_match_table = msm_spss_match,
},
};
static int __init spss_init(void)
{
return platform_driver_register(&msm_spss_driver);
}
static void __exit spss_exit(void)
{
platform_driver_unregister(&msm_spss_driver);
}
module_init(spss_init);
module_exit(spss_exit);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
changbindu/linux-ok6410 | drivers/net/mii.c | 1156 | 12617 | /*
mii.c: MII interface library
Maintained by Jeff Garzik <jgarzik@pobox.com>
Copyright 2001,2002 Jeff Garzik
Various code came from myson803.c and other files by
Donald Becker. Copyright:
Written 1998-2002 by Donald Becker.
This software may be used and distributed according
to the terms of the GNU General Public License (GPL),
incorporated herein by reference. Drivers based on
or derived from this code fall under the GPL and must
retain the authorship, copyright and license notice.
This file is not a complete program and may only be
used when the entire operating system is licensed
under the GPL.
The author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
static u32 mii_get_an(struct mii_if_info *mii, u16 addr)
{
int advert;
advert = mii->mdio_read(mii->dev, mii->phy_id, addr);
return mii_lpa_to_ethtool_lpa_t(advert);
}
/**
* mii_ethtool_gset - get settings that are specified in @ecmd
* @mii: MII interface
* @ecmd: requested ethtool_cmd
*
* The @ecmd parameter is expected to have been cleared before calling
* mii_ethtool_gset().
*
* Returns 0 for success, negative on error.
*/
int mii_ethtool_gset(struct mii_if_info *mii, struct ethtool_cmd *ecmd)
{
struct net_device *dev = mii->dev;
u16 bmcr, bmsr, ctrl1000 = 0, stat1000 = 0;
u32 nego;
ecmd->supported =
(SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
SUPPORTED_Autoneg | SUPPORTED_TP | SUPPORTED_MII);
if (mii->supports_gmii)
ecmd->supported |= SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full;
/* only supports twisted-pair */
ecmd->port = PORT_MII;
/* only supports internal transceiver */
ecmd->transceiver = XCVR_INTERNAL;
/* this isn't fully supported at higher layers */
ecmd->phy_address = mii->phy_id;
ecmd->mdio_support = ETH_MDIO_SUPPORTS_C22;
ecmd->advertising = ADVERTISED_TP | ADVERTISED_MII;
bmcr = mii->mdio_read(dev, mii->phy_id, MII_BMCR);
bmsr = mii->mdio_read(dev, mii->phy_id, MII_BMSR);
if (mii->supports_gmii) {
ctrl1000 = mii->mdio_read(dev, mii->phy_id, MII_CTRL1000);
stat1000 = mii->mdio_read(dev, mii->phy_id, MII_STAT1000);
}
if (bmcr & BMCR_ANENABLE) {
ecmd->advertising |= ADVERTISED_Autoneg;
ecmd->autoneg = AUTONEG_ENABLE;
ecmd->advertising |= mii_get_an(mii, MII_ADVERTISE);
if (mii->supports_gmii)
ecmd->advertising |=
mii_ctrl1000_to_ethtool_adv_t(ctrl1000);
if (bmsr & BMSR_ANEGCOMPLETE) {
ecmd->lp_advertising = mii_get_an(mii, MII_LPA);
ecmd->lp_advertising |=
mii_stat1000_to_ethtool_lpa_t(stat1000);
} else {
ecmd->lp_advertising = 0;
}
nego = ecmd->advertising & ecmd->lp_advertising;
if (nego & (ADVERTISED_1000baseT_Full |
ADVERTISED_1000baseT_Half)) {
ethtool_cmd_speed_set(ecmd, SPEED_1000);
ecmd->duplex = !!(nego & ADVERTISED_1000baseT_Full);
} else if (nego & (ADVERTISED_100baseT_Full |
ADVERTISED_100baseT_Half)) {
ethtool_cmd_speed_set(ecmd, SPEED_100);
ecmd->duplex = !!(nego & ADVERTISED_100baseT_Full);
} else {
ethtool_cmd_speed_set(ecmd, SPEED_10);
ecmd->duplex = !!(nego & ADVERTISED_10baseT_Full);
}
} else {
ecmd->autoneg = AUTONEG_DISABLE;
ethtool_cmd_speed_set(ecmd,
((bmcr & BMCR_SPEED1000 &&
(bmcr & BMCR_SPEED100) == 0) ?
SPEED_1000 :
((bmcr & BMCR_SPEED100) ?
SPEED_100 : SPEED_10)));
ecmd->duplex = (bmcr & BMCR_FULLDPLX) ? DUPLEX_FULL : DUPLEX_HALF;
}
mii->full_duplex = ecmd->duplex;
/* ignore maxtxpkt, maxrxpkt for now */
return 0;
}
/**
* mii_ethtool_sset - set settings that are specified in @ecmd
* @mii: MII interface
* @ecmd: requested ethtool_cmd
*
* Returns 0 for success, negative on error.
*/
int mii_ethtool_sset(struct mii_if_info *mii, struct ethtool_cmd *ecmd)
{
struct net_device *dev = mii->dev;
u32 speed = ethtool_cmd_speed(ecmd);
if (speed != SPEED_10 &&
speed != SPEED_100 &&
speed != SPEED_1000)
return -EINVAL;
if (ecmd->duplex != DUPLEX_HALF && ecmd->duplex != DUPLEX_FULL)
return -EINVAL;
if (ecmd->port != PORT_MII)
return -EINVAL;
if (ecmd->transceiver != XCVR_INTERNAL)
return -EINVAL;
if (ecmd->phy_address != mii->phy_id)
return -EINVAL;
if (ecmd->autoneg != AUTONEG_DISABLE && ecmd->autoneg != AUTONEG_ENABLE)
return -EINVAL;
if ((speed == SPEED_1000) && (!mii->supports_gmii))
return -EINVAL;
/* ignore supported, maxtxpkt, maxrxpkt */
if (ecmd->autoneg == AUTONEG_ENABLE) {
u32 bmcr, advert, tmp;
u32 advert2 = 0, tmp2 = 0;
if ((ecmd->advertising & (ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full)) == 0)
return -EINVAL;
/* advertise only what has been requested */
advert = mii->mdio_read(dev, mii->phy_id, MII_ADVERTISE);
tmp = advert & ~(ADVERTISE_ALL | ADVERTISE_100BASE4);
if (mii->supports_gmii) {
advert2 = mii->mdio_read(dev, mii->phy_id, MII_CTRL1000);
tmp2 = advert2 & ~(ADVERTISE_1000HALF | ADVERTISE_1000FULL);
}
tmp |= ethtool_adv_to_mii_adv_t(ecmd->advertising);
if (mii->supports_gmii)
tmp2 |=
ethtool_adv_to_mii_ctrl1000_t(ecmd->advertising);
if (advert != tmp) {
mii->mdio_write(dev, mii->phy_id, MII_ADVERTISE, tmp);
mii->advertising = tmp;
}
if ((mii->supports_gmii) && (advert2 != tmp2))
mii->mdio_write(dev, mii->phy_id, MII_CTRL1000, tmp2);
/* turn on autonegotiation, and force a renegotiate */
bmcr = mii->mdio_read(dev, mii->phy_id, MII_BMCR);
bmcr |= (BMCR_ANENABLE | BMCR_ANRESTART);
mii->mdio_write(dev, mii->phy_id, MII_BMCR, bmcr);
mii->force_media = 0;
} else {
u32 bmcr, tmp;
/* turn off auto negotiation, set speed and duplexity */
bmcr = mii->mdio_read(dev, mii->phy_id, MII_BMCR);
tmp = bmcr & ~(BMCR_ANENABLE | BMCR_SPEED100 |
BMCR_SPEED1000 | BMCR_FULLDPLX);
if (speed == SPEED_1000)
tmp |= BMCR_SPEED1000;
else if (speed == SPEED_100)
tmp |= BMCR_SPEED100;
if (ecmd->duplex == DUPLEX_FULL) {
tmp |= BMCR_FULLDPLX;
mii->full_duplex = 1;
} else
mii->full_duplex = 0;
if (bmcr != tmp)
mii->mdio_write(dev, mii->phy_id, MII_BMCR, tmp);
mii->force_media = 1;
}
return 0;
}
/**
* mii_check_gmii_support - check if the MII supports Gb interfaces
* @mii: the MII interface
*/
int mii_check_gmii_support(struct mii_if_info *mii)
{
int reg;
reg = mii->mdio_read(mii->dev, mii->phy_id, MII_BMSR);
if (reg & BMSR_ESTATEN) {
reg = mii->mdio_read(mii->dev, mii->phy_id, MII_ESTATUS);
if (reg & (ESTATUS_1000_TFULL | ESTATUS_1000_THALF))
return 1;
}
return 0;
}
/**
* mii_link_ok - is link status up/ok
* @mii: the MII interface
*
* Returns 1 if the MII reports link status up/ok, 0 otherwise.
*/
int mii_link_ok (struct mii_if_info *mii)
{
/* first, a dummy read, needed to latch some MII phys */
mii->mdio_read(mii->dev, mii->phy_id, MII_BMSR);
if (mii->mdio_read(mii->dev, mii->phy_id, MII_BMSR) & BMSR_LSTATUS)
return 1;
return 0;
}
/**
* mii_nway_restart - restart NWay (autonegotiation) for this interface
* @mii: the MII interface
*
* Returns 0 on success, negative on error.
*/
int mii_nway_restart (struct mii_if_info *mii)
{
int bmcr;
int r = -EINVAL;
/* if autoneg is off, it's an error */
bmcr = mii->mdio_read(mii->dev, mii->phy_id, MII_BMCR);
if (bmcr & BMCR_ANENABLE) {
bmcr |= BMCR_ANRESTART;
mii->mdio_write(mii->dev, mii->phy_id, MII_BMCR, bmcr);
r = 0;
}
return r;
}
/**
* mii_check_link - check MII link status
* @mii: MII interface
*
* If the link status changed (previous != current), call
* netif_carrier_on() if current link status is Up or call
* netif_carrier_off() if current link status is Down.
*/
void mii_check_link (struct mii_if_info *mii)
{
int cur_link = mii_link_ok(mii);
int prev_link = netif_carrier_ok(mii->dev);
if (cur_link && !prev_link)
netif_carrier_on(mii->dev);
else if (prev_link && !cur_link)
netif_carrier_off(mii->dev);
}
/**
* mii_check_media - check the MII interface for a carrier/speed/duplex change
* @mii: the MII interface
* @ok_to_print: OK to print link up/down messages
* @init_media: OK to save duplex mode in @mii
*
* Returns 1 if the duplex mode changed, 0 if not.
* If the media type is forced, always returns 0.
*/
unsigned int mii_check_media (struct mii_if_info *mii,
unsigned int ok_to_print,
unsigned int init_media)
{
unsigned int old_carrier, new_carrier;
int advertise, lpa, media, duplex;
int lpa2 = 0;
/* check current and old link status */
old_carrier = netif_carrier_ok(mii->dev) ? 1 : 0;
new_carrier = (unsigned int) mii_link_ok(mii);
/* if carrier state did not change, this is a "bounce",
* just exit as everything is already set correctly
*/
if ((!init_media) && (old_carrier == new_carrier))
return 0; /* duplex did not change */
/* no carrier, nothing much to do */
if (!new_carrier) {
netif_carrier_off(mii->dev);
if (ok_to_print)
netdev_info(mii->dev, "link down\n");
return 0; /* duplex did not change */
}
/*
* we have carrier, see who's on the other end
*/
netif_carrier_on(mii->dev);
if (mii->force_media) {
if (ok_to_print)
netdev_info(mii->dev, "link up\n");
return 0; /* duplex did not change */
}
/* get MII advertise and LPA values */
if ((!init_media) && (mii->advertising))
advertise = mii->advertising;
else {
advertise = mii->mdio_read(mii->dev, mii->phy_id, MII_ADVERTISE);
mii->advertising = advertise;
}
lpa = mii->mdio_read(mii->dev, mii->phy_id, MII_LPA);
if (mii->supports_gmii)
lpa2 = mii->mdio_read(mii->dev, mii->phy_id, MII_STAT1000);
/* figure out media and duplex from advertise and LPA values */
media = mii_nway_result(lpa & advertise);
duplex = (media & ADVERTISE_FULL) ? 1 : 0;
if (lpa2 & LPA_1000FULL)
duplex = 1;
if (ok_to_print)
netdev_info(mii->dev, "link up, %uMbps, %s-duplex, lpa 0x%04X\n",
lpa2 & (LPA_1000FULL | LPA_1000HALF) ? 1000 :
media & (ADVERTISE_100FULL | ADVERTISE_100HALF) ?
100 : 10,
duplex ? "full" : "half",
lpa);
if ((init_media) || (mii->full_duplex != duplex)) {
mii->full_duplex = duplex;
return 1; /* duplex changed */
}
return 0; /* duplex did not change */
}
/**
* generic_mii_ioctl - main MII ioctl interface
* @mii_if: the MII interface
* @mii_data: MII ioctl data structure
* @cmd: MII ioctl command
* @duplex_chg_out: pointer to @duplex_changed status if there was no
* ioctl error
*
* Returns 0 on success, negative on error.
*/
int generic_mii_ioctl(struct mii_if_info *mii_if,
struct mii_ioctl_data *mii_data, int cmd,
unsigned int *duplex_chg_out)
{
int rc = 0;
unsigned int duplex_changed = 0;
if (duplex_chg_out)
*duplex_chg_out = 0;
mii_data->phy_id &= mii_if->phy_id_mask;
mii_data->reg_num &= mii_if->reg_num_mask;
switch(cmd) {
case SIOCGMIIPHY:
mii_data->phy_id = mii_if->phy_id;
/* fall through */
case SIOCGMIIREG:
mii_data->val_out =
mii_if->mdio_read(mii_if->dev, mii_data->phy_id,
mii_data->reg_num);
break;
case SIOCSMIIREG: {
u16 val = mii_data->val_in;
if (mii_data->phy_id == mii_if->phy_id) {
switch(mii_data->reg_num) {
case MII_BMCR: {
unsigned int new_duplex = 0;
if (val & (BMCR_RESET|BMCR_ANENABLE))
mii_if->force_media = 0;
else
mii_if->force_media = 1;
if (mii_if->force_media &&
(val & BMCR_FULLDPLX))
new_duplex = 1;
if (mii_if->full_duplex != new_duplex) {
duplex_changed = 1;
mii_if->full_duplex = new_duplex;
}
break;
}
case MII_ADVERTISE:
mii_if->advertising = val;
break;
default:
/* do nothing */
break;
}
}
mii_if->mdio_write(mii_if->dev, mii_data->phy_id,
mii_data->reg_num, val);
break;
}
default:
rc = -EOPNOTSUPP;
break;
}
if ((rc == 0) && (duplex_chg_out) && (duplex_changed))
*duplex_chg_out = 1;
return rc;
}
MODULE_AUTHOR ("Jeff Garzik <jgarzik@pobox.com>");
MODULE_DESCRIPTION ("MII hardware support library");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(mii_link_ok);
EXPORT_SYMBOL(mii_nway_restart);
EXPORT_SYMBOL(mii_ethtool_gset);
EXPORT_SYMBOL(mii_ethtool_sset);
EXPORT_SYMBOL(mii_check_link);
EXPORT_SYMBOL(mii_check_media);
EXPORT_SYMBOL(mii_check_gmii_support);
EXPORT_SYMBOL(generic_mii_ioctl);
| gpl-2.0 |
abyssxsy/linux-tk1 | drivers/dma/pl330.c | 1668 | 69222 | /*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Copyright (C) 2010 Samsung Electronics Co. Ltd.
* Jaswinder Singh <jassi.brar@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/amba/bus.h>
#include <linux/amba/pl330.h>
#include <linux/scatterlist.h>
#include <linux/of.h>
#include <linux/of_dma.h>
#include <linux/err.h>
#include "dmaengine.h"
#define PL330_MAX_CHAN 8
#define PL330_MAX_IRQS 32
#define PL330_MAX_PERI 32
enum pl330_srccachectrl {
SCCTRL0, /* Noncacheable and nonbufferable */
SCCTRL1, /* Bufferable only */
SCCTRL2, /* Cacheable, but do not allocate */
SCCTRL3, /* Cacheable and bufferable, but do not allocate */
SINVALID1,
SINVALID2,
SCCTRL6, /* Cacheable write-through, allocate on reads only */
SCCTRL7, /* Cacheable write-back, allocate on reads only */
};
enum pl330_dstcachectrl {
DCCTRL0, /* Noncacheable and nonbufferable */
DCCTRL1, /* Bufferable only */
DCCTRL2, /* Cacheable, but do not allocate */
DCCTRL3, /* Cacheable and bufferable, but do not allocate */
DINVALID1, /* AWCACHE = 0x1000 */
DINVALID2,
DCCTRL6, /* Cacheable write-through, allocate on writes only */
DCCTRL7, /* Cacheable write-back, allocate on writes only */
};
enum pl330_byteswap {
SWAP_NO,
SWAP_2,
SWAP_4,
SWAP_8,
SWAP_16,
};
enum pl330_reqtype {
MEMTOMEM,
MEMTODEV,
DEVTOMEM,
DEVTODEV,
};
/* Register and Bit field Definitions */
#define DS 0x0
#define DS_ST_STOP 0x0
#define DS_ST_EXEC 0x1
#define DS_ST_CMISS 0x2
#define DS_ST_UPDTPC 0x3
#define DS_ST_WFE 0x4
#define DS_ST_ATBRR 0x5
#define DS_ST_QBUSY 0x6
#define DS_ST_WFP 0x7
#define DS_ST_KILL 0x8
#define DS_ST_CMPLT 0x9
#define DS_ST_FLTCMP 0xe
#define DS_ST_FAULT 0xf
#define DPC 0x4
#define INTEN 0x20
#define ES 0x24
#define INTSTATUS 0x28
#define INTCLR 0x2c
#define FSM 0x30
#define FSC 0x34
#define FTM 0x38
#define _FTC 0x40
#define FTC(n) (_FTC + (n)*0x4)
#define _CS 0x100
#define CS(n) (_CS + (n)*0x8)
#define CS_CNS (1 << 21)
#define _CPC 0x104
#define CPC(n) (_CPC + (n)*0x8)
#define _SA 0x400
#define SA(n) (_SA + (n)*0x20)
#define _DA 0x404
#define DA(n) (_DA + (n)*0x20)
#define _CC 0x408
#define CC(n) (_CC + (n)*0x20)
#define CC_SRCINC (1 << 0)
#define CC_DSTINC (1 << 14)
#define CC_SRCPRI (1 << 8)
#define CC_DSTPRI (1 << 22)
#define CC_SRCNS (1 << 9)
#define CC_DSTNS (1 << 23)
#define CC_SRCIA (1 << 10)
#define CC_DSTIA (1 << 24)
#define CC_SRCBRSTLEN_SHFT 4
#define CC_DSTBRSTLEN_SHFT 18
#define CC_SRCBRSTSIZE_SHFT 1
#define CC_DSTBRSTSIZE_SHFT 15
#define CC_SRCCCTRL_SHFT 11
#define CC_SRCCCTRL_MASK 0x7
#define CC_DSTCCTRL_SHFT 25
#define CC_DRCCCTRL_MASK 0x7
#define CC_SWAP_SHFT 28
#define _LC0 0x40c
#define LC0(n) (_LC0 + (n)*0x20)
#define _LC1 0x410
#define LC1(n) (_LC1 + (n)*0x20)
#define DBGSTATUS 0xd00
#define DBG_BUSY (1 << 0)
#define DBGCMD 0xd04
#define DBGINST0 0xd08
#define DBGINST1 0xd0c
#define CR0 0xe00
#define CR1 0xe04
#define CR2 0xe08
#define CR3 0xe0c
#define CR4 0xe10
#define CRD 0xe14
#define PERIPH_ID 0xfe0
#define PERIPH_REV_SHIFT 20
#define PERIPH_REV_MASK 0xf
#define PERIPH_REV_R0P0 0
#define PERIPH_REV_R1P0 1
#define PERIPH_REV_R1P1 2
#define PCELL_ID 0xff0
#define CR0_PERIPH_REQ_SET (1 << 0)
#define CR0_BOOT_EN_SET (1 << 1)
#define CR0_BOOT_MAN_NS (1 << 2)
#define CR0_NUM_CHANS_SHIFT 4
#define CR0_NUM_CHANS_MASK 0x7
#define CR0_NUM_PERIPH_SHIFT 12
#define CR0_NUM_PERIPH_MASK 0x1f
#define CR0_NUM_EVENTS_SHIFT 17
#define CR0_NUM_EVENTS_MASK 0x1f
#define CR1_ICACHE_LEN_SHIFT 0
#define CR1_ICACHE_LEN_MASK 0x7
#define CR1_NUM_ICACHELINES_SHIFT 4
#define CR1_NUM_ICACHELINES_MASK 0xf
#define CRD_DATA_WIDTH_SHIFT 0
#define CRD_DATA_WIDTH_MASK 0x7
#define CRD_WR_CAP_SHIFT 4
#define CRD_WR_CAP_MASK 0x7
#define CRD_WR_Q_DEP_SHIFT 8
#define CRD_WR_Q_DEP_MASK 0xf
#define CRD_RD_CAP_SHIFT 12
#define CRD_RD_CAP_MASK 0x7
#define CRD_RD_Q_DEP_SHIFT 16
#define CRD_RD_Q_DEP_MASK 0xf
#define CRD_DATA_BUFF_SHIFT 20
#define CRD_DATA_BUFF_MASK 0x3ff
#define PART 0x330
#define DESIGNER 0x41
#define REVISION 0x0
#define INTEG_CFG 0x0
#define PERIPH_ID_VAL ((PART << 0) | (DESIGNER << 12))
#define PCELL_ID_VAL 0xb105f00d
#define PL330_STATE_STOPPED (1 << 0)
#define PL330_STATE_EXECUTING (1 << 1)
#define PL330_STATE_WFE (1 << 2)
#define PL330_STATE_FAULTING (1 << 3)
#define PL330_STATE_COMPLETING (1 << 4)
#define PL330_STATE_WFP (1 << 5)
#define PL330_STATE_KILLING (1 << 6)
#define PL330_STATE_FAULT_COMPLETING (1 << 7)
#define PL330_STATE_CACHEMISS (1 << 8)
#define PL330_STATE_UPDTPC (1 << 9)
#define PL330_STATE_ATBARRIER (1 << 10)
#define PL330_STATE_QUEUEBUSY (1 << 11)
#define PL330_STATE_INVALID (1 << 15)
#define PL330_STABLE_STATES (PL330_STATE_STOPPED | PL330_STATE_EXECUTING \
| PL330_STATE_WFE | PL330_STATE_FAULTING)
#define CMD_DMAADDH 0x54
#define CMD_DMAEND 0x00
#define CMD_DMAFLUSHP 0x35
#define CMD_DMAGO 0xa0
#define CMD_DMALD 0x04
#define CMD_DMALDP 0x25
#define CMD_DMALP 0x20
#define CMD_DMALPEND 0x28
#define CMD_DMAKILL 0x01
#define CMD_DMAMOV 0xbc
#define CMD_DMANOP 0x18
#define CMD_DMARMB 0x12
#define CMD_DMASEV 0x34
#define CMD_DMAST 0x08
#define CMD_DMASTP 0x29
#define CMD_DMASTZ 0x0c
#define CMD_DMAWFE 0x36
#define CMD_DMAWFP 0x30
#define CMD_DMAWMB 0x13
#define SZ_DMAADDH 3
#define SZ_DMAEND 1
#define SZ_DMAFLUSHP 2
#define SZ_DMALD 1
#define SZ_DMALDP 2
#define SZ_DMALP 2
#define SZ_DMALPEND 2
#define SZ_DMAKILL 1
#define SZ_DMAMOV 6
#define SZ_DMANOP 1
#define SZ_DMARMB 1
#define SZ_DMASEV 2
#define SZ_DMAST 1
#define SZ_DMASTP 2
#define SZ_DMASTZ 1
#define SZ_DMAWFE 2
#define SZ_DMAWFP 2
#define SZ_DMAWMB 1
#define SZ_DMAGO 6
#define BRST_LEN(ccr) ((((ccr) >> CC_SRCBRSTLEN_SHFT) & 0xf) + 1)
#define BRST_SIZE(ccr) (1 << (((ccr) >> CC_SRCBRSTSIZE_SHFT) & 0x7))
#define BYTE_TO_BURST(b, ccr) ((b) / BRST_SIZE(ccr) / BRST_LEN(ccr))
#define BURST_TO_BYTE(c, ccr) ((c) * BRST_SIZE(ccr) * BRST_LEN(ccr))
/*
* With 256 bytes, we can do more than 2.5MB and 5MB xfers per req
* at 1byte/burst for P<->M and M<->M respectively.
* For typical scenario, at 1word/burst, 10MB and 20MB xfers per req
* should be enough for P<->M and M<->M respectively.
*/
#define MCODE_BUFF_PER_REQ 256
/* If the _pl330_req is available to the client */
#define IS_FREE(req) (*((u8 *)((req)->mc_cpu)) == CMD_DMAEND)
/* Use this _only_ to wait on transient states */
#define UNTIL(t, s) while (!(_state(t) & (s))) cpu_relax();
#ifdef PL330_DEBUG_MCGEN
static unsigned cmd_line;
#define PL330_DBGCMD_DUMP(off, x...) do { \
printk("%x:", cmd_line); \
printk(x); \
cmd_line += off; \
} while (0)
#define PL330_DBGMC_START(addr) (cmd_line = addr)
#else
#define PL330_DBGCMD_DUMP(off, x...) do {} while (0)
#define PL330_DBGMC_START(addr) do {} while (0)
#endif
/* The number of default descriptors */
#define NR_DEFAULT_DESC 16
/* Populated by the PL330 core driver for DMA API driver's info */
struct pl330_config {
u32 periph_id;
u32 pcell_id;
#define DMAC_MODE_NS (1 << 0)
unsigned int mode;
unsigned int data_bus_width:10; /* In number of bits */
unsigned int data_buf_dep:10;
unsigned int num_chan:4;
unsigned int num_peri:6;
u32 peri_ns;
unsigned int num_events:6;
u32 irq_ns;
};
/* Handle to the DMAC provided to the PL330 core */
struct pl330_info {
/* Owning device */
struct device *dev;
/* Size of MicroCode buffers for each channel. */
unsigned mcbufsz;
/* ioremap'ed address of PL330 registers. */
void __iomem *base;
/* Client can freely use it. */
void *client_data;
/* PL330 core data, Client must not touch it. */
void *pl330_data;
/* Populated by the PL330 core driver during pl330_add */
struct pl330_config pcfg;
/*
* If the DMAC has some reset mechanism, then the
* client may want to provide pointer to the method.
*/
void (*dmac_reset)(struct pl330_info *pi);
};
/**
* Request Configuration.
* The PL330 core does not modify this and uses the last
* working configuration if the request doesn't provide any.
*
* The Client may want to provide this info only for the
* first request and a request with new settings.
*/
struct pl330_reqcfg {
/* Address Incrementing */
unsigned dst_inc:1;
unsigned src_inc:1;
/*
* For now, the SRC & DST protection levels
* and burst size/length are assumed same.
*/
bool nonsecure;
bool privileged;
bool insnaccess;
unsigned brst_len:5;
unsigned brst_size:3; /* in power of 2 */
enum pl330_dstcachectrl dcctl;
enum pl330_srccachectrl scctl;
enum pl330_byteswap swap;
struct pl330_config *pcfg;
};
/*
* One cycle of DMAC operation.
* There may be more than one xfer in a request.
*/
struct pl330_xfer {
u32 src_addr;
u32 dst_addr;
/* Size to xfer */
u32 bytes;
/*
* Pointer to next xfer in the list.
* The last xfer in the req must point to NULL.
*/
struct pl330_xfer *next;
};
/* The xfer callbacks are made with one of these arguments. */
enum pl330_op_err {
/* The all xfers in the request were success. */
PL330_ERR_NONE,
/* If req aborted due to global error. */
PL330_ERR_ABORT,
/* If req failed due to problem with Channel. */
PL330_ERR_FAIL,
};
/* A request defining Scatter-Gather List ending with NULL xfer. */
struct pl330_req {
enum pl330_reqtype rqtype;
/* Index of peripheral for the xfer. */
unsigned peri:5;
/* Unique token for this xfer, set by the client. */
void *token;
/* Callback to be called after xfer. */
void (*xfer_cb)(void *token, enum pl330_op_err err);
/* If NULL, req will be done at last set parameters. */
struct pl330_reqcfg *cfg;
/* Pointer to first xfer in the request. */
struct pl330_xfer *x;
/* Hook to attach to DMAC's list of reqs with due callback */
struct list_head rqd;
};
/*
* To know the status of the channel and DMAC, the client
* provides a pointer to this structure. The PL330 core
* fills it with current information.
*/
struct pl330_chanstatus {
/*
* If the DMAC engine halted due to some error,
* the client should remove-add DMAC.
*/
bool dmac_halted;
/*
* If channel is halted due to some error,
* the client should ABORT/FLUSH and START the channel.
*/
bool faulting;
/* Location of last load */
u32 src_addr;
/* Location of last store */
u32 dst_addr;
/*
* Pointer to the currently active req, NULL if channel is
* inactive, even though the requests may be present.
*/
struct pl330_req *top_req;
/* Pointer to req waiting second in the queue if any. */
struct pl330_req *wait_req;
};
enum pl330_chan_op {
/* Start the channel */
PL330_OP_START,
/* Abort the active xfer */
PL330_OP_ABORT,
/* Stop xfer and flush queue */
PL330_OP_FLUSH,
};
struct _xfer_spec {
u32 ccr;
struct pl330_req *r;
struct pl330_xfer *x;
};
enum dmamov_dst {
SAR = 0,
CCR,
DAR,
};
enum pl330_dst {
SRC = 0,
DST,
};
enum pl330_cond {
SINGLE,
BURST,
ALWAYS,
};
struct _pl330_req {
u32 mc_bus;
void *mc_cpu;
/* Number of bytes taken to setup MC for the req */
u32 mc_len;
struct pl330_req *r;
};
/* ToBeDone for tasklet */
struct _pl330_tbd {
bool reset_dmac;
bool reset_mngr;
u8 reset_chan;
};
/* A DMAC Thread */
struct pl330_thread {
u8 id;
int ev;
/* If the channel is not yet acquired by any client */
bool free;
/* Parent DMAC */
struct pl330_dmac *dmac;
/* Only two at a time */
struct _pl330_req req[2];
/* Index of the last enqueued request */
unsigned lstenq;
/* Index of the last submitted request or -1 if the DMA is stopped */
int req_running;
};
enum pl330_dmac_state {
UNINIT,
INIT,
DYING,
};
/* A DMAC */
struct pl330_dmac {
spinlock_t lock;
/* Holds list of reqs with due callbacks */
struct list_head req_done;
/* Pointer to platform specific stuff */
struct pl330_info *pinfo;
/* Maximum possible events/irqs */
int events[32];
/* BUS address of MicroCode buffer */
u32 mcode_bus;
/* CPU address of MicroCode buffer */
void *mcode_cpu;
/* List of all Channel threads */
struct pl330_thread *channels;
/* Pointer to the MANAGER thread */
struct pl330_thread *manager;
/* To handle bad news in interrupt */
struct tasklet_struct tasks;
struct _pl330_tbd dmac_tbd;
/* State of DMAC operation */
enum pl330_dmac_state state;
};
enum desc_status {
/* In the DMAC pool */
FREE,
/*
* Allocated to some channel during prep_xxx
* Also may be sitting on the work_list.
*/
PREP,
/*
* Sitting on the work_list and already submitted
* to the PL330 core. Not more than two descriptors
* of a channel can be BUSY at any time.
*/
BUSY,
/*
* Sitting on the channel work_list but xfer done
* by PL330 core
*/
DONE,
};
struct dma_pl330_chan {
/* Schedule desc completion */
struct tasklet_struct task;
/* DMA-Engine Channel */
struct dma_chan chan;
/* List of to be xfered descriptors */
struct list_head work_list;
/* Pointer to the DMAC that manages this channel,
* NULL if the channel is available to be acquired.
* As the parent, this DMAC also provides descriptors
* to the channel.
*/
struct dma_pl330_dmac *dmac;
/* To protect channel manipulation */
spinlock_t lock;
/* Token of a hardware channel thread of PL330 DMAC
* NULL if the channel is available to be acquired.
*/
void *pl330_chid;
/* For D-to-M and M-to-D channels */
int burst_sz; /* the peripheral fifo width */
int burst_len; /* the number of burst */
dma_addr_t fifo_addr;
/* for cyclic capability */
bool cyclic;
};
struct dma_pl330_dmac {
struct pl330_info pif;
/* DMA-Engine Device */
struct dma_device ddma;
/* Pool of descriptors available for the DMAC's channels */
struct list_head desc_pool;
/* To protect desc_pool manipulation */
spinlock_t pool_lock;
/* Peripheral channels connected to this DMAC */
struct dma_pl330_chan *peripherals; /* keep at end */
};
struct dma_pl330_desc {
/* To attach to a queue as child */
struct list_head node;
/* Descriptor for the DMA Engine API */
struct dma_async_tx_descriptor txd;
/* Xfer for PL330 core */
struct pl330_xfer px;
struct pl330_reqcfg rqcfg;
struct pl330_req req;
enum desc_status status;
/* The channel which currently holds this desc */
struct dma_pl330_chan *pchan;
};
struct dma_pl330_filter_args {
struct dma_pl330_dmac *pdmac;
unsigned int chan_id;
};
static inline void _callback(struct pl330_req *r, enum pl330_op_err err)
{
if (r && r->xfer_cb)
r->xfer_cb(r->token, err);
}
static inline bool _queue_empty(struct pl330_thread *thrd)
{
return (IS_FREE(&thrd->req[0]) && IS_FREE(&thrd->req[1]))
? true : false;
}
static inline bool _queue_full(struct pl330_thread *thrd)
{
return (IS_FREE(&thrd->req[0]) || IS_FREE(&thrd->req[1]))
? false : true;
}
static inline bool is_manager(struct pl330_thread *thrd)
{
struct pl330_dmac *pl330 = thrd->dmac;
/* MANAGER is indexed at the end */
if (thrd->id == pl330->pinfo->pcfg.num_chan)
return true;
else
return false;
}
/* If manager of the thread is in Non-Secure mode */
static inline bool _manager_ns(struct pl330_thread *thrd)
{
struct pl330_dmac *pl330 = thrd->dmac;
return (pl330->pinfo->pcfg.mode & DMAC_MODE_NS) ? true : false;
}
static inline u32 get_id(struct pl330_info *pi, u32 off)
{
void __iomem *regs = pi->base;
u32 id = 0;
id |= (readb(regs + off + 0x0) << 0);
id |= (readb(regs + off + 0x4) << 8);
id |= (readb(regs + off + 0x8) << 16);
id |= (readb(regs + off + 0xc) << 24);
return id;
}
static inline u32 get_revision(u32 periph_id)
{
return (periph_id >> PERIPH_REV_SHIFT) & PERIPH_REV_MASK;
}
static inline u32 _emit_ADDH(unsigned dry_run, u8 buf[],
enum pl330_dst da, u16 val)
{
if (dry_run)
return SZ_DMAADDH;
buf[0] = CMD_DMAADDH;
buf[0] |= (da << 1);
*((u16 *)&buf[1]) = val;
PL330_DBGCMD_DUMP(SZ_DMAADDH, "\tDMAADDH %s %u\n",
da == 1 ? "DA" : "SA", val);
return SZ_DMAADDH;
}
static inline u32 _emit_END(unsigned dry_run, u8 buf[])
{
if (dry_run)
return SZ_DMAEND;
buf[0] = CMD_DMAEND;
PL330_DBGCMD_DUMP(SZ_DMAEND, "\tDMAEND\n");
return SZ_DMAEND;
}
static inline u32 _emit_FLUSHP(unsigned dry_run, u8 buf[], u8 peri)
{
if (dry_run)
return SZ_DMAFLUSHP;
buf[0] = CMD_DMAFLUSHP;
peri &= 0x1f;
peri <<= 3;
buf[1] = peri;
PL330_DBGCMD_DUMP(SZ_DMAFLUSHP, "\tDMAFLUSHP %u\n", peri >> 3);
return SZ_DMAFLUSHP;
}
static inline u32 _emit_LD(unsigned dry_run, u8 buf[], enum pl330_cond cond)
{
if (dry_run)
return SZ_DMALD;
buf[0] = CMD_DMALD;
if (cond == SINGLE)
buf[0] |= (0 << 1) | (1 << 0);
else if (cond == BURST)
buf[0] |= (1 << 1) | (1 << 0);
PL330_DBGCMD_DUMP(SZ_DMALD, "\tDMALD%c\n",
cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A'));
return SZ_DMALD;
}
static inline u32 _emit_LDP(unsigned dry_run, u8 buf[],
enum pl330_cond cond, u8 peri)
{
if (dry_run)
return SZ_DMALDP;
buf[0] = CMD_DMALDP;
if (cond == BURST)
buf[0] |= (1 << 1);
peri &= 0x1f;
peri <<= 3;
buf[1] = peri;
PL330_DBGCMD_DUMP(SZ_DMALDP, "\tDMALDP%c %u\n",
cond == SINGLE ? 'S' : 'B', peri >> 3);
return SZ_DMALDP;
}
static inline u32 _emit_LP(unsigned dry_run, u8 buf[],
unsigned loop, u8 cnt)
{
if (dry_run)
return SZ_DMALP;
buf[0] = CMD_DMALP;
if (loop)
buf[0] |= (1 << 1);
cnt--; /* DMAC increments by 1 internally */
buf[1] = cnt;
PL330_DBGCMD_DUMP(SZ_DMALP, "\tDMALP_%c %u\n", loop ? '1' : '0', cnt);
return SZ_DMALP;
}
struct _arg_LPEND {
enum pl330_cond cond;
bool forever;
unsigned loop;
u8 bjump;
};
static inline u32 _emit_LPEND(unsigned dry_run, u8 buf[],
const struct _arg_LPEND *arg)
{
enum pl330_cond cond = arg->cond;
bool forever = arg->forever;
unsigned loop = arg->loop;
u8 bjump = arg->bjump;
if (dry_run)
return SZ_DMALPEND;
buf[0] = CMD_DMALPEND;
if (loop)
buf[0] |= (1 << 2);
if (!forever)
buf[0] |= (1 << 4);
if (cond == SINGLE)
buf[0] |= (0 << 1) | (1 << 0);
else if (cond == BURST)
buf[0] |= (1 << 1) | (1 << 0);
buf[1] = bjump;
PL330_DBGCMD_DUMP(SZ_DMALPEND, "\tDMALP%s%c_%c bjmpto_%x\n",
forever ? "FE" : "END",
cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A'),
loop ? '1' : '0',
bjump);
return SZ_DMALPEND;
}
static inline u32 _emit_KILL(unsigned dry_run, u8 buf[])
{
if (dry_run)
return SZ_DMAKILL;
buf[0] = CMD_DMAKILL;
return SZ_DMAKILL;
}
static inline u32 _emit_MOV(unsigned dry_run, u8 buf[],
enum dmamov_dst dst, u32 val)
{
if (dry_run)
return SZ_DMAMOV;
buf[0] = CMD_DMAMOV;
buf[1] = dst;
*((u32 *)&buf[2]) = val;
PL330_DBGCMD_DUMP(SZ_DMAMOV, "\tDMAMOV %s 0x%x\n",
dst == SAR ? "SAR" : (dst == DAR ? "DAR" : "CCR"), val);
return SZ_DMAMOV;
}
static inline u32 _emit_NOP(unsigned dry_run, u8 buf[])
{
if (dry_run)
return SZ_DMANOP;
buf[0] = CMD_DMANOP;
PL330_DBGCMD_DUMP(SZ_DMANOP, "\tDMANOP\n");
return SZ_DMANOP;
}
static inline u32 _emit_RMB(unsigned dry_run, u8 buf[])
{
if (dry_run)
return SZ_DMARMB;
buf[0] = CMD_DMARMB;
PL330_DBGCMD_DUMP(SZ_DMARMB, "\tDMARMB\n");
return SZ_DMARMB;
}
static inline u32 _emit_SEV(unsigned dry_run, u8 buf[], u8 ev)
{
if (dry_run)
return SZ_DMASEV;
buf[0] = CMD_DMASEV;
ev &= 0x1f;
ev <<= 3;
buf[1] = ev;
PL330_DBGCMD_DUMP(SZ_DMASEV, "\tDMASEV %u\n", ev >> 3);
return SZ_DMASEV;
}
static inline u32 _emit_ST(unsigned dry_run, u8 buf[], enum pl330_cond cond)
{
if (dry_run)
return SZ_DMAST;
buf[0] = CMD_DMAST;
if (cond == SINGLE)
buf[0] |= (0 << 1) | (1 << 0);
else if (cond == BURST)
buf[0] |= (1 << 1) | (1 << 0);
PL330_DBGCMD_DUMP(SZ_DMAST, "\tDMAST%c\n",
cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'A'));
return SZ_DMAST;
}
static inline u32 _emit_STP(unsigned dry_run, u8 buf[],
enum pl330_cond cond, u8 peri)
{
if (dry_run)
return SZ_DMASTP;
buf[0] = CMD_DMASTP;
if (cond == BURST)
buf[0] |= (1 << 1);
peri &= 0x1f;
peri <<= 3;
buf[1] = peri;
PL330_DBGCMD_DUMP(SZ_DMASTP, "\tDMASTP%c %u\n",
cond == SINGLE ? 'S' : 'B', peri >> 3);
return SZ_DMASTP;
}
static inline u32 _emit_STZ(unsigned dry_run, u8 buf[])
{
if (dry_run)
return SZ_DMASTZ;
buf[0] = CMD_DMASTZ;
PL330_DBGCMD_DUMP(SZ_DMASTZ, "\tDMASTZ\n");
return SZ_DMASTZ;
}
static inline u32 _emit_WFE(unsigned dry_run, u8 buf[], u8 ev,
unsigned invalidate)
{
if (dry_run)
return SZ_DMAWFE;
buf[0] = CMD_DMAWFE;
ev &= 0x1f;
ev <<= 3;
buf[1] = ev;
if (invalidate)
buf[1] |= (1 << 1);
PL330_DBGCMD_DUMP(SZ_DMAWFE, "\tDMAWFE %u%s\n",
ev >> 3, invalidate ? ", I" : "");
return SZ_DMAWFE;
}
static inline u32 _emit_WFP(unsigned dry_run, u8 buf[],
enum pl330_cond cond, u8 peri)
{
if (dry_run)
return SZ_DMAWFP;
buf[0] = CMD_DMAWFP;
if (cond == SINGLE)
buf[0] |= (0 << 1) | (0 << 0);
else if (cond == BURST)
buf[0] |= (1 << 1) | (0 << 0);
else
buf[0] |= (0 << 1) | (1 << 0);
peri &= 0x1f;
peri <<= 3;
buf[1] = peri;
PL330_DBGCMD_DUMP(SZ_DMAWFP, "\tDMAWFP%c %u\n",
cond == SINGLE ? 'S' : (cond == BURST ? 'B' : 'P'), peri >> 3);
return SZ_DMAWFP;
}
static inline u32 _emit_WMB(unsigned dry_run, u8 buf[])
{
if (dry_run)
return SZ_DMAWMB;
buf[0] = CMD_DMAWMB;
PL330_DBGCMD_DUMP(SZ_DMAWMB, "\tDMAWMB\n");
return SZ_DMAWMB;
}
struct _arg_GO {
u8 chan;
u32 addr;
unsigned ns;
};
static inline u32 _emit_GO(unsigned dry_run, u8 buf[],
const struct _arg_GO *arg)
{
u8 chan = arg->chan;
u32 addr = arg->addr;
unsigned ns = arg->ns;
if (dry_run)
return SZ_DMAGO;
buf[0] = CMD_DMAGO;
buf[0] |= (ns << 1);
buf[1] = chan & 0x7;
*((u32 *)&buf[2]) = addr;
return SZ_DMAGO;
}
#define msecs_to_loops(t) (loops_per_jiffy / 1000 * HZ * t)
/* Returns Time-Out */
static bool _until_dmac_idle(struct pl330_thread *thrd)
{
void __iomem *regs = thrd->dmac->pinfo->base;
unsigned long loops = msecs_to_loops(5);
do {
/* Until Manager is Idle */
if (!(readl(regs + DBGSTATUS) & DBG_BUSY))
break;
cpu_relax();
} while (--loops);
if (!loops)
return true;
return false;
}
static inline void _execute_DBGINSN(struct pl330_thread *thrd,
u8 insn[], bool as_manager)
{
void __iomem *regs = thrd->dmac->pinfo->base;
u32 val;
val = (insn[0] << 16) | (insn[1] << 24);
if (!as_manager) {
val |= (1 << 0);
val |= (thrd->id << 8); /* Channel Number */
}
writel(val, regs + DBGINST0);
val = *((u32 *)&insn[2]);
writel(val, regs + DBGINST1);
/* If timed out due to halted state-machine */
if (_until_dmac_idle(thrd)) {
dev_err(thrd->dmac->pinfo->dev, "DMAC halted!\n");
return;
}
/* Get going */
writel(0, regs + DBGCMD);
}
/*
* Mark a _pl330_req as free.
* We do it by writing DMAEND as the first instruction
* because no valid request is going to have DMAEND as
* its first instruction to execute.
*/
static void mark_free(struct pl330_thread *thrd, int idx)
{
struct _pl330_req *req = &thrd->req[idx];
_emit_END(0, req->mc_cpu);
req->mc_len = 0;
thrd->req_running = -1;
}
static inline u32 _state(struct pl330_thread *thrd)
{
void __iomem *regs = thrd->dmac->pinfo->base;
u32 val;
if (is_manager(thrd))
val = readl(regs + DS) & 0xf;
else
val = readl(regs + CS(thrd->id)) & 0xf;
switch (val) {
case DS_ST_STOP:
return PL330_STATE_STOPPED;
case DS_ST_EXEC:
return PL330_STATE_EXECUTING;
case DS_ST_CMISS:
return PL330_STATE_CACHEMISS;
case DS_ST_UPDTPC:
return PL330_STATE_UPDTPC;
case DS_ST_WFE:
return PL330_STATE_WFE;
case DS_ST_FAULT:
return PL330_STATE_FAULTING;
case DS_ST_ATBRR:
if (is_manager(thrd))
return PL330_STATE_INVALID;
else
return PL330_STATE_ATBARRIER;
case DS_ST_QBUSY:
if (is_manager(thrd))
return PL330_STATE_INVALID;
else
return PL330_STATE_QUEUEBUSY;
case DS_ST_WFP:
if (is_manager(thrd))
return PL330_STATE_INVALID;
else
return PL330_STATE_WFP;
case DS_ST_KILL:
if (is_manager(thrd))
return PL330_STATE_INVALID;
else
return PL330_STATE_KILLING;
case DS_ST_CMPLT:
if (is_manager(thrd))
return PL330_STATE_INVALID;
else
return PL330_STATE_COMPLETING;
case DS_ST_FLTCMP:
if (is_manager(thrd))
return PL330_STATE_INVALID;
else
return PL330_STATE_FAULT_COMPLETING;
default:
return PL330_STATE_INVALID;
}
}
static void _stop(struct pl330_thread *thrd)
{
void __iomem *regs = thrd->dmac->pinfo->base;
u8 insn[6] = {0, 0, 0, 0, 0, 0};
if (_state(thrd) == PL330_STATE_FAULT_COMPLETING)
UNTIL(thrd, PL330_STATE_FAULTING | PL330_STATE_KILLING);
/* Return if nothing needs to be done */
if (_state(thrd) == PL330_STATE_COMPLETING
|| _state(thrd) == PL330_STATE_KILLING
|| _state(thrd) == PL330_STATE_STOPPED)
return;
_emit_KILL(0, insn);
/* Stop generating interrupts for SEV */
writel(readl(regs + INTEN) & ~(1 << thrd->ev), regs + INTEN);
_execute_DBGINSN(thrd, insn, is_manager(thrd));
}
/* Start doing req 'idx' of thread 'thrd' */
static bool _trigger(struct pl330_thread *thrd)
{
void __iomem *regs = thrd->dmac->pinfo->base;
struct _pl330_req *req;
struct pl330_req *r;
struct _arg_GO go;
unsigned ns;
u8 insn[6] = {0, 0, 0, 0, 0, 0};
int idx;
/* Return if already ACTIVE */
if (_state(thrd) != PL330_STATE_STOPPED)
return true;
idx = 1 - thrd->lstenq;
if (!IS_FREE(&thrd->req[idx]))
req = &thrd->req[idx];
else {
idx = thrd->lstenq;
if (!IS_FREE(&thrd->req[idx]))
req = &thrd->req[idx];
else
req = NULL;
}
/* Return if no request */
if (!req || !req->r)
return true;
r = req->r;
if (r->cfg)
ns = r->cfg->nonsecure ? 1 : 0;
else if (readl(regs + CS(thrd->id)) & CS_CNS)
ns = 1;
else
ns = 0;
/* See 'Abort Sources' point-4 at Page 2-25 */
if (_manager_ns(thrd) && !ns)
dev_info(thrd->dmac->pinfo->dev, "%s:%d Recipe for ABORT!\n",
__func__, __LINE__);
go.chan = thrd->id;
go.addr = req->mc_bus;
go.ns = ns;
_emit_GO(0, insn, &go);
/* Set to generate interrupts for SEV */
writel(readl(regs + INTEN) | (1 << thrd->ev), regs + INTEN);
/* Only manager can execute GO */
_execute_DBGINSN(thrd, insn, true);
thrd->req_running = idx;
return true;
}
static bool _start(struct pl330_thread *thrd)
{
switch (_state(thrd)) {
case PL330_STATE_FAULT_COMPLETING:
UNTIL(thrd, PL330_STATE_FAULTING | PL330_STATE_KILLING);
if (_state(thrd) == PL330_STATE_KILLING)
UNTIL(thrd, PL330_STATE_STOPPED)
case PL330_STATE_FAULTING:
_stop(thrd);
case PL330_STATE_KILLING:
case PL330_STATE_COMPLETING:
UNTIL(thrd, PL330_STATE_STOPPED)
case PL330_STATE_STOPPED:
return _trigger(thrd);
case PL330_STATE_WFP:
case PL330_STATE_QUEUEBUSY:
case PL330_STATE_ATBARRIER:
case PL330_STATE_UPDTPC:
case PL330_STATE_CACHEMISS:
case PL330_STATE_EXECUTING:
return true;
case PL330_STATE_WFE: /* For RESUME, nothing yet */
default:
return false;
}
}
static inline int _ldst_memtomem(unsigned dry_run, u8 buf[],
const struct _xfer_spec *pxs, int cyc)
{
int off = 0;
struct pl330_config *pcfg = pxs->r->cfg->pcfg;
/* check lock-up free version */
if (get_revision(pcfg->periph_id) >= PERIPH_REV_R1P0) {
while (cyc--) {
off += _emit_LD(dry_run, &buf[off], ALWAYS);
off += _emit_ST(dry_run, &buf[off], ALWAYS);
}
} else {
while (cyc--) {
off += _emit_LD(dry_run, &buf[off], ALWAYS);
off += _emit_RMB(dry_run, &buf[off]);
off += _emit_ST(dry_run, &buf[off], ALWAYS);
off += _emit_WMB(dry_run, &buf[off]);
}
}
return off;
}
static inline int _ldst_devtomem(unsigned dry_run, u8 buf[],
const struct _xfer_spec *pxs, int cyc)
{
int off = 0;
while (cyc--) {
off += _emit_WFP(dry_run, &buf[off], SINGLE, pxs->r->peri);
off += _emit_LDP(dry_run, &buf[off], SINGLE, pxs->r->peri);
off += _emit_ST(dry_run, &buf[off], ALWAYS);
off += _emit_FLUSHP(dry_run, &buf[off], pxs->r->peri);
}
return off;
}
static inline int _ldst_memtodev(unsigned dry_run, u8 buf[],
const struct _xfer_spec *pxs, int cyc)
{
int off = 0;
while (cyc--) {
off += _emit_WFP(dry_run, &buf[off], SINGLE, pxs->r->peri);
off += _emit_LD(dry_run, &buf[off], ALWAYS);
off += _emit_STP(dry_run, &buf[off], SINGLE, pxs->r->peri);
off += _emit_FLUSHP(dry_run, &buf[off], pxs->r->peri);
}
return off;
}
static int _bursts(unsigned dry_run, u8 buf[],
const struct _xfer_spec *pxs, int cyc)
{
int off = 0;
switch (pxs->r->rqtype) {
case MEMTODEV:
off += _ldst_memtodev(dry_run, &buf[off], pxs, cyc);
break;
case DEVTOMEM:
off += _ldst_devtomem(dry_run, &buf[off], pxs, cyc);
break;
case MEMTOMEM:
off += _ldst_memtomem(dry_run, &buf[off], pxs, cyc);
break;
default:
off += 0x40000000; /* Scare off the Client */
break;
}
return off;
}
/* Returns bytes consumed and updates bursts */
static inline int _loop(unsigned dry_run, u8 buf[],
unsigned long *bursts, const struct _xfer_spec *pxs)
{
int cyc, cycmax, szlp, szlpend, szbrst, off;
unsigned lcnt0, lcnt1, ljmp0, ljmp1;
struct _arg_LPEND lpend;
/* Max iterations possible in DMALP is 256 */
if (*bursts >= 256*256) {
lcnt1 = 256;
lcnt0 = 256;
cyc = *bursts / lcnt1 / lcnt0;
} else if (*bursts > 256) {
lcnt1 = 256;
lcnt0 = *bursts / lcnt1;
cyc = 1;
} else {
lcnt1 = *bursts;
lcnt0 = 0;
cyc = 1;
}
szlp = _emit_LP(1, buf, 0, 0);
szbrst = _bursts(1, buf, pxs, 1);
lpend.cond = ALWAYS;
lpend.forever = false;
lpend.loop = 0;
lpend.bjump = 0;
szlpend = _emit_LPEND(1, buf, &lpend);
if (lcnt0) {
szlp *= 2;
szlpend *= 2;
}
/*
* Max bursts that we can unroll due to limit on the
* size of backward jump that can be encoded in DMALPEND
* which is 8-bits and hence 255
*/
cycmax = (255 - (szlp + szlpend)) / szbrst;
cyc = (cycmax < cyc) ? cycmax : cyc;
off = 0;
if (lcnt0) {
off += _emit_LP(dry_run, &buf[off], 0, lcnt0);
ljmp0 = off;
}
off += _emit_LP(dry_run, &buf[off], 1, lcnt1);
ljmp1 = off;
off += _bursts(dry_run, &buf[off], pxs, cyc);
lpend.cond = ALWAYS;
lpend.forever = false;
lpend.loop = 1;
lpend.bjump = off - ljmp1;
off += _emit_LPEND(dry_run, &buf[off], &lpend);
if (lcnt0) {
lpend.cond = ALWAYS;
lpend.forever = false;
lpend.loop = 0;
lpend.bjump = off - ljmp0;
off += _emit_LPEND(dry_run, &buf[off], &lpend);
}
*bursts = lcnt1 * cyc;
if (lcnt0)
*bursts *= lcnt0;
return off;
}
static inline int _setup_loops(unsigned dry_run, u8 buf[],
const struct _xfer_spec *pxs)
{
struct pl330_xfer *x = pxs->x;
u32 ccr = pxs->ccr;
unsigned long c, bursts = BYTE_TO_BURST(x->bytes, ccr);
int off = 0;
while (bursts) {
c = bursts;
off += _loop(dry_run, &buf[off], &c, pxs);
bursts -= c;
}
return off;
}
static inline int _setup_xfer(unsigned dry_run, u8 buf[],
const struct _xfer_spec *pxs)
{
struct pl330_xfer *x = pxs->x;
int off = 0;
/* DMAMOV SAR, x->src_addr */
off += _emit_MOV(dry_run, &buf[off], SAR, x->src_addr);
/* DMAMOV DAR, x->dst_addr */
off += _emit_MOV(dry_run, &buf[off], DAR, x->dst_addr);
/* Setup Loop(s) */
off += _setup_loops(dry_run, &buf[off], pxs);
return off;
}
/*
* A req is a sequence of one or more xfer units.
* Returns the number of bytes taken to setup the MC for the req.
*/
static int _setup_req(unsigned dry_run, struct pl330_thread *thrd,
unsigned index, struct _xfer_spec *pxs)
{
struct _pl330_req *req = &thrd->req[index];
struct pl330_xfer *x;
u8 *buf = req->mc_cpu;
int off = 0;
PL330_DBGMC_START(req->mc_bus);
/* DMAMOV CCR, ccr */
off += _emit_MOV(dry_run, &buf[off], CCR, pxs->ccr);
x = pxs->r->x;
do {
/* Error if xfer length is not aligned at burst size */
if (x->bytes % (BRST_SIZE(pxs->ccr) * BRST_LEN(pxs->ccr)))
return -EINVAL;
pxs->x = x;
off += _setup_xfer(dry_run, &buf[off], pxs);
x = x->next;
} while (x);
/* DMASEV peripheral/event */
off += _emit_SEV(dry_run, &buf[off], thrd->ev);
/* DMAEND */
off += _emit_END(dry_run, &buf[off]);
return off;
}
static inline u32 _prepare_ccr(const struct pl330_reqcfg *rqc)
{
u32 ccr = 0;
if (rqc->src_inc)
ccr |= CC_SRCINC;
if (rqc->dst_inc)
ccr |= CC_DSTINC;
/* We set same protection levels for Src and DST for now */
if (rqc->privileged)
ccr |= CC_SRCPRI | CC_DSTPRI;
if (rqc->nonsecure)
ccr |= CC_SRCNS | CC_DSTNS;
if (rqc->insnaccess)
ccr |= CC_SRCIA | CC_DSTIA;
ccr |= (((rqc->brst_len - 1) & 0xf) << CC_SRCBRSTLEN_SHFT);
ccr |= (((rqc->brst_len - 1) & 0xf) << CC_DSTBRSTLEN_SHFT);
ccr |= (rqc->brst_size << CC_SRCBRSTSIZE_SHFT);
ccr |= (rqc->brst_size << CC_DSTBRSTSIZE_SHFT);
ccr |= (rqc->scctl << CC_SRCCCTRL_SHFT);
ccr |= (rqc->dcctl << CC_DSTCCTRL_SHFT);
ccr |= (rqc->swap << CC_SWAP_SHFT);
return ccr;
}
static inline bool _is_valid(u32 ccr)
{
enum pl330_dstcachectrl dcctl;
enum pl330_srccachectrl scctl;
dcctl = (ccr >> CC_DSTCCTRL_SHFT) & CC_DRCCCTRL_MASK;
scctl = (ccr >> CC_SRCCCTRL_SHFT) & CC_SRCCCTRL_MASK;
if (dcctl == DINVALID1 || dcctl == DINVALID2
|| scctl == SINVALID1 || scctl == SINVALID2)
return false;
else
return true;
}
/*
* Submit a list of xfers after which the client wants notification.
* Client is not notified after each xfer unit, just once after all
* xfer units are done or some error occurs.
*/
static int pl330_submit_req(void *ch_id, struct pl330_req *r)
{
struct pl330_thread *thrd = ch_id;
struct pl330_dmac *pl330;
struct pl330_info *pi;
struct _xfer_spec xs;
unsigned long flags;
void __iomem *regs;
unsigned idx;
u32 ccr;
int ret = 0;
/* No Req or Unacquired Channel or DMAC */
if (!r || !thrd || thrd->free)
return -EINVAL;
pl330 = thrd->dmac;
pi = pl330->pinfo;
regs = pi->base;
if (pl330->state == DYING
|| pl330->dmac_tbd.reset_chan & (1 << thrd->id)) {
dev_info(thrd->dmac->pinfo->dev, "%s:%d\n",
__func__, __LINE__);
return -EAGAIN;
}
/* If request for non-existing peripheral */
if (r->rqtype != MEMTOMEM && r->peri >= pi->pcfg.num_peri) {
dev_info(thrd->dmac->pinfo->dev,
"%s:%d Invalid peripheral(%u)!\n",
__func__, __LINE__, r->peri);
return -EINVAL;
}
spin_lock_irqsave(&pl330->lock, flags);
if (_queue_full(thrd)) {
ret = -EAGAIN;
goto xfer_exit;
}
/* Use last settings, if not provided */
if (r->cfg) {
/* Prefer Secure Channel */
if (!_manager_ns(thrd))
r->cfg->nonsecure = 0;
else
r->cfg->nonsecure = 1;
ccr = _prepare_ccr(r->cfg);
} else {
ccr = readl(regs + CC(thrd->id));
}
/* If this req doesn't have valid xfer settings */
if (!_is_valid(ccr)) {
ret = -EINVAL;
dev_info(thrd->dmac->pinfo->dev, "%s:%d Invalid CCR(%x)!\n",
__func__, __LINE__, ccr);
goto xfer_exit;
}
idx = IS_FREE(&thrd->req[0]) ? 0 : 1;
xs.ccr = ccr;
xs.r = r;
/* First dry run to check if req is acceptable */
ret = _setup_req(1, thrd, idx, &xs);
if (ret < 0)
goto xfer_exit;
if (ret > pi->mcbufsz / 2) {
dev_info(thrd->dmac->pinfo->dev,
"%s:%d Trying increasing mcbufsz\n",
__func__, __LINE__);
ret = -ENOMEM;
goto xfer_exit;
}
/* Hook the request */
thrd->lstenq = idx;
thrd->req[idx].mc_len = _setup_req(0, thrd, idx, &xs);
thrd->req[idx].r = r;
ret = 0;
xfer_exit:
spin_unlock_irqrestore(&pl330->lock, flags);
return ret;
}
static void pl330_dotask(unsigned long data)
{
struct pl330_dmac *pl330 = (struct pl330_dmac *) data;
struct pl330_info *pi = pl330->pinfo;
unsigned long flags;
int i;
spin_lock_irqsave(&pl330->lock, flags);
/* The DMAC itself gone nuts */
if (pl330->dmac_tbd.reset_dmac) {
pl330->state = DYING;
/* Reset the manager too */
pl330->dmac_tbd.reset_mngr = true;
/* Clear the reset flag */
pl330->dmac_tbd.reset_dmac = false;
}
if (pl330->dmac_tbd.reset_mngr) {
_stop(pl330->manager);
/* Reset all channels */
pl330->dmac_tbd.reset_chan = (1 << pi->pcfg.num_chan) - 1;
/* Clear the reset flag */
pl330->dmac_tbd.reset_mngr = false;
}
for (i = 0; i < pi->pcfg.num_chan; i++) {
if (pl330->dmac_tbd.reset_chan & (1 << i)) {
struct pl330_thread *thrd = &pl330->channels[i];
void __iomem *regs = pi->base;
enum pl330_op_err err;
_stop(thrd);
if (readl(regs + FSC) & (1 << thrd->id))
err = PL330_ERR_FAIL;
else
err = PL330_ERR_ABORT;
spin_unlock_irqrestore(&pl330->lock, flags);
_callback(thrd->req[1 - thrd->lstenq].r, err);
_callback(thrd->req[thrd->lstenq].r, err);
spin_lock_irqsave(&pl330->lock, flags);
thrd->req[0].r = NULL;
thrd->req[1].r = NULL;
mark_free(thrd, 0);
mark_free(thrd, 1);
/* Clear the reset flag */
pl330->dmac_tbd.reset_chan &= ~(1 << i);
}
}
spin_unlock_irqrestore(&pl330->lock, flags);
return;
}
/* Returns 1 if state was updated, 0 otherwise */
static int pl330_update(const struct pl330_info *pi)
{
struct pl330_req *rqdone, *tmp;
struct pl330_dmac *pl330;
unsigned long flags;
void __iomem *regs;
u32 val;
int id, ev, ret = 0;
if (!pi || !pi->pl330_data)
return 0;
regs = pi->base;
pl330 = pi->pl330_data;
spin_lock_irqsave(&pl330->lock, flags);
val = readl(regs + FSM) & 0x1;
if (val)
pl330->dmac_tbd.reset_mngr = true;
else
pl330->dmac_tbd.reset_mngr = false;
val = readl(regs + FSC) & ((1 << pi->pcfg.num_chan) - 1);
pl330->dmac_tbd.reset_chan |= val;
if (val) {
int i = 0;
while (i < pi->pcfg.num_chan) {
if (val & (1 << i)) {
dev_info(pi->dev,
"Reset Channel-%d\t CS-%x FTC-%x\n",
i, readl(regs + CS(i)),
readl(regs + FTC(i)));
_stop(&pl330->channels[i]);
}
i++;
}
}
/* Check which event happened i.e, thread notified */
val = readl(regs + ES);
if (pi->pcfg.num_events < 32
&& val & ~((1 << pi->pcfg.num_events) - 1)) {
pl330->dmac_tbd.reset_dmac = true;
dev_err(pi->dev, "%s:%d Unexpected!\n", __func__, __LINE__);
ret = 1;
goto updt_exit;
}
for (ev = 0; ev < pi->pcfg.num_events; ev++) {
if (val & (1 << ev)) { /* Event occurred */
struct pl330_thread *thrd;
u32 inten = readl(regs + INTEN);
int active;
/* Clear the event */
if (inten & (1 << ev))
writel(1 << ev, regs + INTCLR);
ret = 1;
id = pl330->events[ev];
thrd = &pl330->channels[id];
active = thrd->req_running;
if (active == -1) /* Aborted */
continue;
/* Detach the req */
rqdone = thrd->req[active].r;
thrd->req[active].r = NULL;
mark_free(thrd, active);
/* Get going again ASAP */
_start(thrd);
/* For now, just make a list of callbacks to be done */
list_add_tail(&rqdone->rqd, &pl330->req_done);
}
}
/* Now that we are in no hurry, do the callbacks */
list_for_each_entry_safe(rqdone, tmp, &pl330->req_done, rqd) {
list_del(&rqdone->rqd);
spin_unlock_irqrestore(&pl330->lock, flags);
_callback(rqdone, PL330_ERR_NONE);
spin_lock_irqsave(&pl330->lock, flags);
}
updt_exit:
spin_unlock_irqrestore(&pl330->lock, flags);
if (pl330->dmac_tbd.reset_dmac
|| pl330->dmac_tbd.reset_mngr
|| pl330->dmac_tbd.reset_chan) {
ret = 1;
tasklet_schedule(&pl330->tasks);
}
return ret;
}
static int pl330_chan_ctrl(void *ch_id, enum pl330_chan_op op)
{
struct pl330_thread *thrd = ch_id;
struct pl330_dmac *pl330;
unsigned long flags;
int ret = 0, active;
if (!thrd || thrd->free || thrd->dmac->state == DYING)
return -EINVAL;
pl330 = thrd->dmac;
active = thrd->req_running;
spin_lock_irqsave(&pl330->lock, flags);
switch (op) {
case PL330_OP_FLUSH:
/* Make sure the channel is stopped */
_stop(thrd);
thrd->req[0].r = NULL;
thrd->req[1].r = NULL;
mark_free(thrd, 0);
mark_free(thrd, 1);
break;
case PL330_OP_ABORT:
/* Make sure the channel is stopped */
_stop(thrd);
/* ABORT is only for the active req */
if (active == -1)
break;
thrd->req[active].r = NULL;
mark_free(thrd, active);
/* Start the next */
case PL330_OP_START:
if ((active == -1) && !_start(thrd))
ret = -EIO;
break;
default:
ret = -EINVAL;
}
spin_unlock_irqrestore(&pl330->lock, flags);
return ret;
}
/* Reserve an event */
static inline int _alloc_event(struct pl330_thread *thrd)
{
struct pl330_dmac *pl330 = thrd->dmac;
struct pl330_info *pi = pl330->pinfo;
int ev;
for (ev = 0; ev < pi->pcfg.num_events; ev++)
if (pl330->events[ev] == -1) {
pl330->events[ev] = thrd->id;
return ev;
}
return -1;
}
static bool _chan_ns(const struct pl330_info *pi, int i)
{
return pi->pcfg.irq_ns & (1 << i);
}
/* Upon success, returns IdentityToken for the
* allocated channel, NULL otherwise.
*/
static void *pl330_request_channel(const struct pl330_info *pi)
{
struct pl330_thread *thrd = NULL;
struct pl330_dmac *pl330;
unsigned long flags;
int chans, i;
if (!pi || !pi->pl330_data)
return NULL;
pl330 = pi->pl330_data;
if (pl330->state == DYING)
return NULL;
chans = pi->pcfg.num_chan;
spin_lock_irqsave(&pl330->lock, flags);
for (i = 0; i < chans; i++) {
thrd = &pl330->channels[i];
if ((thrd->free) && (!_manager_ns(thrd) ||
_chan_ns(pi, i))) {
thrd->ev = _alloc_event(thrd);
if (thrd->ev >= 0) {
thrd->free = false;
thrd->lstenq = 1;
thrd->req[0].r = NULL;
mark_free(thrd, 0);
thrd->req[1].r = NULL;
mark_free(thrd, 1);
break;
}
}
thrd = NULL;
}
spin_unlock_irqrestore(&pl330->lock, flags);
return thrd;
}
/* Release an event */
static inline void _free_event(struct pl330_thread *thrd, int ev)
{
struct pl330_dmac *pl330 = thrd->dmac;
struct pl330_info *pi = pl330->pinfo;
/* If the event is valid and was held by the thread */
if (ev >= 0 && ev < pi->pcfg.num_events
&& pl330->events[ev] == thrd->id)
pl330->events[ev] = -1;
}
static void pl330_release_channel(void *ch_id)
{
struct pl330_thread *thrd = ch_id;
struct pl330_dmac *pl330;
unsigned long flags;
if (!thrd || thrd->free)
return;
_stop(thrd);
_callback(thrd->req[1 - thrd->lstenq].r, PL330_ERR_ABORT);
_callback(thrd->req[thrd->lstenq].r, PL330_ERR_ABORT);
pl330 = thrd->dmac;
spin_lock_irqsave(&pl330->lock, flags);
_free_event(thrd, thrd->ev);
thrd->free = true;
spin_unlock_irqrestore(&pl330->lock, flags);
}
/* Initialize the structure for PL330 configuration, that can be used
* by the client driver the make best use of the DMAC
*/
static void read_dmac_config(struct pl330_info *pi)
{
void __iomem *regs = pi->base;
u32 val;
val = readl(regs + CRD) >> CRD_DATA_WIDTH_SHIFT;
val &= CRD_DATA_WIDTH_MASK;
pi->pcfg.data_bus_width = 8 * (1 << val);
val = readl(regs + CRD) >> CRD_DATA_BUFF_SHIFT;
val &= CRD_DATA_BUFF_MASK;
pi->pcfg.data_buf_dep = val + 1;
val = readl(regs + CR0) >> CR0_NUM_CHANS_SHIFT;
val &= CR0_NUM_CHANS_MASK;
val += 1;
pi->pcfg.num_chan = val;
val = readl(regs + CR0);
if (val & CR0_PERIPH_REQ_SET) {
val = (val >> CR0_NUM_PERIPH_SHIFT) & CR0_NUM_PERIPH_MASK;
val += 1;
pi->pcfg.num_peri = val;
pi->pcfg.peri_ns = readl(regs + CR4);
} else {
pi->pcfg.num_peri = 0;
}
val = readl(regs + CR0);
if (val & CR0_BOOT_MAN_NS)
pi->pcfg.mode |= DMAC_MODE_NS;
else
pi->pcfg.mode &= ~DMAC_MODE_NS;
val = readl(regs + CR0) >> CR0_NUM_EVENTS_SHIFT;
val &= CR0_NUM_EVENTS_MASK;
val += 1;
pi->pcfg.num_events = val;
pi->pcfg.irq_ns = readl(regs + CR3);
pi->pcfg.periph_id = get_id(pi, PERIPH_ID);
pi->pcfg.pcell_id = get_id(pi, PCELL_ID);
}
static inline void _reset_thread(struct pl330_thread *thrd)
{
struct pl330_dmac *pl330 = thrd->dmac;
struct pl330_info *pi = pl330->pinfo;
thrd->req[0].mc_cpu = pl330->mcode_cpu
+ (thrd->id * pi->mcbufsz);
thrd->req[0].mc_bus = pl330->mcode_bus
+ (thrd->id * pi->mcbufsz);
thrd->req[0].r = NULL;
mark_free(thrd, 0);
thrd->req[1].mc_cpu = thrd->req[0].mc_cpu
+ pi->mcbufsz / 2;
thrd->req[1].mc_bus = thrd->req[0].mc_bus
+ pi->mcbufsz / 2;
thrd->req[1].r = NULL;
mark_free(thrd, 1);
}
static int dmac_alloc_threads(struct pl330_dmac *pl330)
{
struct pl330_info *pi = pl330->pinfo;
int chans = pi->pcfg.num_chan;
struct pl330_thread *thrd;
int i;
/* Allocate 1 Manager and 'chans' Channel threads */
pl330->channels = kzalloc((1 + chans) * sizeof(*thrd),
GFP_KERNEL);
if (!pl330->channels)
return -ENOMEM;
/* Init Channel threads */
for (i = 0; i < chans; i++) {
thrd = &pl330->channels[i];
thrd->id = i;
thrd->dmac = pl330;
_reset_thread(thrd);
thrd->free = true;
}
/* MANAGER is indexed at the end */
thrd = &pl330->channels[chans];
thrd->id = chans;
thrd->dmac = pl330;
thrd->free = false;
pl330->manager = thrd;
return 0;
}
static int dmac_alloc_resources(struct pl330_dmac *pl330)
{
struct pl330_info *pi = pl330->pinfo;
int chans = pi->pcfg.num_chan;
int ret;
/*
* Alloc MicroCode buffer for 'chans' Channel threads.
* A channel's buffer offset is (Channel_Id * MCODE_BUFF_PERCHAN)
*/
pl330->mcode_cpu = dma_alloc_coherent(pi->dev,
chans * pi->mcbufsz,
&pl330->mcode_bus, GFP_KERNEL);
if (!pl330->mcode_cpu) {
dev_err(pi->dev, "%s:%d Can't allocate memory!\n",
__func__, __LINE__);
return -ENOMEM;
}
ret = dmac_alloc_threads(pl330);
if (ret) {
dev_err(pi->dev, "%s:%d Can't to create channels for DMAC!\n",
__func__, __LINE__);
dma_free_coherent(pi->dev,
chans * pi->mcbufsz,
pl330->mcode_cpu, pl330->mcode_bus);
return ret;
}
return 0;
}
static int pl330_add(struct pl330_info *pi)
{
struct pl330_dmac *pl330;
void __iomem *regs;
int i, ret;
if (!pi || !pi->dev)
return -EINVAL;
/* If already added */
if (pi->pl330_data)
return -EINVAL;
/*
* If the SoC can perform reset on the DMAC, then do it
* before reading its configuration.
*/
if (pi->dmac_reset)
pi->dmac_reset(pi);
regs = pi->base;
/* Check if we can handle this DMAC */
if ((get_id(pi, PERIPH_ID) & 0xfffff) != PERIPH_ID_VAL
|| get_id(pi, PCELL_ID) != PCELL_ID_VAL) {
dev_err(pi->dev, "PERIPH_ID 0x%x, PCELL_ID 0x%x !\n",
get_id(pi, PERIPH_ID), get_id(pi, PCELL_ID));
return -EINVAL;
}
/* Read the configuration of the DMAC */
read_dmac_config(pi);
if (pi->pcfg.num_events == 0) {
dev_err(pi->dev, "%s:%d Can't work without events!\n",
__func__, __LINE__);
return -EINVAL;
}
pl330 = kzalloc(sizeof(*pl330), GFP_KERNEL);
if (!pl330) {
dev_err(pi->dev, "%s:%d Can't allocate memory!\n",
__func__, __LINE__);
return -ENOMEM;
}
/* Assign the info structure and private data */
pl330->pinfo = pi;
pi->pl330_data = pl330;
spin_lock_init(&pl330->lock);
INIT_LIST_HEAD(&pl330->req_done);
/* Use default MC buffer size if not provided */
if (!pi->mcbufsz)
pi->mcbufsz = MCODE_BUFF_PER_REQ * 2;
/* Mark all events as free */
for (i = 0; i < pi->pcfg.num_events; i++)
pl330->events[i] = -1;
/* Allocate resources needed by the DMAC */
ret = dmac_alloc_resources(pl330);
if (ret) {
dev_err(pi->dev, "Unable to create channels for DMAC\n");
kfree(pl330);
return ret;
}
tasklet_init(&pl330->tasks, pl330_dotask, (unsigned long) pl330);
pl330->state = INIT;
return 0;
}
static int dmac_free_threads(struct pl330_dmac *pl330)
{
struct pl330_info *pi = pl330->pinfo;
int chans = pi->pcfg.num_chan;
struct pl330_thread *thrd;
int i;
/* Release Channel threads */
for (i = 0; i < chans; i++) {
thrd = &pl330->channels[i];
pl330_release_channel((void *)thrd);
}
/* Free memory */
kfree(pl330->channels);
return 0;
}
static void dmac_free_resources(struct pl330_dmac *pl330)
{
struct pl330_info *pi = pl330->pinfo;
int chans = pi->pcfg.num_chan;
dmac_free_threads(pl330);
dma_free_coherent(pi->dev, chans * pi->mcbufsz,
pl330->mcode_cpu, pl330->mcode_bus);
}
static void pl330_del(struct pl330_info *pi)
{
struct pl330_dmac *pl330;
if (!pi || !pi->pl330_data)
return;
pl330 = pi->pl330_data;
pl330->state = UNINIT;
tasklet_kill(&pl330->tasks);
/* Free DMAC resources */
dmac_free_resources(pl330);
kfree(pl330);
pi->pl330_data = NULL;
}
/* forward declaration */
static struct amba_driver pl330_driver;
static inline struct dma_pl330_chan *
to_pchan(struct dma_chan *ch)
{
if (!ch)
return NULL;
return container_of(ch, struct dma_pl330_chan, chan);
}
static inline struct dma_pl330_desc *
to_desc(struct dma_async_tx_descriptor *tx)
{
return container_of(tx, struct dma_pl330_desc, txd);
}
static inline void free_desc_list(struct list_head *list)
{
struct dma_pl330_dmac *pdmac;
struct dma_pl330_desc *desc;
struct dma_pl330_chan *pch = NULL;
unsigned long flags;
/* Finish off the work list */
list_for_each_entry(desc, list, node) {
dma_async_tx_callback callback;
void *param;
/* All desc in a list belong to same channel */
pch = desc->pchan;
callback = desc->txd.callback;
param = desc->txd.callback_param;
if (callback)
callback(param);
desc->pchan = NULL;
}
/* pch will be unset if list was empty */
if (!pch)
return;
pdmac = pch->dmac;
spin_lock_irqsave(&pdmac->pool_lock, flags);
list_splice_tail_init(list, &pdmac->desc_pool);
spin_unlock_irqrestore(&pdmac->pool_lock, flags);
}
static inline void handle_cyclic_desc_list(struct list_head *list)
{
struct dma_pl330_desc *desc;
struct dma_pl330_chan *pch = NULL;
unsigned long flags;
list_for_each_entry(desc, list, node) {
dma_async_tx_callback callback;
/* Change status to reload it */
desc->status = PREP;
pch = desc->pchan;
callback = desc->txd.callback;
if (callback)
callback(desc->txd.callback_param);
}
/* pch will be unset if list was empty */
if (!pch)
return;
spin_lock_irqsave(&pch->lock, flags);
list_splice_tail_init(list, &pch->work_list);
spin_unlock_irqrestore(&pch->lock, flags);
}
static inline void fill_queue(struct dma_pl330_chan *pch)
{
struct dma_pl330_desc *desc;
int ret;
list_for_each_entry(desc, &pch->work_list, node) {
/* If already submitted */
if (desc->status == BUSY)
continue;
ret = pl330_submit_req(pch->pl330_chid,
&desc->req);
if (!ret) {
desc->status = BUSY;
} else if (ret == -EAGAIN) {
/* QFull or DMAC Dying */
break;
} else {
/* Unacceptable request */
desc->status = DONE;
dev_err(pch->dmac->pif.dev, "%s:%d Bad Desc(%d)\n",
__func__, __LINE__, desc->txd.cookie);
tasklet_schedule(&pch->task);
}
}
}
static void pl330_tasklet(unsigned long data)
{
struct dma_pl330_chan *pch = (struct dma_pl330_chan *)data;
struct dma_pl330_desc *desc, *_dt;
unsigned long flags;
LIST_HEAD(list);
spin_lock_irqsave(&pch->lock, flags);
/* Pick up ripe tomatoes */
list_for_each_entry_safe(desc, _dt, &pch->work_list, node)
if (desc->status == DONE) {
if (!pch->cyclic)
dma_cookie_complete(&desc->txd);
list_move_tail(&desc->node, &list);
}
/* Try to submit a req imm. next to the last completed cookie */
fill_queue(pch);
/* Make sure the PL330 Channel thread is active */
pl330_chan_ctrl(pch->pl330_chid, PL330_OP_START);
spin_unlock_irqrestore(&pch->lock, flags);
if (pch->cyclic)
handle_cyclic_desc_list(&list);
else
free_desc_list(&list);
}
static void dma_pl330_rqcb(void *token, enum pl330_op_err err)
{
struct dma_pl330_desc *desc = token;
struct dma_pl330_chan *pch = desc->pchan;
unsigned long flags;
/* If desc aborted */
if (!pch)
return;
spin_lock_irqsave(&pch->lock, flags);
desc->status = DONE;
spin_unlock_irqrestore(&pch->lock, flags);
tasklet_schedule(&pch->task);
}
static bool pl330_dt_filter(struct dma_chan *chan, void *param)
{
struct dma_pl330_filter_args *fargs = param;
if (chan->device != &fargs->pdmac->ddma)
return false;
return (chan->chan_id == fargs->chan_id);
}
bool pl330_filter(struct dma_chan *chan, void *param)
{
u8 *peri_id;
if (chan->device->dev->driver != &pl330_driver.drv)
return false;
peri_id = chan->private;
return *peri_id == (unsigned)param;
}
EXPORT_SYMBOL(pl330_filter);
static struct dma_chan *of_dma_pl330_xlate(struct of_phandle_args *dma_spec,
struct of_dma *ofdma)
{
int count = dma_spec->args_count;
struct dma_pl330_dmac *pdmac = ofdma->of_dma_data;
struct dma_pl330_filter_args fargs;
dma_cap_mask_t cap;
if (!pdmac)
return NULL;
if (count != 1)
return NULL;
fargs.pdmac = pdmac;
fargs.chan_id = dma_spec->args[0];
dma_cap_zero(cap);
dma_cap_set(DMA_SLAVE, cap);
dma_cap_set(DMA_CYCLIC, cap);
return dma_request_channel(cap, pl330_dt_filter, &fargs);
}
static int pl330_alloc_chan_resources(struct dma_chan *chan)
{
struct dma_pl330_chan *pch = to_pchan(chan);
struct dma_pl330_dmac *pdmac = pch->dmac;
unsigned long flags;
spin_lock_irqsave(&pch->lock, flags);
dma_cookie_init(chan);
pch->cyclic = false;
pch->pl330_chid = pl330_request_channel(&pdmac->pif);
if (!pch->pl330_chid) {
spin_unlock_irqrestore(&pch->lock, flags);
return -ENOMEM;
}
tasklet_init(&pch->task, pl330_tasklet, (unsigned long) pch);
spin_unlock_irqrestore(&pch->lock, flags);
return 1;
}
static int pl330_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd, unsigned long arg)
{
struct dma_pl330_chan *pch = to_pchan(chan);
struct dma_pl330_desc *desc, *_dt;
unsigned long flags;
struct dma_pl330_dmac *pdmac = pch->dmac;
struct dma_slave_config *slave_config;
LIST_HEAD(list);
switch (cmd) {
case DMA_TERMINATE_ALL:
spin_lock_irqsave(&pch->lock, flags);
/* FLUSH the PL330 Channel thread */
pl330_chan_ctrl(pch->pl330_chid, PL330_OP_FLUSH);
/* Mark all desc done */
list_for_each_entry_safe(desc, _dt, &pch->work_list , node) {
desc->status = DONE;
list_move_tail(&desc->node, &list);
}
list_splice_tail_init(&list, &pdmac->desc_pool);
spin_unlock_irqrestore(&pch->lock, flags);
break;
case DMA_SLAVE_CONFIG:
slave_config = (struct dma_slave_config *)arg;
if (slave_config->direction == DMA_MEM_TO_DEV) {
if (slave_config->dst_addr)
pch->fifo_addr = slave_config->dst_addr;
if (slave_config->dst_addr_width)
pch->burst_sz = __ffs(slave_config->dst_addr_width);
if (slave_config->dst_maxburst)
pch->burst_len = slave_config->dst_maxburst;
} else if (slave_config->direction == DMA_DEV_TO_MEM) {
if (slave_config->src_addr)
pch->fifo_addr = slave_config->src_addr;
if (slave_config->src_addr_width)
pch->burst_sz = __ffs(slave_config->src_addr_width);
if (slave_config->src_maxburst)
pch->burst_len = slave_config->src_maxburst;
}
break;
default:
dev_err(pch->dmac->pif.dev, "Not supported command.\n");
return -ENXIO;
}
return 0;
}
static void pl330_free_chan_resources(struct dma_chan *chan)
{
struct dma_pl330_chan *pch = to_pchan(chan);
unsigned long flags;
tasklet_kill(&pch->task);
spin_lock_irqsave(&pch->lock, flags);
pl330_release_channel(pch->pl330_chid);
pch->pl330_chid = NULL;
if (pch->cyclic)
list_splice_tail_init(&pch->work_list, &pch->dmac->desc_pool);
spin_unlock_irqrestore(&pch->lock, flags);
}
static enum dma_status
pl330_tx_status(struct dma_chan *chan, dma_cookie_t cookie,
struct dma_tx_state *txstate)
{
return dma_cookie_status(chan, cookie, txstate);
}
static void pl330_issue_pending(struct dma_chan *chan)
{
pl330_tasklet((unsigned long) to_pchan(chan));
}
/*
* We returned the last one of the circular list of descriptor(s)
* from prep_xxx, so the argument to submit corresponds to the last
* descriptor of the list.
*/
static dma_cookie_t pl330_tx_submit(struct dma_async_tx_descriptor *tx)
{
struct dma_pl330_desc *desc, *last = to_desc(tx);
struct dma_pl330_chan *pch = to_pchan(tx->chan);
dma_cookie_t cookie;
unsigned long flags;
spin_lock_irqsave(&pch->lock, flags);
/* Assign cookies to all nodes */
while (!list_empty(&last->node)) {
desc = list_entry(last->node.next, struct dma_pl330_desc, node);
if (pch->cyclic) {
desc->txd.callback = last->txd.callback;
desc->txd.callback_param = last->txd.callback_param;
}
dma_cookie_assign(&desc->txd);
list_move_tail(&desc->node, &pch->work_list);
}
cookie = dma_cookie_assign(&last->txd);
list_add_tail(&last->node, &pch->work_list);
spin_unlock_irqrestore(&pch->lock, flags);
return cookie;
}
static inline void _init_desc(struct dma_pl330_desc *desc)
{
desc->pchan = NULL;
desc->req.x = &desc->px;
desc->req.token = desc;
desc->rqcfg.swap = SWAP_NO;
desc->rqcfg.privileged = 0;
desc->rqcfg.insnaccess = 0;
desc->rqcfg.scctl = SCCTRL0;
desc->rqcfg.dcctl = DCCTRL0;
desc->req.cfg = &desc->rqcfg;
desc->req.xfer_cb = dma_pl330_rqcb;
desc->txd.tx_submit = pl330_tx_submit;
INIT_LIST_HEAD(&desc->node);
}
/* Returns the number of descriptors added to the DMAC pool */
static int add_desc(struct dma_pl330_dmac *pdmac, gfp_t flg, int count)
{
struct dma_pl330_desc *desc;
unsigned long flags;
int i;
if (!pdmac)
return 0;
desc = kmalloc(count * sizeof(*desc), flg);
if (!desc)
return 0;
spin_lock_irqsave(&pdmac->pool_lock, flags);
for (i = 0; i < count; i++) {
_init_desc(&desc[i]);
list_add_tail(&desc[i].node, &pdmac->desc_pool);
}
spin_unlock_irqrestore(&pdmac->pool_lock, flags);
return count;
}
static struct dma_pl330_desc *
pluck_desc(struct dma_pl330_dmac *pdmac)
{
struct dma_pl330_desc *desc = NULL;
unsigned long flags;
if (!pdmac)
return NULL;
spin_lock_irqsave(&pdmac->pool_lock, flags);
if (!list_empty(&pdmac->desc_pool)) {
desc = list_entry(pdmac->desc_pool.next,
struct dma_pl330_desc, node);
list_del_init(&desc->node);
desc->status = PREP;
desc->txd.callback = NULL;
}
spin_unlock_irqrestore(&pdmac->pool_lock, flags);
return desc;
}
static struct dma_pl330_desc *pl330_get_desc(struct dma_pl330_chan *pch)
{
struct dma_pl330_dmac *pdmac = pch->dmac;
u8 *peri_id = pch->chan.private;
struct dma_pl330_desc *desc;
/* Pluck one desc from the pool of DMAC */
desc = pluck_desc(pdmac);
/* If the DMAC pool is empty, alloc new */
if (!desc) {
if (!add_desc(pdmac, GFP_ATOMIC, 1))
return NULL;
/* Try again */
desc = pluck_desc(pdmac);
if (!desc) {
dev_err(pch->dmac->pif.dev,
"%s:%d ALERT!\n", __func__, __LINE__);
return NULL;
}
}
/* Initialize the descriptor */
desc->pchan = pch;
desc->txd.cookie = 0;
async_tx_ack(&desc->txd);
desc->req.peri = peri_id ? pch->chan.chan_id : 0;
desc->rqcfg.pcfg = &pch->dmac->pif.pcfg;
dma_async_tx_descriptor_init(&desc->txd, &pch->chan);
return desc;
}
static inline void fill_px(struct pl330_xfer *px,
dma_addr_t dst, dma_addr_t src, size_t len)
{
px->next = NULL;
px->bytes = len;
px->dst_addr = dst;
px->src_addr = src;
}
static struct dma_pl330_desc *
__pl330_prep_dma_memcpy(struct dma_pl330_chan *pch, dma_addr_t dst,
dma_addr_t src, size_t len)
{
struct dma_pl330_desc *desc = pl330_get_desc(pch);
if (!desc) {
dev_err(pch->dmac->pif.dev, "%s:%d Unable to fetch desc\n",
__func__, __LINE__);
return NULL;
}
/*
* Ideally we should lookout for reqs bigger than
* those that can be programmed with 256 bytes of
* MC buffer, but considering a req size is seldom
* going to be word-unaligned and more than 200MB,
* we take it easy.
* Also, should the limit is reached we'd rather
* have the platform increase MC buffer size than
* complicating this API driver.
*/
fill_px(&desc->px, dst, src, len);
return desc;
}
/* Call after fixing burst size */
static inline int get_burst_len(struct dma_pl330_desc *desc, size_t len)
{
struct dma_pl330_chan *pch = desc->pchan;
struct pl330_info *pi = &pch->dmac->pif;
int burst_len;
burst_len = pi->pcfg.data_bus_width / 8;
burst_len *= pi->pcfg.data_buf_dep;
burst_len >>= desc->rqcfg.brst_size;
/* src/dst_burst_len can't be more than 16 */
if (burst_len > 16)
burst_len = 16;
while (burst_len > 1) {
if (!(len % (burst_len << desc->rqcfg.brst_size)))
break;
burst_len--;
}
return burst_len;
}
static struct dma_async_tx_descriptor *pl330_prep_dma_cyclic(
struct dma_chan *chan, dma_addr_t dma_addr, size_t len,
size_t period_len, enum dma_transfer_direction direction,
unsigned long flags, void *context)
{
struct dma_pl330_desc *desc = NULL, *first = NULL;
struct dma_pl330_chan *pch = to_pchan(chan);
struct dma_pl330_dmac *pdmac = pch->dmac;
unsigned int i;
dma_addr_t dst;
dma_addr_t src;
if (len % period_len != 0)
return NULL;
if (!is_slave_direction(direction)) {
dev_err(pch->dmac->pif.dev, "%s:%d Invalid dma direction\n",
__func__, __LINE__);
return NULL;
}
for (i = 0; i < len / period_len; i++) {
desc = pl330_get_desc(pch);
if (!desc) {
dev_err(pch->dmac->pif.dev, "%s:%d Unable to fetch desc\n",
__func__, __LINE__);
if (!first)
return NULL;
spin_lock_irqsave(&pdmac->pool_lock, flags);
while (!list_empty(&first->node)) {
desc = list_entry(first->node.next,
struct dma_pl330_desc, node);
list_move_tail(&desc->node, &pdmac->desc_pool);
}
list_move_tail(&first->node, &pdmac->desc_pool);
spin_unlock_irqrestore(&pdmac->pool_lock, flags);
return NULL;
}
switch (direction) {
case DMA_MEM_TO_DEV:
desc->rqcfg.src_inc = 1;
desc->rqcfg.dst_inc = 0;
desc->req.rqtype = MEMTODEV;
src = dma_addr;
dst = pch->fifo_addr;
break;
case DMA_DEV_TO_MEM:
desc->rqcfg.src_inc = 0;
desc->rqcfg.dst_inc = 1;
desc->req.rqtype = DEVTOMEM;
src = pch->fifo_addr;
dst = dma_addr;
break;
default:
break;
}
desc->rqcfg.brst_size = pch->burst_sz;
desc->rqcfg.brst_len = 1;
fill_px(&desc->px, dst, src, period_len);
if (!first)
first = desc;
else
list_add_tail(&desc->node, &first->node);
dma_addr += period_len;
}
if (!desc)
return NULL;
pch->cyclic = true;
desc->txd.flags = flags;
return &desc->txd;
}
static struct dma_async_tx_descriptor *
pl330_prep_dma_memcpy(struct dma_chan *chan, dma_addr_t dst,
dma_addr_t src, size_t len, unsigned long flags)
{
struct dma_pl330_desc *desc;
struct dma_pl330_chan *pch = to_pchan(chan);
struct pl330_info *pi;
int burst;
if (unlikely(!pch || !len))
return NULL;
pi = &pch->dmac->pif;
desc = __pl330_prep_dma_memcpy(pch, dst, src, len);
if (!desc)
return NULL;
desc->rqcfg.src_inc = 1;
desc->rqcfg.dst_inc = 1;
desc->req.rqtype = MEMTOMEM;
/* Select max possible burst size */
burst = pi->pcfg.data_bus_width / 8;
while (burst > 1) {
if (!(len % burst))
break;
burst /= 2;
}
desc->rqcfg.brst_size = 0;
while (burst != (1 << desc->rqcfg.brst_size))
desc->rqcfg.brst_size++;
desc->rqcfg.brst_len = get_burst_len(desc, len);
desc->txd.flags = flags;
return &desc->txd;
}
static struct dma_async_tx_descriptor *
pl330_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
unsigned int sg_len, enum dma_transfer_direction direction,
unsigned long flg, void *context)
{
struct dma_pl330_desc *first, *desc = NULL;
struct dma_pl330_chan *pch = to_pchan(chan);
struct scatterlist *sg;
unsigned long flags;
int i;
dma_addr_t addr;
if (unlikely(!pch || !sgl || !sg_len))
return NULL;
addr = pch->fifo_addr;
first = NULL;
for_each_sg(sgl, sg, sg_len, i) {
desc = pl330_get_desc(pch);
if (!desc) {
struct dma_pl330_dmac *pdmac = pch->dmac;
dev_err(pch->dmac->pif.dev,
"%s:%d Unable to fetch desc\n",
__func__, __LINE__);
if (!first)
return NULL;
spin_lock_irqsave(&pdmac->pool_lock, flags);
while (!list_empty(&first->node)) {
desc = list_entry(first->node.next,
struct dma_pl330_desc, node);
list_move_tail(&desc->node, &pdmac->desc_pool);
}
list_move_tail(&first->node, &pdmac->desc_pool);
spin_unlock_irqrestore(&pdmac->pool_lock, flags);
return NULL;
}
if (!first)
first = desc;
else
list_add_tail(&desc->node, &first->node);
if (direction == DMA_MEM_TO_DEV) {
desc->rqcfg.src_inc = 1;
desc->rqcfg.dst_inc = 0;
desc->req.rqtype = MEMTODEV;
fill_px(&desc->px,
addr, sg_dma_address(sg), sg_dma_len(sg));
} else {
desc->rqcfg.src_inc = 0;
desc->rqcfg.dst_inc = 1;
desc->req.rqtype = DEVTOMEM;
fill_px(&desc->px,
sg_dma_address(sg), addr, sg_dma_len(sg));
}
desc->rqcfg.brst_size = pch->burst_sz;
desc->rqcfg.brst_len = 1;
}
/* Return the last desc in the chain */
desc->txd.flags = flg;
return &desc->txd;
}
static irqreturn_t pl330_irq_handler(int irq, void *data)
{
if (pl330_update(data))
return IRQ_HANDLED;
else
return IRQ_NONE;
}
static int
pl330_probe(struct amba_device *adev, const struct amba_id *id)
{
struct dma_pl330_platdata *pdat;
struct dma_pl330_dmac *pdmac;
struct dma_pl330_chan *pch, *_p;
struct pl330_info *pi;
struct dma_device *pd;
struct resource *res;
int i, ret, irq;
int num_chan;
pdat = adev->dev.platform_data;
/* Allocate a new DMAC and its Channels */
pdmac = devm_kzalloc(&adev->dev, sizeof(*pdmac), GFP_KERNEL);
if (!pdmac) {
dev_err(&adev->dev, "unable to allocate mem\n");
return -ENOMEM;
}
pi = &pdmac->pif;
pi->dev = &adev->dev;
pi->pl330_data = NULL;
pi->mcbufsz = pdat ? pdat->mcbuf_sz : 0;
res = &adev->res;
pi->base = devm_ioremap_resource(&adev->dev, res);
if (IS_ERR(pi->base))
return PTR_ERR(pi->base);
amba_set_drvdata(adev, pdmac);
irq = adev->irq[0];
ret = request_irq(irq, pl330_irq_handler, 0,
dev_name(&adev->dev), pi);
if (ret)
return ret;
ret = pl330_add(pi);
if (ret)
goto probe_err1;
INIT_LIST_HEAD(&pdmac->desc_pool);
spin_lock_init(&pdmac->pool_lock);
/* Create a descriptor pool of default size */
if (!add_desc(pdmac, GFP_KERNEL, NR_DEFAULT_DESC))
dev_warn(&adev->dev, "unable to allocate desc\n");
pd = &pdmac->ddma;
INIT_LIST_HEAD(&pd->channels);
/* Initialize channel parameters */
if (pdat)
num_chan = max_t(int, pdat->nr_valid_peri, pi->pcfg.num_chan);
else
num_chan = max_t(int, pi->pcfg.num_peri, pi->pcfg.num_chan);
pdmac->peripherals = kzalloc(num_chan * sizeof(*pch), GFP_KERNEL);
if (!pdmac->peripherals) {
ret = -ENOMEM;
dev_err(&adev->dev, "unable to allocate pdmac->peripherals\n");
goto probe_err2;
}
for (i = 0; i < num_chan; i++) {
pch = &pdmac->peripherals[i];
if (!adev->dev.of_node)
pch->chan.private = pdat ? &pdat->peri_id[i] : NULL;
else
pch->chan.private = adev->dev.of_node;
INIT_LIST_HEAD(&pch->work_list);
spin_lock_init(&pch->lock);
pch->pl330_chid = NULL;
pch->chan.device = pd;
pch->dmac = pdmac;
/* Add the channel to the DMAC list */
list_add_tail(&pch->chan.device_node, &pd->channels);
}
pd->dev = &adev->dev;
if (pdat) {
pd->cap_mask = pdat->cap_mask;
} else {
dma_cap_set(DMA_MEMCPY, pd->cap_mask);
if (pi->pcfg.num_peri) {
dma_cap_set(DMA_SLAVE, pd->cap_mask);
dma_cap_set(DMA_CYCLIC, pd->cap_mask);
dma_cap_set(DMA_PRIVATE, pd->cap_mask);
}
}
pd->device_alloc_chan_resources = pl330_alloc_chan_resources;
pd->device_free_chan_resources = pl330_free_chan_resources;
pd->device_prep_dma_memcpy = pl330_prep_dma_memcpy;
pd->device_prep_dma_cyclic = pl330_prep_dma_cyclic;
pd->device_tx_status = pl330_tx_status;
pd->device_prep_slave_sg = pl330_prep_slave_sg;
pd->device_control = pl330_control;
pd->device_issue_pending = pl330_issue_pending;
ret = dma_async_device_register(pd);
if (ret) {
dev_err(&adev->dev, "unable to register DMAC\n");
goto probe_err3;
}
if (adev->dev.of_node) {
ret = of_dma_controller_register(adev->dev.of_node,
of_dma_pl330_xlate, pdmac);
if (ret) {
dev_err(&adev->dev,
"unable to register DMA to the generic DT DMA helpers\n");
}
}
dev_info(&adev->dev,
"Loaded driver for PL330 DMAC-%d\n", adev->periphid);
dev_info(&adev->dev,
"\tDBUFF-%ux%ubytes Num_Chans-%u Num_Peri-%u Num_Events-%u\n",
pi->pcfg.data_buf_dep,
pi->pcfg.data_bus_width / 8, pi->pcfg.num_chan,
pi->pcfg.num_peri, pi->pcfg.num_events);
return 0;
probe_err3:
amba_set_drvdata(adev, NULL);
/* Idle the DMAC */
list_for_each_entry_safe(pch, _p, &pdmac->ddma.channels,
chan.device_node) {
/* Remove the channel */
list_del(&pch->chan.device_node);
/* Flush the channel */
pl330_control(&pch->chan, DMA_TERMINATE_ALL, 0);
pl330_free_chan_resources(&pch->chan);
}
probe_err2:
pl330_del(pi);
probe_err1:
free_irq(irq, pi);
return ret;
}
static int pl330_remove(struct amba_device *adev)
{
struct dma_pl330_dmac *pdmac = amba_get_drvdata(adev);
struct dma_pl330_chan *pch, *_p;
struct pl330_info *pi;
int irq;
if (!pdmac)
return 0;
if (adev->dev.of_node)
of_dma_controller_free(adev->dev.of_node);
dma_async_device_unregister(&pdmac->ddma);
amba_set_drvdata(adev, NULL);
/* Idle the DMAC */
list_for_each_entry_safe(pch, _p, &pdmac->ddma.channels,
chan.device_node) {
/* Remove the channel */
list_del(&pch->chan.device_node);
/* Flush the channel */
pl330_control(&pch->chan, DMA_TERMINATE_ALL, 0);
pl330_free_chan_resources(&pch->chan);
}
pi = &pdmac->pif;
pl330_del(pi);
irq = adev->irq[0];
free_irq(irq, pi);
return 0;
}
static struct amba_id pl330_ids[] = {
{
.id = 0x00041330,
.mask = 0x000fffff,
},
{ 0, 0 },
};
MODULE_DEVICE_TABLE(amba, pl330_ids);
static struct amba_driver pl330_driver = {
.drv = {
.owner = THIS_MODULE,
.name = "dma-pl330",
},
.id_table = pl330_ids,
.probe = pl330_probe,
.remove = pl330_remove,
};
module_amba_driver(pl330_driver);
MODULE_AUTHOR("Jaswinder Singh <jassi.brar@samsung.com>");
MODULE_DESCRIPTION("API Driver for PL330 DMAC");
MODULE_LICENSE("GPL");
| gpl-2.0 |
lgoptimusdev/lge-kernel-lproj | drivers/net/wireless/bcmdhd/bcmevent.c | 2180 | 5481 | /*
* bcmevent read-only data shared by kernel or app layers
*
* Copyright (C) 1999-2012, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
* $Id: bcmevent.c 327460 2012-04-13 18:38:41Z $
*/
#include <typedefs.h>
#include <bcmutils.h>
#include <proto/ethernet.h>
#include <proto/bcmeth.h>
#include <proto/bcmevent.h>
#if WLC_E_LAST != 94
#error "You need to add an entry to bcmevent_names[] for the new event"
#endif
const bcmevent_name_t bcmevent_names[] = {
{ WLC_E_SET_SSID, "SET_SSID" },
{ WLC_E_JOIN, "JOIN" },
{ WLC_E_START, "START" },
{ WLC_E_AUTH, "AUTH" },
{ WLC_E_AUTH_IND, "AUTH_IND" },
{ WLC_E_DEAUTH, "DEAUTH" },
{ WLC_E_DEAUTH_IND, "DEAUTH_IND" },
{ WLC_E_ASSOC, "ASSOC" },
{ WLC_E_ASSOC_IND, "ASSOC_IND" },
{ WLC_E_REASSOC, "REASSOC" },
{ WLC_E_REASSOC_IND, "REASSOC_IND" },
{ WLC_E_DISASSOC, "DISASSOC" },
{ WLC_E_DISASSOC_IND, "DISASSOC_IND" },
{ WLC_E_QUIET_START, "START_QUIET" },
{ WLC_E_QUIET_END, "END_QUIET" },
{ WLC_E_BEACON_RX, "BEACON_RX" },
{ WLC_E_LINK, "LINK" },
{ WLC_E_MIC_ERROR, "MIC_ERROR" },
{ WLC_E_NDIS_LINK, "NDIS_LINK" },
{ WLC_E_ROAM, "ROAM" },
{ WLC_E_TXFAIL, "TXFAIL" },
{ WLC_E_PMKID_CACHE, "PMKID_CACHE" },
{ WLC_E_RETROGRADE_TSF, "RETROGRADE_TSF" },
{ WLC_E_PRUNE, "PRUNE" },
{ WLC_E_AUTOAUTH, "AUTOAUTH" },
{ WLC_E_EAPOL_MSG, "EAPOL_MSG" },
{ WLC_E_SCAN_COMPLETE, "SCAN_COMPLETE" },
{ WLC_E_ADDTS_IND, "ADDTS_IND" },
{ WLC_E_DELTS_IND, "DELTS_IND" },
{ WLC_E_BCNSENT_IND, "BCNSENT_IND" },
{ WLC_E_BCNRX_MSG, "BCNRX_MSG" },
{ WLC_E_BCNLOST_MSG, "BCNLOST_IND" },
{ WLC_E_ROAM_PREP, "ROAM_PREP" },
{ WLC_E_PFN_NET_FOUND, "PFNFOUND_IND" },
{ WLC_E_PFN_NET_LOST, "PFNLOST_IND" },
#if defined(IBSS_PEER_DISCOVERY_EVENT)
{ WLC_E_IBSS_ASSOC, "IBSS_ASSOC" },
#endif /* defined(IBSS_PEER_DISCOVERY_EVENT) */
{ WLC_E_RADIO, "RADIO" },
{ WLC_E_PSM_WATCHDOG, "PSM_WATCHDOG" },
{ WLC_E_PROBREQ_MSG, "PROBE_REQ_MSG" },
{ WLC_E_SCAN_CONFIRM_IND, "SCAN_CONFIRM_IND" },
{ WLC_E_PSK_SUP, "PSK_SUP" },
{ WLC_E_COUNTRY_CODE_CHANGED, "CNTRYCODE_IND" },
{ WLC_E_EXCEEDED_MEDIUM_TIME, "EXCEEDED_MEDIUM_TIME" },
{ WLC_E_ICV_ERROR, "ICV_ERROR" },
{ WLC_E_UNICAST_DECODE_ERROR, "UNICAST_DECODE_ERROR" },
{ WLC_E_MULTICAST_DECODE_ERROR, "MULTICAST_DECODE_ERROR" },
{ WLC_E_TRACE, "TRACE" },
#ifdef WLBTAMP
{ WLC_E_BTA_HCI_EVENT, "BTA_HCI_EVENT" },
#endif
{ WLC_E_IF, "IF" },
#ifdef WLP2P
{ WLC_E_P2P_DISC_LISTEN_COMPLETE, "WLC_E_P2P_DISC_LISTEN_COMPLETE" },
#endif
{ WLC_E_RSSI, "RSSI" },
{ WLC_E_PFN_SCAN_COMPLETE, "SCAN_COMPLETE" },
{ WLC_E_EXTLOG_MSG, "EXTERNAL LOG MESSAGE" },
#ifdef WIFI_ACT_FRAME
{ WLC_E_ACTION_FRAME, "ACTION_FRAME" },
{ WLC_E_ACTION_FRAME_RX, "ACTION_FRAME_RX" },
{ WLC_E_ACTION_FRAME_COMPLETE, "ACTION_FRAME_COMPLETE" },
#endif
#if 0 && (NDISVER >= 0x0620)
{ WLC_E_PRE_ASSOC_IND, "ASSOC_RECV" },
{ WLC_E_PRE_REASSOC_IND, "REASSOC_RECV" },
{ WLC_E_CHANNEL_ADOPTED, "CHANNEL_ADOPTED" },
{ WLC_E_AP_STARTED, "AP_STARTED" },
{ WLC_E_DFS_AP_STOP, "DFS_AP_STOP" },
{ WLC_E_DFS_AP_RESUME, "DFS_AP_RESUME" },
{ WLC_E_ASSOC_IND_NDIS, "ASSOC_IND_NDIS"},
{ WLC_E_REASSOC_IND_NDIS, "REASSOC_IND_NDIS"},
{ WLC_E_ACTION_FRAME_RX_NDIS, "WLC_E_ACTION_FRAME_RX_NDIS" },
{ WLC_E_AUTH_REQ, "WLC_E_AUTH_REQ" },
#endif
#ifdef BCMWAPI_WAI
{ WLC_E_WAI_STA_EVENT, "WAI_STA_EVENT" },
{ WLC_E_WAI_MSG, "WAI_MSG" },
#endif /* BCMWAPI_WAI */
{ WLC_E_ESCAN_RESULT, "WLC_E_ESCAN_RESULT" },
{ WLC_E_ACTION_FRAME_OFF_CHAN_COMPLETE, "WLC_E_AF_OFF_CHAN_COMPLETE" },
#ifdef WLP2P
{ WLC_E_PROBRESP_MSG, "PROBE_RESP_MSG" },
{ WLC_E_P2P_PROBREQ_MSG, "P2P PROBE_REQ_MSG" },
#endif
#ifdef PROP_TXSTATUS
{ WLC_E_FIFO_CREDIT_MAP, "FIFO_CREDIT_MAP" },
#endif
{ WLC_E_WAKE_EVENT, "WAKE_EVENT" },
{ WLC_E_DCS_REQUEST, "DCS_REQUEST" },
{ WLC_E_RM_COMPLETE, "RM_COMPLETE" },
#ifdef WLMEDIA_HTSF
{ WLC_E_HTSFSYNC, "HTSF_SYNC_EVENT" },
#endif
{ WLC_E_OVERLAY_REQ, "OVERLAY_REQ_EVENT" },
{ WLC_E_CSA_COMPLETE_IND, "WLC_E_CSA_COMPLETE_IND"},
{ WLC_E_EXCESS_PM_WAKE_EVENT, "EXCESS_PM_WAKE_EVENT" },
{ WLC_E_PFN_SCAN_NONE, "PFN_SCAN_NONE" },
{ WLC_E_PFN_SCAN_ALLGONE, "PFN_SCAN_ALLGONE" },
#ifdef SOFTAP
{ WLC_E_GTK_PLUMBED, "GTK_PLUMBED" },
#endif
{ WLC_E_ASSOC_REQ_IE, "ASSOC_REQ_IE" },
{ WLC_E_ASSOC_RESP_IE, "ASSOC_RESP_IE" },
{ WLC_E_ACTION_FRAME_RX_NDIS, "WLC_E_ACTION_FRAME_RX_NDIS" },
#ifdef WLTDLS
{ WLC_E_TDLS_PEER_EVENT, "TDLS_PEER_EVENT" },
#endif /* WLTDLS */
};
const int bcmevent_names_size = ARRAYSIZE(bcmevent_names);
| gpl-2.0 |
TheMeddlingMonk/android_kernel_toshiba_tostab03 | block/blk-settings.c | 2180 | 25929 | /*
* Functions related to setting various queue properties from drivers
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/bootmem.h> /* for max_pfn/max_low_pfn */
#include <linux/gcd.h>
#include <linux/lcm.h>
#include <linux/jiffies.h>
#include <linux/gfp.h>
#include "blk.h"
unsigned long blk_max_low_pfn;
EXPORT_SYMBOL(blk_max_low_pfn);
unsigned long blk_max_pfn;
/**
* blk_queue_prep_rq - set a prepare_request function for queue
* @q: queue
* @pfn: prepare_request function
*
* It's possible for a queue to register a prepare_request callback which
* is invoked before the request is handed to the request_fn. The goal of
* the function is to prepare a request for I/O, it can be used to build a
* cdb from the request data for instance.
*
*/
void blk_queue_prep_rq(struct request_queue *q, prep_rq_fn *pfn)
{
q->prep_rq_fn = pfn;
}
EXPORT_SYMBOL(blk_queue_prep_rq);
/**
* blk_queue_unprep_rq - set an unprepare_request function for queue
* @q: queue
* @ufn: unprepare_request function
*
* It's possible for a queue to register an unprepare_request callback
* which is invoked before the request is finally completed. The goal
* of the function is to deallocate any data that was allocated in the
* prepare_request callback.
*
*/
void blk_queue_unprep_rq(struct request_queue *q, unprep_rq_fn *ufn)
{
q->unprep_rq_fn = ufn;
}
EXPORT_SYMBOL(blk_queue_unprep_rq);
/**
* blk_queue_merge_bvec - set a merge_bvec function for queue
* @q: queue
* @mbfn: merge_bvec_fn
*
* Usually queues have static limitations on the max sectors or segments that
* we can put in a request. Stacking drivers may have some settings that
* are dynamic, and thus we have to query the queue whether it is ok to
* add a new bio_vec to a bio at a given offset or not. If the block device
* has such limitations, it needs to register a merge_bvec_fn to control
* the size of bio's sent to it. Note that a block device *must* allow a
* single page to be added to an empty bio. The block device driver may want
* to use the bio_split() function to deal with these bio's. By default
* no merge_bvec_fn is defined for a queue, and only the fixed limits are
* honored.
*/
void blk_queue_merge_bvec(struct request_queue *q, merge_bvec_fn *mbfn)
{
q->merge_bvec_fn = mbfn;
}
EXPORT_SYMBOL(blk_queue_merge_bvec);
void blk_queue_softirq_done(struct request_queue *q, softirq_done_fn *fn)
{
q->softirq_done_fn = fn;
}
EXPORT_SYMBOL(blk_queue_softirq_done);
void blk_queue_rq_timeout(struct request_queue *q, unsigned int timeout)
{
q->rq_timeout = timeout;
}
EXPORT_SYMBOL_GPL(blk_queue_rq_timeout);
void blk_queue_rq_timed_out(struct request_queue *q, rq_timed_out_fn *fn)
{
q->rq_timed_out_fn = fn;
}
EXPORT_SYMBOL_GPL(blk_queue_rq_timed_out);
void blk_queue_lld_busy(struct request_queue *q, lld_busy_fn *fn)
{
q->lld_busy_fn = fn;
}
EXPORT_SYMBOL_GPL(blk_queue_lld_busy);
/**
* blk_set_default_limits - reset limits to default values
* @lim: the queue_limits structure to reset
*
* Description:
* Returns a queue_limit struct to its default state. Can be used by
* stacking drivers like DM that stage table swaps and reuse an
* existing device queue.
*/
void blk_set_default_limits(struct queue_limits *lim)
{
lim->max_segments = BLK_MAX_SEGMENTS;
lim->max_integrity_segments = 0;
lim->seg_boundary_mask = BLK_SEG_BOUNDARY_MASK;
lim->max_segment_size = BLK_MAX_SEGMENT_SIZE;
lim->max_sectors = BLK_DEF_MAX_SECTORS;
lim->max_hw_sectors = INT_MAX;
lim->max_discard_sectors = 0;
lim->discard_granularity = 0;
lim->discard_alignment = 0;
lim->discard_misaligned = 0;
lim->discard_zeroes_data = 1;
lim->logical_block_size = lim->physical_block_size = lim->io_min = 512;
lim->bounce_pfn = (unsigned long)(BLK_BOUNCE_ANY >> PAGE_SHIFT);
lim->alignment_offset = 0;
lim->io_opt = 0;
lim->misaligned = 0;
lim->cluster = 1;
}
EXPORT_SYMBOL(blk_set_default_limits);
/**
* blk_queue_make_request - define an alternate make_request function for a device
* @q: the request queue for the device to be affected
* @mfn: the alternate make_request function
*
* Description:
* The normal way for &struct bios to be passed to a device
* driver is for them to be collected into requests on a request
* queue, and then to allow the device driver to select requests
* off that queue when it is ready. This works well for many block
* devices. However some block devices (typically virtual devices
* such as md or lvm) do not benefit from the processing on the
* request queue, and are served best by having the requests passed
* directly to them. This can be achieved by providing a function
* to blk_queue_make_request().
*
* Caveat:
* The driver that does this *must* be able to deal appropriately
* with buffers in "highmemory". This can be accomplished by either calling
* __bio_kmap_atomic() to get a temporary kernel mapping, or by calling
* blk_queue_bounce() to create a buffer in normal memory.
**/
void blk_queue_make_request(struct request_queue *q, make_request_fn *mfn)
{
/*
* set defaults
*/
q->nr_requests = BLKDEV_MAX_RQ;
q->make_request_fn = mfn;
blk_queue_dma_alignment(q, 511);
blk_queue_congestion_threshold(q);
q->nr_batching = BLK_BATCH_REQ;
blk_set_default_limits(&q->limits);
blk_queue_max_hw_sectors(q, BLK_SAFE_MAX_SECTORS);
q->limits.discard_zeroes_data = 0;
/*
* by default assume old behaviour and bounce for any highmem page
*/
blk_queue_bounce_limit(q, BLK_BOUNCE_HIGH);
}
EXPORT_SYMBOL(blk_queue_make_request);
/**
* blk_queue_bounce_limit - set bounce buffer limit for queue
* @q: the request queue for the device
* @dma_mask: the maximum address the device can handle
*
* Description:
* Different hardware can have different requirements as to what pages
* it can do I/O directly to. A low level driver can call
* blk_queue_bounce_limit to have lower memory pages allocated as bounce
* buffers for doing I/O to pages residing above @dma_mask.
**/
void blk_queue_bounce_limit(struct request_queue *q, u64 dma_mask)
{
unsigned long b_pfn = dma_mask >> PAGE_SHIFT;
int dma = 0;
q->bounce_gfp = GFP_NOIO;
#if BITS_PER_LONG == 64
/*
* Assume anything <= 4GB can be handled by IOMMU. Actually
* some IOMMUs can handle everything, but I don't know of a
* way to test this here.
*/
if (b_pfn < (min_t(u64, 0xffffffffUL, BLK_BOUNCE_HIGH) >> PAGE_SHIFT))
dma = 1;
q->limits.bounce_pfn = max(max_low_pfn, b_pfn);
#else
if (b_pfn < blk_max_low_pfn)
dma = 1;
q->limits.bounce_pfn = b_pfn;
#endif
if (dma) {
init_emergency_isa_pool();
q->bounce_gfp = GFP_NOIO | GFP_DMA;
q->limits.bounce_pfn = b_pfn;
}
}
EXPORT_SYMBOL(blk_queue_bounce_limit);
/**
* blk_limits_max_hw_sectors - set hard and soft limit of max sectors for request
* @limits: the queue limits
* @max_hw_sectors: max hardware sectors in the usual 512b unit
*
* Description:
* Enables a low level driver to set a hard upper limit,
* max_hw_sectors, on the size of requests. max_hw_sectors is set by
* the device driver based upon the combined capabilities of I/O
* controller and storage device.
*
* max_sectors is a soft limit imposed by the block layer for
* filesystem type requests. This value can be overridden on a
* per-device basis in /sys/block/<device>/queue/max_sectors_kb.
* The soft limit can not exceed max_hw_sectors.
**/
void blk_limits_max_hw_sectors(struct queue_limits *limits, unsigned int max_hw_sectors)
{
if ((max_hw_sectors << 9) < PAGE_CACHE_SIZE) {
max_hw_sectors = 1 << (PAGE_CACHE_SHIFT - 9);
printk(KERN_INFO "%s: set to minimum %d\n",
__func__, max_hw_sectors);
}
limits->max_hw_sectors = max_hw_sectors;
limits->max_sectors = min_t(unsigned int, max_hw_sectors,
BLK_DEF_MAX_SECTORS);
}
EXPORT_SYMBOL(blk_limits_max_hw_sectors);
/**
* blk_queue_max_hw_sectors - set max sectors for a request for this queue
* @q: the request queue for the device
* @max_hw_sectors: max hardware sectors in the usual 512b unit
*
* Description:
* See description for blk_limits_max_hw_sectors().
**/
void blk_queue_max_hw_sectors(struct request_queue *q, unsigned int max_hw_sectors)
{
blk_limits_max_hw_sectors(&q->limits, max_hw_sectors);
}
EXPORT_SYMBOL(blk_queue_max_hw_sectors);
/**
* blk_queue_max_discard_sectors - set max sectors for a single discard
* @q: the request queue for the device
* @max_discard_sectors: maximum number of sectors to discard
**/
void blk_queue_max_discard_sectors(struct request_queue *q,
unsigned int max_discard_sectors)
{
q->limits.max_discard_sectors = max_discard_sectors;
}
EXPORT_SYMBOL(blk_queue_max_discard_sectors);
/**
* blk_queue_max_segments - set max hw segments for a request for this queue
* @q: the request queue for the device
* @max_segments: max number of segments
*
* Description:
* Enables a low level driver to set an upper limit on the number of
* hw data segments in a request.
**/
void blk_queue_max_segments(struct request_queue *q, unsigned short max_segments)
{
if (!max_segments) {
max_segments = 1;
printk(KERN_INFO "%s: set to minimum %d\n",
__func__, max_segments);
}
q->limits.max_segments = max_segments;
}
EXPORT_SYMBOL(blk_queue_max_segments);
/**
* blk_queue_max_segment_size - set max segment size for blk_rq_map_sg
* @q: the request queue for the device
* @max_size: max size of segment in bytes
*
* Description:
* Enables a low level driver to set an upper limit on the size of a
* coalesced segment
**/
void blk_queue_max_segment_size(struct request_queue *q, unsigned int max_size)
{
if (max_size < PAGE_CACHE_SIZE) {
max_size = PAGE_CACHE_SIZE;
printk(KERN_INFO "%s: set to minimum %d\n",
__func__, max_size);
}
q->limits.max_segment_size = max_size;
}
EXPORT_SYMBOL(blk_queue_max_segment_size);
/**
* blk_queue_logical_block_size - set logical block size for the queue
* @q: the request queue for the device
* @size: the logical block size, in bytes
*
* Description:
* This should be set to the lowest possible block size that the
* storage device can address. The default of 512 covers most
* hardware.
**/
void blk_queue_logical_block_size(struct request_queue *q, unsigned short size)
{
q->limits.logical_block_size = size;
if (q->limits.physical_block_size < size)
q->limits.physical_block_size = size;
if (q->limits.io_min < q->limits.physical_block_size)
q->limits.io_min = q->limits.physical_block_size;
}
EXPORT_SYMBOL(blk_queue_logical_block_size);
/**
* blk_queue_physical_block_size - set physical block size for the queue
* @q: the request queue for the device
* @size: the physical block size, in bytes
*
* Description:
* This should be set to the lowest possible sector size that the
* hardware can operate on without reverting to read-modify-write
* operations.
*/
void blk_queue_physical_block_size(struct request_queue *q, unsigned int size)
{
q->limits.physical_block_size = size;
if (q->limits.physical_block_size < q->limits.logical_block_size)
q->limits.physical_block_size = q->limits.logical_block_size;
if (q->limits.io_min < q->limits.physical_block_size)
q->limits.io_min = q->limits.physical_block_size;
}
EXPORT_SYMBOL(blk_queue_physical_block_size);
/**
* blk_queue_alignment_offset - set physical block alignment offset
* @q: the request queue for the device
* @offset: alignment offset in bytes
*
* Description:
* Some devices are naturally misaligned to compensate for things like
* the legacy DOS partition table 63-sector offset. Low-level drivers
* should call this function for devices whose first sector is not
* naturally aligned.
*/
void blk_queue_alignment_offset(struct request_queue *q, unsigned int offset)
{
q->limits.alignment_offset =
offset & (q->limits.physical_block_size - 1);
q->limits.misaligned = 0;
}
EXPORT_SYMBOL(blk_queue_alignment_offset);
/**
* blk_limits_io_min - set minimum request size for a device
* @limits: the queue limits
* @min: smallest I/O size in bytes
*
* Description:
* Some devices have an internal block size bigger than the reported
* hardware sector size. This function can be used to signal the
* smallest I/O the device can perform without incurring a performance
* penalty.
*/
void blk_limits_io_min(struct queue_limits *limits, unsigned int min)
{
limits->io_min = min;
if (limits->io_min < limits->logical_block_size)
limits->io_min = limits->logical_block_size;
if (limits->io_min < limits->physical_block_size)
limits->io_min = limits->physical_block_size;
}
EXPORT_SYMBOL(blk_limits_io_min);
/**
* blk_queue_io_min - set minimum request size for the queue
* @q: the request queue for the device
* @min: smallest I/O size in bytes
*
* Description:
* Storage devices may report a granularity or preferred minimum I/O
* size which is the smallest request the device can perform without
* incurring a performance penalty. For disk drives this is often the
* physical block size. For RAID arrays it is often the stripe chunk
* size. A properly aligned multiple of minimum_io_size is the
* preferred request size for workloads where a high number of I/O
* operations is desired.
*/
void blk_queue_io_min(struct request_queue *q, unsigned int min)
{
blk_limits_io_min(&q->limits, min);
}
EXPORT_SYMBOL(blk_queue_io_min);
/**
* blk_limits_io_opt - set optimal request size for a device
* @limits: the queue limits
* @opt: smallest I/O size in bytes
*
* Description:
* Storage devices may report an optimal I/O size, which is the
* device's preferred unit for sustained I/O. This is rarely reported
* for disk drives. For RAID arrays it is usually the stripe width or
* the internal track size. A properly aligned multiple of
* optimal_io_size is the preferred request size for workloads where
* sustained throughput is desired.
*/
void blk_limits_io_opt(struct queue_limits *limits, unsigned int opt)
{
limits->io_opt = opt;
}
EXPORT_SYMBOL(blk_limits_io_opt);
/**
* blk_queue_io_opt - set optimal request size for the queue
* @q: the request queue for the device
* @opt: optimal request size in bytes
*
* Description:
* Storage devices may report an optimal I/O size, which is the
* device's preferred unit for sustained I/O. This is rarely reported
* for disk drives. For RAID arrays it is usually the stripe width or
* the internal track size. A properly aligned multiple of
* optimal_io_size is the preferred request size for workloads where
* sustained throughput is desired.
*/
void blk_queue_io_opt(struct request_queue *q, unsigned int opt)
{
blk_limits_io_opt(&q->limits, opt);
}
EXPORT_SYMBOL(blk_queue_io_opt);
/**
* blk_queue_stack_limits - inherit underlying queue limits for stacked drivers
* @t: the stacking driver (top)
* @b: the underlying device (bottom)
**/
void blk_queue_stack_limits(struct request_queue *t, struct request_queue *b)
{
blk_stack_limits(&t->limits, &b->limits, 0);
}
EXPORT_SYMBOL(blk_queue_stack_limits);
/**
* blk_stack_limits - adjust queue_limits for stacked devices
* @t: the stacking driver limits (top device)
* @b: the underlying queue limits (bottom, component device)
* @start: first data sector within component device
*
* Description:
* This function is used by stacking drivers like MD and DM to ensure
* that all component devices have compatible block sizes and
* alignments. The stacking driver must provide a queue_limits
* struct (top) and then iteratively call the stacking function for
* all component (bottom) devices. The stacking function will
* attempt to combine the values and ensure proper alignment.
*
* Returns 0 if the top and bottom queue_limits are compatible. The
* top device's block sizes and alignment offsets may be adjusted to
* ensure alignment with the bottom device. If no compatible sizes
* and alignments exist, -1 is returned and the resulting top
* queue_limits will have the misaligned flag set to indicate that
* the alignment_offset is undefined.
*/
int blk_stack_limits(struct queue_limits *t, struct queue_limits *b,
sector_t start)
{
unsigned int top, bottom, alignment, ret = 0;
t->max_sectors = min_not_zero(t->max_sectors, b->max_sectors);
t->max_hw_sectors = min_not_zero(t->max_hw_sectors, b->max_hw_sectors);
t->bounce_pfn = min_not_zero(t->bounce_pfn, b->bounce_pfn);
t->seg_boundary_mask = min_not_zero(t->seg_boundary_mask,
b->seg_boundary_mask);
t->max_segments = min_not_zero(t->max_segments, b->max_segments);
t->max_integrity_segments = min_not_zero(t->max_integrity_segments,
b->max_integrity_segments);
t->max_segment_size = min_not_zero(t->max_segment_size,
b->max_segment_size);
t->misaligned |= b->misaligned;
alignment = queue_limit_alignment_offset(b, start);
/* Bottom device has different alignment. Check that it is
* compatible with the current top alignment.
*/
if (t->alignment_offset != alignment) {
top = max(t->physical_block_size, t->io_min)
+ t->alignment_offset;
bottom = max(b->physical_block_size, b->io_min) + alignment;
/* Verify that top and bottom intervals line up */
if (max(top, bottom) & (min(top, bottom) - 1)) {
t->misaligned = 1;
ret = -1;
}
}
t->logical_block_size = max(t->logical_block_size,
b->logical_block_size);
t->physical_block_size = max(t->physical_block_size,
b->physical_block_size);
t->io_min = max(t->io_min, b->io_min);
t->io_opt = lcm(t->io_opt, b->io_opt);
t->cluster &= b->cluster;
t->discard_zeroes_data &= b->discard_zeroes_data;
/* Physical block size a multiple of the logical block size? */
if (t->physical_block_size & (t->logical_block_size - 1)) {
t->physical_block_size = t->logical_block_size;
t->misaligned = 1;
ret = -1;
}
/* Minimum I/O a multiple of the physical block size? */
if (t->io_min & (t->physical_block_size - 1)) {
t->io_min = t->physical_block_size;
t->misaligned = 1;
ret = -1;
}
/* Optimal I/O a multiple of the physical block size? */
if (t->io_opt & (t->physical_block_size - 1)) {
t->io_opt = 0;
t->misaligned = 1;
ret = -1;
}
/* Find lowest common alignment_offset */
t->alignment_offset = lcm(t->alignment_offset, alignment)
& (max(t->physical_block_size, t->io_min) - 1);
/* Verify that new alignment_offset is on a logical block boundary */
if (t->alignment_offset & (t->logical_block_size - 1)) {
t->misaligned = 1;
ret = -1;
}
/* Discard alignment and granularity */
if (b->discard_granularity) {
alignment = queue_limit_discard_alignment(b, start);
if (t->discard_granularity != 0 &&
t->discard_alignment != alignment) {
top = t->discard_granularity + t->discard_alignment;
bottom = b->discard_granularity + alignment;
/* Verify that top and bottom intervals line up */
if (max(top, bottom) & (min(top, bottom) - 1))
t->discard_misaligned = 1;
}
t->max_discard_sectors = min_not_zero(t->max_discard_sectors,
b->max_discard_sectors);
t->discard_granularity = max(t->discard_granularity,
b->discard_granularity);
t->discard_alignment = lcm(t->discard_alignment, alignment) &
(t->discard_granularity - 1);
}
return ret;
}
EXPORT_SYMBOL(blk_stack_limits);
/**
* bdev_stack_limits - adjust queue limits for stacked drivers
* @t: the stacking driver limits (top device)
* @bdev: the component block_device (bottom)
* @start: first data sector within component device
*
* Description:
* Merges queue limits for a top device and a block_device. Returns
* 0 if alignment didn't change. Returns -1 if adding the bottom
* device caused misalignment.
*/
int bdev_stack_limits(struct queue_limits *t, struct block_device *bdev,
sector_t start)
{
struct request_queue *bq = bdev_get_queue(bdev);
start += get_start_sect(bdev);
return blk_stack_limits(t, &bq->limits, start);
}
EXPORT_SYMBOL(bdev_stack_limits);
/**
* disk_stack_limits - adjust queue limits for stacked drivers
* @disk: MD/DM gendisk (top)
* @bdev: the underlying block device (bottom)
* @offset: offset to beginning of data within component device
*
* Description:
* Merges the limits for a top level gendisk and a bottom level
* block_device.
*/
void disk_stack_limits(struct gendisk *disk, struct block_device *bdev,
sector_t offset)
{
struct request_queue *t = disk->queue;
if (bdev_stack_limits(&t->limits, bdev, offset >> 9) < 0) {
char top[BDEVNAME_SIZE], bottom[BDEVNAME_SIZE];
disk_name(disk, 0, top);
bdevname(bdev, bottom);
printk(KERN_NOTICE "%s: Warning: Device %s is misaligned\n",
top, bottom);
}
}
EXPORT_SYMBOL(disk_stack_limits);
/**
* blk_queue_dma_pad - set pad mask
* @q: the request queue for the device
* @mask: pad mask
*
* Set dma pad mask.
*
* Appending pad buffer to a request modifies the last entry of a
* scatter list such that it includes the pad buffer.
**/
void blk_queue_dma_pad(struct request_queue *q, unsigned int mask)
{
q->dma_pad_mask = mask;
}
EXPORT_SYMBOL(blk_queue_dma_pad);
/**
* blk_queue_update_dma_pad - update pad mask
* @q: the request queue for the device
* @mask: pad mask
*
* Update dma pad mask.
*
* Appending pad buffer to a request modifies the last entry of a
* scatter list such that it includes the pad buffer.
**/
void blk_queue_update_dma_pad(struct request_queue *q, unsigned int mask)
{
if (mask > q->dma_pad_mask)
q->dma_pad_mask = mask;
}
EXPORT_SYMBOL(blk_queue_update_dma_pad);
/**
* blk_queue_dma_drain - Set up a drain buffer for excess dma.
* @q: the request queue for the device
* @dma_drain_needed: fn which returns non-zero if drain is necessary
* @buf: physically contiguous buffer
* @size: size of the buffer in bytes
*
* Some devices have excess DMA problems and can't simply discard (or
* zero fill) the unwanted piece of the transfer. They have to have a
* real area of memory to transfer it into. The use case for this is
* ATAPI devices in DMA mode. If the packet command causes a transfer
* bigger than the transfer size some HBAs will lock up if there
* aren't DMA elements to contain the excess transfer. What this API
* does is adjust the queue so that the buf is always appended
* silently to the scatterlist.
*
* Note: This routine adjusts max_hw_segments to make room for appending
* the drain buffer. If you call blk_queue_max_segments() after calling
* this routine, you must set the limit to one fewer than your device
* can support otherwise there won't be room for the drain buffer.
*/
int blk_queue_dma_drain(struct request_queue *q,
dma_drain_needed_fn *dma_drain_needed,
void *buf, unsigned int size)
{
if (queue_max_segments(q) < 2)
return -EINVAL;
/* make room for appending the drain */
blk_queue_max_segments(q, queue_max_segments(q) - 1);
q->dma_drain_needed = dma_drain_needed;
q->dma_drain_buffer = buf;
q->dma_drain_size = size;
return 0;
}
EXPORT_SYMBOL_GPL(blk_queue_dma_drain);
/**
* blk_queue_segment_boundary - set boundary rules for segment merging
* @q: the request queue for the device
* @mask: the memory boundary mask
**/
void blk_queue_segment_boundary(struct request_queue *q, unsigned long mask)
{
if (mask < PAGE_CACHE_SIZE - 1) {
mask = PAGE_CACHE_SIZE - 1;
printk(KERN_INFO "%s: set to minimum %lx\n",
__func__, mask);
}
q->limits.seg_boundary_mask = mask;
}
EXPORT_SYMBOL(blk_queue_segment_boundary);
/**
* blk_queue_dma_alignment - set dma length and memory alignment
* @q: the request queue for the device
* @mask: alignment mask
*
* description:
* set required memory and length alignment for direct dma transactions.
* this is used when building direct io requests for the queue.
*
**/
void blk_queue_dma_alignment(struct request_queue *q, int mask)
{
q->dma_alignment = mask;
}
EXPORT_SYMBOL(blk_queue_dma_alignment);
/**
* blk_queue_update_dma_alignment - update dma length and memory alignment
* @q: the request queue for the device
* @mask: alignment mask
*
* description:
* update required memory and length alignment for direct dma transactions.
* If the requested alignment is larger than the current alignment, then
* the current queue alignment is updated to the new value, otherwise it
* is left alone. The design of this is to allow multiple objects
* (driver, device, transport etc) to set their respective
* alignments without having them interfere.
*
**/
void blk_queue_update_dma_alignment(struct request_queue *q, int mask)
{
BUG_ON(mask > PAGE_SIZE);
if (mask > q->dma_alignment)
q->dma_alignment = mask;
}
EXPORT_SYMBOL(blk_queue_update_dma_alignment);
/**
* blk_queue_flush - configure queue's cache flush capability
* @q: the request queue for the device
* @flush: 0, REQ_FLUSH or REQ_FLUSH | REQ_FUA
*
* Tell block layer cache flush capability of @q. If it supports
* flushing, REQ_FLUSH should be set. If it supports bypassing
* write cache for individual writes, REQ_FUA should be set.
*/
void blk_queue_flush(struct request_queue *q, unsigned int flush)
{
WARN_ON_ONCE(flush & ~(REQ_FLUSH | REQ_FUA));
if (WARN_ON_ONCE(!(flush & REQ_FLUSH) && (flush & REQ_FUA)))
flush &= ~REQ_FUA;
q->flush_flags = flush & (REQ_FLUSH | REQ_FUA);
}
EXPORT_SYMBOL_GPL(blk_queue_flush);
void blk_queue_flush_queueable(struct request_queue *q, bool queueable)
{
q->flush_not_queueable = !queueable;
}
EXPORT_SYMBOL_GPL(blk_queue_flush_queueable);
static int __init blk_settings_init(void)
{
blk_max_low_pfn = max_low_pfn - 1;
blk_max_pfn = max_pfn - 1;
return 0;
}
subsys_initcall(blk_settings_init);
| gpl-2.0 |
MoKee/android_kernel_cyanogen_msm8916-amss | arch/powerpc/kernel/dma-iommu.c | 2436 | 3620 | /*
* Copyright (C) 2006 Benjamin Herrenschmidt, IBM Corporation
*
* Provide default implementations of the DMA mapping callbacks for
* busses using the iommu infrastructure
*/
#include <linux/export.h>
#include <asm/iommu.h>
/*
* Generic iommu implementation
*/
/* Allocates a contiguous real buffer and creates mappings over it.
* Returns the virtual address of the buffer and sets dma_handle
* to the dma address (mapping) of the first page.
*/
static void *dma_iommu_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flag,
struct dma_attrs *attrs)
{
return iommu_alloc_coherent(dev, get_iommu_table_base(dev), size,
dma_handle, dev->coherent_dma_mask, flag,
dev_to_node(dev));
}
static void dma_iommu_free_coherent(struct device *dev, size_t size,
void *vaddr, dma_addr_t dma_handle,
struct dma_attrs *attrs)
{
iommu_free_coherent(get_iommu_table_base(dev), size, vaddr, dma_handle);
}
/* Creates TCEs for a user provided buffer. The user buffer must be
* contiguous real kernel storage (not vmalloc). The address passed here
* comprises a page address and offset into that page. The dma_addr_t
* returned will point to the same byte within the page as was passed in.
*/
static dma_addr_t dma_iommu_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction direction,
struct dma_attrs *attrs)
{
return iommu_map_page(dev, get_iommu_table_base(dev), page, offset,
size, device_to_mask(dev), direction, attrs);
}
static void dma_iommu_unmap_page(struct device *dev, dma_addr_t dma_handle,
size_t size, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
iommu_unmap_page(get_iommu_table_base(dev), dma_handle, size, direction,
attrs);
}
static int dma_iommu_map_sg(struct device *dev, struct scatterlist *sglist,
int nelems, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
return iommu_map_sg(dev, get_iommu_table_base(dev), sglist, nelems,
device_to_mask(dev), direction, attrs);
}
static void dma_iommu_unmap_sg(struct device *dev, struct scatterlist *sglist,
int nelems, enum dma_data_direction direction,
struct dma_attrs *attrs)
{
iommu_unmap_sg(get_iommu_table_base(dev), sglist, nelems, direction,
attrs);
}
/* We support DMA to/from any memory page via the iommu */
static int dma_iommu_dma_supported(struct device *dev, u64 mask)
{
struct iommu_table *tbl = get_iommu_table_base(dev);
if (!tbl) {
dev_info(dev, "Warning: IOMMU dma not supported: mask 0x%08llx"
", table unavailable\n", mask);
return 0;
}
if (tbl->it_offset > (mask >> IOMMU_PAGE_SHIFT)) {
dev_info(dev, "Warning: IOMMU offset too big for device mask\n");
dev_info(dev, "mask: 0x%08llx, table offset: 0x%08lx\n",
mask, tbl->it_offset << IOMMU_PAGE_SHIFT);
return 0;
} else
return 1;
}
static u64 dma_iommu_get_required_mask(struct device *dev)
{
struct iommu_table *tbl = get_iommu_table_base(dev);
u64 mask;
if (!tbl)
return 0;
mask = 1ULL < (fls_long(tbl->it_offset + tbl->it_size) - 1);
mask += mask - 1;
return mask;
}
struct dma_map_ops dma_iommu_ops = {
.alloc = dma_iommu_alloc_coherent,
.free = dma_iommu_free_coherent,
.mmap = dma_direct_mmap_coherent,
.map_sg = dma_iommu_map_sg,
.unmap_sg = dma_iommu_unmap_sg,
.dma_supported = dma_iommu_dma_supported,
.map_page = dma_iommu_map_page,
.unmap_page = dma_iommu_unmap_page,
.get_required_mask = dma_iommu_get_required_mask,
};
EXPORT_SYMBOL(dma_iommu_ops);
| gpl-2.0 |
teemodk/android_kernel_htc_endeavoru | drivers/usb/serial/moto_modem.c | 3204 | 1888 | /*
* Motorola USB Phone driver
*
* Copyright (C) 2008 Greg Kroah-Hartman <greg@kroah.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* {sigh}
* Motorola should be using the CDC ACM USB spec, but instead
* they try to just "do their own thing"... This driver should handle a
* few phones in which a basic "dumb serial connection" is needed to be
* able to get a connection through to them.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(0x05c6, 0x3197) }, /* unknown Motorola phone */
{ USB_DEVICE(0x0c44, 0x0022) }, /* unknown Mororola phone */
{ USB_DEVICE(0x22b8, 0x2a64) }, /* Motorola KRZR K1m */
{ USB_DEVICE(0x22b8, 0x2c84) }, /* Motorola VE240 phone */
{ USB_DEVICE(0x22b8, 0x2c64) }, /* Motorola V950 phone */
{ },
};
MODULE_DEVICE_TABLE(usb, id_table);
static struct usb_driver moto_driver = {
.name = "moto-modem",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
.no_dynamic_id = 1,
};
static struct usb_serial_driver moto_device = {
.driver = {
.owner = THIS_MODULE,
.name = "moto-modem",
},
.id_table = id_table,
.usb_driver = &moto_driver,
.num_ports = 1,
};
static int __init moto_init(void)
{
int retval;
retval = usb_serial_register(&moto_device);
if (retval)
return retval;
retval = usb_register(&moto_driver);
if (retval)
usb_serial_deregister(&moto_device);
return retval;
}
static void __exit moto_exit(void)
{
usb_deregister(&moto_driver);
usb_serial_deregister(&moto_device);
}
module_init(moto_init);
module_exit(moto_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
NStep/nx_bullhead | drivers/s390/block/scm_drv.c | 4484 | 1786 | /*
* Device driver for s390 storage class memory.
*
* Copyright IBM Corp. 2012
* Author(s): Sebastian Ott <sebott@linux.vnet.ibm.com>
*/
#define KMSG_COMPONENT "scm_block"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/slab.h>
#include <asm/eadm.h>
#include "scm_blk.h"
static void scm_notify(struct scm_device *scmdev, enum scm_event event)
{
struct scm_blk_dev *bdev = dev_get_drvdata(&scmdev->dev);
switch (event) {
case SCM_CHANGE:
pr_info("%lx: The capabilities of the SCM increment changed\n",
(unsigned long) scmdev->address);
SCM_LOG(2, "State changed");
SCM_LOG_STATE(2, scmdev);
break;
case SCM_AVAIL:
SCM_LOG(2, "Increment available");
SCM_LOG_STATE(2, scmdev);
scm_blk_set_available(bdev);
break;
}
}
static int scm_probe(struct scm_device *scmdev)
{
struct scm_blk_dev *bdev;
int ret;
SCM_LOG(2, "probe");
SCM_LOG_STATE(2, scmdev);
if (scmdev->attrs.oper_state != OP_STATE_GOOD)
return -EINVAL;
bdev = kzalloc(sizeof(*bdev), GFP_KERNEL);
if (!bdev)
return -ENOMEM;
dev_set_drvdata(&scmdev->dev, bdev);
ret = scm_blk_dev_setup(bdev, scmdev);
if (ret) {
dev_set_drvdata(&scmdev->dev, NULL);
kfree(bdev);
goto out;
}
out:
return ret;
}
static int scm_remove(struct scm_device *scmdev)
{
struct scm_blk_dev *bdev = dev_get_drvdata(&scmdev->dev);
scm_blk_dev_cleanup(bdev);
dev_set_drvdata(&scmdev->dev, NULL);
kfree(bdev);
return 0;
}
static struct scm_driver scm_drv = {
.drv = {
.name = "scm_block",
.owner = THIS_MODULE,
},
.notify = scm_notify,
.probe = scm_probe,
.remove = scm_remove,
.handler = scm_blk_irq,
};
int __init scm_drv_init(void)
{
return scm_driver_register(&scm_drv);
}
void scm_drv_cleanup(void)
{
scm_driver_unregister(&scm_drv);
}
| gpl-2.0 |
CyanogenMod/android_kernel_oneplus_msm8974 | arch/arm/mach-kirkwood/t5325-setup.c | 4740 | 4742 | /*
*
* HP t5325 Thin Client setup
*
* Copyright (C) 2010 Martin Michlmayr <tbm@cyrius.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/physmap.h>
#include <linux/spi/flash.h>
#include <linux/spi/spi.h>
#include <linux/spi/orion_spi.h>
#include <linux/i2c.h>
#include <linux/mv643xx_eth.h>
#include <linux/ata_platform.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <sound/alc5623.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/kirkwood.h>
#include "common.h"
#include "mpp.h"
struct mtd_partition hp_t5325_partitions[] = {
{
.name = "u-boot env",
.size = SZ_64K,
.offset = SZ_512K + SZ_256K,
},
{
.name = "permanent u-boot env",
.size = SZ_64K,
.offset = MTDPART_OFS_APPEND,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "HP env",
.size = SZ_64K,
.offset = MTDPART_OFS_APPEND,
},
{
.name = "u-boot",
.size = SZ_512K,
.offset = 0,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "SSD firmware",
.size = SZ_256K,
.offset = SZ_512K,
},
};
const struct flash_platform_data hp_t5325_flash = {
.type = "mx25l8005",
.name = "spi_flash",
.parts = hp_t5325_partitions,
.nr_parts = ARRAY_SIZE(hp_t5325_partitions),
};
struct spi_board_info __initdata hp_t5325_spi_slave_info[] = {
{
.modalias = "m25p80",
.platform_data = &hp_t5325_flash,
.irq = -1,
},
};
static struct mv643xx_eth_platform_data hp_t5325_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(8),
};
static struct mv_sata_platform_data hp_t5325_sata_data = {
.n_ports = 2,
};
static struct gpio_keys_button hp_t5325_buttons[] = {
{
.code = KEY_POWER,
.gpio = 45,
.desc = "Power",
.active_low = 1,
},
};
static struct gpio_keys_platform_data hp_t5325_button_data = {
.buttons = hp_t5325_buttons,
.nbuttons = ARRAY_SIZE(hp_t5325_buttons),
};
static struct platform_device hp_t5325_button_device = {
.name = "gpio-keys",
.id = -1,
.num_resources = 0,
.dev = {
.platform_data = &hp_t5325_button_data,
}
};
static struct platform_device hp_t5325_audio_device = {
.name = "t5325-audio",
.id = -1,
};
static unsigned int hp_t5325_mpp_config[] __initdata = {
MPP0_NF_IO2,
MPP1_SPI_MOSI,
MPP2_SPI_SCK,
MPP3_SPI_MISO,
MPP4_NF_IO6,
MPP5_NF_IO7,
MPP6_SYSRST_OUTn,
MPP7_SPI_SCn,
MPP8_TW0_SDA,
MPP9_TW0_SCK,
MPP10_UART0_TXD,
MPP11_UART0_RXD,
MPP12_SD_CLK,
MPP13_GPIO,
MPP14_GPIO,
MPP15_GPIO,
MPP16_GPIO,
MPP17_GPIO,
MPP18_NF_IO0,
MPP19_NF_IO1,
MPP20_GPIO,
MPP21_GPIO,
MPP22_GPIO,
MPP23_GPIO,
MPP32_GPIO,
MPP33_GE1_TXCTL,
MPP39_AU_I2SBCLK,
MPP40_AU_I2SDO,
MPP43_AU_I2SDI,
MPP41_AU_I2SLRCLK,
MPP42_AU_I2SMCLK,
MPP45_GPIO, /* Power button */
MPP48_GPIO, /* Board power off */
0
};
static struct alc5623_platform_data alc5621_data = {
.add_ctrl = 0x3700,
.jack_det_ctrl = 0x4810,
};
static struct i2c_board_info i2c_board_info[] __initdata = {
{
I2C_BOARD_INFO("alc5621", 0x1a),
.platform_data = &alc5621_data,
},
};
#define HP_T5325_GPIO_POWER_OFF 48
static void hp_t5325_power_off(void)
{
gpio_set_value(HP_T5325_GPIO_POWER_OFF, 1);
}
static void __init hp_t5325_init(void)
{
/*
* Basic setup. Needs to be called early.
*/
kirkwood_init();
kirkwood_mpp_conf(hp_t5325_mpp_config);
kirkwood_uart0_init();
spi_register_board_info(hp_t5325_spi_slave_info,
ARRAY_SIZE(hp_t5325_spi_slave_info));
kirkwood_spi_init();
kirkwood_i2c_init();
kirkwood_ge00_init(&hp_t5325_ge00_data);
kirkwood_sata_init(&hp_t5325_sata_data);
kirkwood_ehci_init();
platform_device_register(&hp_t5325_button_device);
platform_device_register(&hp_t5325_audio_device);
i2c_register_board_info(0, i2c_board_info, ARRAY_SIZE(i2c_board_info));
kirkwood_audio_init();
if (gpio_request(HP_T5325_GPIO_POWER_OFF, "power-off") == 0 &&
gpio_direction_output(HP_T5325_GPIO_POWER_OFF, 0) == 0)
pm_power_off = hp_t5325_power_off;
else
pr_err("t5325: failed to configure power-off GPIO\n");
}
static int __init hp_t5325_pci_init(void)
{
if (machine_is_t5325())
kirkwood_pcie_init(KW_PCIE0);
return 0;
}
subsys_initcall(hp_t5325_pci_init);
MACHINE_START(T5325, "HP t5325 Thin Client")
/* Maintainer: Martin Michlmayr <tbm@cyrius.com> */
.atag_offset = 0x100,
.init_machine = hp_t5325_init,
.map_io = kirkwood_map_io,
.init_early = kirkwood_init_early,
.init_irq = kirkwood_init_irq,
.timer = &kirkwood_timer,
.restart = kirkwood_restart,
MACHINE_END
| gpl-2.0 |
M1cha/backup_android_kernel_xiaomi_aries | kernel/profile.c | 4996 | 17053 | /*
* linux/kernel/profile.c
* Simple profiling. Manages a direct-mapped profile hit count buffer,
* with configurable resolution, support for restricting the cpus on
* which profiling is done, and switching between cpu time and
* schedule() calls via kernel command line parameters passed at boot.
*
* Scheduler profiling support, Arjan van de Ven and Ingo Molnar,
* Red Hat, July 2004
* Consolidation of architecture support code for profiling,
* William Irwin, Oracle, July 2004
* Amortized hit count accounting via per-cpu open-addressed hashtables
* to resolve timer interrupt livelocks, William Irwin, Oracle, 2004
*/
#include <linux/export.h>
#include <linux/profile.h>
#include <linux/bootmem.h>
#include <linux/notifier.h>
#include <linux/mm.h>
#include <linux/cpumask.h>
#include <linux/cpu.h>
#include <linux/highmem.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <asm/sections.h>
#include <asm/irq_regs.h>
#include <asm/ptrace.h>
struct profile_hit {
u32 pc, hits;
};
#define PROFILE_GRPSHIFT 3
#define PROFILE_GRPSZ (1 << PROFILE_GRPSHIFT)
#define NR_PROFILE_HIT (PAGE_SIZE/sizeof(struct profile_hit))
#define NR_PROFILE_GRP (NR_PROFILE_HIT/PROFILE_GRPSZ)
/* Oprofile timer tick hook */
static int (*timer_hook)(struct pt_regs *) __read_mostly;
static atomic_t *prof_buffer;
static unsigned long prof_len, prof_shift;
int prof_on __read_mostly;
EXPORT_SYMBOL_GPL(prof_on);
static cpumask_var_t prof_cpu_mask;
#ifdef CONFIG_SMP
static DEFINE_PER_CPU(struct profile_hit *[2], cpu_profile_hits);
static DEFINE_PER_CPU(int, cpu_profile_flip);
static DEFINE_MUTEX(profile_flip_mutex);
#endif /* CONFIG_SMP */
int profile_setup(char *str)
{
static char schedstr[] = "schedule";
static char sleepstr[] = "sleep";
static char kvmstr[] = "kvm";
int par;
if (!strncmp(str, sleepstr, strlen(sleepstr))) {
#ifdef CONFIG_SCHEDSTATS
prof_on = SLEEP_PROFILING;
if (str[strlen(sleepstr)] == ',')
str += strlen(sleepstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel sleep profiling enabled (shift: %ld)\n",
prof_shift);
#else
printk(KERN_WARNING
"kernel sleep profiling requires CONFIG_SCHEDSTATS\n");
#endif /* CONFIG_SCHEDSTATS */
} else if (!strncmp(str, schedstr, strlen(schedstr))) {
prof_on = SCHED_PROFILING;
if (str[strlen(schedstr)] == ',')
str += strlen(schedstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel schedule profiling enabled (shift: %ld)\n",
prof_shift);
} else if (!strncmp(str, kvmstr, strlen(kvmstr))) {
prof_on = KVM_PROFILING;
if (str[strlen(kvmstr)] == ',')
str += strlen(kvmstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel KVM profiling enabled (shift: %ld)\n",
prof_shift);
} else if (get_option(&str, &par)) {
prof_shift = par;
prof_on = CPU_PROFILING;
printk(KERN_INFO "kernel profiling enabled (shift: %ld)\n",
prof_shift);
}
return 1;
}
__setup("profile=", profile_setup);
int __ref profile_init(void)
{
int buffer_bytes;
if (!prof_on)
return 0;
/* only text is profiled */
prof_len = (_etext - _stext) >> prof_shift;
buffer_bytes = prof_len*sizeof(atomic_t);
if (!alloc_cpumask_var(&prof_cpu_mask, GFP_KERNEL))
return -ENOMEM;
cpumask_copy(prof_cpu_mask, cpu_possible_mask);
prof_buffer = kzalloc(buffer_bytes, GFP_KERNEL|__GFP_NOWARN);
if (prof_buffer)
return 0;
prof_buffer = alloc_pages_exact(buffer_bytes,
GFP_KERNEL|__GFP_ZERO|__GFP_NOWARN);
if (prof_buffer)
return 0;
prof_buffer = vzalloc(buffer_bytes);
if (prof_buffer)
return 0;
free_cpumask_var(prof_cpu_mask);
return -ENOMEM;
}
/* Profile event notifications */
static BLOCKING_NOTIFIER_HEAD(task_exit_notifier);
static ATOMIC_NOTIFIER_HEAD(task_free_notifier);
static BLOCKING_NOTIFIER_HEAD(munmap_notifier);
void profile_task_exit(struct task_struct *task)
{
blocking_notifier_call_chain(&task_exit_notifier, 0, task);
}
int profile_handoff_task(struct task_struct *task)
{
int ret;
ret = atomic_notifier_call_chain(&task_free_notifier, 0, task);
return (ret == NOTIFY_OK) ? 1 : 0;
}
void profile_munmap(unsigned long addr)
{
blocking_notifier_call_chain(&munmap_notifier, 0, (void *)addr);
}
int task_handoff_register(struct notifier_block *n)
{
return atomic_notifier_chain_register(&task_free_notifier, n);
}
EXPORT_SYMBOL_GPL(task_handoff_register);
int task_handoff_unregister(struct notifier_block *n)
{
return atomic_notifier_chain_unregister(&task_free_notifier, n);
}
EXPORT_SYMBOL_GPL(task_handoff_unregister);
int profile_event_register(enum profile_type type, struct notifier_block *n)
{
int err = -EINVAL;
switch (type) {
case PROFILE_TASK_EXIT:
err = blocking_notifier_chain_register(
&task_exit_notifier, n);
break;
case PROFILE_MUNMAP:
err = blocking_notifier_chain_register(
&munmap_notifier, n);
break;
}
return err;
}
EXPORT_SYMBOL_GPL(profile_event_register);
int profile_event_unregister(enum profile_type type, struct notifier_block *n)
{
int err = -EINVAL;
switch (type) {
case PROFILE_TASK_EXIT:
err = blocking_notifier_chain_unregister(
&task_exit_notifier, n);
break;
case PROFILE_MUNMAP:
err = blocking_notifier_chain_unregister(
&munmap_notifier, n);
break;
}
return err;
}
EXPORT_SYMBOL_GPL(profile_event_unregister);
int register_timer_hook(int (*hook)(struct pt_regs *))
{
if (timer_hook)
return -EBUSY;
timer_hook = hook;
return 0;
}
EXPORT_SYMBOL_GPL(register_timer_hook);
void unregister_timer_hook(int (*hook)(struct pt_regs *))
{
WARN_ON(hook != timer_hook);
timer_hook = NULL;
/* make sure all CPUs see the NULL hook */
synchronize_sched(); /* Allow ongoing interrupts to complete. */
}
EXPORT_SYMBOL_GPL(unregister_timer_hook);
#ifdef CONFIG_SMP
/*
* Each cpu has a pair of open-addressed hashtables for pending
* profile hits. read_profile() IPI's all cpus to request them
* to flip buffers and flushes their contents to prof_buffer itself.
* Flip requests are serialized by the profile_flip_mutex. The sole
* use of having a second hashtable is for avoiding cacheline
* contention that would otherwise happen during flushes of pending
* profile hits required for the accuracy of reported profile hits
* and so resurrect the interrupt livelock issue.
*
* The open-addressed hashtables are indexed by profile buffer slot
* and hold the number of pending hits to that profile buffer slot on
* a cpu in an entry. When the hashtable overflows, all pending hits
* are accounted to their corresponding profile buffer slots with
* atomic_add() and the hashtable emptied. As numerous pending hits
* may be accounted to a profile buffer slot in a hashtable entry,
* this amortizes a number of atomic profile buffer increments likely
* to be far larger than the number of entries in the hashtable,
* particularly given that the number of distinct profile buffer
* positions to which hits are accounted during short intervals (e.g.
* several seconds) is usually very small. Exclusion from buffer
* flipping is provided by interrupt disablement (note that for
* SCHED_PROFILING or SLEEP_PROFILING profile_hit() may be called from
* process context).
* The hash function is meant to be lightweight as opposed to strong,
* and was vaguely inspired by ppc64 firmware-supported inverted
* pagetable hash functions, but uses a full hashtable full of finite
* collision chains, not just pairs of them.
*
* -- wli
*/
static void __profile_flip_buffers(void *unused)
{
int cpu = smp_processor_id();
per_cpu(cpu_profile_flip, cpu) = !per_cpu(cpu_profile_flip, cpu);
}
static void profile_flip_buffers(void)
{
int i, j, cpu;
mutex_lock(&profile_flip_mutex);
j = per_cpu(cpu_profile_flip, get_cpu());
put_cpu();
on_each_cpu(__profile_flip_buffers, NULL, 1);
for_each_online_cpu(cpu) {
struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[j];
for (i = 0; i < NR_PROFILE_HIT; ++i) {
if (!hits[i].hits) {
if (hits[i].pc)
hits[i].pc = 0;
continue;
}
atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
hits[i].hits = hits[i].pc = 0;
}
}
mutex_unlock(&profile_flip_mutex);
}
static void profile_discard_flip_buffers(void)
{
int i, cpu;
mutex_lock(&profile_flip_mutex);
i = per_cpu(cpu_profile_flip, get_cpu());
put_cpu();
on_each_cpu(__profile_flip_buffers, NULL, 1);
for_each_online_cpu(cpu) {
struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[i];
memset(hits, 0, NR_PROFILE_HIT*sizeof(struct profile_hit));
}
mutex_unlock(&profile_flip_mutex);
}
static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
{
unsigned long primary, secondary, flags, pc = (unsigned long)__pc;
int i, j, cpu;
struct profile_hit *hits;
pc = min((pc - (unsigned long)_stext) >> prof_shift, prof_len - 1);
i = primary = (pc & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
secondary = (~(pc << 1) & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
cpu = get_cpu();
hits = per_cpu(cpu_profile_hits, cpu)[per_cpu(cpu_profile_flip, cpu)];
if (!hits) {
put_cpu();
return;
}
/*
* We buffer the global profiler buffer into a per-CPU
* queue and thus reduce the number of global (and possibly
* NUMA-alien) accesses. The write-queue is self-coalescing:
*/
local_irq_save(flags);
do {
for (j = 0; j < PROFILE_GRPSZ; ++j) {
if (hits[i + j].pc == pc) {
hits[i + j].hits += nr_hits;
goto out;
} else if (!hits[i + j].hits) {
hits[i + j].pc = pc;
hits[i + j].hits = nr_hits;
goto out;
}
}
i = (i + secondary) & (NR_PROFILE_HIT - 1);
} while (i != primary);
/*
* Add the current hit(s) and flush the write-queue out
* to the global buffer:
*/
atomic_add(nr_hits, &prof_buffer[pc]);
for (i = 0; i < NR_PROFILE_HIT; ++i) {
atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
hits[i].pc = hits[i].hits = 0;
}
out:
local_irq_restore(flags);
put_cpu();
}
static int __cpuinit profile_cpu_callback(struct notifier_block *info,
unsigned long action, void *__cpu)
{
int node, cpu = (unsigned long)__cpu;
struct page *page;
switch (action) {
case CPU_UP_PREPARE:
case CPU_UP_PREPARE_FROZEN:
node = cpu_to_mem(cpu);
per_cpu(cpu_profile_flip, cpu) = 0;
if (!per_cpu(cpu_profile_hits, cpu)[1]) {
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO,
0);
if (!page)
return notifier_from_errno(-ENOMEM);
per_cpu(cpu_profile_hits, cpu)[1] = page_address(page);
}
if (!per_cpu(cpu_profile_hits, cpu)[0]) {
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO,
0);
if (!page)
goto out_free;
per_cpu(cpu_profile_hits, cpu)[0] = page_address(page);
}
break;
out_free:
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
return notifier_from_errno(-ENOMEM);
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
if (prof_cpu_mask != NULL)
cpumask_set_cpu(cpu, prof_cpu_mask);
break;
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
case CPU_DEAD:
case CPU_DEAD_FROZEN:
if (prof_cpu_mask != NULL)
cpumask_clear_cpu(cpu, prof_cpu_mask);
if (per_cpu(cpu_profile_hits, cpu)[0]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[0]);
per_cpu(cpu_profile_hits, cpu)[0] = NULL;
__free_page(page);
}
if (per_cpu(cpu_profile_hits, cpu)[1]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
}
break;
}
return NOTIFY_OK;
}
#else /* !CONFIG_SMP */
#define profile_flip_buffers() do { } while (0)
#define profile_discard_flip_buffers() do { } while (0)
#define profile_cpu_callback NULL
static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
{
unsigned long pc;
pc = ((unsigned long)__pc - (unsigned long)_stext) >> prof_shift;
atomic_add(nr_hits, &prof_buffer[min(pc, prof_len - 1)]);
}
#endif /* !CONFIG_SMP */
void profile_hits(int type, void *__pc, unsigned int nr_hits)
{
if (prof_on != type || !prof_buffer)
return;
do_profile_hits(type, __pc, nr_hits);
}
EXPORT_SYMBOL_GPL(profile_hits);
void profile_tick(int type)
{
struct pt_regs *regs = get_irq_regs();
if (type == CPU_PROFILING && timer_hook)
timer_hook(regs);
if (!user_mode(regs) && prof_cpu_mask != NULL &&
cpumask_test_cpu(smp_processor_id(), prof_cpu_mask))
profile_hit(type, (void *)profile_pc(regs));
}
#ifdef CONFIG_PROC_FS
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>
static int prof_cpu_mask_proc_show(struct seq_file *m, void *v)
{
seq_cpumask(m, prof_cpu_mask);
seq_putc(m, '\n');
return 0;
}
static int prof_cpu_mask_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, prof_cpu_mask_proc_show, NULL);
}
static ssize_t prof_cpu_mask_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
cpumask_var_t new_value;
int err;
if (!alloc_cpumask_var(&new_value, GFP_KERNEL))
return -ENOMEM;
err = cpumask_parse_user(buffer, count, new_value);
if (!err) {
cpumask_copy(prof_cpu_mask, new_value);
err = count;
}
free_cpumask_var(new_value);
return err;
}
static const struct file_operations prof_cpu_mask_proc_fops = {
.open = prof_cpu_mask_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = prof_cpu_mask_proc_write,
};
void create_prof_cpu_mask(struct proc_dir_entry *root_irq_dir)
{
/* create /proc/irq/prof_cpu_mask */
proc_create("prof_cpu_mask", 0600, root_irq_dir, &prof_cpu_mask_proc_fops);
}
/*
* This function accesses profiling information. The returned data is
* binary: the sampling step and the actual contents of the profile
* buffer. Use of the program readprofile is recommended in order to
* get meaningful info out of these data.
*/
static ssize_t
read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
unsigned long p = *ppos;
ssize_t read;
char *pnt;
unsigned int sample_step = 1 << prof_shift;
profile_flip_buffers();
if (p >= (prof_len+1)*sizeof(unsigned int))
return 0;
if (count > (prof_len+1)*sizeof(unsigned int) - p)
count = (prof_len+1)*sizeof(unsigned int) - p;
read = 0;
while (p < sizeof(unsigned int) && count > 0) {
if (put_user(*((char *)(&sample_step)+p), buf))
return -EFAULT;
buf++; p++; count--; read++;
}
pnt = (char *)prof_buffer + p - sizeof(atomic_t);
if (copy_to_user(buf, (void *)pnt, count))
return -EFAULT;
read += count;
*ppos += read;
return read;
}
/*
* Writing to /proc/profile resets the counters
*
* Writing a 'profiling multiplier' value into it also re-sets the profiling
* interrupt frequency, on architectures that support this.
*/
static ssize_t write_profile(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
#ifdef CONFIG_SMP
extern int setup_profiling_timer(unsigned int multiplier);
if (count == sizeof(int)) {
unsigned int multiplier;
if (copy_from_user(&multiplier, buf, sizeof(int)))
return -EFAULT;
if (setup_profiling_timer(multiplier))
return -EINVAL;
}
#endif
profile_discard_flip_buffers();
memset(prof_buffer, 0, prof_len * sizeof(atomic_t));
return count;
}
static const struct file_operations proc_profile_operations = {
.read = read_profile,
.write = write_profile,
.llseek = default_llseek,
};
#ifdef CONFIG_SMP
static void profile_nop(void *unused)
{
}
static int create_hash_tables(void)
{
int cpu;
for_each_online_cpu(cpu) {
int node = cpu_to_mem(cpu);
struct page *page;
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO | GFP_THISNODE,
0);
if (!page)
goto out_cleanup;
per_cpu(cpu_profile_hits, cpu)[1]
= (struct profile_hit *)page_address(page);
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO | GFP_THISNODE,
0);
if (!page)
goto out_cleanup;
per_cpu(cpu_profile_hits, cpu)[0]
= (struct profile_hit *)page_address(page);
}
return 0;
out_cleanup:
prof_on = 0;
smp_mb();
on_each_cpu(profile_nop, NULL, 1);
for_each_online_cpu(cpu) {
struct page *page;
if (per_cpu(cpu_profile_hits, cpu)[0]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[0]);
per_cpu(cpu_profile_hits, cpu)[0] = NULL;
__free_page(page);
}
if (per_cpu(cpu_profile_hits, cpu)[1]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
}
}
return -1;
}
#else
#define create_hash_tables() ({ 0; })
#endif
int __ref create_proc_profile(void) /* false positive from hotcpu_notifier */
{
struct proc_dir_entry *entry;
if (!prof_on)
return 0;
if (create_hash_tables())
return -ENOMEM;
entry = proc_create("profile", S_IWUSR | S_IRUGO,
NULL, &proc_profile_operations);
if (!entry)
return 0;
entry->size = (1+prof_len) * sizeof(atomic_t);
hotcpu_notifier(profile_cpu_callback, 0);
return 0;
}
module_init(create_proc_profile);
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
jpihet/linux-omap | kernel/profile.c | 4996 | 17053 | /*
* linux/kernel/profile.c
* Simple profiling. Manages a direct-mapped profile hit count buffer,
* with configurable resolution, support for restricting the cpus on
* which profiling is done, and switching between cpu time and
* schedule() calls via kernel command line parameters passed at boot.
*
* Scheduler profiling support, Arjan van de Ven and Ingo Molnar,
* Red Hat, July 2004
* Consolidation of architecture support code for profiling,
* William Irwin, Oracle, July 2004
* Amortized hit count accounting via per-cpu open-addressed hashtables
* to resolve timer interrupt livelocks, William Irwin, Oracle, 2004
*/
#include <linux/export.h>
#include <linux/profile.h>
#include <linux/bootmem.h>
#include <linux/notifier.h>
#include <linux/mm.h>
#include <linux/cpumask.h>
#include <linux/cpu.h>
#include <linux/highmem.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <asm/sections.h>
#include <asm/irq_regs.h>
#include <asm/ptrace.h>
struct profile_hit {
u32 pc, hits;
};
#define PROFILE_GRPSHIFT 3
#define PROFILE_GRPSZ (1 << PROFILE_GRPSHIFT)
#define NR_PROFILE_HIT (PAGE_SIZE/sizeof(struct profile_hit))
#define NR_PROFILE_GRP (NR_PROFILE_HIT/PROFILE_GRPSZ)
/* Oprofile timer tick hook */
static int (*timer_hook)(struct pt_regs *) __read_mostly;
static atomic_t *prof_buffer;
static unsigned long prof_len, prof_shift;
int prof_on __read_mostly;
EXPORT_SYMBOL_GPL(prof_on);
static cpumask_var_t prof_cpu_mask;
#ifdef CONFIG_SMP
static DEFINE_PER_CPU(struct profile_hit *[2], cpu_profile_hits);
static DEFINE_PER_CPU(int, cpu_profile_flip);
static DEFINE_MUTEX(profile_flip_mutex);
#endif /* CONFIG_SMP */
int profile_setup(char *str)
{
static char schedstr[] = "schedule";
static char sleepstr[] = "sleep";
static char kvmstr[] = "kvm";
int par;
if (!strncmp(str, sleepstr, strlen(sleepstr))) {
#ifdef CONFIG_SCHEDSTATS
prof_on = SLEEP_PROFILING;
if (str[strlen(sleepstr)] == ',')
str += strlen(sleepstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel sleep profiling enabled (shift: %ld)\n",
prof_shift);
#else
printk(KERN_WARNING
"kernel sleep profiling requires CONFIG_SCHEDSTATS\n");
#endif /* CONFIG_SCHEDSTATS */
} else if (!strncmp(str, schedstr, strlen(schedstr))) {
prof_on = SCHED_PROFILING;
if (str[strlen(schedstr)] == ',')
str += strlen(schedstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel schedule profiling enabled (shift: %ld)\n",
prof_shift);
} else if (!strncmp(str, kvmstr, strlen(kvmstr))) {
prof_on = KVM_PROFILING;
if (str[strlen(kvmstr)] == ',')
str += strlen(kvmstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel KVM profiling enabled (shift: %ld)\n",
prof_shift);
} else if (get_option(&str, &par)) {
prof_shift = par;
prof_on = CPU_PROFILING;
printk(KERN_INFO "kernel profiling enabled (shift: %ld)\n",
prof_shift);
}
return 1;
}
__setup("profile=", profile_setup);
int __ref profile_init(void)
{
int buffer_bytes;
if (!prof_on)
return 0;
/* only text is profiled */
prof_len = (_etext - _stext) >> prof_shift;
buffer_bytes = prof_len*sizeof(atomic_t);
if (!alloc_cpumask_var(&prof_cpu_mask, GFP_KERNEL))
return -ENOMEM;
cpumask_copy(prof_cpu_mask, cpu_possible_mask);
prof_buffer = kzalloc(buffer_bytes, GFP_KERNEL|__GFP_NOWARN);
if (prof_buffer)
return 0;
prof_buffer = alloc_pages_exact(buffer_bytes,
GFP_KERNEL|__GFP_ZERO|__GFP_NOWARN);
if (prof_buffer)
return 0;
prof_buffer = vzalloc(buffer_bytes);
if (prof_buffer)
return 0;
free_cpumask_var(prof_cpu_mask);
return -ENOMEM;
}
/* Profile event notifications */
static BLOCKING_NOTIFIER_HEAD(task_exit_notifier);
static ATOMIC_NOTIFIER_HEAD(task_free_notifier);
static BLOCKING_NOTIFIER_HEAD(munmap_notifier);
void profile_task_exit(struct task_struct *task)
{
blocking_notifier_call_chain(&task_exit_notifier, 0, task);
}
int profile_handoff_task(struct task_struct *task)
{
int ret;
ret = atomic_notifier_call_chain(&task_free_notifier, 0, task);
return (ret == NOTIFY_OK) ? 1 : 0;
}
void profile_munmap(unsigned long addr)
{
blocking_notifier_call_chain(&munmap_notifier, 0, (void *)addr);
}
int task_handoff_register(struct notifier_block *n)
{
return atomic_notifier_chain_register(&task_free_notifier, n);
}
EXPORT_SYMBOL_GPL(task_handoff_register);
int task_handoff_unregister(struct notifier_block *n)
{
return atomic_notifier_chain_unregister(&task_free_notifier, n);
}
EXPORT_SYMBOL_GPL(task_handoff_unregister);
int profile_event_register(enum profile_type type, struct notifier_block *n)
{
int err = -EINVAL;
switch (type) {
case PROFILE_TASK_EXIT:
err = blocking_notifier_chain_register(
&task_exit_notifier, n);
break;
case PROFILE_MUNMAP:
err = blocking_notifier_chain_register(
&munmap_notifier, n);
break;
}
return err;
}
EXPORT_SYMBOL_GPL(profile_event_register);
int profile_event_unregister(enum profile_type type, struct notifier_block *n)
{
int err = -EINVAL;
switch (type) {
case PROFILE_TASK_EXIT:
err = blocking_notifier_chain_unregister(
&task_exit_notifier, n);
break;
case PROFILE_MUNMAP:
err = blocking_notifier_chain_unregister(
&munmap_notifier, n);
break;
}
return err;
}
EXPORT_SYMBOL_GPL(profile_event_unregister);
int register_timer_hook(int (*hook)(struct pt_regs *))
{
if (timer_hook)
return -EBUSY;
timer_hook = hook;
return 0;
}
EXPORT_SYMBOL_GPL(register_timer_hook);
void unregister_timer_hook(int (*hook)(struct pt_regs *))
{
WARN_ON(hook != timer_hook);
timer_hook = NULL;
/* make sure all CPUs see the NULL hook */
synchronize_sched(); /* Allow ongoing interrupts to complete. */
}
EXPORT_SYMBOL_GPL(unregister_timer_hook);
#ifdef CONFIG_SMP
/*
* Each cpu has a pair of open-addressed hashtables for pending
* profile hits. read_profile() IPI's all cpus to request them
* to flip buffers and flushes their contents to prof_buffer itself.
* Flip requests are serialized by the profile_flip_mutex. The sole
* use of having a second hashtable is for avoiding cacheline
* contention that would otherwise happen during flushes of pending
* profile hits required for the accuracy of reported profile hits
* and so resurrect the interrupt livelock issue.
*
* The open-addressed hashtables are indexed by profile buffer slot
* and hold the number of pending hits to that profile buffer slot on
* a cpu in an entry. When the hashtable overflows, all pending hits
* are accounted to their corresponding profile buffer slots with
* atomic_add() and the hashtable emptied. As numerous pending hits
* may be accounted to a profile buffer slot in a hashtable entry,
* this amortizes a number of atomic profile buffer increments likely
* to be far larger than the number of entries in the hashtable,
* particularly given that the number of distinct profile buffer
* positions to which hits are accounted during short intervals (e.g.
* several seconds) is usually very small. Exclusion from buffer
* flipping is provided by interrupt disablement (note that for
* SCHED_PROFILING or SLEEP_PROFILING profile_hit() may be called from
* process context).
* The hash function is meant to be lightweight as opposed to strong,
* and was vaguely inspired by ppc64 firmware-supported inverted
* pagetable hash functions, but uses a full hashtable full of finite
* collision chains, not just pairs of them.
*
* -- wli
*/
static void __profile_flip_buffers(void *unused)
{
int cpu = smp_processor_id();
per_cpu(cpu_profile_flip, cpu) = !per_cpu(cpu_profile_flip, cpu);
}
static void profile_flip_buffers(void)
{
int i, j, cpu;
mutex_lock(&profile_flip_mutex);
j = per_cpu(cpu_profile_flip, get_cpu());
put_cpu();
on_each_cpu(__profile_flip_buffers, NULL, 1);
for_each_online_cpu(cpu) {
struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[j];
for (i = 0; i < NR_PROFILE_HIT; ++i) {
if (!hits[i].hits) {
if (hits[i].pc)
hits[i].pc = 0;
continue;
}
atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
hits[i].hits = hits[i].pc = 0;
}
}
mutex_unlock(&profile_flip_mutex);
}
static void profile_discard_flip_buffers(void)
{
int i, cpu;
mutex_lock(&profile_flip_mutex);
i = per_cpu(cpu_profile_flip, get_cpu());
put_cpu();
on_each_cpu(__profile_flip_buffers, NULL, 1);
for_each_online_cpu(cpu) {
struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[i];
memset(hits, 0, NR_PROFILE_HIT*sizeof(struct profile_hit));
}
mutex_unlock(&profile_flip_mutex);
}
static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
{
unsigned long primary, secondary, flags, pc = (unsigned long)__pc;
int i, j, cpu;
struct profile_hit *hits;
pc = min((pc - (unsigned long)_stext) >> prof_shift, prof_len - 1);
i = primary = (pc & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
secondary = (~(pc << 1) & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
cpu = get_cpu();
hits = per_cpu(cpu_profile_hits, cpu)[per_cpu(cpu_profile_flip, cpu)];
if (!hits) {
put_cpu();
return;
}
/*
* We buffer the global profiler buffer into a per-CPU
* queue and thus reduce the number of global (and possibly
* NUMA-alien) accesses. The write-queue is self-coalescing:
*/
local_irq_save(flags);
do {
for (j = 0; j < PROFILE_GRPSZ; ++j) {
if (hits[i + j].pc == pc) {
hits[i + j].hits += nr_hits;
goto out;
} else if (!hits[i + j].hits) {
hits[i + j].pc = pc;
hits[i + j].hits = nr_hits;
goto out;
}
}
i = (i + secondary) & (NR_PROFILE_HIT - 1);
} while (i != primary);
/*
* Add the current hit(s) and flush the write-queue out
* to the global buffer:
*/
atomic_add(nr_hits, &prof_buffer[pc]);
for (i = 0; i < NR_PROFILE_HIT; ++i) {
atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
hits[i].pc = hits[i].hits = 0;
}
out:
local_irq_restore(flags);
put_cpu();
}
static int __cpuinit profile_cpu_callback(struct notifier_block *info,
unsigned long action, void *__cpu)
{
int node, cpu = (unsigned long)__cpu;
struct page *page;
switch (action) {
case CPU_UP_PREPARE:
case CPU_UP_PREPARE_FROZEN:
node = cpu_to_mem(cpu);
per_cpu(cpu_profile_flip, cpu) = 0;
if (!per_cpu(cpu_profile_hits, cpu)[1]) {
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO,
0);
if (!page)
return notifier_from_errno(-ENOMEM);
per_cpu(cpu_profile_hits, cpu)[1] = page_address(page);
}
if (!per_cpu(cpu_profile_hits, cpu)[0]) {
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO,
0);
if (!page)
goto out_free;
per_cpu(cpu_profile_hits, cpu)[0] = page_address(page);
}
break;
out_free:
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
return notifier_from_errno(-ENOMEM);
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
if (prof_cpu_mask != NULL)
cpumask_set_cpu(cpu, prof_cpu_mask);
break;
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
case CPU_DEAD:
case CPU_DEAD_FROZEN:
if (prof_cpu_mask != NULL)
cpumask_clear_cpu(cpu, prof_cpu_mask);
if (per_cpu(cpu_profile_hits, cpu)[0]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[0]);
per_cpu(cpu_profile_hits, cpu)[0] = NULL;
__free_page(page);
}
if (per_cpu(cpu_profile_hits, cpu)[1]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
}
break;
}
return NOTIFY_OK;
}
#else /* !CONFIG_SMP */
#define profile_flip_buffers() do { } while (0)
#define profile_discard_flip_buffers() do { } while (0)
#define profile_cpu_callback NULL
static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
{
unsigned long pc;
pc = ((unsigned long)__pc - (unsigned long)_stext) >> prof_shift;
atomic_add(nr_hits, &prof_buffer[min(pc, prof_len - 1)]);
}
#endif /* !CONFIG_SMP */
void profile_hits(int type, void *__pc, unsigned int nr_hits)
{
if (prof_on != type || !prof_buffer)
return;
do_profile_hits(type, __pc, nr_hits);
}
EXPORT_SYMBOL_GPL(profile_hits);
void profile_tick(int type)
{
struct pt_regs *regs = get_irq_regs();
if (type == CPU_PROFILING && timer_hook)
timer_hook(regs);
if (!user_mode(regs) && prof_cpu_mask != NULL &&
cpumask_test_cpu(smp_processor_id(), prof_cpu_mask))
profile_hit(type, (void *)profile_pc(regs));
}
#ifdef CONFIG_PROC_FS
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>
static int prof_cpu_mask_proc_show(struct seq_file *m, void *v)
{
seq_cpumask(m, prof_cpu_mask);
seq_putc(m, '\n');
return 0;
}
static int prof_cpu_mask_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, prof_cpu_mask_proc_show, NULL);
}
static ssize_t prof_cpu_mask_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
cpumask_var_t new_value;
int err;
if (!alloc_cpumask_var(&new_value, GFP_KERNEL))
return -ENOMEM;
err = cpumask_parse_user(buffer, count, new_value);
if (!err) {
cpumask_copy(prof_cpu_mask, new_value);
err = count;
}
free_cpumask_var(new_value);
return err;
}
static const struct file_operations prof_cpu_mask_proc_fops = {
.open = prof_cpu_mask_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = prof_cpu_mask_proc_write,
};
void create_prof_cpu_mask(struct proc_dir_entry *root_irq_dir)
{
/* create /proc/irq/prof_cpu_mask */
proc_create("prof_cpu_mask", 0600, root_irq_dir, &prof_cpu_mask_proc_fops);
}
/*
* This function accesses profiling information. The returned data is
* binary: the sampling step and the actual contents of the profile
* buffer. Use of the program readprofile is recommended in order to
* get meaningful info out of these data.
*/
static ssize_t
read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
unsigned long p = *ppos;
ssize_t read;
char *pnt;
unsigned int sample_step = 1 << prof_shift;
profile_flip_buffers();
if (p >= (prof_len+1)*sizeof(unsigned int))
return 0;
if (count > (prof_len+1)*sizeof(unsigned int) - p)
count = (prof_len+1)*sizeof(unsigned int) - p;
read = 0;
while (p < sizeof(unsigned int) && count > 0) {
if (put_user(*((char *)(&sample_step)+p), buf))
return -EFAULT;
buf++; p++; count--; read++;
}
pnt = (char *)prof_buffer + p - sizeof(atomic_t);
if (copy_to_user(buf, (void *)pnt, count))
return -EFAULT;
read += count;
*ppos += read;
return read;
}
/*
* Writing to /proc/profile resets the counters
*
* Writing a 'profiling multiplier' value into it also re-sets the profiling
* interrupt frequency, on architectures that support this.
*/
static ssize_t write_profile(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
#ifdef CONFIG_SMP
extern int setup_profiling_timer(unsigned int multiplier);
if (count == sizeof(int)) {
unsigned int multiplier;
if (copy_from_user(&multiplier, buf, sizeof(int)))
return -EFAULT;
if (setup_profiling_timer(multiplier))
return -EINVAL;
}
#endif
profile_discard_flip_buffers();
memset(prof_buffer, 0, prof_len * sizeof(atomic_t));
return count;
}
static const struct file_operations proc_profile_operations = {
.read = read_profile,
.write = write_profile,
.llseek = default_llseek,
};
#ifdef CONFIG_SMP
static void profile_nop(void *unused)
{
}
static int create_hash_tables(void)
{
int cpu;
for_each_online_cpu(cpu) {
int node = cpu_to_mem(cpu);
struct page *page;
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO | GFP_THISNODE,
0);
if (!page)
goto out_cleanup;
per_cpu(cpu_profile_hits, cpu)[1]
= (struct profile_hit *)page_address(page);
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO | GFP_THISNODE,
0);
if (!page)
goto out_cleanup;
per_cpu(cpu_profile_hits, cpu)[0]
= (struct profile_hit *)page_address(page);
}
return 0;
out_cleanup:
prof_on = 0;
smp_mb();
on_each_cpu(profile_nop, NULL, 1);
for_each_online_cpu(cpu) {
struct page *page;
if (per_cpu(cpu_profile_hits, cpu)[0]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[0]);
per_cpu(cpu_profile_hits, cpu)[0] = NULL;
__free_page(page);
}
if (per_cpu(cpu_profile_hits, cpu)[1]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
}
}
return -1;
}
#else
#define create_hash_tables() ({ 0; })
#endif
int __ref create_proc_profile(void) /* false positive from hotcpu_notifier */
{
struct proc_dir_entry *entry;
if (!prof_on)
return 0;
if (create_hash_tables())
return -ENOMEM;
entry = proc_create("profile", S_IWUSR | S_IRUGO,
NULL, &proc_profile_operations);
if (!entry)
return 0;
entry->size = (1+prof_len) * sizeof(atomic_t);
hotcpu_notifier(profile_cpu_callback, 0);
return 0;
}
module_init(create_proc_profile);
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
zhaoleidd/btrfs | net/ipv6/netfilter/ip6t_ah.c | 4996 | 3158 | /* Kernel module to match AH parameters. */
/* (C) 2001-2002 Andras Kis-Szabo <kisza@sch.bme.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/types.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter_ipv6/ip6t_ah.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: IPv6 IPsec-AH match");
MODULE_AUTHOR("Andras Kis-Szabo <kisza@sch.bme.hu>");
/* Returns 1 if the spi is matched by the range, 0 otherwise */
static inline bool
spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, bool invert)
{
bool r;
pr_debug("spi_match:%c 0x%x <= 0x%x <= 0x%x\n",
invert ? '!' : ' ', min, spi, max);
r = (spi >= min && spi <= max) ^ invert;
pr_debug(" result %s\n", r ? "PASS" : "FAILED");
return r;
}
static bool ah_mt6(const struct sk_buff *skb, struct xt_action_param *par)
{
struct ip_auth_hdr _ah;
const struct ip_auth_hdr *ah;
const struct ip6t_ah *ahinfo = par->matchinfo;
unsigned int ptr = 0;
unsigned int hdrlen = 0;
int err;
err = ipv6_find_hdr(skb, &ptr, NEXTHDR_AUTH, NULL, NULL);
if (err < 0) {
if (err != -ENOENT)
par->hotdrop = true;
return false;
}
ah = skb_header_pointer(skb, ptr, sizeof(_ah), &_ah);
if (ah == NULL) {
par->hotdrop = true;
return false;
}
hdrlen = (ah->hdrlen + 2) << 2;
pr_debug("IPv6 AH LEN %u %u ", hdrlen, ah->hdrlen);
pr_debug("RES %04X ", ah->reserved);
pr_debug("SPI %u %08X\n", ntohl(ah->spi), ntohl(ah->spi));
pr_debug("IPv6 AH spi %02X ",
spi_match(ahinfo->spis[0], ahinfo->spis[1],
ntohl(ah->spi),
!!(ahinfo->invflags & IP6T_AH_INV_SPI)));
pr_debug("len %02X %04X %02X ",
ahinfo->hdrlen, hdrlen,
(!ahinfo->hdrlen ||
(ahinfo->hdrlen == hdrlen) ^
!!(ahinfo->invflags & IP6T_AH_INV_LEN)));
pr_debug("res %02X %04X %02X\n",
ahinfo->hdrres, ah->reserved,
!(ahinfo->hdrres && ah->reserved));
return (ah != NULL) &&
spi_match(ahinfo->spis[0], ahinfo->spis[1],
ntohl(ah->spi),
!!(ahinfo->invflags & IP6T_AH_INV_SPI)) &&
(!ahinfo->hdrlen ||
(ahinfo->hdrlen == hdrlen) ^
!!(ahinfo->invflags & IP6T_AH_INV_LEN)) &&
!(ahinfo->hdrres && ah->reserved);
}
static int ah_mt6_check(const struct xt_mtchk_param *par)
{
const struct ip6t_ah *ahinfo = par->matchinfo;
if (ahinfo->invflags & ~IP6T_AH_INV_MASK) {
pr_debug("unknown flags %X\n", ahinfo->invflags);
return -EINVAL;
}
return 0;
}
static struct xt_match ah_mt6_reg __read_mostly = {
.name = "ah",
.family = NFPROTO_IPV6,
.match = ah_mt6,
.matchsize = sizeof(struct ip6t_ah),
.checkentry = ah_mt6_check,
.me = THIS_MODULE,
};
static int __init ah_mt6_init(void)
{
return xt_register_match(&ah_mt6_reg);
}
static void __exit ah_mt6_exit(void)
{
xt_unregister_match(&ah_mt6_reg);
}
module_init(ah_mt6_init);
module_exit(ah_mt6_exit);
| gpl-2.0 |
Jason-Lam/linux-am335x | drivers/ata/pata_atp867x.c | 5508 | 14859 | /*
* pata_atp867x.c - ARTOP 867X 64bit 4-channel UDMA133 ATA controller driver
*
* (C) 2009 Google Inc. John(Jung-Ik) Lee <jilee@google.com>
*
* Per Atp867 data sheet rev 1.2, Acard.
* Based in part on early ide code from
* 2003-2004 by Eric Uhrhane, Google, 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
*
*
* TODO:
* 1. RAID features [comparison, XOR, striping, mirroring, etc.]
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/gfp.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_atp867x"
#define DRV_VERSION "0.7.5"
/*
* IO Registers
* Note that all runtime hot priv ports are cached in ap private_data
*/
enum {
ATP867X_IO_CHANNEL_OFFSET = 0x10,
/*
* IO Register Bitfields
*/
ATP867X_IO_PIOSPD_ACTIVE_SHIFT = 4,
ATP867X_IO_PIOSPD_RECOVER_SHIFT = 0,
ATP867X_IO_DMAMODE_MSTR_SHIFT = 0,
ATP867X_IO_DMAMODE_MSTR_MASK = 0x07,
ATP867X_IO_DMAMODE_SLAVE_SHIFT = 4,
ATP867X_IO_DMAMODE_SLAVE_MASK = 0x70,
ATP867X_IO_DMAMODE_UDMA_6 = 0x07,
ATP867X_IO_DMAMODE_UDMA_5 = 0x06,
ATP867X_IO_DMAMODE_UDMA_4 = 0x05,
ATP867X_IO_DMAMODE_UDMA_3 = 0x04,
ATP867X_IO_DMAMODE_UDMA_2 = 0x03,
ATP867X_IO_DMAMODE_UDMA_1 = 0x02,
ATP867X_IO_DMAMODE_UDMA_0 = 0x01,
ATP867X_IO_DMAMODE_DISABLE = 0x00,
ATP867X_IO_SYS_INFO_66MHZ = 0x04,
ATP867X_IO_SYS_INFO_SLOW_UDMA5 = 0x02,
ATP867X_IO_SYS_MASK_RESERVED = (~0xf1),
ATP867X_IO_PORTSPD_VAL = 0x1143,
ATP867X_PREREAD_VAL = 0x0200,
ATP867X_NUM_PORTS = 4,
ATP867X_BAR_IOBASE = 0,
ATP867X_BAR_ROMBASE = 6,
};
#define ATP867X_IOBASE(ap) ((ap)->host->iomap[0])
#define ATP867X_SYS_INFO(ap) (0x3F + ATP867X_IOBASE(ap))
#define ATP867X_IO_PORTBASE(ap, port) (0x00 + ATP867X_IOBASE(ap) + \
(port) * ATP867X_IO_CHANNEL_OFFSET)
#define ATP867X_IO_DMABASE(ap, port) (0x40 + \
ATP867X_IO_PORTBASE((ap), (port)))
#define ATP867X_IO_STATUS(ap, port) (0x07 + \
ATP867X_IO_PORTBASE((ap), (port)))
#define ATP867X_IO_ALTSTATUS(ap, port) (0x0E + \
ATP867X_IO_PORTBASE((ap), (port)))
/*
* hot priv ports
*/
#define ATP867X_IO_MSTRPIOSPD(ap, port) (0x08 + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_SLAVPIOSPD(ap, port) (0x09 + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_8BPIOSPD(ap, port) (0x0A + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_DMAMODE(ap, port) (0x0B + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_PORTSPD(ap, port) (0x4A + \
ATP867X_IO_PORTBASE((ap), (port)))
#define ATP867X_IO_PREREAD(ap, port) (0x4C + \
ATP867X_IO_PORTBASE((ap), (port)))
struct atp867x_priv {
void __iomem *dma_mode;
void __iomem *mstr_piospd;
void __iomem *slave_piospd;
void __iomem *eightb_piospd;
int pci66mhz;
};
static void atp867x_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct atp867x_priv *dp = ap->private_data;
u8 speed = adev->dma_mode;
u8 b;
u8 mode = speed - XFER_UDMA_0 + 1;
/*
* Doc 6.6.9: decrease the udma mode value by 1 for safer UDMA speed
* on 66MHz bus
* rev-A: UDMA_1~4 (5, 6 no change)
* rev-B: all UDMA modes
* UDMA_0 stays not to disable UDMA
*/
if (dp->pci66mhz && mode > ATP867X_IO_DMAMODE_UDMA_0 &&
(pdev->device == PCI_DEVICE_ID_ARTOP_ATP867B ||
mode < ATP867X_IO_DMAMODE_UDMA_5))
mode--;
b = ioread8(dp->dma_mode);
if (adev->devno & 1) {
b = (b & ~ATP867X_IO_DMAMODE_SLAVE_MASK) |
(mode << ATP867X_IO_DMAMODE_SLAVE_SHIFT);
} else {
b = (b & ~ATP867X_IO_DMAMODE_MSTR_MASK) |
(mode << ATP867X_IO_DMAMODE_MSTR_SHIFT);
}
iowrite8(b, dp->dma_mode);
}
static int atp867x_get_active_clocks_shifted(struct ata_port *ap,
unsigned int clk)
{
struct atp867x_priv *dp = ap->private_data;
unsigned char clocks = clk;
/*
* Doc 6.6.9: increase the clock value by 1 for safer PIO speed
* on 66MHz bus
*/
if (dp->pci66mhz)
clocks++;
switch (clocks) {
case 0:
clocks = 1;
break;
case 1 ... 6:
break;
default:
printk(KERN_WARNING "ATP867X: active %dclk is invalid. "
"Using 12clk.\n", clk);
case 9 ... 12:
clocks = 7; /* 12 clk */
break;
case 7:
case 8: /* default 8 clk */
clocks = 0;
goto active_clock_shift_done;
}
active_clock_shift_done:
return clocks << ATP867X_IO_PIOSPD_ACTIVE_SHIFT;
}
static int atp867x_get_recover_clocks_shifted(unsigned int clk)
{
unsigned char clocks = clk;
switch (clocks) {
case 0:
clocks = 1;
break;
case 1 ... 11:
break;
case 13:
case 14:
--clocks; /* by the spec */
break;
case 15:
break;
default:
printk(KERN_WARNING "ATP867X: recover %dclk is invalid. "
"Using default 12clk.\n", clk);
case 12: /* default 12 clk */
clocks = 0;
break;
}
return clocks << ATP867X_IO_PIOSPD_RECOVER_SHIFT;
}
static void atp867x_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct ata_device *peer = ata_dev_pair(adev);
struct atp867x_priv *dp = ap->private_data;
u8 speed = adev->pio_mode;
struct ata_timing t, p;
int T, UT;
u8 b;
T = 1000000000 / 33333;
UT = T / 4;
ata_timing_compute(adev, speed, &t, T, UT);
if (peer && peer->pio_mode) {
ata_timing_compute(peer, peer->pio_mode, &p, T, UT);
ata_timing_merge(&p, &t, &t, ATA_TIMING_8BIT);
}
b = ioread8(dp->dma_mode);
if (adev->devno & 1)
b = (b & ~ATP867X_IO_DMAMODE_SLAVE_MASK);
else
b = (b & ~ATP867X_IO_DMAMODE_MSTR_MASK);
iowrite8(b, dp->dma_mode);
b = atp867x_get_active_clocks_shifted(ap, t.active) |
atp867x_get_recover_clocks_shifted(t.recover);
if (adev->devno & 1)
iowrite8(b, dp->slave_piospd);
else
iowrite8(b, dp->mstr_piospd);
b = atp867x_get_active_clocks_shifted(ap, t.act8b) |
atp867x_get_recover_clocks_shifted(t.rec8b);
iowrite8(b, dp->eightb_piospd);
}
static int atp867x_cable_override(struct pci_dev *pdev)
{
if (pdev->subsystem_vendor == PCI_VENDOR_ID_ARTOP &&
(pdev->subsystem_device == PCI_DEVICE_ID_ARTOP_ATP867A ||
pdev->subsystem_device == PCI_DEVICE_ID_ARTOP_ATP867B)) {
return 1;
}
return 0;
}
static int atp867x_cable_detect(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
if (atp867x_cable_override(pdev))
return ATA_CBL_PATA40_SHORT;
return ATA_CBL_PATA_UNK;
}
static struct scsi_host_template atp867x_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations atp867x_ops = {
.inherits = &ata_bmdma_port_ops,
.cable_detect = atp867x_cable_detect,
.set_piomode = atp867x_set_piomode,
.set_dmamode = atp867x_set_dmamode,
};
#ifdef ATP867X_DEBUG
static void atp867x_check_res(struct pci_dev *pdev)
{
int i;
unsigned long start, len;
/* Check the PCI resources for this channel are enabled */
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
start = pci_resource_start(pdev, i);
len = pci_resource_len(pdev, i);
printk(KERN_DEBUG "ATP867X: resource start:len=%lx:%lx\n",
start, len);
}
}
static void atp867x_check_ports(struct ata_port *ap, int port)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
struct atp867x_priv *dp = ap->private_data;
printk(KERN_DEBUG "ATP867X: port[%d] addresses\n"
" cmd_addr =0x%llx, 0x%llx\n"
" ctl_addr =0x%llx, 0x%llx\n"
" bmdma_addr =0x%llx, 0x%llx\n"
" data_addr =0x%llx\n"
" error_addr =0x%llx\n"
" feature_addr =0x%llx\n"
" nsect_addr =0x%llx\n"
" lbal_addr =0x%llx\n"
" lbam_addr =0x%llx\n"
" lbah_addr =0x%llx\n"
" device_addr =0x%llx\n"
" status_addr =0x%llx\n"
" command_addr =0x%llx\n"
" dp->dma_mode =0x%llx\n"
" dp->mstr_piospd =0x%llx\n"
" dp->slave_piospd =0x%llx\n"
" dp->eightb_piospd =0x%llx\n"
" dp->pci66mhz =0x%lx\n",
port,
(unsigned long long)ioaddr->cmd_addr,
(unsigned long long)ATP867X_IO_PORTBASE(ap, port),
(unsigned long long)ioaddr->ctl_addr,
(unsigned long long)ATP867X_IO_ALTSTATUS(ap, port),
(unsigned long long)ioaddr->bmdma_addr,
(unsigned long long)ATP867X_IO_DMABASE(ap, port),
(unsigned long long)ioaddr->data_addr,
(unsigned long long)ioaddr->error_addr,
(unsigned long long)ioaddr->feature_addr,
(unsigned long long)ioaddr->nsect_addr,
(unsigned long long)ioaddr->lbal_addr,
(unsigned long long)ioaddr->lbam_addr,
(unsigned long long)ioaddr->lbah_addr,
(unsigned long long)ioaddr->device_addr,
(unsigned long long)ioaddr->status_addr,
(unsigned long long)ioaddr->command_addr,
(unsigned long long)dp->dma_mode,
(unsigned long long)dp->mstr_piospd,
(unsigned long long)dp->slave_piospd,
(unsigned long long)dp->eightb_piospd,
(unsigned long)dp->pci66mhz);
}
#endif
static int atp867x_set_priv(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct atp867x_priv *dp;
int port = ap->port_no;
dp = ap->private_data =
devm_kzalloc(&pdev->dev, sizeof(*dp), GFP_KERNEL);
if (dp == NULL)
return -ENOMEM;
dp->dma_mode = ATP867X_IO_DMAMODE(ap, port);
dp->mstr_piospd = ATP867X_IO_MSTRPIOSPD(ap, port);
dp->slave_piospd = ATP867X_IO_SLAVPIOSPD(ap, port);
dp->eightb_piospd = ATP867X_IO_8BPIOSPD(ap, port);
dp->pci66mhz =
ioread8(ATP867X_SYS_INFO(ap)) & ATP867X_IO_SYS_INFO_66MHZ;
return 0;
}
static void atp867x_fixup(struct ata_host *host)
{
struct pci_dev *pdev = to_pci_dev(host->dev);
struct ata_port *ap = host->ports[0];
int i;
u8 v;
/*
* Broken BIOS might not set latency high enough
*/
pci_read_config_byte(pdev, PCI_LATENCY_TIMER, &v);
if (v < 0x80) {
v = 0x80;
pci_write_config_byte(pdev, PCI_LATENCY_TIMER, v);
printk(KERN_DEBUG "ATP867X: set latency timer of device %s"
" to %d\n", pci_name(pdev), v);
}
/*
* init 8bit io ports speed(0aaarrrr) to 43h and
* init udma modes of master/slave to 0/0(11h)
*/
for (i = 0; i < ATP867X_NUM_PORTS; i++)
iowrite16(ATP867X_IO_PORTSPD_VAL, ATP867X_IO_PORTSPD(ap, i));
/*
* init PreREAD counts
*/
for (i = 0; i < ATP867X_NUM_PORTS; i++)
iowrite16(ATP867X_PREREAD_VAL, ATP867X_IO_PREREAD(ap, i));
v = ioread8(ATP867X_IOBASE(ap) + 0x28);
v &= 0xcf; /* Enable INTA#: bit4=0 means enable */
v |= 0xc0; /* Enable PCI burst, MRM & not immediate interrupts */
iowrite8(v, ATP867X_IOBASE(ap) + 0x28);
/*
* Turn off the over clocked udma5 mode, only for Rev-B
*/
v = ioread8(ATP867X_SYS_INFO(ap));
v &= ATP867X_IO_SYS_MASK_RESERVED;
if (pdev->device == PCI_DEVICE_ID_ARTOP_ATP867B)
v |= ATP867X_IO_SYS_INFO_SLOW_UDMA5;
iowrite8(v, ATP867X_SYS_INFO(ap));
}
static int atp867x_ata_pci_sff_init_host(struct ata_host *host)
{
struct device *gdev = host->dev;
struct pci_dev *pdev = to_pci_dev(gdev);
unsigned int mask = 0;
int i, rc;
/*
* do not map rombase
*/
rc = pcim_iomap_regions(pdev, 1 << ATP867X_BAR_IOBASE, DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
#ifdef ATP867X_DEBUG
atp867x_check_res(pdev);
for (i = 0; i < PCI_ROM_RESOURCE; i++)
printk(KERN_DEBUG "ATP867X: iomap[%d]=0x%llx\n", i,
(unsigned long long)(host->iomap[i]));
#endif
/*
* request, iomap BARs and init port addresses accordingly
*/
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
struct ata_ioports *ioaddr = &ap->ioaddr;
ioaddr->cmd_addr = ATP867X_IO_PORTBASE(ap, i);
ioaddr->ctl_addr = ioaddr->altstatus_addr
= ATP867X_IO_ALTSTATUS(ap, i);
ioaddr->bmdma_addr = ATP867X_IO_DMABASE(ap, i);
ata_sff_std_ports(ioaddr);
rc = atp867x_set_priv(ap);
if (rc)
return rc;
#ifdef ATP867X_DEBUG
atp867x_check_ports(ap, i);
#endif
ata_port_desc(ap, "cmd 0x%lx ctl 0x%lx",
(unsigned long)ioaddr->cmd_addr,
(unsigned long)ioaddr->ctl_addr);
ata_port_desc(ap, "bmdma 0x%lx",
(unsigned long)ioaddr->bmdma_addr);
mask |= 1 << i;
}
if (!mask) {
dev_err(gdev, "no available native port\n");
return -ENODEV;
}
atp867x_fixup(host);
rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
return rc;
}
static int atp867x_init_one(struct pci_dev *pdev,
const struct pci_device_id *id)
{
static const struct ata_port_info info_867x = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.udma_mask = ATA_UDMA6,
.port_ops = &atp867x_ops,
};
struct ata_host *host;
const struct ata_port_info *ppi[] = { &info_867x, NULL };
int rc;
ata_print_version_once(&pdev->dev, DRV_VERSION);
rc = pcim_enable_device(pdev);
if (rc)
return rc;
printk(KERN_INFO "ATP867X: ATP867 ATA UDMA133 controller (rev %02X)",
pdev->device);
host = ata_host_alloc_pinfo(&pdev->dev, ppi, ATP867X_NUM_PORTS);
if (!host) {
dev_err(&pdev->dev, "failed to allocate ATA host\n");
rc = -ENOMEM;
goto err_out;
}
rc = atp867x_ata_pci_sff_init_host(host);
if (rc) {
dev_err(&pdev->dev, "failed to init host\n");
goto err_out;
}
pci_set_master(pdev);
rc = ata_host_activate(host, pdev->irq, ata_bmdma_interrupt,
IRQF_SHARED, &atp867x_sht);
if (rc)
dev_err(&pdev->dev, "failed to activate host\n");
err_out:
return rc;
}
#ifdef CONFIG_PM
static int atp867x_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
atp867x_fixup(host);
ata_host_resume(host);
return 0;
}
#endif
static struct pci_device_id atp867x_pci_tbl[] = {
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP867A), 0 },
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP867B), 0 },
{ },
};
static struct pci_driver atp867x_driver = {
.name = DRV_NAME,
.id_table = atp867x_pci_tbl,
.probe = atp867x_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = atp867x_reinit_one,
#endif
};
static int __init atp867x_init(void)
{
return pci_register_driver(&atp867x_driver);
}
static void __exit atp867x_exit(void)
{
pci_unregister_driver(&atp867x_driver);
}
MODULE_AUTHOR("John(Jung-Ik) Lee, Google Inc.");
MODULE_DESCRIPTION("low level driver for Artop/Acard 867x ATA controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, atp867x_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(atp867x_init);
module_exit(atp867x_exit);
| gpl-2.0 |
StelixROM/android_kernel_sony_msm8930 | drivers/ata/sata_sx4.c | 5508 | 40430 | /*
* sata_sx4.c - Promise SATA
*
* Maintained by: Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2003-2004 Red Hat, 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, 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Hardware documentation available under NDA.
*
*/
/*
Theory of operation
-------------------
The SX4 (PDC20621) chip features a single Host DMA (HDMA) copy
engine, DIMM memory, and four ATA engines (one per SATA port).
Data is copied to/from DIMM memory by the HDMA engine, before
handing off to one (or more) of the ATA engines. The ATA
engines operate solely on DIMM memory.
The SX4 behaves like a PATA chip, with no SATA controls or
knowledge whatsoever, leading to the presumption that
PATA<->SATA bridges exist on SX4 boards, external to the
PDC20621 chip itself.
The chip is quite capable, supporting an XOR engine and linked
hardware commands (permits a string to transactions to be
submitted and waited-on as a single unit), and an optional
microprocessor.
The limiting factor is largely software. This Linux driver was
written to multiplex the single HDMA engine to copy disk
transactions into a fixed DIMM memory space, from where an ATA
engine takes over. As a result, each WRITE looks like this:
submit HDMA packet to hardware
hardware copies data from system memory to DIMM
hardware raises interrupt
submit ATA packet to hardware
hardware executes ATA WRITE command, w/ data in DIMM
hardware raises interrupt
and each READ looks like this:
submit ATA packet to hardware
hardware executes ATA READ command, w/ data in DIMM
hardware raises interrupt
submit HDMA packet to hardware
hardware copies data from DIMM to system memory
hardware raises interrupt
This is a very slow, lock-step way of doing things that can
certainly be improved by motivated kernel hackers.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <linux/libata.h>
#include "sata_promise.h"
#define DRV_NAME "sata_sx4"
#define DRV_VERSION "0.12"
enum {
PDC_MMIO_BAR = 3,
PDC_DIMM_BAR = 4,
PDC_PRD_TBL = 0x44, /* Direct command DMA table addr */
PDC_PKT_SUBMIT = 0x40, /* Command packet pointer addr */
PDC_HDMA_PKT_SUBMIT = 0x100, /* Host DMA packet pointer addr */
PDC_INT_SEQMASK = 0x40, /* Mask of asserted SEQ INTs */
PDC_HDMA_CTLSTAT = 0x12C, /* Host DMA control / status */
PDC_CTLSTAT = 0x60, /* IDEn control / status */
PDC_20621_SEQCTL = 0x400,
PDC_20621_SEQMASK = 0x480,
PDC_20621_GENERAL_CTL = 0x484,
PDC_20621_PAGE_SIZE = (32 * 1024),
/* chosen, not constant, values; we design our own DIMM mem map */
PDC_20621_DIMM_WINDOW = 0x0C, /* page# for 32K DIMM window */
PDC_20621_DIMM_BASE = 0x00200000,
PDC_20621_DIMM_DATA = (64 * 1024),
PDC_DIMM_DATA_STEP = (256 * 1024),
PDC_DIMM_WINDOW_STEP = (8 * 1024),
PDC_DIMM_HOST_PRD = (6 * 1024),
PDC_DIMM_HOST_PKT = (128 * 0),
PDC_DIMM_HPKT_PRD = (128 * 1),
PDC_DIMM_ATA_PKT = (128 * 2),
PDC_DIMM_APKT_PRD = (128 * 3),
PDC_DIMM_HEADER_SZ = PDC_DIMM_APKT_PRD + 128,
PDC_PAGE_WINDOW = 0x40,
PDC_PAGE_DATA = PDC_PAGE_WINDOW +
(PDC_20621_DIMM_DATA / PDC_20621_PAGE_SIZE),
PDC_PAGE_SET = PDC_DIMM_DATA_STEP / PDC_20621_PAGE_SIZE,
PDC_CHIP0_OFS = 0xC0000, /* offset of chip #0 */
PDC_20621_ERR_MASK = (1<<19) | (1<<20) | (1<<21) | (1<<22) |
(1<<23),
board_20621 = 0, /* FastTrak S150 SX4 */
PDC_MASK_INT = (1 << 10), /* HDMA/ATA mask int */
PDC_RESET = (1 << 11), /* HDMA/ATA reset */
PDC_DMA_ENABLE = (1 << 7), /* DMA start/stop */
PDC_MAX_HDMA = 32,
PDC_HDMA_Q_MASK = (PDC_MAX_HDMA - 1),
PDC_DIMM0_SPD_DEV_ADDRESS = 0x50,
PDC_DIMM1_SPD_DEV_ADDRESS = 0x51,
PDC_I2C_CONTROL = 0x48,
PDC_I2C_ADDR_DATA = 0x4C,
PDC_DIMM0_CONTROL = 0x80,
PDC_DIMM1_CONTROL = 0x84,
PDC_SDRAM_CONTROL = 0x88,
PDC_I2C_WRITE = 0, /* master -> slave */
PDC_I2C_READ = (1 << 6), /* master <- slave */
PDC_I2C_START = (1 << 7), /* start I2C proto */
PDC_I2C_MASK_INT = (1 << 5), /* mask I2C interrupt */
PDC_I2C_COMPLETE = (1 << 16), /* I2C normal compl. */
PDC_I2C_NO_ACK = (1 << 20), /* slave no-ack addr */
PDC_DIMM_SPD_SUBADDRESS_START = 0x00,
PDC_DIMM_SPD_SUBADDRESS_END = 0x7F,
PDC_DIMM_SPD_ROW_NUM = 3,
PDC_DIMM_SPD_COLUMN_NUM = 4,
PDC_DIMM_SPD_MODULE_ROW = 5,
PDC_DIMM_SPD_TYPE = 11,
PDC_DIMM_SPD_FRESH_RATE = 12,
PDC_DIMM_SPD_BANK_NUM = 17,
PDC_DIMM_SPD_CAS_LATENCY = 18,
PDC_DIMM_SPD_ATTRIBUTE = 21,
PDC_DIMM_SPD_ROW_PRE_CHARGE = 27,
PDC_DIMM_SPD_ROW_ACTIVE_DELAY = 28,
PDC_DIMM_SPD_RAS_CAS_DELAY = 29,
PDC_DIMM_SPD_ACTIVE_PRECHARGE = 30,
PDC_DIMM_SPD_SYSTEM_FREQ = 126,
PDC_CTL_STATUS = 0x08,
PDC_DIMM_WINDOW_CTLR = 0x0C,
PDC_TIME_CONTROL = 0x3C,
PDC_TIME_PERIOD = 0x40,
PDC_TIME_COUNTER = 0x44,
PDC_GENERAL_CTLR = 0x484,
PCI_PLL_INIT = 0x8A531824,
PCI_X_TCOUNT = 0xEE1E5CFF,
/* PDC_TIME_CONTROL bits */
PDC_TIMER_BUZZER = (1 << 10),
PDC_TIMER_MODE_PERIODIC = 0, /* bits 9:8 == 00 */
PDC_TIMER_MODE_ONCE = (1 << 8), /* bits 9:8 == 01 */
PDC_TIMER_ENABLE = (1 << 7),
PDC_TIMER_MASK_INT = (1 << 5),
PDC_TIMER_SEQ_MASK = 0x1f, /* SEQ ID for timer */
PDC_TIMER_DEFAULT = PDC_TIMER_MODE_ONCE |
PDC_TIMER_ENABLE |
PDC_TIMER_MASK_INT,
};
#define ECC_ERASE_BUF_SZ (128 * 1024)
struct pdc_port_priv {
u8 dimm_buf[(ATA_PRD_SZ * ATA_MAX_PRD) + 512];
u8 *pkt;
dma_addr_t pkt_dma;
};
struct pdc_host_priv {
unsigned int doing_hdma;
unsigned int hdma_prod;
unsigned int hdma_cons;
struct {
struct ata_queued_cmd *qc;
unsigned int seq;
unsigned long pkt_ofs;
} hdma[32];
};
static int pdc_sata_init_one(struct pci_dev *pdev, const struct pci_device_id *ent);
static void pdc_error_handler(struct ata_port *ap);
static void pdc_freeze(struct ata_port *ap);
static void pdc_thaw(struct ata_port *ap);
static int pdc_port_start(struct ata_port *ap);
static void pdc20621_qc_prep(struct ata_queued_cmd *qc);
static void pdc_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf);
static void pdc_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf);
static unsigned int pdc20621_dimm_init(struct ata_host *host);
static int pdc20621_detect_dimm(struct ata_host *host);
static unsigned int pdc20621_i2c_read(struct ata_host *host,
u32 device, u32 subaddr, u32 *pdata);
static int pdc20621_prog_dimm0(struct ata_host *host);
static unsigned int pdc20621_prog_dimm_global(struct ata_host *host);
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_get_from_dimm(struct ata_host *host,
void *psource, u32 offset, u32 size);
#endif
static void pdc20621_put_to_dimm(struct ata_host *host,
void *psource, u32 offset, u32 size);
static void pdc20621_irq_clear(struct ata_port *ap);
static unsigned int pdc20621_qc_issue(struct ata_queued_cmd *qc);
static int pdc_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static void pdc_post_internal_cmd(struct ata_queued_cmd *qc);
static int pdc_check_atapi_dma(struct ata_queued_cmd *qc);
static struct scsi_host_template pdc_sata_sht = {
ATA_BASE_SHT(DRV_NAME),
.sg_tablesize = LIBATA_MAX_PRD,
.dma_boundary = ATA_DMA_BOUNDARY,
};
/* TODO: inherit from base port_ops after converting to new EH */
static struct ata_port_operations pdc_20621_ops = {
.inherits = &ata_sff_port_ops,
.check_atapi_dma = pdc_check_atapi_dma,
.qc_prep = pdc20621_qc_prep,
.qc_issue = pdc20621_qc_issue,
.freeze = pdc_freeze,
.thaw = pdc_thaw,
.softreset = pdc_softreset,
.error_handler = pdc_error_handler,
.lost_interrupt = ATA_OP_NULL,
.post_internal_cmd = pdc_post_internal_cmd,
.port_start = pdc_port_start,
.sff_tf_load = pdc_tf_load_mmio,
.sff_exec_command = pdc_exec_command_mmio,
.sff_irq_clear = pdc20621_irq_clear,
};
static const struct ata_port_info pdc_port_info[] = {
/* board_20621 */
{
.flags = ATA_FLAG_SATA | ATA_FLAG_NO_ATAPI |
ATA_FLAG_PIO_POLLING,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &pdc_20621_ops,
},
};
static const struct pci_device_id pdc_sata_pci_tbl[] = {
{ PCI_VDEVICE(PROMISE, 0x6622), board_20621 },
{ } /* terminate list */
};
static struct pci_driver pdc_sata_pci_driver = {
.name = DRV_NAME,
.id_table = pdc_sata_pci_tbl,
.probe = pdc_sata_init_one,
.remove = ata_pci_remove_one,
};
static int pdc_port_start(struct ata_port *ap)
{
struct device *dev = ap->host->dev;
struct pdc_port_priv *pp;
pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
if (!pp)
return -ENOMEM;
pp->pkt = dmam_alloc_coherent(dev, 128, &pp->pkt_dma, GFP_KERNEL);
if (!pp->pkt)
return -ENOMEM;
ap->private_data = pp;
return 0;
}
static inline void pdc20621_ata_sg(struct ata_taskfile *tf, u8 *buf,
unsigned int portno,
unsigned int total_len)
{
u32 addr;
unsigned int dw = PDC_DIMM_APKT_PRD >> 2;
__le32 *buf32 = (__le32 *) buf;
/* output ATA packet S/G table */
addr = PDC_20621_DIMM_BASE + PDC_20621_DIMM_DATA +
(PDC_DIMM_DATA_STEP * portno);
VPRINTK("ATA sg addr 0x%x, %d\n", addr, addr);
buf32[dw] = cpu_to_le32(addr);
buf32[dw + 1] = cpu_to_le32(total_len | ATA_PRD_EOT);
VPRINTK("ATA PSG @ %x == (0x%x, 0x%x)\n",
PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_APKT_PRD,
buf32[dw], buf32[dw + 1]);
}
static inline void pdc20621_host_sg(struct ata_taskfile *tf, u8 *buf,
unsigned int portno,
unsigned int total_len)
{
u32 addr;
unsigned int dw = PDC_DIMM_HPKT_PRD >> 2;
__le32 *buf32 = (__le32 *) buf;
/* output Host DMA packet S/G table */
addr = PDC_20621_DIMM_BASE + PDC_20621_DIMM_DATA +
(PDC_DIMM_DATA_STEP * portno);
buf32[dw] = cpu_to_le32(addr);
buf32[dw + 1] = cpu_to_le32(total_len | ATA_PRD_EOT);
VPRINTK("HOST PSG @ %x == (0x%x, 0x%x)\n",
PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HPKT_PRD,
buf32[dw], buf32[dw + 1]);
}
static inline unsigned int pdc20621_ata_pkt(struct ata_taskfile *tf,
unsigned int devno, u8 *buf,
unsigned int portno)
{
unsigned int i, dw;
__le32 *buf32 = (__le32 *) buf;
u8 dev_reg;
unsigned int dimm_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_APKT_PRD;
VPRINTK("ENTER, dimm_sg == 0x%x, %d\n", dimm_sg, dimm_sg);
i = PDC_DIMM_ATA_PKT;
/*
* Set up ATA packet
*/
if ((tf->protocol == ATA_PROT_DMA) && (!(tf->flags & ATA_TFLAG_WRITE)))
buf[i++] = PDC_PKT_READ;
else if (tf->protocol == ATA_PROT_NODATA)
buf[i++] = PDC_PKT_NODATA;
else
buf[i++] = 0;
buf[i++] = 0; /* reserved */
buf[i++] = portno + 1; /* seq. id */
buf[i++] = 0xff; /* delay seq. id */
/* dimm dma S/G, and next-pkt */
dw = i >> 2;
if (tf->protocol == ATA_PROT_NODATA)
buf32[dw] = 0;
else
buf32[dw] = cpu_to_le32(dimm_sg);
buf32[dw + 1] = 0;
i += 8;
if (devno == 0)
dev_reg = ATA_DEVICE_OBS;
else
dev_reg = ATA_DEVICE_OBS | ATA_DEV1;
/* select device */
buf[i++] = (1 << 5) | PDC_PKT_CLEAR_BSY | ATA_REG_DEVICE;
buf[i++] = dev_reg;
/* device control register */
buf[i++] = (1 << 5) | PDC_REG_DEVCTL;
buf[i++] = tf->ctl;
return i;
}
static inline void pdc20621_host_pkt(struct ata_taskfile *tf, u8 *buf,
unsigned int portno)
{
unsigned int dw;
u32 tmp;
__le32 *buf32 = (__le32 *) buf;
unsigned int host_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HOST_PRD;
unsigned int dimm_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HPKT_PRD;
VPRINTK("ENTER, dimm_sg == 0x%x, %d\n", dimm_sg, dimm_sg);
VPRINTK("host_sg == 0x%x, %d\n", host_sg, host_sg);
dw = PDC_DIMM_HOST_PKT >> 2;
/*
* Set up Host DMA packet
*/
if ((tf->protocol == ATA_PROT_DMA) && (!(tf->flags & ATA_TFLAG_WRITE)))
tmp = PDC_PKT_READ;
else
tmp = 0;
tmp |= ((portno + 1 + 4) << 16); /* seq. id */
tmp |= (0xff << 24); /* delay seq. id */
buf32[dw + 0] = cpu_to_le32(tmp);
buf32[dw + 1] = cpu_to_le32(host_sg);
buf32[dw + 2] = cpu_to_le32(dimm_sg);
buf32[dw + 3] = 0;
VPRINTK("HOST PKT @ %x == (0x%x 0x%x 0x%x 0x%x)\n",
PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HOST_PKT,
buf32[dw + 0],
buf32[dw + 1],
buf32[dw + 2],
buf32[dw + 3]);
}
static void pdc20621_dma_prep(struct ata_queued_cmd *qc)
{
struct scatterlist *sg;
struct ata_port *ap = qc->ap;
struct pdc_port_priv *pp = ap->private_data;
void __iomem *mmio = ap->host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
unsigned int portno = ap->port_no;
unsigned int i, si, idx, total_len = 0, sgt_len;
__le32 *buf = (__le32 *) &pp->dimm_buf[PDC_DIMM_HEADER_SZ];
WARN_ON(!(qc->flags & ATA_QCFLAG_DMAMAP));
VPRINTK("ata%u: ENTER\n", ap->print_id);
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
* Build S/G table
*/
idx = 0;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
buf[idx++] = cpu_to_le32(sg_dma_address(sg));
buf[idx++] = cpu_to_le32(sg_dma_len(sg));
total_len += sg_dma_len(sg);
}
buf[idx - 1] |= cpu_to_le32(ATA_PRD_EOT);
sgt_len = idx * 4;
/*
* Build ATA, host DMA packets
*/
pdc20621_host_sg(&qc->tf, &pp->dimm_buf[0], portno, total_len);
pdc20621_host_pkt(&qc->tf, &pp->dimm_buf[0], portno);
pdc20621_ata_sg(&qc->tf, &pp->dimm_buf[0], portno, total_len);
i = pdc20621_ata_pkt(&qc->tf, qc->dev->devno, &pp->dimm_buf[0], portno);
if (qc->tf.flags & ATA_TFLAG_LBA48)
i = pdc_prep_lba48(&qc->tf, &pp->dimm_buf[0], i);
else
i = pdc_prep_lba28(&qc->tf, &pp->dimm_buf[0], i);
pdc_pkt_footer(&qc->tf, &pp->dimm_buf[0], i);
/* copy three S/G tables and two packets to DIMM MMIO window */
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP),
&pp->dimm_buf, PDC_DIMM_HEADER_SZ);
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP) +
PDC_DIMM_HOST_PRD,
&pp->dimm_buf[PDC_DIMM_HEADER_SZ], sgt_len);
/* force host FIFO dump */
writel(0x00000001, mmio + PDC_20621_GENERAL_CTL);
readl(dimm_mmio); /* MMIO PCI posting flush */
VPRINTK("ata pkt buf ofs %u, prd size %u, mmio copied\n", i, sgt_len);
}
static void pdc20621_nodata_prep(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pdc_port_priv *pp = ap->private_data;
void __iomem *mmio = ap->host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
unsigned int portno = ap->port_no;
unsigned int i;
VPRINTK("ata%u: ENTER\n", ap->print_id);
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
i = pdc20621_ata_pkt(&qc->tf, qc->dev->devno, &pp->dimm_buf[0], portno);
if (qc->tf.flags & ATA_TFLAG_LBA48)
i = pdc_prep_lba48(&qc->tf, &pp->dimm_buf[0], i);
else
i = pdc_prep_lba28(&qc->tf, &pp->dimm_buf[0], i);
pdc_pkt_footer(&qc->tf, &pp->dimm_buf[0], i);
/* copy three S/G tables and two packets to DIMM MMIO window */
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP),
&pp->dimm_buf, PDC_DIMM_HEADER_SZ);
/* force host FIFO dump */
writel(0x00000001, mmio + PDC_20621_GENERAL_CTL);
readl(dimm_mmio); /* MMIO PCI posting flush */
VPRINTK("ata pkt buf ofs %u, mmio copied\n", i);
}
static void pdc20621_qc_prep(struct ata_queued_cmd *qc)
{
switch (qc->tf.protocol) {
case ATA_PROT_DMA:
pdc20621_dma_prep(qc);
break;
case ATA_PROT_NODATA:
pdc20621_nodata_prep(qc);
break;
default:
break;
}
}
static void __pdc20621_push_hdma(struct ata_queued_cmd *qc,
unsigned int seq,
u32 pkt_ofs)
{
struct ata_port *ap = qc->ap;
struct ata_host *host = ap->host;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4)); /* flush */
writel(pkt_ofs, mmio + PDC_HDMA_PKT_SUBMIT);
readl(mmio + PDC_HDMA_PKT_SUBMIT); /* flush */
}
static void pdc20621_push_hdma(struct ata_queued_cmd *qc,
unsigned int seq,
u32 pkt_ofs)
{
struct ata_port *ap = qc->ap;
struct pdc_host_priv *pp = ap->host->private_data;
unsigned int idx = pp->hdma_prod & PDC_HDMA_Q_MASK;
if (!pp->doing_hdma) {
__pdc20621_push_hdma(qc, seq, pkt_ofs);
pp->doing_hdma = 1;
return;
}
pp->hdma[idx].qc = qc;
pp->hdma[idx].seq = seq;
pp->hdma[idx].pkt_ofs = pkt_ofs;
pp->hdma_prod++;
}
static void pdc20621_pop_hdma(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pdc_host_priv *pp = ap->host->private_data;
unsigned int idx = pp->hdma_cons & PDC_HDMA_Q_MASK;
/* if nothing on queue, we're done */
if (pp->hdma_prod == pp->hdma_cons) {
pp->doing_hdma = 0;
return;
}
__pdc20621_push_hdma(pp->hdma[idx].qc, pp->hdma[idx].seq,
pp->hdma[idx].pkt_ofs);
pp->hdma_cons++;
}
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_dump_hdma(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int port_no = ap->port_no;
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
dimm_mmio += (port_no * PDC_DIMM_WINDOW_STEP);
dimm_mmio += PDC_DIMM_HOST_PKT;
printk(KERN_ERR "HDMA[0] == 0x%08X\n", readl(dimm_mmio));
printk(KERN_ERR "HDMA[1] == 0x%08X\n", readl(dimm_mmio + 4));
printk(KERN_ERR "HDMA[2] == 0x%08X\n", readl(dimm_mmio + 8));
printk(KERN_ERR "HDMA[3] == 0x%08X\n", readl(dimm_mmio + 12));
}
#else
static inline void pdc20621_dump_hdma(struct ata_queued_cmd *qc) { }
#endif /* ATA_VERBOSE_DEBUG */
static void pdc20621_packet_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_host *host = ap->host;
unsigned int port_no = ap->port_no;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 seq = (u8) (port_no + 1);
unsigned int port_ofs;
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
VPRINTK("ata%u: ENTER\n", ap->print_id);
wmb(); /* flush PRD, pkt writes */
port_ofs = PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * port_no);
/* if writing, we (1) DMA to DIMM, then (2) do ATA command */
if (rw && qc->tf.protocol == ATA_PROT_DMA) {
seq += 4;
pdc20621_dump_hdma(qc);
pdc20621_push_hdma(qc, seq, port_ofs + PDC_DIMM_HOST_PKT);
VPRINTK("queued ofs 0x%x (%u), seq %u\n",
port_ofs + PDC_DIMM_HOST_PKT,
port_ofs + PDC_DIMM_HOST_PKT,
seq);
} else {
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4)); /* flush */
writel(port_ofs + PDC_DIMM_ATA_PKT,
ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
readl(ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
VPRINTK("submitted ofs 0x%x (%u), seq %u\n",
port_ofs + PDC_DIMM_ATA_PKT,
port_ofs + PDC_DIMM_ATA_PKT,
seq);
}
}
static unsigned int pdc20621_qc_issue(struct ata_queued_cmd *qc)
{
switch (qc->tf.protocol) {
case ATA_PROT_NODATA:
if (qc->tf.flags & ATA_TFLAG_POLLING)
break;
/*FALLTHROUGH*/
case ATA_PROT_DMA:
pdc20621_packet_start(qc);
return 0;
case ATAPI_PROT_DMA:
BUG();
break;
default:
break;
}
return ata_sff_qc_issue(qc);
}
static inline unsigned int pdc20621_host_intr(struct ata_port *ap,
struct ata_queued_cmd *qc,
unsigned int doing_hdma,
void __iomem *mmio)
{
unsigned int port_no = ap->port_no;
unsigned int port_ofs =
PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * port_no);
u8 status;
unsigned int handled = 0;
VPRINTK("ENTER\n");
if ((qc->tf.protocol == ATA_PROT_DMA) && /* read */
(!(qc->tf.flags & ATA_TFLAG_WRITE))) {
/* step two - DMA from DIMM to host */
if (doing_hdma) {
VPRINTK("ata%u: read hdma, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* get drive status; clear intr; complete txn */
qc->err_mask |= ac_err_mask(ata_wait_idle(ap));
ata_qc_complete(qc);
pdc20621_pop_hdma(qc);
}
/* step one - exec ATA command */
else {
u8 seq = (u8) (port_no + 1 + 4);
VPRINTK("ata%u: read ata, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* submit hdma pkt */
pdc20621_dump_hdma(qc);
pdc20621_push_hdma(qc, seq,
port_ofs + PDC_DIMM_HOST_PKT);
}
handled = 1;
} else if (qc->tf.protocol == ATA_PROT_DMA) { /* write */
/* step one - DMA from host to DIMM */
if (doing_hdma) {
u8 seq = (u8) (port_no + 1);
VPRINTK("ata%u: write hdma, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* submit ata pkt */
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4));
writel(port_ofs + PDC_DIMM_ATA_PKT,
ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
readl(ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
}
/* step two - execute ATA command */
else {
VPRINTK("ata%u: write ata, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* get drive status; clear intr; complete txn */
qc->err_mask |= ac_err_mask(ata_wait_idle(ap));
ata_qc_complete(qc);
pdc20621_pop_hdma(qc);
}
handled = 1;
/* command completion, but no data xfer */
} else if (qc->tf.protocol == ATA_PROT_NODATA) {
status = ata_sff_busy_wait(ap, ATA_BUSY | ATA_DRQ, 1000);
DPRINTK("BUS_NODATA (drv_stat 0x%X)\n", status);
qc->err_mask |= ac_err_mask(status);
ata_qc_complete(qc);
handled = 1;
} else {
ap->stats.idle_irq++;
}
return handled;
}
static void pdc20621_irq_clear(struct ata_port *ap)
{
ioread8(ap->ioaddr.status_addr);
}
static irqreturn_t pdc20621_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
struct ata_port *ap;
u32 mask = 0;
unsigned int i, tmp, port_no;
unsigned int handled = 0;
void __iomem *mmio_base;
VPRINTK("ENTER\n");
if (!host || !host->iomap[PDC_MMIO_BAR]) {
VPRINTK("QUICK EXIT\n");
return IRQ_NONE;
}
mmio_base = host->iomap[PDC_MMIO_BAR];
/* reading should also clear interrupts */
mmio_base += PDC_CHIP0_OFS;
mask = readl(mmio_base + PDC_20621_SEQMASK);
VPRINTK("mask == 0x%x\n", mask);
if (mask == 0xffffffff) {
VPRINTK("QUICK EXIT 2\n");
return IRQ_NONE;
}
mask &= 0xffff; /* only 16 tags possible */
if (!mask) {
VPRINTK("QUICK EXIT 3\n");
return IRQ_NONE;
}
spin_lock(&host->lock);
for (i = 1; i < 9; i++) {
port_no = i - 1;
if (port_no > 3)
port_no -= 4;
if (port_no >= host->n_ports)
ap = NULL;
else
ap = host->ports[port_no];
tmp = mask & (1 << i);
VPRINTK("seq %u, port_no %u, ap %p, tmp %x\n", i, port_no, ap, tmp);
if (tmp && ap) {
struct ata_queued_cmd *qc;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING)))
handled += pdc20621_host_intr(ap, qc, (i > 4),
mmio_base);
}
}
spin_unlock(&host->lock);
VPRINTK("mask == 0x%x\n", mask);
VPRINTK("EXIT\n");
return IRQ_RETVAL(handled);
}
static void pdc_freeze(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr;
u32 tmp;
/* FIXME: if all 4 ATA engines are stopped, also stop HDMA engine */
tmp = readl(mmio + PDC_CTLSTAT);
tmp |= PDC_MASK_INT;
tmp &= ~PDC_DMA_ENABLE;
writel(tmp, mmio + PDC_CTLSTAT);
readl(mmio + PDC_CTLSTAT); /* flush */
}
static void pdc_thaw(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr;
u32 tmp;
/* FIXME: start HDMA engine, if zero ATA engines running */
/* clear IRQ */
ioread8(ap->ioaddr.status_addr);
/* turn IRQ back on */
tmp = readl(mmio + PDC_CTLSTAT);
tmp &= ~PDC_MASK_INT;
writel(tmp, mmio + PDC_CTLSTAT);
readl(mmio + PDC_CTLSTAT); /* flush */
}
static void pdc_reset_port(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr + PDC_CTLSTAT;
unsigned int i;
u32 tmp;
/* FIXME: handle HDMA copy engine */
for (i = 11; i > 0; i--) {
tmp = readl(mmio);
if (tmp & PDC_RESET)
break;
udelay(100);
tmp |= PDC_RESET;
writel(tmp, mmio);
}
tmp &= ~PDC_RESET;
writel(tmp, mmio);
readl(mmio); /* flush */
}
static int pdc_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
pdc_reset_port(link->ap);
return ata_sff_softreset(link, class, deadline);
}
static void pdc_error_handler(struct ata_port *ap)
{
if (!(ap->pflags & ATA_PFLAG_FROZEN))
pdc_reset_port(ap);
ata_sff_error_handler(ap);
}
static void pdc_post_internal_cmd(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
/* make DMA engine forget about the failed command */
if (qc->flags & ATA_QCFLAG_FAILED)
pdc_reset_port(ap);
}
static int pdc_check_atapi_dma(struct ata_queued_cmd *qc)
{
u8 *scsicmd = qc->scsicmd->cmnd;
int pio = 1; /* atapi dma off by default */
/* Whitelist commands that may use DMA. */
switch (scsicmd[0]) {
case WRITE_12:
case WRITE_10:
case WRITE_6:
case READ_12:
case READ_10:
case READ_6:
case 0xad: /* READ_DVD_STRUCTURE */
case 0xbe: /* READ_CD */
pio = 0;
}
/* -45150 (FFFF4FA2) to -1 (FFFFFFFF) shall use PIO mode */
if (scsicmd[0] == WRITE_10) {
unsigned int lba =
(scsicmd[2] << 24) |
(scsicmd[3] << 16) |
(scsicmd[4] << 8) |
scsicmd[5];
if (lba >= 0xFFFF4FA2)
pio = 1;
}
return pio;
}
static void pdc_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
{
WARN_ON(tf->protocol == ATA_PROT_DMA ||
tf->protocol == ATAPI_PROT_DMA);
ata_sff_tf_load(ap, tf);
}
static void pdc_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
{
WARN_ON(tf->protocol == ATA_PROT_DMA ||
tf->protocol == ATAPI_PROT_DMA);
ata_sff_exec_command(ap, tf);
}
static void pdc_sata_setup_port(struct ata_ioports *port, void __iomem *base)
{
port->cmd_addr = base;
port->data_addr = base;
port->feature_addr =
port->error_addr = base + 0x4;
port->nsect_addr = base + 0x8;
port->lbal_addr = base + 0xc;
port->lbam_addr = base + 0x10;
port->lbah_addr = base + 0x14;
port->device_addr = base + 0x18;
port->command_addr =
port->status_addr = base + 0x1c;
port->altstatus_addr =
port->ctl_addr = base + 0x38;
}
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_get_from_dimm(struct ata_host *host, void *psource,
u32 offset, u32 size)
{
u32 window_size;
u16 idx;
u8 page_mask;
long dist;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = host->iomap[PDC_DIMM_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
page_mask = 0x00;
window_size = 0x2000 * 4; /* 32K byte uchar size */
idx = (u16) (offset / window_size);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
offset -= (idx * window_size);
idx++;
dist = ((long) (window_size - (offset + size))) >= 0 ? size :
(long) (window_size - offset);
memcpy_fromio((char *) psource, (char *) (dimm_mmio + offset / 4),
dist);
psource += dist;
size -= dist;
for (; (long) size >= (long) window_size ;) {
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_fromio((char *) psource, (char *) (dimm_mmio),
window_size / 4);
psource += window_size;
size -= window_size;
idx++;
}
if (size) {
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_fromio((char *) psource, (char *) (dimm_mmio),
size / 4);
}
}
#endif
static void pdc20621_put_to_dimm(struct ata_host *host, void *psource,
u32 offset, u32 size)
{
u32 window_size;
u16 idx;
u8 page_mask;
long dist;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = host->iomap[PDC_DIMM_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
page_mask = 0x00;
window_size = 0x2000 * 4; /* 32K byte uchar size */
idx = (u16) (offset / window_size);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
offset -= (idx * window_size);
idx++;
dist = ((long)(s32)(window_size - (offset + size))) >= 0 ? size :
(long) (window_size - offset);
memcpy_toio(dimm_mmio + offset / 4, psource, dist);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
psource += dist;
size -= dist;
for (; (long) size >= (long) window_size ;) {
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_toio(dimm_mmio, psource, window_size / 4);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
psource += window_size;
size -= window_size;
idx++;
}
if (size) {
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_toio(dimm_mmio, psource, size / 4);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
}
}
static unsigned int pdc20621_i2c_read(struct ata_host *host, u32 device,
u32 subaddr, u32 *pdata)
{
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
u32 i2creg = 0;
u32 status;
u32 count = 0;
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
i2creg |= device << 24;
i2creg |= subaddr << 16;
/* Set the device and subaddress */
writel(i2creg, mmio + PDC_I2C_ADDR_DATA);
readl(mmio + PDC_I2C_ADDR_DATA);
/* Write Control to perform read operation, mask int */
writel(PDC_I2C_READ | PDC_I2C_START | PDC_I2C_MASK_INT,
mmio + PDC_I2C_CONTROL);
for (count = 0; count <= 1000; count ++) {
status = readl(mmio + PDC_I2C_CONTROL);
if (status & PDC_I2C_COMPLETE) {
status = readl(mmio + PDC_I2C_ADDR_DATA);
break;
} else if (count == 1000)
return 0;
}
*pdata = (status >> 8) & 0x000000ff;
return 1;
}
static int pdc20621_detect_dimm(struct ata_host *host)
{
u32 data = 0;
if (pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_SYSTEM_FREQ, &data)) {
if (data == 100)
return 100;
} else
return 0;
if (pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS, 9, &data)) {
if (data <= 0x75)
return 133;
} else
return 0;
return 0;
}
static int pdc20621_prog_dimm0(struct ata_host *host)
{
u32 spd0[50];
u32 data = 0;
int size, i;
u8 bdimmsize;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
static const struct {
unsigned int reg;
unsigned int ofs;
} pdc_i2c_read_data [] = {
{ PDC_DIMM_SPD_TYPE, 11 },
{ PDC_DIMM_SPD_FRESH_RATE, 12 },
{ PDC_DIMM_SPD_COLUMN_NUM, 4 },
{ PDC_DIMM_SPD_ATTRIBUTE, 21 },
{ PDC_DIMM_SPD_ROW_NUM, 3 },
{ PDC_DIMM_SPD_BANK_NUM, 17 },
{ PDC_DIMM_SPD_MODULE_ROW, 5 },
{ PDC_DIMM_SPD_ROW_PRE_CHARGE, 27 },
{ PDC_DIMM_SPD_ROW_ACTIVE_DELAY, 28 },
{ PDC_DIMM_SPD_RAS_CAS_DELAY, 29 },
{ PDC_DIMM_SPD_ACTIVE_PRECHARGE, 30 },
{ PDC_DIMM_SPD_CAS_LATENCY, 18 },
};
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
for (i = 0; i < ARRAY_SIZE(pdc_i2c_read_data); i++)
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
pdc_i2c_read_data[i].reg,
&spd0[pdc_i2c_read_data[i].ofs]);
data |= (spd0[4] - 8) | ((spd0[21] != 0) << 3) | ((spd0[3]-11) << 4);
data |= ((spd0[17] / 4) << 6) | ((spd0[5] / 2) << 7) |
((((spd0[27] + 9) / 10) - 1) << 8) ;
data |= (((((spd0[29] > spd0[28])
? spd0[29] : spd0[28]) + 9) / 10) - 1) << 10;
data |= ((spd0[30] - spd0[29] + 9) / 10 - 2) << 12;
if (spd0[18] & 0x08)
data |= ((0x03) << 14);
else if (spd0[18] & 0x04)
data |= ((0x02) << 14);
else if (spd0[18] & 0x01)
data |= ((0x01) << 14);
else
data |= (0 << 14);
/*
Calculate the size of bDIMMSize (power of 2) and
merge the DIMM size by program start/end address.
*/
bdimmsize = spd0[4] + (spd0[5] / 2) + spd0[3] + (spd0[17] / 2) + 3;
size = (1 << bdimmsize) >> 20; /* size = xxx(MB) */
data |= (((size / 16) - 1) << 16);
data |= (0 << 23);
data |= 8;
writel(data, mmio + PDC_DIMM0_CONTROL);
readl(mmio + PDC_DIMM0_CONTROL);
return size;
}
static unsigned int pdc20621_prog_dimm_global(struct ata_host *host)
{
u32 data, spd0;
int error, i;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
Set To Default : DIMM Module Global Control Register (0x022259F1)
DIMM Arbitration Disable (bit 20)
DIMM Data/Control Output Driving Selection (bit12 - bit15)
Refresh Enable (bit 17)
*/
data = 0x022259F1;
writel(data, mmio + PDC_SDRAM_CONTROL);
readl(mmio + PDC_SDRAM_CONTROL);
/* Turn on for ECC */
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_TYPE, &spd0);
if (spd0 == 0x02) {
data |= (0x01 << 16);
writel(data, mmio + PDC_SDRAM_CONTROL);
readl(mmio + PDC_SDRAM_CONTROL);
printk(KERN_ERR "Local DIMM ECC Enabled\n");
}
/* DIMM Initialization Select/Enable (bit 18/19) */
data &= (~(1<<18));
data |= (1<<19);
writel(data, mmio + PDC_SDRAM_CONTROL);
error = 1;
for (i = 1; i <= 10; i++) { /* polling ~5 secs */
data = readl(mmio + PDC_SDRAM_CONTROL);
if (!(data & (1<<19))) {
error = 0;
break;
}
msleep(i*100);
}
return error;
}
static unsigned int pdc20621_dimm_init(struct ata_host *host)
{
int speed, size, length;
u32 addr, spd0, pci_status;
u32 time_period = 0;
u32 tcount = 0;
u32 ticks = 0;
u32 clock = 0;
u32 fparam = 0;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/* Initialize PLL based upon PCI Bus Frequency */
/* Initialize Time Period Register */
writel(0xffffffff, mmio + PDC_TIME_PERIOD);
time_period = readl(mmio + PDC_TIME_PERIOD);
VPRINTK("Time Period Register (0x40): 0x%x\n", time_period);
/* Enable timer */
writel(PDC_TIMER_DEFAULT, mmio + PDC_TIME_CONTROL);
readl(mmio + PDC_TIME_CONTROL);
/* Wait 3 seconds */
msleep(3000);
/*
When timer is enabled, counter is decreased every internal
clock cycle.
*/
tcount = readl(mmio + PDC_TIME_COUNTER);
VPRINTK("Time Counter Register (0x44): 0x%x\n", tcount);
/*
If SX4 is on PCI-X bus, after 3 seconds, the timer counter
register should be >= (0xffffffff - 3x10^8).
*/
if (tcount >= PCI_X_TCOUNT) {
ticks = (time_period - tcount);
VPRINTK("Num counters 0x%x (%d)\n", ticks, ticks);
clock = (ticks / 300000);
VPRINTK("10 * Internal clk = 0x%x (%d)\n", clock, clock);
clock = (clock * 33);
VPRINTK("10 * Internal clk * 33 = 0x%x (%d)\n", clock, clock);
/* PLL F Param (bit 22:16) */
fparam = (1400000 / clock) - 2;
VPRINTK("PLL F Param: 0x%x (%d)\n", fparam, fparam);
/* OD param = 0x2 (bit 31:30), R param = 0x5 (bit 29:25) */
pci_status = (0x8a001824 | (fparam << 16));
} else
pci_status = PCI_PLL_INIT;
/* Initialize PLL. */
VPRINTK("pci_status: 0x%x\n", pci_status);
writel(pci_status, mmio + PDC_CTL_STATUS);
readl(mmio + PDC_CTL_STATUS);
/*
Read SPD of DIMM by I2C interface,
and program the DIMM Module Controller.
*/
if (!(speed = pdc20621_detect_dimm(host))) {
printk(KERN_ERR "Detect Local DIMM Fail\n");
return 1; /* DIMM error */
}
VPRINTK("Local DIMM Speed = %d\n", speed);
/* Programming DIMM0 Module Control Register (index_CID0:80h) */
size = pdc20621_prog_dimm0(host);
VPRINTK("Local DIMM Size = %dMB\n", size);
/* Programming DIMM Module Global Control Register (index_CID0:88h) */
if (pdc20621_prog_dimm_global(host)) {
printk(KERN_ERR "Programming DIMM Module Global Control Register Fail\n");
return 1;
}
#ifdef ATA_VERBOSE_DEBUG
{
u8 test_parttern1[40] =
{0x55,0xAA,'P','r','o','m','i','s','e',' ',
'N','o','t',' ','Y','e','t',' ',
'D','e','f','i','n','e','d',' ',
'1','.','1','0',
'9','8','0','3','1','6','1','2',0,0};
u8 test_parttern2[40] = {0};
pdc20621_put_to_dimm(host, test_parttern2, 0x10040, 40);
pdc20621_put_to_dimm(host, test_parttern2, 0x40, 40);
pdc20621_put_to_dimm(host, test_parttern1, 0x10040, 40);
pdc20621_get_from_dimm(host, test_parttern2, 0x40, 40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
pdc20621_get_from_dimm(host, test_parttern2, 0x10040,
40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
pdc20621_put_to_dimm(host, test_parttern1, 0x40, 40);
pdc20621_get_from_dimm(host, test_parttern2, 0x40, 40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
}
#endif
/* ECC initiliazation. */
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_TYPE, &spd0);
if (spd0 == 0x02) {
void *buf;
VPRINTK("Start ECC initialization\n");
addr = 0;
length = size * 1024 * 1024;
buf = kzalloc(ECC_ERASE_BUF_SZ, GFP_KERNEL);
while (addr < length) {
pdc20621_put_to_dimm(host, buf, addr,
ECC_ERASE_BUF_SZ);
addr += ECC_ERASE_BUF_SZ;
}
kfree(buf);
VPRINTK("Finish ECC initialization\n");
}
return 0;
}
static void pdc_20621_init(struct ata_host *host)
{
u32 tmp;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
* Select page 0x40 for our 32k DIMM window
*/
tmp = readl(mmio + PDC_20621_DIMM_WINDOW) & 0xffff0000;
tmp |= PDC_PAGE_WINDOW; /* page 40h; arbitrarily selected */
writel(tmp, mmio + PDC_20621_DIMM_WINDOW);
/*
* Reset Host DMA
*/
tmp = readl(mmio + PDC_HDMA_CTLSTAT);
tmp |= PDC_RESET;
writel(tmp, mmio + PDC_HDMA_CTLSTAT);
readl(mmio + PDC_HDMA_CTLSTAT); /* flush */
udelay(10);
tmp = readl(mmio + PDC_HDMA_CTLSTAT);
tmp &= ~PDC_RESET;
writel(tmp, mmio + PDC_HDMA_CTLSTAT);
readl(mmio + PDC_HDMA_CTLSTAT); /* flush */
}
static int pdc_sata_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
const struct ata_port_info *ppi[] =
{ &pdc_port_info[ent->driver_data], NULL };
struct ata_host *host;
struct pdc_host_priv *hpriv;
int i, rc;
ata_print_version_once(&pdev->dev, DRV_VERSION);
/* allocate host */
host = ata_host_alloc_pinfo(&pdev->dev, ppi, 4);
hpriv = devm_kzalloc(&pdev->dev, sizeof(*hpriv), GFP_KERNEL);
if (!host || !hpriv)
return -ENOMEM;
host->private_data = hpriv;
/* acquire resources and fill host */
rc = pcim_enable_device(pdev);
if (rc)
return rc;
rc = pcim_iomap_regions(pdev, (1 << PDC_MMIO_BAR) | (1 << PDC_DIMM_BAR),
DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
for (i = 0; i < 4; i++) {
struct ata_port *ap = host->ports[i];
void __iomem *base = host->iomap[PDC_MMIO_BAR] + PDC_CHIP0_OFS;
unsigned int offset = 0x200 + i * 0x80;
pdc_sata_setup_port(&ap->ioaddr, base + offset);
ata_port_pbar_desc(ap, PDC_MMIO_BAR, -1, "mmio");
ata_port_pbar_desc(ap, PDC_DIMM_BAR, -1, "dimm");
ata_port_pbar_desc(ap, PDC_MMIO_BAR, offset, "port");
}
/* configure and activate */
rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
if (pdc20621_dimm_init(host))
return -ENOMEM;
pdc_20621_init(host);
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, pdc20621_interrupt,
IRQF_SHARED, &pdc_sata_sht);
}
static int __init pdc_sata_init(void)
{
return pci_register_driver(&pdc_sata_pci_driver);
}
static void __exit pdc_sata_exit(void)
{
pci_unregister_driver(&pdc_sata_pci_driver);
}
MODULE_AUTHOR("Jeff Garzik");
MODULE_DESCRIPTION("Promise SATA low-level driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pdc_sata_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(pdc_sata_init);
module_exit(pdc_sata_exit);
| gpl-2.0 |
RitaLee79/android_kernel_xiaomi_armani-kk | drivers/ata/pata_atp867x.c | 5508 | 14859 | /*
* pata_atp867x.c - ARTOP 867X 64bit 4-channel UDMA133 ATA controller driver
*
* (C) 2009 Google Inc. John(Jung-Ik) Lee <jilee@google.com>
*
* Per Atp867 data sheet rev 1.2, Acard.
* Based in part on early ide code from
* 2003-2004 by Eric Uhrhane, Google, 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
*
*
* TODO:
* 1. RAID features [comparison, XOR, striping, mirroring, etc.]
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/gfp.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_atp867x"
#define DRV_VERSION "0.7.5"
/*
* IO Registers
* Note that all runtime hot priv ports are cached in ap private_data
*/
enum {
ATP867X_IO_CHANNEL_OFFSET = 0x10,
/*
* IO Register Bitfields
*/
ATP867X_IO_PIOSPD_ACTIVE_SHIFT = 4,
ATP867X_IO_PIOSPD_RECOVER_SHIFT = 0,
ATP867X_IO_DMAMODE_MSTR_SHIFT = 0,
ATP867X_IO_DMAMODE_MSTR_MASK = 0x07,
ATP867X_IO_DMAMODE_SLAVE_SHIFT = 4,
ATP867X_IO_DMAMODE_SLAVE_MASK = 0x70,
ATP867X_IO_DMAMODE_UDMA_6 = 0x07,
ATP867X_IO_DMAMODE_UDMA_5 = 0x06,
ATP867X_IO_DMAMODE_UDMA_4 = 0x05,
ATP867X_IO_DMAMODE_UDMA_3 = 0x04,
ATP867X_IO_DMAMODE_UDMA_2 = 0x03,
ATP867X_IO_DMAMODE_UDMA_1 = 0x02,
ATP867X_IO_DMAMODE_UDMA_0 = 0x01,
ATP867X_IO_DMAMODE_DISABLE = 0x00,
ATP867X_IO_SYS_INFO_66MHZ = 0x04,
ATP867X_IO_SYS_INFO_SLOW_UDMA5 = 0x02,
ATP867X_IO_SYS_MASK_RESERVED = (~0xf1),
ATP867X_IO_PORTSPD_VAL = 0x1143,
ATP867X_PREREAD_VAL = 0x0200,
ATP867X_NUM_PORTS = 4,
ATP867X_BAR_IOBASE = 0,
ATP867X_BAR_ROMBASE = 6,
};
#define ATP867X_IOBASE(ap) ((ap)->host->iomap[0])
#define ATP867X_SYS_INFO(ap) (0x3F + ATP867X_IOBASE(ap))
#define ATP867X_IO_PORTBASE(ap, port) (0x00 + ATP867X_IOBASE(ap) + \
(port) * ATP867X_IO_CHANNEL_OFFSET)
#define ATP867X_IO_DMABASE(ap, port) (0x40 + \
ATP867X_IO_PORTBASE((ap), (port)))
#define ATP867X_IO_STATUS(ap, port) (0x07 + \
ATP867X_IO_PORTBASE((ap), (port)))
#define ATP867X_IO_ALTSTATUS(ap, port) (0x0E + \
ATP867X_IO_PORTBASE((ap), (port)))
/*
* hot priv ports
*/
#define ATP867X_IO_MSTRPIOSPD(ap, port) (0x08 + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_SLAVPIOSPD(ap, port) (0x09 + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_8BPIOSPD(ap, port) (0x0A + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_DMAMODE(ap, port) (0x0B + \
ATP867X_IO_DMABASE((ap), (port)))
#define ATP867X_IO_PORTSPD(ap, port) (0x4A + \
ATP867X_IO_PORTBASE((ap), (port)))
#define ATP867X_IO_PREREAD(ap, port) (0x4C + \
ATP867X_IO_PORTBASE((ap), (port)))
struct atp867x_priv {
void __iomem *dma_mode;
void __iomem *mstr_piospd;
void __iomem *slave_piospd;
void __iomem *eightb_piospd;
int pci66mhz;
};
static void atp867x_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct atp867x_priv *dp = ap->private_data;
u8 speed = adev->dma_mode;
u8 b;
u8 mode = speed - XFER_UDMA_0 + 1;
/*
* Doc 6.6.9: decrease the udma mode value by 1 for safer UDMA speed
* on 66MHz bus
* rev-A: UDMA_1~4 (5, 6 no change)
* rev-B: all UDMA modes
* UDMA_0 stays not to disable UDMA
*/
if (dp->pci66mhz && mode > ATP867X_IO_DMAMODE_UDMA_0 &&
(pdev->device == PCI_DEVICE_ID_ARTOP_ATP867B ||
mode < ATP867X_IO_DMAMODE_UDMA_5))
mode--;
b = ioread8(dp->dma_mode);
if (adev->devno & 1) {
b = (b & ~ATP867X_IO_DMAMODE_SLAVE_MASK) |
(mode << ATP867X_IO_DMAMODE_SLAVE_SHIFT);
} else {
b = (b & ~ATP867X_IO_DMAMODE_MSTR_MASK) |
(mode << ATP867X_IO_DMAMODE_MSTR_SHIFT);
}
iowrite8(b, dp->dma_mode);
}
static int atp867x_get_active_clocks_shifted(struct ata_port *ap,
unsigned int clk)
{
struct atp867x_priv *dp = ap->private_data;
unsigned char clocks = clk;
/*
* Doc 6.6.9: increase the clock value by 1 for safer PIO speed
* on 66MHz bus
*/
if (dp->pci66mhz)
clocks++;
switch (clocks) {
case 0:
clocks = 1;
break;
case 1 ... 6:
break;
default:
printk(KERN_WARNING "ATP867X: active %dclk is invalid. "
"Using 12clk.\n", clk);
case 9 ... 12:
clocks = 7; /* 12 clk */
break;
case 7:
case 8: /* default 8 clk */
clocks = 0;
goto active_clock_shift_done;
}
active_clock_shift_done:
return clocks << ATP867X_IO_PIOSPD_ACTIVE_SHIFT;
}
static int atp867x_get_recover_clocks_shifted(unsigned int clk)
{
unsigned char clocks = clk;
switch (clocks) {
case 0:
clocks = 1;
break;
case 1 ... 11:
break;
case 13:
case 14:
--clocks; /* by the spec */
break;
case 15:
break;
default:
printk(KERN_WARNING "ATP867X: recover %dclk is invalid. "
"Using default 12clk.\n", clk);
case 12: /* default 12 clk */
clocks = 0;
break;
}
return clocks << ATP867X_IO_PIOSPD_RECOVER_SHIFT;
}
static void atp867x_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct ata_device *peer = ata_dev_pair(adev);
struct atp867x_priv *dp = ap->private_data;
u8 speed = adev->pio_mode;
struct ata_timing t, p;
int T, UT;
u8 b;
T = 1000000000 / 33333;
UT = T / 4;
ata_timing_compute(adev, speed, &t, T, UT);
if (peer && peer->pio_mode) {
ata_timing_compute(peer, peer->pio_mode, &p, T, UT);
ata_timing_merge(&p, &t, &t, ATA_TIMING_8BIT);
}
b = ioread8(dp->dma_mode);
if (adev->devno & 1)
b = (b & ~ATP867X_IO_DMAMODE_SLAVE_MASK);
else
b = (b & ~ATP867X_IO_DMAMODE_MSTR_MASK);
iowrite8(b, dp->dma_mode);
b = atp867x_get_active_clocks_shifted(ap, t.active) |
atp867x_get_recover_clocks_shifted(t.recover);
if (adev->devno & 1)
iowrite8(b, dp->slave_piospd);
else
iowrite8(b, dp->mstr_piospd);
b = atp867x_get_active_clocks_shifted(ap, t.act8b) |
atp867x_get_recover_clocks_shifted(t.rec8b);
iowrite8(b, dp->eightb_piospd);
}
static int atp867x_cable_override(struct pci_dev *pdev)
{
if (pdev->subsystem_vendor == PCI_VENDOR_ID_ARTOP &&
(pdev->subsystem_device == PCI_DEVICE_ID_ARTOP_ATP867A ||
pdev->subsystem_device == PCI_DEVICE_ID_ARTOP_ATP867B)) {
return 1;
}
return 0;
}
static int atp867x_cable_detect(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
if (atp867x_cable_override(pdev))
return ATA_CBL_PATA40_SHORT;
return ATA_CBL_PATA_UNK;
}
static struct scsi_host_template atp867x_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations atp867x_ops = {
.inherits = &ata_bmdma_port_ops,
.cable_detect = atp867x_cable_detect,
.set_piomode = atp867x_set_piomode,
.set_dmamode = atp867x_set_dmamode,
};
#ifdef ATP867X_DEBUG
static void atp867x_check_res(struct pci_dev *pdev)
{
int i;
unsigned long start, len;
/* Check the PCI resources for this channel are enabled */
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
start = pci_resource_start(pdev, i);
len = pci_resource_len(pdev, i);
printk(KERN_DEBUG "ATP867X: resource start:len=%lx:%lx\n",
start, len);
}
}
static void atp867x_check_ports(struct ata_port *ap, int port)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
struct atp867x_priv *dp = ap->private_data;
printk(KERN_DEBUG "ATP867X: port[%d] addresses\n"
" cmd_addr =0x%llx, 0x%llx\n"
" ctl_addr =0x%llx, 0x%llx\n"
" bmdma_addr =0x%llx, 0x%llx\n"
" data_addr =0x%llx\n"
" error_addr =0x%llx\n"
" feature_addr =0x%llx\n"
" nsect_addr =0x%llx\n"
" lbal_addr =0x%llx\n"
" lbam_addr =0x%llx\n"
" lbah_addr =0x%llx\n"
" device_addr =0x%llx\n"
" status_addr =0x%llx\n"
" command_addr =0x%llx\n"
" dp->dma_mode =0x%llx\n"
" dp->mstr_piospd =0x%llx\n"
" dp->slave_piospd =0x%llx\n"
" dp->eightb_piospd =0x%llx\n"
" dp->pci66mhz =0x%lx\n",
port,
(unsigned long long)ioaddr->cmd_addr,
(unsigned long long)ATP867X_IO_PORTBASE(ap, port),
(unsigned long long)ioaddr->ctl_addr,
(unsigned long long)ATP867X_IO_ALTSTATUS(ap, port),
(unsigned long long)ioaddr->bmdma_addr,
(unsigned long long)ATP867X_IO_DMABASE(ap, port),
(unsigned long long)ioaddr->data_addr,
(unsigned long long)ioaddr->error_addr,
(unsigned long long)ioaddr->feature_addr,
(unsigned long long)ioaddr->nsect_addr,
(unsigned long long)ioaddr->lbal_addr,
(unsigned long long)ioaddr->lbam_addr,
(unsigned long long)ioaddr->lbah_addr,
(unsigned long long)ioaddr->device_addr,
(unsigned long long)ioaddr->status_addr,
(unsigned long long)ioaddr->command_addr,
(unsigned long long)dp->dma_mode,
(unsigned long long)dp->mstr_piospd,
(unsigned long long)dp->slave_piospd,
(unsigned long long)dp->eightb_piospd,
(unsigned long)dp->pci66mhz);
}
#endif
static int atp867x_set_priv(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct atp867x_priv *dp;
int port = ap->port_no;
dp = ap->private_data =
devm_kzalloc(&pdev->dev, sizeof(*dp), GFP_KERNEL);
if (dp == NULL)
return -ENOMEM;
dp->dma_mode = ATP867X_IO_DMAMODE(ap, port);
dp->mstr_piospd = ATP867X_IO_MSTRPIOSPD(ap, port);
dp->slave_piospd = ATP867X_IO_SLAVPIOSPD(ap, port);
dp->eightb_piospd = ATP867X_IO_8BPIOSPD(ap, port);
dp->pci66mhz =
ioread8(ATP867X_SYS_INFO(ap)) & ATP867X_IO_SYS_INFO_66MHZ;
return 0;
}
static void atp867x_fixup(struct ata_host *host)
{
struct pci_dev *pdev = to_pci_dev(host->dev);
struct ata_port *ap = host->ports[0];
int i;
u8 v;
/*
* Broken BIOS might not set latency high enough
*/
pci_read_config_byte(pdev, PCI_LATENCY_TIMER, &v);
if (v < 0x80) {
v = 0x80;
pci_write_config_byte(pdev, PCI_LATENCY_TIMER, v);
printk(KERN_DEBUG "ATP867X: set latency timer of device %s"
" to %d\n", pci_name(pdev), v);
}
/*
* init 8bit io ports speed(0aaarrrr) to 43h and
* init udma modes of master/slave to 0/0(11h)
*/
for (i = 0; i < ATP867X_NUM_PORTS; i++)
iowrite16(ATP867X_IO_PORTSPD_VAL, ATP867X_IO_PORTSPD(ap, i));
/*
* init PreREAD counts
*/
for (i = 0; i < ATP867X_NUM_PORTS; i++)
iowrite16(ATP867X_PREREAD_VAL, ATP867X_IO_PREREAD(ap, i));
v = ioread8(ATP867X_IOBASE(ap) + 0x28);
v &= 0xcf; /* Enable INTA#: bit4=0 means enable */
v |= 0xc0; /* Enable PCI burst, MRM & not immediate interrupts */
iowrite8(v, ATP867X_IOBASE(ap) + 0x28);
/*
* Turn off the over clocked udma5 mode, only for Rev-B
*/
v = ioread8(ATP867X_SYS_INFO(ap));
v &= ATP867X_IO_SYS_MASK_RESERVED;
if (pdev->device == PCI_DEVICE_ID_ARTOP_ATP867B)
v |= ATP867X_IO_SYS_INFO_SLOW_UDMA5;
iowrite8(v, ATP867X_SYS_INFO(ap));
}
static int atp867x_ata_pci_sff_init_host(struct ata_host *host)
{
struct device *gdev = host->dev;
struct pci_dev *pdev = to_pci_dev(gdev);
unsigned int mask = 0;
int i, rc;
/*
* do not map rombase
*/
rc = pcim_iomap_regions(pdev, 1 << ATP867X_BAR_IOBASE, DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
#ifdef ATP867X_DEBUG
atp867x_check_res(pdev);
for (i = 0; i < PCI_ROM_RESOURCE; i++)
printk(KERN_DEBUG "ATP867X: iomap[%d]=0x%llx\n", i,
(unsigned long long)(host->iomap[i]));
#endif
/*
* request, iomap BARs and init port addresses accordingly
*/
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
struct ata_ioports *ioaddr = &ap->ioaddr;
ioaddr->cmd_addr = ATP867X_IO_PORTBASE(ap, i);
ioaddr->ctl_addr = ioaddr->altstatus_addr
= ATP867X_IO_ALTSTATUS(ap, i);
ioaddr->bmdma_addr = ATP867X_IO_DMABASE(ap, i);
ata_sff_std_ports(ioaddr);
rc = atp867x_set_priv(ap);
if (rc)
return rc;
#ifdef ATP867X_DEBUG
atp867x_check_ports(ap, i);
#endif
ata_port_desc(ap, "cmd 0x%lx ctl 0x%lx",
(unsigned long)ioaddr->cmd_addr,
(unsigned long)ioaddr->ctl_addr);
ata_port_desc(ap, "bmdma 0x%lx",
(unsigned long)ioaddr->bmdma_addr);
mask |= 1 << i;
}
if (!mask) {
dev_err(gdev, "no available native port\n");
return -ENODEV;
}
atp867x_fixup(host);
rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
return rc;
}
static int atp867x_init_one(struct pci_dev *pdev,
const struct pci_device_id *id)
{
static const struct ata_port_info info_867x = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.udma_mask = ATA_UDMA6,
.port_ops = &atp867x_ops,
};
struct ata_host *host;
const struct ata_port_info *ppi[] = { &info_867x, NULL };
int rc;
ata_print_version_once(&pdev->dev, DRV_VERSION);
rc = pcim_enable_device(pdev);
if (rc)
return rc;
printk(KERN_INFO "ATP867X: ATP867 ATA UDMA133 controller (rev %02X)",
pdev->device);
host = ata_host_alloc_pinfo(&pdev->dev, ppi, ATP867X_NUM_PORTS);
if (!host) {
dev_err(&pdev->dev, "failed to allocate ATA host\n");
rc = -ENOMEM;
goto err_out;
}
rc = atp867x_ata_pci_sff_init_host(host);
if (rc) {
dev_err(&pdev->dev, "failed to init host\n");
goto err_out;
}
pci_set_master(pdev);
rc = ata_host_activate(host, pdev->irq, ata_bmdma_interrupt,
IRQF_SHARED, &atp867x_sht);
if (rc)
dev_err(&pdev->dev, "failed to activate host\n");
err_out:
return rc;
}
#ifdef CONFIG_PM
static int atp867x_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
atp867x_fixup(host);
ata_host_resume(host);
return 0;
}
#endif
static struct pci_device_id atp867x_pci_tbl[] = {
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP867A), 0 },
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP867B), 0 },
{ },
};
static struct pci_driver atp867x_driver = {
.name = DRV_NAME,
.id_table = atp867x_pci_tbl,
.probe = atp867x_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = atp867x_reinit_one,
#endif
};
static int __init atp867x_init(void)
{
return pci_register_driver(&atp867x_driver);
}
static void __exit atp867x_exit(void)
{
pci_unregister_driver(&atp867x_driver);
}
MODULE_AUTHOR("John(Jung-Ik) Lee, Google Inc.");
MODULE_DESCRIPTION("low level driver for Artop/Acard 867x ATA controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, atp867x_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(atp867x_init);
module_exit(atp867x_exit);
| gpl-2.0 |
cherifyass/android_kernel_lge_hammerhead | arch/s390/crypto/aes_s390.c | 6532 | 23934 | /*
* Cryptographic API.
*
* s390 implementation of the AES Cipher Algorithm.
*
* s390 Version:
* Copyright IBM Corp. 2005,2007
* Author(s): Jan Glauber (jang@de.ibm.com)
* Sebastian Siewior (sebastian@breakpoint.cc> SW-Fallback
*
* Derived from "crypto/aes_generic.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.
*
*/
#define KMSG_COMPONENT "aes_s390"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <crypto/aes.h>
#include <crypto/algapi.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/init.h>
#include "crypt_s390.h"
#define AES_KEYLEN_128 1
#define AES_KEYLEN_192 2
#define AES_KEYLEN_256 4
static u8 *ctrblk;
static char keylen_flag;
struct s390_aes_ctx {
u8 iv[AES_BLOCK_SIZE];
u8 key[AES_MAX_KEY_SIZE];
long enc;
long dec;
int key_len;
union {
struct crypto_blkcipher *blk;
struct crypto_cipher *cip;
} fallback;
};
struct pcc_param {
u8 key[32];
u8 tweak[16];
u8 block[16];
u8 bit[16];
u8 xts[16];
};
struct s390_xts_ctx {
u8 key[32];
u8 xts_param[16];
struct pcc_param pcc;
long enc;
long dec;
int key_len;
struct crypto_blkcipher *fallback;
};
/*
* Check if the key_len is supported by the HW.
* Returns 0 if it is, a positive number if it is not and software fallback is
* required or a negative number in case the key size is not valid
*/
static int need_fallback(unsigned int key_len)
{
switch (key_len) {
case 16:
if (!(keylen_flag & AES_KEYLEN_128))
return 1;
break;
case 24:
if (!(keylen_flag & AES_KEYLEN_192))
return 1;
break;
case 32:
if (!(keylen_flag & AES_KEYLEN_256))
return 1;
break;
default:
return -1;
break;
}
return 0;
}
static int setkey_fallback_cip(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
int ret;
sctx->fallback.cip->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK;
sctx->fallback.cip->base.crt_flags |= (tfm->crt_flags &
CRYPTO_TFM_REQ_MASK);
ret = crypto_cipher_setkey(sctx->fallback.cip, in_key, key_len);
if (ret) {
tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK;
tfm->crt_flags |= (sctx->fallback.cip->base.crt_flags &
CRYPTO_TFM_RES_MASK);
}
return ret;
}
static int aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
u32 *flags = &tfm->crt_flags;
int ret;
ret = need_fallback(key_len);
if (ret < 0) {
*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
return -EINVAL;
}
sctx->key_len = key_len;
if (!ret) {
memcpy(sctx->key, in_key, key_len);
return 0;
}
return setkey_fallback_cip(tfm, in_key, key_len);
}
static void aes_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
const struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
if (unlikely(need_fallback(sctx->key_len))) {
crypto_cipher_encrypt_one(sctx->fallback.cip, out, in);
return;
}
switch (sctx->key_len) {
case 16:
crypt_s390_km(KM_AES_128_ENCRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 24:
crypt_s390_km(KM_AES_192_ENCRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 32:
crypt_s390_km(KM_AES_256_ENCRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
}
}
static void aes_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
const struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
if (unlikely(need_fallback(sctx->key_len))) {
crypto_cipher_decrypt_one(sctx->fallback.cip, out, in);
return;
}
switch (sctx->key_len) {
case 16:
crypt_s390_km(KM_AES_128_DECRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 24:
crypt_s390_km(KM_AES_192_DECRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 32:
crypt_s390_km(KM_AES_256_DECRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
}
}
static int fallback_init_cip(struct crypto_tfm *tfm)
{
const char *name = tfm->__crt_alg->cra_name;
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
sctx->fallback.cip = crypto_alloc_cipher(name, 0,
CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(sctx->fallback.cip)) {
pr_err("Allocating AES fallback algorithm %s failed\n",
name);
return PTR_ERR(sctx->fallback.cip);
}
return 0;
}
static void fallback_exit_cip(struct crypto_tfm *tfm)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
crypto_free_cipher(sctx->fallback.cip);
sctx->fallback.cip = NULL;
}
static struct crypto_alg aes_alg = {
.cra_name = "aes",
.cra_driver_name = "aes-s390",
.cra_priority = CRYPT_S390_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s390_aes_ctx),
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(aes_alg.cra_list),
.cra_init = fallback_init_cip,
.cra_exit = fallback_exit_cip,
.cra_u = {
.cipher = {
.cia_min_keysize = AES_MIN_KEY_SIZE,
.cia_max_keysize = AES_MAX_KEY_SIZE,
.cia_setkey = aes_set_key,
.cia_encrypt = aes_encrypt,
.cia_decrypt = aes_decrypt,
}
}
};
static int setkey_fallback_blk(struct crypto_tfm *tfm, const u8 *key,
unsigned int len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
unsigned int ret;
sctx->fallback.blk->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK;
sctx->fallback.blk->base.crt_flags |= (tfm->crt_flags &
CRYPTO_TFM_REQ_MASK);
ret = crypto_blkcipher_setkey(sctx->fallback.blk, key, len);
if (ret) {
tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK;
tfm->crt_flags |= (sctx->fallback.blk->base.crt_flags &
CRYPTO_TFM_RES_MASK);
}
return ret;
}
static int fallback_blk_dec(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
unsigned int ret;
struct crypto_blkcipher *tfm;
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
tfm = desc->tfm;
desc->tfm = sctx->fallback.blk;
ret = crypto_blkcipher_decrypt_iv(desc, dst, src, nbytes);
desc->tfm = tfm;
return ret;
}
static int fallback_blk_enc(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
unsigned int ret;
struct crypto_blkcipher *tfm;
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
tfm = desc->tfm;
desc->tfm = sctx->fallback.blk;
ret = crypto_blkcipher_encrypt_iv(desc, dst, src, nbytes);
desc->tfm = tfm;
return ret;
}
static int ecb_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
int ret;
ret = need_fallback(key_len);
if (ret > 0) {
sctx->key_len = key_len;
return setkey_fallback_blk(tfm, in_key, key_len);
}
switch (key_len) {
case 16:
sctx->enc = KM_AES_128_ENCRYPT;
sctx->dec = KM_AES_128_DECRYPT;
break;
case 24:
sctx->enc = KM_AES_192_ENCRYPT;
sctx->dec = KM_AES_192_DECRYPT;
break;
case 32:
sctx->enc = KM_AES_256_ENCRYPT;
sctx->dec = KM_AES_256_DECRYPT;
break;
}
return aes_set_key(tfm, in_key, key_len);
}
static int ecb_aes_crypt(struct blkcipher_desc *desc, long func, void *param,
struct blkcipher_walk *walk)
{
int ret = blkcipher_walk_virt(desc, walk);
unsigned int nbytes;
while ((nbytes = walk->nbytes)) {
/* only use complete blocks */
unsigned int n = nbytes & ~(AES_BLOCK_SIZE - 1);
u8 *out = walk->dst.virt.addr;
u8 *in = walk->src.virt.addr;
ret = crypt_s390_km(func, param, out, in, n);
BUG_ON((ret < 0) || (ret != n));
nbytes &= AES_BLOCK_SIZE - 1;
ret = blkcipher_walk_done(desc, walk, nbytes);
}
return ret;
}
static int ecb_aes_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_enc(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return ecb_aes_crypt(desc, sctx->enc, sctx->key, &walk);
}
static int ecb_aes_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_dec(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return ecb_aes_crypt(desc, sctx->dec, sctx->key, &walk);
}
static int fallback_init_blk(struct crypto_tfm *tfm)
{
const char *name = tfm->__crt_alg->cra_name;
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
sctx->fallback.blk = crypto_alloc_blkcipher(name, 0,
CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(sctx->fallback.blk)) {
pr_err("Allocating AES fallback algorithm %s failed\n",
name);
return PTR_ERR(sctx->fallback.blk);
}
return 0;
}
static void fallback_exit_blk(struct crypto_tfm *tfm)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
crypto_free_blkcipher(sctx->fallback.blk);
sctx->fallback.blk = NULL;
}
static struct crypto_alg ecb_aes_alg = {
.cra_name = "ecb(aes)",
.cra_driver_name = "ecb-aes-s390",
.cra_priority = CRYPT_S390_COMPOSITE_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s390_aes_ctx),
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ecb_aes_alg.cra_list),
.cra_init = fallback_init_blk,
.cra_exit = fallback_exit_blk,
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = ecb_aes_set_key,
.encrypt = ecb_aes_encrypt,
.decrypt = ecb_aes_decrypt,
}
}
};
static int cbc_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
int ret;
ret = need_fallback(key_len);
if (ret > 0) {
sctx->key_len = key_len;
return setkey_fallback_blk(tfm, in_key, key_len);
}
switch (key_len) {
case 16:
sctx->enc = KMC_AES_128_ENCRYPT;
sctx->dec = KMC_AES_128_DECRYPT;
break;
case 24:
sctx->enc = KMC_AES_192_ENCRYPT;
sctx->dec = KMC_AES_192_DECRYPT;
break;
case 32:
sctx->enc = KMC_AES_256_ENCRYPT;
sctx->dec = KMC_AES_256_DECRYPT;
break;
}
return aes_set_key(tfm, in_key, key_len);
}
static int cbc_aes_crypt(struct blkcipher_desc *desc, long func, void *param,
struct blkcipher_walk *walk)
{
int ret = blkcipher_walk_virt(desc, walk);
unsigned int nbytes = walk->nbytes;
if (!nbytes)
goto out;
memcpy(param, walk->iv, AES_BLOCK_SIZE);
do {
/* only use complete blocks */
unsigned int n = nbytes & ~(AES_BLOCK_SIZE - 1);
u8 *out = walk->dst.virt.addr;
u8 *in = walk->src.virt.addr;
ret = crypt_s390_kmc(func, param, out, in, n);
BUG_ON((ret < 0) || (ret != n));
nbytes &= AES_BLOCK_SIZE - 1;
ret = blkcipher_walk_done(desc, walk, nbytes);
} while ((nbytes = walk->nbytes));
memcpy(walk->iv, param, AES_BLOCK_SIZE);
out:
return ret;
}
static int cbc_aes_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_enc(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return cbc_aes_crypt(desc, sctx->enc, sctx->iv, &walk);
}
static int cbc_aes_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_dec(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return cbc_aes_crypt(desc, sctx->dec, sctx->iv, &walk);
}
static struct crypto_alg cbc_aes_alg = {
.cra_name = "cbc(aes)",
.cra_driver_name = "cbc-aes-s390",
.cra_priority = CRYPT_S390_COMPOSITE_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s390_aes_ctx),
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(cbc_aes_alg.cra_list),
.cra_init = fallback_init_blk,
.cra_exit = fallback_exit_blk,
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = cbc_aes_set_key,
.encrypt = cbc_aes_encrypt,
.decrypt = cbc_aes_decrypt,
}
}
};
static int xts_fallback_setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int len)
{
struct s390_xts_ctx *xts_ctx = crypto_tfm_ctx(tfm);
unsigned int ret;
xts_ctx->fallback->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK;
xts_ctx->fallback->base.crt_flags |= (tfm->crt_flags &
CRYPTO_TFM_REQ_MASK);
ret = crypto_blkcipher_setkey(xts_ctx->fallback, key, len);
if (ret) {
tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK;
tfm->crt_flags |= (xts_ctx->fallback->base.crt_flags &
CRYPTO_TFM_RES_MASK);
}
return ret;
}
static int xts_fallback_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_xts_ctx *xts_ctx = crypto_blkcipher_ctx(desc->tfm);
struct crypto_blkcipher *tfm;
unsigned int ret;
tfm = desc->tfm;
desc->tfm = xts_ctx->fallback;
ret = crypto_blkcipher_decrypt_iv(desc, dst, src, nbytes);
desc->tfm = tfm;
return ret;
}
static int xts_fallback_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_xts_ctx *xts_ctx = crypto_blkcipher_ctx(desc->tfm);
struct crypto_blkcipher *tfm;
unsigned int ret;
tfm = desc->tfm;
desc->tfm = xts_ctx->fallback;
ret = crypto_blkcipher_encrypt_iv(desc, dst, src, nbytes);
desc->tfm = tfm;
return ret;
}
static int xts_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_xts_ctx *xts_ctx = crypto_tfm_ctx(tfm);
u32 *flags = &tfm->crt_flags;
switch (key_len) {
case 32:
xts_ctx->enc = KM_XTS_128_ENCRYPT;
xts_ctx->dec = KM_XTS_128_DECRYPT;
memcpy(xts_ctx->key + 16, in_key, 16);
memcpy(xts_ctx->pcc.key + 16, in_key + 16, 16);
break;
case 48:
xts_ctx->enc = 0;
xts_ctx->dec = 0;
xts_fallback_setkey(tfm, in_key, key_len);
break;
case 64:
xts_ctx->enc = KM_XTS_256_ENCRYPT;
xts_ctx->dec = KM_XTS_256_DECRYPT;
memcpy(xts_ctx->key, in_key, 32);
memcpy(xts_ctx->pcc.key, in_key + 32, 32);
break;
default:
*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
return -EINVAL;
}
xts_ctx->key_len = key_len;
return 0;
}
static int xts_aes_crypt(struct blkcipher_desc *desc, long func,
struct s390_xts_ctx *xts_ctx,
struct blkcipher_walk *walk)
{
unsigned int offset = (xts_ctx->key_len >> 1) & 0x10;
int ret = blkcipher_walk_virt(desc, walk);
unsigned int nbytes = walk->nbytes;
unsigned int n;
u8 *in, *out;
void *param;
if (!nbytes)
goto out;
memset(xts_ctx->pcc.block, 0, sizeof(xts_ctx->pcc.block));
memset(xts_ctx->pcc.bit, 0, sizeof(xts_ctx->pcc.bit));
memset(xts_ctx->pcc.xts, 0, sizeof(xts_ctx->pcc.xts));
memcpy(xts_ctx->pcc.tweak, walk->iv, sizeof(xts_ctx->pcc.tweak));
param = xts_ctx->pcc.key + offset;
ret = crypt_s390_pcc(func, param);
BUG_ON(ret < 0);
memcpy(xts_ctx->xts_param, xts_ctx->pcc.xts, 16);
param = xts_ctx->key + offset;
do {
/* only use complete blocks */
n = nbytes & ~(AES_BLOCK_SIZE - 1);
out = walk->dst.virt.addr;
in = walk->src.virt.addr;
ret = crypt_s390_km(func, param, out, in, n);
BUG_ON(ret < 0 || ret != n);
nbytes &= AES_BLOCK_SIZE - 1;
ret = blkcipher_walk_done(desc, walk, nbytes);
} while ((nbytes = walk->nbytes));
out:
return ret;
}
static int xts_aes_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_xts_ctx *xts_ctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(xts_ctx->key_len == 48))
return xts_fallback_encrypt(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return xts_aes_crypt(desc, xts_ctx->enc, xts_ctx, &walk);
}
static int xts_aes_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_xts_ctx *xts_ctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(xts_ctx->key_len == 48))
return xts_fallback_decrypt(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return xts_aes_crypt(desc, xts_ctx->dec, xts_ctx, &walk);
}
static int xts_fallback_init(struct crypto_tfm *tfm)
{
const char *name = tfm->__crt_alg->cra_name;
struct s390_xts_ctx *xts_ctx = crypto_tfm_ctx(tfm);
xts_ctx->fallback = crypto_alloc_blkcipher(name, 0,
CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(xts_ctx->fallback)) {
pr_err("Allocating XTS fallback algorithm %s failed\n",
name);
return PTR_ERR(xts_ctx->fallback);
}
return 0;
}
static void xts_fallback_exit(struct crypto_tfm *tfm)
{
struct s390_xts_ctx *xts_ctx = crypto_tfm_ctx(tfm);
crypto_free_blkcipher(xts_ctx->fallback);
xts_ctx->fallback = NULL;
}
static struct crypto_alg xts_aes_alg = {
.cra_name = "xts(aes)",
.cra_driver_name = "xts-aes-s390",
.cra_priority = CRYPT_S390_COMPOSITE_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s390_xts_ctx),
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(xts_aes_alg.cra_list),
.cra_init = xts_fallback_init,
.cra_exit = xts_fallback_exit,
.cra_u = {
.blkcipher = {
.min_keysize = 2 * AES_MIN_KEY_SIZE,
.max_keysize = 2 * AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = xts_aes_set_key,
.encrypt = xts_aes_encrypt,
.decrypt = xts_aes_decrypt,
}
}
};
static int ctr_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
switch (key_len) {
case 16:
sctx->enc = KMCTR_AES_128_ENCRYPT;
sctx->dec = KMCTR_AES_128_DECRYPT;
break;
case 24:
sctx->enc = KMCTR_AES_192_ENCRYPT;
sctx->dec = KMCTR_AES_192_DECRYPT;
break;
case 32:
sctx->enc = KMCTR_AES_256_ENCRYPT;
sctx->dec = KMCTR_AES_256_DECRYPT;
break;
}
return aes_set_key(tfm, in_key, key_len);
}
static int ctr_aes_crypt(struct blkcipher_desc *desc, long func,
struct s390_aes_ctx *sctx, struct blkcipher_walk *walk)
{
int ret = blkcipher_walk_virt_block(desc, walk, AES_BLOCK_SIZE);
unsigned int i, n, nbytes;
u8 buf[AES_BLOCK_SIZE];
u8 *out, *in;
if (!walk->nbytes)
return ret;
memcpy(ctrblk, walk->iv, AES_BLOCK_SIZE);
while ((nbytes = walk->nbytes) >= AES_BLOCK_SIZE) {
out = walk->dst.virt.addr;
in = walk->src.virt.addr;
while (nbytes >= AES_BLOCK_SIZE) {
/* only use complete blocks, max. PAGE_SIZE */
n = (nbytes > PAGE_SIZE) ? PAGE_SIZE :
nbytes & ~(AES_BLOCK_SIZE - 1);
for (i = AES_BLOCK_SIZE; i < n; i += AES_BLOCK_SIZE) {
memcpy(ctrblk + i, ctrblk + i - AES_BLOCK_SIZE,
AES_BLOCK_SIZE);
crypto_inc(ctrblk + i, AES_BLOCK_SIZE);
}
ret = crypt_s390_kmctr(func, sctx->key, out, in, n, ctrblk);
BUG_ON(ret < 0 || ret != n);
if (n > AES_BLOCK_SIZE)
memcpy(ctrblk, ctrblk + n - AES_BLOCK_SIZE,
AES_BLOCK_SIZE);
crypto_inc(ctrblk, AES_BLOCK_SIZE);
out += n;
in += n;
nbytes -= n;
}
ret = blkcipher_walk_done(desc, walk, nbytes);
}
/*
* final block may be < AES_BLOCK_SIZE, copy only nbytes
*/
if (nbytes) {
out = walk->dst.virt.addr;
in = walk->src.virt.addr;
ret = crypt_s390_kmctr(func, sctx->key, buf, in,
AES_BLOCK_SIZE, ctrblk);
BUG_ON(ret < 0 || ret != AES_BLOCK_SIZE);
memcpy(out, buf, nbytes);
crypto_inc(ctrblk, AES_BLOCK_SIZE);
ret = blkcipher_walk_done(desc, walk, 0);
}
memcpy(walk->iv, ctrblk, AES_BLOCK_SIZE);
return ret;
}
static int ctr_aes_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
blkcipher_walk_init(&walk, dst, src, nbytes);
return ctr_aes_crypt(desc, sctx->enc, sctx, &walk);
}
static int ctr_aes_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
blkcipher_walk_init(&walk, dst, src, nbytes);
return ctr_aes_crypt(desc, sctx->dec, sctx, &walk);
}
static struct crypto_alg ctr_aes_alg = {
.cra_name = "ctr(aes)",
.cra_driver_name = "ctr-aes-s390",
.cra_priority = CRYPT_S390_COMPOSITE_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct s390_aes_ctx),
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ctr_aes_alg.cra_list),
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = ctr_aes_set_key,
.encrypt = ctr_aes_encrypt,
.decrypt = ctr_aes_decrypt,
}
}
};
static int __init aes_s390_init(void)
{
int ret;
if (crypt_s390_func_available(KM_AES_128_ENCRYPT, CRYPT_S390_MSA))
keylen_flag |= AES_KEYLEN_128;
if (crypt_s390_func_available(KM_AES_192_ENCRYPT, CRYPT_S390_MSA))
keylen_flag |= AES_KEYLEN_192;
if (crypt_s390_func_available(KM_AES_256_ENCRYPT, CRYPT_S390_MSA))
keylen_flag |= AES_KEYLEN_256;
if (!keylen_flag)
return -EOPNOTSUPP;
/* z9 109 and z9 BC/EC only support 128 bit key length */
if (keylen_flag == AES_KEYLEN_128)
pr_info("AES hardware acceleration is only available for"
" 128-bit keys\n");
ret = crypto_register_alg(&aes_alg);
if (ret)
goto aes_err;
ret = crypto_register_alg(&ecb_aes_alg);
if (ret)
goto ecb_aes_err;
ret = crypto_register_alg(&cbc_aes_alg);
if (ret)
goto cbc_aes_err;
if (crypt_s390_func_available(KM_XTS_128_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4) &&
crypt_s390_func_available(KM_XTS_256_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4)) {
ret = crypto_register_alg(&xts_aes_alg);
if (ret)
goto xts_aes_err;
}
if (crypt_s390_func_available(KMCTR_AES_128_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4) &&
crypt_s390_func_available(KMCTR_AES_192_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4) &&
crypt_s390_func_available(KMCTR_AES_256_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4)) {
ctrblk = (u8 *) __get_free_page(GFP_KERNEL);
if (!ctrblk) {
ret = -ENOMEM;
goto ctr_aes_err;
}
ret = crypto_register_alg(&ctr_aes_alg);
if (ret) {
free_page((unsigned long) ctrblk);
goto ctr_aes_err;
}
}
out:
return ret;
ctr_aes_err:
crypto_unregister_alg(&xts_aes_alg);
xts_aes_err:
crypto_unregister_alg(&cbc_aes_alg);
cbc_aes_err:
crypto_unregister_alg(&ecb_aes_alg);
ecb_aes_err:
crypto_unregister_alg(&aes_alg);
aes_err:
goto out;
}
static void __exit aes_s390_fini(void)
{
crypto_unregister_alg(&ctr_aes_alg);
free_page((unsigned long) ctrblk);
crypto_unregister_alg(&xts_aes_alg);
crypto_unregister_alg(&cbc_aes_alg);
crypto_unregister_alg(&ecb_aes_alg);
crypto_unregister_alg(&aes_alg);
}
module_init(aes_s390_init);
module_exit(aes_s390_fini);
MODULE_ALIAS("aes-all");
MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kgp700/Neok-GNexroid-JB | drivers/gpu/drm/via/via_dmablit.c | 8324 | 21840 | /* via_dmablit.c -- PCI DMA BitBlt support for the VIA Unichrome/Pro
*
* Copyright (C) 2005 Thomas Hellstrom, 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.
* Partially based on code obtained from Digeo Inc.
*/
/*
* Unmaps the DMA mappings.
* FIXME: Is this a NoOp on x86? Also
* FIXME: What happens if this one is called and a pending blit has previously done
* the same DMA mappings?
*/
#include "drmP.h"
#include "via_drm.h"
#include "via_drv.h"
#include "via_dmablit.h"
#include <linux/pagemap.h>
#include <linux/slab.h>
#define VIA_PGDN(x) (((unsigned long)(x)) & PAGE_MASK)
#define VIA_PGOFF(x) (((unsigned long)(x)) & ~PAGE_MASK)
#define VIA_PFN(x) ((unsigned long)(x) >> PAGE_SHIFT)
typedef struct _drm_via_descriptor {
uint32_t mem_addr;
uint32_t dev_addr;
uint32_t size;
uint32_t next;
} drm_via_descriptor_t;
/*
* Unmap a DMA mapping.
*/
static void
via_unmap_blit_from_device(struct pci_dev *pdev, drm_via_sg_info_t *vsg)
{
int num_desc = vsg->num_desc;
unsigned cur_descriptor_page = num_desc / vsg->descriptors_per_page;
unsigned descriptor_this_page = num_desc % vsg->descriptors_per_page;
drm_via_descriptor_t *desc_ptr = vsg->desc_pages[cur_descriptor_page] +
descriptor_this_page;
dma_addr_t next = vsg->chain_start;
while (num_desc--) {
if (descriptor_this_page-- == 0) {
cur_descriptor_page--;
descriptor_this_page = vsg->descriptors_per_page - 1;
desc_ptr = vsg->desc_pages[cur_descriptor_page] +
descriptor_this_page;
}
dma_unmap_single(&pdev->dev, next, sizeof(*desc_ptr), DMA_TO_DEVICE);
dma_unmap_page(&pdev->dev, desc_ptr->mem_addr, desc_ptr->size, vsg->direction);
next = (dma_addr_t) desc_ptr->next;
desc_ptr--;
}
}
/*
* If mode = 0, count how many descriptors are needed.
* If mode = 1, Map the DMA pages for the device, put together and map also the descriptors.
* Descriptors are run in reverse order by the hardware because we are not allowed to update the
* 'next' field without syncing calls when the descriptor is already mapped.
*/
static void
via_map_blit_for_device(struct pci_dev *pdev,
const drm_via_dmablit_t *xfer,
drm_via_sg_info_t *vsg,
int mode)
{
unsigned cur_descriptor_page = 0;
unsigned num_descriptors_this_page = 0;
unsigned char *mem_addr = xfer->mem_addr;
unsigned char *cur_mem;
unsigned char *first_addr = (unsigned char *)VIA_PGDN(mem_addr);
uint32_t fb_addr = xfer->fb_addr;
uint32_t cur_fb;
unsigned long line_len;
unsigned remaining_len;
int num_desc = 0;
int cur_line;
dma_addr_t next = 0 | VIA_DMA_DPR_EC;
drm_via_descriptor_t *desc_ptr = NULL;
if (mode == 1)
desc_ptr = vsg->desc_pages[cur_descriptor_page];
for (cur_line = 0; cur_line < xfer->num_lines; ++cur_line) {
line_len = xfer->line_length;
cur_fb = fb_addr;
cur_mem = mem_addr;
while (line_len > 0) {
remaining_len = min(PAGE_SIZE-VIA_PGOFF(cur_mem), line_len);
line_len -= remaining_len;
if (mode == 1) {
desc_ptr->mem_addr =
dma_map_page(&pdev->dev,
vsg->pages[VIA_PFN(cur_mem) -
VIA_PFN(first_addr)],
VIA_PGOFF(cur_mem), remaining_len,
vsg->direction);
desc_ptr->dev_addr = cur_fb;
desc_ptr->size = remaining_len;
desc_ptr->next = (uint32_t) next;
next = dma_map_single(&pdev->dev, desc_ptr, sizeof(*desc_ptr),
DMA_TO_DEVICE);
desc_ptr++;
if (++num_descriptors_this_page >= vsg->descriptors_per_page) {
num_descriptors_this_page = 0;
desc_ptr = vsg->desc_pages[++cur_descriptor_page];
}
}
num_desc++;
cur_mem += remaining_len;
cur_fb += remaining_len;
}
mem_addr += xfer->mem_stride;
fb_addr += xfer->fb_stride;
}
if (mode == 1) {
vsg->chain_start = next;
vsg->state = dr_via_device_mapped;
}
vsg->num_desc = num_desc;
}
/*
* Function that frees up all resources for a blit. It is usable even if the
* blit info has only been partially built as long as the status enum is consistent
* with the actual status of the used resources.
*/
static void
via_free_sg_info(struct pci_dev *pdev, drm_via_sg_info_t *vsg)
{
struct page *page;
int i;
switch (vsg->state) {
case dr_via_device_mapped:
via_unmap_blit_from_device(pdev, vsg);
case dr_via_desc_pages_alloc:
for (i = 0; i < vsg->num_desc_pages; ++i) {
if (vsg->desc_pages[i] != NULL)
free_page((unsigned long)vsg->desc_pages[i]);
}
kfree(vsg->desc_pages);
case dr_via_pages_locked:
for (i = 0; i < vsg->num_pages; ++i) {
if (NULL != (page = vsg->pages[i])) {
if (!PageReserved(page) && (DMA_FROM_DEVICE == vsg->direction))
SetPageDirty(page);
page_cache_release(page);
}
}
case dr_via_pages_alloc:
vfree(vsg->pages);
default:
vsg->state = dr_via_sg_init;
}
vfree(vsg->bounce_buffer);
vsg->bounce_buffer = NULL;
vsg->free_on_sequence = 0;
}
/*
* Fire a blit engine.
*/
static void
via_fire_dmablit(struct drm_device *dev, drm_via_sg_info_t *vsg, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_MAR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_DAR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_DD | VIA_DMA_CSR_TD |
VIA_DMA_CSR_DE);
VIA_WRITE(VIA_PCI_DMA_MR0 + engine*0x04, VIA_DMA_MR_CM | VIA_DMA_MR_TDIE);
VIA_WRITE(VIA_PCI_DMA_BCR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_DPR0 + engine*0x10, vsg->chain_start);
DRM_WRITEMEMORYBARRIER();
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_DE | VIA_DMA_CSR_TS);
VIA_READ(VIA_PCI_DMA_CSR0 + engine*0x04);
}
/*
* Obtain a page pointer array and lock all pages into system memory. A segmentation violation will
* occur here if the calling user does not have access to the submitted address.
*/
static int
via_lock_all_dma_pages(drm_via_sg_info_t *vsg, drm_via_dmablit_t *xfer)
{
int ret;
unsigned long first_pfn = VIA_PFN(xfer->mem_addr);
vsg->num_pages = VIA_PFN(xfer->mem_addr + (xfer->num_lines * xfer->mem_stride - 1)) -
first_pfn + 1;
vsg->pages = vzalloc(sizeof(struct page *) * vsg->num_pages);
if (NULL == vsg->pages)
return -ENOMEM;
down_read(¤t->mm->mmap_sem);
ret = get_user_pages(current, current->mm,
(unsigned long)xfer->mem_addr,
vsg->num_pages,
(vsg->direction == DMA_FROM_DEVICE),
0, vsg->pages, NULL);
up_read(¤t->mm->mmap_sem);
if (ret != vsg->num_pages) {
if (ret < 0)
return ret;
vsg->state = dr_via_pages_locked;
return -EINVAL;
}
vsg->state = dr_via_pages_locked;
DRM_DEBUG("DMA pages locked\n");
return 0;
}
/*
* Allocate DMA capable memory for the blit descriptor chain, and an array that keeps track of the
* pages we allocate. We don't want to use kmalloc for the descriptor chain because it may be
* quite large for some blits, and pages don't need to be contingous.
*/
static int
via_alloc_desc_pages(drm_via_sg_info_t *vsg)
{
int i;
vsg->descriptors_per_page = PAGE_SIZE / sizeof(drm_via_descriptor_t);
vsg->num_desc_pages = (vsg->num_desc + vsg->descriptors_per_page - 1) /
vsg->descriptors_per_page;
if (NULL == (vsg->desc_pages = kcalloc(vsg->num_desc_pages, sizeof(void *), GFP_KERNEL)))
return -ENOMEM;
vsg->state = dr_via_desc_pages_alloc;
for (i = 0; i < vsg->num_desc_pages; ++i) {
if (NULL == (vsg->desc_pages[i] =
(drm_via_descriptor_t *) __get_free_page(GFP_KERNEL)))
return -ENOMEM;
}
DRM_DEBUG("Allocated %d pages for %d descriptors.\n", vsg->num_desc_pages,
vsg->num_desc);
return 0;
}
static void
via_abort_dmablit(struct drm_device *dev, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TA);
}
static void
via_dmablit_engine_off(struct drm_device *dev, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TD | VIA_DMA_CSR_DD);
}
/*
* The dmablit part of the IRQ handler. Trying to do only reasonably fast things here.
* The rest, like unmapping and freeing memory for done blits is done in a separate workqueue
* task. Basically the task of the interrupt handler is to submit a new blit to the engine, while
* the workqueue task takes care of processing associated with the old blit.
*/
void
via_dmablit_handler(struct drm_device *dev, int engine, int from_irq)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq = dev_priv->blit_queues + engine;
int cur;
int done_transfer;
unsigned long irqsave = 0;
uint32_t status = 0;
DRM_DEBUG("DMA blit handler called. engine = %d, from_irq = %d, blitq = 0x%lx\n",
engine, from_irq, (unsigned long) blitq);
if (from_irq)
spin_lock(&blitq->blit_lock);
else
spin_lock_irqsave(&blitq->blit_lock, irqsave);
done_transfer = blitq->is_active &&
((status = VIA_READ(VIA_PCI_DMA_CSR0 + engine*0x04)) & VIA_DMA_CSR_TD);
done_transfer = done_transfer || (blitq->aborting && !(status & VIA_DMA_CSR_DE));
cur = blitq->cur;
if (done_transfer) {
blitq->blits[cur]->aborted = blitq->aborting;
blitq->done_blit_handle++;
DRM_WAKEUP(blitq->blit_queue + cur);
cur++;
if (cur >= VIA_NUM_BLIT_SLOTS)
cur = 0;
blitq->cur = cur;
/*
* Clear transfer done flag.
*/
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TD);
blitq->is_active = 0;
blitq->aborting = 0;
schedule_work(&blitq->wq);
} else if (blitq->is_active && time_after_eq(jiffies, blitq->end)) {
/*
* Abort transfer after one second.
*/
via_abort_dmablit(dev, engine);
blitq->aborting = 1;
blitq->end = jiffies + DRM_HZ;
}
if (!blitq->is_active) {
if (blitq->num_outstanding) {
via_fire_dmablit(dev, blitq->blits[cur], engine);
blitq->is_active = 1;
blitq->cur = cur;
blitq->num_outstanding--;
blitq->end = jiffies + DRM_HZ;
if (!timer_pending(&blitq->poll_timer))
mod_timer(&blitq->poll_timer, jiffies + 1);
} else {
if (timer_pending(&blitq->poll_timer))
del_timer(&blitq->poll_timer);
via_dmablit_engine_off(dev, engine);
}
}
if (from_irq)
spin_unlock(&blitq->blit_lock);
else
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
}
/*
* Check whether this blit is still active, performing necessary locking.
*/
static int
via_dmablit_active(drm_via_blitq_t *blitq, int engine, uint32_t handle, wait_queue_head_t **queue)
{
unsigned long irqsave;
uint32_t slot;
int active;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
/*
* Allow for handle wraparounds.
*/
active = ((blitq->done_blit_handle - handle) > (1 << 23)) &&
((blitq->cur_blit_handle - handle) <= (1 << 23));
if (queue && active) {
slot = handle - blitq->done_blit_handle + blitq->cur - 1;
if (slot >= VIA_NUM_BLIT_SLOTS)
slot -= VIA_NUM_BLIT_SLOTS;
*queue = blitq->blit_queue + slot;
}
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
return active;
}
/*
* Sync. Wait for at least three seconds for the blit to be performed.
*/
static int
via_dmablit_sync(struct drm_device *dev, uint32_t handle, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq = dev_priv->blit_queues + engine;
wait_queue_head_t *queue;
int ret = 0;
if (via_dmablit_active(blitq, engine, handle, &queue)) {
DRM_WAIT_ON(ret, *queue, 3 * DRM_HZ,
!via_dmablit_active(blitq, engine, handle, NULL));
}
DRM_DEBUG("DMA blit sync handle 0x%x engine %d returned %d\n",
handle, engine, ret);
return ret;
}
/*
* A timer that regularly polls the blit engine in cases where we don't have interrupts:
* a) Broken hardware (typically those that don't have any video capture facility).
* b) Blit abort. The hardware doesn't send an interrupt when a blit is aborted.
* The timer and hardware IRQ's can and do work in parallel. If the hardware has
* irqs, it will shorten the latency somewhat.
*/
static void
via_dmablit_timer(unsigned long data)
{
drm_via_blitq_t *blitq = (drm_via_blitq_t *) data;
struct drm_device *dev = blitq->dev;
int engine = (int)
(blitq - ((drm_via_private_t *)dev->dev_private)->blit_queues);
DRM_DEBUG("Polling timer called for engine %d, jiffies %lu\n", engine,
(unsigned long) jiffies);
via_dmablit_handler(dev, engine, 0);
if (!timer_pending(&blitq->poll_timer)) {
mod_timer(&blitq->poll_timer, jiffies + 1);
/*
* Rerun handler to delete timer if engines are off, and
* to shorten abort latency. This is a little nasty.
*/
via_dmablit_handler(dev, engine, 0);
}
}
/*
* Workqueue task that frees data and mappings associated with a blit.
* Also wakes up waiting processes. Each of these tasks handles one
* blit engine only and may not be called on each interrupt.
*/
static void
via_dmablit_workqueue(struct work_struct *work)
{
drm_via_blitq_t *blitq = container_of(work, drm_via_blitq_t, wq);
struct drm_device *dev = blitq->dev;
unsigned long irqsave;
drm_via_sg_info_t *cur_sg;
int cur_released;
DRM_DEBUG("Workqueue task called for blit engine %ld\n", (unsigned long)
(blitq - ((drm_via_private_t *)dev->dev_private)->blit_queues));
spin_lock_irqsave(&blitq->blit_lock, irqsave);
while (blitq->serviced != blitq->cur) {
cur_released = blitq->serviced++;
DRM_DEBUG("Releasing blit slot %d\n", cur_released);
if (blitq->serviced >= VIA_NUM_BLIT_SLOTS)
blitq->serviced = 0;
cur_sg = blitq->blits[cur_released];
blitq->num_free++;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAKEUP(&blitq->busy_queue);
via_free_sg_info(dev->pdev, cur_sg);
kfree(cur_sg);
spin_lock_irqsave(&blitq->blit_lock, irqsave);
}
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
}
/*
* Init all blit engines. Currently we use two, but some hardware have 4.
*/
void
via_init_dmablit(struct drm_device *dev)
{
int i, j;
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq;
pci_set_master(dev->pdev);
for (i = 0; i < VIA_NUM_BLIT_ENGINES; ++i) {
blitq = dev_priv->blit_queues + i;
blitq->dev = dev;
blitq->cur_blit_handle = 0;
blitq->done_blit_handle = 0;
blitq->head = 0;
blitq->cur = 0;
blitq->serviced = 0;
blitq->num_free = VIA_NUM_BLIT_SLOTS - 1;
blitq->num_outstanding = 0;
blitq->is_active = 0;
blitq->aborting = 0;
spin_lock_init(&blitq->blit_lock);
for (j = 0; j < VIA_NUM_BLIT_SLOTS; ++j)
DRM_INIT_WAITQUEUE(blitq->blit_queue + j);
DRM_INIT_WAITQUEUE(&blitq->busy_queue);
INIT_WORK(&blitq->wq, via_dmablit_workqueue);
setup_timer(&blitq->poll_timer, via_dmablit_timer,
(unsigned long)blitq);
}
}
/*
* Build all info and do all mappings required for a blit.
*/
static int
via_build_sg_info(struct drm_device *dev, drm_via_sg_info_t *vsg, drm_via_dmablit_t *xfer)
{
int draw = xfer->to_fb;
int ret = 0;
vsg->direction = (draw) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
vsg->bounce_buffer = NULL;
vsg->state = dr_via_sg_init;
if (xfer->num_lines <= 0 || xfer->line_length <= 0) {
DRM_ERROR("Zero size bitblt.\n");
return -EINVAL;
}
/*
* Below check is a driver limitation, not a hardware one. We
* don't want to lock unused pages, and don't want to incoporate the
* extra logic of avoiding them. Make sure there are no.
* (Not a big limitation anyway.)
*/
if ((xfer->mem_stride - xfer->line_length) > 2*PAGE_SIZE) {
DRM_ERROR("Too large system memory stride. Stride: %d, "
"Length: %d\n", xfer->mem_stride, xfer->line_length);
return -EINVAL;
}
if ((xfer->mem_stride == xfer->line_length) &&
(xfer->fb_stride == xfer->line_length)) {
xfer->mem_stride *= xfer->num_lines;
xfer->line_length = xfer->mem_stride;
xfer->fb_stride = xfer->mem_stride;
xfer->num_lines = 1;
}
/*
* Don't lock an arbitrary large number of pages, since that causes a
* DOS security hole.
*/
if (xfer->num_lines > 2048 || (xfer->num_lines*xfer->mem_stride > (2048*2048*4))) {
DRM_ERROR("Too large PCI DMA bitblt.\n");
return -EINVAL;
}
/*
* we allow a negative fb stride to allow flipping of images in
* transfer.
*/
if (xfer->mem_stride < xfer->line_length ||
abs(xfer->fb_stride) < xfer->line_length) {
DRM_ERROR("Invalid frame-buffer / memory stride.\n");
return -EINVAL;
}
/*
* A hardware bug seems to be worked around if system memory addresses start on
* 16 byte boundaries. This seems a bit restrictive however. VIA is contacted
* about this. Meanwhile, impose the following restrictions:
*/
#ifdef VIA_BUGFREE
if ((((unsigned long)xfer->mem_addr & 3) != ((unsigned long)xfer->fb_addr & 3)) ||
((xfer->num_lines > 1) && ((xfer->mem_stride & 3) != (xfer->fb_stride & 3)))) {
DRM_ERROR("Invalid DRM bitblt alignment.\n");
return -EINVAL;
}
#else
if ((((unsigned long)xfer->mem_addr & 15) ||
((unsigned long)xfer->fb_addr & 3)) ||
((xfer->num_lines > 1) &&
((xfer->mem_stride & 15) || (xfer->fb_stride & 3)))) {
DRM_ERROR("Invalid DRM bitblt alignment.\n");
return -EINVAL;
}
#endif
if (0 != (ret = via_lock_all_dma_pages(vsg, xfer))) {
DRM_ERROR("Could not lock DMA pages.\n");
via_free_sg_info(dev->pdev, vsg);
return ret;
}
via_map_blit_for_device(dev->pdev, xfer, vsg, 0);
if (0 != (ret = via_alloc_desc_pages(vsg))) {
DRM_ERROR("Could not allocate DMA descriptor pages.\n");
via_free_sg_info(dev->pdev, vsg);
return ret;
}
via_map_blit_for_device(dev->pdev, xfer, vsg, 1);
return 0;
}
/*
* Reserve one free slot in the blit queue. Will wait for one second for one
* to become available. Otherwise -EBUSY is returned.
*/
static int
via_dmablit_grab_slot(drm_via_blitq_t *blitq, int engine)
{
int ret = 0;
unsigned long irqsave;
DRM_DEBUG("Num free is %d\n", blitq->num_free);
spin_lock_irqsave(&blitq->blit_lock, irqsave);
while (blitq->num_free == 0) {
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAIT_ON(ret, blitq->busy_queue, DRM_HZ, blitq->num_free > 0);
if (ret)
return (-EINTR == ret) ? -EAGAIN : ret;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
}
blitq->num_free--;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
return 0;
}
/*
* Hand back a free slot if we changed our mind.
*/
static void
via_dmablit_release_slot(drm_via_blitq_t *blitq)
{
unsigned long irqsave;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
blitq->num_free++;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAKEUP(&blitq->busy_queue);
}
/*
* Grab a free slot. Build blit info and queue a blit.
*/
static int
via_dmablit(struct drm_device *dev, drm_via_dmablit_t *xfer)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_sg_info_t *vsg;
drm_via_blitq_t *blitq;
int ret;
int engine;
unsigned long irqsave;
if (dev_priv == NULL) {
DRM_ERROR("Called without initialization.\n");
return -EINVAL;
}
engine = (xfer->to_fb) ? 0 : 1;
blitq = dev_priv->blit_queues + engine;
if (0 != (ret = via_dmablit_grab_slot(blitq, engine)))
return ret;
if (NULL == (vsg = kmalloc(sizeof(*vsg), GFP_KERNEL))) {
via_dmablit_release_slot(blitq);
return -ENOMEM;
}
if (0 != (ret = via_build_sg_info(dev, vsg, xfer))) {
via_dmablit_release_slot(blitq);
kfree(vsg);
return ret;
}
spin_lock_irqsave(&blitq->blit_lock, irqsave);
blitq->blits[blitq->head++] = vsg;
if (blitq->head >= VIA_NUM_BLIT_SLOTS)
blitq->head = 0;
blitq->num_outstanding++;
xfer->sync.sync_handle = ++blitq->cur_blit_handle;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
xfer->sync.engine = engine;
via_dmablit_handler(dev, engine, 0);
return 0;
}
/*
* Sync on a previously submitted blit. Note that the X server use signals extensively, and
* that there is a very big probability that this IOCTL will be interrupted by a signal. In that
* case it returns with -EAGAIN for the signal to be delivered.
* The caller should then reissue the IOCTL. This is similar to what is being done for drmGetLock().
*/
int
via_dma_blit_sync(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_via_blitsync_t *sync = data;
int err;
if (sync->engine >= VIA_NUM_BLIT_ENGINES)
return -EINVAL;
err = via_dmablit_sync(dev, sync->sync_handle, sync->engine);
if (-EINTR == err)
err = -EAGAIN;
return err;
}
/*
* Queue a blit and hand back a handle to be used for sync. This IOCTL may be interrupted by a signal
* while waiting for a free slot in the blit queue. In that case it returns with -EAGAIN and should
* be reissued. See the above IOCTL code.
*/
int
via_dma_blit(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_via_dmablit_t *xfer = data;
int err;
err = via_dmablit(dev, xfer);
return err;
}
| gpl-2.0 |
FireHound-Devices/android_kernel_cyanogen_msm8916 | arch/powerpc/platforms/powermac/backlight.c | 9348 | 5538 | /*
* Miscellaneous procedures for dealing with the PowerMac hardware.
* Contains support for the backlight.
*
* Copyright (C) 2000 Benjamin Herrenschmidt
* Copyright (C) 2006 Michael Hanselmann <linux-kernel@hansmi.ch>
*
*/
#include <linux/kernel.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <linux/adb.h>
#include <linux/pmu.h>
#include <linux/atomic.h>
#include <linux/export.h>
#include <asm/prom.h>
#include <asm/backlight.h>
#define OLD_BACKLIGHT_MAX 15
static void pmac_backlight_key_worker(struct work_struct *work);
static void pmac_backlight_set_legacy_worker(struct work_struct *work);
static DECLARE_WORK(pmac_backlight_key_work, pmac_backlight_key_worker);
static DECLARE_WORK(pmac_backlight_set_legacy_work, pmac_backlight_set_legacy_worker);
/* Although these variables are used in interrupt context, it makes no sense to
* protect them. No user is able to produce enough key events per second and
* notice the errors that might happen.
*/
static int pmac_backlight_key_queued;
static int pmac_backlight_set_legacy_queued;
/* The via-pmu code allows the backlight to be grabbed, in which case the
* in-kernel control of the brightness needs to be disabled. This should
* only be used by really old PowerBooks.
*/
static atomic_t kernel_backlight_disabled = ATOMIC_INIT(0);
/* Protect the pmac_backlight variable below.
You should hold this lock when using the pmac_backlight pointer to
prevent its potential removal. */
DEFINE_MUTEX(pmac_backlight_mutex);
/* Main backlight storage
*
* Backlight drivers in this variable are required to have the "ops"
* attribute set and to have an update_status function.
*
* We can only store one backlight here, but since Apple laptops have only one
* internal display, it doesn't matter. Other backlight drivers can be used
* independently.
*
*/
struct backlight_device *pmac_backlight;
int pmac_has_backlight_type(const char *type)
{
struct device_node* bk_node = of_find_node_by_name(NULL, "backlight");
if (bk_node) {
const char *prop = of_get_property(bk_node,
"backlight-control", NULL);
if (prop && strncmp(prop, type, strlen(type)) == 0) {
of_node_put(bk_node);
return 1;
}
of_node_put(bk_node);
}
return 0;
}
int pmac_backlight_curve_lookup(struct fb_info *info, int value)
{
int level = (FB_BACKLIGHT_LEVELS - 1);
if (info && info->bl_dev) {
int i, max = 0;
/* Look for biggest value */
for (i = 0; i < FB_BACKLIGHT_LEVELS; i++)
max = max((int)info->bl_curve[i], max);
/* Look for nearest value */
for (i = 0; i < FB_BACKLIGHT_LEVELS; i++) {
int diff = abs(info->bl_curve[i] - value);
if (diff < max) {
max = diff;
level = i;
}
}
}
return level;
}
static void pmac_backlight_key_worker(struct work_struct *work)
{
if (atomic_read(&kernel_backlight_disabled))
return;
mutex_lock(&pmac_backlight_mutex);
if (pmac_backlight) {
struct backlight_properties *props;
int brightness;
props = &pmac_backlight->props;
brightness = props->brightness +
((pmac_backlight_key_queued?-1:1) *
(props->max_brightness / 15));
if (brightness < 0)
brightness = 0;
else if (brightness > props->max_brightness)
brightness = props->max_brightness;
props->brightness = brightness;
backlight_update_status(pmac_backlight);
}
mutex_unlock(&pmac_backlight_mutex);
}
/* This function is called in interrupt context */
void pmac_backlight_key(int direction)
{
if (atomic_read(&kernel_backlight_disabled))
return;
/* we can receive multiple interrupts here, but the scheduled work
* will run only once, with the last value
*/
pmac_backlight_key_queued = direction;
schedule_work(&pmac_backlight_key_work);
}
static int __pmac_backlight_set_legacy_brightness(int brightness)
{
int error = -ENXIO;
mutex_lock(&pmac_backlight_mutex);
if (pmac_backlight) {
struct backlight_properties *props;
props = &pmac_backlight->props;
props->brightness = brightness *
(props->max_brightness + 1) /
(OLD_BACKLIGHT_MAX + 1);
if (props->brightness > props->max_brightness)
props->brightness = props->max_brightness;
else if (props->brightness < 0)
props->brightness = 0;
backlight_update_status(pmac_backlight);
error = 0;
}
mutex_unlock(&pmac_backlight_mutex);
return error;
}
static void pmac_backlight_set_legacy_worker(struct work_struct *work)
{
if (atomic_read(&kernel_backlight_disabled))
return;
__pmac_backlight_set_legacy_brightness(pmac_backlight_set_legacy_queued);
}
/* This function is called in interrupt context */
void pmac_backlight_set_legacy_brightness_pmu(int brightness) {
if (atomic_read(&kernel_backlight_disabled))
return;
pmac_backlight_set_legacy_queued = brightness;
schedule_work(&pmac_backlight_set_legacy_work);
}
int pmac_backlight_set_legacy_brightness(int brightness)
{
return __pmac_backlight_set_legacy_brightness(brightness);
}
int pmac_backlight_get_legacy_brightness()
{
int result = -ENXIO;
mutex_lock(&pmac_backlight_mutex);
if (pmac_backlight) {
struct backlight_properties *props;
props = &pmac_backlight->props;
result = props->brightness *
(OLD_BACKLIGHT_MAX + 1) /
(props->max_brightness + 1);
}
mutex_unlock(&pmac_backlight_mutex);
return result;
}
void pmac_backlight_disable()
{
atomic_inc(&kernel_backlight_disabled);
}
void pmac_backlight_enable()
{
atomic_dec(&kernel_backlight_disabled);
}
EXPORT_SYMBOL_GPL(pmac_backlight);
EXPORT_SYMBOL_GPL(pmac_backlight_mutex);
EXPORT_SYMBOL_GPL(pmac_has_backlight_type);
| gpl-2.0 |
Hogman500/ouya_1_1-kernel | drivers/pci/hotplug/ibmphp_res.c | 11652 | 59622 | /*
* IBM Hot Plug Controller Driver
*
* Written By: Irene Zubarev, IBM Corporation
*
* Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2001,2002 IBM Corp.
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. 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.
*
* Send feedback to <gregkh@us.ibm.com>
*
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/list.h>
#include <linux/init.h>
#include "ibmphp.h"
static int flags = 0; /* for testing */
static void update_resources (struct bus_node *bus_cur, int type, int rangeno);
static int once_over (void);
static int remove_ranges (struct bus_node *, struct bus_node *);
static int update_bridge_ranges (struct bus_node **);
static int add_bus_range (int type, struct range_node *, struct bus_node *);
static void fix_resources (struct bus_node *);
static struct bus_node *find_bus_wprev (u8, struct bus_node **, u8);
static LIST_HEAD(gbuses);
static struct bus_node * __init alloc_error_bus (struct ebda_pci_rsrc * curr, u8 busno, int flag)
{
struct bus_node * newbus;
if (!(curr) && !(flag)) {
err ("NULL pointer passed\n");
return NULL;
}
newbus = kzalloc(sizeof(struct bus_node), GFP_KERNEL);
if (!newbus) {
err ("out of system memory\n");
return NULL;
}
if (flag)
newbus->busno = busno;
else
newbus->busno = curr->bus_num;
list_add_tail (&newbus->bus_list, &gbuses);
return newbus;
}
static struct resource_node * __init alloc_resources (struct ebda_pci_rsrc * curr)
{
struct resource_node *rs;
if (!curr) {
err ("NULL passed to allocate\n");
return NULL;
}
rs = kzalloc(sizeof(struct resource_node), GFP_KERNEL);
if (!rs) {
err ("out of system memory\n");
return NULL;
}
rs->busno = curr->bus_num;
rs->devfunc = curr->dev_fun;
rs->start = curr->start_addr;
rs->end = curr->end_addr;
rs->len = curr->end_addr - curr->start_addr + 1;
return rs;
}
static int __init alloc_bus_range (struct bus_node **new_bus, struct range_node **new_range, struct ebda_pci_rsrc *curr, int flag, u8 first_bus)
{
struct bus_node * newbus;
struct range_node *newrange;
u8 num_ranges = 0;
if (first_bus) {
newbus = kzalloc(sizeof(struct bus_node), GFP_KERNEL);
if (!newbus) {
err ("out of system memory.\n");
return -ENOMEM;
}
newbus->busno = curr->bus_num;
} else {
newbus = *new_bus;
switch (flag) {
case MEM:
num_ranges = newbus->noMemRanges;
break;
case PFMEM:
num_ranges = newbus->noPFMemRanges;
break;
case IO:
num_ranges = newbus->noIORanges;
break;
}
}
newrange = kzalloc(sizeof(struct range_node), GFP_KERNEL);
if (!newrange) {
if (first_bus)
kfree (newbus);
err ("out of system memory\n");
return -ENOMEM;
}
newrange->start = curr->start_addr;
newrange->end = curr->end_addr;
if (first_bus || (!num_ranges))
newrange->rangeno = 1;
else {
/* need to insert our range */
add_bus_range (flag, newrange, newbus);
debug ("%d resource Primary Bus inserted on bus %x [%x - %x]\n", flag, newbus->busno, newrange->start, newrange->end);
}
switch (flag) {
case MEM:
newbus->rangeMem = newrange;
if (first_bus)
newbus->noMemRanges = 1;
else {
debug ("First Memory Primary on bus %x, [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
++newbus->noMemRanges;
fix_resources (newbus);
}
break;
case IO:
newbus->rangeIO = newrange;
if (first_bus)
newbus->noIORanges = 1;
else {
debug ("First IO Primary on bus %x, [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
++newbus->noIORanges;
fix_resources (newbus);
}
break;
case PFMEM:
newbus->rangePFMem = newrange;
if (first_bus)
newbus->noPFMemRanges = 1;
else {
debug ("1st PFMemory Primary on Bus %x [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
++newbus->noPFMemRanges;
fix_resources (newbus);
}
break;
}
*new_bus = newbus;
*new_range = newrange;
return 0;
}
/* Notes:
* 1. The ranges are ordered. The buses are not ordered. (First come)
*
* 2. If cannot allocate out of PFMem range, allocate from Mem ranges. PFmemFromMem
* are not sorted. (no need since use mem node). To not change the entire code, we
* also add mem node whenever this case happens so as not to change
* ibmphp_check_mem_resource etc (and since it really is taking Mem resource)
*/
/*****************************************************************************
* This is the Resource Management initialization function. It will go through
* the Resource list taken from EBDA and fill in this module's data structures
*
* THIS IS NOT TAKING INTO CONSIDERATION IO RESTRICTIONS OF PRIMARY BUSES,
* SINCE WE'RE GOING TO ASSUME FOR NOW WE DON'T HAVE THOSE ON OUR BUSES FOR NOW
*
* Input: ptr to the head of the resource list from EBDA
* Output: 0, -1 or error codes
***************************************************************************/
int __init ibmphp_rsrc_init (void)
{
struct ebda_pci_rsrc *curr;
struct range_node *newrange = NULL;
struct bus_node *newbus = NULL;
struct bus_node *bus_cur;
struct bus_node *bus_prev;
struct list_head *tmp;
struct resource_node *new_io = NULL;
struct resource_node *new_mem = NULL;
struct resource_node *new_pfmem = NULL;
int rc;
struct list_head *tmp_ebda;
list_for_each (tmp_ebda, &ibmphp_ebda_pci_rsrc_head) {
curr = list_entry (tmp_ebda, struct ebda_pci_rsrc, ebda_pci_rsrc_list);
if (!(curr->rsrc_type & PCIDEVMASK)) {
/* EBDA still lists non PCI devices, so ignore... */
debug ("this is not a PCI DEVICE in rsrc_init, please take care\n");
// continue;
}
/* this is a primary bus resource */
if (curr->rsrc_type & PRIMARYBUSMASK) {
/* memory */
if ((curr->rsrc_type & RESTYPE) == MMASK) {
/* no bus structure exists in place yet */
if (list_empty (&gbuses)) {
if ((rc = alloc_bus_range (&newbus, &newrange, curr, MEM, 1)))
return rc;
list_add_tail (&newbus->bus_list, &gbuses);
debug ("gbuses = NULL, Memory Primary Bus %x [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
} else {
bus_cur = find_bus_wprev (curr->bus_num, &bus_prev, 1);
/* found our bus */
if (bus_cur) {
rc = alloc_bus_range (&bus_cur, &newrange, curr, MEM, 0);
if (rc)
return rc;
} else {
/* went through all the buses and didn't find ours, need to create a new bus node */
if ((rc = alloc_bus_range (&newbus, &newrange, curr, MEM, 1)))
return rc;
list_add_tail (&newbus->bus_list, &gbuses);
debug ("New Bus, Memory Primary Bus %x [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
}
}
} else if ((curr->rsrc_type & RESTYPE) == PFMASK) {
/* prefetchable memory */
if (list_empty (&gbuses)) {
/* no bus structure exists in place yet */
if ((rc = alloc_bus_range (&newbus, &newrange, curr, PFMEM, 1)))
return rc;
list_add_tail (&newbus->bus_list, &gbuses);
debug ("gbuses = NULL, PFMemory Primary Bus %x [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
} else {
bus_cur = find_bus_wprev (curr->bus_num, &bus_prev, 1);
if (bus_cur) {
/* found our bus */
rc = alloc_bus_range (&bus_cur, &newrange, curr, PFMEM, 0);
if (rc)
return rc;
} else {
/* went through all the buses and didn't find ours, need to create a new bus node */
if ((rc = alloc_bus_range (&newbus, &newrange, curr, PFMEM, 1)))
return rc;
list_add_tail (&newbus->bus_list, &gbuses);
debug ("1st Bus, PFMemory Primary Bus %x [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
}
}
} else if ((curr->rsrc_type & RESTYPE) == IOMASK) {
/* IO */
if (list_empty (&gbuses)) {
/* no bus structure exists in place yet */
if ((rc = alloc_bus_range (&newbus, &newrange, curr, IO, 1)))
return rc;
list_add_tail (&newbus->bus_list, &gbuses);
debug ("gbuses = NULL, IO Primary Bus %x [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
} else {
bus_cur = find_bus_wprev (curr->bus_num, &bus_prev, 1);
if (bus_cur) {
rc = alloc_bus_range (&bus_cur, &newrange, curr, IO, 0);
if (rc)
return rc;
} else {
/* went through all the buses and didn't find ours, need to create a new bus node */
if ((rc = alloc_bus_range (&newbus, &newrange, curr, IO, 1)))
return rc;
list_add_tail (&newbus->bus_list, &gbuses);
debug ("1st Bus, IO Primary Bus %x [%x - %x]\n", newbus->busno, newrange->start, newrange->end);
}
}
} else {
; /* type is reserved WHAT TO DO IN THIS CASE???
NOTHING TO DO??? */
}
} else {
/* regular pci device resource */
if ((curr->rsrc_type & RESTYPE) == MMASK) {
/* Memory resource */
new_mem = alloc_resources (curr);
if (!new_mem)
return -ENOMEM;
new_mem->type = MEM;
/*
* if it didn't find the bus, means PCI dev
* came b4 the Primary Bus info, so need to
* create a bus rangeno becomes a problem...
* assign a -1 and then update once the range
* actually appears...
*/
if (ibmphp_add_resource (new_mem) < 0) {
newbus = alloc_error_bus (curr, 0, 0);
if (!newbus)
return -ENOMEM;
newbus->firstMem = new_mem;
++newbus->needMemUpdate;
new_mem->rangeno = -1;
}
debug ("Memory resource for device %x, bus %x, [%x - %x]\n", new_mem->devfunc, new_mem->busno, new_mem->start, new_mem->end);
} else if ((curr->rsrc_type & RESTYPE) == PFMASK) {
/* PFMemory resource */
new_pfmem = alloc_resources (curr);
if (!new_pfmem)
return -ENOMEM;
new_pfmem->type = PFMEM;
new_pfmem->fromMem = 0;
if (ibmphp_add_resource (new_pfmem) < 0) {
newbus = alloc_error_bus (curr, 0, 0);
if (!newbus)
return -ENOMEM;
newbus->firstPFMem = new_pfmem;
++newbus->needPFMemUpdate;
new_pfmem->rangeno = -1;
}
debug ("PFMemory resource for device %x, bus %x, [%x - %x]\n", new_pfmem->devfunc, new_pfmem->busno, new_pfmem->start, new_pfmem->end);
} else if ((curr->rsrc_type & RESTYPE) == IOMASK) {
/* IO resource */
new_io = alloc_resources (curr);
if (!new_io)
return -ENOMEM;
new_io->type = IO;
/*
* if it didn't find the bus, means PCI dev
* came b4 the Primary Bus info, so need to
* create a bus rangeno becomes a problem...
* Can assign a -1 and then update once the
* range actually appears...
*/
if (ibmphp_add_resource (new_io) < 0) {
newbus = alloc_error_bus (curr, 0, 0);
if (!newbus)
return -ENOMEM;
newbus->firstIO = new_io;
++newbus->needIOUpdate;
new_io->rangeno = -1;
}
debug ("IO resource for device %x, bus %x, [%x - %x]\n", new_io->devfunc, new_io->busno, new_io->start, new_io->end);
}
}
}
list_for_each (tmp, &gbuses) {
bus_cur = list_entry (tmp, struct bus_node, bus_list);
/* This is to get info about PPB resources, since EBDA doesn't put this info into the primary bus info */
rc = update_bridge_ranges (&bus_cur);
if (rc)
return rc;
}
rc = once_over (); /* This is to align ranges (so no -1) */
if (rc)
return rc;
return 0;
}
/********************************************************************************
* This function adds a range into a sorted list of ranges per bus for a particular
* range type, it then calls another routine to update the range numbers on the
* pci devices' resources for the appropriate resource
*
* Input: type of the resource, range to add, current bus
* Output: 0 or -1, bus and range ptrs
********************************************************************************/
static int add_bus_range (int type, struct range_node *range, struct bus_node *bus_cur)
{
struct range_node *range_cur = NULL;
struct range_node *range_prev;
int count = 0, i_init;
int noRanges = 0;
switch (type) {
case MEM:
range_cur = bus_cur->rangeMem;
noRanges = bus_cur->noMemRanges;
break;
case PFMEM:
range_cur = bus_cur->rangePFMem;
noRanges = bus_cur->noPFMemRanges;
break;
case IO:
range_cur = bus_cur->rangeIO;
noRanges = bus_cur->noIORanges;
break;
}
range_prev = NULL;
while (range_cur) {
if (range->start < range_cur->start)
break;
range_prev = range_cur;
range_cur = range_cur->next;
count = count + 1;
}
if (!count) {
/* our range will go at the beginning of the list */
switch (type) {
case MEM:
bus_cur->rangeMem = range;
break;
case PFMEM:
bus_cur->rangePFMem = range;
break;
case IO:
bus_cur->rangeIO = range;
break;
}
range->next = range_cur;
range->rangeno = 1;
i_init = 0;
} else if (!range_cur) {
/* our range will go at the end of the list */
range->next = NULL;
range_prev->next = range;
range->rangeno = range_prev->rangeno + 1;
return 0;
} else {
/* the range is in the middle */
range_prev->next = range;
range->next = range_cur;
range->rangeno = range_cur->rangeno;
i_init = range_prev->rangeno;
}
for (count = i_init; count < noRanges; ++count) {
++range_cur->rangeno;
range_cur = range_cur->next;
}
update_resources (bus_cur, type, i_init + 1);
return 0;
}
/*******************************************************************************
* This routine goes through the list of resources of type 'type' and updates
* the range numbers that they correspond to. It was called from add_bus_range fnc
*
* Input: bus, type of the resource, the rangeno starting from which to update
******************************************************************************/
static void update_resources (struct bus_node *bus_cur, int type, int rangeno)
{
struct resource_node *res = NULL;
u8 eol = 0; /* end of list indicator */
switch (type) {
case MEM:
if (bus_cur->firstMem)
res = bus_cur->firstMem;
break;
case PFMEM:
if (bus_cur->firstPFMem)
res = bus_cur->firstPFMem;
break;
case IO:
if (bus_cur->firstIO)
res = bus_cur->firstIO;
break;
}
if (res) {
while (res) {
if (res->rangeno == rangeno)
break;
if (res->next)
res = res->next;
else if (res->nextRange)
res = res->nextRange;
else {
eol = 1;
break;
}
}
if (!eol) {
/* found the range */
while (res) {
++res->rangeno;
res = res->next;
}
}
}
}
static void fix_me (struct resource_node *res, struct bus_node *bus_cur, struct range_node *range)
{
char * str = "";
switch (res->type) {
case IO:
str = "io";
break;
case MEM:
str = "mem";
break;
case PFMEM:
str = "pfmem";
break;
}
while (res) {
if (res->rangeno == -1) {
while (range) {
if ((res->start >= range->start) && (res->end <= range->end)) {
res->rangeno = range->rangeno;
debug ("%s->rangeno in fix_resources is %d\n", str, res->rangeno);
switch (res->type) {
case IO:
--bus_cur->needIOUpdate;
break;
case MEM:
--bus_cur->needMemUpdate;
break;
case PFMEM:
--bus_cur->needPFMemUpdate;
break;
}
break;
}
range = range->next;
}
}
if (res->next)
res = res->next;
else
res = res->nextRange;
}
}
/*****************************************************************************
* This routine reassigns the range numbers to the resources that had a -1
* This case can happen only if upon initialization, resources taken by pci dev
* appear in EBDA before the resources allocated for that bus, since we don't
* know the range, we assign -1, and this routine is called after a new range
* is assigned to see the resources with unknown range belong to the added range
*
* Input: current bus
* Output: none, list of resources for that bus are fixed if can be
*******************************************************************************/
static void fix_resources (struct bus_node *bus_cur)
{
struct range_node *range;
struct resource_node *res;
debug ("%s - bus_cur->busno = %d\n", __func__, bus_cur->busno);
if (bus_cur->needIOUpdate) {
res = bus_cur->firstIO;
range = bus_cur->rangeIO;
fix_me (res, bus_cur, range);
}
if (bus_cur->needMemUpdate) {
res = bus_cur->firstMem;
range = bus_cur->rangeMem;
fix_me (res, bus_cur, range);
}
if (bus_cur->needPFMemUpdate) {
res = bus_cur->firstPFMem;
range = bus_cur->rangePFMem;
fix_me (res, bus_cur, range);
}
}
/*******************************************************************************
* This routine adds a resource to the list of resources to the appropriate bus
* based on their resource type and sorted by their starting addresses. It assigns
* the ptrs to next and nextRange if needed.
*
* Input: resource ptr
* Output: ptrs assigned (to the node)
* 0 or -1
*******************************************************************************/
int ibmphp_add_resource (struct resource_node *res)
{
struct resource_node *res_cur;
struct resource_node *res_prev;
struct bus_node *bus_cur;
struct range_node *range_cur = NULL;
struct resource_node *res_start = NULL;
debug ("%s - enter\n", __func__);
if (!res) {
err ("NULL passed to add\n");
return -ENODEV;
}
bus_cur = find_bus_wprev (res->busno, NULL, 0);
if (!bus_cur) {
/* didn't find a bus, smth's wrong!!! */
debug ("no bus in the system, either pci_dev's wrong or allocation failed\n");
return -ENODEV;
}
/* Normal case */
switch (res->type) {
case IO:
range_cur = bus_cur->rangeIO;
res_start = bus_cur->firstIO;
break;
case MEM:
range_cur = bus_cur->rangeMem;
res_start = bus_cur->firstMem;
break;
case PFMEM:
range_cur = bus_cur->rangePFMem;
res_start = bus_cur->firstPFMem;
break;
default:
err ("cannot read the type of the resource to add... problem\n");
return -EINVAL;
}
while (range_cur) {
if ((res->start >= range_cur->start) && (res->end <= range_cur->end)) {
res->rangeno = range_cur->rangeno;
break;
}
range_cur = range_cur->next;
}
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* this is again the case of rangeno = -1
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
if (!range_cur) {
switch (res->type) {
case IO:
++bus_cur->needIOUpdate;
break;
case MEM:
++bus_cur->needMemUpdate;
break;
case PFMEM:
++bus_cur->needPFMemUpdate;
break;
}
res->rangeno = -1;
}
debug ("The range is %d\n", res->rangeno);
if (!res_start) {
/* no first{IO,Mem,Pfmem} on the bus, 1st IO/Mem/Pfmem resource ever */
switch (res->type) {
case IO:
bus_cur->firstIO = res;
break;
case MEM:
bus_cur->firstMem = res;
break;
case PFMEM:
bus_cur->firstPFMem = res;
break;
}
res->next = NULL;
res->nextRange = NULL;
} else {
res_cur = res_start;
res_prev = NULL;
debug ("res_cur->rangeno is %d\n", res_cur->rangeno);
while (res_cur) {
if (res_cur->rangeno >= res->rangeno)
break;
res_prev = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
}
if (!res_cur) {
/* at the end of the resource list */
debug ("i should be here, [%x - %x]\n", res->start, res->end);
res_prev->nextRange = res;
res->next = NULL;
res->nextRange = NULL;
} else if (res_cur->rangeno == res->rangeno) {
/* in the same range */
while (res_cur) {
if (res->start < res_cur->start)
break;
res_prev = res_cur;
res_cur = res_cur->next;
}
if (!res_cur) {
/* the last resource in this range */
res_prev->next = res;
res->next = NULL;
res->nextRange = res_prev->nextRange;
res_prev->nextRange = NULL;
} else if (res->start < res_cur->start) {
/* at the beginning or middle of the range */
if (!res_prev) {
switch (res->type) {
case IO:
bus_cur->firstIO = res;
break;
case MEM:
bus_cur->firstMem = res;
break;
case PFMEM:
bus_cur->firstPFMem = res;
break;
}
} else if (res_prev->rangeno == res_cur->rangeno)
res_prev->next = res;
else
res_prev->nextRange = res;
res->next = res_cur;
res->nextRange = NULL;
}
} else {
/* this is the case where it is 1st occurrence of the range */
if (!res_prev) {
/* at the beginning of the resource list */
res->next = NULL;
switch (res->type) {
case IO:
res->nextRange = bus_cur->firstIO;
bus_cur->firstIO = res;
break;
case MEM:
res->nextRange = bus_cur->firstMem;
bus_cur->firstMem = res;
break;
case PFMEM:
res->nextRange = bus_cur->firstPFMem;
bus_cur->firstPFMem = res;
break;
}
} else if (res_cur->rangeno > res->rangeno) {
/* in the middle of the resource list */
res_prev->nextRange = res;
res->next = NULL;
res->nextRange = res_cur;
}
}
}
debug ("%s - exit\n", __func__);
return 0;
}
/****************************************************************************
* This routine will remove the resource from the list of resources
*
* Input: io, mem, and/or pfmem resource to be deleted
* Ouput: modified resource list
* 0 or error code
****************************************************************************/
int ibmphp_remove_resource (struct resource_node *res)
{
struct bus_node *bus_cur;
struct resource_node *res_cur = NULL;
struct resource_node *res_prev;
struct resource_node *mem_cur;
char * type = "";
if (!res) {
err ("resource to remove is NULL\n");
return -ENODEV;
}
bus_cur = find_bus_wprev (res->busno, NULL, 0);
if (!bus_cur) {
err ("cannot find corresponding bus of the io resource to remove "
"bailing out...\n");
return -ENODEV;
}
switch (res->type) {
case IO:
res_cur = bus_cur->firstIO;
type = "io";
break;
case MEM:
res_cur = bus_cur->firstMem;
type = "mem";
break;
case PFMEM:
res_cur = bus_cur->firstPFMem;
type = "pfmem";
break;
default:
err ("unknown type for resource to remove\n");
return -EINVAL;
}
res_prev = NULL;
while (res_cur) {
if ((res_cur->start == res->start) && (res_cur->end == res->end))
break;
res_prev = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
}
if (!res_cur) {
if (res->type == PFMEM) {
/*
* case where pfmem might be in the PFMemFromMem list
* so will also need to remove the corresponding mem
* entry
*/
res_cur = bus_cur->firstPFMemFromMem;
res_prev = NULL;
while (res_cur) {
if ((res_cur->start == res->start) && (res_cur->end == res->end)) {
mem_cur = bus_cur->firstMem;
while (mem_cur) {
if ((mem_cur->start == res_cur->start)
&& (mem_cur->end == res_cur->end))
break;
if (mem_cur->next)
mem_cur = mem_cur->next;
else
mem_cur = mem_cur->nextRange;
}
if (!mem_cur) {
err ("cannot find corresponding mem node for pfmem...\n");
return -EINVAL;
}
ibmphp_remove_resource (mem_cur);
if (!res_prev)
bus_cur->firstPFMemFromMem = res_cur->next;
else
res_prev->next = res_cur->next;
kfree (res_cur);
return 0;
}
res_prev = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
}
if (!res_cur) {
err ("cannot find pfmem to delete...\n");
return -EINVAL;
}
} else {
err ("the %s resource is not in the list to be deleted...\n", type);
return -EINVAL;
}
}
if (!res_prev) {
/* first device to be deleted */
if (res_cur->next) {
switch (res->type) {
case IO:
bus_cur->firstIO = res_cur->next;
break;
case MEM:
bus_cur->firstMem = res_cur->next;
break;
case PFMEM:
bus_cur->firstPFMem = res_cur->next;
break;
}
} else if (res_cur->nextRange) {
switch (res->type) {
case IO:
bus_cur->firstIO = res_cur->nextRange;
break;
case MEM:
bus_cur->firstMem = res_cur->nextRange;
break;
case PFMEM:
bus_cur->firstPFMem = res_cur->nextRange;
break;
}
} else {
switch (res->type) {
case IO:
bus_cur->firstIO = NULL;
break;
case MEM:
bus_cur->firstMem = NULL;
break;
case PFMEM:
bus_cur->firstPFMem = NULL;
break;
}
}
kfree (res_cur);
return 0;
} else {
if (res_cur->next) {
if (res_prev->rangeno == res_cur->rangeno)
res_prev->next = res_cur->next;
else
res_prev->nextRange = res_cur->next;
} else if (res_cur->nextRange) {
res_prev->next = NULL;
res_prev->nextRange = res_cur->nextRange;
} else {
res_prev->next = NULL;
res_prev->nextRange = NULL;
}
kfree (res_cur);
return 0;
}
return 0;
}
static struct range_node * find_range (struct bus_node *bus_cur, struct resource_node * res)
{
struct range_node * range = NULL;
switch (res->type) {
case IO:
range = bus_cur->rangeIO;
break;
case MEM:
range = bus_cur->rangeMem;
break;
case PFMEM:
range = bus_cur->rangePFMem;
break;
default:
err ("cannot read resource type in find_range\n");
}
while (range) {
if (res->rangeno == range->rangeno)
break;
range = range->next;
}
return range;
}
/*****************************************************************************
* This routine will check to make sure the io/mem/pfmem->len that the device asked for
* can fit w/i our list of available IO/MEM/PFMEM resources. If cannot, returns -EINVAL,
* otherwise, returns 0
*
* Input: resource
* Ouput: the correct start and end address are inputted into the resource node,
* 0 or -EINVAL
*****************************************************************************/
int ibmphp_check_resource (struct resource_node *res, u8 bridge)
{
struct bus_node *bus_cur;
struct range_node *range = NULL;
struct resource_node *res_prev;
struct resource_node *res_cur = NULL;
u32 len_cur = 0, start_cur = 0, len_tmp = 0;
int noranges = 0;
u32 tmp_start; /* this is to make sure start address is divisible by the length needed */
u32 tmp_divide;
u8 flag = 0;
if (!res)
return -EINVAL;
if (bridge) {
/* The rules for bridges are different, 4K divisible for IO, 1M for (pf)mem*/
if (res->type == IO)
tmp_divide = IOBRIDGE;
else
tmp_divide = MEMBRIDGE;
} else
tmp_divide = res->len;
bus_cur = find_bus_wprev (res->busno, NULL, 0);
if (!bus_cur) {
/* didn't find a bus, smth's wrong!!! */
debug ("no bus in the system, either pci_dev's wrong or allocation failed\n");
return -EINVAL;
}
debug ("%s - enter\n", __func__);
debug ("bus_cur->busno is %d\n", bus_cur->busno);
/* This is a quick fix to not mess up with the code very much. i.e.,
* 2000-2fff, len = 1000, but when we compare, we need it to be fff */
res->len -= 1;
switch (res->type) {
case IO:
res_cur = bus_cur->firstIO;
noranges = bus_cur->noIORanges;
break;
case MEM:
res_cur = bus_cur->firstMem;
noranges = bus_cur->noMemRanges;
break;
case PFMEM:
res_cur = bus_cur->firstPFMem;
noranges = bus_cur->noPFMemRanges;
break;
default:
err ("wrong type of resource to check\n");
return -EINVAL;
}
res_prev = NULL;
while (res_cur) {
range = find_range (bus_cur, res_cur);
debug ("%s - rangeno = %d\n", __func__, res_cur->rangeno);
if (!range) {
err ("no range for the device exists... bailing out...\n");
return -EINVAL;
}
/* found our range */
if (!res_prev) {
/* first time in the loop */
if ((res_cur->start != range->start) && ((len_tmp = res_cur->start - 1 - range->start) >= res->len)) {
debug ("len_tmp = %x\n", len_tmp);
if ((len_tmp < len_cur) || (len_cur == 0)) {
if ((range->start % tmp_divide) == 0) {
/* just perfect, starting address is divisible by length */
flag = 1;
len_cur = len_tmp;
start_cur = range->start;
} else {
/* Needs adjusting */
tmp_start = range->start;
flag = 0;
while ((len_tmp = res_cur->start - 1 - tmp_start) >= res->len) {
if ((tmp_start % tmp_divide) == 0) {
flag = 1;
len_cur = len_tmp;
start_cur = tmp_start;
break;
}
tmp_start += tmp_divide - tmp_start % tmp_divide;
if (tmp_start >= res_cur->start - 1)
break;
}
}
if (flag && len_cur == res->len) {
debug ("but we are not here, right?\n");
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
}
}
}
if (!res_cur->next) {
/* last device on the range */
if ((range->end != res_cur->end) && ((len_tmp = range->end - (res_cur->end + 1)) >= res->len)) {
debug ("len_tmp = %x\n", len_tmp);
if ((len_tmp < len_cur) || (len_cur == 0)) {
if (((res_cur->end + 1) % tmp_divide) == 0) {
/* just perfect, starting address is divisible by length */
flag = 1;
len_cur = len_tmp;
start_cur = res_cur->end + 1;
} else {
/* Needs adjusting */
tmp_start = res_cur->end + 1;
flag = 0;
while ((len_tmp = range->end - tmp_start) >= res->len) {
if ((tmp_start % tmp_divide) == 0) {
flag = 1;
len_cur = len_tmp;
start_cur = tmp_start;
break;
}
tmp_start += tmp_divide - tmp_start % tmp_divide;
if (tmp_start >= range->end)
break;
}
}
if (flag && len_cur == res->len) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
}
}
}
if (res_prev) {
if (res_prev->rangeno != res_cur->rangeno) {
/* 1st device on this range */
if ((res_cur->start != range->start) &&
((len_tmp = res_cur->start - 1 - range->start) >= res->len)) {
if ((len_tmp < len_cur) || (len_cur == 0)) {
if ((range->start % tmp_divide) == 0) {
/* just perfect, starting address is divisible by length */
flag = 1;
len_cur = len_tmp;
start_cur = range->start;
} else {
/* Needs adjusting */
tmp_start = range->start;
flag = 0;
while ((len_tmp = res_cur->start - 1 - tmp_start) >= res->len) {
if ((tmp_start % tmp_divide) == 0) {
flag = 1;
len_cur = len_tmp;
start_cur = tmp_start;
break;
}
tmp_start += tmp_divide - tmp_start % tmp_divide;
if (tmp_start >= res_cur->start - 1)
break;
}
}
if (flag && len_cur == res->len) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
}
}
} else {
/* in the same range */
if ((len_tmp = res_cur->start - 1 - res_prev->end - 1) >= res->len) {
if ((len_tmp < len_cur) || (len_cur == 0)) {
if (((res_prev->end + 1) % tmp_divide) == 0) {
/* just perfect, starting address's divisible by length */
flag = 1;
len_cur = len_tmp;
start_cur = res_prev->end + 1;
} else {
/* Needs adjusting */
tmp_start = res_prev->end + 1;
flag = 0;
while ((len_tmp = res_cur->start - 1 - tmp_start) >= res->len) {
if ((tmp_start % tmp_divide) == 0) {
flag = 1;
len_cur = len_tmp;
start_cur = tmp_start;
break;
}
tmp_start += tmp_divide - tmp_start % tmp_divide;
if (tmp_start >= res_cur->start - 1)
break;
}
}
if (flag && len_cur == res->len) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
}
}
}
}
/* end if (res_prev) */
res_prev = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
} /* end of while */
if (!res_prev) {
/* 1st device ever */
/* need to find appropriate range */
switch (res->type) {
case IO:
range = bus_cur->rangeIO;
break;
case MEM:
range = bus_cur->rangeMem;
break;
case PFMEM:
range = bus_cur->rangePFMem;
break;
}
while (range) {
if ((len_tmp = range->end - range->start) >= res->len) {
if ((len_tmp < len_cur) || (len_cur == 0)) {
if ((range->start % tmp_divide) == 0) {
/* just perfect, starting address's divisible by length */
flag = 1;
len_cur = len_tmp;
start_cur = range->start;
} else {
/* Needs adjusting */
tmp_start = range->start;
flag = 0;
while ((len_tmp = range->end - tmp_start) >= res->len) {
if ((tmp_start % tmp_divide) == 0) {
flag = 1;
len_cur = len_tmp;
start_cur = tmp_start;
break;
}
tmp_start += tmp_divide - tmp_start % tmp_divide;
if (tmp_start >= range->end)
break;
}
}
if (flag && len_cur == res->len) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
}
}
range = range->next;
} /* end of while */
if ((!range) && (len_cur == 0)) {
/* have gone through the list of devices and ranges and haven't found n.e.thing */
err ("no appropriate range.. bailing out...\n");
return -EINVAL;
} else if (len_cur) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
}
if (!res_cur) {
debug ("prev->rangeno = %d, noranges = %d\n", res_prev->rangeno, noranges);
if (res_prev->rangeno < noranges) {
/* if there're more ranges out there to check */
switch (res->type) {
case IO:
range = bus_cur->rangeIO;
break;
case MEM:
range = bus_cur->rangeMem;
break;
case PFMEM:
range = bus_cur->rangePFMem;
break;
}
while (range) {
if ((len_tmp = range->end - range->start) >= res->len) {
if ((len_tmp < len_cur) || (len_cur == 0)) {
if ((range->start % tmp_divide) == 0) {
/* just perfect, starting address's divisible by length */
flag = 1;
len_cur = len_tmp;
start_cur = range->start;
} else {
/* Needs adjusting */
tmp_start = range->start;
flag = 0;
while ((len_tmp = range->end - tmp_start) >= res->len) {
if ((tmp_start % tmp_divide) == 0) {
flag = 1;
len_cur = len_tmp;
start_cur = tmp_start;
break;
}
tmp_start += tmp_divide - tmp_start % tmp_divide;
if (tmp_start >= range->end)
break;
}
}
if (flag && len_cur == res->len) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
}
}
range = range->next;
} /* end of while */
if ((!range) && (len_cur == 0)) {
/* have gone through the list of devices and ranges and haven't found n.e.thing */
err ("no appropriate range.. bailing out...\n");
return -EINVAL;
} else if (len_cur) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
}
} else {
/* no more ranges to check on */
if (len_cur) {
res->start = start_cur;
res->len += 1; /* To restore the balance */
res->end = res->start + res->len - 1;
return 0;
} else {
/* have gone through the list of devices and haven't found n.e.thing */
err ("no appropriate range.. bailing out...\n");
return -EINVAL;
}
}
} /* end if(!res_cur) */
return -EINVAL;
}
/********************************************************************************
* This routine is called from remove_card if the card contained PPB.
* It will remove all the resources on the bus as well as the bus itself
* Input: Bus
* Ouput: 0, -ENODEV
********************************************************************************/
int ibmphp_remove_bus (struct bus_node *bus, u8 parent_busno)
{
struct resource_node *res_cur;
struct resource_node *res_tmp;
struct bus_node *prev_bus;
int rc;
prev_bus = find_bus_wprev (parent_busno, NULL, 0);
if (!prev_bus) {
debug ("something terribly wrong. Cannot find parent bus to the one to remove\n");
return -ENODEV;
}
debug ("In ibmphp_remove_bus... prev_bus->busno is %x\n", prev_bus->busno);
rc = remove_ranges (bus, prev_bus);
if (rc)
return rc;
if (bus->firstIO) {
res_cur = bus->firstIO;
while (res_cur) {
res_tmp = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
kfree (res_tmp);
res_tmp = NULL;
}
bus->firstIO = NULL;
}
if (bus->firstMem) {
res_cur = bus->firstMem;
while (res_cur) {
res_tmp = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
kfree (res_tmp);
res_tmp = NULL;
}
bus->firstMem = NULL;
}
if (bus->firstPFMem) {
res_cur = bus->firstPFMem;
while (res_cur) {
res_tmp = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
kfree (res_tmp);
res_tmp = NULL;
}
bus->firstPFMem = NULL;
}
if (bus->firstPFMemFromMem) {
res_cur = bus->firstPFMemFromMem;
while (res_cur) {
res_tmp = res_cur;
res_cur = res_cur->next;
kfree (res_tmp);
res_tmp = NULL;
}
bus->firstPFMemFromMem = NULL;
}
list_del (&bus->bus_list);
kfree (bus);
return 0;
}
/******************************************************************************
* This routine deletes the ranges from a given bus, and the entries from the
* parent's bus in the resources
* Input: current bus, previous bus
* Output: 0, -EINVAL
******************************************************************************/
static int remove_ranges (struct bus_node *bus_cur, struct bus_node *bus_prev)
{
struct range_node *range_cur;
struct range_node *range_tmp;
int i;
struct resource_node *res = NULL;
if (bus_cur->noIORanges) {
range_cur = bus_cur->rangeIO;
for (i = 0; i < bus_cur->noIORanges; i++) {
if (ibmphp_find_resource (bus_prev, range_cur->start, &res, IO) < 0)
return -EINVAL;
ibmphp_remove_resource (res);
range_tmp = range_cur;
range_cur = range_cur->next;
kfree (range_tmp);
range_tmp = NULL;
}
bus_cur->rangeIO = NULL;
}
if (bus_cur->noMemRanges) {
range_cur = bus_cur->rangeMem;
for (i = 0; i < bus_cur->noMemRanges; i++) {
if (ibmphp_find_resource (bus_prev, range_cur->start, &res, MEM) < 0)
return -EINVAL;
ibmphp_remove_resource (res);
range_tmp = range_cur;
range_cur = range_cur->next;
kfree (range_tmp);
range_tmp = NULL;
}
bus_cur->rangeMem = NULL;
}
if (bus_cur->noPFMemRanges) {
range_cur = bus_cur->rangePFMem;
for (i = 0; i < bus_cur->noPFMemRanges; i++) {
if (ibmphp_find_resource (bus_prev, range_cur->start, &res, PFMEM) < 0)
return -EINVAL;
ibmphp_remove_resource (res);
range_tmp = range_cur;
range_cur = range_cur->next;
kfree (range_tmp);
range_tmp = NULL;
}
bus_cur->rangePFMem = NULL;
}
return 0;
}
/*
* find the resource node in the bus
* Input: Resource needed, start address of the resource, type of resource
*/
int ibmphp_find_resource (struct bus_node *bus, u32 start_address, struct resource_node **res, int flag)
{
struct resource_node *res_cur = NULL;
char * type = "";
if (!bus) {
err ("The bus passed in NULL to find resource\n");
return -ENODEV;
}
switch (flag) {
case IO:
res_cur = bus->firstIO;
type = "io";
break;
case MEM:
res_cur = bus->firstMem;
type = "mem";
break;
case PFMEM:
res_cur = bus->firstPFMem;
type = "pfmem";
break;
default:
err ("wrong type of flag\n");
return -EINVAL;
}
while (res_cur) {
if (res_cur->start == start_address) {
*res = res_cur;
break;
}
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
}
if (!res_cur) {
if (flag == PFMEM) {
res_cur = bus->firstPFMemFromMem;
while (res_cur) {
if (res_cur->start == start_address) {
*res = res_cur;
break;
}
res_cur = res_cur->next;
}
if (!res_cur) {
debug ("SOS...cannot find %s resource in the bus.\n", type);
return -EINVAL;
}
} else {
debug ("SOS... cannot find %s resource in the bus.\n", type);
return -EINVAL;
}
}
if (*res)
debug ("*res->start = %x\n", (*res)->start);
return 0;
}
/***********************************************************************
* This routine will free the resource structures used by the
* system. It is called from cleanup routine for the module
* Parameters: none
* Returns: none
***********************************************************************/
void ibmphp_free_resources (void)
{
struct bus_node *bus_cur = NULL;
struct bus_node *bus_tmp;
struct range_node *range_cur;
struct range_node *range_tmp;
struct resource_node *res_cur;
struct resource_node *res_tmp;
struct list_head *tmp;
struct list_head *next;
int i = 0;
flags = 1;
list_for_each_safe (tmp, next, &gbuses) {
bus_cur = list_entry (tmp, struct bus_node, bus_list);
if (bus_cur->noIORanges) {
range_cur = bus_cur->rangeIO;
for (i = 0; i < bus_cur->noIORanges; i++) {
if (!range_cur)
break;
range_tmp = range_cur;
range_cur = range_cur->next;
kfree (range_tmp);
range_tmp = NULL;
}
}
if (bus_cur->noMemRanges) {
range_cur = bus_cur->rangeMem;
for (i = 0; i < bus_cur->noMemRanges; i++) {
if (!range_cur)
break;
range_tmp = range_cur;
range_cur = range_cur->next;
kfree (range_tmp);
range_tmp = NULL;
}
}
if (bus_cur->noPFMemRanges) {
range_cur = bus_cur->rangePFMem;
for (i = 0; i < bus_cur->noPFMemRanges; i++) {
if (!range_cur)
break;
range_tmp = range_cur;
range_cur = range_cur->next;
kfree (range_tmp);
range_tmp = NULL;
}
}
if (bus_cur->firstIO) {
res_cur = bus_cur->firstIO;
while (res_cur) {
res_tmp = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
kfree (res_tmp);
res_tmp = NULL;
}
bus_cur->firstIO = NULL;
}
if (bus_cur->firstMem) {
res_cur = bus_cur->firstMem;
while (res_cur) {
res_tmp = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
kfree (res_tmp);
res_tmp = NULL;
}
bus_cur->firstMem = NULL;
}
if (bus_cur->firstPFMem) {
res_cur = bus_cur->firstPFMem;
while (res_cur) {
res_tmp = res_cur;
if (res_cur->next)
res_cur = res_cur->next;
else
res_cur = res_cur->nextRange;
kfree (res_tmp);
res_tmp = NULL;
}
bus_cur->firstPFMem = NULL;
}
if (bus_cur->firstPFMemFromMem) {
res_cur = bus_cur->firstPFMemFromMem;
while (res_cur) {
res_tmp = res_cur;
res_cur = res_cur->next;
kfree (res_tmp);
res_tmp = NULL;
}
bus_cur->firstPFMemFromMem = NULL;
}
bus_tmp = bus_cur;
list_del (&bus_cur->bus_list);
kfree (bus_tmp);
bus_tmp = NULL;
}
}
/*********************************************************************************
* This function will go over the PFmem resources to check if the EBDA allocated
* pfmem out of memory buckets of the bus. If so, it will change the range numbers
* and a flag to indicate that this resource is out of memory. It will also move the
* Pfmem out of the pfmem resource list to the PFMemFromMem list, and will create
* a new Mem node
* This routine is called right after initialization
*******************************************************************************/
static int __init once_over (void)
{
struct resource_node *pfmem_cur;
struct resource_node *pfmem_prev;
struct resource_node *mem;
struct bus_node *bus_cur;
struct list_head *tmp;
list_for_each (tmp, &gbuses) {
bus_cur = list_entry (tmp, struct bus_node, bus_list);
if ((!bus_cur->rangePFMem) && (bus_cur->firstPFMem)) {
for (pfmem_cur = bus_cur->firstPFMem, pfmem_prev = NULL; pfmem_cur; pfmem_prev = pfmem_cur, pfmem_cur = pfmem_cur->next) {
pfmem_cur->fromMem = 1;
if (pfmem_prev)
pfmem_prev->next = pfmem_cur->next;
else
bus_cur->firstPFMem = pfmem_cur->next;
if (!bus_cur->firstPFMemFromMem)
pfmem_cur->next = NULL;
else
/* we don't need to sort PFMemFromMem since we're using mem node for
all the real work anyways, so just insert at the beginning of the
list
*/
pfmem_cur->next = bus_cur->firstPFMemFromMem;
bus_cur->firstPFMemFromMem = pfmem_cur;
mem = kzalloc(sizeof(struct resource_node), GFP_KERNEL);
if (!mem) {
err ("out of system memory\n");
return -ENOMEM;
}
mem->type = MEM;
mem->busno = pfmem_cur->busno;
mem->devfunc = pfmem_cur->devfunc;
mem->start = pfmem_cur->start;
mem->end = pfmem_cur->end;
mem->len = pfmem_cur->len;
if (ibmphp_add_resource (mem) < 0)
err ("Trouble...trouble... EBDA allocated pfmem from mem, but system doesn't display it has this space... unless not PCI device...\n");
pfmem_cur->rangeno = mem->rangeno;
} /* end for pfmem */
} /* end if */
} /* end list_for_each bus */
return 0;
}
int ibmphp_add_pfmem_from_mem (struct resource_node *pfmem)
{
struct bus_node *bus_cur = find_bus_wprev (pfmem->busno, NULL, 0);
if (!bus_cur) {
err ("cannot find bus of pfmem to add...\n");
return -ENODEV;
}
if (bus_cur->firstPFMemFromMem)
pfmem->next = bus_cur->firstPFMemFromMem;
else
pfmem->next = NULL;
bus_cur->firstPFMemFromMem = pfmem;
return 0;
}
/* This routine just goes through the buses to see if the bus already exists.
* It is called from ibmphp_find_sec_number, to find out a secondary bus number for
* bridged cards
* Parameters: bus_number
* Returns: Bus pointer or NULL
*/
struct bus_node *ibmphp_find_res_bus (u8 bus_number)
{
return find_bus_wprev (bus_number, NULL, 0);
}
static struct bus_node *find_bus_wprev (u8 bus_number, struct bus_node **prev, u8 flag)
{
struct bus_node *bus_cur;
struct list_head *tmp;
struct list_head *tmp_prev;
list_for_each (tmp, &gbuses) {
tmp_prev = tmp->prev;
bus_cur = list_entry (tmp, struct bus_node, bus_list);
if (flag)
*prev = list_entry (tmp_prev, struct bus_node, bus_list);
if (bus_cur->busno == bus_number)
return bus_cur;
}
return NULL;
}
void ibmphp_print_test (void)
{
int i = 0;
struct bus_node *bus_cur = NULL;
struct range_node *range;
struct resource_node *res;
struct list_head *tmp;
debug_pci ("*****************START**********************\n");
if ((!list_empty(&gbuses)) && flags) {
err ("The GBUSES is not NULL?!?!?!?!?\n");
return;
}
list_for_each (tmp, &gbuses) {
bus_cur = list_entry (tmp, struct bus_node, bus_list);
debug_pci ("This is bus # %d. There are\n", bus_cur->busno);
debug_pci ("IORanges = %d\t", bus_cur->noIORanges);
debug_pci ("MemRanges = %d\t", bus_cur->noMemRanges);
debug_pci ("PFMemRanges = %d\n", bus_cur->noPFMemRanges);
debug_pci ("The IO Ranges are as follows:\n");
if (bus_cur->rangeIO) {
range = bus_cur->rangeIO;
for (i = 0; i < bus_cur->noIORanges; i++) {
debug_pci ("rangeno is %d\n", range->rangeno);
debug_pci ("[%x - %x]\n", range->start, range->end);
range = range->next;
}
}
debug_pci ("The Mem Ranges are as follows:\n");
if (bus_cur->rangeMem) {
range = bus_cur->rangeMem;
for (i = 0; i < bus_cur->noMemRanges; i++) {
debug_pci ("rangeno is %d\n", range->rangeno);
debug_pci ("[%x - %x]\n", range->start, range->end);
range = range->next;
}
}
debug_pci ("The PFMem Ranges are as follows:\n");
if (bus_cur->rangePFMem) {
range = bus_cur->rangePFMem;
for (i = 0; i < bus_cur->noPFMemRanges; i++) {
debug_pci ("rangeno is %d\n", range->rangeno);
debug_pci ("[%x - %x]\n", range->start, range->end);
range = range->next;
}
}
debug_pci ("The resources on this bus are as follows\n");
debug_pci ("IO...\n");
if (bus_cur->firstIO) {
res = bus_cur->firstIO;
while (res) {
debug_pci ("The range # is %d\n", res->rangeno);
debug_pci ("The bus, devfnc is %d, %x\n", res->busno, res->devfunc);
debug_pci ("[%x - %x], len=%x\n", res->start, res->end, res->len);
if (res->next)
res = res->next;
else if (res->nextRange)
res = res->nextRange;
else
break;
}
}
debug_pci ("Mem...\n");
if (bus_cur->firstMem) {
res = bus_cur->firstMem;
while (res) {
debug_pci ("The range # is %d\n", res->rangeno);
debug_pci ("The bus, devfnc is %d, %x\n", res->busno, res->devfunc);
debug_pci ("[%x - %x], len=%x\n", res->start, res->end, res->len);
if (res->next)
res = res->next;
else if (res->nextRange)
res = res->nextRange;
else
break;
}
}
debug_pci ("PFMem...\n");
if (bus_cur->firstPFMem) {
res = bus_cur->firstPFMem;
while (res) {
debug_pci ("The range # is %d\n", res->rangeno);
debug_pci ("The bus, devfnc is %d, %x\n", res->busno, res->devfunc);
debug_pci ("[%x - %x], len=%x\n", res->start, res->end, res->len);
if (res->next)
res = res->next;
else if (res->nextRange)
res = res->nextRange;
else
break;
}
}
debug_pci ("PFMemFromMem...\n");
if (bus_cur->firstPFMemFromMem) {
res = bus_cur->firstPFMemFromMem;
while (res) {
debug_pci ("The range # is %d\n", res->rangeno);
debug_pci ("The bus, devfnc is %d, %x\n", res->busno, res->devfunc);
debug_pci ("[%x - %x], len=%x\n", res->start, res->end, res->len);
res = res->next;
}
}
}
debug_pci ("***********************END***********************\n");
}
static int range_exists_already (struct range_node * range, struct bus_node * bus_cur, u8 type)
{
struct range_node * range_cur = NULL;
switch (type) {
case IO:
range_cur = bus_cur->rangeIO;
break;
case MEM:
range_cur = bus_cur->rangeMem;
break;
case PFMEM:
range_cur = bus_cur->rangePFMem;
break;
default:
err ("wrong type passed to find out if range already exists\n");
return -ENODEV;
}
while (range_cur) {
if ((range_cur->start == range->start) && (range_cur->end == range->end))
return 1;
range_cur = range_cur->next;
}
return 0;
}
/* This routine will read the windows for any PPB we have and update the
* range info for the secondary bus, and will also input this info into
* primary bus, since BIOS doesn't. This is for PPB that are in the system
* on bootup. For bridged cards that were added during previous load of the
* driver, only the ranges and the bus structure are added, the devices are
* added from NVRAM
* Input: primary busno
* Returns: none
* Note: this function doesn't take into account IO restrictions etc,
* so will only work for bridges with no video/ISA devices behind them It
* also will not work for onboard PPB's that can have more than 1 *bus
* behind them All these are TO DO.
* Also need to add more error checkings... (from fnc returns etc)
*/
static int __init update_bridge_ranges (struct bus_node **bus)
{
u8 sec_busno, device, function, hdr_type, start_io_address, end_io_address;
u16 vendor_id, upper_io_start, upper_io_end, start_mem_address, end_mem_address;
u32 start_address, end_address, upper_start, upper_end;
struct bus_node *bus_sec;
struct bus_node *bus_cur;
struct resource_node *io;
struct resource_node *mem;
struct resource_node *pfmem;
struct range_node *range;
unsigned int devfn;
bus_cur = *bus;
if (!bus_cur)
return -ENODEV;
ibmphp_pci_bus->number = bus_cur->busno;
debug ("inside %s\n", __func__);
debug ("bus_cur->busno = %x\n", bus_cur->busno);
for (device = 0; device < 32; device++) {
for (function = 0x00; function < 0x08; function++) {
devfn = PCI_DEVFN(device, function);
pci_bus_read_config_word (ibmphp_pci_bus, devfn, PCI_VENDOR_ID, &vendor_id);
if (vendor_id != PCI_VENDOR_ID_NOTVALID) {
/* found correct device!!! */
pci_bus_read_config_byte (ibmphp_pci_bus, devfn, PCI_HEADER_TYPE, &hdr_type);
switch (hdr_type) {
case PCI_HEADER_TYPE_NORMAL:
function = 0x8;
break;
case PCI_HEADER_TYPE_MULTIDEVICE:
break;
case PCI_HEADER_TYPE_BRIDGE:
function = 0x8;
case PCI_HEADER_TYPE_MULTIBRIDGE:
/* We assume here that only 1 bus behind the bridge
TO DO: add functionality for several:
temp = secondary;
while (temp < subordinate) {
...
temp++;
}
*/
pci_bus_read_config_byte (ibmphp_pci_bus, devfn, PCI_SECONDARY_BUS, &sec_busno);
bus_sec = find_bus_wprev (sec_busno, NULL, 0);
/* this bus structure doesn't exist yet, PPB was configured during previous loading of ibmphp */
if (!bus_sec) {
bus_sec = alloc_error_bus (NULL, sec_busno, 1);
/* the rest will be populated during NVRAM call */
return 0;
}
pci_bus_read_config_byte (ibmphp_pci_bus, devfn, PCI_IO_BASE, &start_io_address);
pci_bus_read_config_byte (ibmphp_pci_bus, devfn, PCI_IO_LIMIT, &end_io_address);
pci_bus_read_config_word (ibmphp_pci_bus, devfn, PCI_IO_BASE_UPPER16, &upper_io_start);
pci_bus_read_config_word (ibmphp_pci_bus, devfn, PCI_IO_LIMIT_UPPER16, &upper_io_end);
start_address = (start_io_address & PCI_IO_RANGE_MASK) << 8;
start_address |= (upper_io_start << 16);
end_address = (end_io_address & PCI_IO_RANGE_MASK) << 8;
end_address |= (upper_io_end << 16);
if ((start_address) && (start_address <= end_address)) {
range = kzalloc(sizeof(struct range_node), GFP_KERNEL);
if (!range) {
err ("out of system memory\n");
return -ENOMEM;
}
range->start = start_address;
range->end = end_address + 0xfff;
if (bus_sec->noIORanges > 0) {
if (!range_exists_already (range, bus_sec, IO)) {
add_bus_range (IO, range, bus_sec);
++bus_sec->noIORanges;
} else {
kfree (range);
range = NULL;
}
} else {
/* 1st IO Range on the bus */
range->rangeno = 1;
bus_sec->rangeIO = range;
++bus_sec->noIORanges;
}
fix_resources (bus_sec);
if (ibmphp_find_resource (bus_cur, start_address, &io, IO)) {
io = kzalloc(sizeof(struct resource_node), GFP_KERNEL);
if (!io) {
kfree (range);
err ("out of system memory\n");
return -ENOMEM;
}
io->type = IO;
io->busno = bus_cur->busno;
io->devfunc = ((device << 3) | (function & 0x7));
io->start = start_address;
io->end = end_address + 0xfff;
io->len = io->end - io->start + 1;
ibmphp_add_resource (io);
}
}
pci_bus_read_config_word (ibmphp_pci_bus, devfn, PCI_MEMORY_BASE, &start_mem_address);
pci_bus_read_config_word (ibmphp_pci_bus, devfn, PCI_MEMORY_LIMIT, &end_mem_address);
start_address = 0x00000000 | (start_mem_address & PCI_MEMORY_RANGE_MASK) << 16;
end_address = 0x00000000 | (end_mem_address & PCI_MEMORY_RANGE_MASK) << 16;
if ((start_address) && (start_address <= end_address)) {
range = kzalloc(sizeof(struct range_node), GFP_KERNEL);
if (!range) {
err ("out of system memory\n");
return -ENOMEM;
}
range->start = start_address;
range->end = end_address + 0xfffff;
if (bus_sec->noMemRanges > 0) {
if (!range_exists_already (range, bus_sec, MEM)) {
add_bus_range (MEM, range, bus_sec);
++bus_sec->noMemRanges;
} else {
kfree (range);
range = NULL;
}
} else {
/* 1st Mem Range on the bus */
range->rangeno = 1;
bus_sec->rangeMem = range;
++bus_sec->noMemRanges;
}
fix_resources (bus_sec);
if (ibmphp_find_resource (bus_cur, start_address, &mem, MEM)) {
mem = kzalloc(sizeof(struct resource_node), GFP_KERNEL);
if (!mem) {
kfree (range);
err ("out of system memory\n");
return -ENOMEM;
}
mem->type = MEM;
mem->busno = bus_cur->busno;
mem->devfunc = ((device << 3) | (function & 0x7));
mem->start = start_address;
mem->end = end_address + 0xfffff;
mem->len = mem->end - mem->start + 1;
ibmphp_add_resource (mem);
}
}
pci_bus_read_config_word (ibmphp_pci_bus, devfn, PCI_PREF_MEMORY_BASE, &start_mem_address);
pci_bus_read_config_word (ibmphp_pci_bus, devfn, PCI_PREF_MEMORY_LIMIT, &end_mem_address);
pci_bus_read_config_dword (ibmphp_pci_bus, devfn, PCI_PREF_BASE_UPPER32, &upper_start);
pci_bus_read_config_dword (ibmphp_pci_bus, devfn, PCI_PREF_LIMIT_UPPER32, &upper_end);
start_address = 0x00000000 | (start_mem_address & PCI_MEMORY_RANGE_MASK) << 16;
end_address = 0x00000000 | (end_mem_address & PCI_MEMORY_RANGE_MASK) << 16;
#if BITS_PER_LONG == 64
start_address |= ((long) upper_start) << 32;
end_address |= ((long) upper_end) << 32;
#endif
if ((start_address) && (start_address <= end_address)) {
range = kzalloc(sizeof(struct range_node), GFP_KERNEL);
if (!range) {
err ("out of system memory\n");
return -ENOMEM;
}
range->start = start_address;
range->end = end_address + 0xfffff;
if (bus_sec->noPFMemRanges > 0) {
if (!range_exists_already (range, bus_sec, PFMEM)) {
add_bus_range (PFMEM, range, bus_sec);
++bus_sec->noPFMemRanges;
} else {
kfree (range);
range = NULL;
}
} else {
/* 1st PFMem Range on the bus */
range->rangeno = 1;
bus_sec->rangePFMem = range;
++bus_sec->noPFMemRanges;
}
fix_resources (bus_sec);
if (ibmphp_find_resource (bus_cur, start_address, &pfmem, PFMEM)) {
pfmem = kzalloc(sizeof(struct resource_node), GFP_KERNEL);
if (!pfmem) {
kfree (range);
err ("out of system memory\n");
return -ENOMEM;
}
pfmem->type = PFMEM;
pfmem->busno = bus_cur->busno;
pfmem->devfunc = ((device << 3) | (function & 0x7));
pfmem->start = start_address;
pfmem->end = end_address + 0xfffff;
pfmem->len = pfmem->end - pfmem->start + 1;
pfmem->fromMem = 0;
ibmphp_add_resource (pfmem);
}
}
break;
} /* end of switch */
} /* end if vendor */
} /* end for function */
} /* end for device */
bus = &bus_cur;
return 0;
}
| gpl-2.0 |
Hybrid-Power/bricked-mako | fs/jfs/jfs_mount.c | 12932 | 12998 | /*
* Copyright (C) International Business Machines Corp., 2000-2004
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Module: jfs_mount.c
*
* note: file system in transition to aggregate/fileset:
*
* file system mount is interpreted as the mount of aggregate,
* if not already mounted, and mount of the single/only fileset in
* the aggregate;
*
* a file system/aggregate is represented by an internal inode
* (aka mount inode) initialized with aggregate superblock;
* each vfs represents a fileset, and points to its "fileset inode
* allocation map inode" (aka fileset inode):
* (an aggregate itself is structured recursively as a filset:
* an internal vfs is constructed and points to its "fileset inode
* allocation map inode" (aka aggregate inode) where each inode
* represents a fileset inode) so that inode number is mapped to
* on-disk inode in uniform way at both aggregate and fileset level;
*
* each vnode/inode of a fileset is linked to its vfs (to facilitate
* per fileset inode operations, e.g., unmount of a fileset, etc.);
* each inode points to the mount inode (to facilitate access to
* per aggregate information, e.g., block size, etc.) as well as
* its file set inode.
*
* aggregate
* ipmnt
* mntvfs -> fileset ipimap+ -> aggregate ipbmap -> aggregate ipaimap;
* fileset vfs -> vp(1) <-> ... <-> vp(n) <->vproot;
*/
#include <linux/fs.h>
#include <linux/buffer_head.h>
#include "jfs_incore.h"
#include "jfs_filsys.h"
#include "jfs_superblock.h"
#include "jfs_dmap.h"
#include "jfs_imap.h"
#include "jfs_metapage.h"
#include "jfs_debug.h"
/*
* forward references
*/
static int chkSuper(struct super_block *);
static int logMOUNT(struct super_block *sb);
/*
* NAME: jfs_mount(sb)
*
* FUNCTION: vfs_mount()
*
* PARAMETER: sb - super block
*
* RETURN: -EBUSY - device already mounted or open for write
* -EBUSY - cvrdvp already mounted;
* -EBUSY - mount table full
* -ENOTDIR- cvrdvp not directory on a device mount
* -ENXIO - device open failure
*/
int jfs_mount(struct super_block *sb)
{
int rc = 0; /* Return code */
struct jfs_sb_info *sbi = JFS_SBI(sb);
struct inode *ipaimap = NULL;
struct inode *ipaimap2 = NULL;
struct inode *ipimap = NULL;
struct inode *ipbmap = NULL;
/*
* read/validate superblock
* (initialize mount inode from the superblock)
*/
if ((rc = chkSuper(sb))) {
goto errout20;
}
ipaimap = diReadSpecial(sb, AGGREGATE_I, 0);
if (ipaimap == NULL) {
jfs_err("jfs_mount: Failed to read AGGREGATE_I");
rc = -EIO;
goto errout20;
}
sbi->ipaimap = ipaimap;
jfs_info("jfs_mount: ipaimap:0x%p", ipaimap);
/*
* initialize aggregate inode allocation map
*/
if ((rc = diMount(ipaimap))) {
jfs_err("jfs_mount: diMount(ipaimap) failed w/rc = %d", rc);
goto errout21;
}
/*
* open aggregate block allocation map
*/
ipbmap = diReadSpecial(sb, BMAP_I, 0);
if (ipbmap == NULL) {
rc = -EIO;
goto errout22;
}
jfs_info("jfs_mount: ipbmap:0x%p", ipbmap);
sbi->ipbmap = ipbmap;
/*
* initialize aggregate block allocation map
*/
if ((rc = dbMount(ipbmap))) {
jfs_err("jfs_mount: dbMount failed w/rc = %d", rc);
goto errout22;
}
/*
* open the secondary aggregate inode allocation map
*
* This is a duplicate of the aggregate inode allocation map.
*
* hand craft a vfs in the same fashion as we did to read ipaimap.
* By adding INOSPEREXT (32) to the inode number, we are telling
* diReadSpecial that we are reading from the secondary aggregate
* inode table. This also creates a unique entry in the inode hash
* table.
*/
if ((sbi->mntflag & JFS_BAD_SAIT) == 0) {
ipaimap2 = diReadSpecial(sb, AGGREGATE_I, 1);
if (!ipaimap2) {
jfs_err("jfs_mount: Failed to read AGGREGATE_I");
rc = -EIO;
goto errout35;
}
sbi->ipaimap2 = ipaimap2;
jfs_info("jfs_mount: ipaimap2:0x%p", ipaimap2);
/*
* initialize secondary aggregate inode allocation map
*/
if ((rc = diMount(ipaimap2))) {
jfs_err("jfs_mount: diMount(ipaimap2) failed, rc = %d",
rc);
goto errout35;
}
} else
/* Secondary aggregate inode table is not valid */
sbi->ipaimap2 = NULL;
/*
* mount (the only/single) fileset
*/
/*
* open fileset inode allocation map (aka fileset inode)
*/
ipimap = diReadSpecial(sb, FILESYSTEM_I, 0);
if (ipimap == NULL) {
jfs_err("jfs_mount: Failed to read FILESYSTEM_I");
/* open fileset secondary inode allocation map */
rc = -EIO;
goto errout40;
}
jfs_info("jfs_mount: ipimap:0x%p", ipimap);
/* map further access of per fileset inodes by the fileset inode */
sbi->ipimap = ipimap;
/* initialize fileset inode allocation map */
if ((rc = diMount(ipimap))) {
jfs_err("jfs_mount: diMount failed w/rc = %d", rc);
goto errout41;
}
goto out;
/*
* unwind on error
*/
errout41: /* close fileset inode allocation map inode */
diFreeSpecial(ipimap);
errout40: /* fileset closed */
/* close secondary aggregate inode allocation map */
if (ipaimap2) {
diUnmount(ipaimap2, 1);
diFreeSpecial(ipaimap2);
}
errout35:
/* close aggregate block allocation map */
dbUnmount(ipbmap, 1);
diFreeSpecial(ipbmap);
errout22: /* close aggregate inode allocation map */
diUnmount(ipaimap, 1);
errout21: /* close aggregate inodes */
diFreeSpecial(ipaimap);
errout20: /* aggregate closed */
out:
if (rc)
jfs_err("Mount JFS Failure: %d", rc);
return rc;
}
/*
* NAME: jfs_mount_rw(sb, remount)
*
* FUNCTION: Completes read-write mount, or remounts read-only volume
* as read-write
*/
int jfs_mount_rw(struct super_block *sb, int remount)
{
struct jfs_sb_info *sbi = JFS_SBI(sb);
int rc;
/*
* If we are re-mounting a previously read-only volume, we want to
* re-read the inode and block maps, since fsck.jfs may have updated
* them.
*/
if (remount) {
if (chkSuper(sb) || (sbi->state != FM_CLEAN))
return -EINVAL;
truncate_inode_pages(sbi->ipimap->i_mapping, 0);
truncate_inode_pages(sbi->ipbmap->i_mapping, 0);
diUnmount(sbi->ipimap, 1);
if ((rc = diMount(sbi->ipimap))) {
jfs_err("jfs_mount_rw: diMount failed!");
return rc;
}
dbUnmount(sbi->ipbmap, 1);
if ((rc = dbMount(sbi->ipbmap))) {
jfs_err("jfs_mount_rw: dbMount failed!");
return rc;
}
}
/*
* open/initialize log
*/
if ((rc = lmLogOpen(sb)))
return rc;
/*
* update file system superblock;
*/
if ((rc = updateSuper(sb, FM_MOUNT))) {
jfs_err("jfs_mount: updateSuper failed w/rc = %d", rc);
lmLogClose(sb);
return rc;
}
/*
* write MOUNT log record of the file system
*/
logMOUNT(sb);
return rc;
}
/*
* chkSuper()
*
* validate the superblock of the file system to be mounted and
* get the file system parameters.
*
* returns
* 0 with fragsize set if check successful
* error code if not successful
*/
static int chkSuper(struct super_block *sb)
{
int rc = 0;
struct jfs_sb_info *sbi = JFS_SBI(sb);
struct jfs_superblock *j_sb;
struct buffer_head *bh;
int AIM_bytesize, AIT_bytesize;
int expected_AIM_bytesize, expected_AIT_bytesize;
s64 AIM_byte_addr, AIT_byte_addr, fsckwsp_addr;
s64 byte_addr_diff0, byte_addr_diff1;
s32 bsize;
if ((rc = readSuper(sb, &bh)))
return rc;
j_sb = (struct jfs_superblock *)bh->b_data;
/*
* validate superblock
*/
/* validate fs signature */
if (strncmp(j_sb->s_magic, JFS_MAGIC, 4) ||
le32_to_cpu(j_sb->s_version) > JFS_VERSION) {
rc = -EINVAL;
goto out;
}
bsize = le32_to_cpu(j_sb->s_bsize);
#ifdef _JFS_4K
if (bsize != PSIZE) {
jfs_err("Currently only 4K block size supported!");
rc = -EINVAL;
goto out;
}
#endif /* _JFS_4K */
jfs_info("superblock: flag:0x%08x state:0x%08x size:0x%Lx",
le32_to_cpu(j_sb->s_flag), le32_to_cpu(j_sb->s_state),
(unsigned long long) le64_to_cpu(j_sb->s_size));
/* validate the descriptors for Secondary AIM and AIT */
if ((j_sb->s_flag & cpu_to_le32(JFS_BAD_SAIT)) !=
cpu_to_le32(JFS_BAD_SAIT)) {
expected_AIM_bytesize = 2 * PSIZE;
AIM_bytesize = lengthPXD(&(j_sb->s_aim2)) * bsize;
expected_AIT_bytesize = 4 * PSIZE;
AIT_bytesize = lengthPXD(&(j_sb->s_ait2)) * bsize;
AIM_byte_addr = addressPXD(&(j_sb->s_aim2)) * bsize;
AIT_byte_addr = addressPXD(&(j_sb->s_ait2)) * bsize;
byte_addr_diff0 = AIT_byte_addr - AIM_byte_addr;
fsckwsp_addr = addressPXD(&(j_sb->s_fsckpxd)) * bsize;
byte_addr_diff1 = fsckwsp_addr - AIT_byte_addr;
if ((AIM_bytesize != expected_AIM_bytesize) ||
(AIT_bytesize != expected_AIT_bytesize) ||
(byte_addr_diff0 != AIM_bytesize) ||
(byte_addr_diff1 <= AIT_bytesize))
j_sb->s_flag |= cpu_to_le32(JFS_BAD_SAIT);
}
if ((j_sb->s_flag & cpu_to_le32(JFS_GROUPCOMMIT)) !=
cpu_to_le32(JFS_GROUPCOMMIT))
j_sb->s_flag |= cpu_to_le32(JFS_GROUPCOMMIT);
/* validate fs state */
if (j_sb->s_state != cpu_to_le32(FM_CLEAN) &&
!(sb->s_flags & MS_RDONLY)) {
jfs_err("jfs_mount: Mount Failure: File System Dirty.");
rc = -EINVAL;
goto out;
}
sbi->state = le32_to_cpu(j_sb->s_state);
sbi->mntflag = le32_to_cpu(j_sb->s_flag);
/*
* JFS always does I/O by 4K pages. Don't tell the buffer cache
* that we use anything else (leave s_blocksize alone).
*/
sbi->bsize = bsize;
sbi->l2bsize = le16_to_cpu(j_sb->s_l2bsize);
/*
* For now, ignore s_pbsize, l2bfactor. All I/O going through buffer
* cache.
*/
sbi->nbperpage = PSIZE >> sbi->l2bsize;
sbi->l2nbperpage = L2PSIZE - sbi->l2bsize;
sbi->l2niperblk = sbi->l2bsize - L2DISIZE;
if (sbi->mntflag & JFS_INLINELOG)
sbi->logpxd = j_sb->s_logpxd;
else {
sbi->logdev = new_decode_dev(le32_to_cpu(j_sb->s_logdev));
memcpy(sbi->uuid, j_sb->s_uuid, sizeof(sbi->uuid));
memcpy(sbi->loguuid, j_sb->s_loguuid, sizeof(sbi->uuid));
}
sbi->fsckpxd = j_sb->s_fsckpxd;
sbi->ait2 = j_sb->s_ait2;
out:
brelse(bh);
return rc;
}
/*
* updateSuper()
*
* update synchronously superblock if it is mounted read-write.
*/
int updateSuper(struct super_block *sb, uint state)
{
struct jfs_superblock *j_sb;
struct jfs_sb_info *sbi = JFS_SBI(sb);
struct buffer_head *bh;
int rc;
if (sbi->flag & JFS_NOINTEGRITY) {
if (state == FM_DIRTY) {
sbi->p_state = state;
return 0;
} else if (state == FM_MOUNT) {
sbi->p_state = sbi->state;
state = FM_DIRTY;
} else if (state == FM_CLEAN) {
state = sbi->p_state;
} else
jfs_err("updateSuper: bad state");
} else if (sbi->state == FM_DIRTY)
return 0;
if ((rc = readSuper(sb, &bh)))
return rc;
j_sb = (struct jfs_superblock *)bh->b_data;
j_sb->s_state = cpu_to_le32(state);
sbi->state = state;
if (state == FM_MOUNT) {
/* record log's dev_t and mount serial number */
j_sb->s_logdev = cpu_to_le32(new_encode_dev(sbi->log->bdev->bd_dev));
j_sb->s_logserial = cpu_to_le32(sbi->log->serial);
} else if (state == FM_CLEAN) {
/*
* If this volume is shared with OS/2, OS/2 will need to
* recalculate DASD usage, since we don't deal with it.
*/
if (j_sb->s_flag & cpu_to_le32(JFS_DASD_ENABLED))
j_sb->s_flag |= cpu_to_le32(JFS_DASD_PRIME);
}
mark_buffer_dirty(bh);
sync_dirty_buffer(bh);
brelse(bh);
return 0;
}
/*
* readSuper()
*
* read superblock by raw sector address
*/
int readSuper(struct super_block *sb, struct buffer_head **bpp)
{
/* read in primary superblock */
*bpp = sb_bread(sb, SUPER1_OFF >> sb->s_blocksize_bits);
if (*bpp)
return 0;
/* read in secondary/replicated superblock */
*bpp = sb_bread(sb, SUPER2_OFF >> sb->s_blocksize_bits);
if (*bpp)
return 0;
return -EIO;
}
/*
* logMOUNT()
*
* function: write a MOUNT log record for file system.
*
* MOUNT record keeps logredo() from processing log records
* for this file system past this point in log.
* it is harmless if mount fails.
*
* note: MOUNT record is at aggregate level, not at fileset level,
* since log records of previous mounts of a fileset
* (e.g., AFTER record of extent allocation) have to be processed
* to update block allocation map at aggregate level.
*/
static int logMOUNT(struct super_block *sb)
{
struct jfs_log *log = JFS_SBI(sb)->log;
struct lrd lrd;
lrd.logtid = 0;
lrd.backchain = 0;
lrd.type = cpu_to_le16(LOG_MOUNT);
lrd.length = 0;
lrd.aggregate = cpu_to_le32(new_encode_dev(sb->s_bdev->bd_dev));
lmLog(log, NULL, &lrd, NULL);
return 0;
}
| gpl-2.0 |
Savaged-Zen/Savaged-Zen-Speedy | arch/tile/kernel/module.c | 389 | 6226 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*
* Based on i386 version, copyright (C) 2001 Rusty Russell.
*/
#include <linux/moduleloader.h>
#include <linux/elf.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <asm/opcode-tile.h>
#include <asm/pgtable.h>
#ifdef __tilegx__
# define Elf_Rela Elf64_Rela
# define ELF_R_SYM ELF64_R_SYM
# define ELF_R_TYPE ELF64_R_TYPE
#else
# define Elf_Rela Elf32_Rela
# define ELF_R_SYM ELF32_R_SYM
# define ELF_R_TYPE ELF32_R_TYPE
#endif
#ifdef MODULE_DEBUG
#define DEBUGP printk
#else
#define DEBUGP(fmt...)
#endif
/*
* Allocate some address space in the range MEM_MODULE_START to
* MEM_MODULE_END and populate it with memory.
*/
void *module_alloc(unsigned long size)
{
struct page **pages;
pgprot_t prot_rwx = __pgprot(_PAGE_KERNEL | _PAGE_KERNEL_EXEC);
struct vm_struct *area;
int i = 0;
int npages;
if (size == 0)
return NULL;
npages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
pages = kmalloc(npages * sizeof(struct page *), GFP_KERNEL);
if (pages == NULL)
return NULL;
for (; i < npages; ++i) {
pages[i] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
if (!pages[i])
goto error;
}
area = __get_vm_area(size, VM_ALLOC, MEM_MODULE_START, MEM_MODULE_END);
if (!area)
goto error;
if (map_vm_area(area, prot_rwx, &pages)) {
vunmap(area->addr);
goto error;
}
return area->addr;
error:
while (--i >= 0)
__free_page(pages[i]);
kfree(pages);
return NULL;
}
/* Free memory returned from module_alloc */
void module_free(struct module *mod, void *module_region)
{
vfree(module_region);
/*
* FIXME: If module_region == mod->init_region, trim exception
* table entries.
*/
}
/* We don't need anything special. */
int module_frob_arch_sections(Elf_Ehdr *hdr,
Elf_Shdr *sechdrs,
char *secstrings,
struct module *mod)
{
return 0;
}
int apply_relocate(Elf_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me)
{
pr_err("module %s: .rel relocation unsupported\n", me->name);
return -ENOEXEC;
}
#ifdef __tilegx__
/*
* Validate that the high 16 bits of "value" is just the sign-extension of
* the low 48 bits.
*/
static int validate_hw2_last(long value, struct module *me)
{
if (((value << 16) >> 16) != value) {
pr_warning("module %s: Out of range HW2_LAST value %#lx\n",
me->name, value);
return 0;
}
return 1;
}
/*
* Validate that "value" isn't too big to hold in a JumpOff relocation.
*/
static int validate_jumpoff(long value)
{
/* Determine size of jump offset. */
int shift = __builtin_clzl(get_JumpOff_X1(create_JumpOff_X1(-1)));
/* Check to see if it fits into the relocation slot. */
long f = get_JumpOff_X1(create_JumpOff_X1(value));
f = (f << shift) >> shift;
return f == value;
}
#endif
int apply_relocate_add(Elf_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me)
{
unsigned int i;
Elf_Rela *rel = (void *)sechdrs[relsec].sh_addr;
Elf_Sym *sym;
u64 *location;
unsigned long value;
DEBUGP("Applying relocate section %u to %u\n", relsec,
sechdrs[relsec].sh_info);
for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) {
/* This is where to make the change */
location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr
+ rel[i].r_offset;
/*
* This is the symbol it is referring to.
* Note that all undefined symbols have been resolved.
*/
sym = (Elf_Sym *)sechdrs[symindex].sh_addr
+ ELF_R_SYM(rel[i].r_info);
value = sym->st_value + rel[i].r_addend;
switch (ELF_R_TYPE(rel[i].r_info)) {
#define MUNGE(func) (*location = ((*location & ~func(-1)) | func(value)))
#ifndef __tilegx__
case R_TILE_32:
*(uint32_t *)location = value;
break;
case R_TILE_IMM16_X0_HA:
value = (value + 0x8000) >> 16;
/*FALLTHROUGH*/
case R_TILE_IMM16_X0_LO:
MUNGE(create_Imm16_X0);
break;
case R_TILE_IMM16_X1_HA:
value = (value + 0x8000) >> 16;
/*FALLTHROUGH*/
case R_TILE_IMM16_X1_LO:
MUNGE(create_Imm16_X1);
break;
case R_TILE_JOFFLONG_X1:
value -= (unsigned long) location; /* pc-relative */
value = (long) value >> 3; /* count by instrs */
MUNGE(create_JOffLong_X1);
break;
#else
case R_TILEGX_64:
*location = value;
break;
case R_TILEGX_IMM16_X0_HW2_LAST:
if (!validate_hw2_last(value, me))
return -ENOEXEC;
value >>= 16;
/*FALLTHROUGH*/
case R_TILEGX_IMM16_X0_HW1:
value >>= 16;
/*FALLTHROUGH*/
case R_TILEGX_IMM16_X0_HW0:
MUNGE(create_Imm16_X0);
break;
case R_TILEGX_IMM16_X1_HW2_LAST:
if (!validate_hw2_last(value, me))
return -ENOEXEC;
value >>= 16;
/*FALLTHROUGH*/
case R_TILEGX_IMM16_X1_HW1:
value >>= 16;
/*FALLTHROUGH*/
case R_TILEGX_IMM16_X1_HW0:
MUNGE(create_Imm16_X1);
break;
case R_TILEGX_JUMPOFF_X1:
value -= (unsigned long) location; /* pc-relative */
value = (long) value >> 3; /* count by instrs */
if (!validate_jumpoff(value)) {
pr_warning("module %s: Out of range jump to"
" %#llx at %#llx (%p)\n", me->name,
sym->st_value + rel[i].r_addend,
rel[i].r_offset, location);
return -ENOEXEC;
}
MUNGE(create_JumpOff_X1);
break;
#endif
#undef MUNGE
default:
pr_err("module %s: Unknown relocation: %d\n",
me->name, (int) ELF_R_TYPE(rel[i].r_info));
return -ENOEXEC;
}
}
return 0;
}
int module_finalize(const Elf_Ehdr *hdr,
const Elf_Shdr *sechdrs,
struct module *me)
{
/* FIXME: perhaps remove the "writable" bit from the TLB? */
return 0;
}
void module_arch_cleanup(struct module *mod)
{
}
| gpl-2.0 |
174high/compat_wl18xx_r8.5_linux3.2_beagleboneblack | drivers/media/i2c/bt856.c | 1669 | 6820 | /*
* bt856 - BT856A Digital Video Encoder (Rockwell Part)
*
* Copyright (C) 1999 Mike Bernson <mike@mlb.org>
* Copyright (C) 1998 Dave Perks <dperks@ibm.net>
*
* Modifications for LML33/DC10plus unified driver
* Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
*
* This code was modify/ported from the saa7111 driver written
* by Dave Perks.
*
* Changes by Ronald Bultje <rbultje@ronald.bitfreak.net>
* - moved over to linux>=2.4.x i2c protocol (9/9/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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/ioctl.h>
#include <asm/uaccess.h>
#include <linux/i2c.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
MODULE_DESCRIPTION("Brooktree-856A video encoder driver");
MODULE_AUTHOR("Mike Bernson & Dave Perks");
MODULE_LICENSE("GPL");
static int debug;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0-1)");
/* ----------------------------------------------------------------------- */
#define BT856_REG_OFFSET 0xDA
#define BT856_NR_REG 6
struct bt856 {
struct v4l2_subdev sd;
unsigned char reg[BT856_NR_REG];
v4l2_std_id norm;
};
static inline struct bt856 *to_bt856(struct v4l2_subdev *sd)
{
return container_of(sd, struct bt856, sd);
}
/* ----------------------------------------------------------------------- */
static inline int bt856_write(struct bt856 *encoder, u8 reg, u8 value)
{
struct i2c_client *client = v4l2_get_subdevdata(&encoder->sd);
encoder->reg[reg - BT856_REG_OFFSET] = value;
return i2c_smbus_write_byte_data(client, reg, value);
}
static inline int bt856_setbit(struct bt856 *encoder, u8 reg, u8 bit, u8 value)
{
return bt856_write(encoder, reg,
(encoder->reg[reg - BT856_REG_OFFSET] & ~(1 << bit)) |
(value ? (1 << bit) : 0));
}
static void bt856_dump(struct bt856 *encoder)
{
int i;
v4l2_info(&encoder->sd, "register dump:\n");
for (i = 0; i < BT856_NR_REG; i += 2)
printk(KERN_CONT " %02x", encoder->reg[i]);
printk(KERN_CONT "\n");
}
/* ----------------------------------------------------------------------- */
static int bt856_init(struct v4l2_subdev *sd, u32 arg)
{
struct bt856 *encoder = to_bt856(sd);
/* This is just for testing!!! */
v4l2_dbg(1, debug, sd, "init\n");
bt856_write(encoder, 0xdc, 0x18);
bt856_write(encoder, 0xda, 0);
bt856_write(encoder, 0xde, 0);
bt856_setbit(encoder, 0xdc, 3, 1);
/*bt856_setbit(encoder, 0xdc, 6, 0);*/
bt856_setbit(encoder, 0xdc, 4, 1);
if (encoder->norm & V4L2_STD_NTSC)
bt856_setbit(encoder, 0xdc, 2, 0);
else
bt856_setbit(encoder, 0xdc, 2, 1);
bt856_setbit(encoder, 0xdc, 1, 1);
bt856_setbit(encoder, 0xde, 4, 0);
bt856_setbit(encoder, 0xde, 3, 1);
if (debug != 0)
bt856_dump(encoder);
return 0;
}
static int bt856_s_std_output(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct bt856 *encoder = to_bt856(sd);
v4l2_dbg(1, debug, sd, "set norm %llx\n", (unsigned long long)std);
if (std & V4L2_STD_NTSC) {
bt856_setbit(encoder, 0xdc, 2, 0);
} else if (std & V4L2_STD_PAL) {
bt856_setbit(encoder, 0xdc, 2, 1);
bt856_setbit(encoder, 0xda, 0, 0);
/*bt856_setbit(encoder, 0xda, 0, 1);*/
} else {
return -EINVAL;
}
encoder->norm = std;
if (debug != 0)
bt856_dump(encoder);
return 0;
}
static int bt856_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct bt856 *encoder = to_bt856(sd);
v4l2_dbg(1, debug, sd, "set input %d\n", input);
/* We only have video bus.
* input= 0: input is from bt819
* input= 1: input is from ZR36060 */
switch (input) {
case 0:
bt856_setbit(encoder, 0xde, 4, 0);
bt856_setbit(encoder, 0xde, 3, 1);
bt856_setbit(encoder, 0xdc, 3, 1);
bt856_setbit(encoder, 0xdc, 6, 0);
break;
case 1:
bt856_setbit(encoder, 0xde, 4, 0);
bt856_setbit(encoder, 0xde, 3, 1);
bt856_setbit(encoder, 0xdc, 3, 1);
bt856_setbit(encoder, 0xdc, 6, 1);
break;
case 2: /* Color bar */
bt856_setbit(encoder, 0xdc, 3, 0);
bt856_setbit(encoder, 0xde, 4, 1);
break;
default:
return -EINVAL;
}
if (debug != 0)
bt856_dump(encoder);
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops bt856_core_ops = {
.init = bt856_init,
};
static const struct v4l2_subdev_video_ops bt856_video_ops = {
.s_std_output = bt856_s_std_output,
.s_routing = bt856_s_routing,
};
static const struct v4l2_subdev_ops bt856_ops = {
.core = &bt856_core_ops,
.video = &bt856_video_ops,
};
/* ----------------------------------------------------------------------- */
static int bt856_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct bt856 *encoder;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
encoder = devm_kzalloc(&client->dev, sizeof(*encoder), GFP_KERNEL);
if (encoder == NULL)
return -ENOMEM;
sd = &encoder->sd;
v4l2_i2c_subdev_init(sd, client, &bt856_ops);
encoder->norm = V4L2_STD_NTSC;
bt856_write(encoder, 0xdc, 0x18);
bt856_write(encoder, 0xda, 0);
bt856_write(encoder, 0xde, 0);
bt856_setbit(encoder, 0xdc, 3, 1);
/*bt856_setbit(encoder, 0xdc, 6, 0);*/
bt856_setbit(encoder, 0xdc, 4, 1);
if (encoder->norm & V4L2_STD_NTSC)
bt856_setbit(encoder, 0xdc, 2, 0);
else
bt856_setbit(encoder, 0xdc, 2, 1);
bt856_setbit(encoder, 0xdc, 1, 1);
bt856_setbit(encoder, 0xde, 4, 0);
bt856_setbit(encoder, 0xde, 3, 1);
if (debug != 0)
bt856_dump(encoder);
return 0;
}
static int bt856_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
v4l2_device_unregister_subdev(sd);
return 0;
}
static const struct i2c_device_id bt856_id[] = {
{ "bt856", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, bt856_id);
static struct i2c_driver bt856_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "bt856",
},
.probe = bt856_probe,
.remove = bt856_remove,
.id_table = bt856_id,
};
module_i2c_driver(bt856_driver);
| gpl-2.0 |
ErikAndren/linux | drivers/staging/rtl8723au/hal/rtl8723a_rxdesc.c | 1669 | 2220 | /******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
******************************************************************************/
#define _RTL8723A_REDESC_C_
#include <osdep_service.h>
#include <drv_types.h>
#include <rtl8723a_hal.h>
static void process_rssi(struct rtw_adapter *padapter,
struct recv_frame *prframe)
{
struct rx_pkt_attrib *pattrib = &prframe->attrib;
struct signal_stat *signal_stat = &padapter->recvpriv.signal_strength_data;
if (signal_stat->update_req) {
signal_stat->total_num = 0;
signal_stat->total_val = 0;
signal_stat->update_req = 0;
}
signal_stat->total_num++;
signal_stat->total_val += pattrib->phy_info.SignalStrength;
signal_stat->avg_val = signal_stat->total_val / signal_stat->total_num;
}
static void process_link_qual(struct rtw_adapter *padapter,
struct recv_frame *prframe)
{
struct rx_pkt_attrib *pattrib;
struct signal_stat *signal_stat;
if (prframe == NULL || padapter == NULL)
return;
pattrib = &prframe->attrib;
signal_stat = &padapter->recvpriv.signal_qual_data;
if (signal_stat->update_req) {
signal_stat->total_num = 0;
signal_stat->total_val = 0;
signal_stat->update_req = 0;
}
signal_stat->total_num++;
signal_stat->total_val += pattrib->phy_info.SignalQuality;
signal_stat->avg_val = signal_stat->total_val / signal_stat->total_num;
}
/* void rtl8723a_process_phy_info(struct rtw_adapter *padapter, union recv_frame *prframe) */
void rtl8723a_process_phy_info(struct rtw_adapter *padapter, void *prframe)
{
struct recv_frame *precvframe = prframe;
/* Check RSSI */
process_rssi(padapter, precvframe);
/* Check EVM */
process_link_qual(padapter, precvframe);
}
| gpl-2.0 |
Hive-Resurrection/kernel_htc_flounder | arch/sparc/kernel/smp_32.c | 1925 | 8015 | /* smp.c: Sparc SMP support.
*
* Copyright (C) 1996 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 2004 Keith M Wesolowski (wesolows@foobazco.org)
*/
#include <asm/head.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/threads.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/cache.h>
#include <linux/delay.h>
#include <linux/cpu.h>
#include <asm/ptrace.h>
#include <linux/atomic.h>
#include <asm/irq.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/oplib.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <asm/cpudata.h>
#include <asm/timer.h>
#include <asm/leon.h>
#include "kernel.h"
#include "irq.h"
volatile unsigned long cpu_callin_map[NR_CPUS] __cpuinitdata = {0,};
cpumask_t smp_commenced_mask = CPU_MASK_NONE;
const struct sparc32_ipi_ops *sparc32_ipi_ops;
/* The only guaranteed locking primitive available on all Sparc
* processors is 'ldstub [%reg + immediate], %dest_reg' which atomically
* places the current byte at the effective address into dest_reg and
* places 0xff there afterwards. Pretty lame locking primitive
* compared to the Alpha and the Intel no? Most Sparcs have 'swap'
* instruction which is much better...
*/
void __cpuinit smp_store_cpu_info(int id)
{
int cpu_node;
int mid;
cpu_data(id).udelay_val = loops_per_jiffy;
cpu_find_by_mid(id, &cpu_node);
cpu_data(id).clock_tick = prom_getintdefault(cpu_node,
"clock-frequency", 0);
cpu_data(id).prom_node = cpu_node;
mid = cpu_get_hwmid(cpu_node);
if (mid < 0) {
printk(KERN_NOTICE "No MID found for CPU%d at node 0x%08d", id, cpu_node);
mid = 0;
}
cpu_data(id).mid = mid;
}
void __init smp_cpus_done(unsigned int max_cpus)
{
extern void smp4m_smp_done(void);
extern void smp4d_smp_done(void);
unsigned long bogosum = 0;
int cpu, num = 0;
for_each_online_cpu(cpu) {
num++;
bogosum += cpu_data(cpu).udelay_val;
}
printk("Total of %d processors activated (%lu.%02lu BogoMIPS).\n",
num, bogosum/(500000/HZ),
(bogosum/(5000/HZ))%100);
switch(sparc_cpu_model) {
case sun4m:
smp4m_smp_done();
break;
case sun4d:
smp4d_smp_done();
break;
case sparc_leon:
leon_smp_done();
break;
case sun4e:
printk("SUN4E\n");
BUG();
break;
case sun4u:
printk("SUN4U\n");
BUG();
break;
default:
printk("UNKNOWN!\n");
BUG();
break;
}
}
void cpu_panic(void)
{
printk("CPU[%d]: Returns from cpu_idle!\n", smp_processor_id());
panic("SMP bolixed\n");
}
struct linux_prom_registers smp_penguin_ctable __cpuinitdata = { 0 };
void smp_send_reschedule(int cpu)
{
/*
* CPU model dependent way of implementing IPI generation targeting
* a single CPU. The trap handler needs only to do trap entry/return
* to call schedule.
*/
sparc32_ipi_ops->resched(cpu);
}
void smp_send_stop(void)
{
}
void arch_send_call_function_single_ipi(int cpu)
{
/* trigger one IPI single call on one CPU */
sparc32_ipi_ops->single(cpu);
}
void arch_send_call_function_ipi_mask(const struct cpumask *mask)
{
int cpu;
/* trigger IPI mask call on each CPU */
for_each_cpu(cpu, mask)
sparc32_ipi_ops->mask_one(cpu);
}
void smp_resched_interrupt(void)
{
irq_enter();
scheduler_ipi();
local_cpu_data().irq_resched_count++;
irq_exit();
/* re-schedule routine called by interrupt return code. */
}
void smp_call_function_single_interrupt(void)
{
irq_enter();
generic_smp_call_function_single_interrupt();
local_cpu_data().irq_call_count++;
irq_exit();
}
void smp_call_function_interrupt(void)
{
irq_enter();
generic_smp_call_function_interrupt();
local_cpu_data().irq_call_count++;
irq_exit();
}
int setup_profiling_timer(unsigned int multiplier)
{
return -EINVAL;
}
void __init smp_prepare_cpus(unsigned int max_cpus)
{
extern void __init smp4m_boot_cpus(void);
extern void __init smp4d_boot_cpus(void);
int i, cpuid, extra;
printk("Entering SMP Mode...\n");
extra = 0;
for (i = 0; !cpu_find_by_instance(i, NULL, &cpuid); i++) {
if (cpuid >= NR_CPUS)
extra++;
}
/* i = number of cpus */
if (extra && max_cpus > i - extra)
printk("Warning: NR_CPUS is too low to start all cpus\n");
smp_store_cpu_info(boot_cpu_id);
switch(sparc_cpu_model) {
case sun4m:
smp4m_boot_cpus();
break;
case sun4d:
smp4d_boot_cpus();
break;
case sparc_leon:
leon_boot_cpus();
break;
case sun4e:
printk("SUN4E\n");
BUG();
break;
case sun4u:
printk("SUN4U\n");
BUG();
break;
default:
printk("UNKNOWN!\n");
BUG();
break;
}
}
/* Set this up early so that things like the scheduler can init
* properly. We use the same cpu mask for both the present and
* possible cpu map.
*/
void __init smp_setup_cpu_possible_map(void)
{
int instance, mid;
instance = 0;
while (!cpu_find_by_instance(instance, NULL, &mid)) {
if (mid < NR_CPUS) {
set_cpu_possible(mid, true);
set_cpu_present(mid, true);
}
instance++;
}
}
void __init smp_prepare_boot_cpu(void)
{
int cpuid = hard_smp_processor_id();
if (cpuid >= NR_CPUS) {
prom_printf("Serious problem, boot cpu id >= NR_CPUS\n");
prom_halt();
}
if (cpuid != 0)
printk("boot cpu id != 0, this could work but is untested\n");
current_thread_info()->cpu = cpuid;
set_cpu_online(cpuid, true);
set_cpu_possible(cpuid, true);
}
int __cpuinit __cpu_up(unsigned int cpu, struct task_struct *tidle)
{
extern int __cpuinit smp4m_boot_one_cpu(int, struct task_struct *);
extern int __cpuinit smp4d_boot_one_cpu(int, struct task_struct *);
int ret=0;
switch(sparc_cpu_model) {
case sun4m:
ret = smp4m_boot_one_cpu(cpu, tidle);
break;
case sun4d:
ret = smp4d_boot_one_cpu(cpu, tidle);
break;
case sparc_leon:
ret = leon_boot_one_cpu(cpu, tidle);
break;
case sun4e:
printk("SUN4E\n");
BUG();
break;
case sun4u:
printk("SUN4U\n");
BUG();
break;
default:
printk("UNKNOWN!\n");
BUG();
break;
}
if (!ret) {
cpumask_set_cpu(cpu, &smp_commenced_mask);
while (!cpu_online(cpu))
mb();
}
return ret;
}
void __cpuinit arch_cpu_pre_starting(void *arg)
{
local_ops->cache_all();
local_ops->tlb_all();
switch(sparc_cpu_model) {
case sun4m:
sun4m_cpu_pre_starting(arg);
break;
case sun4d:
sun4d_cpu_pre_starting(arg);
break;
case sparc_leon:
leon_cpu_pre_starting(arg);
break;
default:
BUG();
}
}
void __cpuinit arch_cpu_pre_online(void *arg)
{
unsigned int cpuid = hard_smp_processor_id();
register_percpu_ce(cpuid);
calibrate_delay();
smp_store_cpu_info(cpuid);
local_ops->cache_all();
local_ops->tlb_all();
switch(sparc_cpu_model) {
case sun4m:
sun4m_cpu_pre_online(arg);
break;
case sun4d:
sun4d_cpu_pre_online(arg);
break;
case sparc_leon:
leon_cpu_pre_online(arg);
break;
default:
BUG();
}
}
void __cpuinit sparc_start_secondary(void *arg)
{
unsigned int cpu;
/*
* SMP booting is extremely fragile in some architectures. So run
* the cpu initialization code first before anything else.
*/
arch_cpu_pre_starting(arg);
preempt_disable();
cpu = smp_processor_id();
/* Invoke the CPU_STARTING notifier callbacks */
notify_cpu_starting(cpu);
arch_cpu_pre_online(arg);
/* Set the CPU in the cpu_online_mask */
set_cpu_online(cpu, true);
/* Enable local interrupts now */
local_irq_enable();
wmb();
cpu_startup_entry(CPUHP_ONLINE);
/* We should never reach here! */
BUG();
}
void __cpuinit smp_callin(void)
{
sparc_start_secondary(NULL);
}
void smp_bogo(struct seq_file *m)
{
int i;
for_each_online_cpu(i) {
seq_printf(m,
"Cpu%dBogo\t: %lu.%02lu\n",
i,
cpu_data(i).udelay_val/(500000/HZ),
(cpu_data(i).udelay_val/(5000/HZ))%100);
}
}
void smp_info(struct seq_file *m)
{
int i;
seq_printf(m, "State:\n");
for_each_online_cpu(i)
seq_printf(m, "CPU%d\t\t: online\n", i);
}
| gpl-2.0 |
garyd9/linux_kernel_sgh-i317 | arch/x86/kernel/apic/bigsmp_32.c | 2437 | 6551 | /*
* APIC driver for "bigsmp" xAPIC machines with more than 8 virtual CPUs.
*
* Drives the local APIC in "clustered mode".
*/
#include <linux/threads.h>
#include <linux/cpumask.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/dmi.h>
#include <linux/smp.h>
#include <asm/apicdef.h>
#include <asm/fixmap.h>
#include <asm/mpspec.h>
#include <asm/apic.h>
#include <asm/ipi.h>
static unsigned bigsmp_get_apic_id(unsigned long x)
{
return (x >> 24) & 0xFF;
}
static int bigsmp_apic_id_registered(void)
{
return 1;
}
static const struct cpumask *bigsmp_target_cpus(void)
{
#ifdef CONFIG_SMP
return cpu_online_mask;
#else
return cpumask_of(0);
#endif
}
static unsigned long bigsmp_check_apicid_used(physid_mask_t *map, int apicid)
{
return 0;
}
static unsigned long bigsmp_check_apicid_present(int bit)
{
return 1;
}
static int bigsmp_early_logical_apicid(int cpu)
{
/* on bigsmp, logical apicid is the same as physical */
return early_per_cpu(x86_cpu_to_apicid, cpu);
}
static inline unsigned long calculate_ldr(int cpu)
{
unsigned long val, id;
val = apic_read(APIC_LDR) & ~APIC_LDR_MASK;
id = per_cpu(x86_bios_cpu_apicid, cpu);
val |= SET_APIC_LOGICAL_ID(id);
return val;
}
/*
* Set up the logical destination ID.
*
* Intel recommends to set DFR, LDR and TPR before enabling
* an APIC. See e.g. "AP-388 82489DX User's Manual" (Intel
* document number 292116). So here it goes...
*/
static void bigsmp_init_apic_ldr(void)
{
unsigned long val;
int cpu = smp_processor_id();
apic_write(APIC_DFR, APIC_DFR_FLAT);
val = calculate_ldr(cpu);
apic_write(APIC_LDR, val);
}
static void bigsmp_setup_apic_routing(void)
{
printk(KERN_INFO
"Enabling APIC mode: Physflat. Using %d I/O APICs\n",
nr_ioapics);
}
static int bigsmp_cpu_present_to_apicid(int mps_cpu)
{
if (mps_cpu < nr_cpu_ids)
return (int) per_cpu(x86_bios_cpu_apicid, mps_cpu);
return BAD_APICID;
}
static void bigsmp_ioapic_phys_id_map(physid_mask_t *phys_map, physid_mask_t *retmap)
{
/* For clustered we don't have a good way to do this yet - hack */
physids_promote(0xFFL, retmap);
}
static int bigsmp_check_phys_apicid_present(int phys_apicid)
{
return 1;
}
/* As we are using single CPU as destination, pick only one CPU here */
static unsigned int bigsmp_cpu_mask_to_apicid(const struct cpumask *cpumask)
{
int cpu = cpumask_first(cpumask);
if (cpu < nr_cpu_ids)
return cpu_physical_id(cpu);
return BAD_APICID;
}
static unsigned int bigsmp_cpu_mask_to_apicid_and(const struct cpumask *cpumask,
const struct cpumask *andmask)
{
int cpu;
/*
* We're using fixed IRQ delivery, can only return one phys APIC ID.
* May as well be the first.
*/
for_each_cpu_and(cpu, cpumask, andmask) {
if (cpumask_test_cpu(cpu, cpu_online_mask))
return cpu_physical_id(cpu);
}
return BAD_APICID;
}
static int bigsmp_phys_pkg_id(int cpuid_apic, int index_msb)
{
return cpuid_apic >> index_msb;
}
static inline void bigsmp_send_IPI_mask(const struct cpumask *mask, int vector)
{
default_send_IPI_mask_sequence_phys(mask, vector);
}
static void bigsmp_send_IPI_allbutself(int vector)
{
default_send_IPI_mask_allbutself_phys(cpu_online_mask, vector);
}
static void bigsmp_send_IPI_all(int vector)
{
bigsmp_send_IPI_mask(cpu_online_mask, vector);
}
static int dmi_bigsmp; /* can be set by dmi scanners */
static int hp_ht_bigsmp(const struct dmi_system_id *d)
{
printk(KERN_NOTICE "%s detected: force use of apic=bigsmp\n", d->ident);
dmi_bigsmp = 1;
return 0;
}
static const struct dmi_system_id bigsmp_dmi_table[] = {
{ hp_ht_bigsmp, "HP ProLiant DL760 G2",
{ DMI_MATCH(DMI_BIOS_VENDOR, "HP"),
DMI_MATCH(DMI_BIOS_VERSION, "P44-"),
}
},
{ hp_ht_bigsmp, "HP ProLiant DL740",
{ DMI_MATCH(DMI_BIOS_VENDOR, "HP"),
DMI_MATCH(DMI_BIOS_VERSION, "P47-"),
}
},
{ } /* NULL entry stops DMI scanning */
};
static void bigsmp_vector_allocation_domain(int cpu, struct cpumask *retmask)
{
cpumask_clear(retmask);
cpumask_set_cpu(cpu, retmask);
}
static int probe_bigsmp(void)
{
if (def_to_bigsmp)
dmi_bigsmp = 1;
else
dmi_check_system(bigsmp_dmi_table);
return dmi_bigsmp;
}
static struct apic apic_bigsmp = {
.name = "bigsmp",
.probe = probe_bigsmp,
.acpi_madt_oem_check = NULL,
.apic_id_registered = bigsmp_apic_id_registered,
.irq_delivery_mode = dest_Fixed,
/* phys delivery to target CPU: */
.irq_dest_mode = 0,
.target_cpus = bigsmp_target_cpus,
.disable_esr = 1,
.dest_logical = 0,
.check_apicid_used = bigsmp_check_apicid_used,
.check_apicid_present = bigsmp_check_apicid_present,
.vector_allocation_domain = bigsmp_vector_allocation_domain,
.init_apic_ldr = bigsmp_init_apic_ldr,
.ioapic_phys_id_map = bigsmp_ioapic_phys_id_map,
.setup_apic_routing = bigsmp_setup_apic_routing,
.multi_timer_check = NULL,
.cpu_present_to_apicid = bigsmp_cpu_present_to_apicid,
.apicid_to_cpu_present = physid_set_mask_of_physid,
.setup_portio_remap = NULL,
.check_phys_apicid_present = bigsmp_check_phys_apicid_present,
.enable_apic_mode = NULL,
.phys_pkg_id = bigsmp_phys_pkg_id,
.mps_oem_check = NULL,
.get_apic_id = bigsmp_get_apic_id,
.set_apic_id = NULL,
.apic_id_mask = 0xFF << 24,
.cpu_mask_to_apicid = bigsmp_cpu_mask_to_apicid,
.cpu_mask_to_apicid_and = bigsmp_cpu_mask_to_apicid_and,
.send_IPI_mask = bigsmp_send_IPI_mask,
.send_IPI_mask_allbutself = NULL,
.send_IPI_allbutself = bigsmp_send_IPI_allbutself,
.send_IPI_all = bigsmp_send_IPI_all,
.send_IPI_self = default_send_IPI_self,
.trampoline_phys_low = DEFAULT_TRAMPOLINE_PHYS_LOW,
.trampoline_phys_high = DEFAULT_TRAMPOLINE_PHYS_HIGH,
.wait_for_init_deassert = default_wait_for_init_deassert,
.smp_callin_clear_local_apic = NULL,
.inquire_remote_apic = default_inquire_remote_apic,
.read = native_apic_mem_read,
.write = native_apic_mem_write,
.icr_read = native_apic_icr_read,
.icr_write = native_apic_icr_write,
.wait_icr_idle = native_apic_wait_icr_idle,
.safe_wait_icr_idle = native_safe_apic_wait_icr_idle,
.x86_32_early_logical_apicid = bigsmp_early_logical_apicid,
};
void __init generic_bigsmp_probe(void)
{
unsigned int cpu;
if (!probe_bigsmp())
return;
apic = &apic_bigsmp;
for_each_possible_cpu(cpu) {
if (early_per_cpu(x86_cpu_to_logical_apicid,
cpu) == BAD_APICID)
continue;
early_per_cpu(x86_cpu_to_logical_apicid, cpu) =
bigsmp_early_logical_apicid(cpu);
}
pr_info("Overriding APIC driver with %s\n", apic_bigsmp.name);
}
apic_driver(apic_bigsmp);
| gpl-2.0 |
itsmerajit/Samsung_j2 | arch/arm/mach-imx/devices/platform-mxc_pwm.c | 2693 | 2086 | /*
* Copyright (C) 2009-2010 Pengutronix
* Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*/
#include "../hardware.h"
#include "devices-common.h"
#define imx_mxc_pwm_data_entry_single(soc, _id, _hwid, _size) \
{ \
.id = _id, \
.iobase = soc ## _PWM ## _hwid ## _BASE_ADDR, \
.iosize = _size, \
.irq = soc ## _INT_PWM ## _hwid, \
}
#define imx_mxc_pwm_data_entry(soc, _id, _hwid, _size) \
[_id] = imx_mxc_pwm_data_entry_single(soc, _id, _hwid, _size)
#ifdef CONFIG_SOC_IMX21
const struct imx_mxc_pwm_data imx21_mxc_pwm_data __initconst =
imx_mxc_pwm_data_entry_single(MX21, 0, , SZ_4K);
#endif /* ifdef CONFIG_SOC_IMX21 */
#ifdef CONFIG_SOC_IMX25
const struct imx_mxc_pwm_data imx25_mxc_pwm_data[] __initconst = {
#define imx25_mxc_pwm_data_entry(_id, _hwid) \
imx_mxc_pwm_data_entry(MX25, _id, _hwid, SZ_16K)
imx25_mxc_pwm_data_entry(0, 1),
imx25_mxc_pwm_data_entry(1, 2),
imx25_mxc_pwm_data_entry(2, 3),
imx25_mxc_pwm_data_entry(3, 4),
};
#endif /* ifdef CONFIG_SOC_IMX25 */
#ifdef CONFIG_SOC_IMX27
const struct imx_mxc_pwm_data imx27_mxc_pwm_data __initconst =
imx_mxc_pwm_data_entry_single(MX27, 0, , SZ_4K);
#endif /* ifdef CONFIG_SOC_IMX27 */
#ifdef CONFIG_SOC_IMX51
const struct imx_mxc_pwm_data imx51_mxc_pwm_data[] __initconst = {
#define imx51_mxc_pwm_data_entry(_id, _hwid) \
imx_mxc_pwm_data_entry(MX51, _id, _hwid, SZ_16K)
imx51_mxc_pwm_data_entry(0, 1),
imx51_mxc_pwm_data_entry(1, 2),
};
#endif /* ifdef CONFIG_SOC_IMX51 */
struct platform_device *__init imx_add_mxc_pwm(
const struct imx_mxc_pwm_data *data)
{
struct resource res[] = {
{
.start = data->iobase,
.end = data->iobase + data->iosize - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irq,
.end = data->irq,
.flags = IORESOURCE_IRQ,
},
};
return imx_add_platform_device("mxc_pwm", data->id,
res, ARRAY_SIZE(res), NULL, 0);
}
| gpl-2.0 |
santod/google_kernel_m7_3.4.10-g1a25406 | drivers/power/ab8500_charger.c | 4741 | 76012 | /*
* Copyright (C) ST-Ericsson SA 2012
*
* Charger driver for AB8500
*
* License Terms: GNU General Public License v2
* Author:
* Johan Palsson <johan.palsson@stericsson.com>
* Karl Komierowski <karl.komierowski@stericsson.com>
* Arun R Murthy <arun.murthy@stericsson.com>
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/completion.h>
#include <linux/regulator/consumer.h>
#include <linux/err.h>
#include <linux/workqueue.h>
#include <linux/kobject.h>
#include <linux/mfd/abx500/ab8500.h>
#include <linux/mfd/abx500.h>
#include <linux/mfd/abx500/ab8500-bm.h>
#include <linux/mfd/abx500/ab8500-gpadc.h>
#include <linux/mfd/abx500/ux500_chargalg.h>
#include <linux/usb/otg.h>
/* Charger constants */
#define NO_PW_CONN 0
#define AC_PW_CONN 1
#define USB_PW_CONN 2
#define MAIN_WDOG_ENA 0x01
#define MAIN_WDOG_KICK 0x02
#define MAIN_WDOG_DIS 0x00
#define CHARG_WD_KICK 0x01
#define MAIN_CH_ENA 0x01
#define MAIN_CH_NO_OVERSHOOT_ENA_N 0x02
#define USB_CH_ENA 0x01
#define USB_CHG_NO_OVERSHOOT_ENA_N 0x02
#define MAIN_CH_DET 0x01
#define MAIN_CH_CV_ON 0x04
#define USB_CH_CV_ON 0x08
#define VBUS_DET_DBNC100 0x02
#define VBUS_DET_DBNC1 0x01
#define OTP_ENABLE_WD 0x01
#define MAIN_CH_INPUT_CURR_SHIFT 4
#define VBUS_IN_CURR_LIM_SHIFT 4
#define LED_INDICATOR_PWM_ENA 0x01
#define LED_INDICATOR_PWM_DIS 0x00
#define LED_IND_CUR_5MA 0x04
#define LED_INDICATOR_PWM_DUTY_252_256 0xBF
/* HW failure constants */
#define MAIN_CH_TH_PROT 0x02
#define VBUS_CH_NOK 0x08
#define USB_CH_TH_PROT 0x02
#define VBUS_OVV_TH 0x01
#define MAIN_CH_NOK 0x01
#define VBUS_DET 0x80
/* UsbLineStatus register bit masks */
#define AB8500_USB_LINK_STATUS 0x78
#define AB8500_STD_HOST_SUSP 0x18
/* Watchdog timeout constant */
#define WD_TIMER 0x30 /* 4min */
#define WD_KICK_INTERVAL (60 * HZ)
/* Lowest charger voltage is 3.39V -> 0x4E */
#define LOW_VOLT_REG 0x4E
/* UsbLineStatus register - usb types */
enum ab8500_charger_link_status {
USB_STAT_NOT_CONFIGURED,
USB_STAT_STD_HOST_NC,
USB_STAT_STD_HOST_C_NS,
USB_STAT_STD_HOST_C_S,
USB_STAT_HOST_CHG_NM,
USB_STAT_HOST_CHG_HS,
USB_STAT_HOST_CHG_HS_CHIRP,
USB_STAT_DEDICATED_CHG,
USB_STAT_ACA_RID_A,
USB_STAT_ACA_RID_B,
USB_STAT_ACA_RID_C_NM,
USB_STAT_ACA_RID_C_HS,
USB_STAT_ACA_RID_C_HS_CHIRP,
USB_STAT_HM_IDGND,
USB_STAT_RESERVED,
USB_STAT_NOT_VALID_LINK,
};
enum ab8500_usb_state {
AB8500_BM_USB_STATE_RESET_HS, /* HighSpeed Reset */
AB8500_BM_USB_STATE_RESET_FS, /* FullSpeed/LowSpeed Reset */
AB8500_BM_USB_STATE_CONFIGURED,
AB8500_BM_USB_STATE_SUSPEND,
AB8500_BM_USB_STATE_RESUME,
AB8500_BM_USB_STATE_MAX,
};
/* VBUS input current limits supported in AB8500 in mA */
#define USB_CH_IP_CUR_LVL_0P05 50
#define USB_CH_IP_CUR_LVL_0P09 98
#define USB_CH_IP_CUR_LVL_0P19 193
#define USB_CH_IP_CUR_LVL_0P29 290
#define USB_CH_IP_CUR_LVL_0P38 380
#define USB_CH_IP_CUR_LVL_0P45 450
#define USB_CH_IP_CUR_LVL_0P5 500
#define USB_CH_IP_CUR_LVL_0P6 600
#define USB_CH_IP_CUR_LVL_0P7 700
#define USB_CH_IP_CUR_LVL_0P8 800
#define USB_CH_IP_CUR_LVL_0P9 900
#define USB_CH_IP_CUR_LVL_1P0 1000
#define USB_CH_IP_CUR_LVL_1P1 1100
#define USB_CH_IP_CUR_LVL_1P3 1300
#define USB_CH_IP_CUR_LVL_1P4 1400
#define USB_CH_IP_CUR_LVL_1P5 1500
#define VBAT_TRESH_IP_CUR_RED 3800
#define to_ab8500_charger_usb_device_info(x) container_of((x), \
struct ab8500_charger, usb_chg)
#define to_ab8500_charger_ac_device_info(x) container_of((x), \
struct ab8500_charger, ac_chg)
/**
* struct ab8500_charger_interrupts - ab8500 interupts
* @name: name of the interrupt
* @isr function pointer to the isr
*/
struct ab8500_charger_interrupts {
char *name;
irqreturn_t (*isr)(int irq, void *data);
};
struct ab8500_charger_info {
int charger_connected;
int charger_online;
int charger_voltage;
int cv_active;
bool wd_expired;
};
struct ab8500_charger_event_flags {
bool mainextchnotok;
bool main_thermal_prot;
bool usb_thermal_prot;
bool vbus_ovv;
bool usbchargernotok;
bool chgwdexp;
bool vbus_collapse;
};
struct ab8500_charger_usb_state {
bool usb_changed;
int usb_current;
enum ab8500_usb_state state;
spinlock_t usb_lock;
};
/**
* struct ab8500_charger - ab8500 Charger device information
* @dev: Pointer to the structure device
* @max_usb_in_curr: Max USB charger input current
* @vbus_detected: VBUS detected
* @vbus_detected_start:
* VBUS detected during startup
* @ac_conn: This will be true when the AC charger has been plugged
* @vddadc_en_ac: Indicate if VDD ADC supply is enabled because AC
* charger is enabled
* @vddadc_en_usb: Indicate if VDD ADC supply is enabled because USB
* charger is enabled
* @vbat Battery voltage
* @old_vbat Previously measured battery voltage
* @autopower Indicate if we should have automatic pwron after pwrloss
* @parent: Pointer to the struct ab8500
* @gpadc: Pointer to the struct gpadc
* @pdata: Pointer to the abx500_charger platform data
* @bat: Pointer to the abx500_bm platform data
* @flags: Structure for information about events triggered
* @usb_state: Structure for usb stack information
* @ac_chg: AC charger power supply
* @usb_chg: USB charger power supply
* @ac: Structure that holds the AC charger properties
* @usb: Structure that holds the USB charger properties
* @regu: Pointer to the struct regulator
* @charger_wq: Work queue for the IRQs and checking HW state
* @check_vbat_work Work for checking vbat threshold to adjust vbus current
* @check_hw_failure_work: Work for checking HW state
* @check_usbchgnotok_work: Work for checking USB charger not ok status
* @kick_wd_work: Work for kicking the charger watchdog in case
* of ABB rev 1.* due to the watchog logic bug
* @ac_work: Work for checking AC charger connection
* @detect_usb_type_work: Work for detecting the USB type connected
* @usb_link_status_work: Work for checking the new USB link status
* @usb_state_changed_work: Work for checking USB state
* @check_main_thermal_prot_work:
* Work for checking Main thermal status
* @check_usb_thermal_prot_work:
* Work for checking USB thermal status
*/
struct ab8500_charger {
struct device *dev;
int max_usb_in_curr;
bool vbus_detected;
bool vbus_detected_start;
bool ac_conn;
bool vddadc_en_ac;
bool vddadc_en_usb;
int vbat;
int old_vbat;
bool autopower;
struct ab8500 *parent;
struct ab8500_gpadc *gpadc;
struct abx500_charger_platform_data *pdata;
struct abx500_bm_data *bat;
struct ab8500_charger_event_flags flags;
struct ab8500_charger_usb_state usb_state;
struct ux500_charger ac_chg;
struct ux500_charger usb_chg;
struct ab8500_charger_info ac;
struct ab8500_charger_info usb;
struct regulator *regu;
struct workqueue_struct *charger_wq;
struct delayed_work check_vbat_work;
struct delayed_work check_hw_failure_work;
struct delayed_work check_usbchgnotok_work;
struct delayed_work kick_wd_work;
struct work_struct ac_work;
struct work_struct detect_usb_type_work;
struct work_struct usb_link_status_work;
struct work_struct usb_state_changed_work;
struct work_struct check_main_thermal_prot_work;
struct work_struct check_usb_thermal_prot_work;
struct usb_phy *usb_phy;
struct notifier_block nb;
};
/* AC properties */
static enum power_supply_property ab8500_charger_ac_props[] = {
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_CURRENT_NOW,
};
/* USB properties */
static enum power_supply_property ab8500_charger_usb_props[] = {
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_CURRENT_NOW,
};
/**
* ab8500_power_loss_handling - set how we handle powerloss.
* @di: pointer to the ab8500_charger structure
*
* Magic nummbers are from STE HW department.
*/
static void ab8500_power_loss_handling(struct ab8500_charger *di)
{
u8 reg;
int ret;
dev_dbg(di->dev, "Autopower : %d\n", di->autopower);
/* read the autopower register */
ret = abx500_get_register_interruptible(di->dev, 0x15, 0x00, ®);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
/* enable the OPT emulation registers */
ret = abx500_set_register_interruptible(di->dev, 0x11, 0x00, 0x2);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
if (di->autopower)
reg |= 0x8;
else
reg &= ~0x8;
/* write back the changed value to autopower reg */
ret = abx500_set_register_interruptible(di->dev, 0x15, 0x00, reg);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
/* disable the set OTP registers again */
ret = abx500_set_register_interruptible(di->dev, 0x11, 0x00, 0x0);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
}
/**
* ab8500_power_supply_changed - a wrapper with local extentions for
* power_supply_changed
* @di: pointer to the ab8500_charger structure
* @psy: pointer to power_supply_that have changed.
*
*/
static void ab8500_power_supply_changed(struct ab8500_charger *di,
struct power_supply *psy)
{
if (di->pdata->autopower_cfg) {
if (!di->usb.charger_connected &&
!di->ac.charger_connected &&
di->autopower) {
di->autopower = false;
ab8500_power_loss_handling(di);
} else if (!di->autopower &&
(di->ac.charger_connected ||
di->usb.charger_connected)) {
di->autopower = true;
ab8500_power_loss_handling(di);
}
}
power_supply_changed(psy);
}
static void ab8500_charger_set_usb_connected(struct ab8500_charger *di,
bool connected)
{
if (connected != di->usb.charger_connected) {
dev_dbg(di->dev, "USB connected:%i\n", connected);
di->usb.charger_connected = connected;
sysfs_notify(&di->usb_chg.psy.dev->kobj, NULL, "present");
}
}
/**
* ab8500_charger_get_ac_voltage() - get ac charger voltage
* @di: pointer to the ab8500_charger structure
*
* Returns ac charger voltage (on success)
*/
static int ab8500_charger_get_ac_voltage(struct ab8500_charger *di)
{
int vch;
/* Only measure voltage if the charger is connected */
if (di->ac.charger_connected) {
vch = ab8500_gpadc_convert(di->gpadc, MAIN_CHARGER_V);
if (vch < 0)
dev_err(di->dev, "%s gpadc conv failed,\n", __func__);
} else {
vch = 0;
}
return vch;
}
/**
* ab8500_charger_ac_cv() - check if the main charger is in CV mode
* @di: pointer to the ab8500_charger structure
*
* Returns ac charger CV mode (on success) else error code
*/
static int ab8500_charger_ac_cv(struct ab8500_charger *di)
{
u8 val;
int ret = 0;
/* Only check CV mode if the charger is online */
if (di->ac.charger_online) {
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_STATUS1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return 0;
}
if (val & MAIN_CH_CV_ON)
ret = 1;
else
ret = 0;
}
return ret;
}
/**
* ab8500_charger_get_vbus_voltage() - get vbus voltage
* @di: pointer to the ab8500_charger structure
*
* This function returns the vbus voltage.
* Returns vbus voltage (on success)
*/
static int ab8500_charger_get_vbus_voltage(struct ab8500_charger *di)
{
int vch;
/* Only measure voltage if the charger is connected */
if (di->usb.charger_connected) {
vch = ab8500_gpadc_convert(di->gpadc, VBUS_V);
if (vch < 0)
dev_err(di->dev, "%s gpadc conv failed\n", __func__);
} else {
vch = 0;
}
return vch;
}
/**
* ab8500_charger_get_usb_current() - get usb charger current
* @di: pointer to the ab8500_charger structure
*
* This function returns the usb charger current.
* Returns usb current (on success) and error code on failure
*/
static int ab8500_charger_get_usb_current(struct ab8500_charger *di)
{
int ich;
/* Only measure current if the charger is online */
if (di->usb.charger_online) {
ich = ab8500_gpadc_convert(di->gpadc, USB_CHARGER_C);
if (ich < 0)
dev_err(di->dev, "%s gpadc conv failed\n", __func__);
} else {
ich = 0;
}
return ich;
}
/**
* ab8500_charger_get_ac_current() - get ac charger current
* @di: pointer to the ab8500_charger structure
*
* This function returns the ac charger current.
* Returns ac current (on success) and error code on failure.
*/
static int ab8500_charger_get_ac_current(struct ab8500_charger *di)
{
int ich;
/* Only measure current if the charger is online */
if (di->ac.charger_online) {
ich = ab8500_gpadc_convert(di->gpadc, MAIN_CHARGER_C);
if (ich < 0)
dev_err(di->dev, "%s gpadc conv failed\n", __func__);
} else {
ich = 0;
}
return ich;
}
/**
* ab8500_charger_usb_cv() - check if the usb charger is in CV mode
* @di: pointer to the ab8500_charger structure
*
* Returns ac charger CV mode (on success) else error code
*/
static int ab8500_charger_usb_cv(struct ab8500_charger *di)
{
int ret;
u8 val;
/* Only check CV mode if the charger is online */
if (di->usb.charger_online) {
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_USBCH_STAT1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return 0;
}
if (val & USB_CH_CV_ON)
ret = 1;
else
ret = 0;
} else {
ret = 0;
}
return ret;
}
/**
* ab8500_charger_detect_chargers() - Detect the connected chargers
* @di: pointer to the ab8500_charger structure
*
* Returns the type of charger connected.
* For USB it will not mean we can actually charge from it
* but that there is a USB cable connected that we have to
* identify. This is used during startup when we don't get
* interrupts of the charger detection
*
* Returns an integer value, that means,
* NO_PW_CONN no power supply is connected
* AC_PW_CONN if the AC power supply is connected
* USB_PW_CONN if the USB power supply is connected
* AC_PW_CONN + USB_PW_CONN if USB and AC power supplies are both connected
*/
static int ab8500_charger_detect_chargers(struct ab8500_charger *di)
{
int result = NO_PW_CONN;
int ret;
u8 val;
/* Check for AC charger */
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_STATUS1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
if (val & MAIN_CH_DET)
result = AC_PW_CONN;
/* Check for USB charger */
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_USBCH_STAT1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
if ((val & VBUS_DET_DBNC1) && (val & VBUS_DET_DBNC100))
result |= USB_PW_CONN;
return result;
}
/**
* ab8500_charger_max_usb_curr() - get the max curr for the USB type
* @di: pointer to the ab8500_charger structure
* @link_status: the identified USB type
*
* Get the maximum current that is allowed to be drawn from the host
* based on the USB type.
* Returns error code in case of failure else 0 on success
*/
static int ab8500_charger_max_usb_curr(struct ab8500_charger *di,
enum ab8500_charger_link_status link_status)
{
int ret = 0;
switch (link_status) {
case USB_STAT_STD_HOST_NC:
case USB_STAT_STD_HOST_C_NS:
case USB_STAT_STD_HOST_C_S:
dev_dbg(di->dev, "USB Type - Standard host is "
"detected through USB driver\n");
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P09;
break;
case USB_STAT_HOST_CHG_HS_CHIRP:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P5;
break;
case USB_STAT_HOST_CHG_HS:
case USB_STAT_ACA_RID_C_HS:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P9;
break;
case USB_STAT_ACA_RID_A:
/*
* Dedicated charger level minus maximum current accessory
* can consume (300mA). Closest level is 1100mA
*/
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_1P1;
break;
case USB_STAT_ACA_RID_B:
/*
* Dedicated charger level minus 120mA (20mA for ACA and
* 100mA for potential accessory). Closest level is 1300mA
*/
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_1P3;
break;
case USB_STAT_DEDICATED_CHG:
case USB_STAT_HOST_CHG_NM:
case USB_STAT_ACA_RID_C_HS_CHIRP:
case USB_STAT_ACA_RID_C_NM:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_1P5;
break;
case USB_STAT_RESERVED:
/*
* This state is used to indicate that VBUS has dropped below
* the detection level 4 times in a row. This is due to the
* charger output current is set to high making the charger
* voltage collapse. This have to be propagated through to
* chargalg. This is done using the property
* POWER_SUPPLY_PROP_CURRENT_AVG = 1
*/
di->flags.vbus_collapse = true;
dev_dbg(di->dev, "USB Type - USB_STAT_RESERVED "
"VBUS has collapsed\n");
ret = -1;
break;
case USB_STAT_HM_IDGND:
case USB_STAT_NOT_CONFIGURED:
case USB_STAT_NOT_VALID_LINK:
dev_err(di->dev, "USB Type - Charging not allowed\n");
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P05;
ret = -ENXIO;
break;
default:
dev_err(di->dev, "USB Type - Unknown\n");
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P05;
ret = -ENXIO;
break;
};
dev_dbg(di->dev, "USB Type - 0x%02x MaxCurr: %d",
link_status, di->max_usb_in_curr);
return ret;
}
/**
* ab8500_charger_read_usb_type() - read the type of usb connected
* @di: pointer to the ab8500_charger structure
*
* Detect the type of the plugged USB
* Returns error code in case of failure else 0 on success
*/
static int ab8500_charger_read_usb_type(struct ab8500_charger *di)
{
int ret;
u8 val;
ret = abx500_get_register_interruptible(di->dev,
AB8500_INTERRUPT, AB8500_IT_SOURCE21_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
ret = abx500_get_register_interruptible(di->dev, AB8500_USB,
AB8500_USB_LINE_STAT_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
/* get the USB type */
val = (val & AB8500_USB_LINK_STATUS) >> 3;
ret = ab8500_charger_max_usb_curr(di,
(enum ab8500_charger_link_status) val);
return ret;
}
/**
* ab8500_charger_detect_usb_type() - get the type of usb connected
* @di: pointer to the ab8500_charger structure
*
* Detect the type of the plugged USB
* Returns error code in case of failure else 0 on success
*/
static int ab8500_charger_detect_usb_type(struct ab8500_charger *di)
{
int i, ret;
u8 val;
/*
* On getting the VBUS rising edge detect interrupt there
* is a 250ms delay after which the register UsbLineStatus
* is filled with valid data.
*/
for (i = 0; i < 10; i++) {
msleep(250);
ret = abx500_get_register_interruptible(di->dev,
AB8500_INTERRUPT, AB8500_IT_SOURCE21_REG,
&val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
ret = abx500_get_register_interruptible(di->dev, AB8500_USB,
AB8500_USB_LINE_STAT_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
/*
* Until the IT source register is read the UsbLineStatus
* register is not updated, hence doing the same
* Revisit this:
*/
/* get the USB type */
val = (val & AB8500_USB_LINK_STATUS) >> 3;
if (val)
break;
}
ret = ab8500_charger_max_usb_curr(di,
(enum ab8500_charger_link_status) val);
return ret;
}
/*
* This array maps the raw hex value to charger voltage used by the AB8500
* Values taken from the UM0836
*/
static int ab8500_charger_voltage_map[] = {
3500 ,
3525 ,
3550 ,
3575 ,
3600 ,
3625 ,
3650 ,
3675 ,
3700 ,
3725 ,
3750 ,
3775 ,
3800 ,
3825 ,
3850 ,
3875 ,
3900 ,
3925 ,
3950 ,
3975 ,
4000 ,
4025 ,
4050 ,
4060 ,
4070 ,
4080 ,
4090 ,
4100 ,
4110 ,
4120 ,
4130 ,
4140 ,
4150 ,
4160 ,
4170 ,
4180 ,
4190 ,
4200 ,
4210 ,
4220 ,
4230 ,
4240 ,
4250 ,
4260 ,
4270 ,
4280 ,
4290 ,
4300 ,
4310 ,
4320 ,
4330 ,
4340 ,
4350 ,
4360 ,
4370 ,
4380 ,
4390 ,
4400 ,
4410 ,
4420 ,
4430 ,
4440 ,
4450 ,
4460 ,
4470 ,
4480 ,
4490 ,
4500 ,
4510 ,
4520 ,
4530 ,
4540 ,
4550 ,
4560 ,
4570 ,
4580 ,
4590 ,
4600 ,
};
/*
* This array maps the raw hex value to charger current used by the AB8500
* Values taken from the UM0836
*/
static int ab8500_charger_current_map[] = {
100 ,
200 ,
300 ,
400 ,
500 ,
600 ,
700 ,
800 ,
900 ,
1000 ,
1100 ,
1200 ,
1300 ,
1400 ,
1500 ,
};
/*
* This array maps the raw hex value to VBUS input current used by the AB8500
* Values taken from the UM0836
*/
static int ab8500_charger_vbus_in_curr_map[] = {
USB_CH_IP_CUR_LVL_0P05,
USB_CH_IP_CUR_LVL_0P09,
USB_CH_IP_CUR_LVL_0P19,
USB_CH_IP_CUR_LVL_0P29,
USB_CH_IP_CUR_LVL_0P38,
USB_CH_IP_CUR_LVL_0P45,
USB_CH_IP_CUR_LVL_0P5,
USB_CH_IP_CUR_LVL_0P6,
USB_CH_IP_CUR_LVL_0P7,
USB_CH_IP_CUR_LVL_0P8,
USB_CH_IP_CUR_LVL_0P9,
USB_CH_IP_CUR_LVL_1P0,
USB_CH_IP_CUR_LVL_1P1,
USB_CH_IP_CUR_LVL_1P3,
USB_CH_IP_CUR_LVL_1P4,
USB_CH_IP_CUR_LVL_1P5,
};
static int ab8500_voltage_to_regval(int voltage)
{
int i;
/* Special case for voltage below 3.5V */
if (voltage < ab8500_charger_voltage_map[0])
return LOW_VOLT_REG;
for (i = 1; i < ARRAY_SIZE(ab8500_charger_voltage_map); i++) {
if (voltage < ab8500_charger_voltage_map[i])
return i - 1;
}
/* If not last element, return error */
i = ARRAY_SIZE(ab8500_charger_voltage_map) - 1;
if (voltage == ab8500_charger_voltage_map[i])
return i;
else
return -1;
}
static int ab8500_current_to_regval(int curr)
{
int i;
if (curr < ab8500_charger_current_map[0])
return 0;
for (i = 0; i < ARRAY_SIZE(ab8500_charger_current_map); i++) {
if (curr < ab8500_charger_current_map[i])
return i - 1;
}
/* If not last element, return error */
i = ARRAY_SIZE(ab8500_charger_current_map) - 1;
if (curr == ab8500_charger_current_map[i])
return i;
else
return -1;
}
static int ab8500_vbus_in_curr_to_regval(int curr)
{
int i;
if (curr < ab8500_charger_vbus_in_curr_map[0])
return 0;
for (i = 0; i < ARRAY_SIZE(ab8500_charger_vbus_in_curr_map); i++) {
if (curr < ab8500_charger_vbus_in_curr_map[i])
return i - 1;
}
/* If not last element, return error */
i = ARRAY_SIZE(ab8500_charger_vbus_in_curr_map) - 1;
if (curr == ab8500_charger_vbus_in_curr_map[i])
return i;
else
return -1;
}
/**
* ab8500_charger_get_usb_cur() - get usb current
* @di: pointer to the ab8500_charger structre
*
* The usb stack provides the maximum current that can be drawn from
* the standard usb host. This will be in mA.
* This function converts current in mA to a value that can be written
* to the register. Returns -1 if charging is not allowed
*/
static int ab8500_charger_get_usb_cur(struct ab8500_charger *di)
{
switch (di->usb_state.usb_current) {
case 100:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P09;
break;
case 200:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P19;
break;
case 300:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P29;
break;
case 400:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P38;
break;
case 500:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P5;
break;
default:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P05;
return -1;
break;
};
return 0;
}
/**
* ab8500_charger_set_vbus_in_curr() - set VBUS input current limit
* @di: pointer to the ab8500_charger structure
* @ich_in: charger input current limit
*
* Sets the current that can be drawn from the USB host
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_set_vbus_in_curr(struct ab8500_charger *di,
int ich_in)
{
int ret;
int input_curr_index;
int min_value;
/* We should always use to lowest current limit */
min_value = min(di->bat->chg_params->usb_curr_max, ich_in);
switch (min_value) {
case 100:
if (di->vbat < VBAT_TRESH_IP_CUR_RED)
min_value = USB_CH_IP_CUR_LVL_0P05;
break;
case 500:
if (di->vbat < VBAT_TRESH_IP_CUR_RED)
min_value = USB_CH_IP_CUR_LVL_0P45;
break;
default:
break;
}
input_curr_index = ab8500_vbus_in_curr_to_regval(min_value);
if (input_curr_index < 0) {
dev_err(di->dev, "VBUS input current limit too high\n");
return -ENXIO;
}
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_USBCH_IPT_CRNTLVL_REG,
input_curr_index << VBUS_IN_CURR_LIM_SHIFT);
if (ret)
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/**
* ab8500_charger_led_en() - turn on/off chargign led
* @di: pointer to the ab8500_charger structure
* @on: flag to turn on/off the chargign led
*
* Power ON/OFF charging LED indication
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_led_en(struct ab8500_charger *di, int on)
{
int ret;
if (on) {
/* Power ON charging LED indicator, set LED current to 5mA */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_LED_INDICATOR_PWM_CTRL,
(LED_IND_CUR_5MA | LED_INDICATOR_PWM_ENA));
if (ret) {
dev_err(di->dev, "Power ON LED failed\n");
return ret;
}
/* LED indicator PWM duty cycle 252/256 */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_LED_INDICATOR_PWM_DUTY,
LED_INDICATOR_PWM_DUTY_252_256);
if (ret) {
dev_err(di->dev, "Set LED PWM duty cycle failed\n");
return ret;
}
} else {
/* Power off charging LED indicator */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_LED_INDICATOR_PWM_CTRL,
LED_INDICATOR_PWM_DIS);
if (ret) {
dev_err(di->dev, "Power-off LED failed\n");
return ret;
}
}
return ret;
}
/**
* ab8500_charger_ac_en() - enable or disable ac charging
* @di: pointer to the ab8500_charger structure
* @enable: enable/disable flag
* @vset: charging voltage
* @iset: charging current
*
* Enable/Disable AC/Mains charging and turns on/off the charging led
* respectively.
**/
static int ab8500_charger_ac_en(struct ux500_charger *charger,
int enable, int vset, int iset)
{
int ret;
int volt_index;
int curr_index;
int input_curr_index;
u8 overshoot = 0;
struct ab8500_charger *di = to_ab8500_charger_ac_device_info(charger);
if (enable) {
/* Check if AC is connected */
if (!di->ac.charger_connected) {
dev_err(di->dev, "AC charger not connected\n");
return -ENXIO;
}
/* Enable AC charging */
dev_dbg(di->dev, "Enable AC: %dmV %dmA\n", vset, iset);
/*
* Due to a bug in AB8500, BTEMP_HIGH/LOW interrupts
* will be triggered everytime we enable the VDD ADC supply.
* This will turn off charging for a short while.
* It can be avoided by having the supply on when
* there is a charger enabled. Normally the VDD ADC supply
* is enabled everytime a GPADC conversion is triggered. We will
* force it to be enabled from this driver to have
* the GPADC module independant of the AB8500 chargers
*/
if (!di->vddadc_en_ac) {
regulator_enable(di->regu);
di->vddadc_en_ac = true;
}
/* Check if the requested voltage or current is valid */
volt_index = ab8500_voltage_to_regval(vset);
curr_index = ab8500_current_to_regval(iset);
input_curr_index = ab8500_current_to_regval(
di->bat->chg_params->ac_curr_max);
if (volt_index < 0 || curr_index < 0 || input_curr_index < 0) {
dev_err(di->dev,
"Charger voltage or current too high, "
"charging not started\n");
return -ENXIO;
}
/* ChVoltLevel: maximum battery charging voltage */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_VOLT_LVL_REG, (u8) volt_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* MainChInputCurr: current that can be drawn from the charger*/
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_MCH_IPT_CURLVL_REG,
input_curr_index << MAIN_CH_INPUT_CURR_SHIFT);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* ChOutputCurentLevel: protected output current */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, (u8) curr_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Check if VBAT overshoot control should be enabled */
if (!di->bat->enable_overshoot)
overshoot = MAIN_CH_NO_OVERSHOOT_ENA_N;
/* Enable Main Charger */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_MCH_CTRL1, MAIN_CH_ENA | overshoot);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Power on charging LED indication */
ret = ab8500_charger_led_en(di, true);
if (ret < 0)
dev_err(di->dev, "failed to enable LED\n");
di->ac.charger_online = 1;
} else {
/* Disable AC charging */
if (is_ab8500_1p1_or_earlier(di->parent)) {
/*
* For ABB revision 1.0 and 1.1 there is a bug in the
* watchdog logic. That means we have to continously
* kick the charger watchdog even when no charger is
* connected. This is only valid once the AC charger
* has been enabled. This is a bug that is not handled
* by the algorithm and the watchdog have to be kicked
* by the charger driver when the AC charger
* is disabled
*/
if (di->ac_conn) {
queue_delayed_work(di->charger_wq,
&di->kick_wd_work,
round_jiffies(WD_KICK_INTERVAL));
}
/*
* We can't turn off charging completely
* due to a bug in AB8500 cut1.
* If we do, charging will not start again.
* That is why we set the lowest voltage
* and current possible
*/
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_VOLT_LVL_REG, CH_VOL_LVL_3P5);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, CH_OP_CUR_LVL_0P1);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
} else {
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_MCH_CTRL1, 0);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
}
ret = ab8500_charger_led_en(di, false);
if (ret < 0)
dev_err(di->dev, "failed to disable LED\n");
di->ac.charger_online = 0;
di->ac.wd_expired = false;
/* Disable regulator if enabled */
if (di->vddadc_en_ac) {
regulator_disable(di->regu);
di->vddadc_en_ac = false;
}
dev_dbg(di->dev, "%s Disabled AC charging\n", __func__);
}
ab8500_power_supply_changed(di, &di->ac_chg.psy);
return ret;
}
/**
* ab8500_charger_usb_en() - enable usb charging
* @di: pointer to the ab8500_charger structure
* @enable: enable/disable flag
* @vset: charging voltage
* @ich_out: charger output current
*
* Enable/Disable USB charging and turns on/off the charging led respectively.
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_usb_en(struct ux500_charger *charger,
int enable, int vset, int ich_out)
{
int ret;
int volt_index;
int curr_index;
u8 overshoot = 0;
struct ab8500_charger *di = to_ab8500_charger_usb_device_info(charger);
if (enable) {
/* Check if USB is connected */
if (!di->usb.charger_connected) {
dev_err(di->dev, "USB charger not connected\n");
return -ENXIO;
}
/*
* Due to a bug in AB8500, BTEMP_HIGH/LOW interrupts
* will be triggered everytime we enable the VDD ADC supply.
* This will turn off charging for a short while.
* It can be avoided by having the supply on when
* there is a charger enabled. Normally the VDD ADC supply
* is enabled everytime a GPADC conversion is triggered. We will
* force it to be enabled from this driver to have
* the GPADC module independant of the AB8500 chargers
*/
if (!di->vddadc_en_usb) {
regulator_enable(di->regu);
di->vddadc_en_usb = true;
}
/* Enable USB charging */
dev_dbg(di->dev, "Enable USB: %dmV %dmA\n", vset, ich_out);
/* Check if the requested voltage or current is valid */
volt_index = ab8500_voltage_to_regval(vset);
curr_index = ab8500_current_to_regval(ich_out);
if (volt_index < 0 || curr_index < 0) {
dev_err(di->dev,
"Charger voltage or current too high, "
"charging not started\n");
return -ENXIO;
}
/* ChVoltLevel: max voltage upto which battery can be charged */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_VOLT_LVL_REG, (u8) volt_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* USBChInputCurr: current that can be drawn from the usb */
ret = ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr);
if (ret) {
dev_err(di->dev, "setting USBChInputCurr failed\n");
return ret;
}
/* ChOutputCurentLevel: protected output current */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, (u8) curr_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Check if VBAT overshoot control should be enabled */
if (!di->bat->enable_overshoot)
overshoot = USB_CHG_NO_OVERSHOOT_ENA_N;
/* Enable USB Charger */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_USBCH_CTRL1_REG, USB_CH_ENA | overshoot);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* If success power on charging LED indication */
ret = ab8500_charger_led_en(di, true);
if (ret < 0)
dev_err(di->dev, "failed to enable LED\n");
queue_delayed_work(di->charger_wq, &di->check_vbat_work, HZ);
di->usb.charger_online = 1;
} else {
/* Disable USB charging */
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_USBCH_CTRL1_REG, 0);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
ret = ab8500_charger_led_en(di, false);
if (ret < 0)
dev_err(di->dev, "failed to disable LED\n");
di->usb.charger_online = 0;
di->usb.wd_expired = false;
/* Disable regulator if enabled */
if (di->vddadc_en_usb) {
regulator_disable(di->regu);
di->vddadc_en_usb = false;
}
dev_dbg(di->dev, "%s Disabled USB charging\n", __func__);
/* Cancel any pending Vbat check work */
if (delayed_work_pending(&di->check_vbat_work))
cancel_delayed_work(&di->check_vbat_work);
}
ab8500_power_supply_changed(di, &di->usb_chg.psy);
return ret;
}
/**
* ab8500_charger_watchdog_kick() - kick charger watchdog
* @di: pointer to the ab8500_charger structure
*
* Kick charger watchdog
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_watchdog_kick(struct ux500_charger *charger)
{
int ret;
struct ab8500_charger *di;
if (charger->psy.type == POWER_SUPPLY_TYPE_MAINS)
di = to_ab8500_charger_ac_device_info(charger);
else if (charger->psy.type == POWER_SUPPLY_TYPE_USB)
di = to_ab8500_charger_usb_device_info(charger);
else
return -ENXIO;
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARG_WD_CTRL, CHARG_WD_KICK);
if (ret)
dev_err(di->dev, "Failed to kick WD!\n");
return ret;
}
/**
* ab8500_charger_update_charger_current() - update charger current
* @di: pointer to the ab8500_charger structure
*
* Update the charger output current for the specified charger
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_update_charger_current(struct ux500_charger *charger,
int ich_out)
{
int ret;
int curr_index;
struct ab8500_charger *di;
if (charger->psy.type == POWER_SUPPLY_TYPE_MAINS)
di = to_ab8500_charger_ac_device_info(charger);
else if (charger->psy.type == POWER_SUPPLY_TYPE_USB)
di = to_ab8500_charger_usb_device_info(charger);
else
return -ENXIO;
curr_index = ab8500_current_to_regval(ich_out);
if (curr_index < 0) {
dev_err(di->dev,
"Charger current too high, "
"charging not started\n");
return -ENXIO;
}
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, (u8) curr_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Reset the main and usb drop input current measurement counter */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARGER_CTRL,
0x1);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
return ret;
}
static int ab8500_charger_get_ext_psy_data(struct device *dev, void *data)
{
struct power_supply *psy;
struct power_supply *ext;
struct ab8500_charger *di;
union power_supply_propval ret;
int i, j;
bool psy_found = false;
struct ux500_charger *usb_chg;
usb_chg = (struct ux500_charger *)data;
psy = &usb_chg->psy;
di = to_ab8500_charger_usb_device_info(usb_chg);
ext = dev_get_drvdata(dev);
/* For all psy where the driver name appears in any supplied_to */
for (i = 0; i < ext->num_supplicants; i++) {
if (!strcmp(ext->supplied_to[i], psy->name))
psy_found = true;
}
if (!psy_found)
return 0;
/* Go through all properties for the psy */
for (j = 0; j < ext->num_properties; j++) {
enum power_supply_property prop;
prop = ext->properties[j];
if (ext->get_property(ext, prop, &ret))
continue;
switch (prop) {
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
switch (ext->type) {
case POWER_SUPPLY_TYPE_BATTERY:
di->vbat = ret.intval / 1000;
break;
default:
break;
}
break;
default:
break;
}
}
return 0;
}
/**
* ab8500_charger_check_vbat_work() - keep vbus current within spec
* @work pointer to the work_struct structure
*
* Due to a asic bug it is necessary to lower the input current to the vbus
* charger when charging with at some specific levels. This issue is only valid
* for below a certain battery voltage. This function makes sure that the
* the allowed current limit isn't exceeded.
*/
static void ab8500_charger_check_vbat_work(struct work_struct *work)
{
int t = 10;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_vbat_work.work);
class_for_each_device(power_supply_class, NULL,
&di->usb_chg.psy, ab8500_charger_get_ext_psy_data);
/* First run old_vbat is 0. */
if (di->old_vbat == 0)
di->old_vbat = di->vbat;
if (!((di->old_vbat <= VBAT_TRESH_IP_CUR_RED &&
di->vbat <= VBAT_TRESH_IP_CUR_RED) ||
(di->old_vbat > VBAT_TRESH_IP_CUR_RED &&
di->vbat > VBAT_TRESH_IP_CUR_RED))) {
dev_dbg(di->dev, "Vbat did cross threshold, curr: %d, new: %d,"
" old: %d\n", di->max_usb_in_curr, di->vbat,
di->old_vbat);
ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr);
power_supply_changed(&di->usb_chg.psy);
}
di->old_vbat = di->vbat;
/*
* No need to check the battery voltage every second when not close to
* the threshold.
*/
if (di->vbat < (VBAT_TRESH_IP_CUR_RED + 100) &&
(di->vbat > (VBAT_TRESH_IP_CUR_RED - 100)))
t = 1;
queue_delayed_work(di->charger_wq, &di->check_vbat_work, t * HZ);
}
/**
* ab8500_charger_check_hw_failure_work() - check main charger failure
* @work: pointer to the work_struct structure
*
* Work queue function for checking the main charger status
*/
static void ab8500_charger_check_hw_failure_work(struct work_struct *work)
{
int ret;
u8 reg_value;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_hw_failure_work.work);
/* Check if the status bits for HW failure is still active */
if (di->flags.mainextchnotok) {
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_STATUS2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (!(reg_value & MAIN_CH_NOK)) {
di->flags.mainextchnotok = false;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
}
}
if (di->flags.vbus_ovv) {
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG,
®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (!(reg_value & VBUS_OVV_TH)) {
di->flags.vbus_ovv = false;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
}
/* If we still have a failure, schedule a new check */
if (di->flags.mainextchnotok || di->flags.vbus_ovv) {
queue_delayed_work(di->charger_wq,
&di->check_hw_failure_work, round_jiffies(HZ));
}
}
/**
* ab8500_charger_kick_watchdog_work() - kick the watchdog
* @work: pointer to the work_struct structure
*
* Work queue function for kicking the charger watchdog.
*
* For ABB revision 1.0 and 1.1 there is a bug in the watchdog
* logic. That means we have to continously kick the charger
* watchdog even when no charger is connected. This is only
* valid once the AC charger has been enabled. This is
* a bug that is not handled by the algorithm and the
* watchdog have to be kicked by the charger driver
* when the AC charger is disabled
*/
static void ab8500_charger_kick_watchdog_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, kick_wd_work.work);
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARG_WD_CTRL, CHARG_WD_KICK);
if (ret)
dev_err(di->dev, "Failed to kick WD!\n");
/* Schedule a new watchdog kick */
queue_delayed_work(di->charger_wq,
&di->kick_wd_work, round_jiffies(WD_KICK_INTERVAL));
}
/**
* ab8500_charger_ac_work() - work to get and set main charger status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the main charger status
*/
static void ab8500_charger_ac_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, ac_work);
/*
* Since we can't be sure that the events are received
* synchronously, we have the check if the main charger is
* connected by reading the status register
*/
ret = ab8500_charger_detect_chargers(di);
if (ret < 0)
return;
if (ret & AC_PW_CONN) {
di->ac.charger_connected = 1;
di->ac_conn = true;
} else {
di->ac.charger_connected = 0;
}
ab8500_power_supply_changed(di, &di->ac_chg.psy);
sysfs_notify(&di->ac_chg.psy.dev->kobj, NULL, "present");
}
/**
* ab8500_charger_detect_usb_type_work() - work to detect USB type
* @work: Pointer to the work_struct structure
*
* Detect the type of USB plugged
*/
static void ab8500_charger_detect_usb_type_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, detect_usb_type_work);
/*
* Since we can't be sure that the events are received
* synchronously, we have the check if is
* connected by reading the status register
*/
ret = ab8500_charger_detect_chargers(di);
if (ret < 0)
return;
if (!(ret & USB_PW_CONN)) {
di->vbus_detected = 0;
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
} else {
di->vbus_detected = 1;
if (is_ab8500_1p1_or_earlier(di->parent)) {
ret = ab8500_charger_detect_usb_type(di);
if (!ret) {
ab8500_charger_set_usb_connected(di, true);
ab8500_power_supply_changed(di,
&di->usb_chg.psy);
}
} else {
/* For ABB cut2.0 and onwards we have an IRQ,
* USB_LINK_STATUS that will be triggered when the USB
* link status changes. The exception is USB connected
* during startup. Then we don't get a
* USB_LINK_STATUS IRQ
*/
if (di->vbus_detected_start) {
di->vbus_detected_start = false;
ret = ab8500_charger_detect_usb_type(di);
if (!ret) {
ab8500_charger_set_usb_connected(di,
true);
ab8500_power_supply_changed(di,
&di->usb_chg.psy);
}
}
}
}
}
/**
* ab8500_charger_usb_link_status_work() - work to detect USB type
* @work: pointer to the work_struct structure
*
* Detect the type of USB plugged
*/
static void ab8500_charger_usb_link_status_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, usb_link_status_work);
/*
* Since we can't be sure that the events are received
* synchronously, we have the check if is
* connected by reading the status register
*/
ret = ab8500_charger_detect_chargers(di);
if (ret < 0)
return;
if (!(ret & USB_PW_CONN)) {
di->vbus_detected = 0;
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
} else {
di->vbus_detected = 1;
ret = ab8500_charger_read_usb_type(di);
if (!ret) {
/* Update maximum input current */
ret = ab8500_charger_set_vbus_in_curr(di,
di->max_usb_in_curr);
if (ret)
return;
ab8500_charger_set_usb_connected(di, true);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
} else if (ret == -ENXIO) {
/* No valid charger type detected */
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
}
}
static void ab8500_charger_usb_state_changed_work(struct work_struct *work)
{
int ret;
unsigned long flags;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, usb_state_changed_work);
if (!di->vbus_detected)
return;
spin_lock_irqsave(&di->usb_state.usb_lock, flags);
di->usb_state.usb_changed = false;
spin_unlock_irqrestore(&di->usb_state.usb_lock, flags);
/*
* wait for some time until you get updates from the usb stack
* and negotiations are completed
*/
msleep(250);
if (di->usb_state.usb_changed)
return;
dev_dbg(di->dev, "%s USB state: 0x%02x mA: %d\n",
__func__, di->usb_state.state, di->usb_state.usb_current);
switch (di->usb_state.state) {
case AB8500_BM_USB_STATE_RESET_HS:
case AB8500_BM_USB_STATE_RESET_FS:
case AB8500_BM_USB_STATE_SUSPEND:
case AB8500_BM_USB_STATE_MAX:
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
break;
case AB8500_BM_USB_STATE_RESUME:
/*
* when suspend->resume there should be delay
* of 1sec for enabling charging
*/
msleep(1000);
/* Intentional fall through */
case AB8500_BM_USB_STATE_CONFIGURED:
/*
* USB is configured, enable charging with the charging
* input current obtained from USB driver
*/
if (!ab8500_charger_get_usb_cur(di)) {
/* Update maximum input current */
ret = ab8500_charger_set_vbus_in_curr(di,
di->max_usb_in_curr);
if (ret)
return;
ab8500_charger_set_usb_connected(di, true);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
break;
default:
break;
};
}
/**
* ab8500_charger_check_usbchargernotok_work() - check USB chg not ok status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the USB charger Not OK status
*/
static void ab8500_charger_check_usbchargernotok_work(struct work_struct *work)
{
int ret;
u8 reg_value;
bool prev_status;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_usbchgnotok_work.work);
/* Check if the status bit for usbchargernotok is still active */
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
prev_status = di->flags.usbchargernotok;
if (reg_value & VBUS_CH_NOK) {
di->flags.usbchargernotok = true;
/* Check again in 1sec */
queue_delayed_work(di->charger_wq,
&di->check_usbchgnotok_work, HZ);
} else {
di->flags.usbchargernotok = false;
di->flags.vbus_collapse = false;
}
if (prev_status != di->flags.usbchargernotok)
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
/**
* ab8500_charger_check_main_thermal_prot_work() - check main thermal status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the Main thermal prot status
*/
static void ab8500_charger_check_main_thermal_prot_work(
struct work_struct *work)
{
int ret;
u8 reg_value;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_main_thermal_prot_work);
/* Check if the status bit for main_thermal_prot is still active */
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_STATUS2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (reg_value & MAIN_CH_TH_PROT)
di->flags.main_thermal_prot = true;
else
di->flags.main_thermal_prot = false;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
}
/**
* ab8500_charger_check_usb_thermal_prot_work() - check usb thermal status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the USB thermal prot status
*/
static void ab8500_charger_check_usb_thermal_prot_work(
struct work_struct *work)
{
int ret;
u8 reg_value;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_usb_thermal_prot_work);
/* Check if the status bit for usb_thermal_prot is still active */
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (reg_value & USB_CH_TH_PROT)
di->flags.usb_thermal_prot = true;
else
di->flags.usb_thermal_prot = false;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
/**
* ab8500_charger_mainchunplugdet_handler() - main charger unplugged
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchunplugdet_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Main charger unplugged\n");
queue_work(di->charger_wq, &di->ac_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainchplugdet_handler() - main charger plugged
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchplugdet_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Main charger plugged\n");
queue_work(di->charger_wq, &di->ac_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainextchnotok_handler() - main charger not ok
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainextchnotok_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Main charger not ok\n");
di->flags.mainextchnotok = true;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
/* Schedule a new HW failure check */
queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, 0);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainchthprotr_handler() - Die temp is above main charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchthprotr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp above Main charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_main_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainchthprotf_handler() - Die temp is below main charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchthprotf_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp ok for Main charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_main_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_vbusdetf_handler() - VBUS falling detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_vbusdetf_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "VBUS falling detected\n");
queue_work(di->charger_wq, &di->detect_usb_type_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_vbusdetr_handler() - VBUS rising detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_vbusdetr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
di->vbus_detected = true;
dev_dbg(di->dev, "VBUS rising detected\n");
queue_work(di->charger_wq, &di->detect_usb_type_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usblinkstatus_handler() - USB link status has changed
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usblinkstatus_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "USB link status changed\n");
queue_work(di->charger_wq, &di->usb_link_status_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usbchthprotr_handler() - Die temp is above usb charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usbchthprotr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp above USB charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_usb_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usbchthprotf_handler() - Die temp is below usb charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usbchthprotf_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp ok for USB charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_usb_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usbchargernotokr_handler() - USB charger not ok detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usbchargernotokr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Not allowed USB charger detected\n");
queue_delayed_work(di->charger_wq, &di->check_usbchgnotok_work, 0);
return IRQ_HANDLED;
}
/**
* ab8500_charger_chwdexp_handler() - Charger watchdog expired
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_chwdexp_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Charger watchdog expired\n");
/*
* The charger that was online when the watchdog expired
* needs to be restarted for charging to start again
*/
if (di->ac.charger_online) {
di->ac.wd_expired = true;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
}
if (di->usb.charger_online) {
di->usb.wd_expired = true;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
return IRQ_HANDLED;
}
/**
* ab8500_charger_vbusovv_handler() - VBUS overvoltage detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_vbusovv_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "VBUS overvoltage detected\n");
di->flags.vbus_ovv = true;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
/* Schedule a new HW failure check */
queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, 0);
return IRQ_HANDLED;
}
/**
* ab8500_charger_ac_get_property() - get the ac/mains properties
* @psy: pointer to the power_supply structure
* @psp: pointer to the power_supply_property structure
* @val: pointer to the power_supply_propval union
*
* This function gets called when an application tries to get the ac/mains
* properties by reading the sysfs files.
* AC/Mains properties are online, present and voltage.
* online: ac/mains charging is in progress or not
* present: presence of the ac/mains
* voltage: AC/Mains voltage
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_ac_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct ab8500_charger *di;
di = to_ab8500_charger_ac_device_info(psy_to_ux500_charger(psy));
switch (psp) {
case POWER_SUPPLY_PROP_HEALTH:
if (di->flags.mainextchnotok)
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
else if (di->ac.wd_expired || di->usb.wd_expired)
val->intval = POWER_SUPPLY_HEALTH_DEAD;
else if (di->flags.main_thermal_prot)
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
else
val->intval = POWER_SUPPLY_HEALTH_GOOD;
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = di->ac.charger_online;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = di->ac.charger_connected;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
di->ac.charger_voltage = ab8500_charger_get_ac_voltage(di);
val->intval = di->ac.charger_voltage * 1000;
break;
case POWER_SUPPLY_PROP_VOLTAGE_AVG:
/*
* This property is used to indicate when CV mode is entered
* for the AC charger
*/
di->ac.cv_active = ab8500_charger_ac_cv(di);
val->intval = di->ac.cv_active;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
val->intval = ab8500_charger_get_ac_current(di) * 1000;
break;
default:
return -EINVAL;
}
return 0;
}
/**
* ab8500_charger_usb_get_property() - get the usb properties
* @psy: pointer to the power_supply structure
* @psp: pointer to the power_supply_property structure
* @val: pointer to the power_supply_propval union
*
* This function gets called when an application tries to get the usb
* properties by reading the sysfs files.
* USB properties are online, present and voltage.
* online: usb charging is in progress or not
* present: presence of the usb
* voltage: vbus voltage
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_usb_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct ab8500_charger *di;
di = to_ab8500_charger_usb_device_info(psy_to_ux500_charger(psy));
switch (psp) {
case POWER_SUPPLY_PROP_HEALTH:
if (di->flags.usbchargernotok)
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
else if (di->ac.wd_expired || di->usb.wd_expired)
val->intval = POWER_SUPPLY_HEALTH_DEAD;
else if (di->flags.usb_thermal_prot)
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
else if (di->flags.vbus_ovv)
val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
else
val->intval = POWER_SUPPLY_HEALTH_GOOD;
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = di->usb.charger_online;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = di->usb.charger_connected;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
di->usb.charger_voltage = ab8500_charger_get_vbus_voltage(di);
val->intval = di->usb.charger_voltage * 1000;
break;
case POWER_SUPPLY_PROP_VOLTAGE_AVG:
/*
* This property is used to indicate when CV mode is entered
* for the USB charger
*/
di->usb.cv_active = ab8500_charger_usb_cv(di);
val->intval = di->usb.cv_active;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
val->intval = ab8500_charger_get_usb_current(di) * 1000;
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
/*
* This property is used to indicate when VBUS has collapsed
* due to too high output current from the USB charger
*/
if (di->flags.vbus_collapse)
val->intval = 1;
else
val->intval = 0;
break;
default:
return -EINVAL;
}
return 0;
}
/**
* ab8500_charger_init_hw_registers() - Set up charger related registers
* @di: pointer to the ab8500_charger structure
*
* Set up charger OVV, watchdog and maximum voltage registers as well as
* charging of the backup battery
*/
static int ab8500_charger_init_hw_registers(struct ab8500_charger *di)
{
int ret = 0;
/* Setup maximum charger current and voltage for ABB cut2.0 */
if (!is_ab8500_1p1_or_earlier(di->parent)) {
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_VOLT_LVL_MAX_REG, CH_VOL_LVL_4P6);
if (ret) {
dev_err(di->dev,
"failed to set CH_VOLT_LVL_MAX_REG\n");
goto out;
}
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_MAX_REG, CH_OP_CUR_LVL_1P6);
if (ret) {
dev_err(di->dev,
"failed to set CH_OPT_CRNTLVL_MAX_REG\n");
goto out;
}
}
/* VBUS OVV set to 6.3V and enable automatic current limitiation */
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_USBCH_CTRL2_REG,
VBUS_OVV_SELECT_6P3V | VBUS_AUTO_IN_CURR_LIM_ENA);
if (ret) {
dev_err(di->dev, "failed to set VBUS OVV\n");
goto out;
}
/* Enable main watchdog in OTP */
ret = abx500_set_register_interruptible(di->dev,
AB8500_OTP_EMUL, AB8500_OTP_CONF_15, OTP_ENABLE_WD);
if (ret) {
dev_err(di->dev, "failed to enable main WD in OTP\n");
goto out;
}
/* Enable main watchdog */
ret = abx500_set_register_interruptible(di->dev,
AB8500_SYS_CTRL2_BLOCK,
AB8500_MAIN_WDOG_CTRL_REG, MAIN_WDOG_ENA);
if (ret) {
dev_err(di->dev, "faile to enable main watchdog\n");
goto out;
}
/*
* Due to internal synchronisation, Enable and Kick watchdog bits
* cannot be enabled in a single write.
* A minimum delay of 2*32 kHz period (62.5µs) must be inserted
* between writing Enable then Kick bits.
*/
udelay(63);
/* Kick main watchdog */
ret = abx500_set_register_interruptible(di->dev,
AB8500_SYS_CTRL2_BLOCK,
AB8500_MAIN_WDOG_CTRL_REG,
(MAIN_WDOG_ENA | MAIN_WDOG_KICK));
if (ret) {
dev_err(di->dev, "failed to kick main watchdog\n");
goto out;
}
/* Disable main watchdog */
ret = abx500_set_register_interruptible(di->dev,
AB8500_SYS_CTRL2_BLOCK,
AB8500_MAIN_WDOG_CTRL_REG, MAIN_WDOG_DIS);
if (ret) {
dev_err(di->dev, "failed to disable main watchdog\n");
goto out;
}
/* Set watchdog timeout */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_WD_TIMER_REG, WD_TIMER);
if (ret) {
dev_err(di->dev, "failed to set charger watchdog timeout\n");
goto out;
}
/* Backup battery voltage and current */
ret = abx500_set_register_interruptible(di->dev,
AB8500_RTC,
AB8500_RTC_BACKUP_CHG_REG,
di->bat->bkup_bat_v |
di->bat->bkup_bat_i);
if (ret) {
dev_err(di->dev, "failed to setup backup battery charging\n");
goto out;
}
/* Enable backup battery charging */
abx500_mask_and_set_register_interruptible(di->dev,
AB8500_RTC, AB8500_RTC_CTRL_REG,
RTC_BUP_CH_ENA, RTC_BUP_CH_ENA);
if (ret < 0)
dev_err(di->dev, "%s mask and set failed\n", __func__);
out:
return ret;
}
/*
* ab8500 charger driver interrupts and their respective isr
*/
static struct ab8500_charger_interrupts ab8500_charger_irq[] = {
{"MAIN_CH_UNPLUG_DET", ab8500_charger_mainchunplugdet_handler},
{"MAIN_CHARGE_PLUG_DET", ab8500_charger_mainchplugdet_handler},
{"MAIN_EXT_CH_NOT_OK", ab8500_charger_mainextchnotok_handler},
{"MAIN_CH_TH_PROT_R", ab8500_charger_mainchthprotr_handler},
{"MAIN_CH_TH_PROT_F", ab8500_charger_mainchthprotf_handler},
{"VBUS_DET_F", ab8500_charger_vbusdetf_handler},
{"VBUS_DET_R", ab8500_charger_vbusdetr_handler},
{"USB_LINK_STATUS", ab8500_charger_usblinkstatus_handler},
{"USB_CH_TH_PROT_R", ab8500_charger_usbchthprotr_handler},
{"USB_CH_TH_PROT_F", ab8500_charger_usbchthprotf_handler},
{"USB_CHARGER_NOT_OKR", ab8500_charger_usbchargernotokr_handler},
{"VBUS_OVV", ab8500_charger_vbusovv_handler},
{"CH_WD_EXP", ab8500_charger_chwdexp_handler},
};
static int ab8500_charger_usb_notifier_call(struct notifier_block *nb,
unsigned long event, void *power)
{
struct ab8500_charger *di =
container_of(nb, struct ab8500_charger, nb);
enum ab8500_usb_state bm_usb_state;
unsigned mA = *((unsigned *)power);
if (event != USB_EVENT_VBUS) {
dev_dbg(di->dev, "not a standard host, returning\n");
return NOTIFY_DONE;
}
/* TODO: State is fabricate here. See if charger really needs USB
* state or if mA is enough
*/
if ((di->usb_state.usb_current == 2) && (mA > 2))
bm_usb_state = AB8500_BM_USB_STATE_RESUME;
else if (mA == 0)
bm_usb_state = AB8500_BM_USB_STATE_RESET_HS;
else if (mA == 2)
bm_usb_state = AB8500_BM_USB_STATE_SUSPEND;
else if (mA >= 8) /* 8, 100, 500 */
bm_usb_state = AB8500_BM_USB_STATE_CONFIGURED;
else /* Should never occur */
bm_usb_state = AB8500_BM_USB_STATE_RESET_FS;
dev_dbg(di->dev, "%s usb_state: 0x%02x mA: %d\n",
__func__, bm_usb_state, mA);
spin_lock(&di->usb_state.usb_lock);
di->usb_state.usb_changed = true;
spin_unlock(&di->usb_state.usb_lock);
di->usb_state.state = bm_usb_state;
di->usb_state.usb_current = mA;
queue_work(di->charger_wq, &di->usb_state_changed_work);
return NOTIFY_OK;
}
#if defined(CONFIG_PM)
static int ab8500_charger_resume(struct platform_device *pdev)
{
int ret;
struct ab8500_charger *di = platform_get_drvdata(pdev);
/*
* For ABB revision 1.0 and 1.1 there is a bug in the watchdog
* logic. That means we have to continously kick the charger
* watchdog even when no charger is connected. This is only
* valid once the AC charger has been enabled. This is
* a bug that is not handled by the algorithm and the
* watchdog have to be kicked by the charger driver
* when the AC charger is disabled
*/
if (di->ac_conn && is_ab8500_1p1_or_earlier(di->parent)) {
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARG_WD_CTRL, CHARG_WD_KICK);
if (ret)
dev_err(di->dev, "Failed to kick WD!\n");
/* If not already pending start a new timer */
if (!delayed_work_pending(
&di->kick_wd_work)) {
queue_delayed_work(di->charger_wq, &di->kick_wd_work,
round_jiffies(WD_KICK_INTERVAL));
}
}
/* If we still have a HW failure, schedule a new check */
if (di->flags.mainextchnotok || di->flags.vbus_ovv) {
queue_delayed_work(di->charger_wq,
&di->check_hw_failure_work, 0);
}
return 0;
}
static int ab8500_charger_suspend(struct platform_device *pdev,
pm_message_t state)
{
struct ab8500_charger *di = platform_get_drvdata(pdev);
/* Cancel any pending HW failure check */
if (delayed_work_pending(&di->check_hw_failure_work))
cancel_delayed_work(&di->check_hw_failure_work);
return 0;
}
#else
#define ab8500_charger_suspend NULL
#define ab8500_charger_resume NULL
#endif
static int __devexit ab8500_charger_remove(struct platform_device *pdev)
{
struct ab8500_charger *di = platform_get_drvdata(pdev);
int i, irq, ret;
/* Disable AC charging */
ab8500_charger_ac_en(&di->ac_chg, false, 0, 0);
/* Disable USB charging */
ab8500_charger_usb_en(&di->usb_chg, false, 0, 0);
/* Disable interrupts */
for (i = 0; i < ARRAY_SIZE(ab8500_charger_irq); i++) {
irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name);
free_irq(irq, di);
}
/* disable the regulator */
regulator_put(di->regu);
/* Backup battery voltage and current disable */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_RTC, AB8500_RTC_CTRL_REG, RTC_BUP_CH_ENA, 0);
if (ret < 0)
dev_err(di->dev, "%s mask and set failed\n", __func__);
usb_unregister_notifier(di->usb_phy, &di->nb);
usb_put_transceiver(di->usb_phy);
/* Delete the work queue */
destroy_workqueue(di->charger_wq);
flush_scheduled_work();
power_supply_unregister(&di->usb_chg.psy);
power_supply_unregister(&di->ac_chg.psy);
platform_set_drvdata(pdev, NULL);
kfree(di);
return 0;
}
static int __devinit ab8500_charger_probe(struct platform_device *pdev)
{
int irq, i, charger_status, ret = 0;
struct abx500_bm_plat_data *plat_data;
struct ab8500_charger *di =
kzalloc(sizeof(struct ab8500_charger), GFP_KERNEL);
if (!di)
return -ENOMEM;
/* get parent data */
di->dev = &pdev->dev;
di->parent = dev_get_drvdata(pdev->dev.parent);
di->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
/* initialize lock */
spin_lock_init(&di->usb_state.usb_lock);
/* get charger specific platform data */
plat_data = pdev->dev.platform_data;
di->pdata = plat_data->charger;
if (!di->pdata) {
dev_err(di->dev, "no charger platform data supplied\n");
ret = -EINVAL;
goto free_device_info;
}
/* get battery specific platform data */
di->bat = plat_data->battery;
if (!di->bat) {
dev_err(di->dev, "no battery platform data supplied\n");
ret = -EINVAL;
goto free_device_info;
}
di->autopower = false;
/* AC supply */
/* power_supply base class */
di->ac_chg.psy.name = "ab8500_ac";
di->ac_chg.psy.type = POWER_SUPPLY_TYPE_MAINS;
di->ac_chg.psy.properties = ab8500_charger_ac_props;
di->ac_chg.psy.num_properties = ARRAY_SIZE(ab8500_charger_ac_props);
di->ac_chg.psy.get_property = ab8500_charger_ac_get_property;
di->ac_chg.psy.supplied_to = di->pdata->supplied_to;
di->ac_chg.psy.num_supplicants = di->pdata->num_supplicants;
/* ux500_charger sub-class */
di->ac_chg.ops.enable = &ab8500_charger_ac_en;
di->ac_chg.ops.kick_wd = &ab8500_charger_watchdog_kick;
di->ac_chg.ops.update_curr = &ab8500_charger_update_charger_current;
di->ac_chg.max_out_volt = ab8500_charger_voltage_map[
ARRAY_SIZE(ab8500_charger_voltage_map) - 1];
di->ac_chg.max_out_curr = ab8500_charger_current_map[
ARRAY_SIZE(ab8500_charger_current_map) - 1];
/* USB supply */
/* power_supply base class */
di->usb_chg.psy.name = "ab8500_usb";
di->usb_chg.psy.type = POWER_SUPPLY_TYPE_USB;
di->usb_chg.psy.properties = ab8500_charger_usb_props;
di->usb_chg.psy.num_properties = ARRAY_SIZE(ab8500_charger_usb_props);
di->usb_chg.psy.get_property = ab8500_charger_usb_get_property;
di->usb_chg.psy.supplied_to = di->pdata->supplied_to;
di->usb_chg.psy.num_supplicants = di->pdata->num_supplicants;
/* ux500_charger sub-class */
di->usb_chg.ops.enable = &ab8500_charger_usb_en;
di->usb_chg.ops.kick_wd = &ab8500_charger_watchdog_kick;
di->usb_chg.ops.update_curr = &ab8500_charger_update_charger_current;
di->usb_chg.max_out_volt = ab8500_charger_voltage_map[
ARRAY_SIZE(ab8500_charger_voltage_map) - 1];
di->usb_chg.max_out_curr = ab8500_charger_current_map[
ARRAY_SIZE(ab8500_charger_current_map) - 1];
/* Create a work queue for the charger */
di->charger_wq =
create_singlethread_workqueue("ab8500_charger_wq");
if (di->charger_wq == NULL) {
dev_err(di->dev, "failed to create work queue\n");
goto free_device_info;
}
/* Init work for HW failure check */
INIT_DELAYED_WORK_DEFERRABLE(&di->check_hw_failure_work,
ab8500_charger_check_hw_failure_work);
INIT_DELAYED_WORK_DEFERRABLE(&di->check_usbchgnotok_work,
ab8500_charger_check_usbchargernotok_work);
/*
* For ABB revision 1.0 and 1.1 there is a bug in the watchdog
* logic. That means we have to continously kick the charger
* watchdog even when no charger is connected. This is only
* valid once the AC charger has been enabled. This is
* a bug that is not handled by the algorithm and the
* watchdog have to be kicked by the charger driver
* when the AC charger is disabled
*/
INIT_DELAYED_WORK_DEFERRABLE(&di->kick_wd_work,
ab8500_charger_kick_watchdog_work);
INIT_DELAYED_WORK_DEFERRABLE(&di->check_vbat_work,
ab8500_charger_check_vbat_work);
/* Init work for charger detection */
INIT_WORK(&di->usb_link_status_work,
ab8500_charger_usb_link_status_work);
INIT_WORK(&di->ac_work, ab8500_charger_ac_work);
INIT_WORK(&di->detect_usb_type_work,
ab8500_charger_detect_usb_type_work);
INIT_WORK(&di->usb_state_changed_work,
ab8500_charger_usb_state_changed_work);
/* Init work for checking HW status */
INIT_WORK(&di->check_main_thermal_prot_work,
ab8500_charger_check_main_thermal_prot_work);
INIT_WORK(&di->check_usb_thermal_prot_work,
ab8500_charger_check_usb_thermal_prot_work);
/*
* VDD ADC supply needs to be enabled from this driver when there
* is a charger connected to avoid erroneous BTEMP_HIGH/LOW
* interrupts during charging
*/
di->regu = regulator_get(di->dev, "vddadc");
if (IS_ERR(di->regu)) {
ret = PTR_ERR(di->regu);
dev_err(di->dev, "failed to get vddadc regulator\n");
goto free_charger_wq;
}
/* Initialize OVV, and other registers */
ret = ab8500_charger_init_hw_registers(di);
if (ret) {
dev_err(di->dev, "failed to initialize ABB registers\n");
goto free_regulator;
}
/* Register AC charger class */
ret = power_supply_register(di->dev, &di->ac_chg.psy);
if (ret) {
dev_err(di->dev, "failed to register AC charger\n");
goto free_regulator;
}
/* Register USB charger class */
ret = power_supply_register(di->dev, &di->usb_chg.psy);
if (ret) {
dev_err(di->dev, "failed to register USB charger\n");
goto free_ac;
}
di->usb_phy = usb_get_transceiver();
if (!di->usb_phy) {
dev_err(di->dev, "failed to get usb transceiver\n");
ret = -EINVAL;
goto free_usb;
}
di->nb.notifier_call = ab8500_charger_usb_notifier_call;
ret = usb_register_notifier(di->usb_phy, &di->nb);
if (ret) {
dev_err(di->dev, "failed to register usb notifier\n");
goto put_usb_phy;
}
/* Identify the connected charger types during startup */
charger_status = ab8500_charger_detect_chargers(di);
if (charger_status & AC_PW_CONN) {
di->ac.charger_connected = 1;
di->ac_conn = true;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
sysfs_notify(&di->ac_chg.psy.dev->kobj, NULL, "present");
}
if (charger_status & USB_PW_CONN) {
dev_dbg(di->dev, "VBUS Detect during startup\n");
di->vbus_detected = true;
di->vbus_detected_start = true;
queue_work(di->charger_wq,
&di->detect_usb_type_work);
}
/* Register interrupts */
for (i = 0; i < ARRAY_SIZE(ab8500_charger_irq); i++) {
irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name);
ret = request_threaded_irq(irq, NULL, ab8500_charger_irq[i].isr,
IRQF_SHARED | IRQF_NO_SUSPEND,
ab8500_charger_irq[i].name, di);
if (ret != 0) {
dev_err(di->dev, "failed to request %s IRQ %d: %d\n"
, ab8500_charger_irq[i].name, irq, ret);
goto free_irq;
}
dev_dbg(di->dev, "Requested %s IRQ %d: %d\n",
ab8500_charger_irq[i].name, irq, ret);
}
platform_set_drvdata(pdev, di);
return ret;
free_irq:
usb_unregister_notifier(di->usb_phy, &di->nb);
/* We also have to free all successfully registered irqs */
for (i = i - 1; i >= 0; i--) {
irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name);
free_irq(irq, di);
}
put_usb_phy:
usb_put_transceiver(di->usb_phy);
free_usb:
power_supply_unregister(&di->usb_chg.psy);
free_ac:
power_supply_unregister(&di->ac_chg.psy);
free_regulator:
regulator_put(di->regu);
free_charger_wq:
destroy_workqueue(di->charger_wq);
free_device_info:
kfree(di);
return ret;
}
static struct platform_driver ab8500_charger_driver = {
.probe = ab8500_charger_probe,
.remove = __devexit_p(ab8500_charger_remove),
.suspend = ab8500_charger_suspend,
.resume = ab8500_charger_resume,
.driver = {
.name = "ab8500-charger",
.owner = THIS_MODULE,
},
};
static int __init ab8500_charger_init(void)
{
return platform_driver_register(&ab8500_charger_driver);
}
static void __exit ab8500_charger_exit(void)
{
platform_driver_unregister(&ab8500_charger_driver);
}
subsys_initcall_sync(ab8500_charger_init);
module_exit(ab8500_charger_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Johan Palsson, Karl Komierowski, Arun R Murthy");
MODULE_ALIAS("platform:ab8500-charger");
MODULE_DESCRIPTION("AB8500 charger management driver");
| gpl-2.0 |
gunine/htc-rider-univ-kernel | lib/smp_processor_id.c | 4741 | 1119 | /*
* lib/smp_processor_id.c
*
* DEBUG_PREEMPT variant of smp_processor_id().
*/
#include <linux/module.h>
#include <linux/kallsyms.h>
#include <linux/sched.h>
notrace unsigned int debug_smp_processor_id(void)
{
unsigned long preempt_count = preempt_count();
int this_cpu = raw_smp_processor_id();
if (likely(preempt_count))
goto out;
if (irqs_disabled())
goto out;
/*
* Kernel threads bound to a single CPU can safely use
* smp_processor_id():
*/
if (cpumask_equal(¤t->cpus_allowed, cpumask_of(this_cpu)))
goto out;
/*
* It is valid to assume CPU-locality during early bootup:
*/
if (system_state != SYSTEM_RUNNING)
goto out;
/*
* Avoid recursion:
*/
preempt_disable_notrace();
if (!printk_ratelimit())
goto out_enable;
printk(KERN_ERR "BUG: using smp_processor_id() in preemptible [%08x] "
"code: %s/%d\n",
preempt_count() - 1, current->comm, current->pid);
print_symbol("caller is %s\n", (long)__builtin_return_address(0));
dump_stack();
out_enable:
preempt_enable_no_resched_notrace();
out:
return this_cpu;
}
EXPORT_SYMBOL(debug_smp_processor_id);
| gpl-2.0 |
JustAkan/F220K_Stock_Kernel | fs/ncpfs/ioctl.c | 4741 | 22958 | /*
* ioctl.c
*
* Copyright (C) 1995, 1996 by Volker Lendecke
* Modified 1997 Peter Waltenberg, Bill Hawes, David Woodhouse for 2.1 dcache
* Modified 1998, 1999 Wolfram Pienkoss for NLS
*
*/
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/mount.h>
#include <linux/slab.h>
#include <linux/highuid.h>
#include <linux/vmalloc.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include "ncp_fs.h"
/* maximum limit for ncp_objectname_ioctl */
#define NCP_OBJECT_NAME_MAX_LEN 4096
/* maximum limit for ncp_privatedata_ioctl */
#define NCP_PRIVATE_DATA_MAX_LEN 8192
/* maximum negotiable packet size */
#define NCP_PACKET_SIZE_INTERNAL 65536
static int
ncp_get_fs_info(struct ncp_server * server, struct inode *inode,
struct ncp_fs_info __user *arg)
{
struct ncp_fs_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (info.version != NCP_GET_FS_INFO_VERSION) {
DPRINTK("info.version invalid: %d\n", info.version);
return -EINVAL;
}
/* TODO: info.addr = server->m.serv_addr; */
SET_UID(info.mounted_uid, server->m.mounted_uid);
info.connection = server->connection;
info.buffer_size = server->buffer_size;
info.volume_number = NCP_FINFO(inode)->volNumber;
info.directory_id = NCP_FINFO(inode)->DosDirNum;
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
static int
ncp_get_fs_info_v2(struct ncp_server * server, struct inode *inode,
struct ncp_fs_info_v2 __user * arg)
{
struct ncp_fs_info_v2 info2;
if (copy_from_user(&info2, arg, sizeof(info2)))
return -EFAULT;
if (info2.version != NCP_GET_FS_INFO_VERSION_V2) {
DPRINTK("info.version invalid: %d\n", info2.version);
return -EINVAL;
}
info2.mounted_uid = server->m.mounted_uid;
info2.connection = server->connection;
info2.buffer_size = server->buffer_size;
info2.volume_number = NCP_FINFO(inode)->volNumber;
info2.directory_id = NCP_FINFO(inode)->DosDirNum;
info2.dummy1 = info2.dummy2 = info2.dummy3 = 0;
if (copy_to_user(arg, &info2, sizeof(info2)))
return -EFAULT;
return 0;
}
#ifdef CONFIG_COMPAT
struct compat_ncp_objectname_ioctl
{
s32 auth_type;
u32 object_name_len;
compat_caddr_t object_name; /* a userspace data, in most cases user name */
};
struct compat_ncp_fs_info_v2 {
s32 version;
u32 mounted_uid;
u32 connection;
u32 buffer_size;
u32 volume_number;
u32 directory_id;
u32 dummy1;
u32 dummy2;
u32 dummy3;
};
struct compat_ncp_ioctl_request {
u32 function;
u32 size;
compat_caddr_t data;
};
struct compat_ncp_privatedata_ioctl
{
u32 len;
compat_caddr_t data; /* ~1000 for NDS */
};
#define NCP_IOC_GET_FS_INFO_V2_32 _IOWR('n', 4, struct compat_ncp_fs_info_v2)
#define NCP_IOC_NCPREQUEST_32 _IOR('n', 1, struct compat_ncp_ioctl_request)
#define NCP_IOC_GETOBJECTNAME_32 _IOWR('n', 9, struct compat_ncp_objectname_ioctl)
#define NCP_IOC_SETOBJECTNAME_32 _IOR('n', 9, struct compat_ncp_objectname_ioctl)
#define NCP_IOC_GETPRIVATEDATA_32 _IOWR('n', 10, struct compat_ncp_privatedata_ioctl)
#define NCP_IOC_SETPRIVATEDATA_32 _IOR('n', 10, struct compat_ncp_privatedata_ioctl)
static int
ncp_get_compat_fs_info_v2(struct ncp_server * server, struct inode *inode,
struct compat_ncp_fs_info_v2 __user * arg)
{
struct compat_ncp_fs_info_v2 info2;
if (copy_from_user(&info2, arg, sizeof(info2)))
return -EFAULT;
if (info2.version != NCP_GET_FS_INFO_VERSION_V2) {
DPRINTK("info.version invalid: %d\n", info2.version);
return -EINVAL;
}
info2.mounted_uid = server->m.mounted_uid;
info2.connection = server->connection;
info2.buffer_size = server->buffer_size;
info2.volume_number = NCP_FINFO(inode)->volNumber;
info2.directory_id = NCP_FINFO(inode)->DosDirNum;
info2.dummy1 = info2.dummy2 = info2.dummy3 = 0;
if (copy_to_user(arg, &info2, sizeof(info2)))
return -EFAULT;
return 0;
}
#endif
#define NCP_IOC_GETMOUNTUID16 _IOW('n', 2, u16)
#define NCP_IOC_GETMOUNTUID32 _IOW('n', 2, u32)
#define NCP_IOC_GETMOUNTUID64 _IOW('n', 2, u64)
#ifdef CONFIG_NCPFS_NLS
/* Here we are select the iocharset and the codepage for NLS.
* Thanks Petr Vandrovec for idea and many hints.
*/
static int
ncp_set_charsets(struct ncp_server* server, struct ncp_nls_ioctl __user *arg)
{
struct ncp_nls_ioctl user;
struct nls_table *codepage;
struct nls_table *iocharset;
struct nls_table *oldset_io;
struct nls_table *oldset_cp;
int utf8;
int err;
if (copy_from_user(&user, arg, sizeof(user)))
return -EFAULT;
codepage = NULL;
user.codepage[NCP_IOCSNAME_LEN] = 0;
if (!user.codepage[0] || !strcmp(user.codepage, "default"))
codepage = load_nls_default();
else {
codepage = load_nls(user.codepage);
if (!codepage) {
return -EBADRQC;
}
}
iocharset = NULL;
user.iocharset[NCP_IOCSNAME_LEN] = 0;
if (!user.iocharset[0] || !strcmp(user.iocharset, "default")) {
iocharset = load_nls_default();
utf8 = 0;
} else if (!strcmp(user.iocharset, "utf8")) {
iocharset = load_nls_default();
utf8 = 1;
} else {
iocharset = load_nls(user.iocharset);
if (!iocharset) {
unload_nls(codepage);
return -EBADRQC;
}
utf8 = 0;
}
mutex_lock(&server->root_setup_lock);
if (server->root_setuped) {
oldset_cp = codepage;
oldset_io = iocharset;
err = -EBUSY;
} else {
if (utf8)
NCP_SET_FLAG(server, NCP_FLAG_UTF8);
else
NCP_CLR_FLAG(server, NCP_FLAG_UTF8);
oldset_cp = server->nls_vol;
server->nls_vol = codepage;
oldset_io = server->nls_io;
server->nls_io = iocharset;
err = 0;
}
mutex_unlock(&server->root_setup_lock);
unload_nls(oldset_cp);
unload_nls(oldset_io);
return err;
}
static int
ncp_get_charsets(struct ncp_server* server, struct ncp_nls_ioctl __user *arg)
{
struct ncp_nls_ioctl user;
int len;
memset(&user, 0, sizeof(user));
mutex_lock(&server->root_setup_lock);
if (server->nls_vol && server->nls_vol->charset) {
len = strlen(server->nls_vol->charset);
if (len > NCP_IOCSNAME_LEN)
len = NCP_IOCSNAME_LEN;
strncpy(user.codepage, server->nls_vol->charset, len);
user.codepage[len] = 0;
}
if (NCP_IS_FLAG(server, NCP_FLAG_UTF8))
strcpy(user.iocharset, "utf8");
else if (server->nls_io && server->nls_io->charset) {
len = strlen(server->nls_io->charset);
if (len > NCP_IOCSNAME_LEN)
len = NCP_IOCSNAME_LEN;
strncpy(user.iocharset, server->nls_io->charset, len);
user.iocharset[len] = 0;
}
mutex_unlock(&server->root_setup_lock);
if (copy_to_user(arg, &user, sizeof(user)))
return -EFAULT;
return 0;
}
#endif /* CONFIG_NCPFS_NLS */
static long __ncp_ioctl(struct inode *inode, unsigned int cmd, unsigned long arg)
{
struct ncp_server *server = NCP_SERVER(inode);
int result;
struct ncp_ioctl_request request;
char* bouncebuffer;
void __user *argp = (void __user *)arg;
switch (cmd) {
#ifdef CONFIG_COMPAT
case NCP_IOC_NCPREQUEST_32:
#endif
case NCP_IOC_NCPREQUEST:
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_NCPREQUEST_32) {
struct compat_ncp_ioctl_request request32;
if (copy_from_user(&request32, argp, sizeof(request32)))
return -EFAULT;
request.function = request32.function;
request.size = request32.size;
request.data = compat_ptr(request32.data);
} else
#endif
if (copy_from_user(&request, argp, sizeof(request)))
return -EFAULT;
if ((request.function > 255)
|| (request.size >
NCP_PACKET_SIZE - sizeof(struct ncp_request_header))) {
return -EINVAL;
}
bouncebuffer = vmalloc(NCP_PACKET_SIZE_INTERNAL);
if (!bouncebuffer)
return -ENOMEM;
if (copy_from_user(bouncebuffer, request.data, request.size)) {
vfree(bouncebuffer);
return -EFAULT;
}
ncp_lock_server(server);
/* FIXME: We hack around in the server's structures
here to be able to use ncp_request */
server->has_subfunction = 0;
server->current_size = request.size;
memcpy(server->packet, bouncebuffer, request.size);
result = ncp_request2(server, request.function,
bouncebuffer, NCP_PACKET_SIZE_INTERNAL);
if (result < 0)
result = -EIO;
else
result = server->reply_size;
ncp_unlock_server(server);
DPRINTK("ncp_ioctl: copy %d bytes\n",
result);
if (result >= 0)
if (copy_to_user(request.data, bouncebuffer, result))
result = -EFAULT;
vfree(bouncebuffer);
return result;
case NCP_IOC_CONN_LOGGED_IN:
if (!(server->m.int_flags & NCP_IMOUNT_LOGGEDIN_POSSIBLE))
return -EINVAL;
mutex_lock(&server->root_setup_lock);
if (server->root_setuped)
result = -EBUSY;
else {
result = ncp_conn_logged_in(inode->i_sb);
if (result == 0)
server->root_setuped = 1;
}
mutex_unlock(&server->root_setup_lock);
return result;
case NCP_IOC_GET_FS_INFO:
return ncp_get_fs_info(server, inode, argp);
case NCP_IOC_GET_FS_INFO_V2:
return ncp_get_fs_info_v2(server, inode, argp);
#ifdef CONFIG_COMPAT
case NCP_IOC_GET_FS_INFO_V2_32:
return ncp_get_compat_fs_info_v2(server, inode, argp);
#endif
/* we have too many combinations of CONFIG_COMPAT,
* CONFIG_64BIT and CONFIG_UID16, so just handle
* any of the possible ioctls */
case NCP_IOC_GETMOUNTUID16:
{
u16 uid;
SET_UID(uid, server->m.mounted_uid);
if (put_user(uid, (u16 __user *)argp))
return -EFAULT;
return 0;
}
case NCP_IOC_GETMOUNTUID32:
if (put_user(server->m.mounted_uid,
(u32 __user *)argp))
return -EFAULT;
return 0;
case NCP_IOC_GETMOUNTUID64:
if (put_user(server->m.mounted_uid,
(u64 __user *)argp))
return -EFAULT;
return 0;
case NCP_IOC_GETROOT:
{
struct ncp_setroot_ioctl sr;
result = -EACCES;
mutex_lock(&server->root_setup_lock);
if (server->m.mounted_vol[0]) {
struct dentry* dentry = inode->i_sb->s_root;
if (dentry) {
struct inode* s_inode = dentry->d_inode;
if (s_inode) {
sr.volNumber = NCP_FINFO(s_inode)->volNumber;
sr.dirEntNum = NCP_FINFO(s_inode)->dirEntNum;
sr.namespace = server->name_space[sr.volNumber];
result = 0;
} else
DPRINTK("ncpfs: s_root->d_inode==NULL\n");
} else
DPRINTK("ncpfs: s_root==NULL\n");
} else {
sr.volNumber = -1;
sr.namespace = 0;
sr.dirEntNum = 0;
result = 0;
}
mutex_unlock(&server->root_setup_lock);
if (!result && copy_to_user(argp, &sr, sizeof(sr)))
result = -EFAULT;
return result;
}
case NCP_IOC_SETROOT:
{
struct ncp_setroot_ioctl sr;
__u32 vnum;
__le32 de;
__le32 dosde;
struct dentry* dentry;
if (copy_from_user(&sr, argp, sizeof(sr)))
return -EFAULT;
mutex_lock(&server->root_setup_lock);
if (server->root_setuped)
result = -EBUSY;
else {
if (sr.volNumber < 0) {
server->m.mounted_vol[0] = 0;
vnum = NCP_NUMBER_OF_VOLUMES;
de = 0;
dosde = 0;
result = 0;
} else if (sr.volNumber >= NCP_NUMBER_OF_VOLUMES) {
result = -EINVAL;
} else if (ncp_mount_subdir(server, sr.volNumber,
sr.namespace, sr.dirEntNum,
&vnum, &de, &dosde)) {
result = -ENOENT;
} else
result = 0;
if (result == 0) {
dentry = inode->i_sb->s_root;
if (dentry) {
struct inode* s_inode = dentry->d_inode;
if (s_inode) {
NCP_FINFO(s_inode)->volNumber = vnum;
NCP_FINFO(s_inode)->dirEntNum = de;
NCP_FINFO(s_inode)->DosDirNum = dosde;
server->root_setuped = 1;
} else {
DPRINTK("ncpfs: s_root->d_inode==NULL\n");
result = -EIO;
}
} else {
DPRINTK("ncpfs: s_root==NULL\n");
result = -EIO;
}
}
result = 0;
}
mutex_unlock(&server->root_setup_lock);
return result;
}
#ifdef CONFIG_NCPFS_PACKET_SIGNING
case NCP_IOC_SIGN_INIT:
{
struct ncp_sign_init sign;
if (argp)
if (copy_from_user(&sign, argp, sizeof(sign)))
return -EFAULT;
ncp_lock_server(server);
mutex_lock(&server->rcv.creq_mutex);
if (argp) {
if (server->sign_wanted) {
memcpy(server->sign_root,sign.sign_root,8);
memcpy(server->sign_last,sign.sign_last,16);
server->sign_active = 1;
}
/* ignore when signatures not wanted */
} else {
server->sign_active = 0;
}
mutex_unlock(&server->rcv.creq_mutex);
ncp_unlock_server(server);
return 0;
}
case NCP_IOC_SIGN_WANTED:
{
int state;
ncp_lock_server(server);
state = server->sign_wanted;
ncp_unlock_server(server);
if (put_user(state, (int __user *)argp))
return -EFAULT;
return 0;
}
case NCP_IOC_SET_SIGN_WANTED:
{
int newstate;
/* get only low 8 bits... */
if (get_user(newstate, (unsigned char __user *)argp))
return -EFAULT;
result = 0;
ncp_lock_server(server);
if (server->sign_active) {
/* cannot turn signatures OFF when active */
if (!newstate)
result = -EINVAL;
} else {
server->sign_wanted = newstate != 0;
}
ncp_unlock_server(server);
return result;
}
#endif /* CONFIG_NCPFS_PACKET_SIGNING */
#ifdef CONFIG_NCPFS_IOCTL_LOCKING
case NCP_IOC_LOCKUNLOCK:
{
struct ncp_lock_ioctl rqdata;
if (copy_from_user(&rqdata, argp, sizeof(rqdata)))
return -EFAULT;
if (rqdata.origin != 0)
return -EINVAL;
/* check for cmd */
switch (rqdata.cmd) {
case NCP_LOCK_EX:
case NCP_LOCK_SH:
if (rqdata.timeout == 0)
rqdata.timeout = NCP_LOCK_DEFAULT_TIMEOUT;
else if (rqdata.timeout > NCP_LOCK_MAX_TIMEOUT)
rqdata.timeout = NCP_LOCK_MAX_TIMEOUT;
break;
case NCP_LOCK_LOG:
rqdata.timeout = NCP_LOCK_DEFAULT_TIMEOUT; /* has no effect */
case NCP_LOCK_CLEAR:
break;
default:
return -EINVAL;
}
/* locking needs both read and write access */
if ((result = ncp_make_open(inode, O_RDWR)) != 0)
{
return result;
}
result = -EISDIR;
if (!S_ISREG(inode->i_mode))
goto outrel;
if (rqdata.cmd == NCP_LOCK_CLEAR)
{
result = ncp_ClearPhysicalRecord(NCP_SERVER(inode),
NCP_FINFO(inode)->file_handle,
rqdata.offset,
rqdata.length);
if (result > 0) result = 0; /* no such lock */
}
else
{
int lockcmd;
switch (rqdata.cmd)
{
case NCP_LOCK_EX: lockcmd=1; break;
case NCP_LOCK_SH: lockcmd=3; break;
default: lockcmd=0; break;
}
result = ncp_LogPhysicalRecord(NCP_SERVER(inode),
NCP_FINFO(inode)->file_handle,
lockcmd,
rqdata.offset,
rqdata.length,
rqdata.timeout);
if (result > 0) result = -EAGAIN;
}
outrel:
ncp_inode_close(inode);
return result;
}
#endif /* CONFIG_NCPFS_IOCTL_LOCKING */
#ifdef CONFIG_COMPAT
case NCP_IOC_GETOBJECTNAME_32:
{
struct compat_ncp_objectname_ioctl user;
size_t outl;
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
down_read(&server->auth_rwsem);
user.auth_type = server->auth.auth_type;
outl = user.object_name_len;
user.object_name_len = server->auth.object_name_len;
if (outl > user.object_name_len)
outl = user.object_name_len;
result = 0;
if (outl) {
if (copy_to_user(compat_ptr(user.object_name),
server->auth.object_name,
outl))
result = -EFAULT;
}
up_read(&server->auth_rwsem);
if (!result && copy_to_user(argp, &user, sizeof(user)))
result = -EFAULT;
return result;
}
#endif
case NCP_IOC_GETOBJECTNAME:
{
struct ncp_objectname_ioctl user;
size_t outl;
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
down_read(&server->auth_rwsem);
user.auth_type = server->auth.auth_type;
outl = user.object_name_len;
user.object_name_len = server->auth.object_name_len;
if (outl > user.object_name_len)
outl = user.object_name_len;
result = 0;
if (outl) {
if (copy_to_user(user.object_name,
server->auth.object_name,
outl))
result = -EFAULT;
}
up_read(&server->auth_rwsem);
if (!result && copy_to_user(argp, &user, sizeof(user)))
result = -EFAULT;
return result;
}
#ifdef CONFIG_COMPAT
case NCP_IOC_SETOBJECTNAME_32:
#endif
case NCP_IOC_SETOBJECTNAME:
{
struct ncp_objectname_ioctl user;
void* newname;
void* oldname;
size_t oldnamelen;
void* oldprivate;
size_t oldprivatelen;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_SETOBJECTNAME_32) {
struct compat_ncp_objectname_ioctl user32;
if (copy_from_user(&user32, argp, sizeof(user32)))
return -EFAULT;
user.auth_type = user32.auth_type;
user.object_name_len = user32.object_name_len;
user.object_name = compat_ptr(user32.object_name);
} else
#endif
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
if (user.object_name_len > NCP_OBJECT_NAME_MAX_LEN)
return -ENOMEM;
if (user.object_name_len) {
newname = memdup_user(user.object_name,
user.object_name_len);
if (IS_ERR(newname))
return PTR_ERR(newname);
} else {
newname = NULL;
}
down_write(&server->auth_rwsem);
oldname = server->auth.object_name;
oldnamelen = server->auth.object_name_len;
oldprivate = server->priv.data;
oldprivatelen = server->priv.len;
server->auth.auth_type = user.auth_type;
server->auth.object_name_len = user.object_name_len;
server->auth.object_name = newname;
server->priv.len = 0;
server->priv.data = NULL;
up_write(&server->auth_rwsem);
kfree(oldprivate);
kfree(oldname);
return 0;
}
#ifdef CONFIG_COMPAT
case NCP_IOC_GETPRIVATEDATA_32:
#endif
case NCP_IOC_GETPRIVATEDATA:
{
struct ncp_privatedata_ioctl user;
size_t outl;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_GETPRIVATEDATA_32) {
struct compat_ncp_privatedata_ioctl user32;
if (copy_from_user(&user32, argp, sizeof(user32)))
return -EFAULT;
user.len = user32.len;
user.data = compat_ptr(user32.data);
} else
#endif
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
down_read(&server->auth_rwsem);
outl = user.len;
user.len = server->priv.len;
if (outl > user.len) outl = user.len;
result = 0;
if (outl) {
if (copy_to_user(user.data,
server->priv.data,
outl))
result = -EFAULT;
}
up_read(&server->auth_rwsem);
if (result)
return result;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_GETPRIVATEDATA_32) {
struct compat_ncp_privatedata_ioctl user32;
user32.len = user.len;
user32.data = (unsigned long) user.data;
if (copy_to_user(argp, &user32, sizeof(user32)))
return -EFAULT;
} else
#endif
if (copy_to_user(argp, &user, sizeof(user)))
return -EFAULT;
return 0;
}
#ifdef CONFIG_COMPAT
case NCP_IOC_SETPRIVATEDATA_32:
#endif
case NCP_IOC_SETPRIVATEDATA:
{
struct ncp_privatedata_ioctl user;
void* new;
void* old;
size_t oldlen;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_SETPRIVATEDATA_32) {
struct compat_ncp_privatedata_ioctl user32;
if (copy_from_user(&user32, argp, sizeof(user32)))
return -EFAULT;
user.len = user32.len;
user.data = compat_ptr(user32.data);
} else
#endif
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
if (user.len > NCP_PRIVATE_DATA_MAX_LEN)
return -ENOMEM;
if (user.len) {
new = memdup_user(user.data, user.len);
if (IS_ERR(new))
return PTR_ERR(new);
} else {
new = NULL;
}
down_write(&server->auth_rwsem);
old = server->priv.data;
oldlen = server->priv.len;
server->priv.len = user.len;
server->priv.data = new;
up_write(&server->auth_rwsem);
kfree(old);
return 0;
}
#ifdef CONFIG_NCPFS_NLS
case NCP_IOC_SETCHARSETS:
return ncp_set_charsets(server, argp);
case NCP_IOC_GETCHARSETS:
return ncp_get_charsets(server, argp);
#endif /* CONFIG_NCPFS_NLS */
case NCP_IOC_SETDENTRYTTL:
{
u_int32_t user;
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
/* 20 secs at most... */
if (user > 20000)
return -EINVAL;
user = (user * HZ) / 1000;
atomic_set(&server->dentry_ttl, user);
return 0;
}
case NCP_IOC_GETDENTRYTTL:
{
u_int32_t user = (atomic_read(&server->dentry_ttl) * 1000) / HZ;
if (copy_to_user(argp, &user, sizeof(user)))
return -EFAULT;
return 0;
}
}
return -EINVAL;
}
long ncp_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = filp->f_dentry->d_inode;
struct ncp_server *server = NCP_SERVER(inode);
uid_t uid = current_uid();
int need_drop_write = 0;
long ret;
switch (cmd) {
case NCP_IOC_SETCHARSETS:
case NCP_IOC_CONN_LOGGED_IN:
case NCP_IOC_SETROOT:
if (!capable(CAP_SYS_ADMIN)) {
ret = -EACCES;
goto out;
}
break;
}
if (server->m.mounted_uid != uid) {
switch (cmd) {
/*
* Only mount owner can issue these ioctls. Information
* necessary to authenticate to other NDS servers are
* stored here.
*/
case NCP_IOC_GETOBJECTNAME:
case NCP_IOC_SETOBJECTNAME:
case NCP_IOC_GETPRIVATEDATA:
case NCP_IOC_SETPRIVATEDATA:
#ifdef CONFIG_COMPAT
case NCP_IOC_GETOBJECTNAME_32:
case NCP_IOC_SETOBJECTNAME_32:
case NCP_IOC_GETPRIVATEDATA_32:
case NCP_IOC_SETPRIVATEDATA_32:
#endif
ret = -EACCES;
goto out;
/*
* These require write access on the inode if user id
* does not match. Note that they do not write to the
* file... But old code did mnt_want_write, so I keep
* it as is. Of course not for mountpoint owner, as
* that breaks read-only mounts altogether as ncpmount
* needs working NCP_IOC_NCPREQUEST and
* NCP_IOC_GET_FS_INFO. Some of these codes (setdentryttl,
* signinit, setsignwanted) should be probably restricted
* to owner only, or even more to CAP_SYS_ADMIN).
*/
case NCP_IOC_GET_FS_INFO:
case NCP_IOC_GET_FS_INFO_V2:
case NCP_IOC_NCPREQUEST:
case NCP_IOC_SETDENTRYTTL:
case NCP_IOC_SIGN_INIT:
case NCP_IOC_LOCKUNLOCK:
case NCP_IOC_SET_SIGN_WANTED:
#ifdef CONFIG_COMPAT
case NCP_IOC_GET_FS_INFO_V2_32:
case NCP_IOC_NCPREQUEST_32:
#endif
ret = mnt_want_write_file(filp);
if (ret)
goto out;
need_drop_write = 1;
ret = inode_permission(inode, MAY_WRITE);
if (ret)
goto outDropWrite;
break;
/*
* Read access required.
*/
case NCP_IOC_GETMOUNTUID16:
case NCP_IOC_GETMOUNTUID32:
case NCP_IOC_GETMOUNTUID64:
case NCP_IOC_GETROOT:
case NCP_IOC_SIGN_WANTED:
ret = inode_permission(inode, MAY_READ);
if (ret)
goto out;
break;
/*
* Anybody can read these.
*/
case NCP_IOC_GETCHARSETS:
case NCP_IOC_GETDENTRYTTL:
default:
/* Three codes below are protected by CAP_SYS_ADMIN above. */
case NCP_IOC_SETCHARSETS:
case NCP_IOC_CONN_LOGGED_IN:
case NCP_IOC_SETROOT:
break;
}
}
ret = __ncp_ioctl(inode, cmd, arg);
outDropWrite:
if (need_drop_write)
mnt_drop_write_file(filp);
out:
return ret;
}
#ifdef CONFIG_COMPAT
long ncp_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
long ret;
arg = (unsigned long) compat_ptr(arg);
ret = ncp_ioctl(file, cmd, arg);
return ret;
}
#endif
| gpl-2.0 |
chrisc93/bullhead | fs/mpage.c | 7045 | 20452 | /*
* fs/mpage.c
*
* Copyright (C) 2002, Linus Torvalds.
*
* Contains functions related to preparing and submitting BIOs which contain
* multiple pagecache pages.
*
* 15May2002 Andrew Morton
* Initial version
* 27Jun2002 axboe@suse.de
* use bio_add_page() to build bio's just the right size
*/
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/mm.h>
#include <linux/kdev_t.h>
#include <linux/gfp.h>
#include <linux/bio.h>
#include <linux/fs.h>
#include <linux/buffer_head.h>
#include <linux/blkdev.h>
#include <linux/highmem.h>
#include <linux/prefetch.h>
#include <linux/mpage.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/pagevec.h>
#include <linux/cleancache.h>
/*
* I/O completion handler for multipage BIOs.
*
* The mpage code never puts partial pages into a BIO (except for end-of-file).
* If a page does not map to a contiguous run of blocks then it simply falls
* back to block_read_full_page().
*
* Why is this? If a page's completion depends on a number of different BIOs
* which can complete in any order (or at the same time) then determining the
* status of that page is hard. See end_buffer_async_read() for the details.
* There is no point in duplicating all that complexity.
*/
static void mpage_end_io(struct bio *bio, int err)
{
const int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
do {
struct page *page = bvec->bv_page;
if (--bvec >= bio->bi_io_vec)
prefetchw(&bvec->bv_page->flags);
if (bio_data_dir(bio) == READ) {
if (uptodate) {
SetPageUptodate(page);
} else {
ClearPageUptodate(page);
SetPageError(page);
}
unlock_page(page);
} else { /* bio_data_dir(bio) == WRITE */
if (!uptodate) {
SetPageError(page);
if (page->mapping)
set_bit(AS_EIO, &page->mapping->flags);
}
end_page_writeback(page);
}
} while (bvec >= bio->bi_io_vec);
bio_put(bio);
}
static struct bio *mpage_bio_submit(int rw, struct bio *bio)
{
bio->bi_end_io = mpage_end_io;
submit_bio(rw, bio);
return NULL;
}
static struct bio *
mpage_alloc(struct block_device *bdev,
sector_t first_sector, int nr_vecs,
gfp_t gfp_flags)
{
struct bio *bio;
bio = bio_alloc(gfp_flags, nr_vecs);
if (bio == NULL && (current->flags & PF_MEMALLOC)) {
while (!bio && (nr_vecs /= 2))
bio = bio_alloc(gfp_flags, nr_vecs);
}
if (bio) {
bio->bi_bdev = bdev;
bio->bi_sector = first_sector;
}
return bio;
}
/*
* support function for mpage_readpages. The fs supplied get_block might
* return an up to date buffer. This is used to map that buffer into
* the page, which allows readpage to avoid triggering a duplicate call
* to get_block.
*
* The idea is to avoid adding buffers to pages that don't already have
* them. So when the buffer is up to date and the page size == block size,
* this marks the page up to date instead of adding new buffers.
*/
static void
map_buffer_to_page(struct page *page, struct buffer_head *bh, int page_block)
{
struct inode *inode = page->mapping->host;
struct buffer_head *page_bh, *head;
int block = 0;
if (!page_has_buffers(page)) {
/*
* don't make any buffers if there is only one buffer on
* the page and the page just needs to be set up to date
*/
if (inode->i_blkbits == PAGE_CACHE_SHIFT &&
buffer_uptodate(bh)) {
SetPageUptodate(page);
return;
}
create_empty_buffers(page, 1 << inode->i_blkbits, 0);
}
head = page_buffers(page);
page_bh = head;
do {
if (block == page_block) {
page_bh->b_state = bh->b_state;
page_bh->b_bdev = bh->b_bdev;
page_bh->b_blocknr = bh->b_blocknr;
break;
}
page_bh = page_bh->b_this_page;
block++;
} while (page_bh != head);
}
/*
* This is the worker routine which does all the work of mapping the disk
* blocks and constructs largest possible bios, submits them for IO if the
* blocks are not contiguous on the disk.
*
* We pass a buffer_head back and forth and use its buffer_mapped() flag to
* represent the validity of its disk mapping and to decide when to do the next
* get_block() call.
*/
static struct bio *
do_mpage_readpage(struct bio *bio, struct page *page, unsigned nr_pages,
sector_t *last_block_in_bio, struct buffer_head *map_bh,
unsigned long *first_logical_block, get_block_t get_block)
{
struct inode *inode = page->mapping->host;
const unsigned blkbits = inode->i_blkbits;
const unsigned blocks_per_page = PAGE_CACHE_SIZE >> blkbits;
const unsigned blocksize = 1 << blkbits;
sector_t block_in_file;
sector_t last_block;
sector_t last_block_in_file;
sector_t blocks[MAX_BUF_PER_PAGE];
unsigned page_block;
unsigned first_hole = blocks_per_page;
struct block_device *bdev = NULL;
int length;
int fully_mapped = 1;
unsigned nblocks;
unsigned relative_block;
if (page_has_buffers(page))
goto confused;
block_in_file = (sector_t)page->index << (PAGE_CACHE_SHIFT - blkbits);
last_block = block_in_file + nr_pages * blocks_per_page;
last_block_in_file = (i_size_read(inode) + blocksize - 1) >> blkbits;
if (last_block > last_block_in_file)
last_block = last_block_in_file;
page_block = 0;
/*
* Map blocks using the result from the previous get_blocks call first.
*/
nblocks = map_bh->b_size >> blkbits;
if (buffer_mapped(map_bh) && block_in_file > *first_logical_block &&
block_in_file < (*first_logical_block + nblocks)) {
unsigned map_offset = block_in_file - *first_logical_block;
unsigned last = nblocks - map_offset;
for (relative_block = 0; ; relative_block++) {
if (relative_block == last) {
clear_buffer_mapped(map_bh);
break;
}
if (page_block == blocks_per_page)
break;
blocks[page_block] = map_bh->b_blocknr + map_offset +
relative_block;
page_block++;
block_in_file++;
}
bdev = map_bh->b_bdev;
}
/*
* Then do more get_blocks calls until we are done with this page.
*/
map_bh->b_page = page;
while (page_block < blocks_per_page) {
map_bh->b_state = 0;
map_bh->b_size = 0;
if (block_in_file < last_block) {
map_bh->b_size = (last_block-block_in_file) << blkbits;
if (get_block(inode, block_in_file, map_bh, 0))
goto confused;
*first_logical_block = block_in_file;
}
if (!buffer_mapped(map_bh)) {
fully_mapped = 0;
if (first_hole == blocks_per_page)
first_hole = page_block;
page_block++;
block_in_file++;
continue;
}
/* some filesystems will copy data into the page during
* the get_block call, in which case we don't want to
* read it again. map_buffer_to_page copies the data
* we just collected from get_block into the page's buffers
* so readpage doesn't have to repeat the get_block call
*/
if (buffer_uptodate(map_bh)) {
map_buffer_to_page(page, map_bh, page_block);
goto confused;
}
if (first_hole != blocks_per_page)
goto confused; /* hole -> non-hole */
/* Contiguous blocks? */
if (page_block && blocks[page_block-1] != map_bh->b_blocknr-1)
goto confused;
nblocks = map_bh->b_size >> blkbits;
for (relative_block = 0; ; relative_block++) {
if (relative_block == nblocks) {
clear_buffer_mapped(map_bh);
break;
} else if (page_block == blocks_per_page)
break;
blocks[page_block] = map_bh->b_blocknr+relative_block;
page_block++;
block_in_file++;
}
bdev = map_bh->b_bdev;
}
if (first_hole != blocks_per_page) {
zero_user_segment(page, first_hole << blkbits, PAGE_CACHE_SIZE);
if (first_hole == 0) {
SetPageUptodate(page);
unlock_page(page);
goto out;
}
} else if (fully_mapped) {
SetPageMappedToDisk(page);
}
if (fully_mapped && blocks_per_page == 1 && !PageUptodate(page) &&
cleancache_get_page(page) == 0) {
SetPageUptodate(page);
goto confused;
}
/*
* This page will go to BIO. Do we need to send this BIO off first?
*/
if (bio && (*last_block_in_bio != blocks[0] - 1))
bio = mpage_bio_submit(READ, bio);
alloc_new:
if (bio == NULL) {
bio = mpage_alloc(bdev, blocks[0] << (blkbits - 9),
min_t(int, nr_pages, bio_get_nr_vecs(bdev)),
GFP_KERNEL);
if (bio == NULL)
goto confused;
}
length = first_hole << blkbits;
if (bio_add_page(bio, page, length, 0) < length) {
bio = mpage_bio_submit(READ, bio);
goto alloc_new;
}
relative_block = block_in_file - *first_logical_block;
nblocks = map_bh->b_size >> blkbits;
if ((buffer_boundary(map_bh) && relative_block == nblocks) ||
(first_hole != blocks_per_page))
bio = mpage_bio_submit(READ, bio);
else
*last_block_in_bio = blocks[blocks_per_page - 1];
out:
return bio;
confused:
if (bio)
bio = mpage_bio_submit(READ, bio);
if (!PageUptodate(page))
block_read_full_page(page, get_block);
else
unlock_page(page);
goto out;
}
/**
* mpage_readpages - populate an address space with some pages & start reads against them
* @mapping: the address_space
* @pages: The address of a list_head which contains the target pages. These
* pages have their ->index populated and are otherwise uninitialised.
* The page at @pages->prev has the lowest file offset, and reads should be
* issued in @pages->prev to @pages->next order.
* @nr_pages: The number of pages at *@pages
* @get_block: The filesystem's block mapper function.
*
* This function walks the pages and the blocks within each page, building and
* emitting large BIOs.
*
* If anything unusual happens, such as:
*
* - encountering a page which has buffers
* - encountering a page which has a non-hole after a hole
* - encountering a page with non-contiguous blocks
*
* then this code just gives up and calls the buffer_head-based read function.
* It does handle a page which has holes at the end - that is a common case:
* the end-of-file on blocksize < PAGE_CACHE_SIZE setups.
*
* BH_Boundary explanation:
*
* There is a problem. The mpage read code assembles several pages, gets all
* their disk mappings, and then submits them all. That's fine, but obtaining
* the disk mappings may require I/O. Reads of indirect blocks, for example.
*
* So an mpage read of the first 16 blocks of an ext2 file will cause I/O to be
* submitted in the following order:
* 12 0 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16
*
* because the indirect block has to be read to get the mappings of blocks
* 13,14,15,16. Obviously, this impacts performance.
*
* So what we do it to allow the filesystem's get_block() function to set
* BH_Boundary when it maps block 11. BH_Boundary says: mapping of the block
* after this one will require I/O against a block which is probably close to
* this one. So you should push what I/O you have currently accumulated.
*
* This all causes the disk requests to be issued in the correct order.
*/
int
mpage_readpages(struct address_space *mapping, struct list_head *pages,
unsigned nr_pages, get_block_t get_block)
{
struct bio *bio = NULL;
unsigned page_idx;
sector_t last_block_in_bio = 0;
struct buffer_head map_bh;
unsigned long first_logical_block = 0;
map_bh.b_state = 0;
map_bh.b_size = 0;
for (page_idx = 0; page_idx < nr_pages; page_idx++) {
struct page *page = list_entry(pages->prev, struct page, lru);
prefetchw(&page->flags);
list_del(&page->lru);
if (!add_to_page_cache_lru(page, mapping,
page->index, GFP_KERNEL)) {
bio = do_mpage_readpage(bio, page,
nr_pages - page_idx,
&last_block_in_bio, &map_bh,
&first_logical_block,
get_block);
}
page_cache_release(page);
}
BUG_ON(!list_empty(pages));
if (bio)
mpage_bio_submit(READ, bio);
return 0;
}
EXPORT_SYMBOL(mpage_readpages);
/*
* This isn't called much at all
*/
int mpage_readpage(struct page *page, get_block_t get_block)
{
struct bio *bio = NULL;
sector_t last_block_in_bio = 0;
struct buffer_head map_bh;
unsigned long first_logical_block = 0;
map_bh.b_state = 0;
map_bh.b_size = 0;
bio = do_mpage_readpage(bio, page, 1, &last_block_in_bio,
&map_bh, &first_logical_block, get_block);
if (bio)
mpage_bio_submit(READ, bio);
return 0;
}
EXPORT_SYMBOL(mpage_readpage);
/*
* Writing is not so simple.
*
* If the page has buffers then they will be used for obtaining the disk
* mapping. We only support pages which are fully mapped-and-dirty, with a
* special case for pages which are unmapped at the end: end-of-file.
*
* If the page has no buffers (preferred) then the page is mapped here.
*
* If all blocks are found to be contiguous then the page can go into the
* BIO. Otherwise fall back to the mapping's writepage().
*
* FIXME: This code wants an estimate of how many pages are still to be
* written, so it can intelligently allocate a suitably-sized BIO. For now,
* just allocate full-size (16-page) BIOs.
*/
struct mpage_data {
struct bio *bio;
sector_t last_block_in_bio;
get_block_t *get_block;
unsigned use_writepage;
};
static int __mpage_writepage(struct page *page, struct writeback_control *wbc,
void *data)
{
struct mpage_data *mpd = data;
struct bio *bio = mpd->bio;
struct address_space *mapping = page->mapping;
struct inode *inode = page->mapping->host;
const unsigned blkbits = inode->i_blkbits;
unsigned long end_index;
const unsigned blocks_per_page = PAGE_CACHE_SIZE >> blkbits;
sector_t last_block;
sector_t block_in_file;
sector_t blocks[MAX_BUF_PER_PAGE];
unsigned page_block;
unsigned first_unmapped = blocks_per_page;
struct block_device *bdev = NULL;
int boundary = 0;
sector_t boundary_block = 0;
struct block_device *boundary_bdev = NULL;
int length;
struct buffer_head map_bh;
loff_t i_size = i_size_read(inode);
int ret = 0;
if (page_has_buffers(page)) {
struct buffer_head *head = page_buffers(page);
struct buffer_head *bh = head;
/* If they're all mapped and dirty, do it */
page_block = 0;
do {
BUG_ON(buffer_locked(bh));
if (!buffer_mapped(bh)) {
/*
* unmapped dirty buffers are created by
* __set_page_dirty_buffers -> mmapped data
*/
if (buffer_dirty(bh))
goto confused;
if (first_unmapped == blocks_per_page)
first_unmapped = page_block;
continue;
}
if (first_unmapped != blocks_per_page)
goto confused; /* hole -> non-hole */
if (!buffer_dirty(bh) || !buffer_uptodate(bh))
goto confused;
if (page_block) {
if (bh->b_blocknr != blocks[page_block-1] + 1)
goto confused;
}
blocks[page_block++] = bh->b_blocknr;
boundary = buffer_boundary(bh);
if (boundary) {
boundary_block = bh->b_blocknr;
boundary_bdev = bh->b_bdev;
}
bdev = bh->b_bdev;
} while ((bh = bh->b_this_page) != head);
if (first_unmapped)
goto page_is_mapped;
/*
* Page has buffers, but they are all unmapped. The page was
* created by pagein or read over a hole which was handled by
* block_read_full_page(). If this address_space is also
* using mpage_readpages then this can rarely happen.
*/
goto confused;
}
/*
* The page has no buffers: map it to disk
*/
BUG_ON(!PageUptodate(page));
block_in_file = (sector_t)page->index << (PAGE_CACHE_SHIFT - blkbits);
last_block = (i_size - 1) >> blkbits;
map_bh.b_page = page;
for (page_block = 0; page_block < blocks_per_page; ) {
map_bh.b_state = 0;
map_bh.b_size = 1 << blkbits;
if (mpd->get_block(inode, block_in_file, &map_bh, 1))
goto confused;
if (buffer_new(&map_bh))
unmap_underlying_metadata(map_bh.b_bdev,
map_bh.b_blocknr);
if (buffer_boundary(&map_bh)) {
boundary_block = map_bh.b_blocknr;
boundary_bdev = map_bh.b_bdev;
}
if (page_block) {
if (map_bh.b_blocknr != blocks[page_block-1] + 1)
goto confused;
}
blocks[page_block++] = map_bh.b_blocknr;
boundary = buffer_boundary(&map_bh);
bdev = map_bh.b_bdev;
if (block_in_file == last_block)
break;
block_in_file++;
}
BUG_ON(page_block == 0);
first_unmapped = page_block;
page_is_mapped:
end_index = i_size >> PAGE_CACHE_SHIFT;
if (page->index >= end_index) {
/*
* The page straddles i_size. It must be zeroed out on each
* and every writepage invocation because it may be mmapped.
* "A file is mapped in multiples of the page size. For a file
* that is not a multiple of the page size, the remaining memory
* is zeroed when mapped, and writes to that region are not
* written out to the file."
*/
unsigned offset = i_size & (PAGE_CACHE_SIZE - 1);
if (page->index > end_index || !offset)
goto confused;
zero_user_segment(page, offset, PAGE_CACHE_SIZE);
}
/*
* This page will go to BIO. Do we need to send this BIO off first?
*/
if (bio && mpd->last_block_in_bio != blocks[0] - 1)
bio = mpage_bio_submit(WRITE, bio);
alloc_new:
if (bio == NULL) {
bio = mpage_alloc(bdev, blocks[0] << (blkbits - 9),
bio_get_nr_vecs(bdev), GFP_NOFS|__GFP_HIGH);
if (bio == NULL)
goto confused;
}
/*
* Must try to add the page before marking the buffer clean or
* the confused fail path above (OOM) will be very confused when
* it finds all bh marked clean (i.e. it will not write anything)
*/
length = first_unmapped << blkbits;
if (bio_add_page(bio, page, length, 0) < length) {
bio = mpage_bio_submit(WRITE, bio);
goto alloc_new;
}
/*
* OK, we have our BIO, so we can now mark the buffers clean. Make
* sure to only clean buffers which we know we'll be writing.
*/
if (page_has_buffers(page)) {
struct buffer_head *head = page_buffers(page);
struct buffer_head *bh = head;
unsigned buffer_counter = 0;
do {
if (buffer_counter++ == first_unmapped)
break;
clear_buffer_dirty(bh);
bh = bh->b_this_page;
} while (bh != head);
/*
* we cannot drop the bh if the page is not uptodate
* or a concurrent readpage would fail to serialize with the bh
* and it would read from disk before we reach the platter.
*/
if (buffer_heads_over_limit && PageUptodate(page))
try_to_free_buffers(page);
}
BUG_ON(PageWriteback(page));
set_page_writeback(page);
unlock_page(page);
if (boundary || (first_unmapped != blocks_per_page)) {
bio = mpage_bio_submit(WRITE, bio);
if (boundary_block) {
write_boundary_block(boundary_bdev,
boundary_block, 1 << blkbits);
}
} else {
mpd->last_block_in_bio = blocks[blocks_per_page - 1];
}
goto out;
confused:
if (bio)
bio = mpage_bio_submit(WRITE, bio);
if (mpd->use_writepage) {
ret = mapping->a_ops->writepage(page, wbc);
} else {
ret = -EAGAIN;
goto out;
}
/*
* The caller has a ref on the inode, so *mapping is stable
*/
mapping_set_error(mapping, ret);
out:
mpd->bio = bio;
return ret;
}
/**
* mpage_writepages - walk the list of dirty pages of the given address space & writepage() all of them
* @mapping: address space structure to write
* @wbc: subtract the number of written pages from *@wbc->nr_to_write
* @get_block: the filesystem's block mapper function.
* If this is NULL then use a_ops->writepage. Otherwise, go
* direct-to-BIO.
*
* This is a library function, which implements the writepages()
* address_space_operation.
*
* If a page is already under I/O, generic_writepages() skips it, even
* if it's dirty. This is desirable behaviour for memory-cleaning writeback,
* but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
* and msync() need to guarantee that all the data which was dirty at the time
* the call was made get new I/O started against them. If wbc->sync_mode is
* WB_SYNC_ALL then we were called for data integrity and we must wait for
* existing IO to complete.
*/
int
mpage_writepages(struct address_space *mapping,
struct writeback_control *wbc, get_block_t get_block)
{
struct blk_plug plug;
int ret;
blk_start_plug(&plug);
if (!get_block)
ret = generic_writepages(mapping, wbc);
else {
struct mpage_data mpd = {
.bio = NULL,
.last_block_in_bio = 0,
.get_block = get_block,
.use_writepage = 1,
};
ret = write_cache_pages(mapping, wbc, __mpage_writepage, &mpd);
if (mpd.bio)
mpage_bio_submit(WRITE, mpd.bio);
}
blk_finish_plug(&plug);
return ret;
}
EXPORT_SYMBOL(mpage_writepages);
int mpage_writepage(struct page *page, get_block_t get_block,
struct writeback_control *wbc)
{
struct mpage_data mpd = {
.bio = NULL,
.last_block_in_bio = 0,
.get_block = get_block,
.use_writepage = 0,
};
int ret = __mpage_writepage(page, wbc, &mpd);
if (mpd.bio)
mpage_bio_submit(WRITE, mpd.bio);
return ret;
}
EXPORT_SYMBOL(mpage_writepage);
| gpl-2.0 |
trader418/android_kernel_samsung_hlte_N | drivers/net/wireless/rtlwifi/rtl8192cu/phy.c | 7557 | 18741 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../pci.h"
#include "../ps.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "rf.h"
#include "dm.h"
#include "table.h"
u32 rtl92cu_phy_query_rf_reg(struct ieee80211_hw *hw,
enum radio_path rfpath, u32 regaddr, u32 bitmask)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 original_value, readback_value, bitshift;
struct rtl_phy *rtlphy = &(rtlpriv->phy);
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), rfpath(%#x), bitmask(%#x)\n",
regaddr, rfpath, bitmask);
if (rtlphy->rf_mode != RF_OP_BY_FW) {
original_value = _rtl92c_phy_rf_serial_read(hw,
rfpath, regaddr);
} else {
original_value = _rtl92c_phy_fw_rf_serial_read(hw,
rfpath, regaddr);
}
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
readback_value = (original_value & bitmask) >> bitshift;
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), rfpath(%#x), bitmask(%#x), original_value(%#x)\n",
regaddr, rfpath, bitmask, original_value);
return readback_value;
}
void rtl92cu_phy_set_rf_reg(struct ieee80211_hw *hw,
enum radio_path rfpath,
u32 regaddr, u32 bitmask, u32 data)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u32 original_value, bitshift;
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), bitmask(%#x), data(%#x), rfpath(%#x)\n",
regaddr, bitmask, data, rfpath);
if (rtlphy->rf_mode != RF_OP_BY_FW) {
if (bitmask != RFREG_OFFSET_MASK) {
original_value = _rtl92c_phy_rf_serial_read(hw,
rfpath,
regaddr);
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
data =
((original_value & (~bitmask)) |
(data << bitshift));
}
_rtl92c_phy_rf_serial_write(hw, rfpath, regaddr, data);
} else {
if (bitmask != RFREG_OFFSET_MASK) {
original_value = _rtl92c_phy_fw_rf_serial_read(hw,
rfpath,
regaddr);
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
data =
((original_value & (~bitmask)) |
(data << bitshift));
}
_rtl92c_phy_fw_rf_serial_write(hw, rfpath, regaddr, data);
}
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), bitmask(%#x), data(%#x), rfpath(%#x)\n",
regaddr, bitmask, data, rfpath);
}
bool rtl92cu_phy_mac_config(struct ieee80211_hw *hw)
{
bool rtstatus;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
bool is92c = IS_92C_SERIAL(rtlhal->version);
rtstatus = _rtl92cu_phy_config_mac_with_headerfile(hw);
if (is92c && IS_HARDWARE_TYPE_8192CE(rtlhal))
rtl_write_byte(rtlpriv, 0x14, 0x71);
return rtstatus;
}
bool rtl92cu_phy_bb_config(struct ieee80211_hw *hw)
{
bool rtstatus = true;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
u16 regval;
u8 b_reg_hwparafile = 1;
_rtl92c_phy_init_bb_rf_register_definition(hw);
regval = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, regval | BIT(13) |
BIT(0) | BIT(1));
rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL, 0x83);
rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL + 1, 0xdb);
rtl_write_byte(rtlpriv, REG_RF_CTRL, RF_EN | RF_RSTB | RF_SDMRSTB);
if (IS_HARDWARE_TYPE_8192CE(rtlhal)) {
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_PPLL | FEN_PCIEA |
FEN_DIO_PCIE | FEN_BB_GLB_RSTn | FEN_BBRSTB);
} else if (IS_HARDWARE_TYPE_8192CU(rtlhal)) {
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_USBA | FEN_USBD |
FEN_BB_GLB_RSTn | FEN_BBRSTB);
rtl_write_byte(rtlpriv, REG_LDOHCI12_CTRL, 0x0f);
}
rtl_write_byte(rtlpriv, REG_AFE_XTAL_CTRL + 1, 0x80);
if (b_reg_hwparafile == 1)
rtstatus = _rtl92c_phy_bb8192c_config_parafile(hw);
return rtstatus;
}
bool _rtl92cu_phy_config_mac_with_headerfile(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u32 i;
u32 arraylength;
u32 *ptrarray;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Read Rtl819XMACPHY_Array\n");
arraylength = rtlphy->hwparam_tables[MAC_REG].length ;
ptrarray = rtlphy->hwparam_tables[MAC_REG].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Img:RTL8192CEMAC_2T_ARRAY\n");
for (i = 0; i < arraylength; i = i + 2)
rtl_write_byte(rtlpriv, ptrarray[i], (u8) ptrarray[i + 1]);
return true;
}
bool _rtl92cu_phy_config_bb_with_headerfile(struct ieee80211_hw *hw,
u8 configtype)
{
int i;
u32 *phy_regarray_table;
u32 *agctab_array_table;
u16 phy_reg_arraylen, agctab_arraylen;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
if (IS_92C_SERIAL(rtlhal->version)) {
agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_2T].length;
agctab_array_table = rtlphy->hwparam_tables[AGCTAB_2T].pdata;
phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_2T].length;
phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_2T].pdata;
} else {
agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_1T].length;
agctab_array_table = rtlphy->hwparam_tables[AGCTAB_1T].pdata;
phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_1T].length;
phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_1T].pdata;
}
if (configtype == BASEBAND_CONFIG_PHY_REG) {
for (i = 0; i < phy_reg_arraylen; i = i + 2) {
if (phy_regarray_table[i] == 0xfe)
mdelay(50);
else if (phy_regarray_table[i] == 0xfd)
mdelay(5);
else if (phy_regarray_table[i] == 0xfc)
mdelay(1);
else if (phy_regarray_table[i] == 0xfb)
udelay(50);
else if (phy_regarray_table[i] == 0xfa)
udelay(5);
else if (phy_regarray_table[i] == 0xf9)
udelay(1);
rtl_set_bbreg(hw, phy_regarray_table[i], MASKDWORD,
phy_regarray_table[i + 1]);
udelay(1);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"The phy_regarray_table[0] is %x Rtl819XPHY_REGArray[1] is %x\n",
phy_regarray_table[i],
phy_regarray_table[i + 1]);
}
} else if (configtype == BASEBAND_CONFIG_AGC_TAB) {
for (i = 0; i < agctab_arraylen; i = i + 2) {
rtl_set_bbreg(hw, agctab_array_table[i], MASKDWORD,
agctab_array_table[i + 1]);
udelay(1);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"The agctab_array_table[0] is %x Rtl819XPHY_REGArray[1] is %x\n",
agctab_array_table[i],
agctab_array_table[i + 1]);
}
}
return true;
}
bool _rtl92cu_phy_config_bb_with_pgheaderfile(struct ieee80211_hw *hw,
u8 configtype)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
int i;
u32 *phy_regarray_table_pg;
u16 phy_regarray_pg_len;
rtlphy->pwrgroup_cnt = 0;
phy_regarray_pg_len = rtlphy->hwparam_tables[PHY_REG_PG].length;
phy_regarray_table_pg = rtlphy->hwparam_tables[PHY_REG_PG].pdata;
if (configtype == BASEBAND_CONFIG_PHY_REG) {
for (i = 0; i < phy_regarray_pg_len; i = i + 3) {
if (phy_regarray_table_pg[i] == 0xfe)
mdelay(50);
else if (phy_regarray_table_pg[i] == 0xfd)
mdelay(5);
else if (phy_regarray_table_pg[i] == 0xfc)
mdelay(1);
else if (phy_regarray_table_pg[i] == 0xfb)
udelay(50);
else if (phy_regarray_table_pg[i] == 0xfa)
udelay(5);
else if (phy_regarray_table_pg[i] == 0xf9)
udelay(1);
_rtl92c_store_pwrIndex_diffrate_offset(hw,
phy_regarray_table_pg[i],
phy_regarray_table_pg[i + 1],
phy_regarray_table_pg[i + 2]);
}
} else {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"configtype != BaseBand_Config_PHY_REG\n");
}
return true;
}
bool rtl92cu_phy_config_rf_with_headerfile(struct ieee80211_hw *hw,
enum radio_path rfpath)
{
int i;
u32 *radioa_array_table;
u32 *radiob_array_table;
u16 radioa_arraylen, radiob_arraylen;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
if (IS_92C_SERIAL(rtlhal->version)) {
radioa_arraylen = rtlphy->hwparam_tables[RADIOA_2T].length;
radioa_array_table = rtlphy->hwparam_tables[RADIOA_2T].pdata;
radiob_arraylen = rtlphy->hwparam_tables[RADIOB_2T].length;
radiob_array_table = rtlphy->hwparam_tables[RADIOB_2T].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_A:RTL8192CERADIOA_2TARRAY\n");
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_B:RTL8192CE_RADIOB_2TARRAY\n");
} else {
radioa_arraylen = rtlphy->hwparam_tables[RADIOA_1T].length;
radioa_array_table = rtlphy->hwparam_tables[RADIOA_1T].pdata;
radiob_arraylen = rtlphy->hwparam_tables[RADIOB_1T].length;
radiob_array_table = rtlphy->hwparam_tables[RADIOB_1T].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_A:RTL8192CE_RADIOA_1TARRAY\n");
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_B:RTL8192CE_RADIOB_1TARRAY\n");
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Radio No %x\n", rfpath);
switch (rfpath) {
case RF90_PATH_A:
for (i = 0; i < radioa_arraylen; i = i + 2) {
if (radioa_array_table[i] == 0xfe)
mdelay(50);
else if (radioa_array_table[i] == 0xfd)
mdelay(5);
else if (radioa_array_table[i] == 0xfc)
mdelay(1);
else if (radioa_array_table[i] == 0xfb)
udelay(50);
else if (radioa_array_table[i] == 0xfa)
udelay(5);
else if (radioa_array_table[i] == 0xf9)
udelay(1);
else {
rtl_set_rfreg(hw, rfpath, radioa_array_table[i],
RFREG_OFFSET_MASK,
radioa_array_table[i + 1]);
udelay(1);
}
}
break;
case RF90_PATH_B:
for (i = 0; i < radiob_arraylen; i = i + 2) {
if (radiob_array_table[i] == 0xfe) {
mdelay(50);
} else if (radiob_array_table[i] == 0xfd)
mdelay(5);
else if (radiob_array_table[i] == 0xfc)
mdelay(1);
else if (radiob_array_table[i] == 0xfb)
udelay(50);
else if (radiob_array_table[i] == 0xfa)
udelay(5);
else if (radiob_array_table[i] == 0xf9)
udelay(1);
else {
rtl_set_rfreg(hw, rfpath, radiob_array_table[i],
RFREG_OFFSET_MASK,
radiob_array_table[i + 1]);
udelay(1);
}
}
break;
case RF90_PATH_C:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
case RF90_PATH_D:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
return true;
}
void rtl92cu_phy_set_bw_mode_callback(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u8 reg_bw_opmode;
u8 reg_prsr_rsc;
RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, "Switch to %s bandwidth\n",
rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20 ?
"20MHz" : "40MHz");
if (is_hal_stop(rtlhal)) {
rtlphy->set_bwmode_inprogress = false;
return;
}
reg_bw_opmode = rtl_read_byte(rtlpriv, REG_BWOPMODE);
reg_prsr_rsc = rtl_read_byte(rtlpriv, REG_RRSR + 2);
switch (rtlphy->current_chan_bw) {
case HT_CHANNEL_WIDTH_20:
reg_bw_opmode |= BW_OPMODE_20MHZ;
rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode);
break;
case HT_CHANNEL_WIDTH_20_40:
reg_bw_opmode &= ~BW_OPMODE_20MHZ;
rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode);
reg_prsr_rsc =
(reg_prsr_rsc & 0x90) | (mac->cur_40_prime_sc << 5);
rtl_write_byte(rtlpriv, REG_RRSR + 2, reg_prsr_rsc);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"unknown bandwidth: %#X\n", rtlphy->current_chan_bw);
break;
}
switch (rtlphy->current_chan_bw) {
case HT_CHANNEL_WIDTH_20:
rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x0);
rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x0);
rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 1);
break;
case HT_CHANNEL_WIDTH_20_40:
rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x1);
rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x1);
rtl_set_bbreg(hw, RCCK0_SYSTEM, BCCK_SIDEBAND,
(mac->cur_40_prime_sc >> 1));
rtl_set_bbreg(hw, ROFDM1_LSTF, 0xC00, mac->cur_40_prime_sc);
rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 0);
rtl_set_bbreg(hw, 0x818, (BIT(26) | BIT(27)),
(mac->cur_40_prime_sc ==
HAL_PRIME_CHNL_OFFSET_LOWER) ? 2 : 1);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"unknown bandwidth: %#X\n", rtlphy->current_chan_bw);
break;
}
rtl92cu_phy_rf6052_set_bandwidth(hw, rtlphy->current_chan_bw);
rtlphy->set_bwmode_inprogress = false;
RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, "<==\n");
}
void rtl92cu_bb_block_on(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
mutex_lock(&rtlpriv->io.bb_mutex);
rtl_set_bbreg(hw, RFPGA0_RFMOD, BCCKEN, 0x1);
rtl_set_bbreg(hw, RFPGA0_RFMOD, BOFDMEN, 0x1);
mutex_unlock(&rtlpriv->io.bb_mutex);
}
void _rtl92cu_phy_lc_calibrate(struct ieee80211_hw *hw, bool is2t)
{
u8 tmpreg;
u32 rf_a_mode = 0, rf_b_mode = 0, lc_cal;
struct rtl_priv *rtlpriv = rtl_priv(hw);
tmpreg = rtl_read_byte(rtlpriv, 0xd03);
if ((tmpreg & 0x70) != 0)
rtl_write_byte(rtlpriv, 0xd03, tmpreg & 0x8F);
else
rtl_write_byte(rtlpriv, REG_TXPAUSE, 0xFF);
if ((tmpreg & 0x70) != 0) {
rf_a_mode = rtl_get_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS);
if (is2t)
rf_b_mode = rtl_get_rfreg(hw, RF90_PATH_B, 0x00,
MASK12BITS);
rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS,
(rf_a_mode & 0x8FFFF) | 0x10000);
if (is2t)
rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS,
(rf_b_mode & 0x8FFFF) | 0x10000);
}
lc_cal = rtl_get_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS);
rtl_set_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS, lc_cal | 0x08000);
mdelay(100);
if ((tmpreg & 0x70) != 0) {
rtl_write_byte(rtlpriv, 0xd03, tmpreg);
rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS, rf_a_mode);
if (is2t)
rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS,
rf_b_mode);
} else {
rtl_write_byte(rtlpriv, REG_TXPAUSE, 0x00);
}
}
static bool _rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw,
enum rf_pwrstate rfpwr_state)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool bresult = true;
u8 i, queue_id;
struct rtl8192_tx_ring *ring = NULL;
switch (rfpwr_state) {
case ERFON:
if ((ppsc->rfpwr_state == ERFOFF) &&
RT_IN_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC)) {
bool rtstatus;
u32 InitializeCount = 0;
do {
InitializeCount++;
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"IPS Set eRf nic enable\n");
rtstatus = rtl_ps_enable_nic(hw);
} while (!rtstatus && (InitializeCount < 10));
RT_CLEAR_PS_LEVEL(ppsc,
RT_RF_OFF_LEVL_HALT_NIC);
} else {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"Set ERFON sleeped:%d ms\n",
jiffies_to_msecs(jiffies -
ppsc->last_sleep_jiffies));
ppsc->last_awake_jiffies = jiffies;
rtl92ce_phy_set_rf_on(hw);
}
if (mac->link_state == MAC80211_LINKED) {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_LINK);
} else {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_NO_LINK);
}
break;
case ERFOFF:
for (queue_id = 0, i = 0;
queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) {
ring = &pcipriv->dev.tx_ring[queue_id];
if (skb_queue_len(&ring->queue) == 0 ||
queue_id == BEACON_QUEUE) {
queue_id++;
continue;
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"eRf Off/Sleep: %d times TcbBusyQueue[%d] =%d before doze!\n",
i + 1,
queue_id,
skb_queue_len(&ring->queue));
udelay(10);
i++;
}
if (i >= MAX_DOZE_WAITING_TIMES_9x) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"ERFOFF: %d times TcbBusyQueue[%d] = %d !\n",
MAX_DOZE_WAITING_TIMES_9x,
queue_id,
skb_queue_len(&ring->queue));
break;
}
}
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_HALT_NIC) {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"IPS Set eRf nic disable\n");
rtl_ps_disable_nic(hw);
RT_SET_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC);
} else {
if (ppsc->rfoff_reason == RF_CHANGE_BY_IPS) {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_NO_LINK);
} else {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_POWER_OFF);
}
}
break;
case ERFSLEEP:
if (ppsc->rfpwr_state == ERFOFF)
return false;
for (queue_id = 0, i = 0;
queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) {
ring = &pcipriv->dev.tx_ring[queue_id];
if (skb_queue_len(&ring->queue) == 0) {
queue_id++;
continue;
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"eRf Off/Sleep: %d times TcbBusyQueue[%d] =%d before doze!\n",
i + 1, queue_id,
skb_queue_len(&ring->queue));
udelay(10);
i++;
}
if (i >= MAX_DOZE_WAITING_TIMES_9x) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"ERFSLEEP: %d times TcbBusyQueue[%d] = %d !\n",
MAX_DOZE_WAITING_TIMES_9x,
queue_id,
skb_queue_len(&ring->queue));
break;
}
}
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"Set ERFSLEEP awaked:%d ms\n",
jiffies_to_msecs(jiffies - ppsc->last_awake_jiffies));
ppsc->last_sleep_jiffies = jiffies;
_rtl92c_phy_set_rf_sleep(hw);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
bresult = false;
break;
}
if (bresult)
ppsc->rfpwr_state = rfpwr_state;
return bresult;
}
bool rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw,
enum rf_pwrstate rfpwr_state)
{
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool bresult = false;
if (rfpwr_state == ppsc->rfpwr_state)
return bresult;
bresult = _rtl92cu_phy_set_rf_power_state(hw, rfpwr_state);
return bresult;
}
| gpl-2.0 |
championswimmer/kernel_sony_msm8960t | drivers/net/wireless/rtlwifi/rtl8192cu/phy.c | 7557 | 18741 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../pci.h"
#include "../ps.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "rf.h"
#include "dm.h"
#include "table.h"
u32 rtl92cu_phy_query_rf_reg(struct ieee80211_hw *hw,
enum radio_path rfpath, u32 regaddr, u32 bitmask)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 original_value, readback_value, bitshift;
struct rtl_phy *rtlphy = &(rtlpriv->phy);
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), rfpath(%#x), bitmask(%#x)\n",
regaddr, rfpath, bitmask);
if (rtlphy->rf_mode != RF_OP_BY_FW) {
original_value = _rtl92c_phy_rf_serial_read(hw,
rfpath, regaddr);
} else {
original_value = _rtl92c_phy_fw_rf_serial_read(hw,
rfpath, regaddr);
}
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
readback_value = (original_value & bitmask) >> bitshift;
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), rfpath(%#x), bitmask(%#x), original_value(%#x)\n",
regaddr, rfpath, bitmask, original_value);
return readback_value;
}
void rtl92cu_phy_set_rf_reg(struct ieee80211_hw *hw,
enum radio_path rfpath,
u32 regaddr, u32 bitmask, u32 data)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u32 original_value, bitshift;
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), bitmask(%#x), data(%#x), rfpath(%#x)\n",
regaddr, bitmask, data, rfpath);
if (rtlphy->rf_mode != RF_OP_BY_FW) {
if (bitmask != RFREG_OFFSET_MASK) {
original_value = _rtl92c_phy_rf_serial_read(hw,
rfpath,
regaddr);
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
data =
((original_value & (~bitmask)) |
(data << bitshift));
}
_rtl92c_phy_rf_serial_write(hw, rfpath, regaddr, data);
} else {
if (bitmask != RFREG_OFFSET_MASK) {
original_value = _rtl92c_phy_fw_rf_serial_read(hw,
rfpath,
regaddr);
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
data =
((original_value & (~bitmask)) |
(data << bitshift));
}
_rtl92c_phy_fw_rf_serial_write(hw, rfpath, regaddr, data);
}
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), bitmask(%#x), data(%#x), rfpath(%#x)\n",
regaddr, bitmask, data, rfpath);
}
bool rtl92cu_phy_mac_config(struct ieee80211_hw *hw)
{
bool rtstatus;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
bool is92c = IS_92C_SERIAL(rtlhal->version);
rtstatus = _rtl92cu_phy_config_mac_with_headerfile(hw);
if (is92c && IS_HARDWARE_TYPE_8192CE(rtlhal))
rtl_write_byte(rtlpriv, 0x14, 0x71);
return rtstatus;
}
bool rtl92cu_phy_bb_config(struct ieee80211_hw *hw)
{
bool rtstatus = true;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
u16 regval;
u8 b_reg_hwparafile = 1;
_rtl92c_phy_init_bb_rf_register_definition(hw);
regval = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, regval | BIT(13) |
BIT(0) | BIT(1));
rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL, 0x83);
rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL + 1, 0xdb);
rtl_write_byte(rtlpriv, REG_RF_CTRL, RF_EN | RF_RSTB | RF_SDMRSTB);
if (IS_HARDWARE_TYPE_8192CE(rtlhal)) {
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_PPLL | FEN_PCIEA |
FEN_DIO_PCIE | FEN_BB_GLB_RSTn | FEN_BBRSTB);
} else if (IS_HARDWARE_TYPE_8192CU(rtlhal)) {
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_USBA | FEN_USBD |
FEN_BB_GLB_RSTn | FEN_BBRSTB);
rtl_write_byte(rtlpriv, REG_LDOHCI12_CTRL, 0x0f);
}
rtl_write_byte(rtlpriv, REG_AFE_XTAL_CTRL + 1, 0x80);
if (b_reg_hwparafile == 1)
rtstatus = _rtl92c_phy_bb8192c_config_parafile(hw);
return rtstatus;
}
bool _rtl92cu_phy_config_mac_with_headerfile(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u32 i;
u32 arraylength;
u32 *ptrarray;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Read Rtl819XMACPHY_Array\n");
arraylength = rtlphy->hwparam_tables[MAC_REG].length ;
ptrarray = rtlphy->hwparam_tables[MAC_REG].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Img:RTL8192CEMAC_2T_ARRAY\n");
for (i = 0; i < arraylength; i = i + 2)
rtl_write_byte(rtlpriv, ptrarray[i], (u8) ptrarray[i + 1]);
return true;
}
bool _rtl92cu_phy_config_bb_with_headerfile(struct ieee80211_hw *hw,
u8 configtype)
{
int i;
u32 *phy_regarray_table;
u32 *agctab_array_table;
u16 phy_reg_arraylen, agctab_arraylen;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
if (IS_92C_SERIAL(rtlhal->version)) {
agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_2T].length;
agctab_array_table = rtlphy->hwparam_tables[AGCTAB_2T].pdata;
phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_2T].length;
phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_2T].pdata;
} else {
agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_1T].length;
agctab_array_table = rtlphy->hwparam_tables[AGCTAB_1T].pdata;
phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_1T].length;
phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_1T].pdata;
}
if (configtype == BASEBAND_CONFIG_PHY_REG) {
for (i = 0; i < phy_reg_arraylen; i = i + 2) {
if (phy_regarray_table[i] == 0xfe)
mdelay(50);
else if (phy_regarray_table[i] == 0xfd)
mdelay(5);
else if (phy_regarray_table[i] == 0xfc)
mdelay(1);
else if (phy_regarray_table[i] == 0xfb)
udelay(50);
else if (phy_regarray_table[i] == 0xfa)
udelay(5);
else if (phy_regarray_table[i] == 0xf9)
udelay(1);
rtl_set_bbreg(hw, phy_regarray_table[i], MASKDWORD,
phy_regarray_table[i + 1]);
udelay(1);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"The phy_regarray_table[0] is %x Rtl819XPHY_REGArray[1] is %x\n",
phy_regarray_table[i],
phy_regarray_table[i + 1]);
}
} else if (configtype == BASEBAND_CONFIG_AGC_TAB) {
for (i = 0; i < agctab_arraylen; i = i + 2) {
rtl_set_bbreg(hw, agctab_array_table[i], MASKDWORD,
agctab_array_table[i + 1]);
udelay(1);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"The agctab_array_table[0] is %x Rtl819XPHY_REGArray[1] is %x\n",
agctab_array_table[i],
agctab_array_table[i + 1]);
}
}
return true;
}
bool _rtl92cu_phy_config_bb_with_pgheaderfile(struct ieee80211_hw *hw,
u8 configtype)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
int i;
u32 *phy_regarray_table_pg;
u16 phy_regarray_pg_len;
rtlphy->pwrgroup_cnt = 0;
phy_regarray_pg_len = rtlphy->hwparam_tables[PHY_REG_PG].length;
phy_regarray_table_pg = rtlphy->hwparam_tables[PHY_REG_PG].pdata;
if (configtype == BASEBAND_CONFIG_PHY_REG) {
for (i = 0; i < phy_regarray_pg_len; i = i + 3) {
if (phy_regarray_table_pg[i] == 0xfe)
mdelay(50);
else if (phy_regarray_table_pg[i] == 0xfd)
mdelay(5);
else if (phy_regarray_table_pg[i] == 0xfc)
mdelay(1);
else if (phy_regarray_table_pg[i] == 0xfb)
udelay(50);
else if (phy_regarray_table_pg[i] == 0xfa)
udelay(5);
else if (phy_regarray_table_pg[i] == 0xf9)
udelay(1);
_rtl92c_store_pwrIndex_diffrate_offset(hw,
phy_regarray_table_pg[i],
phy_regarray_table_pg[i + 1],
phy_regarray_table_pg[i + 2]);
}
} else {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"configtype != BaseBand_Config_PHY_REG\n");
}
return true;
}
bool rtl92cu_phy_config_rf_with_headerfile(struct ieee80211_hw *hw,
enum radio_path rfpath)
{
int i;
u32 *radioa_array_table;
u32 *radiob_array_table;
u16 radioa_arraylen, radiob_arraylen;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
if (IS_92C_SERIAL(rtlhal->version)) {
radioa_arraylen = rtlphy->hwparam_tables[RADIOA_2T].length;
radioa_array_table = rtlphy->hwparam_tables[RADIOA_2T].pdata;
radiob_arraylen = rtlphy->hwparam_tables[RADIOB_2T].length;
radiob_array_table = rtlphy->hwparam_tables[RADIOB_2T].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_A:RTL8192CERADIOA_2TARRAY\n");
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_B:RTL8192CE_RADIOB_2TARRAY\n");
} else {
radioa_arraylen = rtlphy->hwparam_tables[RADIOA_1T].length;
radioa_array_table = rtlphy->hwparam_tables[RADIOA_1T].pdata;
radiob_arraylen = rtlphy->hwparam_tables[RADIOB_1T].length;
radiob_array_table = rtlphy->hwparam_tables[RADIOB_1T].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_A:RTL8192CE_RADIOA_1TARRAY\n");
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_B:RTL8192CE_RADIOB_1TARRAY\n");
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Radio No %x\n", rfpath);
switch (rfpath) {
case RF90_PATH_A:
for (i = 0; i < radioa_arraylen; i = i + 2) {
if (radioa_array_table[i] == 0xfe)
mdelay(50);
else if (radioa_array_table[i] == 0xfd)
mdelay(5);
else if (radioa_array_table[i] == 0xfc)
mdelay(1);
else if (radioa_array_table[i] == 0xfb)
udelay(50);
else if (radioa_array_table[i] == 0xfa)
udelay(5);
else if (radioa_array_table[i] == 0xf9)
udelay(1);
else {
rtl_set_rfreg(hw, rfpath, radioa_array_table[i],
RFREG_OFFSET_MASK,
radioa_array_table[i + 1]);
udelay(1);
}
}
break;
case RF90_PATH_B:
for (i = 0; i < radiob_arraylen; i = i + 2) {
if (radiob_array_table[i] == 0xfe) {
mdelay(50);
} else if (radiob_array_table[i] == 0xfd)
mdelay(5);
else if (radiob_array_table[i] == 0xfc)
mdelay(1);
else if (radiob_array_table[i] == 0xfb)
udelay(50);
else if (radiob_array_table[i] == 0xfa)
udelay(5);
else if (radiob_array_table[i] == 0xf9)
udelay(1);
else {
rtl_set_rfreg(hw, rfpath, radiob_array_table[i],
RFREG_OFFSET_MASK,
radiob_array_table[i + 1]);
udelay(1);
}
}
break;
case RF90_PATH_C:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
case RF90_PATH_D:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
return true;
}
void rtl92cu_phy_set_bw_mode_callback(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u8 reg_bw_opmode;
u8 reg_prsr_rsc;
RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, "Switch to %s bandwidth\n",
rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20 ?
"20MHz" : "40MHz");
if (is_hal_stop(rtlhal)) {
rtlphy->set_bwmode_inprogress = false;
return;
}
reg_bw_opmode = rtl_read_byte(rtlpriv, REG_BWOPMODE);
reg_prsr_rsc = rtl_read_byte(rtlpriv, REG_RRSR + 2);
switch (rtlphy->current_chan_bw) {
case HT_CHANNEL_WIDTH_20:
reg_bw_opmode |= BW_OPMODE_20MHZ;
rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode);
break;
case HT_CHANNEL_WIDTH_20_40:
reg_bw_opmode &= ~BW_OPMODE_20MHZ;
rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode);
reg_prsr_rsc =
(reg_prsr_rsc & 0x90) | (mac->cur_40_prime_sc << 5);
rtl_write_byte(rtlpriv, REG_RRSR + 2, reg_prsr_rsc);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"unknown bandwidth: %#X\n", rtlphy->current_chan_bw);
break;
}
switch (rtlphy->current_chan_bw) {
case HT_CHANNEL_WIDTH_20:
rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x0);
rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x0);
rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 1);
break;
case HT_CHANNEL_WIDTH_20_40:
rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x1);
rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x1);
rtl_set_bbreg(hw, RCCK0_SYSTEM, BCCK_SIDEBAND,
(mac->cur_40_prime_sc >> 1));
rtl_set_bbreg(hw, ROFDM1_LSTF, 0xC00, mac->cur_40_prime_sc);
rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 0);
rtl_set_bbreg(hw, 0x818, (BIT(26) | BIT(27)),
(mac->cur_40_prime_sc ==
HAL_PRIME_CHNL_OFFSET_LOWER) ? 2 : 1);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"unknown bandwidth: %#X\n", rtlphy->current_chan_bw);
break;
}
rtl92cu_phy_rf6052_set_bandwidth(hw, rtlphy->current_chan_bw);
rtlphy->set_bwmode_inprogress = false;
RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, "<==\n");
}
void rtl92cu_bb_block_on(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
mutex_lock(&rtlpriv->io.bb_mutex);
rtl_set_bbreg(hw, RFPGA0_RFMOD, BCCKEN, 0x1);
rtl_set_bbreg(hw, RFPGA0_RFMOD, BOFDMEN, 0x1);
mutex_unlock(&rtlpriv->io.bb_mutex);
}
void _rtl92cu_phy_lc_calibrate(struct ieee80211_hw *hw, bool is2t)
{
u8 tmpreg;
u32 rf_a_mode = 0, rf_b_mode = 0, lc_cal;
struct rtl_priv *rtlpriv = rtl_priv(hw);
tmpreg = rtl_read_byte(rtlpriv, 0xd03);
if ((tmpreg & 0x70) != 0)
rtl_write_byte(rtlpriv, 0xd03, tmpreg & 0x8F);
else
rtl_write_byte(rtlpriv, REG_TXPAUSE, 0xFF);
if ((tmpreg & 0x70) != 0) {
rf_a_mode = rtl_get_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS);
if (is2t)
rf_b_mode = rtl_get_rfreg(hw, RF90_PATH_B, 0x00,
MASK12BITS);
rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS,
(rf_a_mode & 0x8FFFF) | 0x10000);
if (is2t)
rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS,
(rf_b_mode & 0x8FFFF) | 0x10000);
}
lc_cal = rtl_get_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS);
rtl_set_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS, lc_cal | 0x08000);
mdelay(100);
if ((tmpreg & 0x70) != 0) {
rtl_write_byte(rtlpriv, 0xd03, tmpreg);
rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS, rf_a_mode);
if (is2t)
rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS,
rf_b_mode);
} else {
rtl_write_byte(rtlpriv, REG_TXPAUSE, 0x00);
}
}
static bool _rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw,
enum rf_pwrstate rfpwr_state)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool bresult = true;
u8 i, queue_id;
struct rtl8192_tx_ring *ring = NULL;
switch (rfpwr_state) {
case ERFON:
if ((ppsc->rfpwr_state == ERFOFF) &&
RT_IN_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC)) {
bool rtstatus;
u32 InitializeCount = 0;
do {
InitializeCount++;
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"IPS Set eRf nic enable\n");
rtstatus = rtl_ps_enable_nic(hw);
} while (!rtstatus && (InitializeCount < 10));
RT_CLEAR_PS_LEVEL(ppsc,
RT_RF_OFF_LEVL_HALT_NIC);
} else {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"Set ERFON sleeped:%d ms\n",
jiffies_to_msecs(jiffies -
ppsc->last_sleep_jiffies));
ppsc->last_awake_jiffies = jiffies;
rtl92ce_phy_set_rf_on(hw);
}
if (mac->link_state == MAC80211_LINKED) {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_LINK);
} else {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_NO_LINK);
}
break;
case ERFOFF:
for (queue_id = 0, i = 0;
queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) {
ring = &pcipriv->dev.tx_ring[queue_id];
if (skb_queue_len(&ring->queue) == 0 ||
queue_id == BEACON_QUEUE) {
queue_id++;
continue;
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"eRf Off/Sleep: %d times TcbBusyQueue[%d] =%d before doze!\n",
i + 1,
queue_id,
skb_queue_len(&ring->queue));
udelay(10);
i++;
}
if (i >= MAX_DOZE_WAITING_TIMES_9x) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"ERFOFF: %d times TcbBusyQueue[%d] = %d !\n",
MAX_DOZE_WAITING_TIMES_9x,
queue_id,
skb_queue_len(&ring->queue));
break;
}
}
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_HALT_NIC) {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"IPS Set eRf nic disable\n");
rtl_ps_disable_nic(hw);
RT_SET_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC);
} else {
if (ppsc->rfoff_reason == RF_CHANGE_BY_IPS) {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_NO_LINK);
} else {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_POWER_OFF);
}
}
break;
case ERFSLEEP:
if (ppsc->rfpwr_state == ERFOFF)
return false;
for (queue_id = 0, i = 0;
queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) {
ring = &pcipriv->dev.tx_ring[queue_id];
if (skb_queue_len(&ring->queue) == 0) {
queue_id++;
continue;
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"eRf Off/Sleep: %d times TcbBusyQueue[%d] =%d before doze!\n",
i + 1, queue_id,
skb_queue_len(&ring->queue));
udelay(10);
i++;
}
if (i >= MAX_DOZE_WAITING_TIMES_9x) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"ERFSLEEP: %d times TcbBusyQueue[%d] = %d !\n",
MAX_DOZE_WAITING_TIMES_9x,
queue_id,
skb_queue_len(&ring->queue));
break;
}
}
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"Set ERFSLEEP awaked:%d ms\n",
jiffies_to_msecs(jiffies - ppsc->last_awake_jiffies));
ppsc->last_sleep_jiffies = jiffies;
_rtl92c_phy_set_rf_sleep(hw);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
bresult = false;
break;
}
if (bresult)
ppsc->rfpwr_state = rfpwr_state;
return bresult;
}
bool rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw,
enum rf_pwrstate rfpwr_state)
{
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool bresult = false;
if (rfpwr_state == ppsc->rfpwr_state)
return bresult;
bresult = _rtl92cu_phy_set_rf_power_state(hw, rfpwr_state);
return bresult;
}
| gpl-2.0 |
Samsung-BCM/android_kernel_samsung_bcm | arch/h8300/kernel/timer/timer16.c | 7813 | 1603 | /*
* linux/arch/h8300/kernel/timer/timer16.c
*
* Yoshinori Sato <ysato@users.sourcefoge.jp>
*
* 16bit Timer Handler
*
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/timex.h>
#include <asm/segment.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/regs306x.h>
/* 16bit timer */
#if CONFIG_H8300_TIMER16_CH == 0
#define _16BASE 0xffff78
#define _16IRQ 24
#elif CONFIG_H8300_TIMER16_CH == 1
#define _16BASE 0xffff80
#define _16IRQ 28
#elif CONFIG_H8300_TIMER16_CH == 2
#define _16BASE 0xffff88
#define _16IRQ 32
#else
#error Unknown timer channel.
#endif
#define TCR 0
#define TIOR 1
#define TCNT 2
#define GRA 4
#define GRB 6
#define H8300_TIMER_FREQ CONFIG_CPU_CLOCK*10000 /* Timer input freq. */
static irqreturn_t timer_interrupt(int irq, void *dev_id)
{
h8300_timer_tick();
ctrl_bclr(CONFIG_H8300_TIMER16_CH, TISRA);
return IRQ_HANDLED;
}
static struct irqaction timer16_irq = {
.name = "timer-16",
.handler = timer_interrupt,
.flags = IRQF_DISABLED | IRQF_TIMER,
};
static const int __initdata divide_rate[] = {1, 2, 4, 8};
void __init h8300_timer_setup(void)
{
unsigned int div;
unsigned int cnt;
calc_param(cnt, div, divide_rate, 0x10000);
setup_irq(_16IRQ, &timer16_irq);
/* initialize timer */
ctrl_outb(0, TSTR);
ctrl_outb(CCLR0 | div, _16BASE + TCR);
ctrl_outw(cnt, _16BASE + GRA);
ctrl_bset(4 + CONFIG_H8300_TIMER16_CH, TISRA);
ctrl_bset(CONFIG_H8300_TIMER16_CH, TSTR);
}
| gpl-2.0 |
aaronpoweruser/android_kernel_oppo_find5 | drivers/input/joystick/iforce/iforce-main.c | 9093 | 13366 | /*
* Copyright (c) 2000-2002 Vojtech Pavlik <vojtech@ucw.cz>
* Copyright (c) 2001-2002, 2007 Johann Deneux <johann.deneux@gmail.com>
*
* USB/RS232 I-Force joysticks and wheels.
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include "iforce.h"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>, Johann Deneux <johann.deneux@gmail.com>");
MODULE_DESCRIPTION("USB/RS232 I-Force joysticks and wheels driver");
MODULE_LICENSE("GPL");
static signed short btn_joystick[] =
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_BASE5, BTN_A, BTN_B, BTN_C, -1 };
static signed short btn_avb_pegasus[] =
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, -1 };
static signed short btn_wheel[] =
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_BASE5, BTN_A, BTN_B, BTN_C, -1 };
static signed short btn_avb_tw[] =
{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, -1 };
static signed short btn_avb_wheel[] =
{ BTN_GEAR_DOWN, BTN_GEAR_UP, BTN_BASE, BTN_BASE2, BTN_BASE3,
BTN_BASE4, BTN_BASE5, BTN_BASE6, -1 };
static signed short abs_joystick[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short abs_joystick_rudder[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short abs_avb_pegasus[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, ABS_HAT0X, ABS_HAT0Y,
ABS_HAT1X, ABS_HAT1Y, -1 };
static signed short abs_wheel[] =
{ ABS_WHEEL, ABS_GAS, ABS_BRAKE, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short ff_iforce[] =
{ FF_PERIODIC, FF_CONSTANT, FF_SPRING, FF_DAMPER,
FF_SQUARE, FF_TRIANGLE, FF_SINE, FF_SAW_UP, FF_SAW_DOWN, FF_GAIN,
FF_AUTOCENTER, -1 };
static struct iforce_device iforce_device[] = {
{ 0x044f, 0xa01c, "Thrustmaster Motor Sport GT", btn_wheel, abs_wheel, ff_iforce },
{ 0x046d, 0xc281, "Logitech WingMan Force", btn_joystick, abs_joystick, ff_iforce },
{ 0x046d, 0xc291, "Logitech WingMan Formula Force", btn_wheel, abs_wheel, ff_iforce },
{ 0x05ef, 0x020a, "AVB Top Shot Pegasus", btn_avb_pegasus, abs_avb_pegasus, ff_iforce },
{ 0x05ef, 0x8884, "AVB Mag Turbo Force", btn_avb_wheel, abs_wheel, ff_iforce },
{ 0x05ef, 0x8888, "AVB Top Shot Force Feedback Racing Wheel", btn_avb_tw, abs_wheel, ff_iforce }, //?
{ 0x061c, 0xc0a4, "ACT LABS Force RS", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x061c, 0xc084, "ACT LABS Force RS", btn_wheel, abs_wheel, ff_iforce },
{ 0x06f8, 0x0001, "Guillemot Race Leader Force Feedback", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x06f8, 0x0001, "Guillemot Jet Leader Force Feedback", btn_joystick, abs_joystick_rudder, ff_iforce },
{ 0x06f8, 0x0004, "Guillemot Force Feedback Racing Wheel", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x06f8, 0xa302, "Guillemot Jet Leader 3D", btn_joystick, abs_joystick, ff_iforce }, //?
{ 0x06d6, 0x29bc, "Trust Force Feedback Race Master", btn_wheel, abs_wheel, ff_iforce },
{ 0x0000, 0x0000, "Unknown I-Force Device [%04x:%04x]", btn_joystick, abs_joystick, ff_iforce }
};
static int iforce_playback(struct input_dev *dev, int effect_id, int value)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect_id];
if (value > 0)
set_bit(FF_CORE_SHOULD_PLAY, core_effect->flags);
else
clear_bit(FF_CORE_SHOULD_PLAY, core_effect->flags);
iforce_control_playback(iforce, effect_id, value);
return 0;
}
static void iforce_set_gain(struct input_dev *dev, u16 gain)
{
struct iforce *iforce = input_get_drvdata(dev);
unsigned char data[3];
data[0] = gain >> 9;
iforce_send_packet(iforce, FF_CMD_GAIN, data);
}
static void iforce_set_autocenter(struct input_dev *dev, u16 magnitude)
{
struct iforce *iforce = input_get_drvdata(dev);
unsigned char data[3];
data[0] = 0x03;
data[1] = magnitude >> 9;
iforce_send_packet(iforce, FF_CMD_AUTOCENTER, data);
data[0] = 0x04;
data[1] = 0x01;
iforce_send_packet(iforce, FF_CMD_AUTOCENTER, data);
}
/*
* Function called when an ioctl is performed on the event dev entry.
* It uploads an effect to the device
*/
static int iforce_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect->id];
int ret;
if (__test_and_set_bit(FF_CORE_IS_USED, core_effect->flags)) {
/* Check the effect is not already being updated */
if (test_bit(FF_CORE_UPDATE, core_effect->flags))
return -EAGAIN;
}
/*
* Upload the effect
*/
switch (effect->type) {
case FF_PERIODIC:
ret = iforce_upload_periodic(iforce, effect, old);
break;
case FF_CONSTANT:
ret = iforce_upload_constant(iforce, effect, old);
break;
case FF_SPRING:
case FF_DAMPER:
ret = iforce_upload_condition(iforce, effect, old);
break;
default:
return -EINVAL;
}
if (ret == 0) {
/* A packet was sent, forbid new updates until we are notified
* that the packet was updated
*/
set_bit(FF_CORE_UPDATE, core_effect->flags);
}
return ret;
}
/*
* Erases an effect: it frees the effect id and mark as unused the memory
* allocated for the parameters
*/
static int iforce_erase_effect(struct input_dev *dev, int effect_id)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect_id];
int err = 0;
if (test_bit(FF_MOD1_IS_USED, core_effect->flags))
err = release_resource(&core_effect->mod1_chunk);
if (!err && test_bit(FF_MOD2_IS_USED, core_effect->flags))
err = release_resource(&core_effect->mod2_chunk);
/* TODO: remember to change that if more FF_MOD* bits are added */
core_effect->flags[0] = 0;
return err;
}
static int iforce_open(struct input_dev *dev)
{
struct iforce *iforce = input_get_drvdata(dev);
switch (iforce->bus) {
#ifdef CONFIG_JOYSTICK_IFORCE_USB
case IFORCE_USB:
iforce->irq->dev = iforce->usbdev;
if (usb_submit_urb(iforce->irq, GFP_KERNEL))
return -EIO;
break;
#endif
}
if (test_bit(EV_FF, dev->evbit)) {
/* Enable force feedback */
iforce_send_packet(iforce, FF_CMD_ENABLE, "\004");
}
return 0;
}
static void iforce_close(struct input_dev *dev)
{
struct iforce *iforce = input_get_drvdata(dev);
int i;
if (test_bit(EV_FF, dev->evbit)) {
/* Check: no effects should be present in memory */
for (i = 0; i < dev->ff->max_effects; i++) {
if (test_bit(FF_CORE_IS_USED, iforce->core_effects[i].flags)) {
dev_warn(&dev->dev,
"%s: Device still owns effects\n",
__func__);
break;
}
}
/* Disable force feedback playback */
iforce_send_packet(iforce, FF_CMD_ENABLE, "\001");
/* Wait for the command to complete */
wait_event_interruptible(iforce->wait,
!test_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags));
}
switch (iforce->bus) {
#ifdef CONFIG_JOYSTICK_IFORCE_USB
case IFORCE_USB:
usb_kill_urb(iforce->irq);
usb_kill_urb(iforce->out);
usb_kill_urb(iforce->ctrl);
break;
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
case IFORCE_232:
//TODO: Wait for the last packets to be sent
break;
#endif
}
}
int iforce_init_device(struct iforce *iforce)
{
struct input_dev *input_dev;
struct ff_device *ff;
unsigned char c[] = "CEOV";
int i, error;
int ff_effects = 0;
input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
init_waitqueue_head(&iforce->wait);
spin_lock_init(&iforce->xmit_lock);
mutex_init(&iforce->mem_mutex);
iforce->xmit.buf = iforce->xmit_data;
iforce->dev = input_dev;
/*
* Input device fields.
*/
switch (iforce->bus) {
#ifdef CONFIG_JOYSTICK_IFORCE_USB
case IFORCE_USB:
input_dev->id.bustype = BUS_USB;
input_dev->dev.parent = &iforce->usbdev->dev;
break;
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
case IFORCE_232:
input_dev->id.bustype = BUS_RS232;
input_dev->dev.parent = &iforce->serio->dev;
break;
#endif
}
input_set_drvdata(input_dev, iforce);
input_dev->name = "Unknown I-Force device";
input_dev->open = iforce_open;
input_dev->close = iforce_close;
/*
* On-device memory allocation.
*/
iforce->device_memory.name = "I-Force device effect memory";
iforce->device_memory.start = 0;
iforce->device_memory.end = 200;
iforce->device_memory.flags = IORESOURCE_MEM;
iforce->device_memory.parent = NULL;
iforce->device_memory.child = NULL;
iforce->device_memory.sibling = NULL;
/*
* Wait until device ready - until it sends its first response.
*/
for (i = 0; i < 20; i++)
if (!iforce_get_id_packet(iforce, "O"))
break;
if (i == 20) { /* 5 seconds */
err("Timeout waiting for response from device.");
error = -ENODEV;
goto fail;
}
/*
* Get device info.
*/
if (!iforce_get_id_packet(iforce, "M"))
input_dev->id.vendor = (iforce->edata[2] << 8) | iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet M\n");
if (!iforce_get_id_packet(iforce, "P"))
input_dev->id.product = (iforce->edata[2] << 8) | iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet P\n");
if (!iforce_get_id_packet(iforce, "B"))
iforce->device_memory.end = (iforce->edata[2] << 8) | iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet B\n");
if (!iforce_get_id_packet(iforce, "N"))
ff_effects = iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet N\n");
/* Check if the device can store more effects than the driver can really handle */
if (ff_effects > IFORCE_EFFECTS_MAX) {
dev_warn(&iforce->dev->dev, "Limiting number of effects to %d (device reports %d)\n",
IFORCE_EFFECTS_MAX, ff_effects);
ff_effects = IFORCE_EFFECTS_MAX;
}
/*
* Display additional info.
*/
for (i = 0; c[i]; i++)
if (!iforce_get_id_packet(iforce, c + i))
iforce_dump_packet("info", iforce->ecmd, iforce->edata);
/*
* Disable spring, enable force feedback.
*/
iforce_set_autocenter(input_dev, 0);
/*
* Find appropriate device entry
*/
for (i = 0; iforce_device[i].idvendor; i++)
if (iforce_device[i].idvendor == input_dev->id.vendor &&
iforce_device[i].idproduct == input_dev->id.product)
break;
iforce->type = iforce_device + i;
input_dev->name = iforce->type->name;
/*
* Set input device bitfields and ranges.
*/
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) |
BIT_MASK(EV_FF_STATUS);
for (i = 0; iforce->type->btn[i] >= 0; i++)
set_bit(iforce->type->btn[i], input_dev->keybit);
set_bit(BTN_DEAD, input_dev->keybit);
for (i = 0; iforce->type->abs[i] >= 0; i++) {
signed short t = iforce->type->abs[i];
switch (t) {
case ABS_X:
case ABS_Y:
case ABS_WHEEL:
input_set_abs_params(input_dev, t, -1920, 1920, 16, 128);
set_bit(t, input_dev->ffbit);
break;
case ABS_THROTTLE:
case ABS_GAS:
case ABS_BRAKE:
input_set_abs_params(input_dev, t, 0, 255, 0, 0);
break;
case ABS_RUDDER:
input_set_abs_params(input_dev, t, -128, 127, 0, 0);
break;
case ABS_HAT0X:
case ABS_HAT0Y:
case ABS_HAT1X:
case ABS_HAT1Y:
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
break;
}
}
if (ff_effects) {
for (i = 0; iforce->type->ff[i] >= 0; i++)
set_bit(iforce->type->ff[i], input_dev->ffbit);
error = input_ff_create(input_dev, ff_effects);
if (error)
goto fail;
ff = input_dev->ff;
ff->upload = iforce_upload_effect;
ff->erase = iforce_erase_effect;
ff->set_gain = iforce_set_gain;
ff->set_autocenter = iforce_set_autocenter;
ff->playback = iforce_playback;
}
/*
* Register input device.
*/
error = input_register_device(iforce->dev);
if (error)
goto fail;
return 0;
fail: input_free_device(input_dev);
return error;
}
static int __init iforce_init(void)
{
int err = 0;
#ifdef CONFIG_JOYSTICK_IFORCE_USB
err = usb_register(&iforce_usb_driver);
if (err)
return err;
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
err = serio_register_driver(&iforce_serio_drv);
#ifdef CONFIG_JOYSTICK_IFORCE_USB
if (err)
usb_deregister(&iforce_usb_driver);
#endif
#endif
return err;
}
static void __exit iforce_exit(void)
{
#ifdef CONFIG_JOYSTICK_IFORCE_USB
usb_deregister(&iforce_usb_driver);
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
serio_unregister_driver(&iforce_serio_drv);
#endif
}
module_init(iforce_init);
module_exit(iforce_exit);
| gpl-2.0 |
OwnROM-Devices/OwnKernel-shamu | arch/sparc/kernel/tadpole.c | 10373 | 2888 | /* tadpole.c: Probing for the tadpole clock stopping h/w at boot time.
*
* Copyright (C) 1996 David Redman (djhr@tadpole.co.uk)
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <asm/asi.h>
#include <asm/oplib.h>
#include <asm/io.h>
#define MACIO_SCSI_CSR_ADDR 0x78400000
#define MACIO_EN_DMA 0x00000200
#define CLOCK_INIT_DONE 1
static int clk_state;
static volatile unsigned char *clk_ctrl;
void (*cpu_pwr_save)(void);
static inline unsigned int ldphys(unsigned int addr)
{
unsigned long data;
__asm__ __volatile__("\n\tlda [%1] %2, %0\n\t" :
"=r" (data) :
"r" (addr), "i" (ASI_M_BYPASS));
return data;
}
static void clk_init(void)
{
__asm__ __volatile__("mov 0x6c, %%g1\n\t"
"mov 0x4c, %%g2\n\t"
"mov 0xdf, %%g3\n\t"
"stb %%g1, [%0+3]\n\t"
"stb %%g2, [%0+3]\n\t"
"stb %%g3, [%0+3]\n\t" : :
"r" (clk_ctrl) :
"g1", "g2", "g3");
}
static void clk_slow(void)
{
__asm__ __volatile__("mov 0xcc, %%g2\n\t"
"mov 0x4c, %%g3\n\t"
"mov 0xcf, %%g4\n\t"
"mov 0xdf, %%g5\n\t"
"stb %%g2, [%0+3]\n\t"
"stb %%g3, [%0+3]\n\t"
"stb %%g4, [%0+3]\n\t"
"stb %%g5, [%0+3]\n\t" : :
"r" (clk_ctrl) :
"g2", "g3", "g4", "g5");
}
/*
* Tadpole is guaranteed to be UP, using local_irq_save.
*/
static void tsu_clockstop(void)
{
unsigned int mcsr;
unsigned long flags;
if (!clk_ctrl)
return;
if (!(clk_state & CLOCK_INIT_DONE)) {
local_irq_save(flags);
clk_init();
clk_state |= CLOCK_INIT_DONE; /* all done */
local_irq_restore(flags);
return;
}
if (!(clk_ctrl[2] & 1))
return; /* no speed up yet */
local_irq_save(flags);
/* if SCSI DMA in progress, don't slow clock */
mcsr = ldphys(MACIO_SCSI_CSR_ADDR);
if ((mcsr&MACIO_EN_DMA) != 0) {
local_irq_restore(flags);
return;
}
/* TODO... the minimum clock setting ought to increase the
* memory refresh interval..
*/
clk_slow();
local_irq_restore(flags);
}
static void swift_clockstop(void)
{
if (!clk_ctrl)
return;
clk_ctrl[0] = 0;
}
void __init clock_stop_probe(void)
{
phandle node, clk_nd;
char name[20];
prom_getstring(prom_root_node, "name", name, sizeof(name));
if (strncmp(name, "Tadpole", 7))
return;
node = prom_getchild(prom_root_node);
node = prom_searchsiblings(node, "obio");
node = prom_getchild(node);
clk_nd = prom_searchsiblings(node, "clk-ctrl");
if (!clk_nd)
return;
printk("Clock Stopping h/w detected... ");
clk_ctrl = (char *) prom_getint(clk_nd, "address");
clk_state = 0;
if (name[10] == '\0') {
cpu_pwr_save = tsu_clockstop;
printk("enabled (S3)\n");
} else if ((name[10] == 'X') || (name[10] == 'G')) {
cpu_pwr_save = swift_clockstop;
printk("enabled (%s)\n",name+7);
} else
printk("disabled %s\n",name+7);
}
| gpl-2.0 |
neobuddy89/android_kernel_cyanogen_msm8916 | arch/sparc/kernel/tadpole.c | 10373 | 2888 | /* tadpole.c: Probing for the tadpole clock stopping h/w at boot time.
*
* Copyright (C) 1996 David Redman (djhr@tadpole.co.uk)
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <asm/asi.h>
#include <asm/oplib.h>
#include <asm/io.h>
#define MACIO_SCSI_CSR_ADDR 0x78400000
#define MACIO_EN_DMA 0x00000200
#define CLOCK_INIT_DONE 1
static int clk_state;
static volatile unsigned char *clk_ctrl;
void (*cpu_pwr_save)(void);
static inline unsigned int ldphys(unsigned int addr)
{
unsigned long data;
__asm__ __volatile__("\n\tlda [%1] %2, %0\n\t" :
"=r" (data) :
"r" (addr), "i" (ASI_M_BYPASS));
return data;
}
static void clk_init(void)
{
__asm__ __volatile__("mov 0x6c, %%g1\n\t"
"mov 0x4c, %%g2\n\t"
"mov 0xdf, %%g3\n\t"
"stb %%g1, [%0+3]\n\t"
"stb %%g2, [%0+3]\n\t"
"stb %%g3, [%0+3]\n\t" : :
"r" (clk_ctrl) :
"g1", "g2", "g3");
}
static void clk_slow(void)
{
__asm__ __volatile__("mov 0xcc, %%g2\n\t"
"mov 0x4c, %%g3\n\t"
"mov 0xcf, %%g4\n\t"
"mov 0xdf, %%g5\n\t"
"stb %%g2, [%0+3]\n\t"
"stb %%g3, [%0+3]\n\t"
"stb %%g4, [%0+3]\n\t"
"stb %%g5, [%0+3]\n\t" : :
"r" (clk_ctrl) :
"g2", "g3", "g4", "g5");
}
/*
* Tadpole is guaranteed to be UP, using local_irq_save.
*/
static void tsu_clockstop(void)
{
unsigned int mcsr;
unsigned long flags;
if (!clk_ctrl)
return;
if (!(clk_state & CLOCK_INIT_DONE)) {
local_irq_save(flags);
clk_init();
clk_state |= CLOCK_INIT_DONE; /* all done */
local_irq_restore(flags);
return;
}
if (!(clk_ctrl[2] & 1))
return; /* no speed up yet */
local_irq_save(flags);
/* if SCSI DMA in progress, don't slow clock */
mcsr = ldphys(MACIO_SCSI_CSR_ADDR);
if ((mcsr&MACIO_EN_DMA) != 0) {
local_irq_restore(flags);
return;
}
/* TODO... the minimum clock setting ought to increase the
* memory refresh interval..
*/
clk_slow();
local_irq_restore(flags);
}
static void swift_clockstop(void)
{
if (!clk_ctrl)
return;
clk_ctrl[0] = 0;
}
void __init clock_stop_probe(void)
{
phandle node, clk_nd;
char name[20];
prom_getstring(prom_root_node, "name", name, sizeof(name));
if (strncmp(name, "Tadpole", 7))
return;
node = prom_getchild(prom_root_node);
node = prom_searchsiblings(node, "obio");
node = prom_getchild(node);
clk_nd = prom_searchsiblings(node, "clk-ctrl");
if (!clk_nd)
return;
printk("Clock Stopping h/w detected... ");
clk_ctrl = (char *) prom_getint(clk_nd, "address");
clk_state = 0;
if (name[10] == '\0') {
cpu_pwr_save = tsu_clockstop;
printk("enabled (S3)\n");
} else if ((name[10] == 'X') || (name[10] == 'G')) {
cpu_pwr_save = swift_clockstop;
printk("enabled (%s)\n",name+7);
} else
printk("disabled %s\n",name+7);
}
| gpl-2.0 |
mukulsoni/android_kernel_samsung_ms013g | arch/sh/boards/mach-dreamcast/rtc.c | 13189 | 2134 | /*
* arch/sh/boards/dreamcast/rtc.c
*
* Dreamcast AICA RTC routines.
*
* Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org>
* Copyright (c) 2002 Paul Mundt <lethal@chaoticdreams.org>
*
* Released under the terms of the GNU GPL v2.0.
*
*/
#include <linux/time.h>
#include <asm/rtc.h>
#include <asm/io.h>
/* The AICA RTC has an Epoch of 1/1/1950, so we must subtract 20 years (in
seconds) to get the standard Unix Epoch when getting the time, and add
20 years when setting the time. */
#define TWENTY_YEARS ((20 * 365LU + 5) * 86400)
/* The AICA RTC is represented by a 32-bit seconds counter stored in 2 16-bit
registers.*/
#define AICA_RTC_SECS_H 0xa0710000
#define AICA_RTC_SECS_L 0xa0710004
/**
* aica_rtc_gettimeofday - Get the time from the AICA RTC
* @ts: pointer to resulting timespec
*
* Grabs the current RTC seconds counter and adjusts it to the Unix Epoch.
*/
static void aica_rtc_gettimeofday(struct timespec *ts)
{
unsigned long val1, val2;
do {
val1 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
val2 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
} while (val1 != val2);
ts->tv_sec = val1 - TWENTY_YEARS;
/* Can't get nanoseconds with just a seconds counter. */
ts->tv_nsec = 0;
}
/**
* aica_rtc_settimeofday - Set the AICA RTC to the current time
* @secs: contains the time_t to set
*
* Adjusts the given @tv to the AICA Epoch and sets the RTC seconds counter.
*/
static int aica_rtc_settimeofday(const time_t secs)
{
unsigned long val1, val2;
unsigned long adj = secs + TWENTY_YEARS;
do {
__raw_writel((adj & 0xffff0000) >> 16, AICA_RTC_SECS_H);
__raw_writel((adj & 0xffff), AICA_RTC_SECS_L);
val1 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
val2 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
} while (val1 != val2);
return 0;
}
void aica_time_init(void)
{
rtc_sh_get_time = aica_rtc_gettimeofday;
rtc_sh_set_time = aica_rtc_settimeofday;
}
| gpl-2.0 |
zjgeer/linux-80211n-csitool | arch/sh/boards/mach-dreamcast/rtc.c | 13189 | 2134 | /*
* arch/sh/boards/dreamcast/rtc.c
*
* Dreamcast AICA RTC routines.
*
* Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org>
* Copyright (c) 2002 Paul Mundt <lethal@chaoticdreams.org>
*
* Released under the terms of the GNU GPL v2.0.
*
*/
#include <linux/time.h>
#include <asm/rtc.h>
#include <asm/io.h>
/* The AICA RTC has an Epoch of 1/1/1950, so we must subtract 20 years (in
seconds) to get the standard Unix Epoch when getting the time, and add
20 years when setting the time. */
#define TWENTY_YEARS ((20 * 365LU + 5) * 86400)
/* The AICA RTC is represented by a 32-bit seconds counter stored in 2 16-bit
registers.*/
#define AICA_RTC_SECS_H 0xa0710000
#define AICA_RTC_SECS_L 0xa0710004
/**
* aica_rtc_gettimeofday - Get the time from the AICA RTC
* @ts: pointer to resulting timespec
*
* Grabs the current RTC seconds counter and adjusts it to the Unix Epoch.
*/
static void aica_rtc_gettimeofday(struct timespec *ts)
{
unsigned long val1, val2;
do {
val1 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
val2 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
} while (val1 != val2);
ts->tv_sec = val1 - TWENTY_YEARS;
/* Can't get nanoseconds with just a seconds counter. */
ts->tv_nsec = 0;
}
/**
* aica_rtc_settimeofday - Set the AICA RTC to the current time
* @secs: contains the time_t to set
*
* Adjusts the given @tv to the AICA Epoch and sets the RTC seconds counter.
*/
static int aica_rtc_settimeofday(const time_t secs)
{
unsigned long val1, val2;
unsigned long adj = secs + TWENTY_YEARS;
do {
__raw_writel((adj & 0xffff0000) >> 16, AICA_RTC_SECS_H);
__raw_writel((adj & 0xffff), AICA_RTC_SECS_L);
val1 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
val2 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) |
(__raw_readl(AICA_RTC_SECS_L) & 0xffff);
} while (val1 != val2);
return 0;
}
void aica_time_init(void)
{
rtc_sh_get_time = aica_rtc_gettimeofday;
rtc_sh_set_time = aica_rtc_settimeofday;
}
| gpl-2.0 |
micchie/mptcp | drivers/media/radio/radio-timb.c | 134 | 6334 | /*
* radio-timb.c Timberdale FPGA Radio driver
* Copyright (c) 2009 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/io.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <media/timb_radio.h>
#define DRIVER_NAME "timb-radio"
struct timbradio {
struct timb_radio_platform_data pdata;
struct v4l2_subdev *sd_tuner;
struct v4l2_subdev *sd_dsp;
struct video_device video_dev;
struct v4l2_device v4l2_dev;
struct mutex lock;
};
static int timbradio_vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
strlcpy(v->driver, DRIVER_NAME, sizeof(v->driver));
strlcpy(v->card, "Timberdale Radio", sizeof(v->card));
snprintf(v->bus_info, sizeof(v->bus_info), "platform:"DRIVER_NAME);
v->capabilities = V4L2_CAP_TUNER | V4L2_CAP_RADIO;
return 0;
}
static int timbradio_vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct timbradio *tr = video_drvdata(file);
return v4l2_subdev_call(tr->sd_tuner, tuner, g_tuner, v);
}
static int timbradio_vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct timbradio *tr = video_drvdata(file);
return v4l2_subdev_call(tr->sd_tuner, tuner, s_tuner, v);
}
static int timbradio_vidioc_g_input(struct file *filp, void *priv,
unsigned int *i)
{
*i = 0;
return 0;
}
static int timbradio_vidioc_s_input(struct file *filp, void *priv,
unsigned int i)
{
return i ? -EINVAL : 0;
}
static int timbradio_vidioc_g_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
a->index = 0;
strlcpy(a->name, "Radio", sizeof(a->name));
a->capability = V4L2_AUDCAP_STEREO;
return 0;
}
static int timbradio_vidioc_s_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
return a->index ? -EINVAL : 0;
}
static int timbradio_vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct timbradio *tr = video_drvdata(file);
return v4l2_subdev_call(tr->sd_tuner, tuner, s_frequency, f);
}
static int timbradio_vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct timbradio *tr = video_drvdata(file);
return v4l2_subdev_call(tr->sd_tuner, tuner, g_frequency, f);
}
static int timbradio_vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
struct timbradio *tr = video_drvdata(file);
return v4l2_subdev_call(tr->sd_dsp, core, queryctrl, qc);
}
static int timbradio_vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct timbradio *tr = video_drvdata(file);
return v4l2_subdev_call(tr->sd_dsp, core, g_ctrl, ctrl);
}
static int timbradio_vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct timbradio *tr = video_drvdata(file);
return v4l2_subdev_call(tr->sd_dsp, core, s_ctrl, ctrl);
}
static const struct v4l2_ioctl_ops timbradio_ioctl_ops = {
.vidioc_querycap = timbradio_vidioc_querycap,
.vidioc_g_tuner = timbradio_vidioc_g_tuner,
.vidioc_s_tuner = timbradio_vidioc_s_tuner,
.vidioc_g_frequency = timbradio_vidioc_g_frequency,
.vidioc_s_frequency = timbradio_vidioc_s_frequency,
.vidioc_g_input = timbradio_vidioc_g_input,
.vidioc_s_input = timbradio_vidioc_s_input,
.vidioc_g_audio = timbradio_vidioc_g_audio,
.vidioc_s_audio = timbradio_vidioc_s_audio,
.vidioc_queryctrl = timbradio_vidioc_queryctrl,
.vidioc_g_ctrl = timbradio_vidioc_g_ctrl,
.vidioc_s_ctrl = timbradio_vidioc_s_ctrl
};
static const struct v4l2_file_operations timbradio_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
};
static int __devinit timbradio_probe(struct platform_device *pdev)
{
struct timb_radio_platform_data *pdata = pdev->dev.platform_data;
struct timbradio *tr;
int err;
if (!pdata) {
dev_err(&pdev->dev, "Platform data missing\n");
err = -EINVAL;
goto err;
}
tr = kzalloc(sizeof(*tr), GFP_KERNEL);
if (!tr) {
err = -ENOMEM;
goto err;
}
tr->pdata = *pdata;
mutex_init(&tr->lock);
strlcpy(tr->video_dev.name, "Timberdale Radio",
sizeof(tr->video_dev.name));
tr->video_dev.fops = &timbradio_fops;
tr->video_dev.ioctl_ops = &timbradio_ioctl_ops;
tr->video_dev.release = video_device_release_empty;
tr->video_dev.minor = -1;
tr->video_dev.lock = &tr->lock;
strlcpy(tr->v4l2_dev.name, DRIVER_NAME, sizeof(tr->v4l2_dev.name));
err = v4l2_device_register(NULL, &tr->v4l2_dev);
if (err)
goto err_v4l2_dev;
tr->video_dev.v4l2_dev = &tr->v4l2_dev;
err = video_register_device(&tr->video_dev, VFL_TYPE_RADIO, -1);
if (err) {
dev_err(&pdev->dev, "Error reg video\n");
goto err_video_req;
}
video_set_drvdata(&tr->video_dev, tr);
platform_set_drvdata(pdev, tr);
return 0;
err_video_req:
video_device_release_empty(&tr->video_dev);
v4l2_device_unregister(&tr->v4l2_dev);
err_v4l2_dev:
kfree(tr);
err:
dev_err(&pdev->dev, "Failed to register: %d\n", err);
return err;
}
static int __devexit timbradio_remove(struct platform_device *pdev)
{
struct timbradio *tr = platform_get_drvdata(pdev);
video_unregister_device(&tr->video_dev);
video_device_release_empty(&tr->video_dev);
v4l2_device_unregister(&tr->v4l2_dev);
kfree(tr);
return 0;
}
static struct platform_driver timbradio_platform_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
.probe = timbradio_probe,
.remove = __devexit_p(timbradio_remove),
};
module_platform_driver(timbradio_platform_driver);
MODULE_DESCRIPTION("Timberdale Radio driver");
MODULE_AUTHOR("Mocean Laboratories <info@mocean-labs.com>");
MODULE_LICENSE("GPL v2");
MODULE_VERSION("0.0.2");
MODULE_ALIAS("platform:"DRIVER_NAME);
| gpl-2.0 |
freedesktop-unofficial-mirror/drm-intel | drivers/net/usb/catc.c | 646 | 24273 | /*
* Copyright (c) 2001 Vojtech Pavlik
*
* CATC EL1210A NetMate USB Ethernet driver
*
* Sponsored by SuSE
*
* Based on the work of
* Donald Becker
*
* Old chipset support added by Simon Evans <spse@secret.org.uk> 2002
* - adds support for Belkin F5U011
*/
/*
* 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/>.
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@suse.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/crc32.h>
#include <linux/bitops.h>
#include <linux/gfp.h>
#include <asm/uaccess.h>
#undef DEBUG
#include <linux/usb.h>
/*
* Version information.
*/
#define DRIVER_VERSION "v2.8"
#define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@suse.cz>"
#define DRIVER_DESC "CATC EL1210A NetMate USB Ethernet driver"
#define SHORT_DRIVER_DESC "EL1210A NetMate USB Ethernet"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static const char driver_name[] = "catc";
/*
* Some defines.
*/
#define STATS_UPDATE (HZ) /* Time between stats updates */
#define TX_TIMEOUT (5*HZ) /* Max time the queue can be stopped */
#define PKT_SZ 1536 /* Max Ethernet packet size */
#define RX_MAX_BURST 15 /* Max packets per rx buffer (> 0, < 16) */
#define TX_MAX_BURST 15 /* Max full sized packets per tx buffer (> 0) */
#define CTRL_QUEUE 16 /* Max control requests in flight (power of two) */
#define RX_PKT_SZ 1600 /* Max size of receive packet for F5U011 */
/*
* Control requests.
*/
enum control_requests {
ReadMem = 0xf1,
GetMac = 0xf2,
Reset = 0xf4,
SetMac = 0xf5,
SetRxMode = 0xf5, /* F5U011 only */
WriteROM = 0xf8,
SetReg = 0xfa,
GetReg = 0xfb,
WriteMem = 0xfc,
ReadROM = 0xfd,
};
/*
* Registers.
*/
enum register_offsets {
TxBufCount = 0x20,
RxBufCount = 0x21,
OpModes = 0x22,
TxQed = 0x23,
RxQed = 0x24,
MaxBurst = 0x25,
RxUnit = 0x60,
EthStatus = 0x61,
StationAddr0 = 0x67,
EthStats = 0x69,
LEDCtrl = 0x81,
};
enum eth_stats {
TxSingleColl = 0x00,
TxMultiColl = 0x02,
TxExcessColl = 0x04,
RxFramErr = 0x06,
};
enum op_mode_bits {
Op3MemWaits = 0x03,
OpLenInclude = 0x08,
OpRxMerge = 0x10,
OpTxMerge = 0x20,
OpWin95bugfix = 0x40,
OpLoopback = 0x80,
};
enum rx_filter_bits {
RxEnable = 0x01,
RxPolarity = 0x02,
RxForceOK = 0x04,
RxMultiCast = 0x08,
RxPromisc = 0x10,
AltRxPromisc = 0x20, /* F5U011 uses different bit */
};
enum led_values {
LEDFast = 0x01,
LEDSlow = 0x02,
LEDFlash = 0x03,
LEDPulse = 0x04,
LEDLink = 0x08,
};
enum link_status {
LinkNoChange = 0,
LinkGood = 1,
LinkBad = 2
};
/*
* The catc struct.
*/
#define CTRL_RUNNING 0
#define RX_RUNNING 1
#define TX_RUNNING 2
struct catc {
struct net_device *netdev;
struct usb_device *usbdev;
unsigned long flags;
unsigned int tx_ptr, tx_idx;
unsigned int ctrl_head, ctrl_tail;
spinlock_t tx_lock, ctrl_lock;
u8 tx_buf[2][TX_MAX_BURST * (PKT_SZ + 2)];
u8 rx_buf[RX_MAX_BURST * (PKT_SZ + 2)];
u8 irq_buf[2];
u8 ctrl_buf[64];
struct usb_ctrlrequest ctrl_dr;
struct timer_list timer;
u8 stats_buf[8];
u16 stats_vals[4];
unsigned long last_stats;
u8 multicast[64];
struct ctrl_queue {
u8 dir;
u8 request;
u16 value;
u16 index;
void *buf;
int len;
void (*callback)(struct catc *catc, struct ctrl_queue *q);
} ctrl_queue[CTRL_QUEUE];
struct urb *tx_urb, *rx_urb, *irq_urb, *ctrl_urb;
u8 is_f5u011; /* Set if device is an F5U011 */
u8 rxmode[2]; /* Used for F5U011 */
atomic_t recq_sz; /* Used for F5U011 - counter of waiting rx packets */
};
/*
* Useful macros.
*/
#define catc_get_mac(catc, mac) catc_ctrl_msg(catc, USB_DIR_IN, GetMac, 0, 0, mac, 6)
#define catc_reset(catc) catc_ctrl_msg(catc, USB_DIR_OUT, Reset, 0, 0, NULL, 0)
#define catc_set_reg(catc, reg, val) catc_ctrl_msg(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0)
#define catc_get_reg(catc, reg, buf) catc_ctrl_msg(catc, USB_DIR_IN, GetReg, 0, reg, buf, 1)
#define catc_write_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size)
#define catc_read_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_IN, ReadMem, 0, addr, buf, size)
#define f5u011_rxmode(catc, rxmode) catc_ctrl_msg(catc, USB_DIR_OUT, SetRxMode, 0, 1, rxmode, 2)
#define f5u011_rxmode_async(catc, rxmode) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 1, &rxmode, 2, NULL)
#define f5u011_mchash_async(catc, hash) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 2, &hash, 8, NULL)
#define catc_set_reg_async(catc, reg, val) catc_ctrl_async(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0, NULL)
#define catc_get_reg_async(catc, reg, cb) catc_ctrl_async(catc, USB_DIR_IN, GetReg, 0, reg, NULL, 1, cb)
#define catc_write_mem_async(catc, addr, buf, size) catc_ctrl_async(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size, NULL)
/*
* Receive routines.
*/
static void catc_rx_done(struct urb *urb)
{
struct catc *catc = urb->context;
u8 *pkt_start = urb->transfer_buffer;
struct sk_buff *skb;
int pkt_len, pkt_offset = 0;
int status = urb->status;
if (!catc->is_f5u011) {
clear_bit(RX_RUNNING, &catc->flags);
pkt_offset = 2;
}
if (status) {
dev_dbg(&urb->dev->dev, "rx_done, status %d, length %d\n",
status, urb->actual_length);
return;
}
do {
if(!catc->is_f5u011) {
pkt_len = le16_to_cpup((__le16*)pkt_start);
if (pkt_len > urb->actual_length) {
catc->netdev->stats.rx_length_errors++;
catc->netdev->stats.rx_errors++;
break;
}
} else {
pkt_len = urb->actual_length;
}
if (!(skb = dev_alloc_skb(pkt_len)))
return;
skb_copy_to_linear_data(skb, pkt_start + pkt_offset, pkt_len);
skb_put(skb, pkt_len);
skb->protocol = eth_type_trans(skb, catc->netdev);
netif_rx(skb);
catc->netdev->stats.rx_packets++;
catc->netdev->stats.rx_bytes += pkt_len;
/* F5U011 only does one packet per RX */
if (catc->is_f5u011)
break;
pkt_start += (((pkt_len + 1) >> 6) + 1) << 6;
} while (pkt_start - (u8 *) urb->transfer_buffer < urb->actual_length);
if (catc->is_f5u011) {
if (atomic_read(&catc->recq_sz)) {
int state;
atomic_dec(&catc->recq_sz);
netdev_dbg(catc->netdev, "getting extra packet\n");
urb->dev = catc->usbdev;
if ((state = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
netdev_dbg(catc->netdev,
"submit(rx_urb) status %d\n", state);
}
} else {
clear_bit(RX_RUNNING, &catc->flags);
}
}
}
static void catc_irq_done(struct urb *urb)
{
struct catc *catc = urb->context;
u8 *data = urb->transfer_buffer;
int status = urb->status;
unsigned int hasdata = 0, linksts = LinkNoChange;
int res;
if (!catc->is_f5u011) {
hasdata = data[1] & 0x80;
if (data[1] & 0x40)
linksts = LinkGood;
else if (data[1] & 0x20)
linksts = LinkBad;
} else {
hasdata = (unsigned int)(be16_to_cpup((__be16*)data) & 0x0fff);
if (data[0] == 0x90)
linksts = LinkGood;
else if (data[0] == 0xA0)
linksts = LinkBad;
}
switch (status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
dev_dbg(&urb->dev->dev,
"irq_done, status %d, data %02x %02x.\n",
status, data[0], data[1]);
goto resubmit;
}
if (linksts == LinkGood) {
netif_carrier_on(catc->netdev);
netdev_dbg(catc->netdev, "link ok\n");
}
if (linksts == LinkBad) {
netif_carrier_off(catc->netdev);
netdev_dbg(catc->netdev, "link bad\n");
}
if (hasdata) {
if (test_and_set_bit(RX_RUNNING, &catc->flags)) {
if (catc->is_f5u011)
atomic_inc(&catc->recq_sz);
} else {
catc->rx_urb->dev = catc->usbdev;
if ((res = usb_submit_urb(catc->rx_urb, GFP_ATOMIC)) < 0) {
dev_err(&catc->usbdev->dev,
"submit(rx_urb) status %d\n", res);
}
}
}
resubmit:
res = usb_submit_urb (urb, GFP_ATOMIC);
if (res)
dev_err(&catc->usbdev->dev,
"can't resubmit intr, %s-%s, status %d\n",
catc->usbdev->bus->bus_name,
catc->usbdev->devpath, res);
}
/*
* Transmit routines.
*/
static int catc_tx_run(struct catc *catc)
{
int status;
if (catc->is_f5u011)
catc->tx_ptr = (catc->tx_ptr + 63) & ~63;
catc->tx_urb->transfer_buffer_length = catc->tx_ptr;
catc->tx_urb->transfer_buffer = catc->tx_buf[catc->tx_idx];
catc->tx_urb->dev = catc->usbdev;
if ((status = usb_submit_urb(catc->tx_urb, GFP_ATOMIC)) < 0)
dev_err(&catc->usbdev->dev, "submit(tx_urb), status %d\n",
status);
catc->tx_idx = !catc->tx_idx;
catc->tx_ptr = 0;
catc->netdev->trans_start = jiffies;
return status;
}
static void catc_tx_done(struct urb *urb)
{
struct catc *catc = urb->context;
unsigned long flags;
int r, status = urb->status;
if (status == -ECONNRESET) {
dev_dbg(&urb->dev->dev, "Tx Reset.\n");
urb->status = 0;
catc->netdev->trans_start = jiffies;
catc->netdev->stats.tx_errors++;
clear_bit(TX_RUNNING, &catc->flags);
netif_wake_queue(catc->netdev);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "tx_done, status %d, length %d\n",
status, urb->actual_length);
return;
}
spin_lock_irqsave(&catc->tx_lock, flags);
if (catc->tx_ptr) {
r = catc_tx_run(catc);
if (unlikely(r < 0))
clear_bit(TX_RUNNING, &catc->flags);
} else {
clear_bit(TX_RUNNING, &catc->flags);
}
netif_wake_queue(catc->netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
}
static netdev_tx_t catc_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
unsigned long flags;
int r = 0;
char *tx_buf;
spin_lock_irqsave(&catc->tx_lock, flags);
catc->tx_ptr = (((catc->tx_ptr - 1) >> 6) + 1) << 6;
tx_buf = catc->tx_buf[catc->tx_idx] + catc->tx_ptr;
if (catc->is_f5u011)
*(__be16 *)tx_buf = cpu_to_be16(skb->len);
else
*(__le16 *)tx_buf = cpu_to_le16(skb->len);
skb_copy_from_linear_data(skb, tx_buf + 2, skb->len);
catc->tx_ptr += skb->len + 2;
if (!test_and_set_bit(TX_RUNNING, &catc->flags)) {
r = catc_tx_run(catc);
if (r < 0)
clear_bit(TX_RUNNING, &catc->flags);
}
if ((catc->is_f5u011 && catc->tx_ptr) ||
(catc->tx_ptr >= ((TX_MAX_BURST - 1) * (PKT_SZ + 2))))
netif_stop_queue(netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
if (r >= 0) {
catc->netdev->stats.tx_bytes += skb->len;
catc->netdev->stats.tx_packets++;
}
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static void catc_tx_timeout(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
dev_warn(&netdev->dev, "Transmit timed out.\n");
usb_unlink_urb(catc->tx_urb);
}
/*
* Control messages.
*/
static int catc_ctrl_msg(struct catc *catc, u8 dir, u8 request, u16 value, u16 index, void *buf, int len)
{
int retval = usb_control_msg(catc->usbdev,
dir ? usb_rcvctrlpipe(catc->usbdev, 0) : usb_sndctrlpipe(catc->usbdev, 0),
request, 0x40 | dir, value, index, buf, len, 1000);
return retval < 0 ? retval : 0;
}
static void catc_ctrl_run(struct catc *catc)
{
struct ctrl_queue *q = catc->ctrl_queue + catc->ctrl_tail;
struct usb_device *usbdev = catc->usbdev;
struct urb *urb = catc->ctrl_urb;
struct usb_ctrlrequest *dr = &catc->ctrl_dr;
int status;
dr->bRequest = q->request;
dr->bRequestType = 0x40 | q->dir;
dr->wValue = cpu_to_le16(q->value);
dr->wIndex = cpu_to_le16(q->index);
dr->wLength = cpu_to_le16(q->len);
urb->pipe = q->dir ? usb_rcvctrlpipe(usbdev, 0) : usb_sndctrlpipe(usbdev, 0);
urb->transfer_buffer_length = q->len;
urb->transfer_buffer = catc->ctrl_buf;
urb->setup_packet = (void *) dr;
urb->dev = usbdev;
if (!q->dir && q->buf && q->len)
memcpy(catc->ctrl_buf, q->buf, q->len);
if ((status = usb_submit_urb(catc->ctrl_urb, GFP_ATOMIC)))
dev_err(&catc->usbdev->dev, "submit(ctrl_urb) status %d\n",
status);
}
static void catc_ctrl_done(struct urb *urb)
{
struct catc *catc = urb->context;
struct ctrl_queue *q;
unsigned long flags;
int status = urb->status;
if (status)
dev_dbg(&urb->dev->dev, "ctrl_done, status %d, len %d.\n",
status, urb->actual_length);
spin_lock_irqsave(&catc->ctrl_lock, flags);
q = catc->ctrl_queue + catc->ctrl_tail;
if (q->dir) {
if (q->buf && q->len)
memcpy(q->buf, catc->ctrl_buf, q->len);
else
q->buf = catc->ctrl_buf;
}
if (q->callback)
q->callback(catc, q);
catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1);
if (catc->ctrl_head != catc->ctrl_tail)
catc_ctrl_run(catc);
else
clear_bit(CTRL_RUNNING, &catc->flags);
spin_unlock_irqrestore(&catc->ctrl_lock, flags);
}
static int catc_ctrl_async(struct catc *catc, u8 dir, u8 request, u16 value,
u16 index, void *buf, int len, void (*callback)(struct catc *catc, struct ctrl_queue *q))
{
struct ctrl_queue *q;
int retval = 0;
unsigned long flags;
spin_lock_irqsave(&catc->ctrl_lock, flags);
q = catc->ctrl_queue + catc->ctrl_head;
q->dir = dir;
q->request = request;
q->value = value;
q->index = index;
q->buf = buf;
q->len = len;
q->callback = callback;
catc->ctrl_head = (catc->ctrl_head + 1) & (CTRL_QUEUE - 1);
if (catc->ctrl_head == catc->ctrl_tail) {
dev_err(&catc->usbdev->dev, "ctrl queue full\n");
catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1);
retval = -1;
}
if (!test_and_set_bit(CTRL_RUNNING, &catc->flags))
catc_ctrl_run(catc);
spin_unlock_irqrestore(&catc->ctrl_lock, flags);
return retval;
}
/*
* Statistics.
*/
static void catc_stats_done(struct catc *catc, struct ctrl_queue *q)
{
int index = q->index - EthStats;
u16 data, last;
catc->stats_buf[index] = *((char *)q->buf);
if (index & 1)
return;
data = ((u16)catc->stats_buf[index] << 8) | catc->stats_buf[index + 1];
last = catc->stats_vals[index >> 1];
switch (index) {
case TxSingleColl:
case TxMultiColl:
catc->netdev->stats.collisions += data - last;
break;
case TxExcessColl:
catc->netdev->stats.tx_aborted_errors += data - last;
catc->netdev->stats.tx_errors += data - last;
break;
case RxFramErr:
catc->netdev->stats.rx_frame_errors += data - last;
catc->netdev->stats.rx_errors += data - last;
break;
}
catc->stats_vals[index >> 1] = data;
}
static void catc_stats_timer(unsigned long data)
{
struct catc *catc = (void *) data;
int i;
for (i = 0; i < 8; i++)
catc_get_reg_async(catc, EthStats + 7 - i, catc_stats_done);
mod_timer(&catc->timer, jiffies + STATS_UPDATE);
}
/*
* Receive modes. Broadcast, Multicast, Promisc.
*/
static void catc_multicast(unsigned char *addr, u8 *multicast)
{
u32 crc;
crc = ether_crc_le(6, addr);
multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7);
}
static void catc_set_multicast_list(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
struct netdev_hw_addr *ha;
u8 broadcast[ETH_ALEN];
u8 rx = RxEnable | RxPolarity | RxMultiCast;
memset(broadcast, 0xff, ETH_ALEN);
memset(catc->multicast, 0, 64);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
if (netdev->flags & IFF_PROMISC) {
memset(catc->multicast, 0xff, 64);
rx |= (!catc->is_f5u011) ? RxPromisc : AltRxPromisc;
}
if (netdev->flags & IFF_ALLMULTI) {
memset(catc->multicast, 0xff, 64);
} else {
netdev_for_each_mc_addr(ha, netdev) {
u32 crc = ether_crc_le(6, ha->addr);
if (!catc->is_f5u011) {
catc->multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7);
} else {
catc->multicast[7-(crc >> 29)] |= 1 << ((crc >> 26) & 7);
}
}
}
if (!catc->is_f5u011) {
catc_set_reg_async(catc, RxUnit, rx);
catc_write_mem_async(catc, 0xfa80, catc->multicast, 64);
} else {
f5u011_mchash_async(catc, catc->multicast);
if (catc->rxmode[0] != rx) {
catc->rxmode[0] = rx;
netdev_dbg(catc->netdev,
"Setting RX mode to %2.2X %2.2X\n",
catc->rxmode[0], catc->rxmode[1]);
f5u011_rxmode_async(catc, catc->rxmode);
}
}
}
static void catc_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct catc *catc = netdev_priv(dev);
strlcpy(info->driver, driver_name, sizeof(info->driver));
strlcpy(info->version, DRIVER_VERSION, sizeof(info->version));
usb_make_path(catc->usbdev, info->bus_info, sizeof(info->bus_info));
}
static int catc_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct catc *catc = netdev_priv(dev);
if (!catc->is_f5u011)
return -EOPNOTSUPP;
cmd->supported = SUPPORTED_10baseT_Half | SUPPORTED_TP;
cmd->advertising = ADVERTISED_10baseT_Half | ADVERTISED_TP;
ethtool_cmd_speed_set(cmd, SPEED_10);
cmd->duplex = DUPLEX_HALF;
cmd->port = PORT_TP;
cmd->phy_address = 0;
cmd->transceiver = XCVR_INTERNAL;
cmd->autoneg = AUTONEG_DISABLE;
cmd->maxtxpkt = 1;
cmd->maxrxpkt = 1;
return 0;
}
static const struct ethtool_ops ops = {
.get_drvinfo = catc_get_drvinfo,
.get_settings = catc_get_settings,
.get_link = ethtool_op_get_link
};
/*
* Open, close.
*/
static int catc_open(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
int status;
catc->irq_urb->dev = catc->usbdev;
if ((status = usb_submit_urb(catc->irq_urb, GFP_KERNEL)) < 0) {
dev_err(&catc->usbdev->dev, "submit(irq_urb) status %d\n",
status);
return -1;
}
netif_start_queue(netdev);
if (!catc->is_f5u011)
mod_timer(&catc->timer, jiffies + STATS_UPDATE);
return 0;
}
static int catc_stop(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
netif_stop_queue(netdev);
if (!catc->is_f5u011)
del_timer_sync(&catc->timer);
usb_kill_urb(catc->rx_urb);
usb_kill_urb(catc->tx_urb);
usb_kill_urb(catc->irq_urb);
usb_kill_urb(catc->ctrl_urb);
return 0;
}
static const struct net_device_ops catc_netdev_ops = {
.ndo_open = catc_open,
.ndo_stop = catc_stop,
.ndo_start_xmit = catc_start_xmit,
.ndo_tx_timeout = catc_tx_timeout,
.ndo_set_rx_mode = catc_set_multicast_list,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/*
* USB probe, disconnect.
*/
static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int i, pktsz;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
init_timer(&catc->timer);
catc->timer.data = (long) catc;
catc->timer.function = catc_stats_timer;
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return -ENOMEM;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
dev_dbg(dev, "Checking memory size\n");
i = 0x12345678;
catc_write_mem(catc, 0x7a80, &i, 4);
i = 0x87654321;
catc_write_mem(catc, 0xfa80, &i, 4);
catc_read_mem(catc, 0x7a80, &i, 4);
switch (i) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
memset(broadcast, 0xff, ETH_ALEN);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
if (register_netdev(netdev) != 0) {
usb_set_intfdata(intf, NULL);
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return -EIO;
}
return 0;
}
static void catc_disconnect(struct usb_interface *intf)
{
struct catc *catc = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
if (catc) {
unregister_netdev(catc->netdev);
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(catc->netdev);
}
}
/*
* Module functions and tables.
*/
static struct usb_device_id catc_id_table [] = {
{ USB_DEVICE(0x0423, 0xa) }, /* CATC Netmate, Belkin F5U011 */
{ USB_DEVICE(0x0423, 0xc) }, /* CATC Netmate II, Belkin F5U111 */
{ USB_DEVICE(0x08d1, 0x1) }, /* smartBridges smartNIC */
{ }
};
MODULE_DEVICE_TABLE(usb, catc_id_table);
static struct usb_driver catc_driver = {
.name = driver_name,
.probe = catc_probe,
.disconnect = catc_disconnect,
.id_table = catc_id_table,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(catc_driver);
| gpl-2.0 |
chli/tripndroid-endeavoru-3.0 | arch/arm/mach-imx/mm-imx21.c | 646 | 2614 | /*
* arch/arm/mach-imx/mm-imx21.c
*
* Copyright (C) 2008 Juergen Beisert (kernel@pengutronix.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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/mm.h>
#include <linux/init.h>
#include <mach/hardware.h>
#include <mach/common.h>
#include <mach/devices-common.h>
#include <asm/pgtable.h>
#include <asm/mach/map.h>
#include <mach/irqs.h>
#include <mach/iomux-v1.h>
/* MX21 memory map definition */
static struct map_desc imx21_io_desc[] __initdata = {
/*
* this fixed mapping covers:
* - AIPI1
* - AIPI2
* - AITC
* - ROM Patch
* - and some reserved space
*/
imx_map_entry(MX21, AIPI, MT_DEVICE),
/*
* this fixed mapping covers:
* - CSI
* - ATA
*/
imx_map_entry(MX21, SAHB1, MT_DEVICE),
/*
* this fixed mapping covers:
* - EMI
*/
imx_map_entry(MX21, X_MEMC, MT_DEVICE),
};
/*
* Initialize the memory map. It is called during the
* system startup to create static physical to virtual
* memory map for the IO modules.
*/
void __init mx21_map_io(void)
{
iotable_init(imx21_io_desc, ARRAY_SIZE(imx21_io_desc));
}
void __init imx21_init_early(void)
{
mxc_set_cpu_type(MXC_CPU_MX21);
mxc_arch_reset_init(MX21_IO_ADDRESS(MX21_WDOG_BASE_ADDR));
imx_iomuxv1_init(MX21_IO_ADDRESS(MX21_GPIO_BASE_ADDR),
MX21_NUM_GPIO_PORT);
}
void __init mx21_init_irq(void)
{
mxc_init_irq(MX21_IO_ADDRESS(MX21_AVIC_BASE_ADDR));
}
void __init imx21_soc_init(void)
{
mxc_register_gpio("imx21-gpio", 0, MX21_GPIO1_BASE_ADDR, SZ_256, MX21_INT_GPIO, 0);
mxc_register_gpio("imx21-gpio", 1, MX21_GPIO2_BASE_ADDR, SZ_256, MX21_INT_GPIO, 0);
mxc_register_gpio("imx21-gpio", 2, MX21_GPIO3_BASE_ADDR, SZ_256, MX21_INT_GPIO, 0);
mxc_register_gpio("imx21-gpio", 3, MX21_GPIO4_BASE_ADDR, SZ_256, MX21_INT_GPIO, 0);
mxc_register_gpio("imx21-gpio", 4, MX21_GPIO5_BASE_ADDR, SZ_256, MX21_INT_GPIO, 0);
mxc_register_gpio("imx21-gpio", 5, MX21_GPIO6_BASE_ADDR, SZ_256, MX21_INT_GPIO, 0);
imx_add_imx_dma();
}
| gpl-2.0 |
sakuraba001/android_kernel_samsung_d2 | arch/arm/mach-msm/board-9615.c | 902 | 27669 | /* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/slimbus/slimbus.h>
#ifdef CONFIG_WCD9310_CODEC
#include <linux/mfd/wcd9xxx/core.h>
#include <linux/mfd/wcd9xxx/pdata.h>
#endif
#include <linux/msm_ssbi.h>
#include <linux/memblock.h>
#include <linux/usb/android.h>
#include <linux/usb/msm_hsusb.h>
#include <linux/mfd/pm8xxx/pm8xxx-adc.h>
#include <linux/leds.h>
#include <linux/leds-pm8xxx.h>
#include <linux/power/ltc4088-charger.h>
#include <linux/gpio.h>
#include <linux/msm_tsens.h>
#include <linux/msm_ion.h>
#include <linux/memory.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/hardware/gic.h>
#include <mach/board.h>
#include <mach/msm_iomap.h>
#include <mach/socinfo.h>
#include <mach/msm_spi.h>
#include <mach/msm_bus_board.h>
#include <mach/msm_xo.h>
#include <mach/dma.h>
#include <mach/ion.h>
#include <mach/msm_memtypes.h>
#include <mach/cpuidle.h>
#include <mach/usb_bam.h>
#include <mach/restart.h>
#include "timer.h"
#include "devices.h"
#include "board-9615.h"
#include "pm.h"
#include "clock.h"
#include "pm-boot.h"
#include <mach/gpiomux.h>
#include "ci13xxx_udc.h"
#ifdef CONFIG_ION_MSM
#define MSM_ION_AUDIO_SIZE 0xAF000
#define MSM_ION_HEAP_NUM 3
#define MSM_KERNEL_EBI_SIZE 0x51000
static struct memtype_reserve msm9615_reserve_table[] __initdata = {
[MEMTYPE_SMI] = {
},
[MEMTYPE_EBI0] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
[MEMTYPE_EBI1] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
};
static int msm9615_paddr_to_memtype(unsigned int paddr)
{
return MEMTYPE_EBI1;
}
static struct ion_co_heap_pdata co_ion_pdata = {
.adjacent_mem_id = INVALID_HEAP_ID,
.align = PAGE_SIZE,
};
static struct ion_platform_heap msm9615_heaps[] = {
{
.id = ION_SYSTEM_HEAP_ID,
.type = ION_HEAP_TYPE_SYSTEM,
.name = ION_VMALLOC_HEAP_NAME,
},
{
.id = ION_IOMMU_HEAP_ID,
.type = ION_HEAP_TYPE_IOMMU,
.name = ION_IOMMU_HEAP_NAME,
},
{
.id = ION_AUDIO_HEAP_ID,
.type = ION_HEAP_TYPE_CARVEOUT,
.name = ION_AUDIO_HEAP_NAME,
.size = MSM_ION_AUDIO_SIZE,
.memory_type = ION_EBI_TYPE,
.extra_data = (void *) &co_ion_pdata,
},
};
static struct ion_platform_data ion_pdata = {
.nr = MSM_ION_HEAP_NUM,
.heaps = msm9615_heaps,
};
static struct platform_device ion_dev = {
.name = "ion-msm",
.id = 1,
.dev = { .platform_data = &ion_pdata },
};
static void __init reserve_ion_memory(void)
{
msm9615_reserve_table[MEMTYPE_EBI1].size += MSM_ION_AUDIO_SIZE;
}
static void __init msm9615_calculate_reserve_sizes(void)
{
reserve_ion_memory();
msm9615_reserve_table[MEMTYPE_EBI1].size += MSM_KERNEL_EBI_SIZE;
}
static struct reserve_info msm9615_reserve_info __initdata = {
.memtype_reserve_table = msm9615_reserve_table,
.calculate_reserve_sizes = msm9615_calculate_reserve_sizes,
.paddr_to_memtype = msm9615_paddr_to_memtype,
};
#endif
struct pm8xxx_gpio_init {
unsigned gpio;
struct pm_gpio config;
};
struct pm8xxx_mpp_init {
unsigned mpp;
struct pm8xxx_mpp_config_data config;
};
#define PM8018_GPIO_INIT(_gpio, _dir, _buf, _val, _pull, _vin, _out_strength, \
_func, _inv, _disable) \
{ \
.gpio = PM8018_GPIO_PM_TO_SYS(_gpio), \
.config = { \
.direction = _dir, \
.output_buffer = _buf, \
.output_value = _val, \
.pull = _pull, \
.vin_sel = _vin, \
.out_strength = _out_strength, \
.function = _func, \
.inv_int_pol = _inv, \
.disable_pin = _disable, \
} \
}
#define PM8018_MPP_INIT(_mpp, _type, _level, _control) \
{ \
.mpp = PM8018_MPP_PM_TO_SYS(_mpp), \
.config = { \
.type = PM8XXX_MPP_TYPE_##_type, \
.level = _level, \
.control = PM8XXX_MPP_##_control, \
} \
}
#define PM8018_GPIO_DISABLE(_gpio) \
PM8018_GPIO_INIT(_gpio, PM_GPIO_DIR_IN, 0, 0, 0, PM8018_GPIO_VIN_S3, \
0, 0, 0, 1)
#define PM8018_GPIO_OUTPUT(_gpio, _val, _strength) \
PM8018_GPIO_INIT(_gpio, PM_GPIO_DIR_OUT, PM_GPIO_OUT_BUF_CMOS, _val, \
PM_GPIO_PULL_NO, PM8018_GPIO_VIN_S3, \
PM_GPIO_STRENGTH_##_strength, \
PM_GPIO_FUNC_NORMAL, 0, 0)
#define PM8018_GPIO_INPUT(_gpio, _pull) \
PM8018_GPIO_INIT(_gpio, PM_GPIO_DIR_IN, PM_GPIO_OUT_BUF_CMOS, 0, \
_pull, PM8018_GPIO_VIN_S3, \
PM_GPIO_STRENGTH_NO, \
PM_GPIO_FUNC_NORMAL, 0, 0)
#define PM8018_GPIO_OUTPUT_FUNC(_gpio, _val, _func) \
PM8018_GPIO_INIT(_gpio, PM_GPIO_DIR_OUT, PM_GPIO_OUT_BUF_CMOS, _val, \
PM_GPIO_PULL_NO, PM8018_GPIO_VIN_S3, \
PM_GPIO_STRENGTH_HIGH, \
_func, 0, 0)
#define PM8018_GPIO_OUTPUT_VIN(_gpio, _val, _vin) \
PM8018_GPIO_INIT(_gpio, PM_GPIO_DIR_OUT, PM_GPIO_OUT_BUF_CMOS, _val, \
PM_GPIO_PULL_NO, _vin, \
PM_GPIO_STRENGTH_HIGH, \
PM_GPIO_FUNC_NORMAL, 0, 0)
/* Initial PM8018 GPIO configurations */
static struct pm8xxx_gpio_init pm8018_gpios[] __initdata = {
PM8018_GPIO_OUTPUT(2, 0, HIGH), /* EXT_LDO_EN_WLAN */
PM8018_GPIO_OUTPUT(6, 0, LOW), /* WLAN_CLK_PWR_REQ */
};
/* Initial PM8018 MPP configurations */
static struct pm8xxx_mpp_init pm8018_mpps[] __initdata = {
};
void __init msm9615_pm8xxx_gpio_mpp_init(void)
{
int i, rc;
for (i = 0; i < ARRAY_SIZE(pm8018_gpios); i++) {
rc = pm8xxx_gpio_config(pm8018_gpios[i].gpio,
&pm8018_gpios[i].config);
if (rc) {
pr_err("%s: pm8018_gpio_config: rc=%d\n", __func__, rc);
break;
}
}
for (i = 0; i < ARRAY_SIZE(pm8018_mpps); i++) {
rc = pm8xxx_mpp_config(pm8018_mpps[i].mpp,
&pm8018_mpps[i].config);
if (rc) {
pr_err("%s: pm8018_mpp_config: rc=%d\n", __func__, rc);
break;
}
}
}
static struct pm8xxx_adc_amux pm8018_adc_channels_data[] = {
{"vcoin", CHANNEL_VCOIN, CHAN_PATH_SCALING2, AMUX_RSV1,
ADC_DECIMATION_TYPE2, ADC_SCALE_DEFAULT},
{"vbat", CHANNEL_VBAT, CHAN_PATH_SCALING2, AMUX_RSV1,
ADC_DECIMATION_TYPE2, ADC_SCALE_DEFAULT},
{"vph_pwr", CHANNEL_VPH_PWR, CHAN_PATH_SCALING2, AMUX_RSV1,
ADC_DECIMATION_TYPE2, ADC_SCALE_DEFAULT},
/* AMUX8 is used to read either Batt_id/Batt_therm.
* Current configuration is to support Batt_id. If clients
* want to read the Batt_therm, the scaling function needs to be
* updated to use ADC_SCALE_BATT_THERM instead of ADC_SCALE_DEFAULT.
* E.g.
* {"batt_therm", CHANNEL_BATT_ID_THERM, CHAN_PATH_SCALING1,
* AMUX_RSV2, ADC_DECIMATION_TYPE2, ADC_SCALE_BATT_THERM},
*/
{"batt_id", CHANNEL_BATT_ID_THERM, CHAN_PATH_SCALING1,
AMUX_RSV2, ADC_DECIMATION_TYPE2, ADC_SCALE_DEFAULT},
{"pmic_therm", CHANNEL_DIE_TEMP, CHAN_PATH_SCALING1, AMUX_RSV1,
ADC_DECIMATION_TYPE2, ADC_SCALE_PMIC_THERM},
{"625mv", CHANNEL_625MV, CHAN_PATH_SCALING1, AMUX_RSV1,
ADC_DECIMATION_TYPE2, ADC_SCALE_DEFAULT},
{"125v", CHANNEL_125V, CHAN_PATH_SCALING1, AMUX_RSV1,
ADC_DECIMATION_TYPE2, ADC_SCALE_DEFAULT},
{"pa_therm0", ADC_MPP_1_AMUX3, CHAN_PATH_SCALING1, AMUX_RSV1,
ADC_DECIMATION_TYPE2, ADC_SCALE_PA_THERM},
};
static struct pm8xxx_adc_properties pm8018_adc_data = {
.adc_vdd_reference = 1800, /* milli-voltage for this adc */
.bitresolution = 15,
.bipolar = 0,
};
static struct pm8xxx_adc_platform_data pm8018_adc_pdata = {
.adc_channel = pm8018_adc_channels_data,
.adc_num_board_channel = ARRAY_SIZE(pm8018_adc_channels_data),
.adc_prop = &pm8018_adc_data,
};
static struct pm8xxx_irq_platform_data pm8xxx_irq_pdata __devinitdata = {
.irq_base = PM8018_IRQ_BASE,
.devirq = MSM_GPIO_TO_INT(87),
.irq_trigger_flag = IRQF_TRIGGER_LOW,
};
static struct pm8xxx_gpio_platform_data pm8xxx_gpio_pdata __devinitdata = {
.gpio_base = PM8018_GPIO_PM_TO_SYS(1),
};
static struct pm8xxx_mpp_platform_data pm8xxx_mpp_pdata __devinitdata = {
.mpp_base = PM8018_MPP_PM_TO_SYS(1),
};
static struct pm8xxx_rtc_platform_data pm8xxx_rtc_pdata __devinitdata = {
.rtc_write_enable = false,
.rtc_alarm_powerup = false,
};
static struct pm8xxx_pwrkey_platform_data pm8xxx_pwrkey_pdata = {
.pull_up = 1,
.kpd_trigger_delay_us = 15625,
.wakeup = 1,
};
static struct pm8xxx_misc_platform_data pm8xxx_misc_pdata = {
.priority = 0,
};
#define PM8018_LED_KB_MAX_CURRENT 20 /* I = 20mA */
#define PM8XXX_LED_PWM_PERIOD_US 1000
/**
* PM8XXX_PWM_CHANNEL_NONE shall be used when LED shall not be
* driven using PWM feature.
*/
#define PM8XXX_PWM_CHANNEL_NONE -1
static struct led_info pm8018_led_info[] = {
[0] = {
.name = "led:kb",
},
};
static struct led_platform_data pm8018_led_core_pdata = {
.num_leds = ARRAY_SIZE(pm8018_led_info),
.leds = pm8018_led_info,
};
static struct pm8xxx_led_config pm8018_led_configs[] = {
[0] = {
.id = PM8XXX_ID_LED_KB_LIGHT,
.mode = PM8XXX_LED_MODE_PWM3,
.max_current = PM8018_LED_KB_MAX_CURRENT,
.pwm_channel = 2,
.pwm_period_us = PM8XXX_LED_PWM_PERIOD_US,
},
};
static struct pm8xxx_led_platform_data pm8xxx_leds_pdata = {
.led_core = &pm8018_led_core_pdata,
.configs = pm8018_led_configs,
.num_configs = ARRAY_SIZE(pm8018_led_configs),
};
#ifdef CONFIG_LTC4088_CHARGER
static struct ltc4088_charger_platform_data ltc4088_chg_pdata = {
.gpio_mode_select_d0 = 7,
.gpio_mode_select_d1 = 6,
.gpio_mode_select_d2 = 4,
};
#endif
static struct pm8018_platform_data pm8018_platform_data __devinitdata = {
.irq_pdata = &pm8xxx_irq_pdata,
.gpio_pdata = &pm8xxx_gpio_pdata,
.mpp_pdata = &pm8xxx_mpp_pdata,
.rtc_pdata = &pm8xxx_rtc_pdata,
.pwrkey_pdata = &pm8xxx_pwrkey_pdata,
.misc_pdata = &pm8xxx_misc_pdata,
.regulator_pdatas = msm_pm8018_regulator_pdata,
.adc_pdata = &pm8018_adc_pdata,
.leds_pdata = &pm8xxx_leds_pdata,
};
static struct msm_ssbi_platform_data msm9615_ssbi_pm8018_pdata __devinitdata = {
.controller_type = MSM_SBI_CTRL_PMIC_ARBITER,
.slave = {
.name = PM8018_CORE_DEV_NAME,
.platform_data = &pm8018_platform_data,
},
};
static struct platform_device msm9615_device_rpm_regulator __devinitdata = {
.name = "rpm-regulator",
.id = -1,
.dev = {
.platform_data = &msm_rpm_regulator_9615_pdata,
},
};
static struct platform_device msm9615_device_ext_2p95v_vreg = {
.name = GPIO_REGULATOR_DEV_NAME,
.id = 18,
.dev = {
.platform_data =
&msm_gpio_regulator_pdata[GPIO_VREG_ID_EXT_2P95V],
},
};
static struct msm_pm_boot_platform_data msm_pm_boot_pdata __initdata = {
.mode = MSM_PM_BOOT_CONFIG_REMAP_BOOT_ADDR,
.v_addr = MSM_APCS_GLB_BASE + 0x24,
};
static void __init msm9615_init_buses(void)
{
#ifdef CONFIG_MSM_BUS_SCALING
msm_bus_rpm_set_mt_mask();
msm_bus_9615_sys_fabric_pdata.rpm_enabled = 1;
msm_bus_9615_sys_fabric.dev.platform_data =
&msm_bus_9615_sys_fabric_pdata;
msm_bus_def_fab.dev.platform_data = &msm_bus_9615_def_fab_pdata;
#endif
}
#ifdef CONFIG_WCD9310_CODEC
#define TABLA_INTERRUPT_BASE (NR_MSM_IRQS + NR_GPIO_IRQS)
/*
* MDM9x15 I2S.
*/
static struct wcd9xxx_pdata wcd9xxx_i2c_platform_data = {
.irq = MSM_GPIO_TO_INT(85),
.irq_base = TABLA_INTERRUPT_BASE,
.num_irqs = NR_TABLA_IRQS,
.reset_gpio = 84,
.micbias = {
.ldoh_v = TABLA_LDOH_2P85_V,
.cfilt1_mv = 1800,
.cfilt2_mv = 1800,
.cfilt3_mv = 1800,
.bias1_cfilt_sel = TABLA_CFILT1_SEL,
.bias2_cfilt_sel = TABLA_CFILT2_SEL,
.bias3_cfilt_sel = TABLA_CFILT3_SEL,
.bias4_cfilt_sel = TABLA_CFILT3_SEL,
},
.regulator = {
{
.name = "CDC_VDD_CP",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_CP_CUR_MAX,
},
{
.name = "CDC_VDDA_RX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_RX_CUR_MAX,
},
{
.name = "CDC_VDDA_TX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_TX_CUR_MAX,
},
{
.name = "VDDIO_CDC",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_VDDIO_CDC_CUR_MAX,
},
{
.name = "VDDD_CDC_D",
.min_uV = 1225000,
.max_uV = 1225000,
.optimum_uA = WCD9XXX_VDDD_CDC_D_CUR_MAX,
},
{
.name = "CDC_VDDA_A_1P2V",
.min_uV = 1225000,
.max_uV = 1225000,
.optimum_uA = WCD9XXX_VDDD_CDC_A_CUR_MAX,
}
},
};
static struct i2c_board_info wcd9xxx_device_info[] __initdata = {
{
I2C_BOARD_INFO("tabla top level", TABLA_I2C_SLAVE_ADDR),
.platform_data = &wcd9xxx_i2c_platform_data,
},
{
I2C_BOARD_INFO("tabla analog", TABLA_ANALOG_I2C_SLAVE_ADDR),
.platform_data = &wcd9xxx_i2c_platform_data,
},
{
I2C_BOARD_INFO("tabla digital1", TABLA_DIGITAL1_I2C_SLAVE_ADDR),
.platform_data = &wcd9xxx_i2c_platform_data,
},
{
I2C_BOARD_INFO("tabla digital2", TABLA_DIGITAL2_I2C_SLAVE_ADDR),
.platform_data = &wcd9xxx_i2c_platform_data,
},
};
/*
* MDM9x15 I2S.
*/
/* Micbias setting is based on 8660 CDP/MTP/FLUID requirement
* 4 micbiases are used to power various analog and digital
* microphones operating at 1800 mV. Technically, all micbiases
* can source from single cfilter since all microphones operate
* at the same voltage level. The arrangement below is to make
* sure all cfilters are exercised. LDO_H regulator ouput level
* does not need to be as high as 2.85V. It is choosen for
* microphone sensitivity purpose.
*/
static struct wcd9xxx_pdata tabla20_platform_data = {
.slimbus_slave_device = {
.name = "tabla-slave",
.e_addr = {0, 0, 0x60, 0, 0x17, 2},
},
.irq = MSM_GPIO_TO_INT(85),
.irq_base = TABLA_INTERRUPT_BASE,
.num_irqs = NR_WCD9XXX_IRQS,
.reset_gpio = 84,
.micbias = {
.ldoh_v = TABLA_LDOH_2P85_V,
.cfilt1_mv = 1800,
.cfilt2_mv = 1800,
.cfilt3_mv = 1800,
.bias1_cfilt_sel = TABLA_CFILT1_SEL,
.bias2_cfilt_sel = TABLA_CFILT2_SEL,
.bias3_cfilt_sel = TABLA_CFILT3_SEL,
.bias4_cfilt_sel = TABLA_CFILT3_SEL,
},
.regulator = {
{
.name = "CDC_VDD_CP",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_CP_CUR_MAX,
},
{
.name = "CDC_VDDA_RX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_RX_CUR_MAX,
},
{
.name = "CDC_VDDA_TX",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_CDC_VDDA_TX_CUR_MAX,
},
{
.name = "VDDIO_CDC",
.min_uV = 1800000,
.max_uV = 1800000,
.optimum_uA = WCD9XXX_VDDIO_CDC_CUR_MAX,
},
{
.name = "VDDD_CDC_D",
.min_uV = 1225000,
.max_uV = 1225000,
.optimum_uA = WCD9XXX_VDDD_CDC_D_CUR_MAX,
},
{
.name = "CDC_VDDA_A_1P2V",
.min_uV = 1225000,
.max_uV = 1225000,
.optimum_uA = WCD9XXX_VDDD_CDC_A_CUR_MAX,
},
},
};
static struct slim_device msm_slim_tabla20 = {
.name = "tabla2x-slim",
.e_addr = {0, 1, 0x60, 0, 0x17, 2},
.dev = {
.platform_data = &tabla20_platform_data,
},
};
#endif
static struct i2c_registry msm9615_i2c_devices[] __initdata = {
#ifdef CONFIG_WCD9310_CODEC
{
I2C_SURF | I2C_FFA | I2C_FLUID,
MSM_9615_GSBI5_QUP_I2C_BUS_ID,
wcd9xxx_device_info,
ARRAY_SIZE(wcd9xxx_device_info),
},
#endif
};
static struct slim_boardinfo msm_slim_devices[] = {
/* add slimbus slaves as needed */
#ifdef CONFIG_WCD9310_CODEC
{
.bus_num = 1,
.slim_slave = &msm_slim_tabla20,
},
#endif
};
static struct msm_spi_platform_data msm9615_qup_spi_gsbi3_pdata = {
.max_clock_speed = 24000000,
};
static struct msm_i2c_platform_data msm9615_i2c_qup_gsbi5_pdata = {
.clk_freq = 100000,
.src_clk_rate = 24000000,
};
#define USB_5V_EN 3
#define PM_USB_5V_EN PM8018_GPIO_PM_TO_SYS(USB_5V_EN)
static int msm_hsusb_vbus_power(bool on)
{
int rc;
struct pm_gpio usb_vbus = {
.direction = PM_GPIO_DIR_OUT,
.pull = PM_GPIO_PULL_NO,
.output_buffer = PM_GPIO_OUT_BUF_CMOS,
.vin_sel = 2,
.out_strength = PM_GPIO_STRENGTH_HIGH,
.function = PM_GPIO_FUNC_NORMAL,
.inv_int_pol = 0,
};
usb_vbus.output_value = on;
rc = pm8xxx_gpio_config(PM_USB_5V_EN, &usb_vbus);
if (rc)
pr_err("failed to config usb_5v_en gpio\n");
return rc;
}
static int shelby_phy_init_seq[] = {
0x44, 0x80,/* set VBUS valid threshold and
disconnect valid threshold */
0x38, 0x81, /* update DC voltage level */
0x24, 0x82,/* set preemphasis and rise/fall time */
0x13, 0x83,/* set source impedance adjustment */
-1};
#define USB_BAM_PHY_BASE 0x12502000
#define HSIC_BAM_PHY_BASE 0x12542000
#define A2_BAM_PHY_BASE 0x124C2000
static struct usb_bam_pipe_connect msm_usb_bam_connections[2][4][2] = {
[0][0][USB_TO_PEER_PERIPHERAL] = {
.src_phy_addr = USB_BAM_PHY_BASE,
.src_pipe_index = 11,
.dst_phy_addr = A2_BAM_PHY_BASE,
.dst_pipe_index = 0,
.data_fifo_base_offset = 0x1100,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x1700,
.desc_fifo_size = 0x300,
},
[0][0][PEER_PERIPHERAL_TO_USB] = {
.src_phy_addr = A2_BAM_PHY_BASE,
.src_pipe_index = 1,
.dst_phy_addr = USB_BAM_PHY_BASE,
.dst_pipe_index = 10,
.data_fifo_base_offset = 0xa00,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x1000,
.desc_fifo_size = 0x100,
},
[0][1][USB_TO_PEER_PERIPHERAL] = {
.src_phy_addr = USB_BAM_PHY_BASE,
.src_pipe_index = 13,
.dst_phy_addr = A2_BAM_PHY_BASE,
.dst_pipe_index = 2,
.data_fifo_base_offset = 0x2100,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x2700,
.desc_fifo_size = 0x300,
},
[0][1][PEER_PERIPHERAL_TO_USB] = {
.src_phy_addr = A2_BAM_PHY_BASE,
.src_pipe_index = 3,
.dst_phy_addr = USB_BAM_PHY_BASE,
.dst_pipe_index = 12,
.data_fifo_base_offset = 0x1a00,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x2000,
.desc_fifo_size = 0x100,
},
[0][2][USB_TO_PEER_PERIPHERAL] = {
.src_phy_addr = USB_BAM_PHY_BASE,
.src_pipe_index = 15,
.dst_phy_addr = A2_BAM_PHY_BASE,
.dst_pipe_index = 4,
.data_fifo_base_offset = 0x3100,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x3700,
.desc_fifo_size = 0x300,
},
[0][2][PEER_PERIPHERAL_TO_USB] = {
.src_phy_addr = A2_BAM_PHY_BASE,
.src_pipe_index = 5,
.dst_phy_addr = USB_BAM_PHY_BASE,
.dst_pipe_index = 14,
.data_fifo_base_offset = 0x2a00,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x3000,
.desc_fifo_size = 0x100,
},
[1][0][USB_TO_PEER_PERIPHERAL] = {
.src_phy_addr = HSIC_BAM_PHY_BASE,
.src_pipe_index = 1,
.dst_phy_addr = A2_BAM_PHY_BASE,
.dst_pipe_index = 0,
.data_fifo_base_offset = 0x1100,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x1700,
.desc_fifo_size = 0x300,
},
[1][0][PEER_PERIPHERAL_TO_USB] = {
.src_phy_addr = A2_BAM_PHY_BASE,
.src_pipe_index = 1,
.dst_phy_addr = HSIC_BAM_PHY_BASE,
.dst_pipe_index = 0,
.data_fifo_base_offset = 0xa00,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x1000,
.desc_fifo_size = 0x100,
},
[1][1][USB_TO_PEER_PERIPHERAL] = {
.src_phy_addr = HSIC_BAM_PHY_BASE,
.src_pipe_index = 3,
.dst_phy_addr = A2_BAM_PHY_BASE,
.dst_pipe_index = 2,
.data_fifo_base_offset = 0x2100,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x2700,
.desc_fifo_size = 0x300,
},
[1][1][PEER_PERIPHERAL_TO_USB] = {
.src_phy_addr = A2_BAM_PHY_BASE,
.src_pipe_index = 3,
.dst_phy_addr = HSIC_BAM_PHY_BASE,
.dst_pipe_index = 2,
.data_fifo_base_offset = 0x1a00,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x2000,
.desc_fifo_size = 0x100,
},
[1][2][USB_TO_PEER_PERIPHERAL] = {
.src_phy_addr = HSIC_BAM_PHY_BASE,
.src_pipe_index = 5,
.dst_phy_addr = A2_BAM_PHY_BASE,
.dst_pipe_index = 4,
.data_fifo_base_offset = 0x3100,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x3700,
.desc_fifo_size = 0x300,
},
[1][2][PEER_PERIPHERAL_TO_USB] = {
.src_phy_addr = A2_BAM_PHY_BASE,
.src_pipe_index = 5,
.dst_phy_addr = HSIC_BAM_PHY_BASE,
.dst_pipe_index = 4,
.data_fifo_base_offset = 0x2a00,
.data_fifo_size = 0x600,
.desc_fifo_base_offset = 0x3000,
.desc_fifo_size = 0x100,
}
};
static struct msm_usb_bam_platform_data msm_usb_bam_pdata = {
.connections = &msm_usb_bam_connections[0][0][0],
#ifndef CONFIG_USB_CI13XXX_MSM_HSIC
.usb_active_bam = HSUSB_BAM,
#else
.usb_active_bam = HSIC_BAM,
#endif
.usb_bam_num_pipes = 16,
};
static struct msm_otg_platform_data msm_otg_pdata = {
.mode = USB_OTG,
.otg_control = OTG_PHY_CONTROL,
.phy_type = SNPS_28NM_INTEGRATED_PHY,
.vbus_power = msm_hsusb_vbus_power,
.disable_reset_on_disconnect = true,
.enable_lpm_on_dev_suspend = true,
.core_clk_always_on_workaround = true,
};
static struct ci13xxx_platform_data msm_peripheral_pdata = {
.usb_core_id = 0,
};
static struct msm_hsic_peripheral_platform_data
msm_hsic_peripheral_pdata_private = {
.core_clk_always_on_workaround = true,
};
static struct ci13xxx_platform_data msm_hsic_peripheral_pdata = {
.usb_core_id = 1,
.prv_data = &msm_hsic_peripheral_pdata_private,
};
#define PID_MAGIC_ID 0x71432909
#define SERIAL_NUM_MAGIC_ID 0x61945374
#define SERIAL_NUMBER_LENGTH 127
#define DLOAD_USB_BASE_ADD 0x2B0000C8
struct magic_num_struct {
uint32_t pid;
uint32_t serial_num;
};
struct dload_struct {
uint32_t reserved1;
uint32_t reserved2;
uint32_t reserved3;
uint16_t reserved4;
uint16_t pid;
char serial_number[SERIAL_NUMBER_LENGTH];
uint16_t reserved5;
struct magic_num_struct magic_struct;
};
static int usb_diag_update_pid_and_serial_num(uint32_t pid, const char *snum)
{
struct dload_struct __iomem *dload = 0;
dload = ioremap(DLOAD_USB_BASE_ADD, sizeof(*dload));
if (!dload) {
pr_err("%s: cannot remap I/O memory region: %08x\n",
__func__, DLOAD_USB_BASE_ADD);
return -ENXIO;
}
pr_debug("%s: dload:%p pid:%x serial_num:%s\n",
__func__, dload, pid, snum);
/* update pid */
dload->magic_struct.pid = PID_MAGIC_ID;
dload->pid = pid;
/* update serial number */
dload->magic_struct.serial_num = 0;
if (!snum) {
memset(dload->serial_number, 0, SERIAL_NUMBER_LENGTH);
goto out;
}
dload->magic_struct.serial_num = SERIAL_NUM_MAGIC_ID;
strlcpy(dload->serial_number, snum, SERIAL_NUMBER_LENGTH);
out:
iounmap(dload);
return 0;
}
static struct platform_device msm_wlan_ar6000_pm_device = {
.name = "wlan_ar6000_pm_dev",
.id = -1,
};
static int __init msm9615_init_ar6000pm(void)
{
return platform_device_register(&msm_wlan_ar6000_pm_device);
}
#ifdef CONFIG_LTC4088_CHARGER
static struct platform_device msm_device_charger = {
.name = LTC4088_CHARGER_DEV_NAME,
.id = -1,
.dev = {
.platform_data = <c4088_chg_pdata,
},
};
#endif
static struct tsens_platform_data msm_tsens_pdata = {
.tsens_factor = 1000,
.hw_type = MDM_9615,
.tsens_num_sensor = 5,
.slope = {1176, 1162, 1162, 1149, 1176},
};
static struct platform_device msm_tsens_device = {
.name = "tsens8960-tm",
.id = -1,
};
static struct platform_device *common_devices[] = {
&msm9615_device_acpuclk,
&msm9615_device_dmov,
&msm_device_smd,
#ifdef CONFIG_LTC4088_CHARGER
&msm_device_charger,
#endif
&msm_device_otg,
&msm_device_hsic_peripheral,
&msm_device_gadget_peripheral,
&msm_device_hsusb_host,
&msm_device_hsic_host,
&msm_device_usb_bam,
&msm_android_usb_device,
&msm_android_usb_hsic_device,
&msm9615_device_uart_gsbi4,
&msm9615_device_ext_2p95v_vreg,
&msm9615_device_ssbi_pmic1,
&msm9615_device_qup_i2c_gsbi5,
&msm9615_device_qup_spi_gsbi3,
&msm_device_sps,
&msm9615_slim_ctrl,
&msm_device_nand,
&msm_device_bam_dmux,
&msm9615_rpm_device,
#ifdef CONFIG_HW_RANDOM_MSM
&msm_device_rng,
#endif
#ifdef CONFIG_ION_MSM
&ion_dev,
#endif
&msm_pcm,
&msm_multi_ch_pcm,
&msm_pcm_routing,
&msm_cpudai0,
&msm_cpudai1,
&msm_cpudai_bt_rx,
&msm_cpudai_bt_tx,
&msm_cpu_fe,
&msm_stub_codec,
&msm_voice,
&msm_voip,
&msm_i2s_cpudai0,
&msm_i2s_cpudai1,
&msm_pcm_hostless,
&msm_cpudai_afe_01_rx,
&msm_cpudai_afe_01_tx,
&msm_cpudai_afe_02_rx,
&msm_cpudai_afe_02_tx,
&msm_pcm_afe,
&msm_cpudai_auxpcm_rx,
&msm_cpudai_auxpcm_tx,
&msm_cpudai_sec_auxpcm_rx,
&msm_cpudai_sec_auxpcm_tx,
#if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \
defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE)
&msm9615_qcrypto_device,
#endif
#if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \
defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE)
&msm9615_qcedev_device,
#endif
&msm9615_device_watchdog,
&msm_bus_9615_sys_fabric,
&msm_bus_def_fab,
&msm9615_rpm_log_device,
&msm9615_rpm_stat_device,
&msm9615_rpm_master_stat_device,
&msm_tsens_device,
};
static void __init msm9615_i2c_init(void)
{
u8 mach_mask = 0;
int i;
/* Mask is hardcoded to SURF (CDP).
* works on MTP with same configuration.
*/
mach_mask = I2C_SURF;
if (machine_is_msm9615_cdp())
mach_mask = I2C_SURF;
else if (machine_is_msm9615_mtp())
mach_mask = I2C_FFA;
else
pr_err("unmatched machine ID in register_i2c_devices\n");
msm9615_device_qup_i2c_gsbi5.dev.platform_data =
&msm9615_i2c_qup_gsbi5_pdata;
for (i = 0; i < ARRAY_SIZE(msm9615_i2c_devices); ++i) {
if (msm9615_i2c_devices[i].machs & mach_mask) {
i2c_register_board_info(msm9615_i2c_devices[i].bus,
msm9615_i2c_devices[i].info,
msm9615_i2c_devices[i].len);
}
}
}
static void __init msm9615_reserve(void)
{
#ifdef CONFIG_ION_MSM
reserve_info = &msm9615_reserve_info;
msm_reserve();
#endif
}
static void __init msm9615_common_init(void)
{
struct android_usb_platform_data *android_pdata =
msm_android_usb_device.dev.platform_data;
struct android_usb_platform_data *android_hsic_pdata =
msm_android_usb_hsic_device.dev.platform_data;
msm9615_device_init();
platform_device_register(&msm_gpio_device);
msm9615_init_gpiomux();
msm9615_i2c_init();
regulator_suppress_info_printing();
platform_device_register(&msm9615_device_rpm_regulator);
msm_xo_init();
msm_clock_init(&msm9615_clock_init_data);
msm9615_init_buses();
msm9615_device_qup_spi_gsbi3.dev.platform_data =
&msm9615_qup_spi_gsbi3_pdata;
msm9615_device_ssbi_pmic1.dev.platform_data =
&msm9615_ssbi_pm8018_pdata;
pm8018_platform_data.num_regulators = msm_pm8018_regulator_pdata_len;
msm_device_otg.dev.platform_data = &msm_otg_pdata;
msm_otg_pdata.phy_init_seq = shelby_phy_init_seq;
msm_device_gadget_peripheral.dev.platform_data =
&msm_peripheral_pdata;
msm_device_hsic_peripheral.dev.platform_data =
&msm_hsic_peripheral_pdata;
msm_device_usb_bam.dev.platform_data = &msm_usb_bam_pdata;
platform_add_devices(common_devices, ARRAY_SIZE(common_devices));
msm9615_pm8xxx_gpio_mpp_init();
/* Ensure ar6000pm device is registered before MMC/SDC */
msm9615_init_ar6000pm();
msm9615_init_mmc();
slim_register_board_info(msm_slim_devices,
ARRAY_SIZE(msm_slim_devices));
android_pdata->update_pid_and_serial_num =
usb_diag_update_pid_and_serial_num;
android_hsic_pdata->update_pid_and_serial_num =
usb_diag_update_pid_and_serial_num;
msm_pm_boot_pdata.p_addr = allocate_contiguous_ebi_nomap(SZ_8, SZ_64K);
BUG_ON(msm_pm_boot_init(&msm_pm_boot_pdata));
msm_tsens_early_init(&msm_tsens_pdata);
}
static void __init msm9615_cdp_init(void)
{
msm9615_common_init();
#ifdef CONFIG_FB_MSM
mdm9615_init_fb();
#endif
}
static void __init msm9615_mtp_init(void)
{
msm9615_common_init();
}
#ifdef CONFIG_FB_MSM
static void __init mdm9615_allocate_memory_regions(void)
{
mdm9615_allocate_fb_region();
}
#endif
MACHINE_START(MSM9615_CDP, "QCT MSM9615 CDP")
.map_io = msm9615_map_io,
.init_irq = msm9615_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm9615_cdp_init,
.reserve = msm9615_reserve,
#ifdef CONFIG_FB_MSM
.init_early = mdm9615_allocate_memory_regions,
#endif
.restart = msm_restart,
MACHINE_END
MACHINE_START(MSM9615_MTP, "QCT MSM9615 MTP")
.map_io = msm9615_map_io,
.init_irq = msm9615_init_irq,
.handle_irq = gic_handle_irq,
.timer = &msm_timer,
.init_machine = msm9615_mtp_init,
.reserve = msm9615_reserve,
.restart = msm_restart,
MACHINE_END
| gpl-2.0 |
hash07/Apollo_X | net/netfilter/core.c | 1926 | 8010 | /* netfilter.c: look after the filters for various protocols.
* Heavily influenced by the old firewall.c by David Bonn and Alan Cox.
*
* Thanks to Rob `CmdrTaco' Malda for not influencing this code in any
* way.
*
* Rusty Russell (C)2000 -- This code is GPL.
* Patrick McHardy (c) 2006-2012
*/
#include <linux/kernel.h>
#include <linux/netfilter.h>
#include <net/protocol.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/wait.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/if.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/proc_fs.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include "nf_internals.h"
static DEFINE_MUTEX(afinfo_mutex);
const struct nf_afinfo __rcu *nf_afinfo[NFPROTO_NUMPROTO] __read_mostly;
EXPORT_SYMBOL(nf_afinfo);
const struct nf_ipv6_ops __rcu *nf_ipv6_ops __read_mostly;
EXPORT_SYMBOL_GPL(nf_ipv6_ops);
int nf_register_afinfo(const struct nf_afinfo *afinfo)
{
int err;
err = mutex_lock_interruptible(&afinfo_mutex);
if (err < 0)
return err;
RCU_INIT_POINTER(nf_afinfo[afinfo->family], afinfo);
mutex_unlock(&afinfo_mutex);
return 0;
}
EXPORT_SYMBOL_GPL(nf_register_afinfo);
void nf_unregister_afinfo(const struct nf_afinfo *afinfo)
{
mutex_lock(&afinfo_mutex);
RCU_INIT_POINTER(nf_afinfo[afinfo->family], NULL);
mutex_unlock(&afinfo_mutex);
synchronize_rcu();
}
EXPORT_SYMBOL_GPL(nf_unregister_afinfo);
struct list_head nf_hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS] __read_mostly;
EXPORT_SYMBOL(nf_hooks);
#if defined(CONFIG_JUMP_LABEL)
struct static_key nf_hooks_needed[NFPROTO_NUMPROTO][NF_MAX_HOOKS];
EXPORT_SYMBOL(nf_hooks_needed);
#endif
static DEFINE_MUTEX(nf_hook_mutex);
int nf_register_hook(struct nf_hook_ops *reg)
{
struct nf_hook_ops *elem;
int err;
err = mutex_lock_interruptible(&nf_hook_mutex);
if (err < 0)
return err;
list_for_each_entry(elem, &nf_hooks[reg->pf][reg->hooknum], list) {
if (reg->priority < elem->priority)
break;
}
list_add_rcu(®->list, elem->list.prev);
mutex_unlock(&nf_hook_mutex);
#if defined(CONFIG_JUMP_LABEL)
static_key_slow_inc(&nf_hooks_needed[reg->pf][reg->hooknum]);
#endif
return 0;
}
EXPORT_SYMBOL(nf_register_hook);
void nf_unregister_hook(struct nf_hook_ops *reg)
{
mutex_lock(&nf_hook_mutex);
list_del_rcu(®->list);
mutex_unlock(&nf_hook_mutex);
#if defined(CONFIG_JUMP_LABEL)
static_key_slow_dec(&nf_hooks_needed[reg->pf][reg->hooknum]);
#endif
synchronize_net();
}
EXPORT_SYMBOL(nf_unregister_hook);
int nf_register_hooks(struct nf_hook_ops *reg, unsigned int n)
{
unsigned int i;
int err = 0;
for (i = 0; i < n; i++) {
err = nf_register_hook(®[i]);
if (err)
goto err;
}
return err;
err:
if (i > 0)
nf_unregister_hooks(reg, i);
return err;
}
EXPORT_SYMBOL(nf_register_hooks);
void nf_unregister_hooks(struct nf_hook_ops *reg, unsigned int n)
{
while (n-- > 0)
nf_unregister_hook(®[n]);
}
EXPORT_SYMBOL(nf_unregister_hooks);
unsigned int nf_iterate(struct list_head *head,
struct sk_buff *skb,
unsigned int hook,
const struct net_device *indev,
const struct net_device *outdev,
struct nf_hook_ops **elemp,
int (*okfn)(struct sk_buff *),
int hook_thresh)
{
unsigned int verdict;
/*
* The caller must not block between calls to this
* function because of risk of continuing from deleted element.
*/
list_for_each_entry_continue_rcu((*elemp), head, list) {
if (hook_thresh > (*elemp)->priority)
continue;
/* Optimization: we don't need to hold module
reference here, since function can't sleep. --RR */
repeat:
verdict = (*elemp)->hook(hook, skb, indev, outdev, okfn);
if (verdict != NF_ACCEPT) {
#ifdef CONFIG_NETFILTER_DEBUG
if (unlikely((verdict & NF_VERDICT_MASK)
> NF_MAX_VERDICT)) {
NFDEBUG("Evil return from %p(%u).\n",
(*elemp)->hook, hook);
continue;
}
#endif
if (verdict != NF_REPEAT)
return verdict;
goto repeat;
}
}
return NF_ACCEPT;
}
/* Returns 1 if okfn() needs to be executed by the caller,
* -EPERM for NF_DROP, 0 otherwise. */
int nf_hook_slow(u_int8_t pf, unsigned int hook, struct sk_buff *skb,
struct net_device *indev,
struct net_device *outdev,
int (*okfn)(struct sk_buff *),
int hook_thresh)
{
struct nf_hook_ops *elem;
unsigned int verdict;
int ret = 0;
/* We may already have this, but read-locks nest anyway */
rcu_read_lock();
elem = list_entry_rcu(&nf_hooks[pf][hook], struct nf_hook_ops, list);
next_hook:
verdict = nf_iterate(&nf_hooks[pf][hook], skb, hook, indev,
outdev, &elem, okfn, hook_thresh);
if (verdict == NF_ACCEPT || verdict == NF_STOP) {
ret = 1;
} else if ((verdict & NF_VERDICT_MASK) == NF_DROP) {
kfree_skb(skb);
ret = NF_DROP_GETERR(verdict);
if (ret == 0)
ret = -EPERM;
} else if ((verdict & NF_VERDICT_MASK) == NF_QUEUE) {
int err = nf_queue(skb, elem, pf, hook, indev, outdev, okfn,
verdict >> NF_VERDICT_QBITS);
if (err < 0) {
if (err == -ECANCELED)
goto next_hook;
if (err == -ESRCH &&
(verdict & NF_VERDICT_FLAG_QUEUE_BYPASS))
goto next_hook;
kfree_skb(skb);
}
}
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(nf_hook_slow);
int skb_make_writable(struct sk_buff *skb, unsigned int writable_len)
{
if (writable_len > skb->len)
return 0;
/* Not exclusive use of packet? Must copy. */
if (!skb_cloned(skb)) {
if (writable_len <= skb_headlen(skb))
return 1;
} else if (skb_clone_writable(skb, writable_len))
return 1;
if (writable_len <= skb_headlen(skb))
writable_len = 0;
else
writable_len -= skb_headlen(skb);
return !!__pskb_pull_tail(skb, writable_len);
}
EXPORT_SYMBOL(skb_make_writable);
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
/* This does not belong here, but locally generated errors need it if connection
tracking in use: without this, connection may not be in hash table, and hence
manufactured ICMP or RST packets will not be associated with it. */
void (*ip_ct_attach)(struct sk_buff *, struct sk_buff *) __rcu __read_mostly;
EXPORT_SYMBOL(ip_ct_attach);
void nf_ct_attach(struct sk_buff *new, struct sk_buff *skb)
{
void (*attach)(struct sk_buff *, struct sk_buff *);
if (skb->nfct) {
rcu_read_lock();
attach = rcu_dereference(ip_ct_attach);
if (attach)
attach(new, skb);
rcu_read_unlock();
}
}
EXPORT_SYMBOL(nf_ct_attach);
void (*nf_ct_destroy)(struct nf_conntrack *) __rcu __read_mostly;
EXPORT_SYMBOL(nf_ct_destroy);
void nf_conntrack_destroy(struct nf_conntrack *nfct)
{
void (*destroy)(struct nf_conntrack *);
rcu_read_lock();
destroy = rcu_dereference(nf_ct_destroy);
BUG_ON(destroy == NULL);
destroy(nfct);
rcu_read_unlock();
}
EXPORT_SYMBOL(nf_conntrack_destroy);
struct nfq_ct_hook __rcu *nfq_ct_hook __read_mostly;
EXPORT_SYMBOL_GPL(nfq_ct_hook);
struct nfq_ct_nat_hook __rcu *nfq_ct_nat_hook __read_mostly;
EXPORT_SYMBOL_GPL(nfq_ct_nat_hook);
#endif /* CONFIG_NF_CONNTRACK */
#ifdef CONFIG_NF_NAT_NEEDED
void (*nf_nat_decode_session_hook)(struct sk_buff *, struct flowi *);
EXPORT_SYMBOL(nf_nat_decode_session_hook);
#endif
static int __net_init netfilter_net_init(struct net *net)
{
#ifdef CONFIG_PROC_FS
net->nf.proc_netfilter = proc_net_mkdir(net, "netfilter",
net->proc_net);
if (!net->nf.proc_netfilter) {
if (!net_eq(net, &init_net))
pr_err("cannot create netfilter proc entry");
return -ENOMEM;
}
#endif
return 0;
}
static void __net_exit netfilter_net_exit(struct net *net)
{
remove_proc_entry("netfilter", net->proc_net);
}
static struct pernet_operations netfilter_net_ops = {
.init = netfilter_net_init,
.exit = netfilter_net_exit,
};
void __init netfilter_init(void)
{
int i, h;
for (i = 0; i < ARRAY_SIZE(nf_hooks); i++) {
for (h = 0; h < NF_MAX_HOOKS; h++)
INIT_LIST_HEAD(&nf_hooks[i][h]);
}
if (register_pernet_subsys(&netfilter_net_ops) < 0)
panic("cannot create netfilter proc entry");
if (netfilter_log_init() < 0)
panic("cannot initialize nf_log");
}
| gpl-2.0 |
Alonso1398/muZic_kernel_ivoryss | drivers/net/wan/cycx_drv.c | 2694 | 15691 | /*
* cycx_drv.c Cyclom 2X Support Module.
*
* This module is a library of common hardware specific
* functions used by the Cyclades Cyclom 2X sync card.
*
* Author: Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* Copyright: (c) 1998-2003 Arnaldo Carvalho de Melo
*
* Based on sdladrv.c by Gene Kozin <genek@compuserve.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.
* ============================================================================
* 1999/11/11 acme set_current_state(TASK_INTERRUPTIBLE), code
* cleanup
* 1999/11/08 acme init_cyc2x deleted, doing nothing
* 1999/11/06 acme back to read[bw], write[bw] and memcpy_to and
* fromio to use dpmbase ioremaped
* 1999/10/26 acme use isa_read[bw], isa_write[bw] & isa_memcpy_to
* & fromio
* 1999/10/23 acme cleanup to only supports cyclom2x: all the other
* boards are no longer manufactured by cyclades,
* if someone wants to support them... be my guest!
* 1999/05/28 acme cycx_intack & cycx_intde gone for good
* 1999/05/18 acme lots of unlogged work, submitting to Linus...
* 1999/01/03 acme more judicious use of data types
* 1999/01/03 acme judicious use of data types :>
* cycx_inten trying to reset pending interrupts
* from cyclom 2x - I think this isn't the way to
* go, but for now...
* 1999/01/02 acme cycx_intack ok, I think there's nothing to do
* to ack an int in cycx_drv.c, only handle it in
* cyx_isr (or in the other protocols: cyp_isr,
* cyf_isr, when they get implemented.
* Dec 31, 1998 acme cycx_data_boot & cycx_code_boot fixed, crossing
* fingers to see x25_configure in cycx_x25.c
* work... :)
* Dec 26, 1998 acme load implementation fixed, seems to work! :)
* cycx_2x_dpmbase_options with all the possible
* DPM addresses (20).
* cycx_intr implemented (test this!)
* general code cleanup
* Dec 8, 1998 Ivan Passos Cyclom-2X firmware load implementation.
* Aug 8, 1998 acme Initial version.
*/
#include <linux/init.h> /* __init */
#include <linux/module.h>
#include <linux/kernel.h> /* printk(), and other useful stuff */
#include <linux/stddef.h> /* offsetof(), etc. */
#include <linux/errno.h> /* return codes */
#include <linux/cycx_drv.h> /* API definitions */
#include <linux/cycx_cfm.h> /* CYCX firmware module definitions */
#include <linux/delay.h> /* udelay, msleep_interruptible */
#include <asm/io.h> /* read[wl], write[wl], ioremap, iounmap */
#define MOD_VERSION 0
#define MOD_RELEASE 6
MODULE_AUTHOR("Arnaldo Carvalho de Melo");
MODULE_DESCRIPTION("Cyclom 2x Sync Card Driver");
MODULE_LICENSE("GPL");
/* Hardware-specific functions */
static int load_cyc2x(struct cycx_hw *hw, struct cycx_firmware *cfm, u32 len);
static void cycx_bootcfg(struct cycx_hw *hw);
static int reset_cyc2x(void __iomem *addr);
static int detect_cyc2x(void __iomem *addr);
/* Miscellaneous functions */
static int get_option_index(const long *optlist, long optval);
static u16 checksum(u8 *buf, u32 len);
#define wait_cyc(addr) cycx_exec(addr + CMD_OFFSET)
/* Global Data */
/* private data */
static const char modname[] = "cycx_drv";
static const char fullname[] = "Cyclom 2X Support Module";
static const char copyright[] = "(c) 1998-2003 Arnaldo Carvalho de Melo "
"<acme@conectiva.com.br>";
/* Hardware configuration options.
* These are arrays of configuration options used by verification routines.
* The first element of each array is its size (i.e. number of options).
*/
static const long cyc2x_dpmbase_options[] = {
20,
0xA0000, 0xA4000, 0xA8000, 0xAC000, 0xB0000, 0xB4000, 0xB8000,
0xBC000, 0xC0000, 0xC4000, 0xC8000, 0xCC000, 0xD0000, 0xD4000,
0xD8000, 0xDC000, 0xE0000, 0xE4000, 0xE8000, 0xEC000
};
static const long cycx_2x_irq_options[] = { 7, 3, 5, 9, 10, 11, 12, 15 };
/* Kernel Loadable Module Entry Points */
/* Module 'insert' entry point.
* o print announcement
* o initialize static data
*
* Return: 0 Ok
* < 0 error.
* Context: process */
static int __init cycx_drv_init(void)
{
printk(KERN_INFO "%s v%u.%u %s\n", fullname, MOD_VERSION, MOD_RELEASE,
copyright);
return 0;
}
/* Module 'remove' entry point.
* o release all remaining system resources */
static void cycx_drv_cleanup(void)
{
}
/* Kernel APIs */
/* Set up adapter.
* o detect adapter type
* o verify hardware configuration options
* o check for hardware conflicts
* o set up adapter shared memory
* o test adapter memory
* o load firmware
* Return: 0 ok.
* < 0 error */
EXPORT_SYMBOL(cycx_setup);
int cycx_setup(struct cycx_hw *hw, void *cfm, u32 len, unsigned long dpmbase)
{
int err;
/* Verify IRQ configuration options */
if (!get_option_index(cycx_2x_irq_options, hw->irq)) {
printk(KERN_ERR "%s: IRQ %d is invalid!\n", modname, hw->irq);
return -EINVAL;
}
/* Setup adapter dual-port memory window and test memory */
if (!dpmbase) {
printk(KERN_ERR "%s: you must specify the dpm address!\n",
modname);
return -EINVAL;
} else if (!get_option_index(cyc2x_dpmbase_options, dpmbase)) {
printk(KERN_ERR "%s: memory address 0x%lX is invalid!\n",
modname, dpmbase);
return -EINVAL;
}
hw->dpmbase = ioremap(dpmbase, CYCX_WINDOWSIZE);
hw->dpmsize = CYCX_WINDOWSIZE;
if (!detect_cyc2x(hw->dpmbase)) {
printk(KERN_ERR "%s: adapter Cyclom 2X not found at "
"address 0x%lX!\n", modname, dpmbase);
return -EINVAL;
}
printk(KERN_INFO "%s: found Cyclom 2X card at address 0x%lX.\n",
modname, dpmbase);
/* Load firmware. If loader fails then shut down adapter */
err = load_cyc2x(hw, cfm, len);
if (err)
cycx_down(hw); /* shutdown adapter */
return err;
}
EXPORT_SYMBOL(cycx_down);
int cycx_down(struct cycx_hw *hw)
{
iounmap(hw->dpmbase);
return 0;
}
/* Enable interrupt generation. */
static void cycx_inten(struct cycx_hw *hw)
{
writeb(0, hw->dpmbase);
}
/* Generate an interrupt to adapter's CPU. */
EXPORT_SYMBOL(cycx_intr);
void cycx_intr(struct cycx_hw *hw)
{
writew(0, hw->dpmbase + GEN_CYCX_INTR);
}
/* Execute Adapter Command.
* o Set exec flag.
* o Busy-wait until flag is reset. */
EXPORT_SYMBOL(cycx_exec);
int cycx_exec(void __iomem *addr)
{
u16 i = 0;
/* wait till addr content is zeroed */
while (readw(addr)) {
udelay(1000);
if (++i > 50)
return -1;
}
return 0;
}
/* Read absolute adapter memory.
* Transfer data from adapter's memory to data buffer. */
EXPORT_SYMBOL(cycx_peek);
int cycx_peek(struct cycx_hw *hw, u32 addr, void *buf, u32 len)
{
if (len == 1)
*(u8*)buf = readb(hw->dpmbase + addr);
else
memcpy_fromio(buf, hw->dpmbase + addr, len);
return 0;
}
/* Write Absolute Adapter Memory.
* Transfer data from data buffer to adapter's memory. */
EXPORT_SYMBOL(cycx_poke);
int cycx_poke(struct cycx_hw *hw, u32 addr, void *buf, u32 len)
{
if (len == 1)
writeb(*(u8*)buf, hw->dpmbase + addr);
else
memcpy_toio(hw->dpmbase + addr, buf, len);
return 0;
}
/* Hardware-Specific Functions */
/* Load Aux Routines */
/* Reset board hardware.
return 1 if memory exists at addr and 0 if not. */
static int memory_exists(void __iomem *addr)
{
int tries = 0;
for (; tries < 3 ; tries++) {
writew(TEST_PATTERN, addr + 0x10);
if (readw(addr + 0x10) == TEST_PATTERN)
if (readw(addr + 0x10) == TEST_PATTERN)
return 1;
msleep_interruptible(1 * 1000);
}
return 0;
}
/* Load reset code. */
static void reset_load(void __iomem *addr, u8 *buffer, u32 cnt)
{
void __iomem *pt_code = addr + RESET_OFFSET;
u16 i; /*, j; */
for (i = 0 ; i < cnt ; i++) {
/* for (j = 0 ; j < 50 ; j++); Delay - FIXME busy waiting... */
writeb(*buffer++, pt_code++);
}
}
/* Load buffer using boot interface.
* o copy data from buffer to Cyclom-X memory
* o wait for reset code to copy it to right portion of memory */
static int buffer_load(void __iomem *addr, u8 *buffer, u32 cnt)
{
memcpy_toio(addr + DATA_OFFSET, buffer, cnt);
writew(GEN_BOOT_DAT, addr + CMD_OFFSET);
return wait_cyc(addr);
}
/* Set up entry point and kick start Cyclom-X CPU. */
static void cycx_start(void __iomem *addr)
{
/* put in 0x30 offset the jump instruction to the code entry point */
writeb(0xea, addr + 0x30);
writeb(0x00, addr + 0x31);
writeb(0xc4, addr + 0x32);
writeb(0x00, addr + 0x33);
writeb(0x00, addr + 0x34);
/* cmd to start executing code */
writew(GEN_START, addr + CMD_OFFSET);
}
/* Load and boot reset code. */
static void cycx_reset_boot(void __iomem *addr, u8 *code, u32 len)
{
void __iomem *pt_start = addr + START_OFFSET;
writeb(0xea, pt_start++); /* jmp to f000:3f00 */
writeb(0x00, pt_start++);
writeb(0xfc, pt_start++);
writeb(0x00, pt_start++);
writeb(0xf0, pt_start);
reset_load(addr, code, len);
/* 80186 was in hold, go */
writeb(0, addr + START_CPU);
msleep_interruptible(1 * 1000);
}
/* Load data.bin file through boot (reset) interface. */
static int cycx_data_boot(void __iomem *addr, u8 *code, u32 len)
{
void __iomem *pt_boot_cmd = addr + CMD_OFFSET;
u32 i;
/* boot buffer length */
writew(CFM_LOAD_BUFSZ, pt_boot_cmd + sizeof(u16));
writew(GEN_DEFPAR, pt_boot_cmd);
if (wait_cyc(addr) < 0)
return -1;
writew(0, pt_boot_cmd + sizeof(u16));
writew(0x4000, pt_boot_cmd + 2 * sizeof(u16));
writew(GEN_SET_SEG, pt_boot_cmd);
if (wait_cyc(addr) < 0)
return -1;
for (i = 0 ; i < len ; i += CFM_LOAD_BUFSZ)
if (buffer_load(addr, code + i,
min_t(u32, CFM_LOAD_BUFSZ, (len - i))) < 0) {
printk(KERN_ERR "%s: Error !!\n", modname);
return -1;
}
return 0;
}
/* Load code.bin file through boot (reset) interface. */
static int cycx_code_boot(void __iomem *addr, u8 *code, u32 len)
{
void __iomem *pt_boot_cmd = addr + CMD_OFFSET;
u32 i;
/* boot buffer length */
writew(CFM_LOAD_BUFSZ, pt_boot_cmd + sizeof(u16));
writew(GEN_DEFPAR, pt_boot_cmd);
if (wait_cyc(addr) < 0)
return -1;
writew(0x0000, pt_boot_cmd + sizeof(u16));
writew(0xc400, pt_boot_cmd + 2 * sizeof(u16));
writew(GEN_SET_SEG, pt_boot_cmd);
if (wait_cyc(addr) < 0)
return -1;
for (i = 0 ; i < len ; i += CFM_LOAD_BUFSZ)
if (buffer_load(addr, code + i,
min_t(u32, CFM_LOAD_BUFSZ, (len - i)))) {
printk(KERN_ERR "%s: Error !!\n", modname);
return -1;
}
return 0;
}
/* Load adapter from the memory image of the CYCX firmware module.
* o verify firmware integrity and compatibility
* o start adapter up */
static int load_cyc2x(struct cycx_hw *hw, struct cycx_firmware *cfm, u32 len)
{
int i, j;
struct cycx_fw_header *img_hdr;
u8 *reset_image,
*data_image,
*code_image;
void __iomem *pt_cycld = hw->dpmbase + 0x400;
u16 cksum;
/* Announce */
printk(KERN_INFO "%s: firmware signature=\"%s\"\n", modname,
cfm->signature);
/* Verify firmware signature */
if (strcmp(cfm->signature, CFM_SIGNATURE)) {
printk(KERN_ERR "%s:load_cyc2x: not Cyclom-2X firmware!\n",
modname);
return -EINVAL;
}
printk(KERN_INFO "%s: firmware version=%u\n", modname, cfm->version);
/* Verify firmware module format version */
if (cfm->version != CFM_VERSION) {
printk(KERN_ERR "%s:%s: firmware format %u rejected! "
"Expecting %u.\n",
modname, __func__, cfm->version, CFM_VERSION);
return -EINVAL;
}
/* Verify firmware module length and checksum */
cksum = checksum((u8*)&cfm->info, sizeof(struct cycx_fw_info) +
cfm->info.codesize);
/*
FIXME cfm->info.codesize is off by 2
if (((len - sizeof(struct cycx_firmware) - 1) != cfm->info.codesize) ||
*/
if (cksum != cfm->checksum) {
printk(KERN_ERR "%s:%s: firmware corrupted!\n",
modname, __func__);
printk(KERN_ERR " cdsize = 0x%x (expected 0x%lx)\n",
len - (int)sizeof(struct cycx_firmware) - 1,
cfm->info.codesize);
printk(KERN_ERR " chksum = 0x%x (expected 0x%x)\n",
cksum, cfm->checksum);
return -EINVAL;
}
/* If everything is ok, set reset, data and code pointers */
img_hdr = (struct cycx_fw_header *)&cfm->image;
#ifdef FIRMWARE_DEBUG
printk(KERN_INFO "%s:%s: image sizes\n", __func__, modname);
printk(KERN_INFO " reset=%lu\n", img_hdr->reset_size);
printk(KERN_INFO " data=%lu\n", img_hdr->data_size);
printk(KERN_INFO " code=%lu\n", img_hdr->code_size);
#endif
reset_image = ((u8 *)img_hdr) + sizeof(struct cycx_fw_header);
data_image = reset_image + img_hdr->reset_size;
code_image = data_image + img_hdr->data_size;
/*---- Start load ----*/
/* Announce */
printk(KERN_INFO "%s: loading firmware %s (ID=%u)...\n", modname,
cfm->descr[0] ? cfm->descr : "unknown firmware",
cfm->info.codeid);
for (i = 0 ; i < 5 ; i++) {
/* Reset Cyclom hardware */
if (!reset_cyc2x(hw->dpmbase)) {
printk(KERN_ERR "%s: dpm problem or board not found\n",
modname);
return -EINVAL;
}
/* Load reset.bin */
cycx_reset_boot(hw->dpmbase, reset_image, img_hdr->reset_size);
/* reset is waiting for boot */
writew(GEN_POWER_ON, pt_cycld);
msleep_interruptible(1 * 1000);
for (j = 0 ; j < 3 ; j++)
if (!readw(pt_cycld))
goto reset_loaded;
else
msleep_interruptible(1 * 1000);
}
printk(KERN_ERR "%s: reset not started.\n", modname);
return -EINVAL;
reset_loaded:
/* Load data.bin */
if (cycx_data_boot(hw->dpmbase, data_image, img_hdr->data_size)) {
printk(KERN_ERR "%s: cannot load data file.\n", modname);
return -EINVAL;
}
/* Load code.bin */
if (cycx_code_boot(hw->dpmbase, code_image, img_hdr->code_size)) {
printk(KERN_ERR "%s: cannot load code file.\n", modname);
return -EINVAL;
}
/* Prepare boot-time configuration data */
cycx_bootcfg(hw);
/* kick-off CPU */
cycx_start(hw->dpmbase);
/* Arthur Ganzert's tip: wait a while after the firmware loading...
seg abr 26 17:17:12 EST 1999 - acme */
msleep_interruptible(7 * 1000);
printk(KERN_INFO "%s: firmware loaded!\n", modname);
/* enable interrupts */
cycx_inten(hw);
return 0;
}
/* Prepare boot-time firmware configuration data.
* o initialize configuration data area
From async.doc - V_3.4.0 - 07/18/1994
- As of now, only static buffers are available to the user.
So, the bit VD_RXDIRC must be set in 'valid'. That means that user
wants to use the static transmission and reception buffers. */
static void cycx_bootcfg(struct cycx_hw *hw)
{
/* use fixed buffers */
writeb(FIXED_BUFFERS, hw->dpmbase + CONF_OFFSET);
}
/* Detect Cyclom 2x adapter.
* Following tests are used to detect Cyclom 2x adapter:
* to be completed based on the tests done below
* Return 1 if detected o.k. or 0 if failed.
* Note: This test is destructive! Adapter will be left in shutdown
* state after the test. */
static int detect_cyc2x(void __iomem *addr)
{
reset_cyc2x(addr);
return memory_exists(addr);
}
/* Miscellaneous */
/* Get option's index into the options list.
* Return option's index (1 .. N) or zero if option is invalid. */
static int get_option_index(const long *optlist, long optval)
{
int i = 1;
for (; i <= optlist[0]; ++i)
if (optlist[i] == optval)
return i;
return 0;
}
/* Reset adapter's CPU. */
static int reset_cyc2x(void __iomem *addr)
{
writeb(0, addr + RST_ENABLE);
msleep_interruptible(2 * 1000);
writeb(0, addr + RST_DISABLE);
msleep_interruptible(2 * 1000);
return memory_exists(addr);
}
/* Calculate 16-bit CRC using CCITT polynomial. */
static u16 checksum(u8 *buf, u32 len)
{
u16 crc = 0;
u16 mask, flag;
for (; len; --len, ++buf)
for (mask = 0x80; mask; mask >>= 1) {
flag = (crc & 0x8000);
crc <<= 1;
crc |= ((*buf & mask) ? 1 : 0);
if (flag)
crc ^= 0x1021;
}
return crc;
}
module_init(cycx_drv_init);
module_exit(cycx_drv_cleanup);
/* End */
| gpl-2.0 |
moonlightly/android_kernel_zte_msm8960 | drivers/ata/pata_sl82c105.c | 2694 | 9240 | /*
* pata_sl82c105.c - SL82C105 PATA for new ATA layer
* (C) 2005 Red Hat Inc
*
* Based in part on linux/drivers/ide/pci/sl82c105.c
* SL82C105/Winbond 553 IDE driver
*
* and in part on the documentation and errata sheet
*
*
* Note: The controller like many controllers has shared timings for
* PIO and DMA. We thus flip to the DMA timings in dma_start and flip back
* in the dma_stop function. Thus we actually don't need a set_dmamode
* method as the PIO method is always called and will set the right PIO
* timing parameters.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_sl82c105"
#define DRV_VERSION "0.3.3"
enum {
/*
* SL82C105 PCI config register 0x40 bits.
*/
CTRL_IDE_IRQB = (1 << 30),
CTRL_IDE_IRQA = (1 << 28),
CTRL_LEGIRQ = (1 << 11),
CTRL_P1F16 = (1 << 5),
CTRL_P1EN = (1 << 4),
CTRL_P0F16 = (1 << 1),
CTRL_P0EN = (1 << 0)
};
/**
* sl82c105_pre_reset - probe begin
* @link: ATA link
* @deadline: deadline jiffies for the operation
*
* Set up cable type and use generic probe init
*/
static int sl82c105_pre_reset(struct ata_link *link, unsigned long deadline)
{
static const struct pci_bits sl82c105_enable_bits[] = {
{ 0x40, 1, 0x01, 0x01 },
{ 0x40, 1, 0x10, 0x10 }
};
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
if (ap->port_no && !pci_test_config_bits(pdev, &sl82c105_enable_bits[ap->port_no]))
return -ENOENT;
return ata_sff_prereset(link, deadline);
}
/**
* sl82c105_configure_piomode - set chip PIO timing
* @ap: ATA interface
* @adev: ATA device
* @pio: PIO mode
*
* Called to do the PIO mode setup. Our timing registers are shared
* so a configure_dmamode call will undo any work we do here and vice
* versa
*/
static void sl82c105_configure_piomode(struct ata_port *ap, struct ata_device *adev, int pio)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
static u16 pio_timing[5] = {
0x50D, 0x407, 0x304, 0x242, 0x240
};
u16 dummy;
int timing = 0x44 + (8 * ap->port_no) + (4 * adev->devno);
pci_write_config_word(pdev, timing, pio_timing[pio]);
/* Can we lose this oddity of the old driver */
pci_read_config_word(pdev, timing, &dummy);
}
/**
* sl82c105_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called to do the PIO mode setup. Our timing registers are shared
* but we want to set the PIO timing by default.
*/
static void sl82c105_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
sl82c105_configure_piomode(ap, adev, adev->pio_mode - XFER_PIO_0);
}
/**
* sl82c105_configure_dmamode - set DMA mode in chip
* @ap: ATA interface
* @adev: ATA device
*
* Load DMA cycle times into the chip ready for a DMA transfer
* to occur.
*/
static void sl82c105_configure_dmamode(struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
static u16 dma_timing[3] = {
0x707, 0x201, 0x200
};
u16 dummy;
int timing = 0x44 + (8 * ap->port_no) + (4 * adev->devno);
int dma = adev->dma_mode - XFER_MW_DMA_0;
pci_write_config_word(pdev, timing, dma_timing[dma]);
/* Can we lose this oddity of the old driver */
pci_read_config_word(pdev, timing, &dummy);
}
/**
* sl82c105_reset_engine - Reset the DMA engine
* @ap: ATA interface
*
* The sl82c105 has some serious problems with the DMA engine
* when transfers don't run as expected or ATAPI is used. The
* recommended fix is to reset the engine each use using a chip
* test register.
*/
static void sl82c105_reset_engine(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u16 val;
pci_read_config_word(pdev, 0x7E, &val);
pci_write_config_word(pdev, 0x7E, val | 4);
pci_write_config_word(pdev, 0x7E, val & ~4);
}
/**
* sl82c105_bmdma_start - DMA engine begin
* @qc: ATA command
*
* Reset the DMA engine each use as recommended by the errata
* document.
*
* FIXME: if we switch clock at BMDMA start/end we might get better
* PIO performance on DMA capable devices.
*/
static void sl82c105_bmdma_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
udelay(100);
sl82c105_reset_engine(ap);
udelay(100);
/* Set the clocks for DMA */
sl82c105_configure_dmamode(ap, qc->dev);
/* Activate DMA */
ata_bmdma_start(qc);
}
/**
* sl82c105_bmdma_end - DMA engine stop
* @qc: ATA command
*
* Reset the DMA engine each use as recommended by the errata
* document.
*
* This function is also called to turn off DMA when a timeout occurs
* during DMA operation. In both cases we need to reset the engine,
* so no actual eng_timeout handler is required.
*
* We assume bmdma_stop is always called if bmdma_start as called. If
* not then we may need to wrap qc_issue.
*/
static void sl82c105_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
ata_bmdma_stop(qc);
sl82c105_reset_engine(ap);
udelay(100);
/* This will redo the initial setup of the DMA device to matching
PIO timings */
sl82c105_set_piomode(ap, qc->dev);
}
/**
* sl82c105_qc_defer - implement serialization
* @qc: command
*
* We must issue one command per host not per channel because
* of the reset bug.
*
* Q: is the scsi host lock sufficient ?
*/
static int sl82c105_qc_defer(struct ata_queued_cmd *qc)
{
struct ata_host *host = qc->ap->host;
struct ata_port *alt = host->ports[1 ^ qc->ap->port_no];
int rc;
/* First apply the usual rules */
rc = ata_std_qc_defer(qc);
if (rc != 0)
return rc;
/* Now apply serialization rules. Only allow a command if the
other channel state machine is idle */
if (alt && alt->qc_active)
return ATA_DEFER_PORT;
return 0;
}
static bool sl82c105_sff_irq_check(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u32 val, mask = ap->port_no ? CTRL_IDE_IRQB : CTRL_IDE_IRQA;
pci_read_config_dword(pdev, 0x40, &val);
return val & mask;
}
static struct scsi_host_template sl82c105_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations sl82c105_port_ops = {
.inherits = &ata_bmdma_port_ops,
.qc_defer = sl82c105_qc_defer,
.bmdma_start = sl82c105_bmdma_start,
.bmdma_stop = sl82c105_bmdma_stop,
.cable_detect = ata_cable_40wire,
.set_piomode = sl82c105_set_piomode,
.prereset = sl82c105_pre_reset,
.sff_irq_check = sl82c105_sff_irq_check,
};
/**
* sl82c105_bridge_revision - find bridge version
* @pdev: PCI device for the ATA function
*
* Locates the PCI bridge associated with the ATA function and
* providing it is a Winbond 553 reports the revision. If it cannot
* find a revision or the right device it returns -1
*/
static int sl82c105_bridge_revision(struct pci_dev *pdev)
{
struct pci_dev *bridge;
/*
* The bridge should be part of the same device, but function 0.
*/
bridge = pci_get_slot(pdev->bus,
PCI_DEVFN(PCI_SLOT(pdev->devfn), 0));
if (!bridge)
return -1;
/*
* Make sure it is a Winbond 553 and is an ISA bridge.
*/
if (bridge->vendor != PCI_VENDOR_ID_WINBOND ||
bridge->device != PCI_DEVICE_ID_WINBOND_83C553 ||
bridge->class >> 8 != PCI_CLASS_BRIDGE_ISA) {
pci_dev_put(bridge);
return -1;
}
/*
* We need to find function 0's revision, not function 1
*/
pci_dev_put(bridge);
return bridge->revision;
}
static int sl82c105_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
static const struct ata_port_info info_dma = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.port_ops = &sl82c105_port_ops
};
static const struct ata_port_info info_early = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.port_ops = &sl82c105_port_ops
};
/* for now use only the first port */
const struct ata_port_info *ppi[] = { &info_early,
NULL };
u32 val;
int rev;
int rc;
rc = pcim_enable_device(dev);
if (rc)
return rc;
rev = sl82c105_bridge_revision(dev);
if (rev == -1)
dev_printk(KERN_WARNING, &dev->dev, "pata_sl82c105: Unable to find bridge, disabling DMA.\n");
else if (rev <= 5)
dev_printk(KERN_WARNING, &dev->dev, "pata_sl82c105: Early bridge revision, no DMA available.\n");
else
ppi[0] = &info_dma;
pci_read_config_dword(dev, 0x40, &val);
val |= CTRL_P0EN | CTRL_P0F16 | CTRL_P1F16;
pci_write_config_dword(dev, 0x40, val);
return ata_pci_bmdma_init_one(dev, ppi, &sl82c105_sht, NULL, 0);
}
static const struct pci_device_id sl82c105[] = {
{ PCI_VDEVICE(WINBOND, PCI_DEVICE_ID_WINBOND_82C105), },
{ },
};
static struct pci_driver sl82c105_pci_driver = {
.name = DRV_NAME,
.id_table = sl82c105,
.probe = sl82c105_init_one,
.remove = ata_pci_remove_one
};
static int __init sl82c105_init(void)
{
return pci_register_driver(&sl82c105_pci_driver);
}
static void __exit sl82c105_exit(void)
{
pci_unregister_driver(&sl82c105_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for Sl82c105");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, sl82c105);
MODULE_VERSION(DRV_VERSION);
module_init(sl82c105_init);
module_exit(sl82c105_exit);
| gpl-2.0 |
virajkanwade/rk3188_android_kernel | drivers/net/ne2k-pci.c | 3974 | 21171 | /* ne2k-pci.c: A NE2000 clone on PCI bus driver for Linux. */
/*
A Linux device driver for PCI NE2000 clones.
Authors and other copyright holders:
1992-2000 by Donald Becker, NE2000 core and various modifications.
1995-1998 by Paul Gortmaker, core modifications and PCI support.
Copyright 1993 assigned to the United States Government as represented
by the Director, National Security Agency.
This software may be used and distributed according to the terms of
the GNU General Public License (GPL), incorporated herein by reference.
Drivers based on or derived from this code fall under the GPL and must
retain the authorship, copyright and license notice. This file is not
a complete program and may only be used when the entire operating
system is licensed under the GPL.
The author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
Issues remaining:
People are making PCI ne2000 clones! Oh the horror, the horror...
Limited full-duplex support.
*/
#define DRV_NAME "ne2k-pci"
#define DRV_VERSION "1.03"
#define DRV_RELDATE "9/22/2003"
/* The user-configurable values.
These may be modified when a driver module is loaded.*/
static int debug = 1; /* 1 normal messages, 0 quiet .. 7 verbose. */
#define MAX_UNITS 8 /* More are supported, limit only on options */
/* Used to pass the full-duplex flag, etc. */
static int full_duplex[MAX_UNITS];
static int options[MAX_UNITS];
/* Force a non std. amount of memory. Units are 256 byte pages. */
/* #define PACKETBUF_MEMSIZE 0x40 */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/ethtool.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include "8390.h"
/* These identify the driver base version and may not be removed. */
static const char version[] __devinitconst =
KERN_INFO DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE
" D. Becker/P. Gortmaker\n";
#if defined(__powerpc__)
#define inl_le(addr) le32_to_cpu(inl(addr))
#define inw_le(addr) le16_to_cpu(inw(addr))
#endif
#define PFX DRV_NAME ": "
MODULE_AUTHOR("Donald Becker / Paul Gortmaker");
MODULE_DESCRIPTION("PCI NE2000 clone driver");
MODULE_LICENSE("GPL");
module_param(debug, int, 0);
module_param_array(options, int, NULL, 0);
module_param_array(full_duplex, int, NULL, 0);
MODULE_PARM_DESC(debug, "debug level (1-2)");
MODULE_PARM_DESC(options, "Bit 5: full duplex");
MODULE_PARM_DESC(full_duplex, "full duplex setting(s) (1)");
/* Some defines that people can play with if so inclined. */
/* Use 32 bit data-movement operations instead of 16 bit. */
#define USE_LONGIO
/* Do we implement the read before write bugfix ? */
/* #define NE_RW_BUGFIX */
/* Flags. We rename an existing ei_status field to store flags! */
/* Thus only the low 8 bits are usable for non-init-time flags. */
#define ne2k_flags reg0
enum {
ONLY_16BIT_IO=8, ONLY_32BIT_IO=4, /* Chip can do only 16/32-bit xfers. */
FORCE_FDX=0x20, /* User override. */
REALTEK_FDX=0x40, HOLTEK_FDX=0x80,
STOP_PG_0x60=0x100,
};
enum ne2k_pci_chipsets {
CH_RealTek_RTL_8029 = 0,
CH_Winbond_89C940,
CH_Compex_RL2000,
CH_KTI_ET32P2,
CH_NetVin_NV5000SC,
CH_Via_86C926,
CH_SureCom_NE34,
CH_Winbond_W89C940F,
CH_Holtek_HT80232,
CH_Holtek_HT80229,
CH_Winbond_89C940_8c4a,
};
static struct {
char *name;
int flags;
} pci_clone_list[] __devinitdata = {
{"RealTek RTL-8029", REALTEK_FDX},
{"Winbond 89C940", 0},
{"Compex RL2000", 0},
{"KTI ET32P2", 0},
{"NetVin NV5000SC", 0},
{"Via 86C926", ONLY_16BIT_IO},
{"SureCom NE34", 0},
{"Winbond W89C940F", 0},
{"Holtek HT80232", ONLY_16BIT_IO | HOLTEK_FDX},
{"Holtek HT80229", ONLY_32BIT_IO | HOLTEK_FDX | STOP_PG_0x60 },
{"Winbond W89C940(misprogrammed)", 0},
{NULL,}
};
static DEFINE_PCI_DEVICE_TABLE(ne2k_pci_tbl) = {
{ 0x10ec, 0x8029, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_RealTek_RTL_8029 },
{ 0x1050, 0x0940, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Winbond_89C940 },
{ 0x11f6, 0x1401, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Compex_RL2000 },
{ 0x8e2e, 0x3000, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_KTI_ET32P2 },
{ 0x4a14, 0x5000, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_NetVin_NV5000SC },
{ 0x1106, 0x0926, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Via_86C926 },
{ 0x10bd, 0x0e34, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_SureCom_NE34 },
{ 0x1050, 0x5a5a, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Winbond_W89C940F },
{ 0x12c3, 0x0058, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Holtek_HT80232 },
{ 0x12c3, 0x5598, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Holtek_HT80229 },
{ 0x8c4a, 0x1980, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Winbond_89C940_8c4a },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, ne2k_pci_tbl);
/* ---- No user-serviceable parts below ---- */
#define NE_BASE (dev->base_addr)
#define NE_CMD 0x00
#define NE_DATAPORT 0x10 /* NatSemi-defined port window offset. */
#define NE_RESET 0x1f /* Issue a read to reset, a write to clear. */
#define NE_IO_EXTENT 0x20
#define NESM_START_PG 0x40 /* First page of TX buffer */
#define NESM_STOP_PG 0x80 /* Last page +1 of RX ring */
static int ne2k_pci_open(struct net_device *dev);
static int ne2k_pci_close(struct net_device *dev);
static void ne2k_pci_reset_8390(struct net_device *dev);
static void ne2k_pci_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page);
static void ne2k_pci_block_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset);
static void ne2k_pci_block_output(struct net_device *dev, const int count,
const unsigned char *buf, const int start_page);
static const struct ethtool_ops ne2k_pci_ethtool_ops;
/* There is no room in the standard 8390 structure for extra info we need,
so we build a meta/outer-wrapper structure.. */
struct ne2k_pci_card {
struct net_device *dev;
struct pci_dev *pci_dev;
};
/*
NEx000-clone boards have a Station Address (SA) PROM (SAPROM) in the packet
buffer memory space. By-the-spec NE2000 clones have 0x57,0x57 in bytes
0x0e,0x0f of the SAPROM, while other supposed NE2000 clones must be
detected by their SA prefix.
Reading the SAPROM from a word-wide card with the 8390 set in byte-wide
mode results in doubled values, which can be detected and compensated for.
The probe is also responsible for initializing the card and filling
in the 'dev' and 'ei_status' structures.
*/
static const struct net_device_ops ne2k_netdev_ops = {
.ndo_open = ne2k_pci_open,
.ndo_stop = ne2k_pci_close,
.ndo_start_xmit = ei_start_xmit,
.ndo_tx_timeout = ei_tx_timeout,
.ndo_get_stats = ei_get_stats,
.ndo_set_multicast_list = ei_set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = ei_poll,
#endif
};
static int __devinit ne2k_pci_init_one (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev;
int i;
unsigned char SA_prom[32];
int start_page, stop_page;
int irq, reg0, chip_idx = ent->driver_data;
static unsigned int fnd_cnt;
long ioaddr;
int flags = pci_clone_list[chip_idx].flags;
/* when built into the kernel, we only print version if device is found */
#ifndef MODULE
static int printed_version;
if (!printed_version++)
printk(version);
#endif
fnd_cnt++;
i = pci_enable_device (pdev);
if (i)
return i;
ioaddr = pci_resource_start (pdev, 0);
irq = pdev->irq;
if (!ioaddr || ((pci_resource_flags (pdev, 0) & IORESOURCE_IO) == 0)) {
dev_err(&pdev->dev, "no I/O resource at PCI BAR #0\n");
return -ENODEV;
}
if (request_region (ioaddr, NE_IO_EXTENT, DRV_NAME) == NULL) {
dev_err(&pdev->dev, "I/O resource 0x%x @ 0x%lx busy\n",
NE_IO_EXTENT, ioaddr);
return -EBUSY;
}
reg0 = inb(ioaddr);
if (reg0 == 0xFF)
goto err_out_free_res;
/* Do a preliminary verification that we have a 8390. */
{
int regd;
outb(E8390_NODMA+E8390_PAGE1+E8390_STOP, ioaddr + E8390_CMD);
regd = inb(ioaddr + 0x0d);
outb(0xff, ioaddr + 0x0d);
outb(E8390_NODMA+E8390_PAGE0, ioaddr + E8390_CMD);
inb(ioaddr + EN0_COUNTER0); /* Clear the counter by reading. */
if (inb(ioaddr + EN0_COUNTER0) != 0) {
outb(reg0, ioaddr);
outb(regd, ioaddr + 0x0d); /* Restore the old values. */
goto err_out_free_res;
}
}
/* Allocate net_device, dev->priv; fill in 8390 specific dev fields. */
dev = alloc_ei_netdev();
if (!dev) {
dev_err(&pdev->dev, "cannot allocate ethernet device\n");
goto err_out_free_res;
}
dev->netdev_ops = &ne2k_netdev_ops;
SET_NETDEV_DEV(dev, &pdev->dev);
/* Reset card. Who knows what dain-bramaged state it was left in. */
{
unsigned long reset_start_time = jiffies;
outb(inb(ioaddr + NE_RESET), ioaddr + NE_RESET);
/* This looks like a horrible timing loop, but it should never take
more than a few cycles.
*/
while ((inb(ioaddr + EN0_ISR) & ENISR_RESET) == 0)
/* Limit wait: '2' avoids jiffy roll-over. */
if (jiffies - reset_start_time > 2) {
dev_err(&pdev->dev,
"Card failure (no reset ack).\n");
goto err_out_free_netdev;
}
outb(0xff, ioaddr + EN0_ISR); /* Ack all intr. */
}
/* Read the 16 bytes of station address PROM.
We must first initialize registers, similar to NS8390_init(eifdev, 0).
We can't reliably read the SAPROM address without this.
(I learned the hard way!). */
{
struct {unsigned char value, offset; } program_seq[] = {
{E8390_NODMA+E8390_PAGE0+E8390_STOP, E8390_CMD}, /* Select page 0*/
{0x49, EN0_DCFG}, /* Set word-wide access. */
{0x00, EN0_RCNTLO}, /* Clear the count regs. */
{0x00, EN0_RCNTHI},
{0x00, EN0_IMR}, /* Mask completion irq. */
{0xFF, EN0_ISR},
{E8390_RXOFF, EN0_RXCR}, /* 0x20 Set to monitor */
{E8390_TXOFF, EN0_TXCR}, /* 0x02 and loopback mode. */
{32, EN0_RCNTLO},
{0x00, EN0_RCNTHI},
{0x00, EN0_RSARLO}, /* DMA starting at 0x0000. */
{0x00, EN0_RSARHI},
{E8390_RREAD+E8390_START, E8390_CMD},
};
for (i = 0; i < ARRAY_SIZE(program_seq); i++)
outb(program_seq[i].value, ioaddr + program_seq[i].offset);
}
/* Note: all PCI cards have at least 16 bit access, so we don't have
to check for 8 bit cards. Most cards permit 32 bit access. */
if (flags & ONLY_32BIT_IO) {
for (i = 0; i < 4 ; i++)
((u32 *)SA_prom)[i] = le32_to_cpu(inl(ioaddr + NE_DATAPORT));
} else
for(i = 0; i < 32 /*sizeof(SA_prom)*/; i++)
SA_prom[i] = inb(ioaddr + NE_DATAPORT);
/* We always set the 8390 registers for word mode. */
outb(0x49, ioaddr + EN0_DCFG);
start_page = NESM_START_PG;
stop_page = flags & STOP_PG_0x60 ? 0x60 : NESM_STOP_PG;
/* Set up the rest of the parameters. */
dev->irq = irq;
dev->base_addr = ioaddr;
pci_set_drvdata(pdev, dev);
ei_status.name = pci_clone_list[chip_idx].name;
ei_status.tx_start_page = start_page;
ei_status.stop_page = stop_page;
ei_status.word16 = 1;
ei_status.ne2k_flags = flags;
if (fnd_cnt < MAX_UNITS) {
if (full_duplex[fnd_cnt] > 0 || (options[fnd_cnt] & FORCE_FDX))
ei_status.ne2k_flags |= FORCE_FDX;
}
ei_status.rx_start_page = start_page + TX_PAGES;
#ifdef PACKETBUF_MEMSIZE
/* Allow the packet buffer size to be overridden by know-it-alls. */
ei_status.stop_page = ei_status.tx_start_page + PACKETBUF_MEMSIZE;
#endif
ei_status.reset_8390 = &ne2k_pci_reset_8390;
ei_status.block_input = &ne2k_pci_block_input;
ei_status.block_output = &ne2k_pci_block_output;
ei_status.get_8390_hdr = &ne2k_pci_get_8390_hdr;
ei_status.priv = (unsigned long) pdev;
dev->ethtool_ops = &ne2k_pci_ethtool_ops;
NS8390_init(dev, 0);
memcpy(dev->dev_addr, SA_prom, dev->addr_len);
memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
i = register_netdev(dev);
if (i)
goto err_out_free_netdev;
printk("%s: %s found at %#lx, IRQ %d, %pM.\n",
dev->name, pci_clone_list[chip_idx].name, ioaddr, dev->irq,
dev->dev_addr);
return 0;
err_out_free_netdev:
free_netdev (dev);
err_out_free_res:
release_region (ioaddr, NE_IO_EXTENT);
pci_set_drvdata (pdev, NULL);
return -ENODEV;
}
/*
* Magic incantation sequence for full duplex on the supported cards.
*/
static inline int set_realtek_fdx(struct net_device *dev)
{
long ioaddr = dev->base_addr;
outb(0xC0 + E8390_NODMA, ioaddr + NE_CMD); /* Page 3 */
outb(0xC0, ioaddr + 0x01); /* Enable writes to CONFIG3 */
outb(0x40, ioaddr + 0x06); /* Enable full duplex */
outb(0x00, ioaddr + 0x01); /* Disable writes to CONFIG3 */
outb(E8390_PAGE0 + E8390_NODMA, ioaddr + NE_CMD); /* Page 0 */
return 0;
}
static inline int set_holtek_fdx(struct net_device *dev)
{
long ioaddr = dev->base_addr;
outb(inb(ioaddr + 0x20) | 0x80, ioaddr + 0x20);
return 0;
}
static int ne2k_pci_set_fdx(struct net_device *dev)
{
if (ei_status.ne2k_flags & REALTEK_FDX)
return set_realtek_fdx(dev);
else if (ei_status.ne2k_flags & HOLTEK_FDX)
return set_holtek_fdx(dev);
return -EOPNOTSUPP;
}
static int ne2k_pci_open(struct net_device *dev)
{
int ret = request_irq(dev->irq, ei_interrupt, IRQF_SHARED, dev->name, dev);
if (ret)
return ret;
if (ei_status.ne2k_flags & FORCE_FDX)
ne2k_pci_set_fdx(dev);
ei_open(dev);
return 0;
}
static int ne2k_pci_close(struct net_device *dev)
{
ei_close(dev);
free_irq(dev->irq, dev);
return 0;
}
/* Hard reset the card. This used to pause for the same period that a
8390 reset command required, but that shouldn't be necessary. */
static void ne2k_pci_reset_8390(struct net_device *dev)
{
unsigned long reset_start_time = jiffies;
if (debug > 1) printk("%s: Resetting the 8390 t=%ld...",
dev->name, jiffies);
outb(inb(NE_BASE + NE_RESET), NE_BASE + NE_RESET);
ei_status.txing = 0;
ei_status.dmaing = 0;
/* This check _should_not_ be necessary, omit eventually. */
while ((inb(NE_BASE+EN0_ISR) & ENISR_RESET) == 0)
if (jiffies - reset_start_time > 2) {
printk("%s: ne2k_pci_reset_8390() did not complete.\n", dev->name);
break;
}
outb(ENISR_RESET, NE_BASE + EN0_ISR); /* Ack intr. */
}
/* Grab the 8390 specific header. Similar to the block_input routine, but
we don't need to be concerned with ring wrap as the header will be at
the start of a page, so we optimize accordingly. */
static void ne2k_pci_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page)
{
long nic_base = dev->base_addr;
/* This *shouldn't* happen. If it does, it's the last thing you'll see */
if (ei_status.dmaing) {
printk("%s: DMAing conflict in ne2k_pci_get_8390_hdr "
"[DMAstat:%d][irqlock:%d].\n",
dev->name, ei_status.dmaing, ei_status.irqlock);
return;
}
ei_status.dmaing |= 0x01;
outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD);
outb(sizeof(struct e8390_pkt_hdr), nic_base + EN0_RCNTLO);
outb(0, nic_base + EN0_RCNTHI);
outb(0, nic_base + EN0_RSARLO); /* On page boundary */
outb(ring_page, nic_base + EN0_RSARHI);
outb(E8390_RREAD+E8390_START, nic_base + NE_CMD);
if (ei_status.ne2k_flags & ONLY_16BIT_IO) {
insw(NE_BASE + NE_DATAPORT, hdr, sizeof(struct e8390_pkt_hdr)>>1);
} else {
*(u32*)hdr = le32_to_cpu(inl(NE_BASE + NE_DATAPORT));
le16_to_cpus(&hdr->count);
}
outb(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
ei_status.dmaing &= ~0x01;
}
/* Block input and output, similar to the Crynwr packet driver. If you
are porting to a new ethercard, look at the packet driver source for hints.
The NEx000 doesn't share the on-board packet memory -- you have to put
the packet out through the "remote DMA" dataport using outb. */
static void ne2k_pci_block_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset)
{
long nic_base = dev->base_addr;
char *buf = skb->data;
/* This *shouldn't* happen. If it does, it's the last thing you'll see */
if (ei_status.dmaing) {
printk("%s: DMAing conflict in ne2k_pci_block_input "
"[DMAstat:%d][irqlock:%d].\n",
dev->name, ei_status.dmaing, ei_status.irqlock);
return;
}
ei_status.dmaing |= 0x01;
if (ei_status.ne2k_flags & ONLY_32BIT_IO)
count = (count + 3) & 0xFFFC;
outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD);
outb(count & 0xff, nic_base + EN0_RCNTLO);
outb(count >> 8, nic_base + EN0_RCNTHI);
outb(ring_offset & 0xff, nic_base + EN0_RSARLO);
outb(ring_offset >> 8, nic_base + EN0_RSARHI);
outb(E8390_RREAD+E8390_START, nic_base + NE_CMD);
if (ei_status.ne2k_flags & ONLY_16BIT_IO) {
insw(NE_BASE + NE_DATAPORT,buf,count>>1);
if (count & 0x01) {
buf[count-1] = inb(NE_BASE + NE_DATAPORT);
}
} else {
insl(NE_BASE + NE_DATAPORT, buf, count>>2);
if (count & 3) {
buf += count & ~3;
if (count & 2) {
__le16 *b = (__le16 *)buf;
*b++ = cpu_to_le16(inw(NE_BASE + NE_DATAPORT));
buf = (char *)b;
}
if (count & 1)
*buf = inb(NE_BASE + NE_DATAPORT);
}
}
outb(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
ei_status.dmaing &= ~0x01;
}
static void ne2k_pci_block_output(struct net_device *dev, int count,
const unsigned char *buf, const int start_page)
{
long nic_base = NE_BASE;
unsigned long dma_start;
/* On little-endian it's always safe to round the count up for
word writes. */
if (ei_status.ne2k_flags & ONLY_32BIT_IO)
count = (count + 3) & 0xFFFC;
else
if (count & 0x01)
count++;
/* This *shouldn't* happen. If it does, it's the last thing you'll see */
if (ei_status.dmaing) {
printk("%s: DMAing conflict in ne2k_pci_block_output."
"[DMAstat:%d][irqlock:%d]\n",
dev->name, ei_status.dmaing, ei_status.irqlock);
return;
}
ei_status.dmaing |= 0x01;
/* We should already be in page 0, but to be safe... */
outb(E8390_PAGE0+E8390_START+E8390_NODMA, nic_base + NE_CMD);
#ifdef NE8390_RW_BUGFIX
/* Handle the read-before-write bug the same way as the
Crynwr packet driver -- the NatSemi method doesn't work.
Actually this doesn't always work either, but if you have
problems with your NEx000 this is better than nothing! */
outb(0x42, nic_base + EN0_RCNTLO);
outb(0x00, nic_base + EN0_RCNTHI);
outb(0x42, nic_base + EN0_RSARLO);
outb(0x00, nic_base + EN0_RSARHI);
outb(E8390_RREAD+E8390_START, nic_base + NE_CMD);
#endif
outb(ENISR_RDC, nic_base + EN0_ISR);
/* Now the normal output. */
outb(count & 0xff, nic_base + EN0_RCNTLO);
outb(count >> 8, nic_base + EN0_RCNTHI);
outb(0x00, nic_base + EN0_RSARLO);
outb(start_page, nic_base + EN0_RSARHI);
outb(E8390_RWRITE+E8390_START, nic_base + NE_CMD);
if (ei_status.ne2k_flags & ONLY_16BIT_IO) {
outsw(NE_BASE + NE_DATAPORT, buf, count>>1);
} else {
outsl(NE_BASE + NE_DATAPORT, buf, count>>2);
if (count & 3) {
buf += count & ~3;
if (count & 2) {
__le16 *b = (__le16 *)buf;
outw(le16_to_cpu(*b++), NE_BASE + NE_DATAPORT);
buf = (char *)b;
}
}
}
dma_start = jiffies;
while ((inb(nic_base + EN0_ISR) & ENISR_RDC) == 0)
if (jiffies - dma_start > 2) { /* Avoid clock roll-over. */
printk(KERN_WARNING "%s: timeout waiting for Tx RDC.\n", dev->name);
ne2k_pci_reset_8390(dev);
NS8390_init(dev,1);
break;
}
outb(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
ei_status.dmaing &= ~0x01;
}
static void ne2k_pci_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct ei_device *ei = netdev_priv(dev);
struct pci_dev *pci_dev = (struct pci_dev *) ei->priv;
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, pci_name(pci_dev));
}
static const struct ethtool_ops ne2k_pci_ethtool_ops = {
.get_drvinfo = ne2k_pci_get_drvinfo,
};
static void __devexit ne2k_pci_remove_one (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
BUG_ON(!dev);
unregister_netdev(dev);
release_region(dev->base_addr, NE_IO_EXTENT);
free_netdev(dev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
#ifdef CONFIG_PM
static int ne2k_pci_suspend (struct pci_dev *pdev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata (pdev);
netif_device_detach(dev);
pci_save_state(pdev);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int ne2k_pci_resume (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata (pdev);
int rc;
pci_set_power_state(pdev, 0);
pci_restore_state(pdev);
rc = pci_enable_device(pdev);
if (rc)
return rc;
NS8390_init(dev, 1);
netif_device_attach(dev);
return 0;
}
#endif /* CONFIG_PM */
static struct pci_driver ne2k_driver = {
.name = DRV_NAME,
.probe = ne2k_pci_init_one,
.remove = __devexit_p(ne2k_pci_remove_one),
.id_table = ne2k_pci_tbl,
#ifdef CONFIG_PM
.suspend = ne2k_pci_suspend,
.resume = ne2k_pci_resume,
#endif /* CONFIG_PM */
};
static int __init ne2k_pci_init(void)
{
/* when a module, this is printed whether or not devices are found in probe */
#ifdef MODULE
printk(version);
#endif
return pci_register_driver(&ne2k_driver);
}
static void __exit ne2k_pci_cleanup(void)
{
pci_unregister_driver (&ne2k_driver);
}
module_init(ne2k_pci_init);
module_exit(ne2k_pci_cleanup);
| gpl-2.0 |
zhaochengw/ef40s_kernel-4.2 | arch/arm/mm/copypage-v4wb.c | 4230 | 2922 | /*
* linux/arch/arm/mm/copypage-v4wb.c
*
* Copyright (C) 1995-1999 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/init.h>
#include <linux/highmem.h>
/*
* ARMv4 optimised copy_user_highpage
*
* We flush the destination cache lines just before we write the data into the
* corresponding address. Since the Dcache is read-allocate, this removes the
* Dcache aliasing issue. The writes will be forwarded to the write buffer,
* and merged as appropriate.
*
* Note: We rely on all ARMv4 processors implementing the "invalidate D line"
* instruction. If your processor does not supply this, you have to write your
* own copy_user_highpage that does the right thing.
*/
static void __naked
v4wb_copy_user_page(void *kto, const void *kfrom)
{
asm("\
stmfd sp!, {r4, lr} @ 2\n\
mov r2, %2 @ 1\n\
ldmia r1!, {r3, r4, ip, lr} @ 4\n\
1: mcr p15, 0, r0, c7, c6, 1 @ 1 invalidate D line\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmia r1!, {r3, r4, ip, lr} @ 4+1\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmia r1!, {r3, r4, ip, lr} @ 4\n\
mcr p15, 0, r0, c7, c6, 1 @ 1 invalidate D line\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmia r1!, {r3, r4, ip, lr} @ 4\n\
subs r2, r2, #1 @ 1\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmneia r1!, {r3, r4, ip, lr} @ 4\n\
bne 1b @ 1\n\
mcr p15, 0, r1, c7, c10, 4 @ 1 drain WB\n\
ldmfd sp!, {r4, pc} @ 3"
:
: "r" (kto), "r" (kfrom), "I" (PAGE_SIZE / 64));
}
void v4wb_copy_user_highpage(struct page *to, struct page *from,
unsigned long vaddr, struct vm_area_struct *vma)
{
void *kto, *kfrom;
kto = kmap_atomic(to, KM_USER0);
kfrom = kmap_atomic(from, KM_USER1);
flush_cache_page(vma, vaddr, page_to_pfn(from));
v4wb_copy_user_page(kto, kfrom);
kunmap_atomic(kfrom, KM_USER1);
kunmap_atomic(kto, KM_USER0);
}
/*
* ARMv4 optimised clear_user_page
*
* Same story as above.
*/
void v4wb_clear_user_highpage(struct page *page, unsigned long vaddr)
{
void *ptr, *kaddr = kmap_atomic(page, KM_USER0);
asm volatile("\
mov r1, %2 @ 1\n\
mov r2, #0 @ 1\n\
mov r3, #0 @ 1\n\
mov ip, #0 @ 1\n\
mov lr, #0 @ 1\n\
1: mcr p15, 0, %0, c7, c6, 1 @ 1 invalidate D line\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
mcr p15, 0, %0, c7, c6, 1 @ 1 invalidate D line\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
subs r1, r1, #1 @ 1\n\
bne 1b @ 1\n\
mcr p15, 0, r1, c7, c10, 4 @ 1 drain WB"
: "=r" (ptr)
: "0" (kaddr), "I" (PAGE_SIZE / 64)
: "r1", "r2", "r3", "ip", "lr");
kunmap_atomic(kaddr, KM_USER0);
}
struct cpu_user_fns v4wb_user_fns __initdata = {
.cpu_clear_user_highpage = v4wb_clear_user_highpage,
.cpu_copy_user_highpage = v4wb_copy_user_highpage,
};
| gpl-2.0 |
x942/GuardianKernel-Tuna | arch/arm/mm/copypage-v4wb.c | 4230 | 2922 | /*
* linux/arch/arm/mm/copypage-v4wb.c
*
* Copyright (C) 1995-1999 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/init.h>
#include <linux/highmem.h>
/*
* ARMv4 optimised copy_user_highpage
*
* We flush the destination cache lines just before we write the data into the
* corresponding address. Since the Dcache is read-allocate, this removes the
* Dcache aliasing issue. The writes will be forwarded to the write buffer,
* and merged as appropriate.
*
* Note: We rely on all ARMv4 processors implementing the "invalidate D line"
* instruction. If your processor does not supply this, you have to write your
* own copy_user_highpage that does the right thing.
*/
static void __naked
v4wb_copy_user_page(void *kto, const void *kfrom)
{
asm("\
stmfd sp!, {r4, lr} @ 2\n\
mov r2, %2 @ 1\n\
ldmia r1!, {r3, r4, ip, lr} @ 4\n\
1: mcr p15, 0, r0, c7, c6, 1 @ 1 invalidate D line\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmia r1!, {r3, r4, ip, lr} @ 4+1\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmia r1!, {r3, r4, ip, lr} @ 4\n\
mcr p15, 0, r0, c7, c6, 1 @ 1 invalidate D line\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmia r1!, {r3, r4, ip, lr} @ 4\n\
subs r2, r2, #1 @ 1\n\
stmia r0!, {r3, r4, ip, lr} @ 4\n\
ldmneia r1!, {r3, r4, ip, lr} @ 4\n\
bne 1b @ 1\n\
mcr p15, 0, r1, c7, c10, 4 @ 1 drain WB\n\
ldmfd sp!, {r4, pc} @ 3"
:
: "r" (kto), "r" (kfrom), "I" (PAGE_SIZE / 64));
}
void v4wb_copy_user_highpage(struct page *to, struct page *from,
unsigned long vaddr, struct vm_area_struct *vma)
{
void *kto, *kfrom;
kto = kmap_atomic(to, KM_USER0);
kfrom = kmap_atomic(from, KM_USER1);
flush_cache_page(vma, vaddr, page_to_pfn(from));
v4wb_copy_user_page(kto, kfrom);
kunmap_atomic(kfrom, KM_USER1);
kunmap_atomic(kto, KM_USER0);
}
/*
* ARMv4 optimised clear_user_page
*
* Same story as above.
*/
void v4wb_clear_user_highpage(struct page *page, unsigned long vaddr)
{
void *ptr, *kaddr = kmap_atomic(page, KM_USER0);
asm volatile("\
mov r1, %2 @ 1\n\
mov r2, #0 @ 1\n\
mov r3, #0 @ 1\n\
mov ip, #0 @ 1\n\
mov lr, #0 @ 1\n\
1: mcr p15, 0, %0, c7, c6, 1 @ 1 invalidate D line\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
mcr p15, 0, %0, c7, c6, 1 @ 1 invalidate D line\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
stmia %0!, {r2, r3, ip, lr} @ 4\n\
subs r1, r1, #1 @ 1\n\
bne 1b @ 1\n\
mcr p15, 0, r1, c7, c10, 4 @ 1 drain WB"
: "=r" (ptr)
: "0" (kaddr), "I" (PAGE_SIZE / 64)
: "r1", "r2", "r3", "ip", "lr");
kunmap_atomic(kaddr, KM_USER0);
}
struct cpu_user_fns v4wb_user_fns __initdata = {
.cpu_clear_user_highpage = v4wb_clear_user_highpage,
.cpu_copy_user_highpage = v4wb_copy_user_highpage,
};
| gpl-2.0 |
sssemil/linux-3.3.0-a31 | drivers/video/fbcmap.c | 6278 | 8660 | /*
* linux/drivers/video/fbcmap.c -- Colormap handling for frame buffer devices
*
* Created 15 Jun 1997 by Geert Uytterhoeven
*
* 2001 - Documented with DocBook
* - Brad Douglas <brad@neruo.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/string.h>
#include <linux/module.h>
#include <linux/fb.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
static u16 red2[] __read_mostly = {
0x0000, 0xaaaa
};
static u16 green2[] __read_mostly = {
0x0000, 0xaaaa
};
static u16 blue2[] __read_mostly = {
0x0000, 0xaaaa
};
static u16 red4[] __read_mostly = {
0x0000, 0xaaaa, 0x5555, 0xffff
};
static u16 green4[] __read_mostly = {
0x0000, 0xaaaa, 0x5555, 0xffff
};
static u16 blue4[] __read_mostly = {
0x0000, 0xaaaa, 0x5555, 0xffff
};
static u16 red8[] __read_mostly = {
0x0000, 0x0000, 0x0000, 0x0000, 0xaaaa, 0xaaaa, 0xaaaa, 0xaaaa
};
static u16 green8[] __read_mostly = {
0x0000, 0x0000, 0xaaaa, 0xaaaa, 0x0000, 0x0000, 0x5555, 0xaaaa
};
static u16 blue8[] __read_mostly = {
0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa
};
static u16 red16[] __read_mostly = {
0x0000, 0x0000, 0x0000, 0x0000, 0xaaaa, 0xaaaa, 0xaaaa, 0xaaaa,
0x5555, 0x5555, 0x5555, 0x5555, 0xffff, 0xffff, 0xffff, 0xffff
};
static u16 green16[] __read_mostly = {
0x0000, 0x0000, 0xaaaa, 0xaaaa, 0x0000, 0x0000, 0x5555, 0xaaaa,
0x5555, 0x5555, 0xffff, 0xffff, 0x5555, 0x5555, 0xffff, 0xffff
};
static u16 blue16[] __read_mostly = {
0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa,
0x5555, 0xffff, 0x5555, 0xffff, 0x5555, 0xffff, 0x5555, 0xffff
};
static const struct fb_cmap default_2_colors = {
.len=2, .red=red2, .green=green2, .blue=blue2
};
static const struct fb_cmap default_8_colors = {
.len=8, .red=red8, .green=green8, .blue=blue8
};
static const struct fb_cmap default_4_colors = {
.len=4, .red=red4, .green=green4, .blue=blue4
};
static const struct fb_cmap default_16_colors = {
.len=16, .red=red16, .green=green16, .blue=blue16
};
/**
* fb_alloc_cmap - allocate a colormap
* @cmap: frame buffer colormap structure
* @len: length of @cmap
* @transp: boolean, 1 if there is transparency, 0 otherwise
* @flags: flags for kmalloc memory allocation
*
* Allocates memory for a colormap @cmap. @len is the
* number of entries in the palette.
*
* Returns negative errno on error, or zero on success.
*
*/
int fb_alloc_cmap_gfp(struct fb_cmap *cmap, int len, int transp, gfp_t flags)
{
int size = len * sizeof(u16);
int ret = -ENOMEM;
if (cmap->len != len) {
fb_dealloc_cmap(cmap);
if (!len)
return 0;
cmap->red = kmalloc(size, flags);
if (!cmap->red)
goto fail;
cmap->green = kmalloc(size, flags);
if (!cmap->green)
goto fail;
cmap->blue = kmalloc(size, flags);
if (!cmap->blue)
goto fail;
if (transp) {
cmap->transp = kmalloc(size, flags);
if (!cmap->transp)
goto fail;
} else {
cmap->transp = NULL;
}
}
cmap->start = 0;
cmap->len = len;
ret = fb_copy_cmap(fb_default_cmap(len), cmap);
if (ret)
goto fail;
return 0;
fail:
fb_dealloc_cmap(cmap);
return ret;
}
int fb_alloc_cmap(struct fb_cmap *cmap, int len, int transp)
{
return fb_alloc_cmap_gfp(cmap, len, transp, GFP_ATOMIC);
}
/**
* fb_dealloc_cmap - deallocate a colormap
* @cmap: frame buffer colormap structure
*
* Deallocates a colormap that was previously allocated with
* fb_alloc_cmap().
*
*/
void fb_dealloc_cmap(struct fb_cmap *cmap)
{
kfree(cmap->red);
kfree(cmap->green);
kfree(cmap->blue);
kfree(cmap->transp);
cmap->red = cmap->green = cmap->blue = cmap->transp = NULL;
cmap->len = 0;
}
/**
* fb_copy_cmap - copy a colormap
* @from: frame buffer colormap structure
* @to: frame buffer colormap structure
*
* Copy contents of colormap from @from to @to.
*/
int fb_copy_cmap(const struct fb_cmap *from, struct fb_cmap *to)
{
int tooff = 0, fromoff = 0;
int size;
if (to->start > from->start)
fromoff = to->start - from->start;
else
tooff = from->start - to->start;
size = to->len - tooff;
if (size > (int) (from->len - fromoff))
size = from->len - fromoff;
if (size <= 0)
return -EINVAL;
size *= sizeof(u16);
memcpy(to->red+tooff, from->red+fromoff, size);
memcpy(to->green+tooff, from->green+fromoff, size);
memcpy(to->blue+tooff, from->blue+fromoff, size);
if (from->transp && to->transp)
memcpy(to->transp+tooff, from->transp+fromoff, size);
return 0;
}
int fb_cmap_to_user(const struct fb_cmap *from, struct fb_cmap_user *to)
{
int tooff = 0, fromoff = 0;
int size;
if (to->start > from->start)
fromoff = to->start - from->start;
else
tooff = from->start - to->start;
size = to->len - tooff;
if (size > (int) (from->len - fromoff))
size = from->len - fromoff;
if (size <= 0)
return -EINVAL;
size *= sizeof(u16);
if (copy_to_user(to->red+tooff, from->red+fromoff, size))
return -EFAULT;
if (copy_to_user(to->green+tooff, from->green+fromoff, size))
return -EFAULT;
if (copy_to_user(to->blue+tooff, from->blue+fromoff, size))
return -EFAULT;
if (from->transp && to->transp)
if (copy_to_user(to->transp+tooff, from->transp+fromoff, size))
return -EFAULT;
return 0;
}
/**
* fb_set_cmap - set the colormap
* @cmap: frame buffer colormap structure
* @info: frame buffer info structure
*
* Sets the colormap @cmap for a screen of device @info.
*
* Returns negative errno on error, or zero on success.
*
*/
int fb_set_cmap(struct fb_cmap *cmap, struct fb_info *info)
{
int i, start, rc = 0;
u16 *red, *green, *blue, *transp;
u_int hred, hgreen, hblue, htransp = 0xffff;
red = cmap->red;
green = cmap->green;
blue = cmap->blue;
transp = cmap->transp;
start = cmap->start;
if (start < 0 || (!info->fbops->fb_setcolreg &&
!info->fbops->fb_setcmap))
return -EINVAL;
if (info->fbops->fb_setcmap) {
rc = info->fbops->fb_setcmap(cmap, info);
} else {
for (i = 0; i < cmap->len; i++) {
hred = *red++;
hgreen = *green++;
hblue = *blue++;
if (transp)
htransp = *transp++;
if (info->fbops->fb_setcolreg(start++,
hred, hgreen, hblue,
htransp, info))
break;
}
}
if (rc == 0)
fb_copy_cmap(cmap, &info->cmap);
return rc;
}
int fb_set_user_cmap(struct fb_cmap_user *cmap, struct fb_info *info)
{
int rc, size = cmap->len * sizeof(u16);
struct fb_cmap umap;
if (size < 0 || size < cmap->len)
return -E2BIG;
memset(&umap, 0, sizeof(struct fb_cmap));
rc = fb_alloc_cmap_gfp(&umap, cmap->len, cmap->transp != NULL,
GFP_KERNEL);
if (rc)
return rc;
if (copy_from_user(umap.red, cmap->red, size) ||
copy_from_user(umap.green, cmap->green, size) ||
copy_from_user(umap.blue, cmap->blue, size) ||
(cmap->transp && copy_from_user(umap.transp, cmap->transp, size))) {
rc = -EFAULT;
goto out;
}
umap.start = cmap->start;
if (!lock_fb_info(info)) {
rc = -ENODEV;
goto out;
}
if (cmap->start < 0 || (!info->fbops->fb_setcolreg &&
!info->fbops->fb_setcmap)) {
rc = -EINVAL;
goto out1;
}
rc = fb_set_cmap(&umap, info);
out1:
unlock_fb_info(info);
out:
fb_dealloc_cmap(&umap);
return rc;
}
/**
* fb_default_cmap - get default colormap
* @len: size of palette for a depth
*
* Gets the default colormap for a specific screen depth. @len
* is the size of the palette for a particular screen depth.
*
* Returns pointer to a frame buffer colormap structure.
*
*/
const struct fb_cmap *fb_default_cmap(int len)
{
if (len <= 2)
return &default_2_colors;
if (len <= 4)
return &default_4_colors;
if (len <= 8)
return &default_8_colors;
return &default_16_colors;
}
/**
* fb_invert_cmaps - invert all defaults colormaps
*
* Invert all default colormaps.
*
*/
void fb_invert_cmaps(void)
{
u_int i;
for (i = 0; i < ARRAY_SIZE(red2); i++) {
red2[i] = ~red2[i];
green2[i] = ~green2[i];
blue2[i] = ~blue2[i];
}
for (i = 0; i < ARRAY_SIZE(red4); i++) {
red4[i] = ~red4[i];
green4[i] = ~green4[i];
blue4[i] = ~blue4[i];
}
for (i = 0; i < ARRAY_SIZE(red8); i++) {
red8[i] = ~red8[i];
green8[i] = ~green8[i];
blue8[i] = ~blue8[i];
}
for (i = 0; i < ARRAY_SIZE(red16); i++) {
red16[i] = ~red16[i];
green16[i] = ~green16[i];
blue16[i] = ~blue16[i];
}
}
/*
* Visible symbols for modules
*/
EXPORT_SYMBOL(fb_alloc_cmap);
EXPORT_SYMBOL(fb_dealloc_cmap);
EXPORT_SYMBOL(fb_copy_cmap);
EXPORT_SYMBOL(fb_set_cmap);
EXPORT_SYMBOL(fb_default_cmap);
EXPORT_SYMBOL(fb_invert_cmaps);
| gpl-2.0 |
DirtyUnicorns/android_kernel_oppo_msm8974 | net/netlabel/netlabel_addrlist.c | 7558 | 10564 | /*
* NetLabel Network Address Lists
*
* This file contains network address list functions used to manage ordered
* lists of network addresses for use by the NetLabel subsystem. The NetLabel
* system manages static and dynamic label mappings for network protocols such
* as CIPSO and RIPSO.
*
* Author: Paul Moore <paul@paul-moore.com>
*
*/
/*
* (c) Copyright Hewlett-Packard Development Company, L.P., 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/types.h>
#include <linux/rcupdate.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <linux/audit.h>
#include "netlabel_addrlist.h"
/*
* Address List Functions
*/
/**
* netlbl_af4list_search - Search for a matching IPv4 address entry
* @addr: IPv4 address
* @head: the list head
*
* Description:
* Searches the IPv4 address list given by @head. If a matching address entry
* is found it is returned, otherwise NULL is returned. The caller is
* responsible for calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af4list *netlbl_af4list_search(__be32 addr,
struct list_head *head)
{
struct netlbl_af4list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid && (addr & iter->mask) == iter->addr)
return iter;
return NULL;
}
/**
* netlbl_af4list_search_exact - Search for an exact IPv4 address entry
* @addr: IPv4 address
* @mask: IPv4 address mask
* @head: the list head
*
* Description:
* Searches the IPv4 address list given by @head. If an exact match if found
* it is returned, otherwise NULL is returned. The caller is responsible for
* calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af4list *netlbl_af4list_search_exact(__be32 addr,
__be32 mask,
struct list_head *head)
{
struct netlbl_af4list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid && iter->addr == addr && iter->mask == mask)
return iter;
return NULL;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_search - Search for a matching IPv6 address entry
* @addr: IPv6 address
* @head: the list head
*
* Description:
* Searches the IPv6 address list given by @head. If a matching address entry
* is found it is returned, otherwise NULL is returned. The caller is
* responsible for calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af6list *netlbl_af6list_search(const struct in6_addr *addr,
struct list_head *head)
{
struct netlbl_af6list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_masked_addr_cmp(&iter->addr, &iter->mask, addr) == 0)
return iter;
return NULL;
}
/**
* netlbl_af6list_search_exact - Search for an exact IPv6 address entry
* @addr: IPv6 address
* @mask: IPv6 address mask
* @head: the list head
*
* Description:
* Searches the IPv6 address list given by @head. If an exact match if found
* it is returned, otherwise NULL is returned. The caller is responsible for
* calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af6list *netlbl_af6list_search_exact(const struct in6_addr *addr,
const struct in6_addr *mask,
struct list_head *head)
{
struct netlbl_af6list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_addr_equal(&iter->addr, addr) &&
ipv6_addr_equal(&iter->mask, mask))
return iter;
return NULL;
}
#endif /* IPv6 */
/**
* netlbl_af4list_add - Add a new IPv4 address entry to a list
* @entry: address entry
* @head: the list head
*
* Description:
* Add a new address entry to the list pointed to by @head. On success zero is
* returned, otherwise a negative value is returned. The caller is responsible
* for calling the necessary locking functions.
*
*/
int netlbl_af4list_add(struct netlbl_af4list *entry, struct list_head *head)
{
struct netlbl_af4list *iter;
iter = netlbl_af4list_search(entry->addr, head);
if (iter != NULL &&
iter->addr == entry->addr && iter->mask == entry->mask)
return -EEXIST;
/* in order to speed up address searches through the list (the common
* case) we need to keep the list in order based on the size of the
* address mask such that the entry with the widest mask (smallest
* numerical value) appears first in the list */
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ntohl(entry->mask) > ntohl(iter->mask)) {
__list_add_rcu(&entry->list,
iter->list.prev,
&iter->list);
return 0;
}
list_add_tail_rcu(&entry->list, head);
return 0;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_add - Add a new IPv6 address entry to a list
* @entry: address entry
* @head: the list head
*
* Description:
* Add a new address entry to the list pointed to by @head. On success zero is
* returned, otherwise a negative value is returned. The caller is responsible
* for calling the necessary locking functions.
*
*/
int netlbl_af6list_add(struct netlbl_af6list *entry, struct list_head *head)
{
struct netlbl_af6list *iter;
iter = netlbl_af6list_search(&entry->addr, head);
if (iter != NULL &&
ipv6_addr_equal(&iter->addr, &entry->addr) &&
ipv6_addr_equal(&iter->mask, &entry->mask))
return -EEXIST;
/* in order to speed up address searches through the list (the common
* case) we need to keep the list in order based on the size of the
* address mask such that the entry with the widest mask (smallest
* numerical value) appears first in the list */
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_addr_cmp(&entry->mask, &iter->mask) > 0) {
__list_add_rcu(&entry->list,
iter->list.prev,
&iter->list);
return 0;
}
list_add_tail_rcu(&entry->list, head);
return 0;
}
#endif /* IPv6 */
/**
* netlbl_af4list_remove_entry - Remove an IPv4 address entry
* @entry: address entry
*
* Description:
* Remove the specified IP address entry. The caller is responsible for
* calling the necessary locking functions.
*
*/
void netlbl_af4list_remove_entry(struct netlbl_af4list *entry)
{
entry->valid = 0;
list_del_rcu(&entry->list);
}
/**
* netlbl_af4list_remove - Remove an IPv4 address entry
* @addr: IP address
* @mask: IP address mask
* @head: the list head
*
* Description:
* Remove an IP address entry from the list pointed to by @head. Returns the
* entry on success, NULL on failure. The caller is responsible for calling
* the necessary locking functions.
*
*/
struct netlbl_af4list *netlbl_af4list_remove(__be32 addr, __be32 mask,
struct list_head *head)
{
struct netlbl_af4list *entry;
entry = netlbl_af4list_search_exact(addr, mask, head);
if (entry == NULL)
return NULL;
netlbl_af4list_remove_entry(entry);
return entry;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_remove_entry - Remove an IPv6 address entry
* @entry: address entry
*
* Description:
* Remove the specified IP address entry. The caller is responsible for
* calling the necessary locking functions.
*
*/
void netlbl_af6list_remove_entry(struct netlbl_af6list *entry)
{
entry->valid = 0;
list_del_rcu(&entry->list);
}
/**
* netlbl_af6list_remove - Remove an IPv6 address entry
* @addr: IP address
* @mask: IP address mask
* @head: the list head
*
* Description:
* Remove an IP address entry from the list pointed to by @head. Returns the
* entry on success, NULL on failure. The caller is responsible for calling
* the necessary locking functions.
*
*/
struct netlbl_af6list *netlbl_af6list_remove(const struct in6_addr *addr,
const struct in6_addr *mask,
struct list_head *head)
{
struct netlbl_af6list *entry;
entry = netlbl_af6list_search_exact(addr, mask, head);
if (entry == NULL)
return NULL;
netlbl_af6list_remove_entry(entry);
return entry;
}
#endif /* IPv6 */
/*
* Audit Helper Functions
*/
#ifdef CONFIG_AUDIT
/**
* netlbl_af4list_audit_addr - Audit an IPv4 address
* @audit_buf: audit buffer
* @src: true if source address, false if destination
* @dev: network interface
* @addr: IP address
* @mask: IP address mask
*
* Description:
* Write the IPv4 address and address mask, if necessary, to @audit_buf.
*
*/
void netlbl_af4list_audit_addr(struct audit_buffer *audit_buf,
int src, const char *dev,
__be32 addr, __be32 mask)
{
u32 mask_val = ntohl(mask);
char *dir = (src ? "src" : "dst");
if (dev != NULL)
audit_log_format(audit_buf, " netif=%s", dev);
audit_log_format(audit_buf, " %s=%pI4", dir, &addr);
if (mask_val != 0xffffffff) {
u32 mask_len = 0;
while (mask_val > 0) {
mask_val <<= 1;
mask_len++;
}
audit_log_format(audit_buf, " %s_prefixlen=%d", dir, mask_len);
}
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_audit_addr - Audit an IPv6 address
* @audit_buf: audit buffer
* @src: true if source address, false if destination
* @dev: network interface
* @addr: IP address
* @mask: IP address mask
*
* Description:
* Write the IPv6 address and address mask, if necessary, to @audit_buf.
*
*/
void netlbl_af6list_audit_addr(struct audit_buffer *audit_buf,
int src,
const char *dev,
const struct in6_addr *addr,
const struct in6_addr *mask)
{
char *dir = (src ? "src" : "dst");
if (dev != NULL)
audit_log_format(audit_buf, " netif=%s", dev);
audit_log_format(audit_buf, " %s=%pI6", dir, addr);
if (ntohl(mask->s6_addr32[3]) != 0xffffffff) {
u32 mask_len = 0;
u32 mask_val;
int iter = -1;
while (ntohl(mask->s6_addr32[++iter]) == 0xffffffff)
mask_len += 32;
mask_val = ntohl(mask->s6_addr32[iter]);
while (mask_val > 0) {
mask_val <<= 1;
mask_len++;
}
audit_log_format(audit_buf, " %s_prefixlen=%d", dir, mask_len);
}
}
#endif /* IPv6 */
#endif /* CONFIG_AUDIT */
| gpl-2.0 |
lctwsnuc/mptcp_galaxy_nexus | drivers/staging/line6/dumprequest.c | 8326 | 2992 | /*
* Line6 Linux USB driver - 0.9.1beta
*
* Copyright (C) 2004-2010 Markus Grabner (grabner@icg.tugraz.at)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include <linux/slab.h>
#include "driver.h"
#include "dumprequest.h"
/*
Set "dump in progress" flag.
*/
void line6_dump_started(struct line6_dump_request *l6dr, int dest)
{
l6dr->in_progress = dest;
}
/*
Invalidate current channel, i.e., set "dump in progress" flag.
Reading from the "dump" special file blocks until dump is completed.
*/
void line6_invalidate_current(struct line6_dump_request *l6dr)
{
line6_dump_started(l6dr, LINE6_DUMP_CURRENT);
}
/*
Clear "dump in progress" flag and notify waiting processes.
*/
void line6_dump_finished(struct line6_dump_request *l6dr)
{
l6dr->in_progress = LINE6_DUMP_NONE;
wake_up(&l6dr->wait);
}
/*
Send an asynchronous channel dump request.
*/
int line6_dump_request_async(struct line6_dump_request *l6dr,
struct usb_line6 *line6, int num, int dest)
{
int ret;
line6_dump_started(l6dr, dest);
ret = line6_send_raw_message_async(line6, l6dr->reqbufs[num].buffer,
l6dr->reqbufs[num].length);
if (ret < 0)
line6_dump_finished(l6dr);
return ret;
}
/*
Wait for completion (interruptible).
*/
int line6_dump_wait_interruptible(struct line6_dump_request *l6dr)
{
return wait_event_interruptible(l6dr->wait,
l6dr->in_progress == LINE6_DUMP_NONE);
}
/*
Wait for completion.
*/
void line6_dump_wait(struct line6_dump_request *l6dr)
{
wait_event(l6dr->wait, l6dr->in_progress == LINE6_DUMP_NONE);
}
/*
Wait for completion (with timeout).
*/
int line6_dump_wait_timeout(struct line6_dump_request *l6dr, long timeout)
{
return wait_event_timeout(l6dr->wait,
l6dr->in_progress == LINE6_DUMP_NONE,
timeout);
}
/*
Initialize dump request buffer.
*/
int line6_dumpreq_initbuf(struct line6_dump_request *l6dr, const void *buf,
size_t len, int num)
{
l6dr->reqbufs[num].buffer = kmemdup(buf, len, GFP_KERNEL);
if (l6dr->reqbufs[num].buffer == NULL)
return -ENOMEM;
l6dr->reqbufs[num].length = len;
return 0;
}
/*
Initialize dump request data structure (including one buffer).
*/
int line6_dumpreq_init(struct line6_dump_request *l6dr, const void *buf,
size_t len)
{
int ret;
ret = line6_dumpreq_initbuf(l6dr, buf, len, 0);
if (ret < 0)
return ret;
init_waitqueue_head(&l6dr->wait);
return 0;
}
/*
Destruct dump request data structure.
*/
void line6_dumpreq_destructbuf(struct line6_dump_request *l6dr, int num)
{
if (l6dr == NULL)
return;
if (l6dr->reqbufs[num].buffer == NULL)
return;
kfree(l6dr->reqbufs[num].buffer);
l6dr->reqbufs[num].buffer = NULL;
}
/*
Destruct dump request data structure.
*/
void line6_dumpreq_destruct(struct line6_dump_request *l6dr)
{
if (l6dr->reqbufs[0].buffer == NULL)
return;
line6_dumpreq_destructbuf(l6dr, 0);
}
| gpl-2.0 |
transi/kernel_amazon_bowser-common | sound/pci/emu10k1/emuproc.c | 8838 | 21631 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Creative Labs, Inc.
* Routines for control of EMU10K1 chips / proc interface routines
*
* Copyright (c) by James Courtier-Dutton <James@superbug.co.uk>
* Added EMU 1010 support.
*
* BUGS:
* --
*
* TODO:
* --
*
* 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/slab.h>
#include <linux/init.h>
#include <sound/core.h>
#include <sound/emu10k1.h>
#include "p16v.h"
#ifdef CONFIG_PROC_FS
static void snd_emu10k1_proc_spdif_status(struct snd_emu10k1 * emu,
struct snd_info_buffer *buffer,
char *title,
int status_reg,
int rate_reg)
{
static char *clkaccy[4] = { "1000ppm", "50ppm", "variable", "unknown" };
static int samplerate[16] = { 44100, 1, 48000, 32000, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
static char *channel[16] = { "unspec", "left", "right", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" };
static char *emphasis[8] = { "none", "50/15 usec 2 channel", "2", "3", "4", "5", "6", "7" };
unsigned int status, rate = 0;
status = snd_emu10k1_ptr_read(emu, status_reg, 0);
snd_iprintf(buffer, "\n%s\n", title);
if (status != 0xffffffff) {
snd_iprintf(buffer, "Professional Mode : %s\n", (status & SPCS_PROFESSIONAL) ? "yes" : "no");
snd_iprintf(buffer, "Not Audio Data : %s\n", (status & SPCS_NOTAUDIODATA) ? "yes" : "no");
snd_iprintf(buffer, "Copyright : %s\n", (status & SPCS_COPYRIGHT) ? "yes" : "no");
snd_iprintf(buffer, "Emphasis : %s\n", emphasis[(status & SPCS_EMPHASISMASK) >> 3]);
snd_iprintf(buffer, "Mode : %i\n", (status & SPCS_MODEMASK) >> 6);
snd_iprintf(buffer, "Category Code : 0x%x\n", (status & SPCS_CATEGORYCODEMASK) >> 8);
snd_iprintf(buffer, "Generation Status : %s\n", status & SPCS_GENERATIONSTATUS ? "original" : "copy");
snd_iprintf(buffer, "Source Mask : %i\n", (status & SPCS_SOURCENUMMASK) >> 16);
snd_iprintf(buffer, "Channel Number : %s\n", channel[(status & SPCS_CHANNELNUMMASK) >> 20]);
snd_iprintf(buffer, "Sample Rate : %iHz\n", samplerate[(status & SPCS_SAMPLERATEMASK) >> 24]);
snd_iprintf(buffer, "Clock Accuracy : %s\n", clkaccy[(status & SPCS_CLKACCYMASK) >> 28]);
if (rate_reg > 0) {
rate = snd_emu10k1_ptr_read(emu, rate_reg, 0);
snd_iprintf(buffer, "S/PDIF Valid : %s\n", rate & SRCS_SPDIFVALID ? "on" : "off");
snd_iprintf(buffer, "S/PDIF Locked : %s\n", rate & SRCS_SPDIFLOCKED ? "on" : "off");
snd_iprintf(buffer, "Rate Locked : %s\n", rate & SRCS_RATELOCKED ? "on" : "off");
/* From ((Rate * 48000 ) / 262144); */
snd_iprintf(buffer, "Estimated Sample Rate : %d\n", ((rate & 0xFFFFF ) * 375) >> 11);
}
} else {
snd_iprintf(buffer, "No signal detected.\n");
}
}
static void snd_emu10k1_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
/* FIXME - output names are in emufx.c too */
static char *creative_outs[32] = {
/* 00 */ "AC97 Left",
/* 01 */ "AC97 Right",
/* 02 */ "Optical IEC958 Left",
/* 03 */ "Optical IEC958 Right",
/* 04 */ "Center",
/* 05 */ "LFE",
/* 06 */ "Headphone Left",
/* 07 */ "Headphone Right",
/* 08 */ "Surround Left",
/* 09 */ "Surround Right",
/* 10 */ "PCM Capture Left",
/* 11 */ "PCM Capture Right",
/* 12 */ "MIC Capture",
/* 13 */ "AC97 Surround Left",
/* 14 */ "AC97 Surround Right",
/* 15 */ "???",
/* 16 */ "???",
/* 17 */ "Analog Center",
/* 18 */ "Analog LFE",
/* 19 */ "???",
/* 20 */ "???",
/* 21 */ "???",
/* 22 */ "???",
/* 23 */ "???",
/* 24 */ "???",
/* 25 */ "???",
/* 26 */ "???",
/* 27 */ "???",
/* 28 */ "???",
/* 29 */ "???",
/* 30 */ "???",
/* 31 */ "???"
};
static char *audigy_outs[64] = {
/* 00 */ "Digital Front Left",
/* 01 */ "Digital Front Right",
/* 02 */ "Digital Center",
/* 03 */ "Digital LEF",
/* 04 */ "Headphone Left",
/* 05 */ "Headphone Right",
/* 06 */ "Digital Rear Left",
/* 07 */ "Digital Rear Right",
/* 08 */ "Front Left",
/* 09 */ "Front Right",
/* 10 */ "Center",
/* 11 */ "LFE",
/* 12 */ "???",
/* 13 */ "???",
/* 14 */ "Rear Left",
/* 15 */ "Rear Right",
/* 16 */ "AC97 Front Left",
/* 17 */ "AC97 Front Right",
/* 18 */ "ADC Caputre Left",
/* 19 */ "ADC Capture Right",
/* 20 */ "???",
/* 21 */ "???",
/* 22 */ "???",
/* 23 */ "???",
/* 24 */ "???",
/* 25 */ "???",
/* 26 */ "???",
/* 27 */ "???",
/* 28 */ "???",
/* 29 */ "???",
/* 30 */ "???",
/* 31 */ "???",
/* 32 */ "FXBUS2_0",
/* 33 */ "FXBUS2_1",
/* 34 */ "FXBUS2_2",
/* 35 */ "FXBUS2_3",
/* 36 */ "FXBUS2_4",
/* 37 */ "FXBUS2_5",
/* 38 */ "FXBUS2_6",
/* 39 */ "FXBUS2_7",
/* 40 */ "FXBUS2_8",
/* 41 */ "FXBUS2_9",
/* 42 */ "FXBUS2_10",
/* 43 */ "FXBUS2_11",
/* 44 */ "FXBUS2_12",
/* 45 */ "FXBUS2_13",
/* 46 */ "FXBUS2_14",
/* 47 */ "FXBUS2_15",
/* 48 */ "FXBUS2_16",
/* 49 */ "FXBUS2_17",
/* 50 */ "FXBUS2_18",
/* 51 */ "FXBUS2_19",
/* 52 */ "FXBUS2_20",
/* 53 */ "FXBUS2_21",
/* 54 */ "FXBUS2_22",
/* 55 */ "FXBUS2_23",
/* 56 */ "FXBUS2_24",
/* 57 */ "FXBUS2_25",
/* 58 */ "FXBUS2_26",
/* 59 */ "FXBUS2_27",
/* 60 */ "FXBUS2_28",
/* 61 */ "FXBUS2_29",
/* 62 */ "FXBUS2_30",
/* 63 */ "FXBUS2_31"
};
struct snd_emu10k1 *emu = entry->private_data;
unsigned int val, val1;
int nefx = emu->audigy ? 64 : 32;
char **outputs = emu->audigy ? audigy_outs : creative_outs;
int idx;
snd_iprintf(buffer, "EMU10K1\n\n");
snd_iprintf(buffer, "Card : %s\n",
emu->audigy ? "Audigy" : (emu->card_capabilities->ecard ? "EMU APS" : "Creative"));
snd_iprintf(buffer, "Internal TRAM (words) : 0x%x\n", emu->fx8010.itram_size);
snd_iprintf(buffer, "External TRAM (words) : 0x%x\n", (int)emu->fx8010.etram_pages.bytes / 2);
snd_iprintf(buffer, "\n");
snd_iprintf(buffer, "Effect Send Routing :\n");
for (idx = 0; idx < NUM_G; idx++) {
val = emu->audigy ?
snd_emu10k1_ptr_read(emu, A_FXRT1, idx) :
snd_emu10k1_ptr_read(emu, FXRT, idx);
val1 = emu->audigy ?
snd_emu10k1_ptr_read(emu, A_FXRT2, idx) :
0;
if (emu->audigy) {
snd_iprintf(buffer, "Ch%i: A=%i, B=%i, C=%i, D=%i, ",
idx,
val & 0x3f,
(val >> 8) & 0x3f,
(val >> 16) & 0x3f,
(val >> 24) & 0x3f);
snd_iprintf(buffer, "E=%i, F=%i, G=%i, H=%i\n",
val1 & 0x3f,
(val1 >> 8) & 0x3f,
(val1 >> 16) & 0x3f,
(val1 >> 24) & 0x3f);
} else {
snd_iprintf(buffer, "Ch%i: A=%i, B=%i, C=%i, D=%i\n",
idx,
(val >> 16) & 0x0f,
(val >> 20) & 0x0f,
(val >> 24) & 0x0f,
(val >> 28) & 0x0f);
}
}
snd_iprintf(buffer, "\nCaptured FX Outputs :\n");
for (idx = 0; idx < nefx; idx++) {
if (emu->efx_voices_mask[idx/32] & (1 << (idx%32)))
snd_iprintf(buffer, " Output %02i [%s]\n", idx, outputs[idx]);
}
snd_iprintf(buffer, "\nAll FX Outputs :\n");
for (idx = 0; idx < (emu->audigy ? 64 : 32); idx++)
snd_iprintf(buffer, " Output %02i [%s]\n", idx, outputs[idx]);
}
static void snd_emu10k1_proc_spdif_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_emu10k1 *emu = entry->private_data;
u32 value;
u32 value2;
unsigned long flags;
u32 rate;
if (emu->card_capabilities->emu_model) {
spin_lock_irqsave(&emu->emu_lock, flags);
snd_emu1010_fpga_read(emu, 0x38, &value);
spin_unlock_irqrestore(&emu->emu_lock, flags);
if ((value & 0x1) == 0) {
spin_lock_irqsave(&emu->emu_lock, flags);
snd_emu1010_fpga_read(emu, 0x2a, &value);
snd_emu1010_fpga_read(emu, 0x2b, &value2);
spin_unlock_irqrestore(&emu->emu_lock, flags);
rate = 0x1770000 / (((value << 5) | value2)+1);
snd_iprintf(buffer, "ADAT Locked : %u\n", rate);
} else {
snd_iprintf(buffer, "ADAT Unlocked\n");
}
spin_lock_irqsave(&emu->emu_lock, flags);
snd_emu1010_fpga_read(emu, 0x20, &value);
spin_unlock_irqrestore(&emu->emu_lock, flags);
if ((value & 0x4) == 0) {
spin_lock_irqsave(&emu->emu_lock, flags);
snd_emu1010_fpga_read(emu, 0x28, &value);
snd_emu1010_fpga_read(emu, 0x29, &value2);
spin_unlock_irqrestore(&emu->emu_lock, flags);
rate = 0x1770000 / (((value << 5) | value2)+1);
snd_iprintf(buffer, "SPDIF Locked : %d\n", rate);
} else {
snd_iprintf(buffer, "SPDIF Unlocked\n");
}
} else {
snd_emu10k1_proc_spdif_status(emu, buffer, "CD-ROM S/PDIF In", CDCS, CDSRCS);
snd_emu10k1_proc_spdif_status(emu, buffer, "Optical or Coax S/PDIF In", GPSCS, GPSRCS);
}
#if 0
val = snd_emu10k1_ptr_read(emu, ZVSRCS, 0);
snd_iprintf(buffer, "\nZoomed Video\n");
snd_iprintf(buffer, "Rate Locked : %s\n", val & SRCS_RATELOCKED ? "on" : "off");
snd_iprintf(buffer, "Estimated Sample Rate : 0x%x\n", val & SRCS_ESTSAMPLERATE);
#endif
}
static void snd_emu10k1_proc_rates_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
static int samplerate[8] = { 44100, 48000, 96000, 192000, 4, 5, 6, 7 };
struct snd_emu10k1 *emu = entry->private_data;
unsigned int val, tmp, n;
val = snd_emu10k1_ptr20_read(emu, CAPTURE_RATE_STATUS, 0);
tmp = (val >> 16) & 0x8;
for (n = 0; n < 4; n++) {
tmp = val >> (16 + (n*4));
if (tmp & 0x8) snd_iprintf(buffer, "Channel %d: Rate=%d\n", n, samplerate[tmp & 0x7]);
else snd_iprintf(buffer, "Channel %d: No input\n", n);
}
}
static void snd_emu10k1_proc_acode_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
u32 pc;
struct snd_emu10k1 *emu = entry->private_data;
snd_iprintf(buffer, "FX8010 Instruction List '%s'\n", emu->fx8010.name);
snd_iprintf(buffer, " Code dump :\n");
for (pc = 0; pc < (emu->audigy ? 1024 : 512); pc++) {
u32 low, high;
low = snd_emu10k1_efx_read(emu, pc * 2);
high = snd_emu10k1_efx_read(emu, pc * 2 + 1);
if (emu->audigy)
snd_iprintf(buffer, " OP(0x%02x, 0x%03x, 0x%03x, 0x%03x, 0x%03x) /* 0x%04x: 0x%08x%08x */\n",
(high >> 24) & 0x0f,
(high >> 12) & 0x7ff,
(high >> 0) & 0x7ff,
(low >> 12) & 0x7ff,
(low >> 0) & 0x7ff,
pc,
high, low);
else
snd_iprintf(buffer, " OP(0x%02x, 0x%03x, 0x%03x, 0x%03x, 0x%03x) /* 0x%04x: 0x%08x%08x */\n",
(high >> 20) & 0x0f,
(high >> 10) & 0x3ff,
(high >> 0) & 0x3ff,
(low >> 10) & 0x3ff,
(low >> 0) & 0x3ff,
pc,
high, low);
}
}
#define TOTAL_SIZE_GPR (0x100*4)
#define A_TOTAL_SIZE_GPR (0x200*4)
#define TOTAL_SIZE_TANKMEM_DATA (0xa0*4)
#define TOTAL_SIZE_TANKMEM_ADDR (0xa0*4)
#define A_TOTAL_SIZE_TANKMEM_DATA (0x100*4)
#define A_TOTAL_SIZE_TANKMEM_ADDR (0x100*4)
#define TOTAL_SIZE_CODE (0x200*8)
#define A_TOTAL_SIZE_CODE (0x400*8)
static ssize_t snd_emu10k1_fx8010_read(struct snd_info_entry *entry,
void *file_private_data,
struct file *file, char __user *buf,
size_t count, loff_t pos)
{
struct snd_emu10k1 *emu = entry->private_data;
unsigned int offset;
int tram_addr = 0;
unsigned int *tmp;
long res;
unsigned int idx;
if (!strcmp(entry->name, "fx8010_tram_addr")) {
offset = TANKMEMADDRREGBASE;
tram_addr = 1;
} else if (!strcmp(entry->name, "fx8010_tram_data")) {
offset = TANKMEMDATAREGBASE;
} else if (!strcmp(entry->name, "fx8010_code")) {
offset = emu->audigy ? A_MICROCODEBASE : MICROCODEBASE;
} else {
offset = emu->audigy ? A_FXGPREGBASE : FXGPREGBASE;
}
tmp = kmalloc(count + 8, GFP_KERNEL);
if (!tmp)
return -ENOMEM;
for (idx = 0; idx < ((pos & 3) + count + 3) >> 2; idx++) {
unsigned int val;
val = snd_emu10k1_ptr_read(emu, offset + idx + (pos >> 2), 0);
if (tram_addr && emu->audigy) {
val >>= 11;
val |= snd_emu10k1_ptr_read(emu, 0x100 + idx + (pos >> 2), 0) << 20;
}
tmp[idx] = val;
}
if (copy_to_user(buf, ((char *)tmp) + (pos & 3), count))
res = -EFAULT;
else
res = count;
kfree(tmp);
return res;
}
static void snd_emu10k1_proc_voices_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_emu10k1 *emu = entry->private_data;
struct snd_emu10k1_voice *voice;
int idx;
snd_iprintf(buffer, "ch\tuse\tpcm\tefx\tsynth\tmidi\n");
for (idx = 0; idx < NUM_G; idx++) {
voice = &emu->voices[idx];
snd_iprintf(buffer, "%i\t%i\t%i\t%i\t%i\t%i\n",
idx,
voice->use,
voice->pcm,
voice->efx,
voice->synth,
voice->midi);
}
}
#ifdef CONFIG_SND_DEBUG
static void snd_emu_proc_emu1010_reg_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_emu10k1 *emu = entry->private_data;
u32 value;
unsigned long flags;
int i;
snd_iprintf(buffer, "EMU1010 Registers:\n\n");
for(i = 0; i < 0x40; i+=1) {
spin_lock_irqsave(&emu->emu_lock, flags);
snd_emu1010_fpga_read(emu, i, &value);
spin_unlock_irqrestore(&emu->emu_lock, flags);
snd_iprintf(buffer, "%02X: %08X, %02X\n", i, value, (value >> 8) & 0x7f);
}
}
static void snd_emu_proc_io_reg_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_emu10k1 *emu = entry->private_data;
unsigned long value;
unsigned long flags;
int i;
snd_iprintf(buffer, "IO Registers:\n\n");
for(i = 0; i < 0x40; i+=4) {
spin_lock_irqsave(&emu->emu_lock, flags);
value = inl(emu->port + i);
spin_unlock_irqrestore(&emu->emu_lock, flags);
snd_iprintf(buffer, "%02X: %08lX\n", i, value);
}
}
static void snd_emu_proc_io_reg_write(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_emu10k1 *emu = entry->private_data;
unsigned long flags;
char line[64];
u32 reg, val;
while (!snd_info_get_line(buffer, line, sizeof(line))) {
if (sscanf(line, "%x %x", ®, &val) != 2)
continue;
if (reg < 0x40 && val <= 0xffffffff) {
spin_lock_irqsave(&emu->emu_lock, flags);
outl(val, emu->port + (reg & 0xfffffffc));
spin_unlock_irqrestore(&emu->emu_lock, flags);
}
}
}
static unsigned int snd_ptr_read(struct snd_emu10k1 * emu,
unsigned int iobase,
unsigned int reg,
unsigned int chn)
{
unsigned long flags;
unsigned int regptr, val;
regptr = (reg << 16) | chn;
spin_lock_irqsave(&emu->emu_lock, flags);
outl(regptr, emu->port + iobase + PTR);
val = inl(emu->port + iobase + DATA);
spin_unlock_irqrestore(&emu->emu_lock, flags);
return val;
}
static void snd_ptr_write(struct snd_emu10k1 *emu,
unsigned int iobase,
unsigned int reg,
unsigned int chn,
unsigned int data)
{
unsigned int regptr;
unsigned long flags;
regptr = (reg << 16) | chn;
spin_lock_irqsave(&emu->emu_lock, flags);
outl(regptr, emu->port + iobase + PTR);
outl(data, emu->port + iobase + DATA);
spin_unlock_irqrestore(&emu->emu_lock, flags);
}
static void snd_emu_proc_ptr_reg_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer, int iobase, int offset, int length, int voices)
{
struct snd_emu10k1 *emu = entry->private_data;
unsigned long value;
int i,j;
if (offset+length > 0xa0) {
snd_iprintf(buffer, "Input values out of range\n");
return;
}
snd_iprintf(buffer, "Registers 0x%x\n", iobase);
for(i = offset; i < offset+length; i++) {
snd_iprintf(buffer, "%02X: ",i);
for (j = 0; j < voices; j++) {
if(iobase == 0)
value = snd_ptr_read(emu, 0, i, j);
else
value = snd_ptr_read(emu, 0x20, i, j);
snd_iprintf(buffer, "%08lX ", value);
}
snd_iprintf(buffer, "\n");
}
}
static void snd_emu_proc_ptr_reg_write(struct snd_info_entry *entry,
struct snd_info_buffer *buffer, int iobase)
{
struct snd_emu10k1 *emu = entry->private_data;
char line[64];
unsigned int reg, channel_id , val;
while (!snd_info_get_line(buffer, line, sizeof(line))) {
if (sscanf(line, "%x %x %x", ®, &channel_id, &val) != 3)
continue;
if (reg < 0xa0 && val <= 0xffffffff && channel_id <= 3)
snd_ptr_write(emu, iobase, reg, channel_id, val);
}
}
static void snd_emu_proc_ptr_reg_write00(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_emu_proc_ptr_reg_write(entry, buffer, 0);
}
static void snd_emu_proc_ptr_reg_write20(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_emu_proc_ptr_reg_write(entry, buffer, 0x20);
}
static void snd_emu_proc_ptr_reg_read00a(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_emu_proc_ptr_reg_read(entry, buffer, 0, 0, 0x40, 64);
}
static void snd_emu_proc_ptr_reg_read00b(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_emu_proc_ptr_reg_read(entry, buffer, 0, 0x40, 0x40, 64);
}
static void snd_emu_proc_ptr_reg_read20a(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_emu_proc_ptr_reg_read(entry, buffer, 0x20, 0, 0x40, 4);
}
static void snd_emu_proc_ptr_reg_read20b(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_emu_proc_ptr_reg_read(entry, buffer, 0x20, 0x40, 0x40, 4);
}
static void snd_emu_proc_ptr_reg_read20c(struct snd_info_entry *entry,
struct snd_info_buffer * buffer)
{
snd_emu_proc_ptr_reg_read(entry, buffer, 0x20, 0x80, 0x20, 4);
}
#endif
static struct snd_info_entry_ops snd_emu10k1_proc_ops_fx8010 = {
.read = snd_emu10k1_fx8010_read,
};
int __devinit snd_emu10k1_proc_init(struct snd_emu10k1 * emu)
{
struct snd_info_entry *entry;
#ifdef CONFIG_SND_DEBUG
if (emu->card_capabilities->emu_model) {
if (! snd_card_proc_new(emu->card, "emu1010_regs", &entry))
snd_info_set_text_ops(entry, emu, snd_emu_proc_emu1010_reg_read);
}
if (! snd_card_proc_new(emu->card, "io_regs", &entry)) {
snd_info_set_text_ops(entry, emu, snd_emu_proc_io_reg_read);
entry->c.text.write = snd_emu_proc_io_reg_write;
entry->mode |= S_IWUSR;
}
if (! snd_card_proc_new(emu->card, "ptr_regs00a", &entry)) {
snd_info_set_text_ops(entry, emu, snd_emu_proc_ptr_reg_read00a);
entry->c.text.write = snd_emu_proc_ptr_reg_write00;
entry->mode |= S_IWUSR;
}
if (! snd_card_proc_new(emu->card, "ptr_regs00b", &entry)) {
snd_info_set_text_ops(entry, emu, snd_emu_proc_ptr_reg_read00b);
entry->c.text.write = snd_emu_proc_ptr_reg_write00;
entry->mode |= S_IWUSR;
}
if (! snd_card_proc_new(emu->card, "ptr_regs20a", &entry)) {
snd_info_set_text_ops(entry, emu, snd_emu_proc_ptr_reg_read20a);
entry->c.text.write = snd_emu_proc_ptr_reg_write20;
entry->mode |= S_IWUSR;
}
if (! snd_card_proc_new(emu->card, "ptr_regs20b", &entry)) {
snd_info_set_text_ops(entry, emu, snd_emu_proc_ptr_reg_read20b);
entry->c.text.write = snd_emu_proc_ptr_reg_write20;
entry->mode |= S_IWUSR;
}
if (! snd_card_proc_new(emu->card, "ptr_regs20c", &entry)) {
snd_info_set_text_ops(entry, emu, snd_emu_proc_ptr_reg_read20c);
entry->c.text.write = snd_emu_proc_ptr_reg_write20;
entry->mode |= S_IWUSR;
}
#endif
if (! snd_card_proc_new(emu->card, "emu10k1", &entry))
snd_info_set_text_ops(entry, emu, snd_emu10k1_proc_read);
if (emu->card_capabilities->emu10k2_chip) {
if (! snd_card_proc_new(emu->card, "spdif-in", &entry))
snd_info_set_text_ops(entry, emu, snd_emu10k1_proc_spdif_read);
}
if (emu->card_capabilities->ca0151_chip) {
if (! snd_card_proc_new(emu->card, "capture-rates", &entry))
snd_info_set_text_ops(entry, emu, snd_emu10k1_proc_rates_read);
}
if (! snd_card_proc_new(emu->card, "voices", &entry))
snd_info_set_text_ops(entry, emu, snd_emu10k1_proc_voices_read);
if (! snd_card_proc_new(emu->card, "fx8010_gpr", &entry)) {
entry->content = SNDRV_INFO_CONTENT_DATA;
entry->private_data = emu;
entry->mode = S_IFREG | S_IRUGO /*| S_IWUSR*/;
entry->size = emu->audigy ? A_TOTAL_SIZE_GPR : TOTAL_SIZE_GPR;
entry->c.ops = &snd_emu10k1_proc_ops_fx8010;
}
if (! snd_card_proc_new(emu->card, "fx8010_tram_data", &entry)) {
entry->content = SNDRV_INFO_CONTENT_DATA;
entry->private_data = emu;
entry->mode = S_IFREG | S_IRUGO /*| S_IWUSR*/;
entry->size = emu->audigy ? A_TOTAL_SIZE_TANKMEM_DATA : TOTAL_SIZE_TANKMEM_DATA ;
entry->c.ops = &snd_emu10k1_proc_ops_fx8010;
}
if (! snd_card_proc_new(emu->card, "fx8010_tram_addr", &entry)) {
entry->content = SNDRV_INFO_CONTENT_DATA;
entry->private_data = emu;
entry->mode = S_IFREG | S_IRUGO /*| S_IWUSR*/;
entry->size = emu->audigy ? A_TOTAL_SIZE_TANKMEM_ADDR : TOTAL_SIZE_TANKMEM_ADDR ;
entry->c.ops = &snd_emu10k1_proc_ops_fx8010;
}
if (! snd_card_proc_new(emu->card, "fx8010_code", &entry)) {
entry->content = SNDRV_INFO_CONTENT_DATA;
entry->private_data = emu;
entry->mode = S_IFREG | S_IRUGO /*| S_IWUSR*/;
entry->size = emu->audigy ? A_TOTAL_SIZE_CODE : TOTAL_SIZE_CODE;
entry->c.ops = &snd_emu10k1_proc_ops_fx8010;
}
if (! snd_card_proc_new(emu->card, "fx8010_acode", &entry)) {
entry->content = SNDRV_INFO_CONTENT_TEXT;
entry->private_data = emu;
entry->mode = S_IFREG | S_IRUGO /*| S_IWUSR*/;
entry->c.text.read = snd_emu10k1_proc_acode_read;
}
return 0;
}
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
flzyup/2.6.29-kernel-BFS-LiGux-FLZYUP | arch/x86/xen/enlighten.c | 135 | 41019 | /*
* Core of Xen paravirt_ops implementation.
*
* This file contains the xen_paravirt_ops structure itself, and the
* implementations for:
* - privileged instructions
* - interrupt flags
* - segment operations
* - booting and setup
*
* Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/smp.h>
#include <linux/preempt.h>
#include <linux/hardirq.h>
#include <linux/percpu.h>
#include <linux/delay.h>
#include <linux/start_kernel.h>
#include <linux/sched.h>
#include <linux/bootmem.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/page-flags.h>
#include <linux/highmem.h>
#include <linux/console.h>
#include <xen/interface/xen.h>
#include <xen/interface/version.h>
#include <xen/interface/physdev.h>
#include <xen/interface/vcpu.h>
#include <xen/features.h>
#include <xen/page.h>
#include <xen/hvc-console.h>
#include <asm/paravirt.h>
#include <asm/apic.h>
#include <asm/page.h>
#include <asm/xen/hypercall.h>
#include <asm/xen/hypervisor.h>
#include <asm/fixmap.h>
#include <asm/processor.h>
#include <asm/msr-index.h>
#include <asm/setup.h>
#include <asm/desc.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include <asm/reboot.h>
#include "xen-ops.h"
#include "mmu.h"
#include "multicalls.h"
EXPORT_SYMBOL_GPL(hypercall_page);
DEFINE_PER_CPU(struct vcpu_info *, xen_vcpu);
DEFINE_PER_CPU(struct vcpu_info, xen_vcpu_info);
enum xen_domain_type xen_domain_type = XEN_NATIVE;
EXPORT_SYMBOL_GPL(xen_domain_type);
/*
* Identity map, in addition to plain kernel map. This needs to be
* large enough to allocate page table pages to allocate the rest.
* Each page can map 2MB.
*/
static pte_t level1_ident_pgt[PTRS_PER_PTE * 4] __page_aligned_bss;
#ifdef CONFIG_X86_64
/* l3 pud for userspace vsyscall mapping */
static pud_t level3_user_vsyscall[PTRS_PER_PUD] __page_aligned_bss;
#endif /* CONFIG_X86_64 */
/*
* Note about cr3 (pagetable base) values:
*
* xen_cr3 contains the current logical cr3 value; it contains the
* last set cr3. This may not be the current effective cr3, because
* its update may be being lazily deferred. However, a vcpu looking
* at its own cr3 can use this value knowing that it everything will
* be self-consistent.
*
* xen_current_cr3 contains the actual vcpu cr3; it is set once the
* hypercall to set the vcpu cr3 is complete (so it may be a little
* out of date, but it will never be set early). If one vcpu is
* looking at another vcpu's cr3 value, it should use this variable.
*/
DEFINE_PER_CPU(unsigned long, xen_cr3); /* cr3 stored as physaddr */
DEFINE_PER_CPU(unsigned long, xen_current_cr3); /* actual vcpu cr3 */
struct start_info *xen_start_info;
EXPORT_SYMBOL_GPL(xen_start_info);
struct shared_info xen_dummy_shared_info;
/*
* Point at some empty memory to start with. We map the real shared_info
* page as soon as fixmap is up and running.
*/
struct shared_info *HYPERVISOR_shared_info = (void *)&xen_dummy_shared_info;
/*
* Flag to determine whether vcpu info placement is available on all
* VCPUs. We assume it is to start with, and then set it to zero on
* the first failure. This is because it can succeed on some VCPUs
* and not others, since it can involve hypervisor memory allocation,
* or because the guest failed to guarantee all the appropriate
* constraints on all VCPUs (ie buffer can't cross a page boundary).
*
* Note that any particular CPU may be using a placed vcpu structure,
* but we can only optimise if the all are.
*
* 0: not available, 1: available
*/
static int have_vcpu_info_placement =
#ifdef CONFIG_X86_32
1
#else
0
#endif
;
static void xen_vcpu_setup(int cpu)
{
struct vcpu_register_vcpu_info info;
int err;
struct vcpu_info *vcpup;
BUG_ON(HYPERVISOR_shared_info == &xen_dummy_shared_info);
per_cpu(xen_vcpu, cpu) = &HYPERVISOR_shared_info->vcpu_info[cpu];
if (!have_vcpu_info_placement)
return; /* already tested, not available */
vcpup = &per_cpu(xen_vcpu_info, cpu);
info.mfn = virt_to_mfn(vcpup);
info.offset = offset_in_page(vcpup);
printk(KERN_DEBUG "trying to map vcpu_info %d at %p, mfn %llx, offset %d\n",
cpu, vcpup, info.mfn, info.offset);
/* Check to see if the hypervisor will put the vcpu_info
structure where we want it, which allows direct access via
a percpu-variable. */
err = HYPERVISOR_vcpu_op(VCPUOP_register_vcpu_info, cpu, &info);
if (err) {
printk(KERN_DEBUG "register_vcpu_info failed: err=%d\n", err);
have_vcpu_info_placement = 0;
} else {
/* This cpu is using the registered vcpu info, even if
later ones fail to. */
per_cpu(xen_vcpu, cpu) = vcpup;
printk(KERN_DEBUG "cpu %d using vcpu_info at %p\n",
cpu, vcpup);
}
}
/*
* On restore, set the vcpu placement up again.
* If it fails, then we're in a bad state, since
* we can't back out from using it...
*/
void xen_vcpu_restore(void)
{
if (have_vcpu_info_placement) {
int cpu;
for_each_online_cpu(cpu) {
bool other_cpu = (cpu != smp_processor_id());
if (other_cpu &&
HYPERVISOR_vcpu_op(VCPUOP_down, cpu, NULL))
BUG();
xen_vcpu_setup(cpu);
if (other_cpu &&
HYPERVISOR_vcpu_op(VCPUOP_up, cpu, NULL))
BUG();
}
BUG_ON(!have_vcpu_info_placement);
}
}
static void __init xen_banner(void)
{
unsigned version = HYPERVISOR_xen_version(XENVER_version, NULL);
struct xen_extraversion extra;
HYPERVISOR_xen_version(XENVER_extraversion, &extra);
printk(KERN_INFO "Booting paravirtualized kernel on %s\n",
pv_info.name);
printk(KERN_INFO "Xen version: %d.%d%s%s\n",
version >> 16, version & 0xffff, extra.extraversion,
xen_feature(XENFEAT_mmu_pt_update_preserve_ad) ? " (preserve-AD)" : "");
}
static void xen_cpuid(unsigned int *ax, unsigned int *bx,
unsigned int *cx, unsigned int *dx)
{
unsigned maskedx = ~0;
/*
* Mask out inconvenient features, to try and disable as many
* unsupported kernel subsystems as possible.
*/
if (*ax == 1)
maskedx = ~((1 << X86_FEATURE_APIC) | /* disable APIC */
(1 << X86_FEATURE_ACPI) | /* disable ACPI */
(1 << X86_FEATURE_MCE) | /* disable MCE */
(1 << X86_FEATURE_MCA) | /* disable MCA */
(1 << X86_FEATURE_ACC)); /* thermal monitoring */
asm(XEN_EMULATE_PREFIX "cpuid"
: "=a" (*ax),
"=b" (*bx),
"=c" (*cx),
"=d" (*dx)
: "0" (*ax), "2" (*cx));
*dx &= maskedx;
}
static void xen_set_debugreg(int reg, unsigned long val)
{
HYPERVISOR_set_debugreg(reg, val);
}
static unsigned long xen_get_debugreg(int reg)
{
return HYPERVISOR_get_debugreg(reg);
}
static void xen_leave_lazy(void)
{
paravirt_leave_lazy(paravirt_get_lazy_mode());
xen_mc_flush();
}
static unsigned long xen_store_tr(void)
{
return 0;
}
/*
* Set the page permissions for a particular virtual address. If the
* address is a vmalloc mapping (or other non-linear mapping), then
* find the linear mapping of the page and also set its protections to
* match.
*/
static void set_aliased_prot(void *v, pgprot_t prot)
{
int level;
pte_t *ptep;
pte_t pte;
unsigned long pfn;
struct page *page;
ptep = lookup_address((unsigned long)v, &level);
BUG_ON(ptep == NULL);
pfn = pte_pfn(*ptep);
page = pfn_to_page(pfn);
pte = pfn_pte(pfn, prot);
if (HYPERVISOR_update_va_mapping((unsigned long)v, pte, 0))
BUG();
if (!PageHighMem(page)) {
void *av = __va(PFN_PHYS(pfn));
if (av != v)
if (HYPERVISOR_update_va_mapping((unsigned long)av, pte, 0))
BUG();
} else
kmap_flush_unused();
}
static void xen_alloc_ldt(struct desc_struct *ldt, unsigned entries)
{
const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE;
int i;
for(i = 0; i < entries; i += entries_per_page)
set_aliased_prot(ldt + i, PAGE_KERNEL_RO);
}
static void xen_free_ldt(struct desc_struct *ldt, unsigned entries)
{
const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE;
int i;
for(i = 0; i < entries; i += entries_per_page)
set_aliased_prot(ldt + i, PAGE_KERNEL);
}
static void xen_set_ldt(const void *addr, unsigned entries)
{
struct mmuext_op *op;
struct multicall_space mcs = xen_mc_entry(sizeof(*op));
op = mcs.args;
op->cmd = MMUEXT_SET_LDT;
op->arg1.linear_addr = (unsigned long)addr;
op->arg2.nr_ents = entries;
MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
xen_mc_issue(PARAVIRT_LAZY_CPU);
}
static void xen_load_gdt(const struct desc_ptr *dtr)
{
unsigned long *frames;
unsigned long va = dtr->address;
unsigned int size = dtr->size + 1;
unsigned pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
int f;
struct multicall_space mcs;
/* A GDT can be up to 64k in size, which corresponds to 8192
8-byte entries, or 16 4k pages.. */
BUG_ON(size > 65536);
BUG_ON(va & ~PAGE_MASK);
mcs = xen_mc_entry(sizeof(*frames) * pages);
frames = mcs.args;
for (f = 0; va < dtr->address + size; va += PAGE_SIZE, f++) {
frames[f] = virt_to_mfn(va);
make_lowmem_page_readonly((void *)va);
}
MULTI_set_gdt(mcs.mc, frames, size / sizeof(struct desc_struct));
xen_mc_issue(PARAVIRT_LAZY_CPU);
}
static void load_TLS_descriptor(struct thread_struct *t,
unsigned int cpu, unsigned int i)
{
struct desc_struct *gdt = get_cpu_gdt_table(cpu);
xmaddr_t maddr = virt_to_machine(&gdt[GDT_ENTRY_TLS_MIN+i]);
struct multicall_space mc = __xen_mc_entry(0);
MULTI_update_descriptor(mc.mc, maddr.maddr, t->tls_array[i]);
}
static void xen_load_tls(struct thread_struct *t, unsigned int cpu)
{
/*
* XXX sleazy hack: If we're being called in a lazy-cpu zone,
* it means we're in a context switch, and %gs has just been
* saved. This means we can zero it out to prevent faults on
* exit from the hypervisor if the next process has no %gs.
* Either way, it has been saved, and the new value will get
* loaded properly. This will go away as soon as Xen has been
* modified to not save/restore %gs for normal hypercalls.
*
* On x86_64, this hack is not used for %gs, because gs points
* to KERNEL_GS_BASE (and uses it for PDA references), so we
* must not zero %gs on x86_64
*
* For x86_64, we need to zero %fs, otherwise we may get an
* exception between the new %fs descriptor being loaded and
* %fs being effectively cleared at __switch_to().
*/
if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_CPU) {
#ifdef CONFIG_X86_32
loadsegment(gs, 0);
#else
loadsegment(fs, 0);
#endif
}
xen_mc_batch();
load_TLS_descriptor(t, cpu, 0);
load_TLS_descriptor(t, cpu, 1);
load_TLS_descriptor(t, cpu, 2);
xen_mc_issue(PARAVIRT_LAZY_CPU);
}
#ifdef CONFIG_X86_64
static void xen_load_gs_index(unsigned int idx)
{
if (HYPERVISOR_set_segment_base(SEGBASE_GS_USER_SEL, idx))
BUG();
}
#endif
static void xen_write_ldt_entry(struct desc_struct *dt, int entrynum,
const void *ptr)
{
xmaddr_t mach_lp = arbitrary_virt_to_machine(&dt[entrynum]);
u64 entry = *(u64 *)ptr;
preempt_disable();
xen_mc_flush();
if (HYPERVISOR_update_descriptor(mach_lp.maddr, entry))
BUG();
preempt_enable();
}
static int cvt_gate_to_trap(int vector, const gate_desc *val,
struct trap_info *info)
{
if (val->type != 0xf && val->type != 0xe)
return 0;
info->vector = vector;
info->address = gate_offset(*val);
info->cs = gate_segment(*val);
info->flags = val->dpl;
/* interrupt gates clear IF */
if (val->type == 0xe)
info->flags |= 4;
return 1;
}
/* Locations of each CPU's IDT */
static DEFINE_PER_CPU(struct desc_ptr, idt_desc);
/* Set an IDT entry. If the entry is part of the current IDT, then
also update Xen. */
static void xen_write_idt_entry(gate_desc *dt, int entrynum, const gate_desc *g)
{
unsigned long p = (unsigned long)&dt[entrynum];
unsigned long start, end;
preempt_disable();
start = __get_cpu_var(idt_desc).address;
end = start + __get_cpu_var(idt_desc).size + 1;
xen_mc_flush();
native_write_idt_entry(dt, entrynum, g);
if (p >= start && (p + 8) <= end) {
struct trap_info info[2];
info[1].address = 0;
if (cvt_gate_to_trap(entrynum, g, &info[0]))
if (HYPERVISOR_set_trap_table(info))
BUG();
}
preempt_enable();
}
static void xen_convert_trap_info(const struct desc_ptr *desc,
struct trap_info *traps)
{
unsigned in, out, count;
count = (desc->size+1) / sizeof(gate_desc);
BUG_ON(count > 256);
for (in = out = 0; in < count; in++) {
gate_desc *entry = (gate_desc*)(desc->address) + in;
if (cvt_gate_to_trap(in, entry, &traps[out]))
out++;
}
traps[out].address = 0;
}
void xen_copy_trap_info(struct trap_info *traps)
{
const struct desc_ptr *desc = &__get_cpu_var(idt_desc);
xen_convert_trap_info(desc, traps);
}
/* Load a new IDT into Xen. In principle this can be per-CPU, so we
hold a spinlock to protect the static traps[] array (static because
it avoids allocation, and saves stack space). */
static void xen_load_idt(const struct desc_ptr *desc)
{
static DEFINE_SPINLOCK(lock);
static struct trap_info traps[257];
spin_lock(&lock);
__get_cpu_var(idt_desc) = *desc;
xen_convert_trap_info(desc, traps);
xen_mc_flush();
if (HYPERVISOR_set_trap_table(traps))
BUG();
spin_unlock(&lock);
}
/* Write a GDT descriptor entry. Ignore LDT descriptors, since
they're handled differently. */
static void xen_write_gdt_entry(struct desc_struct *dt, int entry,
const void *desc, int type)
{
preempt_disable();
switch (type) {
case DESC_LDT:
case DESC_TSS:
/* ignore */
break;
default: {
xmaddr_t maddr = virt_to_machine(&dt[entry]);
xen_mc_flush();
if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc))
BUG();
}
}
preempt_enable();
}
static void xen_load_sp0(struct tss_struct *tss,
struct thread_struct *thread)
{
struct multicall_space mcs = xen_mc_entry(0);
MULTI_stack_switch(mcs.mc, __KERNEL_DS, thread->sp0);
xen_mc_issue(PARAVIRT_LAZY_CPU);
}
static void xen_set_iopl_mask(unsigned mask)
{
struct physdev_set_iopl set_iopl;
/* Force the change at ring 0. */
set_iopl.iopl = (mask == 0) ? 1 : (mask >> 12) & 3;
HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl);
}
static void xen_io_delay(void)
{
}
#ifdef CONFIG_X86_LOCAL_APIC
static u32 xen_apic_read(u32 reg)
{
return 0;
}
static void xen_apic_write(u32 reg, u32 val)
{
/* Warn to see if there's any stray references */
WARN_ON(1);
}
static u64 xen_apic_icr_read(void)
{
return 0;
}
static void xen_apic_icr_write(u32 low, u32 id)
{
/* Warn to see if there's any stray references */
WARN_ON(1);
}
static void xen_apic_wait_icr_idle(void)
{
return;
}
static u32 xen_safe_apic_wait_icr_idle(void)
{
return 0;
}
static struct apic_ops xen_basic_apic_ops = {
.read = xen_apic_read,
.write = xen_apic_write,
.icr_read = xen_apic_icr_read,
.icr_write = xen_apic_icr_write,
.wait_icr_idle = xen_apic_wait_icr_idle,
.safe_wait_icr_idle = xen_safe_apic_wait_icr_idle,
};
#endif
static void xen_flush_tlb(void)
{
struct mmuext_op *op;
struct multicall_space mcs;
preempt_disable();
mcs = xen_mc_entry(sizeof(*op));
op = mcs.args;
op->cmd = MMUEXT_TLB_FLUSH_LOCAL;
MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
xen_mc_issue(PARAVIRT_LAZY_MMU);
preempt_enable();
}
static void xen_flush_tlb_single(unsigned long addr)
{
struct mmuext_op *op;
struct multicall_space mcs;
preempt_disable();
mcs = xen_mc_entry(sizeof(*op));
op = mcs.args;
op->cmd = MMUEXT_INVLPG_LOCAL;
op->arg1.linear_addr = addr & PAGE_MASK;
MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
xen_mc_issue(PARAVIRT_LAZY_MMU);
preempt_enable();
}
static void xen_flush_tlb_others(const cpumask_t *cpus, struct mm_struct *mm,
unsigned long va)
{
struct {
struct mmuext_op op;
cpumask_t mask;
} *args;
cpumask_t cpumask = *cpus;
struct multicall_space mcs;
/*
* A couple of (to be removed) sanity checks:
*
* - current CPU must not be in mask
* - mask must exist :)
*/
BUG_ON(cpus_empty(cpumask));
BUG_ON(cpu_isset(smp_processor_id(), cpumask));
BUG_ON(!mm);
/* If a CPU which we ran on has gone down, OK. */
cpus_and(cpumask, cpumask, cpu_online_map);
if (cpus_empty(cpumask))
return;
mcs = xen_mc_entry(sizeof(*args));
args = mcs.args;
args->mask = cpumask;
args->op.arg2.vcpumask = &args->mask;
if (va == TLB_FLUSH_ALL) {
args->op.cmd = MMUEXT_TLB_FLUSH_MULTI;
} else {
args->op.cmd = MMUEXT_INVLPG_MULTI;
args->op.arg1.linear_addr = va;
}
MULTI_mmuext_op(mcs.mc, &args->op, 1, NULL, DOMID_SELF);
xen_mc_issue(PARAVIRT_LAZY_MMU);
}
static void xen_clts(void)
{
struct multicall_space mcs;
mcs = xen_mc_entry(0);
MULTI_fpu_taskswitch(mcs.mc, 0);
xen_mc_issue(PARAVIRT_LAZY_CPU);
}
static void xen_write_cr0(unsigned long cr0)
{
struct multicall_space mcs;
/* Only pay attention to cr0.TS; everything else is
ignored. */
mcs = xen_mc_entry(0);
MULTI_fpu_taskswitch(mcs.mc, (cr0 & X86_CR0_TS) != 0);
xen_mc_issue(PARAVIRT_LAZY_CPU);
}
static void xen_write_cr2(unsigned long cr2)
{
x86_read_percpu(xen_vcpu)->arch.cr2 = cr2;
}
static unsigned long xen_read_cr2(void)
{
return x86_read_percpu(xen_vcpu)->arch.cr2;
}
static unsigned long xen_read_cr2_direct(void)
{
return x86_read_percpu(xen_vcpu_info.arch.cr2);
}
static void xen_write_cr4(unsigned long cr4)
{
cr4 &= ~X86_CR4_PGE;
cr4 &= ~X86_CR4_PSE;
native_write_cr4(cr4);
}
static unsigned long xen_read_cr3(void)
{
return x86_read_percpu(xen_cr3);
}
static void set_current_cr3(void *v)
{
x86_write_percpu(xen_current_cr3, (unsigned long)v);
}
static void __xen_write_cr3(bool kernel, unsigned long cr3)
{
struct mmuext_op *op;
struct multicall_space mcs;
unsigned long mfn;
if (cr3)
mfn = pfn_to_mfn(PFN_DOWN(cr3));
else
mfn = 0;
WARN_ON(mfn == 0 && kernel);
mcs = __xen_mc_entry(sizeof(*op));
op = mcs.args;
op->cmd = kernel ? MMUEXT_NEW_BASEPTR : MMUEXT_NEW_USER_BASEPTR;
op->arg1.mfn = mfn;
MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF);
if (kernel) {
x86_write_percpu(xen_cr3, cr3);
/* Update xen_current_cr3 once the batch has actually
been submitted. */
xen_mc_callback(set_current_cr3, (void *)cr3);
}
}
static void xen_write_cr3(unsigned long cr3)
{
BUG_ON(preemptible());
xen_mc_batch(); /* disables interrupts */
/* Update while interrupts are disabled, so its atomic with
respect to ipis */
x86_write_percpu(xen_cr3, cr3);
__xen_write_cr3(true, cr3);
#ifdef CONFIG_X86_64
{
pgd_t *user_pgd = xen_get_user_pgd(__va(cr3));
if (user_pgd)
__xen_write_cr3(false, __pa(user_pgd));
else
__xen_write_cr3(false, 0);
}
#endif
xen_mc_issue(PARAVIRT_LAZY_CPU); /* interrupts restored */
}
static int xen_write_msr_safe(unsigned int msr, unsigned low, unsigned high)
{
int ret;
ret = 0;
switch (msr) {
#ifdef CONFIG_X86_64
unsigned which;
u64 base;
case MSR_FS_BASE: which = SEGBASE_FS; goto set;
case MSR_KERNEL_GS_BASE: which = SEGBASE_GS_USER; goto set;
case MSR_GS_BASE: which = SEGBASE_GS_KERNEL; goto set;
set:
base = ((u64)high << 32) | low;
if (HYPERVISOR_set_segment_base(which, base) != 0)
ret = -EFAULT;
break;
#endif
case MSR_STAR:
case MSR_CSTAR:
case MSR_LSTAR:
case MSR_SYSCALL_MASK:
case MSR_IA32_SYSENTER_CS:
case MSR_IA32_SYSENTER_ESP:
case MSR_IA32_SYSENTER_EIP:
/* Fast syscall setup is all done in hypercalls, so
these are all ignored. Stub them out here to stop
Xen console noise. */
break;
default:
ret = native_write_msr_safe(msr, low, high);
}
return ret;
}
/* Early in boot, while setting up the initial pagetable, assume
everything is pinned. */
static __init void xen_alloc_pte_init(struct mm_struct *mm, unsigned long pfn)
{
#ifdef CONFIG_FLATMEM
BUG_ON(mem_map); /* should only be used early */
#endif
make_lowmem_page_readonly(__va(PFN_PHYS(pfn)));
}
/* Early release_pte assumes that all pts are pinned, since there's
only init_mm and anything attached to that is pinned. */
static void xen_release_pte_init(unsigned long pfn)
{
make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
}
static void pin_pagetable_pfn(unsigned cmd, unsigned long pfn)
{
struct mmuext_op op;
op.cmd = cmd;
op.arg1.mfn = pfn_to_mfn(pfn);
if (HYPERVISOR_mmuext_op(&op, 1, NULL, DOMID_SELF))
BUG();
}
/* This needs to make sure the new pte page is pinned iff its being
attached to a pinned pagetable. */
static void xen_alloc_ptpage(struct mm_struct *mm, unsigned long pfn, unsigned level)
{
struct page *page = pfn_to_page(pfn);
if (PagePinned(virt_to_page(mm->pgd))) {
SetPagePinned(page);
vm_unmap_aliases();
if (!PageHighMem(page)) {
make_lowmem_page_readonly(__va(PFN_PHYS((unsigned long)pfn)));
if (level == PT_PTE && USE_SPLIT_PTLOCKS)
pin_pagetable_pfn(MMUEXT_PIN_L1_TABLE, pfn);
} else {
/* make sure there are no stray mappings of
this page */
kmap_flush_unused();
}
}
}
static void xen_alloc_pte(struct mm_struct *mm, unsigned long pfn)
{
xen_alloc_ptpage(mm, pfn, PT_PTE);
}
static void xen_alloc_pmd(struct mm_struct *mm, unsigned long pfn)
{
xen_alloc_ptpage(mm, pfn, PT_PMD);
}
static int xen_pgd_alloc(struct mm_struct *mm)
{
pgd_t *pgd = mm->pgd;
int ret = 0;
BUG_ON(PagePinned(virt_to_page(pgd)));
#ifdef CONFIG_X86_64
{
struct page *page = virt_to_page(pgd);
pgd_t *user_pgd;
BUG_ON(page->private != 0);
ret = -ENOMEM;
user_pgd = (pgd_t *)__get_free_page(GFP_KERNEL | __GFP_ZERO);
page->private = (unsigned long)user_pgd;
if (user_pgd != NULL) {
user_pgd[pgd_index(VSYSCALL_START)] =
__pgd(__pa(level3_user_vsyscall) | _PAGE_TABLE);
ret = 0;
}
BUG_ON(PagePinned(virt_to_page(xen_get_user_pgd(pgd))));
}
#endif
return ret;
}
static void xen_pgd_free(struct mm_struct *mm, pgd_t *pgd)
{
#ifdef CONFIG_X86_64
pgd_t *user_pgd = xen_get_user_pgd(pgd);
if (user_pgd)
free_page((unsigned long)user_pgd);
#endif
}
/* This should never happen until we're OK to use struct page */
static void xen_release_ptpage(unsigned long pfn, unsigned level)
{
struct page *page = pfn_to_page(pfn);
if (PagePinned(page)) {
if (!PageHighMem(page)) {
if (level == PT_PTE && USE_SPLIT_PTLOCKS)
pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, pfn);
make_lowmem_page_readwrite(__va(PFN_PHYS(pfn)));
}
ClearPagePinned(page);
}
}
static void xen_release_pte(unsigned long pfn)
{
xen_release_ptpage(pfn, PT_PTE);
}
static void xen_release_pmd(unsigned long pfn)
{
xen_release_ptpage(pfn, PT_PMD);
}
#if PAGETABLE_LEVELS == 4
static void xen_alloc_pud(struct mm_struct *mm, unsigned long pfn)
{
xen_alloc_ptpage(mm, pfn, PT_PUD);
}
static void xen_release_pud(unsigned long pfn)
{
xen_release_ptpage(pfn, PT_PUD);
}
#endif
#ifdef CONFIG_HIGHPTE
static void *xen_kmap_atomic_pte(struct page *page, enum km_type type)
{
pgprot_t prot = PAGE_KERNEL;
if (PagePinned(page))
prot = PAGE_KERNEL_RO;
if (0 && PageHighMem(page))
printk("mapping highpte %lx type %d prot %s\n",
page_to_pfn(page), type,
(unsigned long)pgprot_val(prot) & _PAGE_RW ? "WRITE" : "READ");
return kmap_atomic_prot(page, type, prot);
}
#endif
#ifdef CONFIG_X86_32
static __init pte_t mask_rw_pte(pte_t *ptep, pte_t pte)
{
/* If there's an existing pte, then don't allow _PAGE_RW to be set */
if (pte_val_ma(*ptep) & _PAGE_PRESENT)
pte = __pte_ma(((pte_val_ma(*ptep) & _PAGE_RW) | ~_PAGE_RW) &
pte_val_ma(pte));
return pte;
}
/* Init-time set_pte while constructing initial pagetables, which
doesn't allow RO pagetable pages to be remapped RW */
static __init void xen_set_pte_init(pte_t *ptep, pte_t pte)
{
pte = mask_rw_pte(ptep, pte);
xen_set_pte(ptep, pte);
}
#endif
static __init void xen_pagetable_setup_start(pgd_t *base)
{
}
void xen_setup_shared_info(void)
{
if (!xen_feature(XENFEAT_auto_translated_physmap)) {
set_fixmap(FIX_PARAVIRT_BOOTMAP,
xen_start_info->shared_info);
HYPERVISOR_shared_info =
(struct shared_info *)fix_to_virt(FIX_PARAVIRT_BOOTMAP);
} else
HYPERVISOR_shared_info =
(struct shared_info *)__va(xen_start_info->shared_info);
#ifndef CONFIG_SMP
/* In UP this is as good a place as any to set up shared info */
xen_setup_vcpu_info_placement();
#endif
xen_setup_mfn_list_list();
}
static __init void xen_pagetable_setup_done(pgd_t *base)
{
xen_setup_shared_info();
}
static __init void xen_post_allocator_init(void)
{
pv_mmu_ops.set_pte = xen_set_pte;
pv_mmu_ops.set_pmd = xen_set_pmd;
pv_mmu_ops.set_pud = xen_set_pud;
#if PAGETABLE_LEVELS == 4
pv_mmu_ops.set_pgd = xen_set_pgd;
#endif
/* This will work as long as patching hasn't happened yet
(which it hasn't) */
pv_mmu_ops.alloc_pte = xen_alloc_pte;
pv_mmu_ops.alloc_pmd = xen_alloc_pmd;
pv_mmu_ops.release_pte = xen_release_pte;
pv_mmu_ops.release_pmd = xen_release_pmd;
#if PAGETABLE_LEVELS == 4
pv_mmu_ops.alloc_pud = xen_alloc_pud;
pv_mmu_ops.release_pud = xen_release_pud;
#endif
#ifdef CONFIG_X86_64
SetPagePinned(virt_to_page(level3_user_vsyscall));
#endif
xen_mark_init_mm_pinned();
}
/* This is called once we have the cpu_possible_map */
void xen_setup_vcpu_info_placement(void)
{
int cpu;
for_each_possible_cpu(cpu)
xen_vcpu_setup(cpu);
/* xen_vcpu_setup managed to place the vcpu_info within the
percpu area for all cpus, so make use of it */
if (have_vcpu_info_placement) {
printk(KERN_INFO "Xen: using vcpu_info placement\n");
pv_irq_ops.save_fl = xen_save_fl_direct;
pv_irq_ops.restore_fl = xen_restore_fl_direct;
pv_irq_ops.irq_disable = xen_irq_disable_direct;
pv_irq_ops.irq_enable = xen_irq_enable_direct;
pv_mmu_ops.read_cr2 = xen_read_cr2_direct;
}
}
static unsigned xen_patch(u8 type, u16 clobbers, void *insnbuf,
unsigned long addr, unsigned len)
{
char *start, *end, *reloc;
unsigned ret;
start = end = reloc = NULL;
#define SITE(op, x) \
case PARAVIRT_PATCH(op.x): \
if (have_vcpu_info_placement) { \
start = (char *)xen_##x##_direct; \
end = xen_##x##_direct_end; \
reloc = xen_##x##_direct_reloc; \
} \
goto patch_site
switch (type) {
SITE(pv_irq_ops, irq_enable);
SITE(pv_irq_ops, irq_disable);
SITE(pv_irq_ops, save_fl);
SITE(pv_irq_ops, restore_fl);
#undef SITE
patch_site:
if (start == NULL || (end-start) > len)
goto default_patch;
ret = paravirt_patch_insns(insnbuf, len, start, end);
/* Note: because reloc is assigned from something that
appears to be an array, gcc assumes it's non-null,
but doesn't know its relationship with start and
end. */
if (reloc > start && reloc < end) {
int reloc_off = reloc - start;
long *relocp = (long *)(insnbuf + reloc_off);
long delta = start - (char *)addr;
*relocp += delta;
}
break;
default_patch:
default:
ret = paravirt_patch_default(type, clobbers, insnbuf,
addr, len);
break;
}
return ret;
}
static void xen_set_fixmap(unsigned idx, unsigned long phys, pgprot_t prot)
{
pte_t pte;
phys >>= PAGE_SHIFT;
switch (idx) {
case FIX_BTMAP_END ... FIX_BTMAP_BEGIN:
#ifdef CONFIG_X86_F00F_BUG
case FIX_F00F_IDT:
#endif
#ifdef CONFIG_X86_32
case FIX_WP_TEST:
case FIX_VDSO:
# ifdef CONFIG_HIGHMEM
case FIX_KMAP_BEGIN ... FIX_KMAP_END:
# endif
#else
case VSYSCALL_LAST_PAGE ... VSYSCALL_FIRST_PAGE:
#endif
#ifdef CONFIG_X86_LOCAL_APIC
case FIX_APIC_BASE: /* maps dummy local APIC */
#endif
pte = pfn_pte(phys, prot);
break;
default:
pte = mfn_pte(phys, prot);
break;
}
__native_set_fixmap(idx, pte);
#ifdef CONFIG_X86_64
/* Replicate changes to map the vsyscall page into the user
pagetable vsyscall mapping. */
if (idx >= VSYSCALL_LAST_PAGE && idx <= VSYSCALL_FIRST_PAGE) {
unsigned long vaddr = __fix_to_virt(idx);
set_pte_vaddr_pud(level3_user_vsyscall, vaddr, pte);
}
#endif
}
static const struct pv_info xen_info __initdata = {
.paravirt_enabled = 1,
.shared_kernel_pmd = 0,
.name = "Xen",
};
static const struct pv_init_ops xen_init_ops __initdata = {
.patch = xen_patch,
.banner = xen_banner,
.memory_setup = xen_memory_setup,
.arch_setup = xen_arch_setup,
.post_allocator_init = xen_post_allocator_init,
};
static const struct pv_time_ops xen_time_ops __initdata = {
.time_init = xen_time_init,
.set_wallclock = xen_set_wallclock,
.get_wallclock = xen_get_wallclock,
.get_tsc_khz = xen_tsc_khz,
.sched_clock = xen_sched_clock,
};
static const struct pv_cpu_ops xen_cpu_ops __initdata = {
.cpuid = xen_cpuid,
.set_debugreg = xen_set_debugreg,
.get_debugreg = xen_get_debugreg,
.clts = xen_clts,
.read_cr0 = native_read_cr0,
.write_cr0 = xen_write_cr0,
.read_cr4 = native_read_cr4,
.read_cr4_safe = native_read_cr4_safe,
.write_cr4 = xen_write_cr4,
.wbinvd = native_wbinvd,
.read_msr = native_read_msr_safe,
.write_msr = xen_write_msr_safe,
.read_tsc = native_read_tsc,
.read_pmc = native_read_pmc,
.iret = xen_iret,
.irq_enable_sysexit = xen_sysexit,
#ifdef CONFIG_X86_64
.usergs_sysret32 = xen_sysret32,
.usergs_sysret64 = xen_sysret64,
#endif
.load_tr_desc = paravirt_nop,
.set_ldt = xen_set_ldt,
.load_gdt = xen_load_gdt,
.load_idt = xen_load_idt,
.load_tls = xen_load_tls,
#ifdef CONFIG_X86_64
.load_gs_index = xen_load_gs_index,
#endif
.alloc_ldt = xen_alloc_ldt,
.free_ldt = xen_free_ldt,
.store_gdt = native_store_gdt,
.store_idt = native_store_idt,
.store_tr = xen_store_tr,
.write_ldt_entry = xen_write_ldt_entry,
.write_gdt_entry = xen_write_gdt_entry,
.write_idt_entry = xen_write_idt_entry,
.load_sp0 = xen_load_sp0,
.set_iopl_mask = xen_set_iopl_mask,
.io_delay = xen_io_delay,
/* Xen takes care of %gs when switching to usermode for us */
.swapgs = paravirt_nop,
.lazy_mode = {
.enter = paravirt_enter_lazy_cpu,
.leave = xen_leave_lazy,
},
};
static const struct pv_apic_ops xen_apic_ops __initdata = {
#ifdef CONFIG_X86_LOCAL_APIC
.setup_boot_clock = paravirt_nop,
.setup_secondary_clock = paravirt_nop,
.startup_ipi_hook = paravirt_nop,
#endif
};
static const struct pv_mmu_ops xen_mmu_ops __initdata = {
.pagetable_setup_start = xen_pagetable_setup_start,
.pagetable_setup_done = xen_pagetable_setup_done,
.read_cr2 = xen_read_cr2,
.write_cr2 = xen_write_cr2,
.read_cr3 = xen_read_cr3,
.write_cr3 = xen_write_cr3,
.flush_tlb_user = xen_flush_tlb,
.flush_tlb_kernel = xen_flush_tlb,
.flush_tlb_single = xen_flush_tlb_single,
.flush_tlb_others = xen_flush_tlb_others,
.pte_update = paravirt_nop,
.pte_update_defer = paravirt_nop,
.pgd_alloc = xen_pgd_alloc,
.pgd_free = xen_pgd_free,
.alloc_pte = xen_alloc_pte_init,
.release_pte = xen_release_pte_init,
.alloc_pmd = xen_alloc_pte_init,
.alloc_pmd_clone = paravirt_nop,
.release_pmd = xen_release_pte_init,
#ifdef CONFIG_HIGHPTE
.kmap_atomic_pte = xen_kmap_atomic_pte,
#endif
#ifdef CONFIG_X86_64
.set_pte = xen_set_pte,
#else
.set_pte = xen_set_pte_init,
#endif
.set_pte_at = xen_set_pte_at,
.set_pmd = xen_set_pmd_hyper,
.ptep_modify_prot_start = __ptep_modify_prot_start,
.ptep_modify_prot_commit = __ptep_modify_prot_commit,
.pte_val = xen_pte_val,
.pte_flags = native_pte_flags,
.pgd_val = xen_pgd_val,
.make_pte = xen_make_pte,
.make_pgd = xen_make_pgd,
#ifdef CONFIG_X86_PAE
.set_pte_atomic = xen_set_pte_atomic,
.set_pte_present = xen_set_pte_at,
.pte_clear = xen_pte_clear,
.pmd_clear = xen_pmd_clear,
#endif /* CONFIG_X86_PAE */
.set_pud = xen_set_pud_hyper,
.make_pmd = xen_make_pmd,
.pmd_val = xen_pmd_val,
#if PAGETABLE_LEVELS == 4
.pud_val = xen_pud_val,
.make_pud = xen_make_pud,
.set_pgd = xen_set_pgd_hyper,
.alloc_pud = xen_alloc_pte_init,
.release_pud = xen_release_pte_init,
#endif /* PAGETABLE_LEVELS == 4 */
.activate_mm = xen_activate_mm,
.dup_mmap = xen_dup_mmap,
.exit_mmap = xen_exit_mmap,
.lazy_mode = {
.enter = paravirt_enter_lazy_mmu,
.leave = xen_leave_lazy,
},
.set_fixmap = xen_set_fixmap,
};
static void xen_reboot(int reason)
{
struct sched_shutdown r = { .reason = reason };
#ifdef CONFIG_SMP
smp_send_stop();
#endif
if (HYPERVISOR_sched_op(SCHEDOP_shutdown, &r))
BUG();
}
static void xen_restart(char *msg)
{
xen_reboot(SHUTDOWN_reboot);
}
static void xen_emergency_restart(void)
{
xen_reboot(SHUTDOWN_reboot);
}
static void xen_machine_halt(void)
{
xen_reboot(SHUTDOWN_poweroff);
}
static void xen_crash_shutdown(struct pt_regs *regs)
{
xen_reboot(SHUTDOWN_crash);
}
static const struct machine_ops __initdata xen_machine_ops = {
.restart = xen_restart,
.halt = xen_machine_halt,
.power_off = xen_machine_halt,
.shutdown = xen_machine_halt,
.crash_shutdown = xen_crash_shutdown,
.emergency_restart = xen_emergency_restart,
};
static void __init xen_reserve_top(void)
{
#ifdef CONFIG_X86_32
unsigned long top = HYPERVISOR_VIRT_START;
struct xen_platform_parameters pp;
if (HYPERVISOR_xen_version(XENVER_platform_parameters, &pp) == 0)
top = pp.virt_start;
reserve_top_address(-top);
#endif /* CONFIG_X86_32 */
}
/*
* Like __va(), but returns address in the kernel mapping (which is
* all we have until the physical memory mapping has been set up.
*/
static void *__ka(phys_addr_t paddr)
{
#ifdef CONFIG_X86_64
return (void *)(paddr + __START_KERNEL_map);
#else
return __va(paddr);
#endif
}
/* Convert a machine address to physical address */
static unsigned long m2p(phys_addr_t maddr)
{
phys_addr_t paddr;
maddr &= PTE_PFN_MASK;
paddr = mfn_to_pfn(maddr >> PAGE_SHIFT) << PAGE_SHIFT;
return paddr;
}
/* Convert a machine address to kernel virtual */
static void *m2v(phys_addr_t maddr)
{
return __ka(m2p(maddr));
}
static void set_page_prot(void *addr, pgprot_t prot)
{
unsigned long pfn = __pa(addr) >> PAGE_SHIFT;
pte_t pte = pfn_pte(pfn, prot);
if (HYPERVISOR_update_va_mapping((unsigned long)addr, pte, 0))
BUG();
}
static __init void xen_map_identity_early(pmd_t *pmd, unsigned long max_pfn)
{
unsigned pmdidx, pteidx;
unsigned ident_pte;
unsigned long pfn;
ident_pte = 0;
pfn = 0;
for (pmdidx = 0; pmdidx < PTRS_PER_PMD && pfn < max_pfn; pmdidx++) {
pte_t *pte_page;
/* Reuse or allocate a page of ptes */
if (pmd_present(pmd[pmdidx]))
pte_page = m2v(pmd[pmdidx].pmd);
else {
/* Check for free pte pages */
if (ident_pte == ARRAY_SIZE(level1_ident_pgt))
break;
pte_page = &level1_ident_pgt[ident_pte];
ident_pte += PTRS_PER_PTE;
pmd[pmdidx] = __pmd(__pa(pte_page) | _PAGE_TABLE);
}
/* Install mappings */
for (pteidx = 0; pteidx < PTRS_PER_PTE; pteidx++, pfn++) {
pte_t pte;
if (pfn > max_pfn_mapped)
max_pfn_mapped = pfn;
if (!pte_none(pte_page[pteidx]))
continue;
pte = pfn_pte(pfn, PAGE_KERNEL_EXEC);
pte_page[pteidx] = pte;
}
}
for (pteidx = 0; pteidx < ident_pte; pteidx += PTRS_PER_PTE)
set_page_prot(&level1_ident_pgt[pteidx], PAGE_KERNEL_RO);
set_page_prot(pmd, PAGE_KERNEL_RO);
}
#ifdef CONFIG_X86_64
static void convert_pfn_mfn(void *v)
{
pte_t *pte = v;
int i;
/* All levels are converted the same way, so just treat them
as ptes. */
for (i = 0; i < PTRS_PER_PTE; i++)
pte[i] = xen_make_pte(pte[i].pte);
}
/*
* Set up the inital kernel pagetable.
*
* We can construct this by grafting the Xen provided pagetable into
* head_64.S's preconstructed pagetables. We copy the Xen L2's into
* level2_ident_pgt, level2_kernel_pgt and level2_fixmap_pgt. This
* means that only the kernel has a physical mapping to start with -
* but that's enough to get __va working. We need to fill in the rest
* of the physical mapping once some sort of allocator has been set
* up.
*/
static __init pgd_t *xen_setup_kernel_pagetable(pgd_t *pgd,
unsigned long max_pfn)
{
pud_t *l3;
pmd_t *l2;
/* Zap identity mapping */
init_level4_pgt[0] = __pgd(0);
/* Pre-constructed entries are in pfn, so convert to mfn */
convert_pfn_mfn(init_level4_pgt);
convert_pfn_mfn(level3_ident_pgt);
convert_pfn_mfn(level3_kernel_pgt);
l3 = m2v(pgd[pgd_index(__START_KERNEL_map)].pgd);
l2 = m2v(l3[pud_index(__START_KERNEL_map)].pud);
memcpy(level2_ident_pgt, l2, sizeof(pmd_t) * PTRS_PER_PMD);
memcpy(level2_kernel_pgt, l2, sizeof(pmd_t) * PTRS_PER_PMD);
l3 = m2v(pgd[pgd_index(__START_KERNEL_map + PMD_SIZE)].pgd);
l2 = m2v(l3[pud_index(__START_KERNEL_map + PMD_SIZE)].pud);
memcpy(level2_fixmap_pgt, l2, sizeof(pmd_t) * PTRS_PER_PMD);
/* Set up identity map */
xen_map_identity_early(level2_ident_pgt, max_pfn);
/* Make pagetable pieces RO */
set_page_prot(init_level4_pgt, PAGE_KERNEL_RO);
set_page_prot(level3_ident_pgt, PAGE_KERNEL_RO);
set_page_prot(level3_kernel_pgt, PAGE_KERNEL_RO);
set_page_prot(level3_user_vsyscall, PAGE_KERNEL_RO);
set_page_prot(level2_kernel_pgt, PAGE_KERNEL_RO);
set_page_prot(level2_fixmap_pgt, PAGE_KERNEL_RO);
/* Pin down new L4 */
pin_pagetable_pfn(MMUEXT_PIN_L4_TABLE,
PFN_DOWN(__pa_symbol(init_level4_pgt)));
/* Unpin Xen-provided one */
pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, PFN_DOWN(__pa(pgd)));
/* Switch over */
pgd = init_level4_pgt;
/*
* At this stage there can be no user pgd, and no page
* structure to attach it to, so make sure we just set kernel
* pgd.
*/
xen_mc_batch();
__xen_write_cr3(true, __pa(pgd));
xen_mc_issue(PARAVIRT_LAZY_CPU);
reserve_early(__pa(xen_start_info->pt_base),
__pa(xen_start_info->pt_base +
xen_start_info->nr_pt_frames * PAGE_SIZE),
"XEN PAGETABLES");
return pgd;
}
#else /* !CONFIG_X86_64 */
static pmd_t level2_kernel_pgt[PTRS_PER_PMD] __page_aligned_bss;
static __init pgd_t *xen_setup_kernel_pagetable(pgd_t *pgd,
unsigned long max_pfn)
{
pmd_t *kernel_pmd;
init_pg_tables_start = __pa(pgd);
init_pg_tables_end = __pa(pgd) + xen_start_info->nr_pt_frames*PAGE_SIZE;
max_pfn_mapped = PFN_DOWN(init_pg_tables_end + 512*1024);
kernel_pmd = m2v(pgd[KERNEL_PGD_BOUNDARY].pgd);
memcpy(level2_kernel_pgt, kernel_pmd, sizeof(pmd_t) * PTRS_PER_PMD);
xen_map_identity_early(level2_kernel_pgt, max_pfn);
memcpy(swapper_pg_dir, pgd, sizeof(pgd_t) * PTRS_PER_PGD);
set_pgd(&swapper_pg_dir[KERNEL_PGD_BOUNDARY],
__pgd(__pa(level2_kernel_pgt) | _PAGE_PRESENT));
set_page_prot(level2_kernel_pgt, PAGE_KERNEL_RO);
set_page_prot(swapper_pg_dir, PAGE_KERNEL_RO);
set_page_prot(empty_zero_page, PAGE_KERNEL_RO);
pin_pagetable_pfn(MMUEXT_UNPIN_TABLE, PFN_DOWN(__pa(pgd)));
xen_write_cr3(__pa(swapper_pg_dir));
pin_pagetable_pfn(MMUEXT_PIN_L3_TABLE, PFN_DOWN(__pa(swapper_pg_dir)));
return swapper_pg_dir;
}
#endif /* CONFIG_X86_64 */
/* First C function to be called on Xen boot */
asmlinkage void __init xen_start_kernel(void)
{
pgd_t *pgd;
if (!xen_start_info)
return;
xen_domain_type = XEN_PV_DOMAIN;
BUG_ON(memcmp(xen_start_info->magic, "xen-3", 5) != 0);
xen_setup_features();
/* Install Xen paravirt ops */
pv_info = xen_info;
pv_init_ops = xen_init_ops;
pv_time_ops = xen_time_ops;
pv_cpu_ops = xen_cpu_ops;
pv_apic_ops = xen_apic_ops;
pv_mmu_ops = xen_mmu_ops;
xen_init_irq_ops();
#ifdef CONFIG_X86_LOCAL_APIC
/*
* set up the basic apic ops.
*/
apic_ops = &xen_basic_apic_ops;
#endif
if (xen_feature(XENFEAT_mmu_pt_update_preserve_ad)) {
pv_mmu_ops.ptep_modify_prot_start = xen_ptep_modify_prot_start;
pv_mmu_ops.ptep_modify_prot_commit = xen_ptep_modify_prot_commit;
}
machine_ops = xen_machine_ops;
#ifdef CONFIG_X86_64
/* Disable until direct per-cpu data access. */
have_vcpu_info_placement = 0;
x86_64_init_pda();
#endif
xen_smp_init();
/* Get mfn list */
if (!xen_feature(XENFEAT_auto_translated_physmap))
xen_build_dynamic_phys_to_machine();
pgd = (pgd_t *)xen_start_info->pt_base;
/* Prevent unwanted bits from being set in PTEs. */
__supported_pte_mask &= ~_PAGE_GLOBAL;
if (!xen_initial_domain())
__supported_pte_mask &= ~(_PAGE_PWT | _PAGE_PCD);
/* Don't do the full vcpu_info placement stuff until we have a
possible map and a non-dummy shared_info. */
per_cpu(xen_vcpu, 0) = &HYPERVISOR_shared_info->vcpu_info[0];
local_irq_disable();
early_boot_irqs_off();
xen_raw_console_write("mapping kernel into physical memory\n");
pgd = xen_setup_kernel_pagetable(pgd, xen_start_info->nr_pages);
init_mm.pgd = pgd;
/* keep using Xen gdt for now; no urgent need to change it */
pv_info.kernel_rpl = 1;
if (xen_feature(XENFEAT_supervisor_mode_kernel))
pv_info.kernel_rpl = 0;
/* set the limit of our address space */
xen_reserve_top();
#ifdef CONFIG_X86_32
/* set up basic CPUID stuff */
cpu_detect(&new_cpu_data);
new_cpu_data.hard_math = 1;
new_cpu_data.x86_capability[0] = cpuid_edx(1);
#endif
/* Poke various useful things into boot_params */
boot_params.hdr.type_of_loader = (9 << 4) | 0;
boot_params.hdr.ramdisk_image = xen_start_info->mod_start
? __pa(xen_start_info->mod_start) : 0;
boot_params.hdr.ramdisk_size = xen_start_info->mod_len;
boot_params.hdr.cmd_line_ptr = __pa(xen_start_info->cmd_line);
if (!xen_initial_domain()) {
add_preferred_console("xenboot", 0, NULL);
add_preferred_console("tty", 0, NULL);
add_preferred_console("hvc", 0, NULL);
}
xen_raw_console_write("about to get started...\n");
/* Start the world */
#ifdef CONFIG_X86_32
i386_start_kernel();
#else
x86_64_start_reservations((char *)__pa_symbol(&boot_params));
#endif
}
| gpl-2.0 |
CyanogenMod/android_kernel_asus_tf700t | drivers/video/omap2/dss/display.c | 391 | 13285 | /*
* linux/drivers/video/omap2/dss/display.c
*
* Copyright (C) 2009 Nokia Corporation
* Author: Tomi Valkeinen <tomi.valkeinen@nokia.com>
*
* Some code and ideas taken from drivers/video/omap/ driver
* by Imre Deak.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define DSS_SUBSYS_NAME "DISPLAY"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <video/omapdss.h>
#include "dss.h"
#include "dss_features.h"
static ssize_t display_enabled_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
bool enabled = dssdev->state != OMAP_DSS_DISPLAY_DISABLED;
return snprintf(buf, PAGE_SIZE, "%d\n", enabled);
}
static ssize_t display_enabled_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int r, enabled;
r = kstrtoint(buf, 0, &enabled);
if (r)
return r;
enabled = !!enabled;
if (enabled != (dssdev->state != OMAP_DSS_DISPLAY_DISABLED)) {
if (enabled) {
r = dssdev->driver->enable(dssdev);
if (r)
return r;
} else {
dssdev->driver->disable(dssdev);
}
}
return size;
}
static ssize_t display_tear_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
return snprintf(buf, PAGE_SIZE, "%d\n",
dssdev->driver->get_te ?
dssdev->driver->get_te(dssdev) : 0);
}
static ssize_t display_tear_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int te, r;
if (!dssdev->driver->enable_te || !dssdev->driver->get_te)
return -ENOENT;
r = kstrtoint(buf, 0, &te);
if (r)
return r;
te = !!te;
r = dssdev->driver->enable_te(dssdev, te);
if (r)
return r;
return size;
}
static ssize_t display_timings_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
struct omap_video_timings t;
if (!dssdev->driver->get_timings)
return -ENOENT;
dssdev->driver->get_timings(dssdev, &t);
return snprintf(buf, PAGE_SIZE, "%u,%u/%u/%u/%u,%u/%u/%u/%u\n",
t.pixel_clock,
t.x_res, t.hfp, t.hbp, t.hsw,
t.y_res, t.vfp, t.vbp, t.vsw);
}
static ssize_t display_timings_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
struct omap_video_timings t;
int r, found;
if (!dssdev->driver->set_timings || !dssdev->driver->check_timings)
return -ENOENT;
found = 0;
#ifdef CONFIG_OMAP2_DSS_VENC
if (strncmp("pal", buf, 3) == 0) {
t = omap_dss_pal_timings;
found = 1;
} else if (strncmp("ntsc", buf, 4) == 0) {
t = omap_dss_ntsc_timings;
found = 1;
}
#endif
if (!found && sscanf(buf, "%u,%hu/%hu/%hu/%hu,%hu/%hu/%hu/%hu",
&t.pixel_clock,
&t.x_res, &t.hfp, &t.hbp, &t.hsw,
&t.y_res, &t.vfp, &t.vbp, &t.vsw) != 9)
return -EINVAL;
r = dssdev->driver->check_timings(dssdev, &t);
if (r)
return r;
dssdev->driver->set_timings(dssdev, &t);
return size;
}
static ssize_t display_rotate_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int rotate;
if (!dssdev->driver->get_rotate)
return -ENOENT;
rotate = dssdev->driver->get_rotate(dssdev);
return snprintf(buf, PAGE_SIZE, "%u\n", rotate);
}
static ssize_t display_rotate_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int rot, r;
if (!dssdev->driver->set_rotate || !dssdev->driver->get_rotate)
return -ENOENT;
r = kstrtoint(buf, 0, &rot);
if (r)
return r;
r = dssdev->driver->set_rotate(dssdev, rot);
if (r)
return r;
return size;
}
static ssize_t display_mirror_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int mirror;
if (!dssdev->driver->get_mirror)
return -ENOENT;
mirror = dssdev->driver->get_mirror(dssdev);
return snprintf(buf, PAGE_SIZE, "%u\n", mirror);
}
static ssize_t display_mirror_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int mirror, r;
if (!dssdev->driver->set_mirror || !dssdev->driver->get_mirror)
return -ENOENT;
r = kstrtoint(buf, 0, &mirror);
if (r)
return r;
mirror = !!mirror;
r = dssdev->driver->set_mirror(dssdev, mirror);
if (r)
return r;
return size;
}
static ssize_t display_wss_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
unsigned int wss;
if (!dssdev->driver->get_wss)
return -ENOENT;
wss = dssdev->driver->get_wss(dssdev);
return snprintf(buf, PAGE_SIZE, "0x%05x\n", wss);
}
static ssize_t display_wss_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
u32 wss;
int r;
if (!dssdev->driver->get_wss || !dssdev->driver->set_wss)
return -ENOENT;
r = kstrtou32(buf, 0, &wss);
if (r)
return r;
if (wss > 0xfffff)
return -EINVAL;
r = dssdev->driver->set_wss(dssdev, wss);
if (r)
return r;
return size;
}
static DEVICE_ATTR(enabled, S_IRUGO|S_IWUSR,
display_enabled_show, display_enabled_store);
static DEVICE_ATTR(tear_elim, S_IRUGO|S_IWUSR,
display_tear_show, display_tear_store);
static DEVICE_ATTR(timings, S_IRUGO|S_IWUSR,
display_timings_show, display_timings_store);
static DEVICE_ATTR(rotate, S_IRUGO|S_IWUSR,
display_rotate_show, display_rotate_store);
static DEVICE_ATTR(mirror, S_IRUGO|S_IWUSR,
display_mirror_show, display_mirror_store);
static DEVICE_ATTR(wss, S_IRUGO|S_IWUSR,
display_wss_show, display_wss_store);
static struct device_attribute *display_sysfs_attrs[] = {
&dev_attr_enabled,
&dev_attr_tear_elim,
&dev_attr_timings,
&dev_attr_rotate,
&dev_attr_mirror,
&dev_attr_wss,
NULL
};
void omapdss_default_get_resolution(struct omap_dss_device *dssdev,
u16 *xres, u16 *yres)
{
*xres = dssdev->panel.timings.x_res;
*yres = dssdev->panel.timings.y_res;
}
EXPORT_SYMBOL(omapdss_default_get_resolution);
void default_get_overlay_fifo_thresholds(enum omap_plane plane,
u32 fifo_size, u32 burst_size,
u32 *fifo_low, u32 *fifo_high)
{
unsigned buf_unit = dss_feat_get_buffer_size_unit();
*fifo_high = fifo_size - buf_unit;
*fifo_low = fifo_size - burst_size;
}
int omapdss_default_get_recommended_bpp(struct omap_dss_device *dssdev)
{
switch (dssdev->type) {
case OMAP_DISPLAY_TYPE_DPI:
if (dssdev->phy.dpi.data_lines == 24)
return 24;
else
return 16;
case OMAP_DISPLAY_TYPE_DBI:
case OMAP_DISPLAY_TYPE_DSI:
if (dssdev->ctrl.pixel_size == 24)
return 24;
else
return 16;
case OMAP_DISPLAY_TYPE_VENC:
case OMAP_DISPLAY_TYPE_SDI:
case OMAP_DISPLAY_TYPE_HDMI:
return 24;
default:
BUG();
}
}
EXPORT_SYMBOL(omapdss_default_get_recommended_bpp);
/* Checks if replication logic should be used. Only use for active matrix,
* when overlay is in RGB12U or RGB16 mode, and LCD interface is
* 18bpp or 24bpp */
bool dss_use_replication(struct omap_dss_device *dssdev,
enum omap_color_mode mode)
{
int bpp;
if (mode != OMAP_DSS_COLOR_RGB12U && mode != OMAP_DSS_COLOR_RGB16)
return false;
if (dssdev->type == OMAP_DISPLAY_TYPE_DPI &&
(dssdev->panel.config & OMAP_DSS_LCD_TFT) == 0)
return false;
switch (dssdev->type) {
case OMAP_DISPLAY_TYPE_DPI:
bpp = dssdev->phy.dpi.data_lines;
break;
case OMAP_DISPLAY_TYPE_HDMI:
case OMAP_DISPLAY_TYPE_VENC:
case OMAP_DISPLAY_TYPE_SDI:
bpp = 24;
break;
case OMAP_DISPLAY_TYPE_DBI:
case OMAP_DISPLAY_TYPE_DSI:
bpp = dssdev->ctrl.pixel_size;
break;
default:
BUG();
}
return bpp > 16;
}
void dss_init_device(struct platform_device *pdev,
struct omap_dss_device *dssdev)
{
struct device_attribute *attr;
int i;
int r;
switch (dssdev->type) {
#ifdef CONFIG_OMAP2_DSS_DPI
case OMAP_DISPLAY_TYPE_DPI:
r = dpi_init_display(dssdev);
break;
#endif
#ifdef CONFIG_OMAP2_DSS_RFBI
case OMAP_DISPLAY_TYPE_DBI:
r = rfbi_init_display(dssdev);
break;
#endif
#ifdef CONFIG_OMAP2_DSS_VENC
case OMAP_DISPLAY_TYPE_VENC:
r = venc_init_display(dssdev);
break;
#endif
#ifdef CONFIG_OMAP2_DSS_SDI
case OMAP_DISPLAY_TYPE_SDI:
r = sdi_init_display(dssdev);
break;
#endif
#ifdef CONFIG_OMAP2_DSS_DSI
case OMAP_DISPLAY_TYPE_DSI:
r = dsi_init_display(dssdev);
break;
#endif
case OMAP_DISPLAY_TYPE_HDMI:
r = hdmi_init_display(dssdev);
break;
default:
DSSERR("Support for display '%s' not compiled in.\n",
dssdev->name);
return;
}
if (r) {
DSSERR("failed to init display %s\n", dssdev->name);
return;
}
/* create device sysfs files */
i = 0;
while ((attr = display_sysfs_attrs[i++]) != NULL) {
r = device_create_file(&dssdev->dev, attr);
if (r)
DSSERR("failed to create sysfs file\n");
}
/* create display? sysfs links */
r = sysfs_create_link(&pdev->dev.kobj, &dssdev->dev.kobj,
dev_name(&dssdev->dev));
if (r)
DSSERR("failed to create sysfs display link\n");
}
void dss_uninit_device(struct platform_device *pdev,
struct omap_dss_device *dssdev)
{
struct device_attribute *attr;
int i = 0;
sysfs_remove_link(&pdev->dev.kobj, dev_name(&dssdev->dev));
while ((attr = display_sysfs_attrs[i++]) != NULL)
device_remove_file(&dssdev->dev, attr);
if (dssdev->manager)
dssdev->manager->unset_device(dssdev->manager);
}
static int dss_suspend_device(struct device *dev, void *data)
{
int r;
struct omap_dss_device *dssdev = to_dss_device(dev);
if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE) {
dssdev->activate_after_resume = false;
return 0;
}
if (!dssdev->driver->suspend) {
DSSERR("display '%s' doesn't implement suspend\n",
dssdev->name);
return -ENOSYS;
}
r = dssdev->driver->suspend(dssdev);
if (r)
return r;
dssdev->activate_after_resume = true;
return 0;
}
int dss_suspend_all_devices(void)
{
int r;
struct bus_type *bus = dss_get_bus();
r = bus_for_each_dev(bus, NULL, NULL, dss_suspend_device);
if (r) {
/* resume all displays that were suspended */
dss_resume_all_devices();
return r;
}
return 0;
}
static int dss_resume_device(struct device *dev, void *data)
{
int r;
struct omap_dss_device *dssdev = to_dss_device(dev);
if (dssdev->activate_after_resume && dssdev->driver->resume) {
r = dssdev->driver->resume(dssdev);
if (r)
return r;
}
dssdev->activate_after_resume = false;
return 0;
}
int dss_resume_all_devices(void)
{
struct bus_type *bus = dss_get_bus();
return bus_for_each_dev(bus, NULL, NULL, dss_resume_device);
}
static int dss_disable_device(struct device *dev, void *data)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
if (dssdev->state != OMAP_DSS_DISPLAY_DISABLED)
dssdev->driver->disable(dssdev);
return 0;
}
void dss_disable_all_devices(void)
{
struct bus_type *bus = dss_get_bus();
bus_for_each_dev(bus, NULL, NULL, dss_disable_device);
}
void omap_dss_get_device(struct omap_dss_device *dssdev)
{
get_device(&dssdev->dev);
}
EXPORT_SYMBOL(omap_dss_get_device);
void omap_dss_put_device(struct omap_dss_device *dssdev)
{
put_device(&dssdev->dev);
}
EXPORT_SYMBOL(omap_dss_put_device);
/* ref count of the found device is incremented. ref count
* of from-device is decremented. */
struct omap_dss_device *omap_dss_get_next_device(struct omap_dss_device *from)
{
struct device *dev;
struct device *dev_start = NULL;
struct omap_dss_device *dssdev = NULL;
int match(struct device *dev, void *data)
{
return 1;
}
if (from)
dev_start = &from->dev;
dev = bus_find_device(dss_get_bus(), dev_start, NULL, match);
if (dev)
dssdev = to_dss_device(dev);
if (from)
put_device(&from->dev);
return dssdev;
}
EXPORT_SYMBOL(omap_dss_get_next_device);
struct omap_dss_device *omap_dss_find_device(void *data,
int (*match)(struct omap_dss_device *dssdev, void *data))
{
struct omap_dss_device *dssdev = NULL;
while ((dssdev = omap_dss_get_next_device(dssdev)) != NULL) {
if (match(dssdev, data))
return dssdev;
}
return NULL;
}
EXPORT_SYMBOL(omap_dss_find_device);
int omap_dss_start_device(struct omap_dss_device *dssdev)
{
if (!dssdev->driver) {
DSSDBG("no driver\n");
return -ENODEV;
}
if (!try_module_get(dssdev->dev.driver->owner)) {
return -ENODEV;
}
return 0;
}
EXPORT_SYMBOL(omap_dss_start_device);
void omap_dss_stop_device(struct omap_dss_device *dssdev)
{
module_put(dssdev->dev.driver->owner);
}
EXPORT_SYMBOL(omap_dss_stop_device);
| gpl-2.0 |
pboettch/linux | arch/arm64/kernel/kgdb.c | 391 | 8822 | /*
* AArch64 KGDB support
*
* Based on arch/arm/kernel/kgdb.c
*
* Copyright (C) 2013 Cavium Inc.
* Author: Vijaya Kumar K <vijaya.kumar@caviumnetworks.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/irq.h>
#include <linux/kdebug.h>
#include <linux/kgdb.h>
#include <asm/traps.h>
struct dbg_reg_def_t dbg_reg_def[DBG_MAX_REG_NUM] = {
{ "x0", 8, offsetof(struct pt_regs, regs[0])},
{ "x1", 8, offsetof(struct pt_regs, regs[1])},
{ "x2", 8, offsetof(struct pt_regs, regs[2])},
{ "x3", 8, offsetof(struct pt_regs, regs[3])},
{ "x4", 8, offsetof(struct pt_regs, regs[4])},
{ "x5", 8, offsetof(struct pt_regs, regs[5])},
{ "x6", 8, offsetof(struct pt_regs, regs[6])},
{ "x7", 8, offsetof(struct pt_regs, regs[7])},
{ "x8", 8, offsetof(struct pt_regs, regs[8])},
{ "x9", 8, offsetof(struct pt_regs, regs[9])},
{ "x10", 8, offsetof(struct pt_regs, regs[10])},
{ "x11", 8, offsetof(struct pt_regs, regs[11])},
{ "x12", 8, offsetof(struct pt_regs, regs[12])},
{ "x13", 8, offsetof(struct pt_regs, regs[13])},
{ "x14", 8, offsetof(struct pt_regs, regs[14])},
{ "x15", 8, offsetof(struct pt_regs, regs[15])},
{ "x16", 8, offsetof(struct pt_regs, regs[16])},
{ "x17", 8, offsetof(struct pt_regs, regs[17])},
{ "x18", 8, offsetof(struct pt_regs, regs[18])},
{ "x19", 8, offsetof(struct pt_regs, regs[19])},
{ "x20", 8, offsetof(struct pt_regs, regs[20])},
{ "x21", 8, offsetof(struct pt_regs, regs[21])},
{ "x22", 8, offsetof(struct pt_regs, regs[22])},
{ "x23", 8, offsetof(struct pt_regs, regs[23])},
{ "x24", 8, offsetof(struct pt_regs, regs[24])},
{ "x25", 8, offsetof(struct pt_regs, regs[25])},
{ "x26", 8, offsetof(struct pt_regs, regs[26])},
{ "x27", 8, offsetof(struct pt_regs, regs[27])},
{ "x28", 8, offsetof(struct pt_regs, regs[28])},
{ "x29", 8, offsetof(struct pt_regs, regs[29])},
{ "x30", 8, offsetof(struct pt_regs, regs[30])},
{ "sp", 8, offsetof(struct pt_regs, sp)},
{ "pc", 8, offsetof(struct pt_regs, pc)},
{ "pstate", 8, offsetof(struct pt_regs, pstate)},
{ "v0", 16, -1 },
{ "v1", 16, -1 },
{ "v2", 16, -1 },
{ "v3", 16, -1 },
{ "v4", 16, -1 },
{ "v5", 16, -1 },
{ "v6", 16, -1 },
{ "v7", 16, -1 },
{ "v8", 16, -1 },
{ "v9", 16, -1 },
{ "v10", 16, -1 },
{ "v11", 16, -1 },
{ "v12", 16, -1 },
{ "v13", 16, -1 },
{ "v14", 16, -1 },
{ "v15", 16, -1 },
{ "v16", 16, -1 },
{ "v17", 16, -1 },
{ "v18", 16, -1 },
{ "v19", 16, -1 },
{ "v20", 16, -1 },
{ "v21", 16, -1 },
{ "v22", 16, -1 },
{ "v23", 16, -1 },
{ "v24", 16, -1 },
{ "v25", 16, -1 },
{ "v26", 16, -1 },
{ "v27", 16, -1 },
{ "v28", 16, -1 },
{ "v29", 16, -1 },
{ "v30", 16, -1 },
{ "v31", 16, -1 },
{ "fpsr", 4, -1 },
{ "fpcr", 4, -1 },
};
char *dbg_get_reg(int regno, void *mem, struct pt_regs *regs)
{
if (regno >= DBG_MAX_REG_NUM || regno < 0)
return NULL;
if (dbg_reg_def[regno].offset != -1)
memcpy(mem, (void *)regs + dbg_reg_def[regno].offset,
dbg_reg_def[regno].size);
else
memset(mem, 0, dbg_reg_def[regno].size);
return dbg_reg_def[regno].name;
}
int dbg_set_reg(int regno, void *mem, struct pt_regs *regs)
{
if (regno >= DBG_MAX_REG_NUM || regno < 0)
return -EINVAL;
if (dbg_reg_def[regno].offset != -1)
memcpy((void *)regs + dbg_reg_def[regno].offset, mem,
dbg_reg_def[regno].size);
return 0;
}
void
sleeping_thread_to_gdb_regs(unsigned long *gdb_regs, struct task_struct *task)
{
struct pt_regs *thread_regs;
/* Initialize to zero */
memset((char *)gdb_regs, 0, NUMREGBYTES);
thread_regs = task_pt_regs(task);
memcpy((void *)gdb_regs, (void *)thread_regs->regs, GP_REG_BYTES);
}
void kgdb_arch_set_pc(struct pt_regs *regs, unsigned long pc)
{
regs->pc = pc;
}
static int compiled_break;
static void kgdb_arch_update_addr(struct pt_regs *regs,
char *remcom_in_buffer)
{
unsigned long addr;
char *ptr;
ptr = &remcom_in_buffer[1];
if (kgdb_hex2long(&ptr, &addr))
kgdb_arch_set_pc(regs, addr);
else if (compiled_break == 1)
kgdb_arch_set_pc(regs, regs->pc + 4);
compiled_break = 0;
}
int kgdb_arch_handle_exception(int exception_vector, int signo,
int err_code, char *remcom_in_buffer,
char *remcom_out_buffer,
struct pt_regs *linux_regs)
{
int err;
switch (remcom_in_buffer[0]) {
case 'D':
case 'k':
/*
* Packet D (Detach), k (kill). No special handling
* is required here. Handle same as c packet.
*/
case 'c':
/*
* Packet c (Continue) to continue executing.
* Set pc to required address.
* Try to read optional parameter and set pc.
* If this was a compiled breakpoint, we need to move
* to the next instruction else we will just breakpoint
* over and over again.
*/
kgdb_arch_update_addr(linux_regs, remcom_in_buffer);
atomic_set(&kgdb_cpu_doing_single_step, -1);
kgdb_single_step = 0;
/*
* Received continue command, disable single step
*/
if (kernel_active_single_step())
kernel_disable_single_step();
err = 0;
break;
case 's':
/*
* Update step address value with address passed
* with step packet.
* On debug exception return PC is copied to ELR
* So just update PC.
* If no step address is passed, resume from the address
* pointed by PC. Do not update PC
*/
kgdb_arch_update_addr(linux_regs, remcom_in_buffer);
atomic_set(&kgdb_cpu_doing_single_step, raw_smp_processor_id());
kgdb_single_step = 1;
/*
* Enable single step handling
*/
if (!kernel_active_single_step())
kernel_enable_single_step(linux_regs);
err = 0;
break;
default:
err = -1;
}
return err;
}
static int kgdb_brk_fn(struct pt_regs *regs, unsigned int esr)
{
kgdb_handle_exception(1, SIGTRAP, 0, regs);
return 0;
}
static int kgdb_compiled_brk_fn(struct pt_regs *regs, unsigned int esr)
{
compiled_break = 1;
kgdb_handle_exception(1, SIGTRAP, 0, regs);
return 0;
}
static int kgdb_step_brk_fn(struct pt_regs *regs, unsigned int esr)
{
kgdb_handle_exception(1, SIGTRAP, 0, regs);
return 0;
}
static struct break_hook kgdb_brkpt_hook = {
.esr_mask = 0xffffffff,
.esr_val = (u32)ESR_ELx_VAL_BRK64(KGDB_DYN_DBG_BRK_IMM),
.fn = kgdb_brk_fn
};
static struct break_hook kgdb_compiled_brkpt_hook = {
.esr_mask = 0xffffffff,
.esr_val = (u32)ESR_ELx_VAL_BRK64(KGDB_COMPILED_DBG_BRK_IMM),
.fn = kgdb_compiled_brk_fn
};
static struct step_hook kgdb_step_hook = {
.fn = kgdb_step_brk_fn
};
static void kgdb_call_nmi_hook(void *ignored)
{
kgdb_nmicallback(raw_smp_processor_id(), get_irq_regs());
}
void kgdb_roundup_cpus(unsigned long flags)
{
local_irq_enable();
smp_call_function(kgdb_call_nmi_hook, NULL, 0);
local_irq_disable();
}
static int __kgdb_notify(struct die_args *args, unsigned long cmd)
{
struct pt_regs *regs = args->regs;
if (kgdb_handle_exception(1, args->signr, cmd, regs))
return NOTIFY_DONE;
return NOTIFY_STOP;
}
static int
kgdb_notify(struct notifier_block *self, unsigned long cmd, void *ptr)
{
unsigned long flags;
int ret;
local_irq_save(flags);
ret = __kgdb_notify(ptr, cmd);
local_irq_restore(flags);
return ret;
}
static struct notifier_block kgdb_notifier = {
.notifier_call = kgdb_notify,
/*
* Want to be lowest priority
*/
.priority = -INT_MAX,
};
/*
* kgdb_arch_init - Perform any architecture specific initalization.
* This function will handle the initalization of any architecture
* specific callbacks.
*/
int kgdb_arch_init(void)
{
int ret = register_die_notifier(&kgdb_notifier);
if (ret != 0)
return ret;
register_break_hook(&kgdb_brkpt_hook);
register_break_hook(&kgdb_compiled_brkpt_hook);
register_step_hook(&kgdb_step_hook);
return 0;
}
/*
* kgdb_arch_exit - Perform any architecture specific uninitalization.
* This function will handle the uninitalization of any architecture
* specific callbacks, for dynamic registration and unregistration.
*/
void kgdb_arch_exit(void)
{
unregister_break_hook(&kgdb_brkpt_hook);
unregister_break_hook(&kgdb_compiled_brkpt_hook);
unregister_step_hook(&kgdb_step_hook);
unregister_die_notifier(&kgdb_notifier);
}
/*
* ARM instructions are always in LE.
* Break instruction is encoded in LE format
*/
struct kgdb_arch arch_kgdb_ops = {
.gdb_bpt_instr = {
KGDB_DYN_BRK_INS_BYTE(0),
KGDB_DYN_BRK_INS_BYTE(1),
KGDB_DYN_BRK_INS_BYTE(2),
KGDB_DYN_BRK_INS_BYTE(3),
}
};
| gpl-2.0 |
cornedor/android_kernel_htc_enrc2b | drivers/staging/iio/dds/ad5930.c | 391 | 3644 | /*
* Driver for ADI Direct Digital Synthesis ad5930
*
* Copyright (c) 2010-2010 Analog Devices Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/types.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include "../iio.h"
#include "../sysfs.h"
#define DRV_NAME "ad5930"
#define value_mask (u16)0xf000
#define addr_shift 12
/* Register format: 4 bits addr + 12 bits value */
struct ad5903_config {
u16 control;
u16 incnum;
u16 frqdelt[2];
u16 incitvl;
u16 buritvl;
u16 strtfrq[2];
};
struct ad5930_state {
struct mutex lock;
struct spi_device *sdev;
};
static ssize_t ad5930_set_parameter(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct spi_message msg;
struct spi_transfer xfer;
int ret;
struct ad5903_config *config = (struct ad5903_config *)buf;
struct iio_dev *idev = dev_get_drvdata(dev);
struct ad5930_state *st = iio_priv(idev);
config->control = (config->control & ~value_mask);
config->incnum = (config->control & ~value_mask) | (1 << addr_shift);
config->frqdelt[0] = (config->control & ~value_mask) | (2 << addr_shift);
config->frqdelt[1] = (config->control & ~value_mask) | 3 << addr_shift;
config->incitvl = (config->control & ~value_mask) | 4 << addr_shift;
config->buritvl = (config->control & ~value_mask) | 8 << addr_shift;
config->strtfrq[0] = (config->control & ~value_mask) | 0xc << addr_shift;
config->strtfrq[1] = (config->control & ~value_mask) | 0xd << addr_shift;
xfer.len = len;
xfer.tx_buf = config;
mutex_lock(&st->lock);
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
ret = spi_sync(st->sdev, &msg);
if (ret)
goto error_ret;
error_ret:
mutex_unlock(&st->lock);
return ret ? ret : len;
}
static IIO_DEVICE_ATTR(dds, S_IWUSR, NULL, ad5930_set_parameter, 0);
static struct attribute *ad5930_attributes[] = {
&iio_dev_attr_dds.dev_attr.attr,
NULL,
};
static const struct attribute_group ad5930_attribute_group = {
.attrs = ad5930_attributes,
};
static const struct iio_info ad5930_info = {
.attrs = &ad5930_attribute_group,
.driver_module = THIS_MODULE,
};
static int __devinit ad5930_probe(struct spi_device *spi)
{
struct ad5930_state *st;
struct iio_dev *idev;
int ret = 0;
idev = iio_allocate_device(sizeof(*st));
if (idev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
spi_set_drvdata(spi, idev);
st = iio_priv(idev);
mutex_init(&st->lock);
st->sdev = spi;
idev->dev.parent = &spi->dev;
idev->info = &ad5930_info;
idev->modes = INDIO_DIRECT_MODE;
ret = iio_device_register(idev);
if (ret)
goto error_free_dev;
spi->max_speed_hz = 2000000;
spi->mode = SPI_MODE_3;
spi->bits_per_word = 16;
spi_setup(spi);
return 0;
error_free_dev:
iio_free_device(idev);
error_ret:
return ret;
}
static int __devexit ad5930_remove(struct spi_device *spi)
{
iio_device_unregister(spi_get_drvdata(spi));
return 0;
}
static struct spi_driver ad5930_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ad5930_probe,
.remove = __devexit_p(ad5930_remove),
};
static __init int ad5930_spi_init(void)
{
return spi_register_driver(&ad5930_driver);
}
module_init(ad5930_spi_init);
static __exit void ad5930_spi_exit(void)
{
spi_unregister_driver(&ad5930_driver);
}
module_exit(ad5930_spi_exit);
MODULE_AUTHOR("Cliff Cai");
MODULE_DESCRIPTION("Analog Devices ad5930 driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
fosser2/linux-2.6 | drivers/staging/iio/addac/adt7316.c | 391 | 58444 | /*
* ADT7316 digital temperature sensor driver supporting ADT7316/7/8 ADT7516/7/9
*
*
* Copyright 2010 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/workqueue.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/list.h>
#include <linux/i2c.h>
#include <linux/rtc.h>
#include "../iio.h"
#include "../sysfs.h"
#include "adt7316.h"
/*
* ADT7316 registers definition
*/
#define ADT7316_INT_STAT1 0x0
#define ADT7316_INT_STAT2 0x1
#define ADT7316_LSB_IN_TEMP_VDD 0x3
#define ADT7316_LSB_IN_TEMP_MASK 0x3
#define ADT7316_LSB_VDD_MASK 0xC
#define ADT7316_LSB_VDD_OFFSET 2
#define ADT7316_LSB_EX_TEMP_AIN 0x4
#define ADT7316_LSB_EX_TEMP_MASK 0x3
#define ADT7516_LSB_AIN_SHIFT 2
#define ADT7316_AD_MSB_DATA_BASE 0x6
#define ADT7316_AD_MSB_DATA_REGS 3
#define ADT7516_AD_MSB_DATA_REGS 6
#define ADT7316_MSB_VDD 0x6
#define ADT7316_MSB_IN_TEMP 0x7
#define ADT7316_MSB_EX_TEMP 0x8
#define ADT7516_MSB_AIN1 0x8
#define ADT7516_MSB_AIN2 0x9
#define ADT7516_MSB_AIN3 0xA
#define ADT7516_MSB_AIN4 0xB
#define ADT7316_DA_DATA_BASE 0x10
#define ADT7316_DA_MSB_DATA_REGS 4
#define ADT7316_LSB_DAC_A 0x10
#define ADT7316_MSB_DAC_A 0x11
#define ADT7316_LSB_DAC_B 0x12
#define ADT7316_MSB_DAC_B 0x13
#define ADT7316_LSB_DAC_C 0x14
#define ADT7316_MSB_DAC_C 0x15
#define ADT7316_LSB_DAC_D 0x16
#define ADT7316_MSB_DAC_D 0x17
#define ADT7316_CONFIG1 0x18
#define ADT7316_CONFIG2 0x19
#define ADT7316_CONFIG3 0x1A
#define ADT7316_LDAC_CONFIG 0x1B
#define ADT7316_DAC_CONFIG 0x1C
#define ADT7316_INT_MASK1 0x1D
#define ADT7316_INT_MASK2 0x1E
#define ADT7316_IN_TEMP_OFFSET 0x1F
#define ADT7316_EX_TEMP_OFFSET 0x20
#define ADT7316_IN_ANALOG_TEMP_OFFSET 0x21
#define ADT7316_EX_ANALOG_TEMP_OFFSET 0x22
#define ADT7316_VDD_HIGH 0x23
#define ADT7316_VDD_LOW 0x24
#define ADT7316_IN_TEMP_HIGH 0x25
#define ADT7316_IN_TEMP_LOW 0x26
#define ADT7316_EX_TEMP_HIGH 0x27
#define ADT7316_EX_TEMP_LOW 0x28
#define ADT7516_AIN2_HIGH 0x2B
#define ADT7516_AIN2_LOW 0x2C
#define ADT7516_AIN3_HIGH 0x2D
#define ADT7516_AIN3_LOW 0x2E
#define ADT7516_AIN4_HIGH 0x2F
#define ADT7516_AIN4_LOW 0x30
#define ADT7316_DEVICE_ID 0x4D
#define ADT7316_MANUFACTURE_ID 0x4E
#define ADT7316_DEVICE_REV 0x4F
#define ADT7316_SPI_LOCK_STAT 0x7F
/*
* ADT7316 config1
*/
#define ADT7316_EN 0x1
#define ADT7516_SEL_EX_TEMP 0x4
#define ADT7516_SEL_AIN1_2_EX_TEMP_MASK 0x6
#define ADT7516_SEL_AIN3 0x8
#define ADT7316_INT_EN 0x20
#define ADT7316_INT_POLARITY 0x40
#define ADT7316_PD 0x80
/*
* ADT7316 config2
*/
#define ADT7316_AD_SINGLE_CH_MASK 0x3
#define ADT7516_AD_SINGLE_CH_MASK 0x7
#define ADT7316_AD_SINGLE_CH_VDD 0
#define ADT7316_AD_SINGLE_CH_IN 1
#define ADT7316_AD_SINGLE_CH_EX 2
#define ADT7516_AD_SINGLE_CH_AIN1 2
#define ADT7516_AD_SINGLE_CH_AIN2 3
#define ADT7516_AD_SINGLE_CH_AIN3 4
#define ADT7516_AD_SINGLE_CH_AIN4 5
#define ADT7316_AD_SINGLE_CH_MODE 0x10
#define ADT7316_DISABLE_AVERAGING 0x20
#define ADT7316_EN_SMBUS_TIMEOUT 0x40
#define ADT7316_RESET 0x80
/*
* ADT7316 config3
*/
#define ADT7316_ADCLK_22_5 0x1
#define ADT7316_DA_HIGH_RESOLUTION 0x2
#define ADT7316_DA_EN_VIA_DAC_LDCA 0x4
#define ADT7516_AIN_IN_VREF 0x10
#define ADT7316_EN_IN_TEMP_PROP_DACA 0x20
#define ADT7316_EN_EX_TEMP_PROP_DACB 0x40
/*
* ADT7316 DAC config
*/
#define ADT7316_DA_2VREF_CH_MASK 0xF
#define ADT7316_DA_EN_MODE_MASK 0x30
#define ADT7316_DA_EN_MODE_SINGLE 0x00
#define ADT7316_DA_EN_MODE_AB_CD 0x10
#define ADT7316_DA_EN_MODE_ABCD 0x20
#define ADT7316_DA_EN_MODE_LDAC 0x30
#define ADT7316_VREF_BYPASS_DAC_AB 0x40
#define ADT7316_VREF_BYPASS_DAC_CD 0x80
/*
* ADT7316 LDAC config
*/
#define ADT7316_LDAC_EN_DA_MASK 0xF
#define ADT7316_DAC_IN_VREF 0x10
#define ADT7516_DAC_AB_IN_VREF 0x10
#define ADT7516_DAC_CD_IN_VREF 0x20
#define ADT7516_DAC_IN_VREF_OFFSET 4
#define ADT7516_DAC_IN_VREF_MASK 0x30
/*
* ADT7316 INT_MASK2
*/
#define ADT7316_INT_MASK2_VDD 0x10
/*
* ADT7316 value masks
*/
#define ADT7316_VALUE_MASK 0xfff
#define ADT7316_T_VALUE_SIGN 0x400
#define ADT7316_T_VALUE_FLOAT_OFFSET 2
#define ADT7316_T_VALUE_FLOAT_MASK 0x2
/*
* Chip ID
*/
#define ID_ADT7316 0x1
#define ID_ADT7317 0x2
#define ID_ADT7318 0x3
#define ID_ADT7516 0x11
#define ID_ADT7517 0x12
#define ID_ADT7519 0x14
#define ID_FAMILY_MASK 0xF0
#define ID_ADT73XX 0x0
#define ID_ADT75XX 0x10
/*
* struct adt7316_chip_info - chip specifc information
*/
struct adt7316_chip_info {
struct adt7316_bus bus;
u16 ldac_pin;
u16 int_mask; /* 0x2f */
u8 config1;
u8 config2;
u8 config3;
u8 dac_config; /* DAC config */
u8 ldac_config; /* LDAC config */
u8 dac_bits; /* 8, 10, 12 */
u8 id; /* chip id */
};
/*
* Logic interrupt mask for user application to enable
* interrupts.
*/
#define ADT7316_IN_TEMP_HIGH_INT_MASK 0x1
#define ADT7316_IN_TEMP_LOW_INT_MASK 0x2
#define ADT7316_EX_TEMP_HIGH_INT_MASK 0x4
#define ADT7316_EX_TEMP_LOW_INT_MASK 0x8
#define ADT7316_EX_TEMP_FAULT_INT_MASK 0x10
#define ADT7516_AIN1_INT_MASK 0x4
#define ADT7516_AIN2_INT_MASK 0x20
#define ADT7516_AIN3_INT_MASK 0x40
#define ADT7516_AIN4_INT_MASK 0x80
#define ADT7316_VDD_INT_MASK 0x100
#define ADT7316_TEMP_INT_MASK 0x1F
#define ADT7516_AIN_INT_MASK 0xE0
#define ADT7316_TEMP_AIN_INT_MASK \
(ADT7316_TEMP_INT_MASK | ADT7316_TEMP_INT_MASK)
/*
* struct adt7316_chip_info - chip specifc information
*/
struct adt7316_limit_regs {
u16 data_high;
u16 data_low;
};
static ssize_t adt7316_show_enabled(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n", !!(chip->config1 & ADT7316_EN));
}
static ssize_t _adt7316_store_enabled(struct adt7316_chip_info *chip,
int enable)
{
u8 config1;
int ret;
if (enable)
config1 = chip->config1 | ADT7316_EN;
else
config1 = chip->config1 & ~ADT7316_EN;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG1, config1);
if (ret)
return -EIO;
chip->config1 = config1;
return ret;
}
static ssize_t adt7316_store_enabled(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
int enable;
if (!memcmp(buf, "1", 1))
enable = 1;
else
enable = 0;
if (_adt7316_store_enabled(chip, enable) < 0)
return -EIO;
else
return len;
}
static IIO_DEVICE_ATTR(enabled, S_IRUGO | S_IWUSR,
adt7316_show_enabled,
adt7316_store_enabled,
0);
static ssize_t adt7316_show_select_ex_temp(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if ((chip->id & ID_FAMILY_MASK) != ID_ADT75XX)
return -EPERM;
return sprintf(buf, "%d\n", !!(chip->config1 & ADT7516_SEL_EX_TEMP));
}
static ssize_t adt7316_store_select_ex_temp(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config1;
int ret;
if ((chip->id & ID_FAMILY_MASK) != ID_ADT75XX)
return -EPERM;
config1 = chip->config1 & (~ADT7516_SEL_EX_TEMP);
if (!memcmp(buf, "1", 1))
config1 |= ADT7516_SEL_EX_TEMP;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG1, config1);
if (ret)
return -EIO;
chip->config1 = config1;
return len;
}
static IIO_DEVICE_ATTR(select_ex_temp, S_IRUGO | S_IWUSR,
adt7316_show_select_ex_temp,
adt7316_store_select_ex_temp,
0);
static ssize_t adt7316_show_mode(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if (chip->config2 & ADT7316_AD_SINGLE_CH_MODE)
return sprintf(buf, "single_channel\n");
else
return sprintf(buf, "round_robin\n");
}
static ssize_t adt7316_store_mode(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config2;
int ret;
config2 = chip->config2 & (~ADT7316_AD_SINGLE_CH_MODE);
if (!memcmp(buf, "single_channel", 14))
config2 |= ADT7316_AD_SINGLE_CH_MODE;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG2, config2);
if (ret)
return -EIO;
chip->config2 = config2;
return len;
}
static IIO_DEVICE_ATTR(mode, S_IRUGO | S_IWUSR,
adt7316_show_mode,
adt7316_store_mode,
0);
static ssize_t adt7316_show_all_modes(struct device *dev,
struct device_attribute *attr,
char *buf)
{
return sprintf(buf, "single_channel\nround_robin\n");
}
static IIO_DEVICE_ATTR(all_modes, S_IRUGO, adt7316_show_all_modes, NULL, 0);
static ssize_t adt7316_show_ad_channel(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if (!(chip->config2 & ADT7316_AD_SINGLE_CH_MODE))
return -EPERM;
switch (chip->config2 & ADT7516_AD_SINGLE_CH_MASK) {
case ADT7316_AD_SINGLE_CH_VDD:
return sprintf(buf, "0 - VDD\n");
case ADT7316_AD_SINGLE_CH_IN:
return sprintf(buf, "1 - Internal Temperature\n");
case ADT7316_AD_SINGLE_CH_EX:
if (((chip->id & ID_FAMILY_MASK) == ID_ADT75XX) &&
(chip->config1 & ADT7516_SEL_AIN1_2_EX_TEMP_MASK) == 0)
return sprintf(buf, "2 - AIN1\n");
else
return sprintf(buf, "2 - External Temperature\n");
case ADT7516_AD_SINGLE_CH_AIN2:
if ((chip->config1 & ADT7516_SEL_AIN1_2_EX_TEMP_MASK) == 0)
return sprintf(buf, "3 - AIN2\n");
else
return sprintf(buf, "N/A\n");
case ADT7516_AD_SINGLE_CH_AIN3:
if (chip->config1 & ADT7516_SEL_AIN3)
return sprintf(buf, "4 - AIN3\n");
else
return sprintf(buf, "N/A\n");
case ADT7516_AD_SINGLE_CH_AIN4:
return sprintf(buf, "5 - AIN4\n");
default:
return sprintf(buf, "N/A\n");
}
}
static ssize_t adt7316_store_ad_channel(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config2;
unsigned long data = 0;
int ret;
if (!(chip->config2 & ADT7316_AD_SINGLE_CH_MODE))
return -EPERM;
ret = strict_strtoul(buf, 10, &data);
if (ret)
return -EINVAL;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX) {
if (data > 5)
return -EINVAL;
config2 = chip->config2 & (~ADT7516_AD_SINGLE_CH_MASK);
} else {
if (data > 2)
return -EINVAL;
config2 = chip->config2 & (~ADT7316_AD_SINGLE_CH_MASK);
}
config2 |= data;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG2, config2);
if (ret)
return -EIO;
chip->config2 = config2;
return len;
}
static IIO_DEVICE_ATTR(ad_channel, S_IRUGO | S_IWUSR,
adt7316_show_ad_channel,
adt7316_store_ad_channel,
0);
static ssize_t adt7316_show_all_ad_channels(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if (!(chip->config2 & ADT7316_AD_SINGLE_CH_MODE))
return -EPERM;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
return sprintf(buf, "0 - VDD\n1 - Internal Temperature\n"
"2 - External Temperature or AIN1\n"
"3 - AIN2\n4 - AIN3\n5 - AIN4\n");
else
return sprintf(buf, "0 - VDD\n1 - Internal Temperature\n"
"2 - External Temperature\n");
}
static IIO_DEVICE_ATTR(all_ad_channels, S_IRUGO,
adt7316_show_all_ad_channels, NULL, 0);
static ssize_t adt7316_show_disable_averaging(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n",
!!(chip->config2 & ADT7316_DISABLE_AVERAGING));
}
static ssize_t adt7316_store_disable_averaging(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config2;
int ret;
config2 = chip->config2 & (~ADT7316_DISABLE_AVERAGING);
if (!memcmp(buf, "1", 1))
config2 |= ADT7316_DISABLE_AVERAGING;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG2, config2);
if (ret)
return -EIO;
chip->config2 = config2;
return len;
}
static IIO_DEVICE_ATTR(disable_averaging, S_IRUGO | S_IWUSR,
adt7316_show_disable_averaging,
adt7316_store_disable_averaging,
0);
static ssize_t adt7316_show_enable_smbus_timeout(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n",
!!(chip->config2 & ADT7316_EN_SMBUS_TIMEOUT));
}
static ssize_t adt7316_store_enable_smbus_timeout(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config2;
int ret;
config2 = chip->config2 & (~ADT7316_EN_SMBUS_TIMEOUT);
if (!memcmp(buf, "1", 1))
config2 |= ADT7316_EN_SMBUS_TIMEOUT;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG2, config2);
if (ret)
return -EIO;
chip->config2 = config2;
return len;
}
static IIO_DEVICE_ATTR(enable_smbus_timeout, S_IRUGO | S_IWUSR,
adt7316_show_enable_smbus_timeout,
adt7316_store_enable_smbus_timeout,
0);
static ssize_t adt7316_store_reset(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config2;
int ret;
config2 = chip->config2 | ADT7316_RESET;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG2, config2);
if (ret)
return -EIO;
return len;
}
static IIO_DEVICE_ATTR(reset, S_IWUSR,
NULL,
adt7316_store_reset,
0);
static ssize_t adt7316_show_powerdown(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n", !!(chip->config1 & ADT7316_PD));
}
static ssize_t adt7316_store_powerdown(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config1;
int ret;
config1 = chip->config1 & (~ADT7316_PD);
if (!memcmp(buf, "1", 1))
config1 |= ADT7316_PD;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG1, config1);
if (ret)
return -EIO;
chip->config1 = config1;
return len;
}
static IIO_DEVICE_ATTR(powerdown, S_IRUGO | S_IWUSR,
adt7316_show_powerdown,
adt7316_store_powerdown,
0);
static ssize_t adt7316_show_fast_ad_clock(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n", !!(chip->config3 & ADT7316_ADCLK_22_5));
}
static ssize_t adt7316_store_fast_ad_clock(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config3;
int ret;
config3 = chip->config3 & (~ADT7316_ADCLK_22_5);
if (!memcmp(buf, "1", 1))
config3 |= ADT7316_ADCLK_22_5;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG3, config3);
if (ret)
return -EIO;
chip->config3 = config3;
return len;
}
static IIO_DEVICE_ATTR(fast_ad_clock, S_IRUGO | S_IWUSR,
adt7316_show_fast_ad_clock,
adt7316_store_fast_ad_clock,
0);
static ssize_t adt7316_show_da_high_resolution(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if (chip->config3 & ADT7316_DA_HIGH_RESOLUTION) {
if (chip->id == ID_ADT7316 || chip->id == ID_ADT7516)
return sprintf(buf, "1 (12 bits)\n");
else if (chip->id == ID_ADT7317 || chip->id == ID_ADT7517)
return sprintf(buf, "1 (10 bits)\n");
}
return sprintf(buf, "0 (8 bits)\n");
}
static ssize_t adt7316_store_da_high_resolution(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config3;
int ret;
chip->dac_bits = 8;
if (!memcmp(buf, "1", 1)) {
config3 = chip->config3 | ADT7316_DA_HIGH_RESOLUTION;
if (chip->id == ID_ADT7316 || chip->id == ID_ADT7516)
chip->dac_bits = 12;
else if (chip->id == ID_ADT7317 || chip->id == ID_ADT7517)
chip->dac_bits = 10;
} else
config3 = chip->config3 & (~ADT7316_DA_HIGH_RESOLUTION);
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG3, config3);
if (ret)
return -EIO;
chip->config3 = config3;
return len;
}
static IIO_DEVICE_ATTR(da_high_resolution, S_IRUGO | S_IWUSR,
adt7316_show_da_high_resolution,
adt7316_store_da_high_resolution,
0);
static ssize_t adt7316_show_AIN_internal_Vref(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if ((chip->id & ID_FAMILY_MASK) != ID_ADT75XX)
return -EPERM;
return sprintf(buf, "%d\n",
!!(chip->config3 & ADT7516_AIN_IN_VREF));
}
static ssize_t adt7316_store_AIN_internal_Vref(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config3;
int ret;
if ((chip->id & ID_FAMILY_MASK) != ID_ADT75XX)
return -EPERM;
if (memcmp(buf, "1", 1))
config3 = chip->config3 & (~ADT7516_AIN_IN_VREF);
else
config3 = chip->config3 | ADT7516_AIN_IN_VREF;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG3, config3);
if (ret)
return -EIO;
chip->config3 = config3;
return len;
}
static IIO_DEVICE_ATTR(AIN_internal_Vref, S_IRUGO | S_IWUSR,
adt7316_show_AIN_internal_Vref,
adt7316_store_AIN_internal_Vref,
0);
static ssize_t adt7316_show_enable_prop_DACA(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n",
!!(chip->config3 & ADT7316_EN_IN_TEMP_PROP_DACA));
}
static ssize_t adt7316_store_enable_prop_DACA(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config3;
int ret;
config3 = chip->config3 & (~ADT7316_EN_IN_TEMP_PROP_DACA);
if (!memcmp(buf, "1", 1))
config3 |= ADT7316_EN_IN_TEMP_PROP_DACA;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG3, config3);
if (ret)
return -EIO;
chip->config3 = config3;
return len;
}
static IIO_DEVICE_ATTR(enable_proportion_DACA, S_IRUGO | S_IWUSR,
adt7316_show_enable_prop_DACA,
adt7316_store_enable_prop_DACA,
0);
static ssize_t adt7316_show_enable_prop_DACB(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n",
!!(chip->config3 & ADT7316_EN_EX_TEMP_PROP_DACB));
}
static ssize_t adt7316_store_enable_prop_DACB(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config3;
int ret;
config3 = chip->config3 & (~ADT7316_EN_EX_TEMP_PROP_DACB);
if (!memcmp(buf, "1", 1))
config3 |= ADT7316_EN_EX_TEMP_PROP_DACB;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG3, config3);
if (ret)
return -EIO;
chip->config3 = config3;
return len;
}
static IIO_DEVICE_ATTR(enable_proportion_DACB, S_IRUGO | S_IWUSR,
adt7316_show_enable_prop_DACB,
adt7316_store_enable_prop_DACB,
0);
static ssize_t adt7316_show_DAC_2Vref_ch_mask(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "0x%x\n",
chip->dac_config & ADT7316_DA_2VREF_CH_MASK);
}
static ssize_t adt7316_store_DAC_2Vref_ch_mask(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 dac_config;
unsigned long data = 0;
int ret;
ret = strict_strtoul(buf, 16, &data);
if (ret || data > ADT7316_DA_2VREF_CH_MASK)
return -EINVAL;
dac_config = chip->dac_config & (~ADT7316_DA_2VREF_CH_MASK);
dac_config |= data;
ret = chip->bus.write(chip->bus.client, ADT7316_DAC_CONFIG, dac_config);
if (ret)
return -EIO;
chip->dac_config = dac_config;
return len;
}
static IIO_DEVICE_ATTR(DAC_2Vref_channels_mask, S_IRUGO | S_IWUSR,
adt7316_show_DAC_2Vref_ch_mask,
adt7316_store_DAC_2Vref_ch_mask,
0);
static ssize_t adt7316_show_DAC_update_mode(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if (!(chip->config3 & ADT7316_DA_EN_VIA_DAC_LDCA))
return sprintf(buf, "manual\n");
else {
switch (chip->dac_config & ADT7316_DA_EN_MODE_MASK) {
case ADT7316_DA_EN_MODE_SINGLE:
return sprintf(buf, "0 - auto at any MSB DAC writing\n");
case ADT7316_DA_EN_MODE_AB_CD:
return sprintf(buf, "1 - auto at MSB DAC AB and CD writing\n");
case ADT7316_DA_EN_MODE_ABCD:
return sprintf(buf, "2 - auto at MSB DAC ABCD writing\n");
default: /* ADT7316_DA_EN_MODE_LDAC */
return sprintf(buf, "3 - manual\n");
}
}
}
static ssize_t adt7316_store_DAC_update_mode(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 dac_config;
unsigned long data;
int ret;
if (!(chip->config3 & ADT7316_DA_EN_VIA_DAC_LDCA))
return -EPERM;
ret = strict_strtoul(buf, 10, &data);
if (ret || data > ADT7316_DA_EN_MODE_MASK)
return -EINVAL;
dac_config = chip->dac_config & (~ADT7316_DA_EN_MODE_MASK);
dac_config |= data;
ret = chip->bus.write(chip->bus.client, ADT7316_DAC_CONFIG, dac_config);
if (ret)
return -EIO;
chip->dac_config = dac_config;
return len;
}
static IIO_DEVICE_ATTR(DAC_update_mode, S_IRUGO | S_IWUSR,
adt7316_show_DAC_update_mode,
adt7316_store_DAC_update_mode,
0);
static ssize_t adt7316_show_all_DAC_update_modes(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if (chip->config3 & ADT7316_DA_EN_VIA_DAC_LDCA)
return sprintf(buf, "0 - auto at any MSB DAC writing\n"
"1 - auto at MSB DAC AB and CD writing\n"
"2 - auto at MSB DAC ABCD writing\n"
"3 - manual\n");
else
return sprintf(buf, "manual\n");
}
static IIO_DEVICE_ATTR(all_DAC_update_modes, S_IRUGO,
adt7316_show_all_DAC_update_modes, NULL, 0);
static ssize_t adt7316_store_update_DAC(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 ldac_config;
unsigned long data;
int ret;
if (chip->config3 & ADT7316_DA_EN_VIA_DAC_LDCA) {
if ((chip->dac_config & ADT7316_DA_EN_MODE_MASK) !=
ADT7316_DA_EN_MODE_LDAC)
return -EPERM;
ret = strict_strtoul(buf, 16, &data);
if (ret || data > ADT7316_LDAC_EN_DA_MASK)
return -EINVAL;
ldac_config = chip->ldac_config & (~ADT7316_LDAC_EN_DA_MASK);
ldac_config |= data;
ret = chip->bus.write(chip->bus.client, ADT7316_LDAC_CONFIG,
ldac_config);
if (ret)
return -EIO;
} else {
gpio_set_value(chip->ldac_pin, 0);
gpio_set_value(chip->ldac_pin, 1);
}
return len;
}
static IIO_DEVICE_ATTR(update_DAC, S_IRUGO | S_IWUSR,
NULL,
adt7316_store_update_DAC,
0);
static ssize_t adt7316_show_DA_AB_Vref_bypass(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
return -EPERM;
return sprintf(buf, "%d\n",
!!(chip->dac_config & ADT7316_VREF_BYPASS_DAC_AB));
}
static ssize_t adt7316_store_DA_AB_Vref_bypass(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 dac_config;
int ret;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
return -EPERM;
dac_config = chip->dac_config & (~ADT7316_VREF_BYPASS_DAC_AB);
if (!memcmp(buf, "1", 1))
dac_config |= ADT7316_VREF_BYPASS_DAC_AB;
ret = chip->bus.write(chip->bus.client, ADT7316_DAC_CONFIG, dac_config);
if (ret)
return -EIO;
chip->dac_config = dac_config;
return len;
}
static IIO_DEVICE_ATTR(DA_AB_Vref_bypass, S_IRUGO | S_IWUSR,
adt7316_show_DA_AB_Vref_bypass,
adt7316_store_DA_AB_Vref_bypass,
0);
static ssize_t adt7316_show_DA_CD_Vref_bypass(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
return -EPERM;
return sprintf(buf, "%d\n",
!!(chip->dac_config & ADT7316_VREF_BYPASS_DAC_CD));
}
static ssize_t adt7316_store_DA_CD_Vref_bypass(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 dac_config;
int ret;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
return -EPERM;
dac_config = chip->dac_config & (~ADT7316_VREF_BYPASS_DAC_CD);
if (!memcmp(buf, "1", 1))
dac_config |= ADT7316_VREF_BYPASS_DAC_CD;
ret = chip->bus.write(chip->bus.client, ADT7316_DAC_CONFIG, dac_config);
if (ret)
return -EIO;
chip->dac_config = dac_config;
return len;
}
static IIO_DEVICE_ATTR(DA_CD_Vref_bypass, S_IRUGO | S_IWUSR,
adt7316_show_DA_CD_Vref_bypass,
adt7316_store_DA_CD_Vref_bypass,
0);
static ssize_t adt7316_show_DAC_internal_Vref(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
return sprintf(buf, "0x%x\n",
(chip->dac_config & ADT7516_DAC_IN_VREF_MASK) >>
ADT7516_DAC_IN_VREF_OFFSET);
else
return sprintf(buf, "%d\n",
!!(chip->dac_config & ADT7316_DAC_IN_VREF));
}
static ssize_t adt7316_store_DAC_internal_Vref(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 ldac_config;
unsigned long data;
int ret;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX) {
ret = strict_strtoul(buf, 16, &data);
if (ret || data > 3)
return -EINVAL;
ldac_config = chip->ldac_config & (~ADT7516_DAC_IN_VREF_MASK);
if (data & 0x1)
ldac_config |= ADT7516_DAC_AB_IN_VREF;
else if (data & 0x2)
ldac_config |= ADT7516_DAC_CD_IN_VREF;
} else {
ret = strict_strtoul(buf, 16, &data);
if (ret)
return -EINVAL;
ldac_config = chip->ldac_config & (~ADT7316_DAC_IN_VREF);
if (data)
ldac_config = chip->ldac_config | ADT7316_DAC_IN_VREF;
}
ret = chip->bus.write(chip->bus.client, ADT7316_LDAC_CONFIG, ldac_config);
if (ret)
return -EIO;
chip->ldac_config = ldac_config;
return len;
}
static IIO_DEVICE_ATTR(DAC_internal_Vref, S_IRUGO | S_IWUSR,
adt7316_show_DAC_internal_Vref,
adt7316_store_DAC_internal_Vref,
0);
static ssize_t adt7316_show_ad(struct adt7316_chip_info *chip,
int channel, char *buf)
{
u16 data;
u8 msb, lsb;
char sign = ' ';
int ret;
if ((chip->config2 & ADT7316_AD_SINGLE_CH_MODE) &&
channel != (chip->config2 & ADT7516_AD_SINGLE_CH_MASK))
return -EPERM;
switch (channel) {
case ADT7316_AD_SINGLE_CH_IN:
ret = chip->bus.read(chip->bus.client,
ADT7316_LSB_IN_TEMP_VDD, &lsb);
if (ret)
return -EIO;
ret = chip->bus.read(chip->bus.client,
ADT7316_AD_MSB_DATA_BASE + channel, &msb);
if (ret)
return -EIO;
data = msb << ADT7316_T_VALUE_FLOAT_OFFSET;
data |= lsb & ADT7316_LSB_IN_TEMP_MASK;
break;
case ADT7316_AD_SINGLE_CH_VDD:
ret = chip->bus.read(chip->bus.client,
ADT7316_LSB_IN_TEMP_VDD, &lsb);
if (ret)
return -EIO;
ret = chip->bus.read(chip->bus.client,
ADT7316_AD_MSB_DATA_BASE + channel, &msb);
if (ret)
return -EIO;
data = msb << ADT7316_T_VALUE_FLOAT_OFFSET;
data |= (lsb & ADT7316_LSB_VDD_MASK) >> ADT7316_LSB_VDD_OFFSET;
return sprintf(buf, "%d\n", data);
default: /* ex_temp and ain */
ret = chip->bus.read(chip->bus.client,
ADT7316_LSB_EX_TEMP_AIN, &lsb);
if (ret)
return -EIO;
ret = chip->bus.read(chip->bus.client,
ADT7316_AD_MSB_DATA_BASE + channel, &msb);
if (ret)
return -EIO;
data = msb << ADT7316_T_VALUE_FLOAT_OFFSET;
data |= lsb & (ADT7316_LSB_EX_TEMP_MASK <<
(ADT7516_LSB_AIN_SHIFT * (channel -
(ADT7316_MSB_EX_TEMP - ADT7316_AD_MSB_DATA_BASE))));
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
return sprintf(buf, "%d\n", data);
else
break;
}
if (data & ADT7316_T_VALUE_SIGN) {
/* convert supplement to positive value */
data = (ADT7316_T_VALUE_SIGN << 1) - data;
sign = '-';
}
return sprintf(buf, "%c%d.%.2d\n", sign,
(data >> ADT7316_T_VALUE_FLOAT_OFFSET),
(data & ADT7316_T_VALUE_FLOAT_MASK) * 25);
}
static ssize_t adt7316_show_VDD(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_ad(chip, ADT7316_AD_SINGLE_CH_VDD, buf);
}
static IIO_DEVICE_ATTR(VDD, S_IRUGO, adt7316_show_VDD, NULL, 0);
static ssize_t adt7316_show_in_temp(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_ad(chip, ADT7316_AD_SINGLE_CH_IN, buf);
}
static IIO_DEVICE_ATTR(in_temp, S_IRUGO, adt7316_show_in_temp, NULL, 0);
static ssize_t adt7316_show_ex_temp_AIN1(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_ad(chip, ADT7316_AD_SINGLE_CH_EX, buf);
}
static IIO_DEVICE_ATTR(ex_temp_AIN1, S_IRUGO, adt7316_show_ex_temp_AIN1, NULL, 0);
static IIO_DEVICE_ATTR(ex_temp, S_IRUGO, adt7316_show_ex_temp_AIN1, NULL, 0);
static ssize_t adt7316_show_AIN2(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_ad(chip, ADT7516_AD_SINGLE_CH_AIN2, buf);
}
static IIO_DEVICE_ATTR(AIN2, S_IRUGO, adt7316_show_AIN2, NULL, 0);
static ssize_t adt7316_show_AIN3(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_ad(chip, ADT7516_AD_SINGLE_CH_AIN3, buf);
}
static IIO_DEVICE_ATTR(AIN3, S_IRUGO, adt7316_show_AIN3, NULL, 0);
static ssize_t adt7316_show_AIN4(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_ad(chip, ADT7516_AD_SINGLE_CH_AIN4, buf);
}
static IIO_DEVICE_ATTR(AIN4, S_IRUGO, adt7316_show_AIN4, NULL, 0);
static ssize_t adt7316_show_temp_offset(struct adt7316_chip_info *chip,
int offset_addr, char *buf)
{
int data;
u8 val;
int ret;
ret = chip->bus.read(chip->bus.client, offset_addr, &val);
if (ret)
return -EIO;
data = (int)val;
if (val & 0x80)
data -= 256;
return sprintf(buf, "%d\n", data);
}
static ssize_t adt7316_store_temp_offset(struct adt7316_chip_info *chip,
int offset_addr, const char *buf, size_t len)
{
long data;
u8 val;
int ret;
ret = strict_strtol(buf, 10, &data);
if (ret || data > 127 || data < -128)
return -EINVAL;
if (data < 0)
data += 256;
val = (u8)data;
ret = chip->bus.write(chip->bus.client, offset_addr, val);
if (ret)
return -EIO;
return len;
}
static ssize_t adt7316_show_in_temp_offset(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_temp_offset(chip, ADT7316_IN_TEMP_OFFSET, buf);
}
static ssize_t adt7316_store_in_temp_offset(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_temp_offset(chip, ADT7316_IN_TEMP_OFFSET, buf, len);
}
static IIO_DEVICE_ATTR(in_temp_offset, S_IRUGO | S_IWUSR,
adt7316_show_in_temp_offset,
adt7316_store_in_temp_offset, 0);
static ssize_t adt7316_show_ex_temp_offset(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_temp_offset(chip, ADT7316_EX_TEMP_OFFSET, buf);
}
static ssize_t adt7316_store_ex_temp_offset(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_temp_offset(chip, ADT7316_EX_TEMP_OFFSET, buf, len);
}
static IIO_DEVICE_ATTR(ex_temp_offset, S_IRUGO | S_IWUSR,
adt7316_show_ex_temp_offset,
adt7316_store_ex_temp_offset, 0);
static ssize_t adt7316_show_in_analog_temp_offset(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_temp_offset(chip,
ADT7316_IN_ANALOG_TEMP_OFFSET, buf);
}
static ssize_t adt7316_store_in_analog_temp_offset(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_temp_offset(chip,
ADT7316_IN_ANALOG_TEMP_OFFSET, buf, len);
}
static IIO_DEVICE_ATTR(in_analog_temp_offset, S_IRUGO | S_IWUSR,
adt7316_show_in_analog_temp_offset,
adt7316_store_in_analog_temp_offset, 0);
static ssize_t adt7316_show_ex_analog_temp_offset(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_temp_offset(chip,
ADT7316_EX_ANALOG_TEMP_OFFSET, buf);
}
static ssize_t adt7316_store_ex_analog_temp_offset(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_temp_offset(chip,
ADT7316_EX_ANALOG_TEMP_OFFSET, buf, len);
}
static IIO_DEVICE_ATTR(ex_analog_temp_offset, S_IRUGO | S_IWUSR,
adt7316_show_ex_analog_temp_offset,
adt7316_store_ex_analog_temp_offset, 0);
static ssize_t adt7316_show_DAC(struct adt7316_chip_info *chip,
int channel, char *buf)
{
u16 data;
u8 msb, lsb, offset;
int ret;
if (channel >= ADT7316_DA_MSB_DATA_REGS ||
(channel == 0 &&
(chip->config3 & ADT7316_EN_IN_TEMP_PROP_DACA)) ||
(channel == 1 &&
(chip->config3 & ADT7316_EN_EX_TEMP_PROP_DACB)))
return -EPERM;
offset = chip->dac_bits - 8;
if (chip->dac_bits > 8) {
ret = chip->bus.read(chip->bus.client,
ADT7316_DA_DATA_BASE + channel * 2, &lsb);
if (ret)
return -EIO;
}
ret = chip->bus.read(chip->bus.client,
ADT7316_DA_DATA_BASE + 1 + channel * 2, &msb);
if (ret)
return -EIO;
data = (msb << offset) + (lsb & ((1 << offset) - 1));
return sprintf(buf, "%d\n", data);
}
static ssize_t adt7316_store_DAC(struct adt7316_chip_info *chip,
int channel, const char *buf, size_t len)
{
u8 msb, lsb, offset;
unsigned long data;
int ret;
if (channel >= ADT7316_DA_MSB_DATA_REGS ||
(channel == 0 &&
(chip->config3 & ADT7316_EN_IN_TEMP_PROP_DACA)) ||
(channel == 1 &&
(chip->config3 & ADT7316_EN_EX_TEMP_PROP_DACB)))
return -EPERM;
offset = chip->dac_bits - 8;
ret = strict_strtoul(buf, 10, &data);
if (ret || data >= (1 << chip->dac_bits))
return -EINVAL;
if (chip->dac_bits > 8) {
lsb = data & (1 << offset);
ret = chip->bus.write(chip->bus.client,
ADT7316_DA_DATA_BASE + channel * 2, lsb);
if (ret)
return -EIO;
}
msb = data >> offset;
ret = chip->bus.write(chip->bus.client,
ADT7316_DA_DATA_BASE + 1 + channel * 2, msb);
if (ret)
return -EIO;
return len;
}
static ssize_t adt7316_show_DAC_A(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_DAC(chip, 0, buf);
}
static ssize_t adt7316_store_DAC_A(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_DAC(chip, 0, buf, len);
}
static IIO_DEVICE_ATTR(DAC_A, S_IRUGO | S_IWUSR, adt7316_show_DAC_A,
adt7316_store_DAC_A, 0);
static ssize_t adt7316_show_DAC_B(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_DAC(chip, 1, buf);
}
static ssize_t adt7316_store_DAC_B(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_DAC(chip, 1, buf, len);
}
static IIO_DEVICE_ATTR(DAC_B, S_IRUGO | S_IWUSR, adt7316_show_DAC_B,
adt7316_store_DAC_B, 0);
static ssize_t adt7316_show_DAC_C(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_DAC(chip, 2, buf);
}
static ssize_t adt7316_store_DAC_C(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_DAC(chip, 2, buf, len);
}
static IIO_DEVICE_ATTR(DAC_C, S_IRUGO | S_IWUSR, adt7316_show_DAC_C,
adt7316_store_DAC_C, 0);
static ssize_t adt7316_show_DAC_D(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_show_DAC(chip, 3, buf);
}
static ssize_t adt7316_store_DAC_D(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return adt7316_store_DAC(chip, 3, buf, len);
}
static IIO_DEVICE_ATTR(DAC_D, S_IRUGO | S_IWUSR, adt7316_show_DAC_D,
adt7316_store_DAC_D, 0);
static ssize_t adt7316_show_device_id(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 id;
int ret;
ret = chip->bus.read(chip->bus.client, ADT7316_DEVICE_ID, &id);
if (ret)
return -EIO;
return sprintf(buf, "%d\n", id);
}
static IIO_DEVICE_ATTR(device_id, S_IRUGO, adt7316_show_device_id, NULL, 0);
static ssize_t adt7316_show_manufactorer_id(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 id;
int ret;
ret = chip->bus.read(chip->bus.client, ADT7316_MANUFACTURE_ID, &id);
if (ret)
return -EIO;
return sprintf(buf, "%d\n", id);
}
static IIO_DEVICE_ATTR(manufactorer_id, S_IRUGO,
adt7316_show_manufactorer_id, NULL, 0);
static ssize_t adt7316_show_device_rev(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 rev;
int ret;
ret = chip->bus.read(chip->bus.client, ADT7316_DEVICE_REV, &rev);
if (ret)
return -EIO;
return sprintf(buf, "%d\n", rev);
}
static IIO_DEVICE_ATTR(device_rev, S_IRUGO, adt7316_show_device_rev, NULL, 0);
static ssize_t adt7316_show_bus_type(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 stat;
int ret;
ret = chip->bus.read(chip->bus.client, ADT7316_SPI_LOCK_STAT, &stat);
if (ret)
return -EIO;
if (stat)
return sprintf(buf, "spi\n");
else
return sprintf(buf, "i2c\n");
}
static IIO_DEVICE_ATTR(bus_type, S_IRUGO, adt7316_show_bus_type, NULL, 0);
static struct attribute *adt7316_attributes[] = {
&iio_dev_attr_all_modes.dev_attr.attr,
&iio_dev_attr_mode.dev_attr.attr,
&iio_dev_attr_reset.dev_attr.attr,
&iio_dev_attr_enabled.dev_attr.attr,
&iio_dev_attr_ad_channel.dev_attr.attr,
&iio_dev_attr_all_ad_channels.dev_attr.attr,
&iio_dev_attr_disable_averaging.dev_attr.attr,
&iio_dev_attr_enable_smbus_timeout.dev_attr.attr,
&iio_dev_attr_powerdown.dev_attr.attr,
&iio_dev_attr_fast_ad_clock.dev_attr.attr,
&iio_dev_attr_da_high_resolution.dev_attr.attr,
&iio_dev_attr_enable_proportion_DACA.dev_attr.attr,
&iio_dev_attr_enable_proportion_DACB.dev_attr.attr,
&iio_dev_attr_DAC_2Vref_channels_mask.dev_attr.attr,
&iio_dev_attr_DAC_update_mode.dev_attr.attr,
&iio_dev_attr_all_DAC_update_modes.dev_attr.attr,
&iio_dev_attr_update_DAC.dev_attr.attr,
&iio_dev_attr_DA_AB_Vref_bypass.dev_attr.attr,
&iio_dev_attr_DA_CD_Vref_bypass.dev_attr.attr,
&iio_dev_attr_DAC_internal_Vref.dev_attr.attr,
&iio_dev_attr_VDD.dev_attr.attr,
&iio_dev_attr_in_temp.dev_attr.attr,
&iio_dev_attr_ex_temp.dev_attr.attr,
&iio_dev_attr_in_temp_offset.dev_attr.attr,
&iio_dev_attr_ex_temp_offset.dev_attr.attr,
&iio_dev_attr_in_analog_temp_offset.dev_attr.attr,
&iio_dev_attr_ex_analog_temp_offset.dev_attr.attr,
&iio_dev_attr_DAC_A.dev_attr.attr,
&iio_dev_attr_DAC_B.dev_attr.attr,
&iio_dev_attr_DAC_C.dev_attr.attr,
&iio_dev_attr_DAC_D.dev_attr.attr,
&iio_dev_attr_device_id.dev_attr.attr,
&iio_dev_attr_manufactorer_id.dev_attr.attr,
&iio_dev_attr_device_rev.dev_attr.attr,
&iio_dev_attr_bus_type.dev_attr.attr,
NULL,
};
static const struct attribute_group adt7316_attribute_group = {
.attrs = adt7316_attributes,
};
static struct attribute *adt7516_attributes[] = {
&iio_dev_attr_all_modes.dev_attr.attr,
&iio_dev_attr_mode.dev_attr.attr,
&iio_dev_attr_select_ex_temp.dev_attr.attr,
&iio_dev_attr_reset.dev_attr.attr,
&iio_dev_attr_enabled.dev_attr.attr,
&iio_dev_attr_ad_channel.dev_attr.attr,
&iio_dev_attr_all_ad_channels.dev_attr.attr,
&iio_dev_attr_disable_averaging.dev_attr.attr,
&iio_dev_attr_enable_smbus_timeout.dev_attr.attr,
&iio_dev_attr_powerdown.dev_attr.attr,
&iio_dev_attr_fast_ad_clock.dev_attr.attr,
&iio_dev_attr_AIN_internal_Vref.dev_attr.attr,
&iio_dev_attr_da_high_resolution.dev_attr.attr,
&iio_dev_attr_enable_proportion_DACA.dev_attr.attr,
&iio_dev_attr_enable_proportion_DACB.dev_attr.attr,
&iio_dev_attr_DAC_2Vref_channels_mask.dev_attr.attr,
&iio_dev_attr_DAC_update_mode.dev_attr.attr,
&iio_dev_attr_all_DAC_update_modes.dev_attr.attr,
&iio_dev_attr_update_DAC.dev_attr.attr,
&iio_dev_attr_DA_AB_Vref_bypass.dev_attr.attr,
&iio_dev_attr_DA_CD_Vref_bypass.dev_attr.attr,
&iio_dev_attr_DAC_internal_Vref.dev_attr.attr,
&iio_dev_attr_VDD.dev_attr.attr,
&iio_dev_attr_in_temp.dev_attr.attr,
&iio_dev_attr_ex_temp_AIN1.dev_attr.attr,
&iio_dev_attr_AIN2.dev_attr.attr,
&iio_dev_attr_AIN3.dev_attr.attr,
&iio_dev_attr_AIN4.dev_attr.attr,
&iio_dev_attr_in_temp_offset.dev_attr.attr,
&iio_dev_attr_ex_temp_offset.dev_attr.attr,
&iio_dev_attr_in_analog_temp_offset.dev_attr.attr,
&iio_dev_attr_ex_analog_temp_offset.dev_attr.attr,
&iio_dev_attr_DAC_A.dev_attr.attr,
&iio_dev_attr_DAC_B.dev_attr.attr,
&iio_dev_attr_DAC_C.dev_attr.attr,
&iio_dev_attr_DAC_D.dev_attr.attr,
&iio_dev_attr_device_id.dev_attr.attr,
&iio_dev_attr_manufactorer_id.dev_attr.attr,
&iio_dev_attr_device_rev.dev_attr.attr,
&iio_dev_attr_bus_type.dev_attr.attr,
NULL,
};
static const struct attribute_group adt7516_attribute_group = {
.attrs = adt7516_attributes,
};
static irqreturn_t adt7316_event_handler(int irq, void *private)
{
struct iio_dev *indio_dev = private;
struct adt7316_chip_info *chip = iio_priv(indio_dev);
u8 stat1, stat2;
int ret;
s64 time;
ret = chip->bus.read(chip->bus.client, ADT7316_INT_STAT1, &stat1);
if (!ret) {
if ((chip->id & ID_FAMILY_MASK) != ID_ADT75XX)
stat1 &= 0x1F;
time = iio_get_time_ns();
if (stat1 & (1 << 0))
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_TEMP, 0,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_RISING),
time);
if (stat1 & (1 << 1))
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_TEMP, 0,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_FALLING),
time);
if (stat1 & (1 << 2))
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_TEMP, 1,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_RISING),
time);
if (stat1 & (1 << 3))
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_TEMP, 1,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_FALLING),
time);
if (stat1 & (1 << 5))
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_IN, 1,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_EITHER),
time);
if (stat1 & (1 << 6))
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_IN, 2,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_EITHER),
time);
if (stat1 & (1 << 7))
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_IN, 3,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_EITHER),
time);
}
ret = chip->bus.read(chip->bus.client, ADT7316_INT_STAT2, &stat2);
if (!ret) {
if (stat2 & ADT7316_INT_MASK2_VDD)
iio_push_event(indio_dev, 0,
IIO_UNMOD_EVENT_CODE(IIO_IN,
0,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_RISING),
iio_get_time_ns());
}
return IRQ_HANDLED;
}
/*
* Show mask of enabled interrupts in Hex.
*/
static ssize_t adt7316_show_int_mask(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "0x%x\n", chip->int_mask);
}
/*
* Set 1 to the mask in Hex to enabled interrupts.
*/
static ssize_t adt7316_set_int_mask(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
unsigned long data;
int ret;
u8 mask;
ret = strict_strtoul(buf, 16, &data);
if (ret || data >= ADT7316_VDD_INT_MASK + 1)
return -EINVAL;
if (data & ADT7316_VDD_INT_MASK)
mask = 0; /* enable vdd int */
else
mask = ADT7316_INT_MASK2_VDD; /* disable vdd int */
ret = chip->bus.write(chip->bus.client, ADT7316_INT_MASK2, mask);
if (!ret) {
chip->int_mask &= ~ADT7316_VDD_INT_MASK;
chip->int_mask |= data & ADT7316_VDD_INT_MASK;
}
if (data & ADT7316_TEMP_AIN_INT_MASK) {
if ((chip->id & ID_FAMILY_MASK) == ID_ADT73XX)
/* mask in reg is opposite, set 1 to disable */
mask = (~data) & ADT7316_TEMP_INT_MASK;
else
/* mask in reg is opposite, set 1 to disable */
mask = (~data) & ADT7316_TEMP_AIN_INT_MASK;
}
ret = chip->bus.write(chip->bus.client, ADT7316_INT_MASK1, mask);
chip->int_mask = mask;
return len;
}
static inline ssize_t adt7316_show_ad_bound(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 val;
int data;
int ret;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT73XX &&
this_attr->address > ADT7316_EX_TEMP_LOW)
return -EPERM;
ret = chip->bus.read(chip->bus.client, this_attr->address, &val);
if (ret)
return -EIO;
data = (int)val;
if (!((chip->id & ID_FAMILY_MASK) == ID_ADT75XX &&
(chip->config1 & ADT7516_SEL_AIN1_2_EX_TEMP_MASK) == 0)) {
if (data & 0x80)
data -= 256;
}
return sprintf(buf, "%d\n", data);
}
static inline ssize_t adt7316_set_ad_bound(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
long data;
u8 val;
int ret;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT73XX &&
this_attr->address > ADT7316_EX_TEMP_LOW)
return -EPERM;
ret = strict_strtol(buf, 10, &data);
if (ret)
return -EINVAL;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX &&
(chip->config1 & ADT7516_SEL_AIN1_2_EX_TEMP_MASK) == 0) {
if (data > 255 || data < 0)
return -EINVAL;
} else {
if (data > 127 || data < -128)
return -EINVAL;
if (data < 0)
data += 256;
}
val = (u8)data;
ret = chip->bus.write(chip->bus.client, this_attr->address, val);
if (ret)
return -EIO;
return len;
}
static ssize_t adt7316_show_int_enabled(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return sprintf(buf, "%d\n", !!(chip->config1 & ADT7316_INT_EN));
}
static ssize_t adt7316_set_int_enabled(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
u8 config1;
int ret;
config1 = chip->config1 & (~ADT7316_INT_EN);
if (!memcmp(buf, "1", 1))
config1 |= ADT7316_INT_EN;
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG1, config1);
if (ret)
return -EIO;
chip->config1 = config1;
return len;
}
static IIO_DEVICE_ATTR(int_mask,
S_IRUGO | S_IWUSR,
adt7316_show_int_mask, adt7316_set_int_mask,
0);
static IIO_DEVICE_ATTR(in_temp_high_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7316_IN_TEMP_HIGH);
static IIO_DEVICE_ATTR(in_temp_low_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7316_IN_TEMP_LOW);
static IIO_DEVICE_ATTR(ex_temp_high_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7316_EX_TEMP_HIGH);
static IIO_DEVICE_ATTR(ex_temp_low_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7316_EX_TEMP_LOW);
/* NASTY duplication to be fixed */
static IIO_DEVICE_ATTR(ex_temp_ain1_high_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7316_EX_TEMP_HIGH);
static IIO_DEVICE_ATTR(ex_temp_ain1_low_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7316_EX_TEMP_LOW);
static IIO_DEVICE_ATTR(ain2_high_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7516_AIN2_HIGH);
static IIO_DEVICE_ATTR(ain2_low_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7516_AIN2_LOW);
static IIO_DEVICE_ATTR(ain3_high_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7516_AIN3_HIGH);
static IIO_DEVICE_ATTR(ain3_low_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7516_AIN3_LOW);
static IIO_DEVICE_ATTR(ain4_high_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7516_AIN4_HIGH);
static IIO_DEVICE_ATTR(ain4_low_value,
S_IRUGO | S_IWUSR,
adt7316_show_ad_bound, adt7316_set_ad_bound,
ADT7516_AIN4_LOW);
static IIO_DEVICE_ATTR(int_enabled,
S_IRUGO | S_IWUSR,
adt7316_show_int_enabled,
adt7316_set_int_enabled, 0);
static struct attribute *adt7316_event_attributes[] = {
&iio_dev_attr_int_mask.dev_attr.attr,
&iio_dev_attr_in_temp_high_value.dev_attr.attr,
&iio_dev_attr_in_temp_low_value.dev_attr.attr,
&iio_dev_attr_ex_temp_high_value.dev_attr.attr,
&iio_dev_attr_ex_temp_low_value.dev_attr.attr,
&iio_dev_attr_int_enabled.dev_attr.attr,
NULL,
};
static struct attribute_group adt7316_event_attribute_group = {
.attrs = adt7316_event_attributes,
};
static struct attribute *adt7516_event_attributes[] = {
&iio_dev_attr_int_mask.dev_attr.attr,
&iio_dev_attr_in_temp_high_value.dev_attr.attr,
&iio_dev_attr_in_temp_low_value.dev_attr.attr,
&iio_dev_attr_ex_temp_ain1_high_value.dev_attr.attr,
&iio_dev_attr_ex_temp_ain1_low_value.dev_attr.attr,
&iio_dev_attr_ain2_high_value.dev_attr.attr,
&iio_dev_attr_ain2_low_value.dev_attr.attr,
&iio_dev_attr_ain3_high_value.dev_attr.attr,
&iio_dev_attr_ain3_low_value.dev_attr.attr,
&iio_dev_attr_ain4_high_value.dev_attr.attr,
&iio_dev_attr_ain4_low_value.dev_attr.attr,
&iio_dev_attr_int_enabled.dev_attr.attr,
NULL,
};
static struct attribute_group adt7516_event_attribute_group = {
.attrs = adt7516_event_attributes,
};
#ifdef CONFIG_PM
int adt7316_disable(struct device *dev)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return _adt7316_store_enabled(chip, 0);
}
EXPORT_SYMBOL(adt7316_disable);
int adt7316_enable(struct device *dev)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(dev_info);
return _adt7316_store_enabled(chip, 1);
}
EXPORT_SYMBOL(adt7316_enable);
#endif
static const struct iio_info adt7316_info = {
.attrs = &adt7316_attribute_group,
.num_interrupt_lines = 1,
.event_attrs = &adt7316_event_attribute_group,
.driver_module = THIS_MODULE,
};
static const struct iio_info adt7516_info = {
.attrs = &adt7516_attribute_group,
.num_interrupt_lines = 1,
.event_attrs = &adt7516_event_attribute_group,
.driver_module = THIS_MODULE,
};
/*
* device probe and remove
*/
int __devinit adt7316_probe(struct device *dev, struct adt7316_bus *bus,
const char *name)
{
struct adt7316_chip_info *chip;
struct iio_dev *indio_dev;
unsigned short *adt7316_platform_data = dev->platform_data;
int ret = 0;
indio_dev = iio_allocate_device(sizeof(*chip));
if (indio_dev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
chip = iio_priv(indio_dev);
/* this is only used for device removal purposes */
dev_set_drvdata(dev, indio_dev);
chip->bus = *bus;
if (name[4] == '3')
chip->id = ID_ADT7316 + (name[6] - '6');
else if (name[4] == '5')
chip->id = ID_ADT7516 + (name[6] - '6');
else
return -ENODEV;
chip->ldac_pin = adt7316_platform_data[1];
if (chip->ldac_pin) {
chip->config3 |= ADT7316_DA_EN_VIA_DAC_LDCA;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
chip->config1 |= ADT7516_SEL_AIN3;
}
chip->int_mask = ADT7316_TEMP_INT_MASK | ADT7316_VDD_INT_MASK;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
chip->int_mask |= ADT7516_AIN_INT_MASK;
indio_dev->dev.parent = dev;
if ((chip->id & ID_FAMILY_MASK) == ID_ADT75XX)
indio_dev->info = &adt7516_info;
else
indio_dev->info = &adt7316_info;
indio_dev->name = name;
indio_dev->modes = INDIO_DIRECT_MODE;
ret = iio_device_register(indio_dev);
if (ret)
goto error_free_dev;
if (chip->bus.irq > 0) {
if (adt7316_platform_data[0])
chip->bus.irq_flags = adt7316_platform_data[0];
ret = request_threaded_irq(chip->bus.irq,
NULL,
&adt7316_event_handler,
chip->bus.irq_flags | IRQF_ONESHOT,
indio_dev->name,
indio_dev);
if (ret)
goto error_unreg_dev;
if (chip->bus.irq_flags & IRQF_TRIGGER_HIGH)
chip->config1 |= ADT7316_INT_POLARITY;
}
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG1, chip->config1);
if (ret) {
ret = -EIO;
goto error_unreg_irq;
}
ret = chip->bus.write(chip->bus.client, ADT7316_CONFIG3, chip->config3);
if (ret) {
ret = -EIO;
goto error_unreg_irq;
}
dev_info(dev, "%s temperature sensor, ADC and DAC registered.\n",
indio_dev->name);
return 0;
error_unreg_irq:
free_irq(chip->bus.irq, indio_dev);
error_unreg_dev:
iio_device_unregister(indio_dev);
error_free_dev:
iio_free_device(indio_dev);
error_ret:
return ret;
}
EXPORT_SYMBOL(adt7316_probe);
int __devexit adt7316_remove(struct device *dev)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct adt7316_chip_info *chip = iio_priv(indio_dev);
dev_set_drvdata(dev, NULL);
if (chip->bus.irq)
free_irq(chip->bus.irq, indio_dev);
iio_device_unregister(indio_dev);
iio_free_device(indio_dev);
return 0;
}
EXPORT_SYMBOL(adt7316_remove);
MODULE_AUTHOR("Sonic Zhang <sonic.zhang@analog.com>");
MODULE_DESCRIPTION("Analog Devices ADT7316/7/8 and ADT7516/7/9 digital"
" temperature sensor, ADC and DAC driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
bndmag/linux | mm/mlock.c | 391 | 20011 | /*
* linux/mm/mlock.c
*
* (C) Copyright 1995 Linus Torvalds
* (C) Copyright 2002 Christoph Hellwig
*/
#include <linux/capability.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/pagemap.h>
#include <linux/pagevec.h>
#include <linux/mempolicy.h>
#include <linux/syscalls.h>
#include <linux/sched.h>
#include <linux/export.h>
#include <linux/rmap.h>
#include <linux/mmzone.h>
#include <linux/hugetlb.h>
#include <linux/memcontrol.h>
#include <linux/mm_inline.h>
#include "internal.h"
int can_do_mlock(void)
{
if (rlimit(RLIMIT_MEMLOCK) != 0)
return 1;
if (capable(CAP_IPC_LOCK))
return 1;
return 0;
}
EXPORT_SYMBOL(can_do_mlock);
/*
* Mlocked pages are marked with PageMlocked() flag for efficient testing
* in vmscan and, possibly, the fault path; and to support semi-accurate
* statistics.
*
* An mlocked page [PageMlocked(page)] is unevictable. As such, it will
* be placed on the LRU "unevictable" list, rather than the [in]active lists.
* The unevictable list is an LRU sibling list to the [in]active lists.
* PageUnevictable is set to indicate the unevictable state.
*
* When lazy mlocking via vmscan, it is important to ensure that the
* vma's VM_LOCKED status is not concurrently being modified, otherwise we
* may have mlocked a page that is being munlocked. So lazy mlock must take
* the mmap_sem for read, and verify that the vma really is locked
* (see mm/rmap.c).
*/
/*
* LRU accounting for clear_page_mlock()
*/
void clear_page_mlock(struct page *page)
{
if (!TestClearPageMlocked(page))
return;
mod_zone_page_state(page_zone(page), NR_MLOCK,
-hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGCLEARED);
if (!isolate_lru_page(page)) {
putback_lru_page(page);
} else {
/*
* We lost the race. the page already moved to evictable list.
*/
if (PageUnevictable(page))
count_vm_event(UNEVICTABLE_PGSTRANDED);
}
}
/*
* Mark page as mlocked if not already.
* If page on LRU, isolate and putback to move to unevictable list.
*/
void mlock_vma_page(struct page *page)
{
/* Serialize with page migration */
BUG_ON(!PageLocked(page));
if (!TestSetPageMlocked(page)) {
mod_zone_page_state(page_zone(page), NR_MLOCK,
hpage_nr_pages(page));
count_vm_event(UNEVICTABLE_PGMLOCKED);
if (!isolate_lru_page(page))
putback_lru_page(page);
}
}
/*
* Isolate a page from LRU with optional get_page() pin.
* Assumes lru_lock already held and page already pinned.
*/
static bool __munlock_isolate_lru_page(struct page *page, bool getpage)
{
if (PageLRU(page)) {
struct lruvec *lruvec;
lruvec = mem_cgroup_page_lruvec(page, page_zone(page));
if (getpage)
get_page(page);
ClearPageLRU(page);
del_page_from_lru_list(page, lruvec, page_lru(page));
return true;
}
return false;
}
/*
* Finish munlock after successful page isolation
*
* Page must be locked. This is a wrapper for try_to_munlock()
* and putback_lru_page() with munlock accounting.
*/
static void __munlock_isolated_page(struct page *page)
{
int ret = SWAP_AGAIN;
/*
* Optimization: if the page was mapped just once, that's our mapping
* and we don't need to check all the other vmas.
*/
if (page_mapcount(page) > 1)
ret = try_to_munlock(page);
/* Did try_to_unlock() succeed or punt? */
if (ret != SWAP_MLOCK)
count_vm_event(UNEVICTABLE_PGMUNLOCKED);
putback_lru_page(page);
}
/*
* Accounting for page isolation fail during munlock
*
* Performs accounting when page isolation fails in munlock. There is nothing
* else to do because it means some other task has already removed the page
* from the LRU. putback_lru_page() will take care of removing the page from
* the unevictable list, if necessary. vmscan [page_referenced()] will move
* the page back to the unevictable list if some other vma has it mlocked.
*/
static void __munlock_isolation_failed(struct page *page)
{
if (PageUnevictable(page))
__count_vm_event(UNEVICTABLE_PGSTRANDED);
else
__count_vm_event(UNEVICTABLE_PGMUNLOCKED);
}
/**
* munlock_vma_page - munlock a vma page
* @page - page to be unlocked, either a normal page or THP page head
*
* returns the size of the page as a page mask (0 for normal page,
* HPAGE_PMD_NR - 1 for THP head page)
*
* called from munlock()/munmap() path with page supposedly on the LRU.
* When we munlock a page, because the vma where we found the page is being
* munlock()ed or munmap()ed, we want to check whether other vmas hold the
* page locked so that we can leave it on the unevictable lru list and not
* bother vmscan with it. However, to walk the page's rmap list in
* try_to_munlock() we must isolate the page from the LRU. If some other
* task has removed the page from the LRU, we won't be able to do that.
* So we clear the PageMlocked as we might not get another chance. If we
* can't isolate the page, we leave it for putback_lru_page() and vmscan
* [page_referenced()/try_to_unmap()] to deal with.
*/
unsigned int munlock_vma_page(struct page *page)
{
unsigned int nr_pages;
struct zone *zone = page_zone(page);
/* For try_to_munlock() and to serialize with page migration */
BUG_ON(!PageLocked(page));
/*
* Serialize with any parallel __split_huge_page_refcount() which
* might otherwise copy PageMlocked to part of the tail pages before
* we clear it in the head page. It also stabilizes hpage_nr_pages().
*/
spin_lock_irq(&zone->lru_lock);
nr_pages = hpage_nr_pages(page);
if (!TestClearPageMlocked(page))
goto unlock_out;
__mod_zone_page_state(zone, NR_MLOCK, -nr_pages);
if (__munlock_isolate_lru_page(page, true)) {
spin_unlock_irq(&zone->lru_lock);
__munlock_isolated_page(page);
goto out;
}
__munlock_isolation_failed(page);
unlock_out:
spin_unlock_irq(&zone->lru_lock);
out:
return nr_pages - 1;
}
/*
* convert get_user_pages() return value to posix mlock() error
*/
static int __mlock_posix_error_return(long retval)
{
if (retval == -EFAULT)
retval = -ENOMEM;
else if (retval == -ENOMEM)
retval = -EAGAIN;
return retval;
}
/*
* Prepare page for fast batched LRU putback via putback_lru_evictable_pagevec()
*
* The fast path is available only for evictable pages with single mapping.
* Then we can bypass the per-cpu pvec and get better performance.
* when mapcount > 1 we need try_to_munlock() which can fail.
* when !page_evictable(), we need the full redo logic of putback_lru_page to
* avoid leaving evictable page in unevictable list.
*
* In case of success, @page is added to @pvec and @pgrescued is incremented
* in case that the page was previously unevictable. @page is also unlocked.
*/
static bool __putback_lru_fast_prepare(struct page *page, struct pagevec *pvec,
int *pgrescued)
{
VM_BUG_ON_PAGE(PageLRU(page), page);
VM_BUG_ON_PAGE(!PageLocked(page), page);
if (page_mapcount(page) <= 1 && page_evictable(page)) {
pagevec_add(pvec, page);
if (TestClearPageUnevictable(page))
(*pgrescued)++;
unlock_page(page);
return true;
}
return false;
}
/*
* Putback multiple evictable pages to the LRU
*
* Batched putback of evictable pages that bypasses the per-cpu pvec. Some of
* the pages might have meanwhile become unevictable but that is OK.
*/
static void __putback_lru_fast(struct pagevec *pvec, int pgrescued)
{
count_vm_events(UNEVICTABLE_PGMUNLOCKED, pagevec_count(pvec));
/*
*__pagevec_lru_add() calls release_pages() so we don't call
* put_page() explicitly
*/
__pagevec_lru_add(pvec);
count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
}
/*
* Munlock a batch of pages from the same zone
*
* The work is split to two main phases. First phase clears the Mlocked flag
* and attempts to isolate the pages, all under a single zone lru lock.
* The second phase finishes the munlock only for pages where isolation
* succeeded.
*
* Note that the pagevec may be modified during the process.
*/
static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)
{
int i;
int nr = pagevec_count(pvec);
int delta_munlocked;
struct pagevec pvec_putback;
int pgrescued = 0;
pagevec_init(&pvec_putback, 0);
/* Phase 1: page isolation */
spin_lock_irq(&zone->lru_lock);
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (TestClearPageMlocked(page)) {
/*
* We already have pin from follow_page_mask()
* so we can spare the get_page() here.
*/
if (__munlock_isolate_lru_page(page, false))
continue;
else
__munlock_isolation_failed(page);
}
/*
* We won't be munlocking this page in the next phase
* but we still need to release the follow_page_mask()
* pin. We cannot do it under lru_lock however. If it's
* the last pin, __page_cache_release() would deadlock.
*/
pagevec_add(&pvec_putback, pvec->pages[i]);
pvec->pages[i] = NULL;
}
delta_munlocked = -nr + pagevec_count(&pvec_putback);
__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);
spin_unlock_irq(&zone->lru_lock);
/* Now we can release pins of pages that we are not munlocking */
pagevec_release(&pvec_putback);
/* Phase 2: page munlock */
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (page) {
lock_page(page);
if (!__putback_lru_fast_prepare(page, &pvec_putback,
&pgrescued)) {
/*
* Slow path. We don't want to lose the last
* pin before unlock_page()
*/
get_page(page); /* for putback_lru_page() */
__munlock_isolated_page(page);
unlock_page(page);
put_page(page); /* from follow_page_mask() */
}
}
}
/*
* Phase 3: page putback for pages that qualified for the fast path
* This will also call put_page() to return pin from follow_page_mask()
*/
if (pagevec_count(&pvec_putback))
__putback_lru_fast(&pvec_putback, pgrescued);
}
/*
* Fill up pagevec for __munlock_pagevec using pte walk
*
* The function expects that the struct page corresponding to @start address is
* a non-TPH page already pinned and in the @pvec, and that it belongs to @zone.
*
* The rest of @pvec is filled by subsequent pages within the same pmd and same
* zone, as long as the pte's are present and vm_normal_page() succeeds. These
* pages also get pinned.
*
* Returns the address of the next page that should be scanned. This equals
* @start + PAGE_SIZE when no page could be added by the pte walk.
*/
static unsigned long __munlock_pagevec_fill(struct pagevec *pvec,
struct vm_area_struct *vma, int zoneid, unsigned long start,
unsigned long end)
{
pte_t *pte;
spinlock_t *ptl;
/*
* Initialize pte walk starting at the already pinned page where we
* are sure that there is a pte, as it was pinned under the same
* mmap_sem write op.
*/
pte = get_locked_pte(vma->vm_mm, start, &ptl);
/* Make sure we do not cross the page table boundary */
end = pgd_addr_end(start, end);
end = pud_addr_end(start, end);
end = pmd_addr_end(start, end);
/* The page next to the pinned page is the first we will try to get */
start += PAGE_SIZE;
while (start < end) {
struct page *page = NULL;
pte++;
if (pte_present(*pte))
page = vm_normal_page(vma, start, *pte);
/*
* Break if page could not be obtained or the page's node+zone does not
* match
*/
if (!page || page_zone_id(page) != zoneid)
break;
get_page(page);
/*
* Increase the address that will be returned *before* the
* eventual break due to pvec becoming full by adding the page
*/
start += PAGE_SIZE;
if (pagevec_add(pvec, page) == 0)
break;
}
pte_unmap_unlock(pte, ptl);
return start;
}
/*
* munlock_vma_pages_range() - munlock all pages in the vma range.'
* @vma - vma containing range to be munlock()ed.
* @start - start address in @vma of the range
* @end - end of range in @vma.
*
* For mremap(), munmap() and exit().
*
* Called with @vma VM_LOCKED.
*
* Returns with VM_LOCKED cleared. Callers must be prepared to
* deal with this.
*
* We don't save and restore VM_LOCKED here because pages are
* still on lru. In unmap path, pages might be scanned by reclaim
* and re-mlocked by try_to_{munlock|unmap} before we unmap and
* free them. This will result in freeing mlocked pages.
*/
void munlock_vma_pages_range(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
vma->vm_flags &= ~VM_LOCKED;
while (start < end) {
struct page *page = NULL;
unsigned int page_mask;
unsigned long page_increm;
struct pagevec pvec;
struct zone *zone;
int zoneid;
pagevec_init(&pvec, 0);
/*
* Although FOLL_DUMP is intended for get_dump_page(),
* it just so happens that its special treatment of the
* ZERO_PAGE (returning an error instead of doing get_page)
* suits munlock very well (and if somehow an abnormal page
* has sneaked into the range, we won't oops here: great).
*/
page = follow_page_mask(vma, start, FOLL_GET | FOLL_DUMP,
&page_mask);
if (page && !IS_ERR(page)) {
if (PageTransHuge(page)) {
lock_page(page);
/*
* Any THP page found by follow_page_mask() may
* have gotten split before reaching
* munlock_vma_page(), so we need to recompute
* the page_mask here.
*/
page_mask = munlock_vma_page(page);
unlock_page(page);
put_page(page); /* follow_page_mask() */
} else {
/*
* Non-huge pages are handled in batches via
* pagevec. The pin from follow_page_mask()
* prevents them from collapsing by THP.
*/
pagevec_add(&pvec, page);
zone = page_zone(page);
zoneid = page_zone_id(page);
/*
* Try to fill the rest of pagevec using fast
* pte walk. This will also update start to
* the next page to process. Then munlock the
* pagevec.
*/
start = __munlock_pagevec_fill(&pvec, vma,
zoneid, start, end);
__munlock_pagevec(&pvec, zone);
goto next;
}
}
/* It's a bug to munlock in the middle of a THP page */
VM_BUG_ON((start >> PAGE_SHIFT) & page_mask);
page_increm = 1 + page_mask;
start += page_increm * PAGE_SIZE;
next:
cond_resched();
}
}
/*
* mlock_fixup - handle mlock[all]/munlock[all] requests.
*
* Filters out "special" vmas -- VM_LOCKED never gets set for these, and
* munlock is a no-op. However, for some special vmas, we go ahead and
* populate the ptes.
*
* For vmas that pass the filters, merge/split as appropriate.
*/
static int mlock_fixup(struct vm_area_struct *vma, struct vm_area_struct **prev,
unsigned long start, unsigned long end, vm_flags_t newflags)
{
struct mm_struct *mm = vma->vm_mm;
pgoff_t pgoff;
int nr_pages;
int ret = 0;
int lock = !!(newflags & VM_LOCKED);
if (newflags == vma->vm_flags || (vma->vm_flags & VM_SPECIAL) ||
is_vm_hugetlb_page(vma) || vma == get_gate_vma(current->mm))
goto out; /* don't set VM_LOCKED, don't count */
pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
*prev = vma_merge(mm, *prev, start, end, newflags, vma->anon_vma,
vma->vm_file, pgoff, vma_policy(vma));
if (*prev) {
vma = *prev;
goto success;
}
if (start != vma->vm_start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
goto out;
}
if (end != vma->vm_end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
goto out;
}
success:
/*
* Keep track of amount of locked VM.
*/
nr_pages = (end - start) >> PAGE_SHIFT;
if (!lock)
nr_pages = -nr_pages;
mm->locked_vm += nr_pages;
/*
* vm_flags is protected by the mmap_sem held in write mode.
* It's okay if try_to_unmap_one unmaps a page just after we
* set VM_LOCKED, populate_vma_page_range will bring it back.
*/
if (lock)
vma->vm_flags = newflags;
else
munlock_vma_pages_range(vma, start, end);
out:
*prev = vma;
return ret;
}
static int do_mlock(unsigned long start, size_t len, int on)
{
unsigned long nstart, end, tmp;
struct vm_area_struct * vma, * prev;
int error;
VM_BUG_ON(start & ~PAGE_MASK);
VM_BUG_ON(len != PAGE_ALIGN(len));
end = start + len;
if (end < start)
return -EINVAL;
if (end == start)
return 0;
vma = find_vma(current->mm, start);
if (!vma || vma->vm_start > start)
return -ENOMEM;
prev = vma->vm_prev;
if (start > vma->vm_start)
prev = vma;
for (nstart = start ; ; ) {
vm_flags_t newflags;
/* Here we know that vma->vm_start <= nstart < vma->vm_end. */
newflags = vma->vm_flags & ~VM_LOCKED;
if (on)
newflags |= VM_LOCKED;
tmp = vma->vm_end;
if (tmp > end)
tmp = end;
error = mlock_fixup(vma, &prev, nstart, tmp, newflags);
if (error)
break;
nstart = tmp;
if (nstart < prev->vm_end)
nstart = prev->vm_end;
if (nstart >= end)
break;
vma = prev->vm_next;
if (!vma || vma->vm_start != nstart) {
error = -ENOMEM;
break;
}
}
return error;
}
SYSCALL_DEFINE2(mlock, unsigned long, start, size_t, len)
{
unsigned long locked;
unsigned long lock_limit;
int error = -ENOMEM;
if (!can_do_mlock())
return -EPERM;
lru_add_drain_all(); /* flush pagevec */
len = PAGE_ALIGN(len + (start & ~PAGE_MASK));
start &= PAGE_MASK;
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
locked = len >> PAGE_SHIFT;
down_write(¤t->mm->mmap_sem);
locked += current->mm->locked_vm;
/* check against resource limits */
if ((locked <= lock_limit) || capable(CAP_IPC_LOCK))
error = do_mlock(start, len, 1);
up_write(¤t->mm->mmap_sem);
if (error)
return error;
error = __mm_populate(start, len, 0);
if (error)
return __mlock_posix_error_return(error);
return 0;
}
SYSCALL_DEFINE2(munlock, unsigned long, start, size_t, len)
{
int ret;
len = PAGE_ALIGN(len + (start & ~PAGE_MASK));
start &= PAGE_MASK;
down_write(¤t->mm->mmap_sem);
ret = do_mlock(start, len, 0);
up_write(¤t->mm->mmap_sem);
return ret;
}
static int do_mlockall(int flags)
{
struct vm_area_struct * vma, * prev = NULL;
if (flags & MCL_FUTURE)
current->mm->def_flags |= VM_LOCKED;
else
current->mm->def_flags &= ~VM_LOCKED;
if (flags == MCL_FUTURE)
goto out;
for (vma = current->mm->mmap; vma ; vma = prev->vm_next) {
vm_flags_t newflags;
newflags = vma->vm_flags & ~VM_LOCKED;
if (flags & MCL_CURRENT)
newflags |= VM_LOCKED;
/* Ignore errors */
mlock_fixup(vma, &prev, vma->vm_start, vma->vm_end, newflags);
cond_resched_rcu_qs();
}
out:
return 0;
}
SYSCALL_DEFINE1(mlockall, int, flags)
{
unsigned long lock_limit;
int ret = -EINVAL;
if (!flags || (flags & ~(MCL_CURRENT | MCL_FUTURE)))
goto out;
ret = -EPERM;
if (!can_do_mlock())
goto out;
if (flags & MCL_CURRENT)
lru_add_drain_all(); /* flush pagevec */
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
ret = -ENOMEM;
down_write(¤t->mm->mmap_sem);
if (!(flags & MCL_CURRENT) || (current->mm->total_vm <= lock_limit) ||
capable(CAP_IPC_LOCK))
ret = do_mlockall(flags);
up_write(¤t->mm->mmap_sem);
if (!ret && (flags & MCL_CURRENT))
mm_populate(0, TASK_SIZE);
out:
return ret;
}
SYSCALL_DEFINE0(munlockall)
{
int ret;
down_write(¤t->mm->mmap_sem);
ret = do_mlockall(0);
up_write(¤t->mm->mmap_sem);
return ret;
}
/*
* Objects with different lifetime than processes (SHM_LOCK and SHM_HUGETLB
* shm segments) get accounted against the user_struct instead.
*/
static DEFINE_SPINLOCK(shmlock_user_lock);
int user_shm_lock(size_t size, struct user_struct *user)
{
unsigned long lock_limit, locked;
int allowed = 0;
locked = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
lock_limit = rlimit(RLIMIT_MEMLOCK);
if (lock_limit == RLIM_INFINITY)
allowed = 1;
lock_limit >>= PAGE_SHIFT;
spin_lock(&shmlock_user_lock);
if (!allowed &&
locked + user->locked_shm > lock_limit && !capable(CAP_IPC_LOCK))
goto out;
get_uid(user);
user->locked_shm += locked;
allowed = 1;
out:
spin_unlock(&shmlock_user_lock);
return allowed;
}
void user_shm_unlock(size_t size, struct user_struct *user)
{
spin_lock(&shmlock_user_lock);
user->locked_shm -= (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
spin_unlock(&shmlock_user_lock);
free_uid(user);
}
| gpl-2.0 |
Bauuuuu/android_kernel_zte_nx512j | drivers/net/ethernet/smsc/smsc911x.c | 1159 | 70960 | /***************************************************************************
*
* Copyright (C) 2004-2008 SMSC
* Copyright (C) 2005-2008 ARM
*
* 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.
*
***************************************************************************
* Rewritten, heavily based on smsc911x simple driver by SMSC.
* Partly uses io macros from smc91x.c by Nicolas Pitre
*
* Supported devices:
* LAN9115, LAN9116, LAN9117, LAN9118
* LAN9215, LAN9216, LAN9217, LAN9218
* LAN9210, LAN9211
* LAN9220, LAN9221
* LAN89218
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/crc32.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/bug.h>
#include <linux/bitops.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/swab.h>
#include <linux/phy.h>
#include <linux/smsc911x.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/of_net.h>
#include "smsc911x.h"
#define SMSC_CHIPNAME "smsc911x"
#define SMSC_MDIONAME "smsc911x-mdio"
#define SMSC_DRV_VERSION "2008-10-21"
MODULE_LICENSE("GPL");
MODULE_VERSION(SMSC_DRV_VERSION);
MODULE_ALIAS("platform:smsc911x");
#if USE_DEBUG > 0
static int debug = 16;
#else
static int debug = 3;
#endif
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
struct smsc911x_data;
struct smsc911x_ops {
u32 (*reg_read)(struct smsc911x_data *pdata, u32 reg);
void (*reg_write)(struct smsc911x_data *pdata, u32 reg, u32 val);
void (*rx_readfifo)(struct smsc911x_data *pdata,
unsigned int *buf, unsigned int wordcount);
void (*tx_writefifo)(struct smsc911x_data *pdata,
unsigned int *buf, unsigned int wordcount);
};
#define SMSC911X_NUM_SUPPLIES 2
struct smsc911x_data {
void __iomem *ioaddr;
unsigned int idrev;
/* used to decide which workarounds apply */
unsigned int generation;
/* device configuration (copied from platform_data during probe) */
struct smsc911x_platform_config config;
/* This needs to be acquired before calling any of below:
* smsc911x_mac_read(), smsc911x_mac_write()
*/
spinlock_t mac_lock;
/* spinlock to ensure register accesses are serialised */
spinlock_t dev_lock;
struct phy_device *phy_dev;
struct mii_bus *mii_bus;
int phy_irq[PHY_MAX_ADDR];
unsigned int using_extphy;
int last_duplex;
int last_carrier;
u32 msg_enable;
unsigned int gpio_setting;
unsigned int gpio_orig_setting;
struct net_device *dev;
struct napi_struct napi;
unsigned int software_irq_signal;
#ifdef USE_PHY_WORK_AROUND
#define MIN_PACKET_SIZE (64)
char loopback_tx_pkt[MIN_PACKET_SIZE];
char loopback_rx_pkt[MIN_PACKET_SIZE];
unsigned int resetcount;
#endif
/* Members for Multicast filter workaround */
unsigned int multicast_update_pending;
unsigned int set_bits_mask;
unsigned int clear_bits_mask;
unsigned int hashhi;
unsigned int hashlo;
/* register access functions */
const struct smsc911x_ops *ops;
/* regulators */
struct regulator_bulk_data supplies[SMSC911X_NUM_SUPPLIES];
/* clock */
struct clk *clk;
};
/* Easy access to information */
#define __smsc_shift(pdata, reg) ((reg) << ((pdata)->config.shift))
static inline u32 __smsc911x_reg_read(struct smsc911x_data *pdata, u32 reg)
{
if (pdata->config.flags & SMSC911X_USE_32BIT)
return readl(pdata->ioaddr + reg);
if (pdata->config.flags & SMSC911X_USE_16BIT)
return ((readw(pdata->ioaddr + reg) & 0xFFFF) |
((readw(pdata->ioaddr + reg + 2) & 0xFFFF) << 16));
BUG();
return 0;
}
static inline u32
__smsc911x_reg_read_shift(struct smsc911x_data *pdata, u32 reg)
{
if (pdata->config.flags & SMSC911X_USE_32BIT)
return readl(pdata->ioaddr + __smsc_shift(pdata, reg));
if (pdata->config.flags & SMSC911X_USE_16BIT)
return (readw(pdata->ioaddr +
__smsc_shift(pdata, reg)) & 0xFFFF) |
((readw(pdata->ioaddr +
__smsc_shift(pdata, reg + 2)) & 0xFFFF) << 16);
BUG();
return 0;
}
static inline u32 smsc911x_reg_read(struct smsc911x_data *pdata, u32 reg)
{
u32 data;
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
data = pdata->ops->reg_read(pdata, reg);
spin_unlock_irqrestore(&pdata->dev_lock, flags);
return data;
}
static inline void __smsc911x_reg_write(struct smsc911x_data *pdata, u32 reg,
u32 val)
{
if (pdata->config.flags & SMSC911X_USE_32BIT) {
writel(val, pdata->ioaddr + reg);
return;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
writew(val & 0xFFFF, pdata->ioaddr + reg);
writew((val >> 16) & 0xFFFF, pdata->ioaddr + reg + 2);
return;
}
BUG();
}
static inline void
__smsc911x_reg_write_shift(struct smsc911x_data *pdata, u32 reg, u32 val)
{
if (pdata->config.flags & SMSC911X_USE_32BIT) {
writel(val, pdata->ioaddr + __smsc_shift(pdata, reg));
return;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
writew(val & 0xFFFF,
pdata->ioaddr + __smsc_shift(pdata, reg));
writew((val >> 16) & 0xFFFF,
pdata->ioaddr + __smsc_shift(pdata, reg + 2));
return;
}
BUG();
}
static inline void smsc911x_reg_write(struct smsc911x_data *pdata, u32 reg,
u32 val)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
pdata->ops->reg_write(pdata, reg, val);
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Writes a packet to the TX_DATA_FIFO */
static inline void
smsc911x_tx_writefifo(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
__smsc911x_reg_write(pdata, TX_DATA_FIFO,
swab32(*buf++));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
iowrite32_rep(pdata->ioaddr + TX_DATA_FIFO, buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
__smsc911x_reg_write(pdata, TX_DATA_FIFO, *buf++);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Writes a packet to the TX_DATA_FIFO - shifted version */
static inline void
smsc911x_tx_writefifo_shift(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
__smsc911x_reg_write_shift(pdata, TX_DATA_FIFO,
swab32(*buf++));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
iowrite32_rep(pdata->ioaddr + __smsc_shift(pdata,
TX_DATA_FIFO), buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
__smsc911x_reg_write_shift(pdata,
TX_DATA_FIFO, *buf++);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Reads a packet out of the RX_DATA_FIFO */
static inline void
smsc911x_rx_readfifo(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
*buf++ = swab32(__smsc911x_reg_read(pdata,
RX_DATA_FIFO));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
ioread32_rep(pdata->ioaddr + RX_DATA_FIFO, buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
*buf++ = __smsc911x_reg_read(pdata, RX_DATA_FIFO);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Reads a packet out of the RX_DATA_FIFO - shifted version */
static inline void
smsc911x_rx_readfifo_shift(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
*buf++ = swab32(__smsc911x_reg_read_shift(pdata,
RX_DATA_FIFO));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
ioread32_rep(pdata->ioaddr + __smsc_shift(pdata,
RX_DATA_FIFO), buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
*buf++ = __smsc911x_reg_read_shift(pdata,
RX_DATA_FIFO);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/*
* enable regulator and clock resources.
*/
static int smsc911x_enable_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
int ret = 0;
ret = regulator_bulk_enable(ARRAY_SIZE(pdata->supplies),
pdata->supplies);
if (ret)
netdev_err(ndev, "failed to enable regulators %d\n",
ret);
if (!IS_ERR(pdata->clk)) {
ret = clk_prepare_enable(pdata->clk);
if (ret < 0)
netdev_err(ndev, "failed to enable clock %d\n", ret);
}
return ret;
}
/*
* disable resources, currently just regulators.
*/
static int smsc911x_disable_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
int ret = 0;
ret = regulator_bulk_disable(ARRAY_SIZE(pdata->supplies),
pdata->supplies);
if (!IS_ERR(pdata->clk))
clk_disable_unprepare(pdata->clk);
return ret;
}
/*
* Request resources, currently just regulators.
*
* The SMSC911x has two power pins: vddvario and vdd33a, in designs where
* these are not always-on we need to request regulators to be turned on
* before we can try to access the device registers.
*/
static int smsc911x_request_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
int ret = 0;
/* Request regulators */
pdata->supplies[0].supply = "vdd33a";
pdata->supplies[1].supply = "vddvario";
ret = regulator_bulk_get(&pdev->dev,
ARRAY_SIZE(pdata->supplies),
pdata->supplies);
if (ret)
netdev_err(ndev, "couldn't get regulators %d\n",
ret);
/* Request clock */
pdata->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(pdata->clk))
netdev_warn(ndev, "couldn't get clock %li\n", PTR_ERR(pdata->clk));
return ret;
}
/*
* Free resources, currently just regulators.
*
*/
static void smsc911x_free_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
/* Free regulators */
regulator_bulk_free(ARRAY_SIZE(pdata->supplies),
pdata->supplies);
/* Free clock */
if (!IS_ERR(pdata->clk)) {
clk_put(pdata->clk);
pdata->clk = NULL;
}
}
/* waits for MAC not busy, with timeout. Only called by smsc911x_mac_read
* and smsc911x_mac_write, so assumes mac_lock is held */
static int smsc911x_mac_complete(struct smsc911x_data *pdata)
{
int i;
u32 val;
SMSC_ASSERT_MAC_LOCK(pdata);
for (i = 0; i < 40; i++) {
val = smsc911x_reg_read(pdata, MAC_CSR_CMD);
if (!(val & MAC_CSR_CMD_CSR_BUSY_))
return 0;
}
SMSC_WARN(pdata, hw, "Timed out waiting for MAC not BUSY. "
"MAC_CSR_CMD: 0x%08X", val);
return -EIO;
}
/* Fetches a MAC register value. Assumes mac_lock is acquired */
static u32 smsc911x_mac_read(struct smsc911x_data *pdata, unsigned int offset)
{
unsigned int temp;
SMSC_ASSERT_MAC_LOCK(pdata);
temp = smsc911x_reg_read(pdata, MAC_CSR_CMD);
if (unlikely(temp & MAC_CSR_CMD_CSR_BUSY_)) {
SMSC_WARN(pdata, hw, "MAC busy at entry");
return 0xFFFFFFFF;
}
/* Send the MAC cmd */
smsc911x_reg_write(pdata, MAC_CSR_CMD, ((offset & 0xFF) |
MAC_CSR_CMD_CSR_BUSY_ | MAC_CSR_CMD_R_NOT_W_));
/* Workaround for hardware read-after-write restriction */
temp = smsc911x_reg_read(pdata, BYTE_TEST);
/* Wait for the read to complete */
if (likely(smsc911x_mac_complete(pdata) == 0))
return smsc911x_reg_read(pdata, MAC_CSR_DATA);
SMSC_WARN(pdata, hw, "MAC busy after read");
return 0xFFFFFFFF;
}
/* Set a mac register, mac_lock must be acquired before calling */
static void smsc911x_mac_write(struct smsc911x_data *pdata,
unsigned int offset, u32 val)
{
unsigned int temp;
SMSC_ASSERT_MAC_LOCK(pdata);
temp = smsc911x_reg_read(pdata, MAC_CSR_CMD);
if (unlikely(temp & MAC_CSR_CMD_CSR_BUSY_)) {
SMSC_WARN(pdata, hw,
"smsc911x_mac_write failed, MAC busy at entry");
return;
}
/* Send data to write */
smsc911x_reg_write(pdata, MAC_CSR_DATA, val);
/* Write the actual data */
smsc911x_reg_write(pdata, MAC_CSR_CMD, ((offset & 0xFF) |
MAC_CSR_CMD_CSR_BUSY_));
/* Workaround for hardware read-after-write restriction */
temp = smsc911x_reg_read(pdata, BYTE_TEST);
/* Wait for the write to complete */
if (likely(smsc911x_mac_complete(pdata) == 0))
return;
SMSC_WARN(pdata, hw, "smsc911x_mac_write failed, MAC busy after write");
}
/* Get a phy register */
static int smsc911x_mii_read(struct mii_bus *bus, int phyaddr, int regidx)
{
struct smsc911x_data *pdata = (struct smsc911x_data *)bus->priv;
unsigned long flags;
unsigned int addr;
int i, reg;
spin_lock_irqsave(&pdata->mac_lock, flags);
/* Confirm MII not busy */
if (unlikely(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
SMSC_WARN(pdata, hw, "MII is busy in smsc911x_mii_read???");
reg = -EIO;
goto out;
}
/* Set the address, index & direction (read from PHY) */
addr = ((phyaddr & 0x1F) << 11) | ((regidx & 0x1F) << 6);
smsc911x_mac_write(pdata, MII_ACC, addr);
/* Wait for read to complete w/ timeout */
for (i = 0; i < 100; i++)
if (!(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
reg = smsc911x_mac_read(pdata, MII_DATA);
goto out;
}
SMSC_WARN(pdata, hw, "Timed out waiting for MII read to finish");
reg = -EIO;
out:
spin_unlock_irqrestore(&pdata->mac_lock, flags);
return reg;
}
/* Set a phy register */
static int smsc911x_mii_write(struct mii_bus *bus, int phyaddr, int regidx,
u16 val)
{
struct smsc911x_data *pdata = (struct smsc911x_data *)bus->priv;
unsigned long flags;
unsigned int addr;
int i, reg;
spin_lock_irqsave(&pdata->mac_lock, flags);
/* Confirm MII not busy */
if (unlikely(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
SMSC_WARN(pdata, hw, "MII is busy in smsc911x_mii_write???");
reg = -EIO;
goto out;
}
/* Put the data to write in the MAC */
smsc911x_mac_write(pdata, MII_DATA, val);
/* Set the address, index & direction (write to PHY) */
addr = ((phyaddr & 0x1F) << 11) | ((regidx & 0x1F) << 6) |
MII_ACC_MII_WRITE_;
smsc911x_mac_write(pdata, MII_ACC, addr);
/* Wait for write to complete w/ timeout */
for (i = 0; i < 100; i++)
if (!(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
reg = 0;
goto out;
}
SMSC_WARN(pdata, hw, "Timed out waiting for MII write to finish");
reg = -EIO;
out:
spin_unlock_irqrestore(&pdata->mac_lock, flags);
return reg;
}
/* Switch to external phy. Assumes tx and rx are stopped. */
static void smsc911x_phy_enable_external(struct smsc911x_data *pdata)
{
unsigned int hwcfg = smsc911x_reg_read(pdata, HW_CFG);
/* Disable phy clocks to the MAC */
hwcfg &= (~HW_CFG_PHY_CLK_SEL_);
hwcfg |= HW_CFG_PHY_CLK_SEL_CLK_DIS_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
udelay(10); /* Enough time for clocks to stop */
/* Switch to external phy */
hwcfg |= HW_CFG_EXT_PHY_EN_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
/* Enable phy clocks to the MAC */
hwcfg &= (~HW_CFG_PHY_CLK_SEL_);
hwcfg |= HW_CFG_PHY_CLK_SEL_EXT_PHY_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
udelay(10); /* Enough time for clocks to restart */
hwcfg |= HW_CFG_SMI_SEL_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
}
/* Autodetects and enables external phy if present on supported chips.
* autodetection can be overridden by specifying SMSC911X_FORCE_INTERNAL_PHY
* or SMSC911X_FORCE_EXTERNAL_PHY in the platform_data flags. */
static void smsc911x_phy_initialise_external(struct smsc911x_data *pdata)
{
unsigned int hwcfg = smsc911x_reg_read(pdata, HW_CFG);
if (pdata->config.flags & SMSC911X_FORCE_INTERNAL_PHY) {
SMSC_TRACE(pdata, hw, "Forcing internal PHY");
pdata->using_extphy = 0;
} else if (pdata->config.flags & SMSC911X_FORCE_EXTERNAL_PHY) {
SMSC_TRACE(pdata, hw, "Forcing external PHY");
smsc911x_phy_enable_external(pdata);
pdata->using_extphy = 1;
} else if (hwcfg & HW_CFG_EXT_PHY_DET_) {
SMSC_TRACE(pdata, hw,
"HW_CFG EXT_PHY_DET set, using external PHY");
smsc911x_phy_enable_external(pdata);
pdata->using_extphy = 1;
} else {
SMSC_TRACE(pdata, hw,
"HW_CFG EXT_PHY_DET clear, using internal PHY");
pdata->using_extphy = 0;
}
}
/* Fetches a tx status out of the status fifo */
static unsigned int smsc911x_tx_get_txstatus(struct smsc911x_data *pdata)
{
unsigned int result =
smsc911x_reg_read(pdata, TX_FIFO_INF) & TX_FIFO_INF_TSUSED_;
if (result != 0)
result = smsc911x_reg_read(pdata, TX_STATUS_FIFO);
return result;
}
/* Fetches the next rx status */
static unsigned int smsc911x_rx_get_rxstatus(struct smsc911x_data *pdata)
{
unsigned int result =
smsc911x_reg_read(pdata, RX_FIFO_INF) & RX_FIFO_INF_RXSUSED_;
if (result != 0)
result = smsc911x_reg_read(pdata, RX_STATUS_FIFO);
return result;
}
#ifdef USE_PHY_WORK_AROUND
static int smsc911x_phy_check_loopbackpkt(struct smsc911x_data *pdata)
{
unsigned int tries;
u32 wrsz;
u32 rdsz;
ulong bufp;
for (tries = 0; tries < 10; tries++) {
unsigned int txcmd_a;
unsigned int txcmd_b;
unsigned int status;
unsigned int pktlength;
unsigned int i;
/* Zero-out rx packet memory */
memset(pdata->loopback_rx_pkt, 0, MIN_PACKET_SIZE);
/* Write tx packet to 118 */
txcmd_a = (u32)((ulong)pdata->loopback_tx_pkt & 0x03) << 16;
txcmd_a |= TX_CMD_A_FIRST_SEG_ | TX_CMD_A_LAST_SEG_;
txcmd_a |= MIN_PACKET_SIZE;
txcmd_b = MIN_PACKET_SIZE << 16 | MIN_PACKET_SIZE;
smsc911x_reg_write(pdata, TX_DATA_FIFO, txcmd_a);
smsc911x_reg_write(pdata, TX_DATA_FIFO, txcmd_b);
bufp = (ulong)pdata->loopback_tx_pkt & (~0x3);
wrsz = MIN_PACKET_SIZE + 3;
wrsz += (u32)((ulong)pdata->loopback_tx_pkt & 0x3);
wrsz >>= 2;
pdata->ops->tx_writefifo(pdata, (unsigned int *)bufp, wrsz);
/* Wait till transmit is done */
i = 60;
do {
udelay(5);
status = smsc911x_tx_get_txstatus(pdata);
} while ((i--) && (!status));
if (!status) {
SMSC_WARN(pdata, hw,
"Failed to transmit during loopback test");
continue;
}
if (status & TX_STS_ES_) {
SMSC_WARN(pdata, hw,
"Transmit encountered errors during loopback test");
continue;
}
/* Wait till receive is done */
i = 60;
do {
udelay(5);
status = smsc911x_rx_get_rxstatus(pdata);
} while ((i--) && (!status));
if (!status) {
SMSC_WARN(pdata, hw,
"Failed to receive during loopback test");
continue;
}
if (status & RX_STS_ES_) {
SMSC_WARN(pdata, hw,
"Receive encountered errors during loopback test");
continue;
}
pktlength = ((status & 0x3FFF0000UL) >> 16);
bufp = (ulong)pdata->loopback_rx_pkt;
rdsz = pktlength + 3;
rdsz += (u32)((ulong)pdata->loopback_rx_pkt & 0x3);
rdsz >>= 2;
pdata->ops->rx_readfifo(pdata, (unsigned int *)bufp, rdsz);
if (pktlength != (MIN_PACKET_SIZE + 4)) {
SMSC_WARN(pdata, hw, "Unexpected packet size "
"during loop back test, size=%d, will retry",
pktlength);
} else {
unsigned int j;
int mismatch = 0;
for (j = 0; j < MIN_PACKET_SIZE; j++) {
if (pdata->loopback_tx_pkt[j]
!= pdata->loopback_rx_pkt[j]) {
mismatch = 1;
break;
}
}
if (!mismatch) {
SMSC_TRACE(pdata, hw, "Successfully verified "
"loopback packet");
return 0;
} else {
SMSC_WARN(pdata, hw, "Data mismatch "
"during loop back test, will retry");
}
}
}
return -EIO;
}
static int smsc911x_phy_reset(struct smsc911x_data *pdata)
{
struct phy_device *phy_dev = pdata->phy_dev;
unsigned int temp;
unsigned int i = 100000;
BUG_ON(!phy_dev);
BUG_ON(!phy_dev->bus);
SMSC_TRACE(pdata, hw, "Performing PHY BCR Reset");
smsc911x_mii_write(phy_dev->bus, phy_dev->addr, MII_BMCR, BMCR_RESET);
do {
msleep(1);
temp = smsc911x_mii_read(phy_dev->bus, phy_dev->addr,
MII_BMCR);
} while ((i--) && (temp & BMCR_RESET));
if (temp & BMCR_RESET) {
SMSC_WARN(pdata, hw, "PHY reset failed to complete");
return -EIO;
}
/* Extra delay required because the phy may not be completed with
* its reset when BMCR_RESET is cleared. Specs say 256 uS is
* enough delay but using 1ms here to be safe */
msleep(1);
return 0;
}
static int smsc911x_phy_loopbacktest(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phy_dev = pdata->phy_dev;
int result = -EIO;
unsigned int i, val;
unsigned long flags;
/* Initialise tx packet using broadcast destination address */
memset(pdata->loopback_tx_pkt, 0xff, ETH_ALEN);
/* Use incrementing source address */
for (i = 6; i < 12; i++)
pdata->loopback_tx_pkt[i] = (char)i;
/* Set length type field */
pdata->loopback_tx_pkt[12] = 0x00;
pdata->loopback_tx_pkt[13] = 0x00;
for (i = 14; i < MIN_PACKET_SIZE; i++)
pdata->loopback_tx_pkt[i] = (char)i;
val = smsc911x_reg_read(pdata, HW_CFG);
val &= HW_CFG_TX_FIF_SZ_;
val |= HW_CFG_SF_;
smsc911x_reg_write(pdata, HW_CFG, val);
smsc911x_reg_write(pdata, TX_CFG, TX_CFG_TX_ON_);
smsc911x_reg_write(pdata, RX_CFG,
(u32)((ulong)pdata->loopback_rx_pkt & 0x03) << 8);
for (i = 0; i < 10; i++) {
/* Set PHY to 10/FD, no ANEG, and loopback mode */
smsc911x_mii_write(phy_dev->bus, phy_dev->addr, MII_BMCR,
BMCR_LOOPBACK | BMCR_FULLDPLX);
/* Enable MAC tx/rx, FD */
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, MAC_CR, MAC_CR_FDPX_
| MAC_CR_TXEN_ | MAC_CR_RXEN_);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
if (smsc911x_phy_check_loopbackpkt(pdata) == 0) {
result = 0;
break;
}
pdata->resetcount++;
/* Disable MAC rx */
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, MAC_CR, 0);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
smsc911x_phy_reset(pdata);
}
/* Disable MAC */
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, MAC_CR, 0);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
/* Cancel PHY loopback mode */
smsc911x_mii_write(phy_dev->bus, phy_dev->addr, MII_BMCR, 0);
smsc911x_reg_write(pdata, TX_CFG, 0);
smsc911x_reg_write(pdata, RX_CFG, 0);
return result;
}
#endif /* USE_PHY_WORK_AROUND */
static void smsc911x_phy_update_flowcontrol(struct smsc911x_data *pdata)
{
struct phy_device *phy_dev = pdata->phy_dev;
u32 afc = smsc911x_reg_read(pdata, AFC_CFG);
u32 flow;
unsigned long flags;
if (phy_dev->duplex == DUPLEX_FULL) {
u16 lcladv = phy_read(phy_dev, MII_ADVERTISE);
u16 rmtadv = phy_read(phy_dev, MII_LPA);
u8 cap = mii_resolve_flowctrl_fdx(lcladv, rmtadv);
if (cap & FLOW_CTRL_RX)
flow = 0xFFFF0002;
else
flow = 0;
if (cap & FLOW_CTRL_TX)
afc |= 0xF;
else
afc &= ~0xF;
SMSC_TRACE(pdata, hw, "rx pause %s, tx pause %s",
(cap & FLOW_CTRL_RX ? "enabled" : "disabled"),
(cap & FLOW_CTRL_TX ? "enabled" : "disabled"));
} else {
SMSC_TRACE(pdata, hw, "half duplex");
flow = 0;
afc |= 0xF;
}
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, FLOW, flow);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
smsc911x_reg_write(pdata, AFC_CFG, afc);
}
/* Update link mode if anything has changed. Called periodically when the
* PHY is in polling mode, even if nothing has changed. */
static void smsc911x_phy_adjust_link(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phy_dev = pdata->phy_dev;
unsigned long flags;
int carrier;
if (phy_dev->duplex != pdata->last_duplex) {
unsigned int mac_cr;
SMSC_TRACE(pdata, hw, "duplex state has changed");
spin_lock_irqsave(&pdata->mac_lock, flags);
mac_cr = smsc911x_mac_read(pdata, MAC_CR);
if (phy_dev->duplex) {
SMSC_TRACE(pdata, hw,
"configuring for full duplex mode");
mac_cr |= MAC_CR_FDPX_;
} else {
SMSC_TRACE(pdata, hw,
"configuring for half duplex mode");
mac_cr &= ~MAC_CR_FDPX_;
}
smsc911x_mac_write(pdata, MAC_CR, mac_cr);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
smsc911x_phy_update_flowcontrol(pdata);
pdata->last_duplex = phy_dev->duplex;
}
carrier = netif_carrier_ok(dev);
if (carrier != pdata->last_carrier) {
SMSC_TRACE(pdata, hw, "carrier state has changed");
if (carrier) {
SMSC_TRACE(pdata, hw, "configuring for carrier OK");
if ((pdata->gpio_orig_setting & GPIO_CFG_LED1_EN_) &&
(!pdata->using_extphy)) {
/* Restore original GPIO configuration */
pdata->gpio_setting = pdata->gpio_orig_setting;
smsc911x_reg_write(pdata, SMSC_GPIO_CFG,
pdata->gpio_setting);
}
} else {
SMSC_TRACE(pdata, hw, "configuring for no carrier");
/* Check global setting that LED1
* usage is 10/100 indicator */
pdata->gpio_setting = smsc911x_reg_read(pdata,
SMSC_GPIO_CFG);
if ((pdata->gpio_setting & GPIO_CFG_LED1_EN_) &&
(!pdata->using_extphy)) {
/* Force 10/100 LED off, after saving
* original GPIO configuration */
pdata->gpio_orig_setting = pdata->gpio_setting;
pdata->gpio_setting &= ~GPIO_CFG_LED1_EN_;
pdata->gpio_setting |= (GPIO_CFG_GPIOBUF0_
| GPIO_CFG_GPIODIR0_
| GPIO_CFG_GPIOD0_);
smsc911x_reg_write(pdata, SMSC_GPIO_CFG,
pdata->gpio_setting);
}
}
pdata->last_carrier = carrier;
}
}
static int smsc911x_mii_probe(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phydev = NULL;
int ret;
/* find the first phy */
phydev = phy_find_first(pdata->mii_bus);
if (!phydev) {
netdev_err(dev, "no PHY found\n");
return -ENODEV;
}
SMSC_TRACE(pdata, probe, "PHY: addr %d, phy_id 0x%08X",
phydev->addr, phydev->phy_id);
ret = phy_connect_direct(dev, phydev, &smsc911x_phy_adjust_link,
pdata->config.phy_interface);
if (ret) {
netdev_err(dev, "Could not attach to PHY\n");
return ret;
}
netdev_info(dev,
"attached PHY driver [%s] (mii_bus:phy_addr=%s, irq=%d)\n",
phydev->drv->name, dev_name(&phydev->dev), phydev->irq);
/* mask with MAC supported features */
phydev->supported &= (PHY_BASIC_FEATURES | SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
phydev->advertising = phydev->supported;
pdata->phy_dev = phydev;
pdata->last_duplex = -1;
pdata->last_carrier = -1;
#ifdef USE_PHY_WORK_AROUND
if (smsc911x_phy_loopbacktest(dev) < 0) {
SMSC_WARN(pdata, hw, "Failed Loop Back Test");
return -ENODEV;
}
SMSC_TRACE(pdata, hw, "Passed Loop Back Test");
#endif /* USE_PHY_WORK_AROUND */
SMSC_TRACE(pdata, hw, "phy initialised successfully");
return 0;
}
static int smsc911x_mii_init(struct platform_device *pdev,
struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
int err = -ENXIO, i;
pdata->mii_bus = mdiobus_alloc();
if (!pdata->mii_bus) {
err = -ENOMEM;
goto err_out_1;
}
pdata->mii_bus->name = SMSC_MDIONAME;
snprintf(pdata->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x",
pdev->name, pdev->id);
pdata->mii_bus->priv = pdata;
pdata->mii_bus->read = smsc911x_mii_read;
pdata->mii_bus->write = smsc911x_mii_write;
pdata->mii_bus->irq = pdata->phy_irq;
for (i = 0; i < PHY_MAX_ADDR; ++i)
pdata->mii_bus->irq[i] = PHY_POLL;
pdata->mii_bus->parent = &pdev->dev;
switch (pdata->idrev & 0xFFFF0000) {
case 0x01170000:
case 0x01150000:
case 0x117A0000:
case 0x115A0000:
/* External PHY supported, try to autodetect */
smsc911x_phy_initialise_external(pdata);
break;
default:
SMSC_TRACE(pdata, hw, "External PHY is not supported, "
"using internal PHY");
pdata->using_extphy = 0;
break;
}
if (!pdata->using_extphy) {
/* Mask all PHYs except ID 1 (internal) */
pdata->mii_bus->phy_mask = ~(1 << 1);
}
if (mdiobus_register(pdata->mii_bus)) {
SMSC_WARN(pdata, probe, "Error registering mii bus");
goto err_out_free_bus_2;
}
if (smsc911x_mii_probe(dev) < 0) {
SMSC_WARN(pdata, probe, "Error registering mii bus");
goto err_out_unregister_bus_3;
}
return 0;
err_out_unregister_bus_3:
mdiobus_unregister(pdata->mii_bus);
err_out_free_bus_2:
mdiobus_free(pdata->mii_bus);
err_out_1:
return err;
}
/* Gets the number of tx statuses in the fifo */
static unsigned int smsc911x_tx_get_txstatcount(struct smsc911x_data *pdata)
{
return (smsc911x_reg_read(pdata, TX_FIFO_INF)
& TX_FIFO_INF_TSUSED_) >> 16;
}
/* Reads tx statuses and increments counters where necessary */
static void smsc911x_tx_update_txcounters(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int tx_stat;
while ((tx_stat = smsc911x_tx_get_txstatus(pdata)) != 0) {
if (unlikely(tx_stat & 0x80000000)) {
/* In this driver the packet tag is used as the packet
* length. Since a packet length can never reach the
* size of 0x8000, this bit is reserved. It is worth
* noting that the "reserved bit" in the warning above
* does not reference a hardware defined reserved bit
* but rather a driver defined one.
*/
SMSC_WARN(pdata, hw, "Packet tag reserved bit is high");
} else {
if (unlikely(tx_stat & TX_STS_ES_)) {
dev->stats.tx_errors++;
} else {
dev->stats.tx_packets++;
dev->stats.tx_bytes += (tx_stat >> 16);
}
if (unlikely(tx_stat & TX_STS_EXCESS_COL_)) {
dev->stats.collisions += 16;
dev->stats.tx_aborted_errors += 1;
} else {
dev->stats.collisions +=
((tx_stat >> 3) & 0xF);
}
if (unlikely(tx_stat & TX_STS_LOST_CARRIER_))
dev->stats.tx_carrier_errors += 1;
if (unlikely(tx_stat & TX_STS_LATE_COL_)) {
dev->stats.collisions++;
dev->stats.tx_aborted_errors++;
}
}
}
}
/* Increments the Rx error counters */
static void
smsc911x_rx_counterrors(struct net_device *dev, unsigned int rxstat)
{
int crc_err = 0;
if (unlikely(rxstat & RX_STS_ES_)) {
dev->stats.rx_errors++;
if (unlikely(rxstat & RX_STS_CRC_ERR_)) {
dev->stats.rx_crc_errors++;
crc_err = 1;
}
}
if (likely(!crc_err)) {
if (unlikely((rxstat & RX_STS_FRAME_TYPE_) &&
(rxstat & RX_STS_LENGTH_ERR_)))
dev->stats.rx_length_errors++;
if (rxstat & RX_STS_MCAST_)
dev->stats.multicast++;
}
}
/* Quickly dumps bad packets */
static void
smsc911x_rx_fastforward(struct smsc911x_data *pdata, unsigned int pktwords)
{
if (likely(pktwords >= 4)) {
unsigned int timeout = 500;
unsigned int val;
smsc911x_reg_write(pdata, RX_DP_CTRL, RX_DP_CTRL_RX_FFWD_);
do {
udelay(1);
val = smsc911x_reg_read(pdata, RX_DP_CTRL);
} while ((val & RX_DP_CTRL_RX_FFWD_) && --timeout);
if (unlikely(timeout == 0))
SMSC_WARN(pdata, hw, "Timed out waiting for "
"RX FFWD to finish, RX_DP_CTRL: 0x%08X", val);
} else {
unsigned int temp;
while (pktwords--)
temp = smsc911x_reg_read(pdata, RX_DATA_FIFO);
}
}
/* NAPI poll function */
static int smsc911x_poll(struct napi_struct *napi, int budget)
{
struct smsc911x_data *pdata =
container_of(napi, struct smsc911x_data, napi);
struct net_device *dev = pdata->dev;
int npackets = 0;
while (npackets < budget) {
unsigned int pktlength;
unsigned int pktwords;
struct sk_buff *skb;
unsigned int rxstat = smsc911x_rx_get_rxstatus(pdata);
if (!rxstat) {
unsigned int temp;
/* We processed all packets available. Tell NAPI it can
* stop polling then re-enable rx interrupts */
smsc911x_reg_write(pdata, INT_STS, INT_STS_RSFL_);
napi_complete(napi);
temp = smsc911x_reg_read(pdata, INT_EN);
temp |= INT_EN_RSFL_EN_;
smsc911x_reg_write(pdata, INT_EN, temp);
break;
}
/* Count packet for NAPI scheduling, even if it has an error.
* Error packets still require cycles to discard */
npackets++;
pktlength = ((rxstat & 0x3FFF0000) >> 16);
pktwords = (pktlength + NET_IP_ALIGN + 3) >> 2;
smsc911x_rx_counterrors(dev, rxstat);
if (unlikely(rxstat & RX_STS_ES_)) {
SMSC_WARN(pdata, rx_err,
"Discarding packet with error bit set");
/* Packet has an error, discard it and continue with
* the next */
smsc911x_rx_fastforward(pdata, pktwords);
dev->stats.rx_dropped++;
continue;
}
skb = netdev_alloc_skb(dev, pktwords << 2);
if (unlikely(!skb)) {
SMSC_WARN(pdata, rx_err,
"Unable to allocate skb for rx packet");
/* Drop the packet and stop this polling iteration */
smsc911x_rx_fastforward(pdata, pktwords);
dev->stats.rx_dropped++;
break;
}
pdata->ops->rx_readfifo(pdata,
(unsigned int *)skb->data, pktwords);
/* Align IP on 16B boundary */
skb_reserve(skb, NET_IP_ALIGN);
skb_put(skb, pktlength - 4);
skb->protocol = eth_type_trans(skb, dev);
skb_checksum_none_assert(skb);
netif_receive_skb(skb);
/* Update counters */
dev->stats.rx_packets++;
dev->stats.rx_bytes += (pktlength - 4);
}
/* Return total received packets */
return npackets;
}
/* Returns hash bit number for given MAC address
* Example:
* 01 00 5E 00 00 01 -> returns bit number 31 */
static unsigned int smsc911x_hash(char addr[ETH_ALEN])
{
return (ether_crc(ETH_ALEN, addr) >> 26) & 0x3f;
}
static void smsc911x_rx_multicast_update(struct smsc911x_data *pdata)
{
/* Performs the multicast & mac_cr update. This is called when
* safe on the current hardware, and with the mac_lock held */
unsigned int mac_cr;
SMSC_ASSERT_MAC_LOCK(pdata);
mac_cr = smsc911x_mac_read(pdata, MAC_CR);
mac_cr |= pdata->set_bits_mask;
mac_cr &= ~(pdata->clear_bits_mask);
smsc911x_mac_write(pdata, MAC_CR, mac_cr);
smsc911x_mac_write(pdata, HASHH, pdata->hashhi);
smsc911x_mac_write(pdata, HASHL, pdata->hashlo);
SMSC_TRACE(pdata, hw, "maccr 0x%08X, HASHH 0x%08X, HASHL 0x%08X",
mac_cr, pdata->hashhi, pdata->hashlo);
}
static void smsc911x_rx_multicast_update_workaround(struct smsc911x_data *pdata)
{
unsigned int mac_cr;
/* This function is only called for older LAN911x devices
* (revA or revB), where MAC_CR, HASHH and HASHL should not
* be modified during Rx - newer devices immediately update the
* registers.
*
* This is called from interrupt context */
spin_lock(&pdata->mac_lock);
/* Check Rx has stopped */
if (smsc911x_mac_read(pdata, MAC_CR) & MAC_CR_RXEN_)
SMSC_WARN(pdata, drv, "Rx not stopped");
/* Perform the update - safe to do now Rx has stopped */
smsc911x_rx_multicast_update(pdata);
/* Re-enable Rx */
mac_cr = smsc911x_mac_read(pdata, MAC_CR);
mac_cr |= MAC_CR_RXEN_;
smsc911x_mac_write(pdata, MAC_CR, mac_cr);
pdata->multicast_update_pending = 0;
spin_unlock(&pdata->mac_lock);
}
static int smsc911x_phy_disable_energy_detect(struct smsc911x_data *pdata)
{
int rc = 0;
if (!pdata->phy_dev)
return rc;
rc = phy_read(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS);
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed reading PHY control reg");
return rc;
}
/*
* If energy is detected the PHY is already awake so is not necessary
* to disable the energy detect power-down mode.
*/
if ((rc & MII_LAN83C185_EDPWRDOWN) &&
!(rc & MII_LAN83C185_ENERGYON)) {
/* Disable energy detect mode for this SMSC Transceivers */
rc = phy_write(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS,
rc & (~MII_LAN83C185_EDPWRDOWN));
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed writing PHY control reg");
return rc;
}
mdelay(1);
}
return 0;
}
static int smsc911x_phy_enable_energy_detect(struct smsc911x_data *pdata)
{
int rc = 0;
if (!pdata->phy_dev)
return rc;
rc = phy_read(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS);
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed reading PHY control reg");
return rc;
}
/* Only enable if energy detect mode is already disabled */
if (!(rc & MII_LAN83C185_EDPWRDOWN)) {
mdelay(100);
/* Enable energy detect mode for this SMSC Transceivers */
rc = phy_write(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS,
rc | MII_LAN83C185_EDPWRDOWN);
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed writing PHY control reg");
return rc;
}
mdelay(1);
}
return 0;
}
static int smsc911x_soft_reset(struct smsc911x_data *pdata)
{
unsigned int timeout;
unsigned int temp;
int ret;
/*
* LAN9210/LAN9211/LAN9220/LAN9221 chips have an internal PHY that
* are initialized in a Energy Detect Power-Down mode that prevents
* the MAC chip to be software reseted. So we have to wakeup the PHY
* before.
*/
if (pdata->generation == 4) {
ret = smsc911x_phy_disable_energy_detect(pdata);
if (ret) {
SMSC_WARN(pdata, drv, "Failed to wakeup the PHY chip");
return ret;
}
}
/* Reset the LAN911x */
smsc911x_reg_write(pdata, HW_CFG, HW_CFG_SRST_);
timeout = 10;
do {
udelay(10);
temp = smsc911x_reg_read(pdata, HW_CFG);
} while ((--timeout) && (temp & HW_CFG_SRST_));
if (unlikely(temp & HW_CFG_SRST_)) {
SMSC_WARN(pdata, drv, "Failed to complete reset");
return -EIO;
}
if (pdata->generation == 4) {
ret = smsc911x_phy_enable_energy_detect(pdata);
if (ret) {
SMSC_WARN(pdata, drv, "Failed to wakeup the PHY chip");
return ret;
}
}
return 0;
}
/* Sets the device MAC address to dev_addr, called with mac_lock held */
static void
smsc911x_set_hw_mac_address(struct smsc911x_data *pdata, u8 dev_addr[6])
{
u32 mac_high16 = (dev_addr[5] << 8) | dev_addr[4];
u32 mac_low32 = (dev_addr[3] << 24) | (dev_addr[2] << 16) |
(dev_addr[1] << 8) | dev_addr[0];
SMSC_ASSERT_MAC_LOCK(pdata);
smsc911x_mac_write(pdata, ADDRH, mac_high16);
smsc911x_mac_write(pdata, ADDRL, mac_low32);
}
static void smsc911x_disable_irq_chip(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
smsc911x_reg_write(pdata, INT_EN, 0);
smsc911x_reg_write(pdata, INT_STS, 0xFFFFFFFF);
}
static int smsc911x_open(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int timeout;
unsigned int temp;
unsigned int intcfg;
/* if the phy is not yet registered, retry later*/
if (!pdata->phy_dev) {
SMSC_WARN(pdata, hw, "phy_dev is NULL");
return -EAGAIN;
}
/* Reset the LAN911x */
if (smsc911x_soft_reset(pdata)) {
SMSC_WARN(pdata, hw, "soft reset failed");
return -EIO;
}
smsc911x_reg_write(pdata, HW_CFG, 0x00050000);
smsc911x_reg_write(pdata, AFC_CFG, 0x006E3740);
/* Increase the legal frame size of VLAN tagged frames to 1522 bytes */
spin_lock_irq(&pdata->mac_lock);
smsc911x_mac_write(pdata, VLAN1, ETH_P_8021Q);
spin_unlock_irq(&pdata->mac_lock);
/* Make sure EEPROM has finished loading before setting GPIO_CFG */
timeout = 50;
while ((smsc911x_reg_read(pdata, E2P_CMD) & E2P_CMD_EPC_BUSY_) &&
--timeout) {
udelay(10);
}
if (unlikely(timeout == 0))
SMSC_WARN(pdata, ifup,
"Timed out waiting for EEPROM busy bit to clear");
smsc911x_reg_write(pdata, SMSC_GPIO_CFG, 0x70070000);
/* The soft reset above cleared the device's MAC address,
* restore it from local copy (set in probe) */
spin_lock_irq(&pdata->mac_lock);
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
spin_unlock_irq(&pdata->mac_lock);
/* Initialise irqs, but leave all sources disabled */
smsc911x_disable_irq_chip(dev);
/* Set interrupt deassertion to 100uS */
intcfg = ((10 << 24) | INT_CFG_IRQ_EN_);
if (pdata->config.irq_polarity) {
SMSC_TRACE(pdata, ifup, "irq polarity: active high");
intcfg |= INT_CFG_IRQ_POL_;
} else {
SMSC_TRACE(pdata, ifup, "irq polarity: active low");
}
if (pdata->config.irq_type) {
SMSC_TRACE(pdata, ifup, "irq type: push-pull");
intcfg |= INT_CFG_IRQ_TYPE_;
} else {
SMSC_TRACE(pdata, ifup, "irq type: open drain");
}
smsc911x_reg_write(pdata, INT_CFG, intcfg);
SMSC_TRACE(pdata, ifup, "Testing irq handler using IRQ %d", dev->irq);
pdata->software_irq_signal = 0;
smp_wmb();
temp = smsc911x_reg_read(pdata, INT_EN);
temp |= INT_EN_SW_INT_EN_;
smsc911x_reg_write(pdata, INT_EN, temp);
timeout = 1000;
while (timeout--) {
if (pdata->software_irq_signal)
break;
msleep(1);
}
if (!pdata->software_irq_signal) {
netdev_warn(dev, "ISR failed signaling test (IRQ %d)\n",
dev->irq);
return -ENODEV;
}
SMSC_TRACE(pdata, ifup, "IRQ handler passed test using IRQ %d",
dev->irq);
netdev_info(dev, "SMSC911x/921x identified at %#08lx, IRQ: %d\n",
(unsigned long)pdata->ioaddr, dev->irq);
/* Reset the last known duplex and carrier */
pdata->last_duplex = -1;
pdata->last_carrier = -1;
/* Bring the PHY up */
phy_start(pdata->phy_dev);
temp = smsc911x_reg_read(pdata, HW_CFG);
/* Preserve TX FIFO size and external PHY configuration */
temp &= (HW_CFG_TX_FIF_SZ_|0x00000FFF);
temp |= HW_CFG_SF_;
smsc911x_reg_write(pdata, HW_CFG, temp);
temp = smsc911x_reg_read(pdata, FIFO_INT);
temp |= FIFO_INT_TX_AVAIL_LEVEL_;
temp &= ~(FIFO_INT_RX_STS_LEVEL_);
smsc911x_reg_write(pdata, FIFO_INT, temp);
/* set RX Data offset to 2 bytes for alignment */
smsc911x_reg_write(pdata, RX_CFG, (NET_IP_ALIGN << 8));
/* enable NAPI polling before enabling RX interrupts */
napi_enable(&pdata->napi);
temp = smsc911x_reg_read(pdata, INT_EN);
temp |= (INT_EN_TDFA_EN_ | INT_EN_RSFL_EN_ | INT_EN_RXSTOP_INT_EN_);
smsc911x_reg_write(pdata, INT_EN, temp);
spin_lock_irq(&pdata->mac_lock);
temp = smsc911x_mac_read(pdata, MAC_CR);
temp |= (MAC_CR_TXEN_ | MAC_CR_RXEN_ | MAC_CR_HBDIS_);
smsc911x_mac_write(pdata, MAC_CR, temp);
spin_unlock_irq(&pdata->mac_lock);
smsc911x_reg_write(pdata, TX_CFG, TX_CFG_TX_ON_);
netif_start_queue(dev);
return 0;
}
/* Entry point for stopping the interface */
static int smsc911x_stop(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int temp;
/* Disable all device interrupts */
temp = smsc911x_reg_read(pdata, INT_CFG);
temp &= ~INT_CFG_IRQ_EN_;
smsc911x_reg_write(pdata, INT_CFG, temp);
/* Stop Tx and Rx polling */
netif_stop_queue(dev);
napi_disable(&pdata->napi);
/* At this point all Rx and Tx activity is stopped */
dev->stats.rx_dropped += smsc911x_reg_read(pdata, RX_DROP);
smsc911x_tx_update_txcounters(dev);
/* Bring the PHY down */
if (pdata->phy_dev)
phy_stop(pdata->phy_dev);
SMSC_TRACE(pdata, ifdown, "Interface stopped");
return 0;
}
/* Entry point for transmitting a packet */
static int smsc911x_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int freespace;
unsigned int tx_cmd_a;
unsigned int tx_cmd_b;
unsigned int temp;
u32 wrsz;
ulong bufp;
freespace = smsc911x_reg_read(pdata, TX_FIFO_INF) & TX_FIFO_INF_TDFREE_;
if (unlikely(freespace < TX_FIFO_LOW_THRESHOLD))
SMSC_WARN(pdata, tx_err,
"Tx data fifo low, space available: %d", freespace);
/* Word alignment adjustment */
tx_cmd_a = (u32)((ulong)skb->data & 0x03) << 16;
tx_cmd_a |= TX_CMD_A_FIRST_SEG_ | TX_CMD_A_LAST_SEG_;
tx_cmd_a |= (unsigned int)skb->len;
tx_cmd_b = ((unsigned int)skb->len) << 16;
tx_cmd_b |= (unsigned int)skb->len;
smsc911x_reg_write(pdata, TX_DATA_FIFO, tx_cmd_a);
smsc911x_reg_write(pdata, TX_DATA_FIFO, tx_cmd_b);
bufp = (ulong)skb->data & (~0x3);
wrsz = (u32)skb->len + 3;
wrsz += (u32)((ulong)skb->data & 0x3);
wrsz >>= 2;
pdata->ops->tx_writefifo(pdata, (unsigned int *)bufp, wrsz);
freespace -= (skb->len + 32);
skb_tx_timestamp(skb);
dev_kfree_skb(skb);
if (unlikely(smsc911x_tx_get_txstatcount(pdata) >= 30))
smsc911x_tx_update_txcounters(dev);
if (freespace < TX_FIFO_LOW_THRESHOLD) {
netif_stop_queue(dev);
temp = smsc911x_reg_read(pdata, FIFO_INT);
temp &= 0x00FFFFFF;
temp |= 0x32000000;
smsc911x_reg_write(pdata, FIFO_INT, temp);
}
return NETDEV_TX_OK;
}
/* Entry point for getting status counters */
static struct net_device_stats *smsc911x_get_stats(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
smsc911x_tx_update_txcounters(dev);
dev->stats.rx_dropped += smsc911x_reg_read(pdata, RX_DROP);
return &dev->stats;
}
/* Entry point for setting addressing modes */
static void smsc911x_set_multicast_list(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned long flags;
if (dev->flags & IFF_PROMISC) {
/* Enabling promiscuous mode */
pdata->set_bits_mask = MAC_CR_PRMS_;
pdata->clear_bits_mask = (MAC_CR_MCPAS_ | MAC_CR_HPFILT_);
pdata->hashhi = 0;
pdata->hashlo = 0;
} else if (dev->flags & IFF_ALLMULTI) {
/* Enabling all multicast mode */
pdata->set_bits_mask = MAC_CR_MCPAS_;
pdata->clear_bits_mask = (MAC_CR_PRMS_ | MAC_CR_HPFILT_);
pdata->hashhi = 0;
pdata->hashlo = 0;
} else if (!netdev_mc_empty(dev)) {
/* Enabling specific multicast addresses */
unsigned int hash_high = 0;
unsigned int hash_low = 0;
struct netdev_hw_addr *ha;
pdata->set_bits_mask = MAC_CR_HPFILT_;
pdata->clear_bits_mask = (MAC_CR_PRMS_ | MAC_CR_MCPAS_);
netdev_for_each_mc_addr(ha, dev) {
unsigned int bitnum = smsc911x_hash(ha->addr);
unsigned int mask = 0x01 << (bitnum & 0x1F);
if (bitnum & 0x20)
hash_high |= mask;
else
hash_low |= mask;
}
pdata->hashhi = hash_high;
pdata->hashlo = hash_low;
} else {
/* Enabling local MAC address only */
pdata->set_bits_mask = 0;
pdata->clear_bits_mask =
(MAC_CR_PRMS_ | MAC_CR_MCPAS_ | MAC_CR_HPFILT_);
pdata->hashhi = 0;
pdata->hashlo = 0;
}
spin_lock_irqsave(&pdata->mac_lock, flags);
if (pdata->generation <= 1) {
/* Older hardware revision - cannot change these flags while
* receiving data */
if (!pdata->multicast_update_pending) {
unsigned int temp;
SMSC_TRACE(pdata, hw, "scheduling mcast update");
pdata->multicast_update_pending = 1;
/* Request the hardware to stop, then perform the
* update when we get an RX_STOP interrupt */
temp = smsc911x_mac_read(pdata, MAC_CR);
temp &= ~(MAC_CR_RXEN_);
smsc911x_mac_write(pdata, MAC_CR, temp);
} else {
/* There is another update pending, this should now
* use the newer values */
}
} else {
/* Newer hardware revision - can write immediately */
smsc911x_rx_multicast_update(pdata);
}
spin_unlock_irqrestore(&pdata->mac_lock, flags);
}
static irqreturn_t smsc911x_irqhandler(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct smsc911x_data *pdata = netdev_priv(dev);
u32 intsts = smsc911x_reg_read(pdata, INT_STS);
u32 inten = smsc911x_reg_read(pdata, INT_EN);
int serviced = IRQ_NONE;
u32 temp;
if (unlikely(intsts & inten & INT_STS_SW_INT_)) {
temp = smsc911x_reg_read(pdata, INT_EN);
temp &= (~INT_EN_SW_INT_EN_);
smsc911x_reg_write(pdata, INT_EN, temp);
smsc911x_reg_write(pdata, INT_STS, INT_STS_SW_INT_);
pdata->software_irq_signal = 1;
smp_wmb();
serviced = IRQ_HANDLED;
}
if (unlikely(intsts & inten & INT_STS_RXSTOP_INT_)) {
/* Called when there is a multicast update scheduled and
* it is now safe to complete the update */
SMSC_TRACE(pdata, intr, "RX Stop interrupt");
smsc911x_reg_write(pdata, INT_STS, INT_STS_RXSTOP_INT_);
if (pdata->multicast_update_pending)
smsc911x_rx_multicast_update_workaround(pdata);
serviced = IRQ_HANDLED;
}
if (intsts & inten & INT_STS_TDFA_) {
temp = smsc911x_reg_read(pdata, FIFO_INT);
temp |= FIFO_INT_TX_AVAIL_LEVEL_;
smsc911x_reg_write(pdata, FIFO_INT, temp);
smsc911x_reg_write(pdata, INT_STS, INT_STS_TDFA_);
netif_wake_queue(dev);
serviced = IRQ_HANDLED;
}
if (unlikely(intsts & inten & INT_STS_RXE_)) {
SMSC_TRACE(pdata, intr, "RX Error interrupt");
smsc911x_reg_write(pdata, INT_STS, INT_STS_RXE_);
serviced = IRQ_HANDLED;
}
if (likely(intsts & inten & INT_STS_RSFL_)) {
if (likely(napi_schedule_prep(&pdata->napi))) {
/* Disable Rx interrupts */
temp = smsc911x_reg_read(pdata, INT_EN);
temp &= (~INT_EN_RSFL_EN_);
smsc911x_reg_write(pdata, INT_EN, temp);
/* Schedule a NAPI poll */
__napi_schedule(&pdata->napi);
} else {
SMSC_WARN(pdata, rx_err, "napi_schedule_prep failed");
}
serviced = IRQ_HANDLED;
}
return serviced;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void smsc911x_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
smsc911x_irqhandler(0, dev);
enable_irq(dev->irq);
}
#endif /* CONFIG_NET_POLL_CONTROLLER */
static int smsc911x_set_mac_address(struct net_device *dev, void *p)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct sockaddr *addr = p;
/* On older hardware revisions we cannot change the mac address
* registers while receiving data. Newer devices can safely change
* this at any time. */
if (pdata->generation <= 1 && netif_running(dev))
return -EBUSY;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
spin_lock_irq(&pdata->mac_lock);
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
spin_unlock_irq(&pdata->mac_lock);
netdev_info(dev, "MAC Address: %pM\n", dev->dev_addr);
return 0;
}
/* Standard ioctls for mii-tool */
static int smsc911x_do_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct smsc911x_data *pdata = netdev_priv(dev);
if (!netif_running(dev) || !pdata->phy_dev)
return -EINVAL;
return phy_mii_ioctl(pdata->phy_dev, ifr, cmd);
}
static int
smsc911x_ethtool_getsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smsc911x_data *pdata = netdev_priv(dev);
cmd->maxtxpkt = 1;
cmd->maxrxpkt = 1;
return phy_ethtool_gset(pdata->phy_dev, cmd);
}
static int
smsc911x_ethtool_setsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smsc911x_data *pdata = netdev_priv(dev);
return phy_ethtool_sset(pdata->phy_dev, cmd);
}
static void smsc911x_ethtool_getdrvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
strlcpy(info->driver, SMSC_CHIPNAME, sizeof(info->driver));
strlcpy(info->version, SMSC_DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, dev_name(dev->dev.parent),
sizeof(info->bus_info));
}
static int smsc911x_ethtool_nwayreset(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
return phy_start_aneg(pdata->phy_dev);
}
static u32 smsc911x_ethtool_getmsglevel(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
return pdata->msg_enable;
}
static void smsc911x_ethtool_setmsglevel(struct net_device *dev, u32 level)
{
struct smsc911x_data *pdata = netdev_priv(dev);
pdata->msg_enable = level;
}
static int smsc911x_ethtool_getregslen(struct net_device *dev)
{
return (((E2P_DATA - ID_REV) / 4 + 1) + (WUCSR - MAC_CR) + 1 + 32) *
sizeof(u32);
}
static void
smsc911x_ethtool_getregs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phy_dev = pdata->phy_dev;
unsigned long flags;
unsigned int i;
unsigned int j = 0;
u32 *data = buf;
regs->version = pdata->idrev;
for (i = ID_REV; i <= E2P_DATA; i += (sizeof(u32)))
data[j++] = smsc911x_reg_read(pdata, i);
for (i = MAC_CR; i <= WUCSR; i++) {
spin_lock_irqsave(&pdata->mac_lock, flags);
data[j++] = smsc911x_mac_read(pdata, i);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
}
for (i = 0; i <= 31; i++)
data[j++] = smsc911x_mii_read(phy_dev->bus, phy_dev->addr, i);
}
static void smsc911x_eeprom_enable_access(struct smsc911x_data *pdata)
{
unsigned int temp = smsc911x_reg_read(pdata, SMSC_GPIO_CFG);
temp &= ~GPIO_CFG_EEPR_EN_;
smsc911x_reg_write(pdata, SMSC_GPIO_CFG, temp);
msleep(1);
}
static int smsc911x_eeprom_send_cmd(struct smsc911x_data *pdata, u32 op)
{
int timeout = 100;
u32 e2cmd;
SMSC_TRACE(pdata, drv, "op 0x%08x", op);
if (smsc911x_reg_read(pdata, E2P_CMD) & E2P_CMD_EPC_BUSY_) {
SMSC_WARN(pdata, drv, "Busy at start");
return -EBUSY;
}
e2cmd = op | E2P_CMD_EPC_BUSY_;
smsc911x_reg_write(pdata, E2P_CMD, e2cmd);
do {
msleep(1);
e2cmd = smsc911x_reg_read(pdata, E2P_CMD);
} while ((e2cmd & E2P_CMD_EPC_BUSY_) && (--timeout));
if (!timeout) {
SMSC_TRACE(pdata, drv, "TIMED OUT");
return -EAGAIN;
}
if (e2cmd & E2P_CMD_EPC_TIMEOUT_) {
SMSC_TRACE(pdata, drv, "Error occurred during eeprom operation");
return -EINVAL;
}
return 0;
}
static int smsc911x_eeprom_read_location(struct smsc911x_data *pdata,
u8 address, u8 *data)
{
u32 op = E2P_CMD_EPC_CMD_READ_ | address;
int ret;
SMSC_TRACE(pdata, drv, "address 0x%x", address);
ret = smsc911x_eeprom_send_cmd(pdata, op);
if (!ret)
data[address] = smsc911x_reg_read(pdata, E2P_DATA);
return ret;
}
static int smsc911x_eeprom_write_location(struct smsc911x_data *pdata,
u8 address, u8 data)
{
u32 op = E2P_CMD_EPC_CMD_ERASE_ | address;
u32 temp;
int ret;
SMSC_TRACE(pdata, drv, "address 0x%x, data 0x%x", address, data);
ret = smsc911x_eeprom_send_cmd(pdata, op);
if (!ret) {
op = E2P_CMD_EPC_CMD_WRITE_ | address;
smsc911x_reg_write(pdata, E2P_DATA, (u32)data);
/* Workaround for hardware read-after-write restriction */
temp = smsc911x_reg_read(pdata, BYTE_TEST);
ret = smsc911x_eeprom_send_cmd(pdata, op);
}
return ret;
}
static int smsc911x_ethtool_get_eeprom_len(struct net_device *dev)
{
return SMSC911X_EEPROM_SIZE;
}
static int smsc911x_ethtool_get_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
struct smsc911x_data *pdata = netdev_priv(dev);
u8 eeprom_data[SMSC911X_EEPROM_SIZE];
int len;
int i;
smsc911x_eeprom_enable_access(pdata);
len = min(eeprom->len, SMSC911X_EEPROM_SIZE);
for (i = 0; i < len; i++) {
int ret = smsc911x_eeprom_read_location(pdata, i, eeprom_data);
if (ret < 0) {
eeprom->len = 0;
return ret;
}
}
memcpy(data, &eeprom_data[eeprom->offset], len);
eeprom->len = len;
return 0;
}
static int smsc911x_ethtool_set_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
int ret;
struct smsc911x_data *pdata = netdev_priv(dev);
smsc911x_eeprom_enable_access(pdata);
smsc911x_eeprom_send_cmd(pdata, E2P_CMD_EPC_CMD_EWEN_);
ret = smsc911x_eeprom_write_location(pdata, eeprom->offset, *data);
smsc911x_eeprom_send_cmd(pdata, E2P_CMD_EPC_CMD_EWDS_);
/* Single byte write, according to man page */
eeprom->len = 1;
return ret;
}
static const struct ethtool_ops smsc911x_ethtool_ops = {
.get_settings = smsc911x_ethtool_getsettings,
.set_settings = smsc911x_ethtool_setsettings,
.get_link = ethtool_op_get_link,
.get_drvinfo = smsc911x_ethtool_getdrvinfo,
.nway_reset = smsc911x_ethtool_nwayreset,
.get_msglevel = smsc911x_ethtool_getmsglevel,
.set_msglevel = smsc911x_ethtool_setmsglevel,
.get_regs_len = smsc911x_ethtool_getregslen,
.get_regs = smsc911x_ethtool_getregs,
.get_eeprom_len = smsc911x_ethtool_get_eeprom_len,
.get_eeprom = smsc911x_ethtool_get_eeprom,
.set_eeprom = smsc911x_ethtool_set_eeprom,
.get_ts_info = ethtool_op_get_ts_info,
};
static const struct net_device_ops smsc911x_netdev_ops = {
.ndo_open = smsc911x_open,
.ndo_stop = smsc911x_stop,
.ndo_start_xmit = smsc911x_hard_start_xmit,
.ndo_get_stats = smsc911x_get_stats,
.ndo_set_rx_mode = smsc911x_set_multicast_list,
.ndo_do_ioctl = smsc911x_do_ioctl,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = smsc911x_set_mac_address,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = smsc911x_poll_controller,
#endif
};
/* copies the current mac address from hardware to dev->dev_addr */
static void smsc911x_read_mac_address(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
u32 mac_high16 = smsc911x_mac_read(pdata, ADDRH);
u32 mac_low32 = smsc911x_mac_read(pdata, ADDRL);
dev->dev_addr[0] = (u8)(mac_low32);
dev->dev_addr[1] = (u8)(mac_low32 >> 8);
dev->dev_addr[2] = (u8)(mac_low32 >> 16);
dev->dev_addr[3] = (u8)(mac_low32 >> 24);
dev->dev_addr[4] = (u8)(mac_high16);
dev->dev_addr[5] = (u8)(mac_high16 >> 8);
}
/* Initializing private device structures, only called from probe */
static int smsc911x_init(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int byte_test, mask;
unsigned int to = 100;
SMSC_TRACE(pdata, probe, "Driver Parameters:");
SMSC_TRACE(pdata, probe, "LAN base: 0x%08lX",
(unsigned long)pdata->ioaddr);
SMSC_TRACE(pdata, probe, "IRQ: %d", dev->irq);
SMSC_TRACE(pdata, probe, "PHY will be autodetected.");
spin_lock_init(&pdata->dev_lock);
spin_lock_init(&pdata->mac_lock);
if (pdata->ioaddr == NULL) {
SMSC_WARN(pdata, probe, "pdata->ioaddr: 0x00000000");
return -ENODEV;
}
/*
* poll the READY bit in PMT_CTRL. Any other access to the device is
* forbidden while this bit isn't set. Try for 100ms
*
* Note that this test is done before the WORD_SWAP register is
* programmed. So in some configurations the READY bit is at 16 before
* WORD_SWAP is written to. This issue is worked around by waiting
* until either bit 0 or bit 16 gets set in PMT_CTRL.
*
* SMSC has confirmed that checking bit 16 (marked as reserved in
* the datasheet) is fine since these bits "will either never be set
* or can only go high after READY does (so also indicate the device
* is ready)".
*/
mask = PMT_CTRL_READY_ | swahw32(PMT_CTRL_READY_);
while (!(smsc911x_reg_read(pdata, PMT_CTRL) & mask) && --to)
udelay(1000);
if (to == 0) {
pr_err("Device not READY in 100ms aborting\n");
return -ENODEV;
}
/* Check byte ordering */
byte_test = smsc911x_reg_read(pdata, BYTE_TEST);
SMSC_TRACE(pdata, probe, "BYTE_TEST: 0x%08X", byte_test);
if (byte_test == 0x43218765) {
SMSC_TRACE(pdata, probe, "BYTE_TEST looks swapped, "
"applying WORD_SWAP");
smsc911x_reg_write(pdata, WORD_SWAP, 0xffffffff);
/* 1 dummy read of BYTE_TEST is needed after a write to
* WORD_SWAP before its contents are valid */
byte_test = smsc911x_reg_read(pdata, BYTE_TEST);
byte_test = smsc911x_reg_read(pdata, BYTE_TEST);
}
if (byte_test != 0x87654321) {
SMSC_WARN(pdata, drv, "BYTE_TEST: 0x%08X", byte_test);
if (((byte_test >> 16) & 0xFFFF) == (byte_test & 0xFFFF)) {
SMSC_WARN(pdata, probe,
"top 16 bits equal to bottom 16 bits");
SMSC_TRACE(pdata, probe,
"This may mean the chip is set "
"for 32 bit while the bus is reading 16 bit");
}
return -ENODEV;
}
/* Default generation to zero (all workarounds apply) */
pdata->generation = 0;
pdata->idrev = smsc911x_reg_read(pdata, ID_REV);
switch (pdata->idrev & 0xFFFF0000) {
case 0x01180000:
case 0x01170000:
case 0x01160000:
case 0x01150000:
case 0x218A0000:
/* LAN911[5678] family */
pdata->generation = pdata->idrev & 0x0000FFFF;
break;
case 0x118A0000:
case 0x117A0000:
case 0x116A0000:
case 0x115A0000:
/* LAN921[5678] family */
pdata->generation = 3;
break;
case 0x92100000:
case 0x92110000:
case 0x92200000:
case 0x92210000:
/* LAN9210/LAN9211/LAN9220/LAN9221 */
pdata->generation = 4;
break;
default:
SMSC_WARN(pdata, probe, "LAN911x not identified, idrev: 0x%08X",
pdata->idrev);
return -ENODEV;
}
SMSC_TRACE(pdata, probe,
"LAN911x identified, idrev: 0x%08X, generation: %d",
pdata->idrev, pdata->generation);
if (pdata->generation == 0)
SMSC_WARN(pdata, probe,
"This driver is not intended for this chip revision");
/* workaround for platforms without an eeprom, where the mac address
* is stored elsewhere and set by the bootloader. This saves the
* mac address before resetting the device */
if (pdata->config.flags & SMSC911X_SAVE_MAC_ADDRESS) {
spin_lock_irq(&pdata->mac_lock);
smsc911x_read_mac_address(dev);
spin_unlock_irq(&pdata->mac_lock);
}
/* Reset the LAN911x */
if (smsc911x_soft_reset(pdata))
return -ENODEV;
ether_setup(dev);
dev->flags |= IFF_MULTICAST;
netif_napi_add(dev, &pdata->napi, smsc911x_poll, SMSC_NAPI_WEIGHT);
dev->netdev_ops = &smsc911x_netdev_ops;
dev->ethtool_ops = &smsc911x_ethtool_ops;
return 0;
}
static int smsc911x_drv_remove(struct platform_device *pdev)
{
struct net_device *dev;
struct smsc911x_data *pdata;
struct resource *res;
dev = platform_get_drvdata(pdev);
BUG_ON(!dev);
pdata = netdev_priv(dev);
BUG_ON(!pdata);
BUG_ON(!pdata->ioaddr);
BUG_ON(!pdata->phy_dev);
SMSC_TRACE(pdata, ifdown, "Stopping driver");
if (pdata->config.has_reset_gpio) {
gpio_set_value_cansleep(pdata->config.reset_gpio, 0);
gpio_free(pdata->config.reset_gpio);
}
phy_disconnect(pdata->phy_dev);
pdata->phy_dev = NULL;
mdiobus_unregister(pdata->mii_bus);
mdiobus_free(pdata->mii_bus);
platform_set_drvdata(pdev, NULL);
unregister_netdev(dev);
free_irq(dev->irq, dev);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"smsc911x-memory");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
iounmap(pdata->ioaddr);
(void)smsc911x_disable_resources(pdev);
smsc911x_free_resources(pdev);
free_netdev(dev);
return 0;
}
/* standard register acces */
static const struct smsc911x_ops standard_smsc911x_ops = {
.reg_read = __smsc911x_reg_read,
.reg_write = __smsc911x_reg_write,
.rx_readfifo = smsc911x_rx_readfifo,
.tx_writefifo = smsc911x_tx_writefifo,
};
/* shifted register access */
static const struct smsc911x_ops shifted_smsc911x_ops = {
.reg_read = __smsc911x_reg_read_shift,
.reg_write = __smsc911x_reg_write_shift,
.rx_readfifo = smsc911x_rx_readfifo_shift,
.tx_writefifo = smsc911x_tx_writefifo_shift,
};
#ifdef CONFIG_OF
static int smsc911x_probe_config_dt(struct smsc911x_platform_config *config,
struct device_node *np)
{
const char *mac;
u32 width = 0;
if (!np)
return -ENODEV;
config->phy_interface = of_get_phy_mode(np);
mac = of_get_mac_address(np);
if (mac)
memcpy(config->mac, mac, ETH_ALEN);
of_property_read_u32(np, "reg-shift", &config->shift);
of_property_read_u32(np, "reg-io-width", &width);
if (width == 4)
config->flags |= SMSC911X_USE_32BIT;
else
config->flags |= SMSC911X_USE_16BIT;
if (of_get_property(np, "smsc,irq-active-high", NULL))
config->irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_HIGH;
if (of_get_property(np, "smsc,irq-push-pull", NULL))
config->irq_type = SMSC911X_IRQ_TYPE_PUSH_PULL;
if (of_get_property(np, "smsc,force-internal-phy", NULL))
config->flags |= SMSC911X_FORCE_INTERNAL_PHY;
if (of_get_property(np, "smsc,force-external-phy", NULL))
config->flags |= SMSC911X_FORCE_EXTERNAL_PHY;
if (of_get_property(np, "smsc,save-mac-address", NULL))
config->flags |= SMSC911X_SAVE_MAC_ADDRESS;
return 0;
}
#else
static inline int smsc911x_probe_config_dt(
struct smsc911x_platform_config *config,
struct device_node *np)
{
return -ENODEV;
}
#endif /* CONFIG_OF */
static int smsc911x_drv_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct net_device *dev;
struct smsc911x_data *pdata;
struct smsc911x_platform_config *config = pdev->dev.platform_data;
struct resource *res, *irq_res;
unsigned int intcfg = 0;
int res_size, irq_flags;
int retval;
pr_info("Driver version %s\n", SMSC_DRV_VERSION);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"smsc911x-memory");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
pr_warn("Could not allocate resource\n");
retval = -ENODEV;
goto out_0;
}
res_size = resource_size(res);
irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq_res) {
pr_warn("Could not allocate irq resource\n");
retval = -ENODEV;
goto out_0;
}
if (!request_mem_region(res->start, res_size, SMSC_CHIPNAME)) {
retval = -EBUSY;
goto out_0;
}
dev = alloc_etherdev(sizeof(struct smsc911x_data));
if (!dev) {
retval = -ENOMEM;
goto out_release_io_1;
}
SET_NETDEV_DEV(dev, &pdev->dev);
pdata = netdev_priv(dev);
dev->irq = irq_res->start;
irq_flags = irq_res->flags & IRQF_TRIGGER_MASK;
pdata->ioaddr = ioremap_nocache(res->start, res_size);
pdata->dev = dev;
pdata->msg_enable = ((1 << debug) - 1);
platform_set_drvdata(pdev, dev);
retval = smsc911x_request_resources(pdev);
if (retval)
goto out_request_resources_fail;
retval = smsc911x_enable_resources(pdev);
if (retval)
goto out_enable_resources_fail;
if (pdata->ioaddr == NULL) {
SMSC_WARN(pdata, probe, "Error smsc911x base address invalid");
retval = -ENOMEM;
goto out_disable_resources;
}
retval = smsc911x_probe_config_dt(&pdata->config, np);
if (retval && config) {
/* copy config parameters across to pdata */
memcpy(&pdata->config, config, sizeof(pdata->config));
retval = 0;
}
if (retval) {
SMSC_WARN(pdata, probe, "Error smsc911x config not found");
goto out_disable_resources;
}
/* assume standard, non-shifted, access to HW registers */
pdata->ops = &standard_smsc911x_ops;
/* apply the right access if shifting is needed */
if (pdata->config.shift)
pdata->ops = &shifted_smsc911x_ops;
retval = smsc911x_init(dev);
if (retval < 0)
goto out_disable_resources;
/* configure irq polarity and type before connecting isr */
if (pdata->config.irq_polarity == SMSC911X_IRQ_POLARITY_ACTIVE_HIGH)
intcfg |= INT_CFG_IRQ_POL_;
if (pdata->config.irq_type == SMSC911X_IRQ_TYPE_PUSH_PULL)
intcfg |= INT_CFG_IRQ_TYPE_;
smsc911x_reg_write(pdata, INT_CFG, intcfg);
/* Ensure interrupts are globally disabled before connecting ISR */
smsc911x_disable_irq_chip(dev);
retval = request_any_context_irq(dev->irq, smsc911x_irqhandler,
irq_flags | IRQF_SHARED, dev->name,
dev);
if (retval < 0) {
SMSC_WARN(pdata, probe,
"Unable to claim requested irq: %d", dev->irq);
goto out_disable_resources;
}
retval = register_netdev(dev);
if (retval) {
SMSC_WARN(pdata, probe, "Error %i registering device", retval);
goto out_free_irq;
} else {
SMSC_TRACE(pdata, probe,
"Network interface: \"%s\"", dev->name);
}
retval = smsc911x_mii_init(pdev, dev);
if (retval) {
SMSC_WARN(pdata, probe, "Error %i initialising mii", retval);
goto out_unregister_netdev_5;
}
spin_lock_irq(&pdata->mac_lock);
/* Check if mac address has been specified when bringing interface up */
if (is_valid_ether_addr(dev->dev_addr)) {
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
SMSC_TRACE(pdata, probe,
"MAC Address is specified by configuration");
} else if (is_valid_ether_addr(pdata->config.mac)) {
memcpy(dev->dev_addr, pdata->config.mac, 6);
SMSC_TRACE(pdata, probe,
"MAC Address specified by platform data");
} else {
/* Try reading mac address from device. if EEPROM is present
* it will already have been set */
smsc_get_mac(dev);
if (is_valid_ether_addr(dev->dev_addr)) {
/* eeprom values are valid so use them */
SMSC_TRACE(pdata, probe,
"Mac Address is read from LAN911x EEPROM");
} else {
/* eeprom values are invalid, generate random MAC */
eth_hw_addr_random(dev);
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
SMSC_TRACE(pdata, probe,
"MAC Address is set to eth_random_addr");
}
}
spin_unlock_irq(&pdata->mac_lock);
netdev_info(dev, "MAC Address: %pM\n", dev->dev_addr);
return 0;
out_unregister_netdev_5:
unregister_netdev(dev);
out_free_irq:
free_irq(dev->irq, dev);
out_disable_resources:
(void)smsc911x_disable_resources(pdev);
out_enable_resources_fail:
smsc911x_free_resources(pdev);
out_request_resources_fail:
platform_set_drvdata(pdev, NULL);
iounmap(pdata->ioaddr);
free_netdev(dev);
out_release_io_1:
release_mem_region(res->start, resource_size(res));
out_0:
return retval;
}
#ifdef CONFIG_PM
/* This implementation assumes the devices remains powered on its VDDVARIO
* pins during suspend. */
/* TODO: implement freeze/thaw callbacks for hibernation.*/
static int smsc911x_suspend(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
struct smsc911x_data *pdata = netdev_priv(ndev);
/* enable wake on LAN, energy detection and the external PME
* signal. */
smsc911x_reg_write(pdata, PMT_CTRL,
PMT_CTRL_PM_MODE_D1_ | PMT_CTRL_WOL_EN_ |
PMT_CTRL_ED_EN_ | PMT_CTRL_PME_EN_);
/* Drive the GPIO Ethernet_Reset Line low to Suspend */
if (pdata->config.has_reset_gpio)
gpio_set_value_cansleep(pdata->config.reset_gpio, 0);
return 0;
}
static int smsc911x_resume(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
struct smsc911x_data *pdata = netdev_priv(ndev);
unsigned int to = 100;
if (pdata->config.has_reset_gpio)
gpio_set_value_cansleep(pdata->config.reset_gpio, 1);
/* Note 3.11 from the datasheet:
* "When the LAN9220 is in a power saving state, a write of any
* data to the BYTE_TEST register will wake-up the device."
*/
smsc911x_reg_write(pdata, BYTE_TEST, 0);
/* poll the READY bit in PMT_CTRL. Any other access to the device is
* forbidden while this bit isn't set. Try for 100ms and return -EIO
* if it failed. */
while (!(smsc911x_reg_read(pdata, PMT_CTRL) & PMT_CTRL_READY_) && --to)
udelay(1000);
return (to == 0) ? -EIO : 0;
}
static const struct dev_pm_ops smsc911x_pm_ops = {
.suspend = smsc911x_suspend,
.resume = smsc911x_resume,
};
#define SMSC911X_PM_OPS (&smsc911x_pm_ops)
#else
#define SMSC911X_PM_OPS NULL
#endif
#ifdef CONFIG_OF
static const struct of_device_id smsc911x_dt_ids[] = {
{ .compatible = "smsc,lan9115", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, smsc911x_dt_ids);
#endif
static struct platform_driver smsc911x_driver = {
.probe = smsc911x_drv_probe,
.remove = smsc911x_drv_remove,
.driver = {
.name = SMSC_CHIPNAME,
.owner = THIS_MODULE,
.pm = SMSC911X_PM_OPS,
.of_match_table = of_match_ptr(smsc911x_dt_ids),
},
};
/* Entry point for loading the module */
static int __init smsc911x_init_module(void)
{
SMSC_INITIALIZE();
return platform_driver_register(&smsc911x_driver);
}
/* entry point for unloading the module */
static void __exit smsc911x_cleanup_module(void)
{
platform_driver_unregister(&smsc911x_driver);
}
module_init(smsc911x_init_module);
module_exit(smsc911x_cleanup_module);
| gpl-2.0 |
Stane1983/buildroot-linux-kernel-m6 | arch/arm/mach-omap2/board-h4.c | 2439 | 9667 | /*
* linux/arch/arm/mach-omap2/board-h4.c
*
* Copyright (C) 2005 Nokia Corporation
* Author: Paul Mundt <paul.mundt@nokia.com>
*
* Modified from mach-omap/omap1/board-generic.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/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
#include <linux/input.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/gpio.h>
#include <plat/usb.h>
#include <plat/board.h>
#include <plat/common.h>
#include <plat/keypad.h>
#include <plat/menelaus.h>
#include <plat/dma.h>
#include <plat/gpmc.h>
#include "mux.h"
#include "control.h"
#define H4_FLASH_CS 0
#define H4_SMC91X_CS 1
#define H4_ETHR_GPIO_IRQ 92
static unsigned int row_gpios[6] = { 88, 89, 124, 11, 6, 96 };
static unsigned int col_gpios[7] = { 90, 91, 100, 36, 12, 97, 98 };
static const unsigned int h4_keymap[] = {
KEY(0, 0, KEY_LEFT),
KEY(1, 0, KEY_RIGHT),
KEY(2, 0, KEY_A),
KEY(3, 0, KEY_B),
KEY(4, 0, KEY_C),
KEY(0, 1, KEY_DOWN),
KEY(1, 1, KEY_UP),
KEY(2, 1, KEY_E),
KEY(3, 1, KEY_F),
KEY(4, 1, KEY_G),
KEY(0, 2, KEY_ENTER),
KEY(1, 2, KEY_I),
KEY(2, 2, KEY_J),
KEY(3, 2, KEY_K),
KEY(4, 2, KEY_3),
KEY(0, 3, KEY_M),
KEY(1, 3, KEY_N),
KEY(2, 3, KEY_O),
KEY(3, 3, KEY_P),
KEY(4, 3, KEY_Q),
KEY(0, 4, KEY_R),
KEY(1, 4, KEY_4),
KEY(2, 4, KEY_T),
KEY(3, 4, KEY_U),
KEY(4, 4, KEY_ENTER),
KEY(0, 5, KEY_V),
KEY(1, 5, KEY_W),
KEY(2, 5, KEY_L),
KEY(3, 5, KEY_S),
KEY(4, 5, KEY_ENTER),
};
static struct mtd_partition h4_partitions[] = {
/* bootloader (U-Boot, etc) in first sector */
{
.name = "bootloader",
.offset = 0,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* bootloader params in the next sector */
{
.name = "params",
.offset = MTDPART_OFS_APPEND,
.size = SZ_128K,
.mask_flags = 0,
},
/* kernel */
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M,
.mask_flags = 0
},
/* file system */
{
.name = "filesystem",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0
}
};
static struct physmap_flash_data h4_flash_data = {
.width = 2,
.parts = h4_partitions,
.nr_parts = ARRAY_SIZE(h4_partitions),
};
static struct resource h4_flash_resource = {
.flags = IORESOURCE_MEM,
};
static struct platform_device h4_flash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &h4_flash_data,
},
.num_resources = 1,
.resource = &h4_flash_resource,
};
static const struct matrix_keymap_data h4_keymap_data = {
.keymap = h4_keymap,
.keymap_size = ARRAY_SIZE(h4_keymap),
};
static struct omap_kp_platform_data h4_kp_data = {
.rows = 6,
.cols = 7,
.keymap_data = &h4_keymap_data,
.rep = true,
.row_gpios = row_gpios,
.col_gpios = col_gpios,
};
static struct platform_device h4_kp_device = {
.name = "omap-keypad",
.id = -1,
.dev = {
.platform_data = &h4_kp_data,
},
};
static struct platform_device h4_lcd_device = {
.name = "lcd_h4",
.id = -1,
};
static struct platform_device *h4_devices[] __initdata = {
&h4_flash_device,
&h4_kp_device,
&h4_lcd_device,
};
/* 2420 Sysboot setup (2430 is different) */
static u32 get_sysboot_value(void)
{
return (omap_ctrl_readl(OMAP24XX_CONTROL_STATUS) &
(OMAP2_SYSBOOT_5_MASK | OMAP2_SYSBOOT_4_MASK |
OMAP2_SYSBOOT_3_MASK | OMAP2_SYSBOOT_2_MASK |
OMAP2_SYSBOOT_1_MASK | OMAP2_SYSBOOT_0_MASK));
}
/* H4-2420's always used muxed mode, H4-2422's always use non-muxed
*
* Note: OMAP-GIT doesn't correctly do is_cpu_omap2422 and is_cpu_omap2423
* correctly. The macro needs to look at production_id not just hawkeye.
*/
static u32 is_gpmc_muxed(void)
{
u32 mux;
mux = get_sysboot_value();
if ((mux & 0xF) == 0xd)
return 1; /* NAND config (could be either) */
if (mux & 0x2) /* if mux'ed */
return 1;
else
return 0;
}
static inline void __init h4_init_debug(void)
{
int eth_cs;
unsigned long cs_mem_base;
unsigned int muxed, rate;
struct clk *gpmc_fck;
eth_cs = H4_SMC91X_CS;
gpmc_fck = clk_get(NULL, "gpmc_fck"); /* Always on ENABLE_ON_INIT */
if (IS_ERR(gpmc_fck)) {
WARN_ON(1);
return;
}
clk_enable(gpmc_fck);
rate = clk_get_rate(gpmc_fck);
clk_disable(gpmc_fck);
clk_put(gpmc_fck);
if (is_gpmc_muxed())
muxed = 0x200;
else
muxed = 0;
/* Make sure CS1 timings are correct */
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG1,
0x00011000 | muxed);
if (rate >= 160000000) {
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG2, 0x001f1f01);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG3, 0x00080803);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG4, 0x1c0b1c0a);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG5, 0x041f1F1F);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG6, 0x000004C4);
} else if (rate >= 130000000) {
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG2, 0x001f1f00);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG3, 0x00080802);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG4, 0x1C091C09);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG5, 0x041f1F1F);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG6, 0x000004C4);
} else {/* rate = 100000000 */
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG2, 0x001f1f00);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG3, 0x00080802);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG4, 0x1C091C09);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG5, 0x031A1F1F);
gpmc_cs_write_reg(eth_cs, GPMC_CS_CONFIG6, 0x000003C2);
}
if (gpmc_cs_request(eth_cs, SZ_16M, &cs_mem_base) < 0) {
printk(KERN_ERR "Failed to request GPMC mem for smc91x\n");
goto out;
}
udelay(100);
omap_mux_init_gpio(92, 0);
if (debug_card_init(cs_mem_base, H4_ETHR_GPIO_IRQ) < 0)
gpmc_cs_free(eth_cs);
out:
clk_disable(gpmc_fck);
clk_put(gpmc_fck);
}
static void __init h4_init_flash(void)
{
unsigned long base;
if (gpmc_cs_request(H4_FLASH_CS, SZ_64M, &base) < 0) {
printk("Can't request GPMC CS for flash\n");
return;
}
h4_flash_resource.start = base;
h4_flash_resource.end = base + SZ_64M - 1;
}
static struct omap_lcd_config h4_lcd_config __initdata = {
.ctrl_name = "internal",
};
static struct omap_usb_config h4_usb_config __initdata = {
/* S1.10 OFF -- usb "download port"
* usb0 switched to Mini-B port and isp1105 transceiver;
* S2.POS3 = ON, S2.POS4 = OFF ... to enable battery charging
*/
.register_dev = 1,
.pins[0] = 3,
/* .hmc_mode = 0x14,*/ /* 0:dev 1:host 2:disable */
.hmc_mode = 0x00, /* 0:dev|otg 1:disable 2:disable */
};
static struct omap_board_config_kernel h4_config[] __initdata = {
{ OMAP_TAG_LCD, &h4_lcd_config },
};
static void __init omap_h4_init_early(void)
{
omap2_init_common_infrastructure();
omap2_init_common_devices(NULL, NULL);
}
static void __init omap_h4_init_irq(void)
{
omap_init_irq();
}
static struct at24_platform_data m24c01 = {
.byte_len = SZ_1K / 8,
.page_size = 16,
};
static struct i2c_board_info __initdata h4_i2c_board_info[] = {
{
I2C_BOARD_INFO("isp1301_omap", 0x2d),
.irq = OMAP_GPIO_IRQ(125),
},
{ /* EEPROM on mainboard */
I2C_BOARD_INFO("24c01", 0x52),
.platform_data = &m24c01,
},
{ /* EEPROM on cpu card */
I2C_BOARD_INFO("24c01", 0x57),
.platform_data = &m24c01,
},
};
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#endif
static void __init omap_h4_init(void)
{
omap2420_mux_init(board_mux, OMAP_PACKAGE_ZAF);
omap_board_config = h4_config;
omap_board_config_size = ARRAY_SIZE(h4_config);
/*
* Make sure the serial ports are muxed on at this point.
* You have to mux them off in device drivers later on
* if not needed.
*/
#if defined(CONFIG_KEYBOARD_OMAP) || defined(CONFIG_KEYBOARD_OMAP_MODULE)
omap_mux_init_gpio(88, OMAP_PULL_ENA | OMAP_PULL_UP);
omap_mux_init_gpio(89, OMAP_PULL_ENA | OMAP_PULL_UP);
omap_mux_init_gpio(124, OMAP_PULL_ENA | OMAP_PULL_UP);
omap_mux_init_signal("mcbsp2_dr.gpio_11", OMAP_PULL_ENA | OMAP_PULL_UP);
if (omap_has_menelaus()) {
omap_mux_init_signal("sdrc_a14.gpio0",
OMAP_PULL_ENA | OMAP_PULL_UP);
omap_mux_init_signal("vlynq_rx0.gpio_15", 0);
omap_mux_init_signal("gpio_98", 0);
row_gpios[5] = 0;
col_gpios[2] = 15;
col_gpios[6] = 18;
} else {
omap_mux_init_signal("gpio_96", OMAP_PULL_ENA | OMAP_PULL_UP);
omap_mux_init_signal("gpio_100", 0);
omap_mux_init_signal("gpio_98", 0);
}
omap_mux_init_signal("gpio_90", 0);
omap_mux_init_signal("gpio_91", 0);
omap_mux_init_signal("gpio_36", 0);
omap_mux_init_signal("mcbsp2_clkx.gpio_12", 0);
omap_mux_init_signal("gpio_97", 0);
#endif
i2c_register_board_info(1, h4_i2c_board_info,
ARRAY_SIZE(h4_i2c_board_info));
platform_add_devices(h4_devices, ARRAY_SIZE(h4_devices));
omap2_usbfs_init(&h4_usb_config);
omap_serial_init();
h4_init_flash();
}
static void __init omap_h4_map_io(void)
{
omap2_set_globals_242x();
omap242x_map_common_io();
}
MACHINE_START(OMAP_H4, "OMAP2420 H4 board")
/* Maintainer: Paul Mundt <paul.mundt@nokia.com> */
.boot_params = 0x80000100,
.reserve = omap_reserve,
.map_io = omap_h4_map_io,
.init_early = omap_h4_init_early,
.init_irq = omap_h4_init_irq,
.init_machine = omap_h4_init,
.timer = &omap_timer,
MACHINE_END
| gpl-2.0 |
javelinanddart/moretz_kernel | drivers/net/plip.c | 2695 | 35176 | /* $Id: plip.c,v 1.3.6.2 1997/04/16 15:07:56 phil Exp $ */
/* PLIP: A parallel port "network" driver for Linux. */
/* This driver is for parallel port with 5-bit cable (LapLink (R) cable). */
/*
* Authors: Donald Becker <becker@scyld.com>
* Tommy Thorn <thorn@daimi.aau.dk>
* Tanabe Hiroyasu <hiro@sanpo.t.u-tokyo.ac.jp>
* Alan Cox <gw4pts@gw4pts.ampr.org>
* Peter Bauer <100136.3530@compuserve.com>
* Niibe Yutaka <gniibe@mri.co.jp>
* Nimrod Zimerman <zimerman@mailandnews.com>
*
* Enhancements:
* Modularization and ifreq/ifmap support by Alan Cox.
* Rewritten by Niibe Yutaka.
* parport-sharing awareness code by Philip Blundell.
* SMP locking by Niibe Yutaka.
* Support for parallel ports with no IRQ (poll mode),
* Modifications to use the parallel port API
* by Nimrod Zimerman.
*
* Fixes:
* Niibe Yutaka
* - Module initialization.
* - MTU fix.
* - Make sure other end is OK, before sending a packet.
* - Fix immediate timer problem.
*
* Al Viro
* - Changed {enable,disable}_irq handling to make it work
* with new ("stack") semantics.
*
* 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.
*/
/*
* Original version and the name 'PLIP' from Donald Becker <becker@scyld.com>
* inspired by Russ Nelson's parallel port packet driver.
*
* NOTE:
* Tanabe Hiroyasu had changed the protocol, and it was in Linux v1.0.
* Because of the necessity to communicate to DOS machines with the
* Crynwr packet driver, Peter Bauer changed the protocol again
* back to original protocol.
*
* This version follows original PLIP protocol.
* So, this PLIP can't communicate the PLIP of Linux v1.0.
*/
/*
* To use with DOS box, please do (Turn on ARP switch):
* # ifconfig plip[0-2] arp
*/
static const char version[] = "NET3 PLIP version 2.4-parport gniibe@mri.co.jp\n";
/*
Sources:
Ideas and protocols came from Russ Nelson's <nelson@crynwr.com>
"parallel.asm" parallel port packet driver.
The "Crynwr" parallel port standard specifies the following protocol:
Trigger by sending nibble '0x8' (this causes interrupt on other end)
count-low octet
count-high octet
... data octets
checksum octet
Each octet is sent as <wait for rx. '0x1?'> <send 0x10+(octet&0x0F)>
<wait for rx. '0x0?'> <send 0x00+((octet>>4)&0x0F)>
The packet is encapsulated as if it were ethernet.
The cable used is a de facto standard parallel null cable -- sold as
a "LapLink" cable by various places. You'll need a 12-conductor cable to
make one yourself. The wiring is:
SLCTIN 17 - 17
GROUND 25 - 25
D0->ERROR 2 - 15 15 - 2
D1->SLCT 3 - 13 13 - 3
D2->PAPOUT 4 - 12 12 - 4
D3->ACK 5 - 10 10 - 5
D4->BUSY 6 - 11 11 - 6
Do not connect the other pins. They are
D5,D6,D7 are 7,8,9
STROBE is 1, FEED is 14, INIT is 16
extra grounds are 18,19,20,21,22,23,24
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/inetdevice.h>
#include <linux/skbuff.h>
#include <linux/if_plip.h>
#include <linux/workqueue.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/parport.h>
#include <linux/bitops.h>
#include <net/neighbour.h>
#include <asm/system.h>
#include <asm/irq.h>
#include <asm/byteorder.h>
/* Maximum number of devices to support. */
#define PLIP_MAX 8
/* Use 0 for production, 1 for verification, >2 for debug */
#ifndef NET_DEBUG
#define NET_DEBUG 1
#endif
static const unsigned int net_debug = NET_DEBUG;
#define ENABLE(irq) if (irq != -1) enable_irq(irq)
#define DISABLE(irq) if (irq != -1) disable_irq(irq)
/* In micro second */
#define PLIP_DELAY_UNIT 1
/* Connection time out = PLIP_TRIGGER_WAIT * PLIP_DELAY_UNIT usec */
#define PLIP_TRIGGER_WAIT 500
/* Nibble time out = PLIP_NIBBLE_WAIT * PLIP_DELAY_UNIT usec */
#define PLIP_NIBBLE_WAIT 3000
/* Bottom halves */
static void plip_kick_bh(struct work_struct *work);
static void plip_bh(struct work_struct *work);
static void plip_timer_bh(struct work_struct *work);
/* Interrupt handler */
static void plip_interrupt(void *dev_id);
/* Functions for DEV methods */
static int plip_tx_packet(struct sk_buff *skb, struct net_device *dev);
static int plip_hard_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type, const void *daddr,
const void *saddr, unsigned len);
static int plip_hard_header_cache(const struct neighbour *neigh,
struct hh_cache *hh);
static int plip_open(struct net_device *dev);
static int plip_close(struct net_device *dev);
static int plip_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd);
static int plip_preempt(void *handle);
static void plip_wakeup(void *handle);
enum plip_connection_state {
PLIP_CN_NONE=0,
PLIP_CN_RECEIVE,
PLIP_CN_SEND,
PLIP_CN_CLOSING,
PLIP_CN_ERROR
};
enum plip_packet_state {
PLIP_PK_DONE=0,
PLIP_PK_TRIGGER,
PLIP_PK_LENGTH_LSB,
PLIP_PK_LENGTH_MSB,
PLIP_PK_DATA,
PLIP_PK_CHECKSUM
};
enum plip_nibble_state {
PLIP_NB_BEGIN,
PLIP_NB_1,
PLIP_NB_2,
};
struct plip_local {
enum plip_packet_state state;
enum plip_nibble_state nibble;
union {
struct {
#if defined(__LITTLE_ENDIAN)
unsigned char lsb;
unsigned char msb;
#elif defined(__BIG_ENDIAN)
unsigned char msb;
unsigned char lsb;
#else
#error "Please fix the endianness defines in <asm/byteorder.h>"
#endif
} b;
unsigned short h;
} length;
unsigned short byte;
unsigned char checksum;
unsigned char data;
struct sk_buff *skb;
};
struct net_local {
struct net_device *dev;
struct work_struct immediate;
struct delayed_work deferred;
struct delayed_work timer;
struct plip_local snd_data;
struct plip_local rcv_data;
struct pardevice *pardev;
unsigned long trigger;
unsigned long nibble;
enum plip_connection_state connection;
unsigned short timeout_count;
int is_deferred;
int port_owner;
int should_relinquish;
spinlock_t lock;
atomic_t kill_timer;
struct completion killed_timer_cmp;
};
static inline void enable_parport_interrupts (struct net_device *dev)
{
if (dev->irq != -1)
{
struct parport *port =
((struct net_local *)netdev_priv(dev))->pardev->port;
port->ops->enable_irq (port);
}
}
static inline void disable_parport_interrupts (struct net_device *dev)
{
if (dev->irq != -1)
{
struct parport *port =
((struct net_local *)netdev_priv(dev))->pardev->port;
port->ops->disable_irq (port);
}
}
static inline void write_data (struct net_device *dev, unsigned char data)
{
struct parport *port =
((struct net_local *)netdev_priv(dev))->pardev->port;
port->ops->write_data (port, data);
}
static inline unsigned char read_status (struct net_device *dev)
{
struct parport *port =
((struct net_local *)netdev_priv(dev))->pardev->port;
return port->ops->read_status (port);
}
static const struct header_ops plip_header_ops = {
.create = plip_hard_header,
.cache = plip_hard_header_cache,
};
static const struct net_device_ops plip_netdev_ops = {
.ndo_open = plip_open,
.ndo_stop = plip_close,
.ndo_start_xmit = plip_tx_packet,
.ndo_do_ioctl = plip_ioctl,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/* Entry point of PLIP driver.
Probe the hardware, and register/initialize the driver.
PLIP is rather weird, because of the way it interacts with the parport
system. It is _not_ initialised from Space.c. Instead, plip_init()
is called, and that function makes up a "struct net_device" for each port, and
then calls us here.
*/
static void
plip_init_netdev(struct net_device *dev)
{
struct net_local *nl = netdev_priv(dev);
/* Then, override parts of it */
dev->tx_queue_len = 10;
dev->flags = IFF_POINTOPOINT|IFF_NOARP;
memset(dev->dev_addr, 0xfc, ETH_ALEN);
dev->netdev_ops = &plip_netdev_ops;
dev->header_ops = &plip_header_ops;
nl->port_owner = 0;
/* Initialize constants */
nl->trigger = PLIP_TRIGGER_WAIT;
nl->nibble = PLIP_NIBBLE_WAIT;
/* Initialize task queue structures */
INIT_WORK(&nl->immediate, plip_bh);
INIT_DELAYED_WORK(&nl->deferred, plip_kick_bh);
if (dev->irq == -1)
INIT_DELAYED_WORK(&nl->timer, plip_timer_bh);
spin_lock_init(&nl->lock);
}
/* Bottom half handler for the delayed request.
This routine is kicked by do_timer().
Request `plip_bh' to be invoked. */
static void
plip_kick_bh(struct work_struct *work)
{
struct net_local *nl =
container_of(work, struct net_local, deferred.work);
if (nl->is_deferred)
schedule_work(&nl->immediate);
}
/* Forward declarations of internal routines */
static int plip_none(struct net_device *, struct net_local *,
struct plip_local *, struct plip_local *);
static int plip_receive_packet(struct net_device *, struct net_local *,
struct plip_local *, struct plip_local *);
static int plip_send_packet(struct net_device *, struct net_local *,
struct plip_local *, struct plip_local *);
static int plip_connection_close(struct net_device *, struct net_local *,
struct plip_local *, struct plip_local *);
static int plip_error(struct net_device *, struct net_local *,
struct plip_local *, struct plip_local *);
static int plip_bh_timeout_error(struct net_device *dev, struct net_local *nl,
struct plip_local *snd,
struct plip_local *rcv,
int error);
#define OK 0
#define TIMEOUT 1
#define ERROR 2
#define HS_TIMEOUT 3
typedef int (*plip_func)(struct net_device *dev, struct net_local *nl,
struct plip_local *snd, struct plip_local *rcv);
static const plip_func connection_state_table[] =
{
plip_none,
plip_receive_packet,
plip_send_packet,
plip_connection_close,
plip_error
};
/* Bottom half handler of PLIP. */
static void
plip_bh(struct work_struct *work)
{
struct net_local *nl = container_of(work, struct net_local, immediate);
struct plip_local *snd = &nl->snd_data;
struct plip_local *rcv = &nl->rcv_data;
plip_func f;
int r;
nl->is_deferred = 0;
f = connection_state_table[nl->connection];
if ((r = (*f)(nl->dev, nl, snd, rcv)) != OK &&
(r = plip_bh_timeout_error(nl->dev, nl, snd, rcv, r)) != OK) {
nl->is_deferred = 1;
schedule_delayed_work(&nl->deferred, 1);
}
}
static void
plip_timer_bh(struct work_struct *work)
{
struct net_local *nl =
container_of(work, struct net_local, timer.work);
if (!(atomic_read (&nl->kill_timer))) {
plip_interrupt (nl->dev);
schedule_delayed_work(&nl->timer, 1);
}
else {
complete(&nl->killed_timer_cmp);
}
}
static int
plip_bh_timeout_error(struct net_device *dev, struct net_local *nl,
struct plip_local *snd, struct plip_local *rcv,
int error)
{
unsigned char c0;
/*
* This is tricky. If we got here from the beginning of send (either
* with ERROR or HS_TIMEOUT) we have IRQ enabled. Otherwise it's
* already disabled. With the old variant of {enable,disable}_irq()
* extra disable_irq() was a no-op. Now it became mortal - it's
* unbalanced and thus we'll never re-enable IRQ (until rmmod plip,
* that is). So we have to treat HS_TIMEOUT and ERROR from send
* in a special way.
*/
spin_lock_irq(&nl->lock);
if (nl->connection == PLIP_CN_SEND) {
if (error != ERROR) { /* Timeout */
nl->timeout_count++;
if ((error == HS_TIMEOUT && nl->timeout_count <= 10) ||
nl->timeout_count <= 3) {
spin_unlock_irq(&nl->lock);
/* Try again later */
return TIMEOUT;
}
c0 = read_status(dev);
printk(KERN_WARNING "%s: transmit timeout(%d,%02x)\n",
dev->name, snd->state, c0);
} else
error = HS_TIMEOUT;
dev->stats.tx_errors++;
dev->stats.tx_aborted_errors++;
} else if (nl->connection == PLIP_CN_RECEIVE) {
if (rcv->state == PLIP_PK_TRIGGER) {
/* Transmission was interrupted. */
spin_unlock_irq(&nl->lock);
return OK;
}
if (error != ERROR) { /* Timeout */
if (++nl->timeout_count <= 3) {
spin_unlock_irq(&nl->lock);
/* Try again later */
return TIMEOUT;
}
c0 = read_status(dev);
printk(KERN_WARNING "%s: receive timeout(%d,%02x)\n",
dev->name, rcv->state, c0);
}
dev->stats.rx_dropped++;
}
rcv->state = PLIP_PK_DONE;
if (rcv->skb) {
kfree_skb(rcv->skb);
rcv->skb = NULL;
}
snd->state = PLIP_PK_DONE;
if (snd->skb) {
dev_kfree_skb(snd->skb);
snd->skb = NULL;
}
spin_unlock_irq(&nl->lock);
if (error == HS_TIMEOUT) {
DISABLE(dev->irq);
synchronize_irq(dev->irq);
}
disable_parport_interrupts (dev);
netif_stop_queue (dev);
nl->connection = PLIP_CN_ERROR;
write_data (dev, 0x00);
return TIMEOUT;
}
static int
plip_none(struct net_device *dev, struct net_local *nl,
struct plip_local *snd, struct plip_local *rcv)
{
return OK;
}
/* PLIP_RECEIVE --- receive a byte(two nibbles)
Returns OK on success, TIMEOUT on timeout */
static inline int
plip_receive(unsigned short nibble_timeout, struct net_device *dev,
enum plip_nibble_state *ns_p, unsigned char *data_p)
{
unsigned char c0, c1;
unsigned int cx;
switch (*ns_p) {
case PLIP_NB_BEGIN:
cx = nibble_timeout;
while (1) {
c0 = read_status(dev);
udelay(PLIP_DELAY_UNIT);
if ((c0 & 0x80) == 0) {
c1 = read_status(dev);
if (c0 == c1)
break;
}
if (--cx == 0)
return TIMEOUT;
}
*data_p = (c0 >> 3) & 0x0f;
write_data (dev, 0x10); /* send ACK */
*ns_p = PLIP_NB_1;
case PLIP_NB_1:
cx = nibble_timeout;
while (1) {
c0 = read_status(dev);
udelay(PLIP_DELAY_UNIT);
if (c0 & 0x80) {
c1 = read_status(dev);
if (c0 == c1)
break;
}
if (--cx == 0)
return TIMEOUT;
}
*data_p |= (c0 << 1) & 0xf0;
write_data (dev, 0x00); /* send ACK */
*ns_p = PLIP_NB_BEGIN;
case PLIP_NB_2:
break;
}
return OK;
}
/*
* Determine the packet's protocol ID. The rule here is that we
* assume 802.3 if the type field is short enough to be a length.
* This is normal practice and works for any 'now in use' protocol.
*
* PLIP is ethernet ish but the daddr might not be valid if unicast.
* PLIP fortunately has no bus architecture (its Point-to-point).
*
* We can't fix the daddr thing as that quirk (more bug) is embedded
* in far too many old systems not all even running Linux.
*/
static __be16 plip_type_trans(struct sk_buff *skb, struct net_device *dev)
{
struct ethhdr *eth;
unsigned char *rawp;
skb_reset_mac_header(skb);
skb_pull(skb,dev->hard_header_len);
eth = eth_hdr(skb);
if(*eth->h_dest&1)
{
if(memcmp(eth->h_dest,dev->broadcast, ETH_ALEN)==0)
skb->pkt_type=PACKET_BROADCAST;
else
skb->pkt_type=PACKET_MULTICAST;
}
/*
* This ALLMULTI check should be redundant by 1.4
* so don't forget to remove it.
*/
if (ntohs(eth->h_proto) >= 1536)
return eth->h_proto;
rawp = skb->data;
/*
* This is a magic hack to spot IPX packets. Older Novell breaks
* the protocol design and runs IPX over 802.3 without an 802.2 LLC
* layer. We look for FFFF which isn't a used 802.2 SSAP/DSAP. This
* won't work for fault tolerant netware but does for the rest.
*/
if (*(unsigned short *)rawp == 0xFFFF)
return htons(ETH_P_802_3);
/*
* Real 802.2 LLC
*/
return htons(ETH_P_802_2);
}
/* PLIP_RECEIVE_PACKET --- receive a packet */
static int
plip_receive_packet(struct net_device *dev, struct net_local *nl,
struct plip_local *snd, struct plip_local *rcv)
{
unsigned short nibble_timeout = nl->nibble;
unsigned char *lbuf;
switch (rcv->state) {
case PLIP_PK_TRIGGER:
DISABLE(dev->irq);
/* Don't need to synchronize irq, as we can safely ignore it */
disable_parport_interrupts (dev);
write_data (dev, 0x01); /* send ACK */
if (net_debug > 2)
printk(KERN_DEBUG "%s: receive start\n", dev->name);
rcv->state = PLIP_PK_LENGTH_LSB;
rcv->nibble = PLIP_NB_BEGIN;
case PLIP_PK_LENGTH_LSB:
if (snd->state != PLIP_PK_DONE) {
if (plip_receive(nl->trigger, dev,
&rcv->nibble, &rcv->length.b.lsb)) {
/* collision, here dev->tbusy == 1 */
rcv->state = PLIP_PK_DONE;
nl->is_deferred = 1;
nl->connection = PLIP_CN_SEND;
schedule_delayed_work(&nl->deferred, 1);
enable_parport_interrupts (dev);
ENABLE(dev->irq);
return OK;
}
} else {
if (plip_receive(nibble_timeout, dev,
&rcv->nibble, &rcv->length.b.lsb))
return TIMEOUT;
}
rcv->state = PLIP_PK_LENGTH_MSB;
case PLIP_PK_LENGTH_MSB:
if (plip_receive(nibble_timeout, dev,
&rcv->nibble, &rcv->length.b.msb))
return TIMEOUT;
if (rcv->length.h > dev->mtu + dev->hard_header_len ||
rcv->length.h < 8) {
printk(KERN_WARNING "%s: bogus packet size %d.\n", dev->name, rcv->length.h);
return ERROR;
}
/* Malloc up new buffer. */
rcv->skb = dev_alloc_skb(rcv->length.h + 2);
if (rcv->skb == NULL) {
printk(KERN_ERR "%s: Memory squeeze.\n", dev->name);
return ERROR;
}
skb_reserve(rcv->skb, 2); /* Align IP on 16 byte boundaries */
skb_put(rcv->skb,rcv->length.h);
rcv->skb->dev = dev;
rcv->state = PLIP_PK_DATA;
rcv->byte = 0;
rcv->checksum = 0;
case PLIP_PK_DATA:
lbuf = rcv->skb->data;
do {
if (plip_receive(nibble_timeout, dev,
&rcv->nibble, &lbuf[rcv->byte]))
return TIMEOUT;
} while (++rcv->byte < rcv->length.h);
do {
rcv->checksum += lbuf[--rcv->byte];
} while (rcv->byte);
rcv->state = PLIP_PK_CHECKSUM;
case PLIP_PK_CHECKSUM:
if (plip_receive(nibble_timeout, dev,
&rcv->nibble, &rcv->data))
return TIMEOUT;
if (rcv->data != rcv->checksum) {
dev->stats.rx_crc_errors++;
if (net_debug)
printk(KERN_DEBUG "%s: checksum error\n", dev->name);
return ERROR;
}
rcv->state = PLIP_PK_DONE;
case PLIP_PK_DONE:
/* Inform the upper layer for the arrival of a packet. */
rcv->skb->protocol=plip_type_trans(rcv->skb, dev);
netif_rx_ni(rcv->skb);
dev->stats.rx_bytes += rcv->length.h;
dev->stats.rx_packets++;
rcv->skb = NULL;
if (net_debug > 2)
printk(KERN_DEBUG "%s: receive end\n", dev->name);
/* Close the connection. */
write_data (dev, 0x00);
spin_lock_irq(&nl->lock);
if (snd->state != PLIP_PK_DONE) {
nl->connection = PLIP_CN_SEND;
spin_unlock_irq(&nl->lock);
schedule_work(&nl->immediate);
enable_parport_interrupts (dev);
ENABLE(dev->irq);
return OK;
} else {
nl->connection = PLIP_CN_NONE;
spin_unlock_irq(&nl->lock);
enable_parport_interrupts (dev);
ENABLE(dev->irq);
return OK;
}
}
return OK;
}
/* PLIP_SEND --- send a byte (two nibbles)
Returns OK on success, TIMEOUT when timeout */
static inline int
plip_send(unsigned short nibble_timeout, struct net_device *dev,
enum plip_nibble_state *ns_p, unsigned char data)
{
unsigned char c0;
unsigned int cx;
switch (*ns_p) {
case PLIP_NB_BEGIN:
write_data (dev, data & 0x0f);
*ns_p = PLIP_NB_1;
case PLIP_NB_1:
write_data (dev, 0x10 | (data & 0x0f));
cx = nibble_timeout;
while (1) {
c0 = read_status(dev);
if ((c0 & 0x80) == 0)
break;
if (--cx == 0)
return TIMEOUT;
udelay(PLIP_DELAY_UNIT);
}
write_data (dev, 0x10 | (data >> 4));
*ns_p = PLIP_NB_2;
case PLIP_NB_2:
write_data (dev, (data >> 4));
cx = nibble_timeout;
while (1) {
c0 = read_status(dev);
if (c0 & 0x80)
break;
if (--cx == 0)
return TIMEOUT;
udelay(PLIP_DELAY_UNIT);
}
*ns_p = PLIP_NB_BEGIN;
return OK;
}
return OK;
}
/* PLIP_SEND_PACKET --- send a packet */
static int
plip_send_packet(struct net_device *dev, struct net_local *nl,
struct plip_local *snd, struct plip_local *rcv)
{
unsigned short nibble_timeout = nl->nibble;
unsigned char *lbuf;
unsigned char c0;
unsigned int cx;
if (snd->skb == NULL || (lbuf = snd->skb->data) == NULL) {
printk(KERN_DEBUG "%s: send skb lost\n", dev->name);
snd->state = PLIP_PK_DONE;
snd->skb = NULL;
return ERROR;
}
switch (snd->state) {
case PLIP_PK_TRIGGER:
if ((read_status(dev) & 0xf8) != 0x80)
return HS_TIMEOUT;
/* Trigger remote rx interrupt. */
write_data (dev, 0x08);
cx = nl->trigger;
while (1) {
udelay(PLIP_DELAY_UNIT);
spin_lock_irq(&nl->lock);
if (nl->connection == PLIP_CN_RECEIVE) {
spin_unlock_irq(&nl->lock);
/* Interrupted. */
dev->stats.collisions++;
return OK;
}
c0 = read_status(dev);
if (c0 & 0x08) {
spin_unlock_irq(&nl->lock);
DISABLE(dev->irq);
synchronize_irq(dev->irq);
if (nl->connection == PLIP_CN_RECEIVE) {
/* Interrupted.
We don't need to enable irq,
as it is soon disabled. */
/* Yes, we do. New variant of
{enable,disable}_irq *counts*
them. -- AV */
ENABLE(dev->irq);
dev->stats.collisions++;
return OK;
}
disable_parport_interrupts (dev);
if (net_debug > 2)
printk(KERN_DEBUG "%s: send start\n", dev->name);
snd->state = PLIP_PK_LENGTH_LSB;
snd->nibble = PLIP_NB_BEGIN;
nl->timeout_count = 0;
break;
}
spin_unlock_irq(&nl->lock);
if (--cx == 0) {
write_data (dev, 0x00);
return HS_TIMEOUT;
}
}
case PLIP_PK_LENGTH_LSB:
if (plip_send(nibble_timeout, dev,
&snd->nibble, snd->length.b.lsb))
return TIMEOUT;
snd->state = PLIP_PK_LENGTH_MSB;
case PLIP_PK_LENGTH_MSB:
if (plip_send(nibble_timeout, dev,
&snd->nibble, snd->length.b.msb))
return TIMEOUT;
snd->state = PLIP_PK_DATA;
snd->byte = 0;
snd->checksum = 0;
case PLIP_PK_DATA:
do {
if (plip_send(nibble_timeout, dev,
&snd->nibble, lbuf[snd->byte]))
return TIMEOUT;
} while (++snd->byte < snd->length.h);
do {
snd->checksum += lbuf[--snd->byte];
} while (snd->byte);
snd->state = PLIP_PK_CHECKSUM;
case PLIP_PK_CHECKSUM:
if (plip_send(nibble_timeout, dev,
&snd->nibble, snd->checksum))
return TIMEOUT;
dev->stats.tx_bytes += snd->skb->len;
dev_kfree_skb(snd->skb);
dev->stats.tx_packets++;
snd->state = PLIP_PK_DONE;
case PLIP_PK_DONE:
/* Close the connection */
write_data (dev, 0x00);
snd->skb = NULL;
if (net_debug > 2)
printk(KERN_DEBUG "%s: send end\n", dev->name);
nl->connection = PLIP_CN_CLOSING;
nl->is_deferred = 1;
schedule_delayed_work(&nl->deferred, 1);
enable_parport_interrupts (dev);
ENABLE(dev->irq);
return OK;
}
return OK;
}
static int
plip_connection_close(struct net_device *dev, struct net_local *nl,
struct plip_local *snd, struct plip_local *rcv)
{
spin_lock_irq(&nl->lock);
if (nl->connection == PLIP_CN_CLOSING) {
nl->connection = PLIP_CN_NONE;
netif_wake_queue (dev);
}
spin_unlock_irq(&nl->lock);
if (nl->should_relinquish) {
nl->should_relinquish = nl->port_owner = 0;
parport_release(nl->pardev);
}
return OK;
}
/* PLIP_ERROR --- wait till other end settled */
static int
plip_error(struct net_device *dev, struct net_local *nl,
struct plip_local *snd, struct plip_local *rcv)
{
unsigned char status;
status = read_status(dev);
if ((status & 0xf8) == 0x80) {
if (net_debug > 2)
printk(KERN_DEBUG "%s: reset interface.\n", dev->name);
nl->connection = PLIP_CN_NONE;
nl->should_relinquish = 0;
netif_start_queue (dev);
enable_parport_interrupts (dev);
ENABLE(dev->irq);
netif_wake_queue (dev);
} else {
nl->is_deferred = 1;
schedule_delayed_work(&nl->deferred, 1);
}
return OK;
}
/* Handle the parallel port interrupts. */
static void
plip_interrupt(void *dev_id)
{
struct net_device *dev = dev_id;
struct net_local *nl;
struct plip_local *rcv;
unsigned char c0;
unsigned long flags;
nl = netdev_priv(dev);
rcv = &nl->rcv_data;
spin_lock_irqsave (&nl->lock, flags);
c0 = read_status(dev);
if ((c0 & 0xf8) != 0xc0) {
if ((dev->irq != -1) && (net_debug > 1))
printk(KERN_DEBUG "%s: spurious interrupt\n", dev->name);
spin_unlock_irqrestore (&nl->lock, flags);
return;
}
if (net_debug > 3)
printk(KERN_DEBUG "%s: interrupt.\n", dev->name);
switch (nl->connection) {
case PLIP_CN_CLOSING:
netif_wake_queue (dev);
case PLIP_CN_NONE:
case PLIP_CN_SEND:
rcv->state = PLIP_PK_TRIGGER;
nl->connection = PLIP_CN_RECEIVE;
nl->timeout_count = 0;
schedule_work(&nl->immediate);
break;
case PLIP_CN_RECEIVE:
/* May occur because there is race condition
around test and set of dev->interrupt.
Ignore this interrupt. */
break;
case PLIP_CN_ERROR:
printk(KERN_ERR "%s: receive interrupt in error state\n", dev->name);
break;
}
spin_unlock_irqrestore(&nl->lock, flags);
}
static int
plip_tx_packet(struct sk_buff *skb, struct net_device *dev)
{
struct net_local *nl = netdev_priv(dev);
struct plip_local *snd = &nl->snd_data;
if (netif_queue_stopped(dev))
return NETDEV_TX_BUSY;
/* We may need to grab the bus */
if (!nl->port_owner) {
if (parport_claim(nl->pardev))
return NETDEV_TX_BUSY;
nl->port_owner = 1;
}
netif_stop_queue (dev);
if (skb->len > dev->mtu + dev->hard_header_len) {
printk(KERN_WARNING "%s: packet too big, %d.\n", dev->name, (int)skb->len);
netif_start_queue (dev);
return NETDEV_TX_BUSY;
}
if (net_debug > 2)
printk(KERN_DEBUG "%s: send request\n", dev->name);
spin_lock_irq(&nl->lock);
snd->skb = skb;
snd->length.h = skb->len;
snd->state = PLIP_PK_TRIGGER;
if (nl->connection == PLIP_CN_NONE) {
nl->connection = PLIP_CN_SEND;
nl->timeout_count = 0;
}
schedule_work(&nl->immediate);
spin_unlock_irq(&nl->lock);
return NETDEV_TX_OK;
}
static void
plip_rewrite_address(const struct net_device *dev, struct ethhdr *eth)
{
const struct in_device *in_dev;
rcu_read_lock();
in_dev = __in_dev_get_rcu(dev);
if (in_dev) {
/* Any address will do - we take the first */
const struct in_ifaddr *ifa = in_dev->ifa_list;
if (ifa) {
memcpy(eth->h_source, dev->dev_addr, 6);
memset(eth->h_dest, 0xfc, 2);
memcpy(eth->h_dest+2, &ifa->ifa_address, 4);
}
}
rcu_read_unlock();
}
static int
plip_hard_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type, const void *daddr,
const void *saddr, unsigned len)
{
int ret;
ret = eth_header(skb, dev, type, daddr, saddr, len);
if (ret >= 0)
plip_rewrite_address (dev, (struct ethhdr *)skb->data);
return ret;
}
static int plip_hard_header_cache(const struct neighbour *neigh,
struct hh_cache *hh)
{
int ret;
ret = eth_header_cache(neigh, hh);
if (ret == 0) {
struct ethhdr *eth;
eth = (struct ethhdr*)(((u8*)hh->hh_data) +
HH_DATA_OFF(sizeof(*eth)));
plip_rewrite_address (neigh->dev, eth);
}
return ret;
}
/* Open/initialize the board. This is called (in the current kernel)
sometime after booting when the 'ifconfig' program is run.
This routine gets exclusive access to the parallel port by allocating
its IRQ line.
*/
static int
plip_open(struct net_device *dev)
{
struct net_local *nl = netdev_priv(dev);
struct in_device *in_dev;
/* Grab the port */
if (!nl->port_owner) {
if (parport_claim(nl->pardev)) return -EAGAIN;
nl->port_owner = 1;
}
nl->should_relinquish = 0;
/* Clear the data port. */
write_data (dev, 0x00);
/* Enable rx interrupt. */
enable_parport_interrupts (dev);
if (dev->irq == -1)
{
atomic_set (&nl->kill_timer, 0);
schedule_delayed_work(&nl->timer, 1);
}
/* Initialize the state machine. */
nl->rcv_data.state = nl->snd_data.state = PLIP_PK_DONE;
nl->rcv_data.skb = nl->snd_data.skb = NULL;
nl->connection = PLIP_CN_NONE;
nl->is_deferred = 0;
/* Fill in the MAC-level header.
We used to abuse dev->broadcast to store the point-to-point
MAC address, but we no longer do it. Instead, we fetch the
interface address whenever it is needed, which is cheap enough
because we use the hh_cache. Actually, abusing dev->broadcast
didn't work, because when using plip_open the point-to-point
address isn't yet known.
PLIP doesn't have a real MAC address, but we need it to be
DOS compatible, and to properly support taps (otherwise,
when the device address isn't identical to the address of a
received frame, the kernel incorrectly drops it). */
in_dev=__in_dev_get_rtnl(dev);
if (in_dev) {
/* Any address will do - we take the first. We already
have the first two bytes filled with 0xfc, from
plip_init_dev(). */
struct in_ifaddr *ifa=in_dev->ifa_list;
if (ifa != NULL) {
memcpy(dev->dev_addr+2, &ifa->ifa_local, 4);
}
}
netif_start_queue (dev);
return 0;
}
/* The inverse routine to plip_open (). */
static int
plip_close(struct net_device *dev)
{
struct net_local *nl = netdev_priv(dev);
struct plip_local *snd = &nl->snd_data;
struct plip_local *rcv = &nl->rcv_data;
netif_stop_queue (dev);
DISABLE(dev->irq);
synchronize_irq(dev->irq);
if (dev->irq == -1)
{
init_completion(&nl->killed_timer_cmp);
atomic_set (&nl->kill_timer, 1);
wait_for_completion(&nl->killed_timer_cmp);
}
#ifdef NOTDEF
outb(0x00, PAR_DATA(dev));
#endif
nl->is_deferred = 0;
nl->connection = PLIP_CN_NONE;
if (nl->port_owner) {
parport_release(nl->pardev);
nl->port_owner = 0;
}
snd->state = PLIP_PK_DONE;
if (snd->skb) {
dev_kfree_skb(snd->skb);
snd->skb = NULL;
}
rcv->state = PLIP_PK_DONE;
if (rcv->skb) {
kfree_skb(rcv->skb);
rcv->skb = NULL;
}
#ifdef NOTDEF
/* Reset. */
outb(0x00, PAR_CONTROL(dev));
#endif
return 0;
}
static int
plip_preempt(void *handle)
{
struct net_device *dev = (struct net_device *)handle;
struct net_local *nl = netdev_priv(dev);
/* Stand our ground if a datagram is on the wire */
if (nl->connection != PLIP_CN_NONE) {
nl->should_relinquish = 1;
return 1;
}
nl->port_owner = 0; /* Remember that we released the bus */
return 0;
}
static void
plip_wakeup(void *handle)
{
struct net_device *dev = (struct net_device *)handle;
struct net_local *nl = netdev_priv(dev);
if (nl->port_owner) {
/* Why are we being woken up? */
printk(KERN_DEBUG "%s: why am I being woken up?\n", dev->name);
if (!parport_claim(nl->pardev))
/* bus_owner is already set (but why?) */
printk(KERN_DEBUG "%s: I'm broken.\n", dev->name);
else
return;
}
if (!(dev->flags & IFF_UP))
/* Don't need the port when the interface is down */
return;
if (!parport_claim(nl->pardev)) {
nl->port_owner = 1;
/* Clear the data port. */
write_data (dev, 0x00);
}
}
static int
plip_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct net_local *nl = netdev_priv(dev);
struct plipconf *pc = (struct plipconf *) &rq->ifr_ifru;
if (cmd != SIOCDEVPLIP)
return -EOPNOTSUPP;
switch(pc->pcmd) {
case PLIP_GET_TIMEOUT:
pc->trigger = nl->trigger;
pc->nibble = nl->nibble;
break;
case PLIP_SET_TIMEOUT:
if(!capable(CAP_NET_ADMIN))
return -EPERM;
nl->trigger = pc->trigger;
nl->nibble = pc->nibble;
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int parport[PLIP_MAX] = { [0 ... PLIP_MAX-1] = -1 };
static int timid;
module_param_array(parport, int, NULL, 0);
module_param(timid, int, 0);
MODULE_PARM_DESC(parport, "List of parport device numbers to use by plip");
static struct net_device *dev_plip[PLIP_MAX] = { NULL, };
static inline int
plip_searchfor(int list[], int a)
{
int i;
for (i = 0; i < PLIP_MAX && list[i] != -1; i++) {
if (list[i] == a) return 1;
}
return 0;
}
/* plip_attach() is called (by the parport code) when a port is
* available to use. */
static void plip_attach (struct parport *port)
{
static int unit;
struct net_device *dev;
struct net_local *nl;
char name[IFNAMSIZ];
if ((parport[0] == -1 && (!timid || !port->devices)) ||
plip_searchfor(parport, port->number)) {
if (unit == PLIP_MAX) {
printk(KERN_ERR "plip: too many devices\n");
return;
}
sprintf(name, "plip%d", unit);
dev = alloc_etherdev(sizeof(struct net_local));
if (!dev) {
printk(KERN_ERR "plip: memory squeeze\n");
return;
}
strcpy(dev->name, name);
dev->irq = port->irq;
dev->base_addr = port->base;
if (port->irq == -1) {
printk(KERN_INFO "plip: %s has no IRQ. Using IRQ-less mode,"
"which is fairly inefficient!\n", port->name);
}
nl = netdev_priv(dev);
nl->dev = dev;
nl->pardev = parport_register_device(port, dev->name, plip_preempt,
plip_wakeup, plip_interrupt,
0, dev);
if (!nl->pardev) {
printk(KERN_ERR "%s: parport_register failed\n", name);
goto err_free_dev;
}
plip_init_netdev(dev);
if (register_netdev(dev)) {
printk(KERN_ERR "%s: network register failed\n", name);
goto err_parport_unregister;
}
printk(KERN_INFO "%s", version);
if (dev->irq != -1)
printk(KERN_INFO "%s: Parallel port at %#3lx, "
"using IRQ %d.\n",
dev->name, dev->base_addr, dev->irq);
else
printk(KERN_INFO "%s: Parallel port at %#3lx, "
"not using IRQ.\n",
dev->name, dev->base_addr);
dev_plip[unit++] = dev;
}
return;
err_parport_unregister:
parport_unregister_device(nl->pardev);
err_free_dev:
free_netdev(dev);
}
/* plip_detach() is called (by the parport code) when a port is
* no longer available to use. */
static void plip_detach (struct parport *port)
{
/* Nothing to do */
}
static struct parport_driver plip_driver = {
.name = "plip",
.attach = plip_attach,
.detach = plip_detach
};
static void __exit plip_cleanup_module (void)
{
struct net_device *dev;
int i;
parport_unregister_driver (&plip_driver);
for (i=0; i < PLIP_MAX; i++) {
if ((dev = dev_plip[i])) {
struct net_local *nl = netdev_priv(dev);
unregister_netdev(dev);
if (nl->port_owner)
parport_release(nl->pardev);
parport_unregister_device(nl->pardev);
free_netdev(dev);
dev_plip[i] = NULL;
}
}
}
#ifndef MODULE
static int parport_ptr;
static int __init plip_setup(char *str)
{
int ints[4];
str = get_options(str, ARRAY_SIZE(ints), ints);
/* Ugh. */
if (!strncmp(str, "parport", 7)) {
int n = simple_strtoul(str+7, NULL, 10);
if (parport_ptr < PLIP_MAX)
parport[parport_ptr++] = n;
else
printk(KERN_INFO "plip: too many ports, %s ignored.\n",
str);
} else if (!strcmp(str, "timid")) {
timid = 1;
} else {
if (ints[0] == 0 || ints[1] == 0) {
/* disable driver on "plip=" or "plip=0" */
parport[0] = -2;
} else {
printk(KERN_WARNING "warning: 'plip=0x%x' ignored\n",
ints[1]);
}
}
return 1;
}
__setup("plip=", plip_setup);
#endif /* !MODULE */
static int __init plip_init (void)
{
if (parport[0] == -2)
return 0;
if (parport[0] != -1 && timid) {
printk(KERN_WARNING "plip: warning, ignoring `timid' since specific ports given.\n");
timid = 0;
}
if (parport_register_driver (&plip_driver)) {
printk (KERN_WARNING "plip: couldn't register driver\n");
return 1;
}
return 0;
}
module_init(plip_init);
module_exit(plip_cleanup_module);
MODULE_LICENSE("GPL");
| gpl-2.0 |
bhanu9999/furryb | drivers/regulator/tps6586x-regulator.c | 4743 | 12257 | /*
* Regulator driver for TI TPS6586x
*
* Copyright (C) 2010 Compulab Ltd.
* Author: Mike Rapoport <mike@compulab.co.il>
*
* Based on da903x
* Copyright (C) 2006-2008 Marvell International Ltd.
* Copyright (C) 2008 Compulab Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/mfd/tps6586x.h>
/* supply control and voltage setting */
#define TPS6586X_SUPPLYENA 0x10
#define TPS6586X_SUPPLYENB 0x11
#define TPS6586X_SUPPLYENC 0x12
#define TPS6586X_SUPPLYEND 0x13
#define TPS6586X_SUPPLYENE 0x14
#define TPS6586X_VCC1 0x20
#define TPS6586X_VCC2 0x21
#define TPS6586X_SM1V1 0x23
#define TPS6586X_SM1V2 0x24
#define TPS6586X_SM1SL 0x25
#define TPS6586X_SM0V1 0x26
#define TPS6586X_SM0V2 0x27
#define TPS6586X_SM0SL 0x28
#define TPS6586X_LDO2AV1 0x29
#define TPS6586X_LDO2AV2 0x2A
#define TPS6586X_LDO2BV1 0x2F
#define TPS6586X_LDO2BV2 0x30
#define TPS6586X_LDO4V1 0x32
#define TPS6586X_LDO4V2 0x33
/* converter settings */
#define TPS6586X_SUPPLYV1 0x41
#define TPS6586X_SUPPLYV2 0x42
#define TPS6586X_SUPPLYV3 0x43
#define TPS6586X_SUPPLYV4 0x44
#define TPS6586X_SUPPLYV5 0x45
#define TPS6586X_SUPPLYV6 0x46
#define TPS6586X_SMODE1 0x47
#define TPS6586X_SMODE2 0x48
struct tps6586x_regulator {
struct regulator_desc desc;
int volt_reg;
int volt_shift;
int volt_nbits;
int enable_bit[2];
int enable_reg[2];
int *voltages;
/* for DVM regulators */
int go_reg;
int go_bit;
};
static inline struct device *to_tps6586x_dev(struct regulator_dev *rdev)
{
return rdev_get_dev(rdev)->parent->parent;
}
static int tps6586x_ldo_list_voltage(struct regulator_dev *rdev,
unsigned selector)
{
struct tps6586x_regulator *info = rdev_get_drvdata(rdev);
int rid = rdev_get_id(rdev);
/* LDO0 has minimal voltage 1.2V rather than 1.25V */
if ((rid == TPS6586X_ID_LDO_0) && (selector == 0))
return (info->voltages[0] - 50) * 1000;
return info->voltages[selector] * 1000;
}
static int __tps6586x_ldo_set_voltage(struct device *parent,
struct tps6586x_regulator *ri,
int min_uV, int max_uV,
unsigned *selector)
{
int val, uV;
uint8_t mask;
for (val = 0; val < ri->desc.n_voltages; val++) {
uV = ri->voltages[val] * 1000;
/* LDO0 has minimal voltage 1.2 rather than 1.25 */
if (ri->desc.id == TPS6586X_ID_LDO_0 && val == 0)
uV -= 50 * 1000;
/* use the first in-range value */
if (min_uV <= uV && uV <= max_uV) {
*selector = val;
val <<= ri->volt_shift;
mask = ((1 << ri->volt_nbits) - 1) << ri->volt_shift;
return tps6586x_update(parent, ri->volt_reg, val, mask);
}
}
return -EINVAL;
}
static int tps6586x_ldo_set_voltage(struct regulator_dev *rdev,
int min_uV, int max_uV, unsigned *selector)
{
struct tps6586x_regulator *ri = rdev_get_drvdata(rdev);
struct device *parent = to_tps6586x_dev(rdev);
return __tps6586x_ldo_set_voltage(parent, ri, min_uV, max_uV,
selector);
}
static int tps6586x_ldo_get_voltage(struct regulator_dev *rdev)
{
struct tps6586x_regulator *ri = rdev_get_drvdata(rdev);
struct device *parent = to_tps6586x_dev(rdev);
uint8_t val, mask;
int ret;
ret = tps6586x_read(parent, ri->volt_reg, &val);
if (ret)
return ret;
mask = ((1 << ri->volt_nbits) - 1) << ri->volt_shift;
val = (val & mask) >> ri->volt_shift;
if (val >= ri->desc.n_voltages)
BUG();
return ri->voltages[val] * 1000;
}
static int tps6586x_dvm_set_voltage(struct regulator_dev *rdev,
int min_uV, int max_uV, unsigned *selector)
{
struct tps6586x_regulator *ri = rdev_get_drvdata(rdev);
struct device *parent = to_tps6586x_dev(rdev);
int ret;
ret = __tps6586x_ldo_set_voltage(parent, ri, min_uV, max_uV,
selector);
if (ret)
return ret;
return tps6586x_set_bits(parent, ri->go_reg, 1 << ri->go_bit);
}
static int tps6586x_regulator_enable(struct regulator_dev *rdev)
{
struct tps6586x_regulator *ri = rdev_get_drvdata(rdev);
struct device *parent = to_tps6586x_dev(rdev);
return tps6586x_set_bits(parent, ri->enable_reg[0],
1 << ri->enable_bit[0]);
}
static int tps6586x_regulator_disable(struct regulator_dev *rdev)
{
struct tps6586x_regulator *ri = rdev_get_drvdata(rdev);
struct device *parent = to_tps6586x_dev(rdev);
return tps6586x_clr_bits(parent, ri->enable_reg[0],
1 << ri->enable_bit[0]);
}
static int tps6586x_regulator_is_enabled(struct regulator_dev *rdev)
{
struct tps6586x_regulator *ri = rdev_get_drvdata(rdev);
struct device *parent = to_tps6586x_dev(rdev);
uint8_t reg_val;
int ret;
ret = tps6586x_read(parent, ri->enable_reg[0], ®_val);
if (ret)
return ret;
return !!(reg_val & (1 << ri->enable_bit[0]));
}
static struct regulator_ops tps6586x_regulator_ldo_ops = {
.list_voltage = tps6586x_ldo_list_voltage,
.get_voltage = tps6586x_ldo_get_voltage,
.set_voltage = tps6586x_ldo_set_voltage,
.is_enabled = tps6586x_regulator_is_enabled,
.enable = tps6586x_regulator_enable,
.disable = tps6586x_regulator_disable,
};
static struct regulator_ops tps6586x_regulator_dvm_ops = {
.list_voltage = tps6586x_ldo_list_voltage,
.get_voltage = tps6586x_ldo_get_voltage,
.set_voltage = tps6586x_dvm_set_voltage,
.is_enabled = tps6586x_regulator_is_enabled,
.enable = tps6586x_regulator_enable,
.disable = tps6586x_regulator_disable,
};
static int tps6586x_ldo_voltages[] = {
1250, 1500, 1800, 2500, 2700, 2850, 3100, 3300,
};
static int tps6586x_ldo4_voltages[] = {
1700, 1725, 1750, 1775, 1800, 1825, 1850, 1875,
1900, 1925, 1950, 1975, 2000, 2025, 2050, 2075,
2100, 2125, 2150, 2175, 2200, 2225, 2250, 2275,
2300, 2325, 2350, 2375, 2400, 2425, 2450, 2475,
};
static int tps6586x_sm2_voltages[] = {
3000, 3050, 3100, 3150, 3200, 3250, 3300, 3350,
3400, 3450, 3500, 3550, 3600, 3650, 3700, 3750,
3800, 3850, 3900, 3950, 4000, 4050, 4100, 4150,
4200, 4250, 4300, 4350, 4400, 4450, 4500, 4550,
};
static int tps6586x_dvm_voltages[] = {
725, 750, 775, 800, 825, 850, 875, 900,
925, 950, 975, 1000, 1025, 1050, 1075, 1100,
1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300,
1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500,
};
#define TPS6586X_REGULATOR(_id, vdata, _ops, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1) \
.desc = { \
.name = "REG-" #_id, \
.ops = &tps6586x_regulator_##_ops, \
.type = REGULATOR_VOLTAGE, \
.id = TPS6586X_ID_##_id, \
.n_voltages = ARRAY_SIZE(tps6586x_##vdata##_voltages), \
.owner = THIS_MODULE, \
}, \
.volt_reg = TPS6586X_##vreg, \
.volt_shift = (shift), \
.volt_nbits = (nbits), \
.enable_reg[0] = TPS6586X_SUPPLY##ereg0, \
.enable_bit[0] = (ebit0), \
.enable_reg[1] = TPS6586X_SUPPLY##ereg1, \
.enable_bit[1] = (ebit1), \
.voltages = tps6586x_##vdata##_voltages,
#define TPS6586X_REGULATOR_DVM_GOREG(goreg, gobit) \
.go_reg = TPS6586X_##goreg, \
.go_bit = (gobit),
#define TPS6586X_LDO(_id, vdata, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1) \
{ \
TPS6586X_REGULATOR(_id, vdata, ldo_ops, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1) \
}
#define TPS6586X_DVM(_id, vdata, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1, goreg, gobit) \
{ \
TPS6586X_REGULATOR(_id, vdata, dvm_ops, vreg, shift, nbits, \
ereg0, ebit0, ereg1, ebit1) \
TPS6586X_REGULATOR_DVM_GOREG(goreg, gobit) \
}
static struct tps6586x_regulator tps6586x_regulator[] = {
TPS6586X_LDO(LDO_0, ldo, SUPPLYV1, 5, 3, ENC, 0, END, 0),
TPS6586X_LDO(LDO_3, ldo, SUPPLYV4, 0, 3, ENC, 2, END, 2),
TPS6586X_LDO(LDO_5, ldo, SUPPLYV6, 0, 3, ENE, 6, ENE, 6),
TPS6586X_LDO(LDO_6, ldo, SUPPLYV3, 0, 3, ENC, 4, END, 4),
TPS6586X_LDO(LDO_7, ldo, SUPPLYV3, 3, 3, ENC, 5, END, 5),
TPS6586X_LDO(LDO_8, ldo, SUPPLYV2, 5, 3, ENC, 6, END, 6),
TPS6586X_LDO(LDO_9, ldo, SUPPLYV6, 3, 3, ENE, 7, ENE, 7),
TPS6586X_LDO(LDO_RTC, ldo, SUPPLYV4, 3, 3, V4, 7, V4, 7),
TPS6586X_LDO(LDO_1, dvm, SUPPLYV1, 0, 5, ENC, 1, END, 1),
TPS6586X_LDO(SM_2, sm2, SUPPLYV2, 0, 5, ENC, 7, END, 7),
TPS6586X_DVM(LDO_2, dvm, LDO2BV1, 0, 5, ENA, 3, ENB, 3, VCC2, 6),
TPS6586X_DVM(LDO_4, ldo4, LDO4V1, 0, 5, ENC, 3, END, 3, VCC1, 6),
TPS6586X_DVM(SM_0, dvm, SM0V1, 0, 5, ENA, 1, ENB, 1, VCC1, 2),
TPS6586X_DVM(SM_1, dvm, SM1V1, 0, 5, ENA, 0, ENB, 0, VCC1, 0),
};
/*
* TPS6586X has 2 enable bits that are OR'ed to determine the actual
* regulator state. Clearing one of this bits allows switching
* regulator on and of with single register write.
*/
static inline int tps6586x_regulator_preinit(struct device *parent,
struct tps6586x_regulator *ri)
{
uint8_t val1, val2;
int ret;
if (ri->enable_reg[0] == ri->enable_reg[1] &&
ri->enable_bit[0] == ri->enable_bit[1])
return 0;
ret = tps6586x_read(parent, ri->enable_reg[0], &val1);
if (ret)
return ret;
ret = tps6586x_read(parent, ri->enable_reg[1], &val2);
if (ret)
return ret;
if (!(val2 & (1 << ri->enable_bit[1])))
return 0;
/*
* The regulator is on, but it's enabled with the bit we don't
* want to use, so we switch the enable bits
*/
if (!(val1 & (1 << ri->enable_bit[0]))) {
ret = tps6586x_set_bits(parent, ri->enable_reg[0],
1 << ri->enable_bit[0]);
if (ret)
return ret;
}
return tps6586x_clr_bits(parent, ri->enable_reg[1],
1 << ri->enable_bit[1]);
}
static int tps6586x_regulator_set_slew_rate(struct platform_device *pdev)
{
struct device *parent = pdev->dev.parent;
struct regulator_init_data *p = pdev->dev.platform_data;
struct tps6586x_settings *setting = p->driver_data;
uint8_t reg;
if (setting == NULL)
return 0;
if (!(setting->slew_rate & TPS6586X_SLEW_RATE_SET))
return 0;
/* only SM0 and SM1 can have the slew rate settings */
switch (pdev->id) {
case TPS6586X_ID_SM_0:
reg = TPS6586X_SM0SL;
break;
case TPS6586X_ID_SM_1:
reg = TPS6586X_SM1SL;
break;
default:
dev_warn(&pdev->dev, "Only SM0/SM1 can set slew rate\n");
return -EINVAL;
}
return tps6586x_write(parent, reg,
setting->slew_rate & TPS6586X_SLEW_RATE_MASK);
}
static inline struct tps6586x_regulator *find_regulator_info(int id)
{
struct tps6586x_regulator *ri;
int i;
for (i = 0; i < ARRAY_SIZE(tps6586x_regulator); i++) {
ri = &tps6586x_regulator[i];
if (ri->desc.id == id)
return ri;
}
return NULL;
}
static int __devinit tps6586x_regulator_probe(struct platform_device *pdev)
{
struct tps6586x_regulator *ri = NULL;
struct regulator_dev *rdev;
int id = pdev->id;
int err;
dev_dbg(&pdev->dev, "Probing regulator %d\n", id);
ri = find_regulator_info(id);
if (ri == NULL) {
dev_err(&pdev->dev, "invalid regulator ID specified\n");
return -EINVAL;
}
err = tps6586x_regulator_preinit(pdev->dev.parent, ri);
if (err)
return err;
rdev = regulator_register(&ri->desc, &pdev->dev,
pdev->dev.platform_data, ri, NULL);
if (IS_ERR(rdev)) {
dev_err(&pdev->dev, "failed to register regulator %s\n",
ri->desc.name);
return PTR_ERR(rdev);
}
platform_set_drvdata(pdev, rdev);
return tps6586x_regulator_set_slew_rate(pdev);
}
static int __devexit tps6586x_regulator_remove(struct platform_device *pdev)
{
struct regulator_dev *rdev = platform_get_drvdata(pdev);
regulator_unregister(rdev);
return 0;
}
static struct platform_driver tps6586x_regulator_driver = {
.driver = {
.name = "tps6586x-regulator",
.owner = THIS_MODULE,
},
.probe = tps6586x_regulator_probe,
.remove = __devexit_p(tps6586x_regulator_remove),
};
static int __init tps6586x_regulator_init(void)
{
return platform_driver_register(&tps6586x_regulator_driver);
}
subsys_initcall(tps6586x_regulator_init);
static void __exit tps6586x_regulator_exit(void)
{
platform_driver_unregister(&tps6586x_regulator_driver);
}
module_exit(tps6586x_regulator_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mike Rapoport <mike@compulab.co.il>");
MODULE_DESCRIPTION("Regulator Driver for TI TPS6586X PMIC");
MODULE_ALIAS("platform:tps6586x-regulator");
| gpl-2.0 |
evildemon0s/android_kernel_semc_msm7x30 | fs/xfs/xfs_quotaops.c | 5511 | 3145 | /*
* Copyright (c) 2008, Christoph Hellwig
* 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.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_sb.h"
#include "xfs_inum.h"
#include "xfs_log.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_quota.h"
#include "xfs_trans.h"
#include "xfs_bmap_btree.h"
#include "xfs_inode.h"
#include "xfs_qm.h"
#include <linux/quota.h>
STATIC int
xfs_quota_type(int type)
{
switch (type) {
case USRQUOTA:
return XFS_DQ_USER;
case GRPQUOTA:
return XFS_DQ_GROUP;
default:
return XFS_DQ_PROJ;
}
}
STATIC int
xfs_fs_get_xstate(
struct super_block *sb,
struct fs_quota_stat *fqs)
{
struct xfs_mount *mp = XFS_M(sb);
if (!XFS_IS_QUOTA_RUNNING(mp))
return -ENOSYS;
return -xfs_qm_scall_getqstat(mp, fqs);
}
STATIC int
xfs_fs_set_xstate(
struct super_block *sb,
unsigned int uflags,
int op)
{
struct xfs_mount *mp = XFS_M(sb);
unsigned int flags = 0;
if (sb->s_flags & MS_RDONLY)
return -EROFS;
if (op != Q_XQUOTARM && !XFS_IS_QUOTA_RUNNING(mp))
return -ENOSYS;
if (uflags & FS_QUOTA_UDQ_ACCT)
flags |= XFS_UQUOTA_ACCT;
if (uflags & FS_QUOTA_PDQ_ACCT)
flags |= XFS_PQUOTA_ACCT;
if (uflags & FS_QUOTA_GDQ_ACCT)
flags |= XFS_GQUOTA_ACCT;
if (uflags & FS_QUOTA_UDQ_ENFD)
flags |= XFS_UQUOTA_ENFD;
if (uflags & (FS_QUOTA_PDQ_ENFD|FS_QUOTA_GDQ_ENFD))
flags |= XFS_OQUOTA_ENFD;
switch (op) {
case Q_XQUOTAON:
return -xfs_qm_scall_quotaon(mp, flags);
case Q_XQUOTAOFF:
if (!XFS_IS_QUOTA_ON(mp))
return -EINVAL;
return -xfs_qm_scall_quotaoff(mp, flags);
case Q_XQUOTARM:
if (XFS_IS_QUOTA_ON(mp))
return -EINVAL;
return -xfs_qm_scall_trunc_qfiles(mp, flags);
}
return -EINVAL;
}
STATIC int
xfs_fs_get_dqblk(
struct super_block *sb,
int type,
qid_t id,
struct fs_disk_quota *fdq)
{
struct xfs_mount *mp = XFS_M(sb);
if (!XFS_IS_QUOTA_RUNNING(mp))
return -ENOSYS;
if (!XFS_IS_QUOTA_ON(mp))
return -ESRCH;
return -xfs_qm_scall_getquota(mp, id, xfs_quota_type(type), fdq);
}
STATIC int
xfs_fs_set_dqblk(
struct super_block *sb,
int type,
qid_t id,
struct fs_disk_quota *fdq)
{
struct xfs_mount *mp = XFS_M(sb);
if (sb->s_flags & MS_RDONLY)
return -EROFS;
if (!XFS_IS_QUOTA_RUNNING(mp))
return -ENOSYS;
if (!XFS_IS_QUOTA_ON(mp))
return -ESRCH;
return -xfs_qm_scall_setqlim(mp, id, xfs_quota_type(type), fdq);
}
const struct quotactl_ops xfs_quotactl_operations = {
.get_xstate = xfs_fs_get_xstate,
.set_xstate = xfs_fs_set_xstate,
.get_dqblk = xfs_fs_get_dqblk,
.set_dqblk = xfs_fs_set_dqblk,
};
| gpl-2.0 |
extremegf/debian | net/sunrpc/auth_gss/gss_krb5_crypto.c | 7815 | 24980 | /*
* linux/net/sunrpc/gss_krb5_crypto.c
*
* Copyright (c) 2000-2008 The Regents of the University of Michigan.
* All rights reserved.
*
* Andy Adamson <andros@umich.edu>
* Bruce Fields <bfields@umich.edu>
*/
/*
* Copyright (C) 1998 by the FundsXpress, INC.
*
* All rights reserved.
*
* Export of this software from the United States of America may require
* a specific license from the United States Government. It is the
* responsibility of any person or organization contemplating export to
* obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of FundsXpress. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. FundsXpress makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <linux/err.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/scatterlist.h>
#include <linux/crypto.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/random.h>
#include <linux/sunrpc/gss_krb5.h>
#include <linux/sunrpc/xdr.h>
#ifdef RPC_DEBUG
# define RPCDBG_FACILITY RPCDBG_AUTH
#endif
u32
krb5_encrypt(
struct crypto_blkcipher *tfm,
void * iv,
void * in,
void * out,
int length)
{
u32 ret = -EINVAL;
struct scatterlist sg[1];
u8 local_iv[GSS_KRB5_MAX_BLOCKSIZE] = {0};
struct blkcipher_desc desc = { .tfm = tfm, .info = local_iv };
if (length % crypto_blkcipher_blocksize(tfm) != 0)
goto out;
if (crypto_blkcipher_ivsize(tfm) > GSS_KRB5_MAX_BLOCKSIZE) {
dprintk("RPC: gss_k5encrypt: tfm iv size too large %d\n",
crypto_blkcipher_ivsize(tfm));
goto out;
}
if (iv)
memcpy(local_iv, iv, crypto_blkcipher_ivsize(tfm));
memcpy(out, in, length);
sg_init_one(sg, out, length);
ret = crypto_blkcipher_encrypt_iv(&desc, sg, sg, length);
out:
dprintk("RPC: krb5_encrypt returns %d\n", ret);
return ret;
}
u32
krb5_decrypt(
struct crypto_blkcipher *tfm,
void * iv,
void * in,
void * out,
int length)
{
u32 ret = -EINVAL;
struct scatterlist sg[1];
u8 local_iv[GSS_KRB5_MAX_BLOCKSIZE] = {0};
struct blkcipher_desc desc = { .tfm = tfm, .info = local_iv };
if (length % crypto_blkcipher_blocksize(tfm) != 0)
goto out;
if (crypto_blkcipher_ivsize(tfm) > GSS_KRB5_MAX_BLOCKSIZE) {
dprintk("RPC: gss_k5decrypt: tfm iv size too large %d\n",
crypto_blkcipher_ivsize(tfm));
goto out;
}
if (iv)
memcpy(local_iv,iv, crypto_blkcipher_ivsize(tfm));
memcpy(out, in, length);
sg_init_one(sg, out, length);
ret = crypto_blkcipher_decrypt_iv(&desc, sg, sg, length);
out:
dprintk("RPC: gss_k5decrypt returns %d\n",ret);
return ret;
}
static int
checksummer(struct scatterlist *sg, void *data)
{
struct hash_desc *desc = data;
return crypto_hash_update(desc, sg, sg->length);
}
static int
arcfour_hmac_md5_usage_to_salt(unsigned int usage, u8 salt[4])
{
unsigned int ms_usage;
switch (usage) {
case KG_USAGE_SIGN:
ms_usage = 15;
break;
case KG_USAGE_SEAL:
ms_usage = 13;
break;
default:
return -EINVAL;
}
salt[0] = (ms_usage >> 0) & 0xff;
salt[1] = (ms_usage >> 8) & 0xff;
salt[2] = (ms_usage >> 16) & 0xff;
salt[3] = (ms_usage >> 24) & 0xff;
return 0;
}
static u32
make_checksum_hmac_md5(struct krb5_ctx *kctx, char *header, int hdrlen,
struct xdr_buf *body, int body_offset, u8 *cksumkey,
unsigned int usage, struct xdr_netobj *cksumout)
{
struct hash_desc desc;
struct scatterlist sg[1];
int err;
u8 checksumdata[GSS_KRB5_MAX_CKSUM_LEN];
u8 rc4salt[4];
struct crypto_hash *md5;
struct crypto_hash *hmac_md5;
if (cksumkey == NULL)
return GSS_S_FAILURE;
if (cksumout->len < kctx->gk5e->cksumlength) {
dprintk("%s: checksum buffer length, %u, too small for %s\n",
__func__, cksumout->len, kctx->gk5e->name);
return GSS_S_FAILURE;
}
if (arcfour_hmac_md5_usage_to_salt(usage, rc4salt)) {
dprintk("%s: invalid usage value %u\n", __func__, usage);
return GSS_S_FAILURE;
}
md5 = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(md5))
return GSS_S_FAILURE;
hmac_md5 = crypto_alloc_hash(kctx->gk5e->cksum_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(hmac_md5)) {
crypto_free_hash(md5);
return GSS_S_FAILURE;
}
desc.tfm = md5;
desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
err = crypto_hash_init(&desc);
if (err)
goto out;
sg_init_one(sg, rc4salt, 4);
err = crypto_hash_update(&desc, sg, 4);
if (err)
goto out;
sg_init_one(sg, header, hdrlen);
err = crypto_hash_update(&desc, sg, hdrlen);
if (err)
goto out;
err = xdr_process_buf(body, body_offset, body->len - body_offset,
checksummer, &desc);
if (err)
goto out;
err = crypto_hash_final(&desc, checksumdata);
if (err)
goto out;
desc.tfm = hmac_md5;
desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
err = crypto_hash_init(&desc);
if (err)
goto out;
err = crypto_hash_setkey(hmac_md5, cksumkey, kctx->gk5e->keylength);
if (err)
goto out;
sg_init_one(sg, checksumdata, crypto_hash_digestsize(md5));
err = crypto_hash_digest(&desc, sg, crypto_hash_digestsize(md5),
checksumdata);
if (err)
goto out;
memcpy(cksumout->data, checksumdata, kctx->gk5e->cksumlength);
cksumout->len = kctx->gk5e->cksumlength;
out:
crypto_free_hash(md5);
crypto_free_hash(hmac_md5);
return err ? GSS_S_FAILURE : 0;
}
/*
* checksum the plaintext data and hdrlen bytes of the token header
* The checksum is performed over the first 8 bytes of the
* gss token header and then over the data body
*/
u32
make_checksum(struct krb5_ctx *kctx, char *header, int hdrlen,
struct xdr_buf *body, int body_offset, u8 *cksumkey,
unsigned int usage, struct xdr_netobj *cksumout)
{
struct hash_desc desc;
struct scatterlist sg[1];
int err;
u8 checksumdata[GSS_KRB5_MAX_CKSUM_LEN];
unsigned int checksumlen;
if (kctx->gk5e->ctype == CKSUMTYPE_HMAC_MD5_ARCFOUR)
return make_checksum_hmac_md5(kctx, header, hdrlen,
body, body_offset,
cksumkey, usage, cksumout);
if (cksumout->len < kctx->gk5e->cksumlength) {
dprintk("%s: checksum buffer length, %u, too small for %s\n",
__func__, cksumout->len, kctx->gk5e->name);
return GSS_S_FAILURE;
}
desc.tfm = crypto_alloc_hash(kctx->gk5e->cksum_name, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(desc.tfm))
return GSS_S_FAILURE;
desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
checksumlen = crypto_hash_digestsize(desc.tfm);
if (cksumkey != NULL) {
err = crypto_hash_setkey(desc.tfm, cksumkey,
kctx->gk5e->keylength);
if (err)
goto out;
}
err = crypto_hash_init(&desc);
if (err)
goto out;
sg_init_one(sg, header, hdrlen);
err = crypto_hash_update(&desc, sg, hdrlen);
if (err)
goto out;
err = xdr_process_buf(body, body_offset, body->len - body_offset,
checksummer, &desc);
if (err)
goto out;
err = crypto_hash_final(&desc, checksumdata);
if (err)
goto out;
switch (kctx->gk5e->ctype) {
case CKSUMTYPE_RSA_MD5:
err = kctx->gk5e->encrypt(kctx->seq, NULL, checksumdata,
checksumdata, checksumlen);
if (err)
goto out;
memcpy(cksumout->data,
checksumdata + checksumlen - kctx->gk5e->cksumlength,
kctx->gk5e->cksumlength);
break;
case CKSUMTYPE_HMAC_SHA1_DES3:
memcpy(cksumout->data, checksumdata, kctx->gk5e->cksumlength);
break;
default:
BUG();
break;
}
cksumout->len = kctx->gk5e->cksumlength;
out:
crypto_free_hash(desc.tfm);
return err ? GSS_S_FAILURE : 0;
}
/*
* checksum the plaintext data and hdrlen bytes of the token header
* Per rfc4121, sec. 4.2.4, the checksum is performed over the data
* body then over the first 16 octets of the MIC token
* Inclusion of the header data in the calculation of the
* checksum is optional.
*/
u32
make_checksum_v2(struct krb5_ctx *kctx, char *header, int hdrlen,
struct xdr_buf *body, int body_offset, u8 *cksumkey,
unsigned int usage, struct xdr_netobj *cksumout)
{
struct hash_desc desc;
struct scatterlist sg[1];
int err;
u8 checksumdata[GSS_KRB5_MAX_CKSUM_LEN];
unsigned int checksumlen;
if (kctx->gk5e->keyed_cksum == 0) {
dprintk("%s: expected keyed hash for %s\n",
__func__, kctx->gk5e->name);
return GSS_S_FAILURE;
}
if (cksumkey == NULL) {
dprintk("%s: no key supplied for %s\n",
__func__, kctx->gk5e->name);
return GSS_S_FAILURE;
}
desc.tfm = crypto_alloc_hash(kctx->gk5e->cksum_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(desc.tfm))
return GSS_S_FAILURE;
checksumlen = crypto_hash_digestsize(desc.tfm);
desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
err = crypto_hash_setkey(desc.tfm, cksumkey, kctx->gk5e->keylength);
if (err)
goto out;
err = crypto_hash_init(&desc);
if (err)
goto out;
err = xdr_process_buf(body, body_offset, body->len - body_offset,
checksummer, &desc);
if (err)
goto out;
if (header != NULL) {
sg_init_one(sg, header, hdrlen);
err = crypto_hash_update(&desc, sg, hdrlen);
if (err)
goto out;
}
err = crypto_hash_final(&desc, checksumdata);
if (err)
goto out;
cksumout->len = kctx->gk5e->cksumlength;
switch (kctx->gk5e->ctype) {
case CKSUMTYPE_HMAC_SHA1_96_AES128:
case CKSUMTYPE_HMAC_SHA1_96_AES256:
/* note that this truncates the hash */
memcpy(cksumout->data, checksumdata, kctx->gk5e->cksumlength);
break;
default:
BUG();
break;
}
out:
crypto_free_hash(desc.tfm);
return err ? GSS_S_FAILURE : 0;
}
struct encryptor_desc {
u8 iv[GSS_KRB5_MAX_BLOCKSIZE];
struct blkcipher_desc desc;
int pos;
struct xdr_buf *outbuf;
struct page **pages;
struct scatterlist infrags[4];
struct scatterlist outfrags[4];
int fragno;
int fraglen;
};
static int
encryptor(struct scatterlist *sg, void *data)
{
struct encryptor_desc *desc = data;
struct xdr_buf *outbuf = desc->outbuf;
struct page *in_page;
int thislen = desc->fraglen + sg->length;
int fraglen, ret;
int page_pos;
/* Worst case is 4 fragments: head, end of page 1, start
* of page 2, tail. Anything more is a bug. */
BUG_ON(desc->fragno > 3);
page_pos = desc->pos - outbuf->head[0].iov_len;
if (page_pos >= 0 && page_pos < outbuf->page_len) {
/* pages are not in place: */
int i = (page_pos + outbuf->page_base) >> PAGE_CACHE_SHIFT;
in_page = desc->pages[i];
} else {
in_page = sg_page(sg);
}
sg_set_page(&desc->infrags[desc->fragno], in_page, sg->length,
sg->offset);
sg_set_page(&desc->outfrags[desc->fragno], sg_page(sg), sg->length,
sg->offset);
desc->fragno++;
desc->fraglen += sg->length;
desc->pos += sg->length;
fraglen = thislen & (crypto_blkcipher_blocksize(desc->desc.tfm) - 1);
thislen -= fraglen;
if (thislen == 0)
return 0;
sg_mark_end(&desc->infrags[desc->fragno - 1]);
sg_mark_end(&desc->outfrags[desc->fragno - 1]);
ret = crypto_blkcipher_encrypt_iv(&desc->desc, desc->outfrags,
desc->infrags, thislen);
if (ret)
return ret;
sg_init_table(desc->infrags, 4);
sg_init_table(desc->outfrags, 4);
if (fraglen) {
sg_set_page(&desc->outfrags[0], sg_page(sg), fraglen,
sg->offset + sg->length - fraglen);
desc->infrags[0] = desc->outfrags[0];
sg_assign_page(&desc->infrags[0], in_page);
desc->fragno = 1;
desc->fraglen = fraglen;
} else {
desc->fragno = 0;
desc->fraglen = 0;
}
return 0;
}
int
gss_encrypt_xdr_buf(struct crypto_blkcipher *tfm, struct xdr_buf *buf,
int offset, struct page **pages)
{
int ret;
struct encryptor_desc desc;
BUG_ON((buf->len - offset) % crypto_blkcipher_blocksize(tfm) != 0);
memset(desc.iv, 0, sizeof(desc.iv));
desc.desc.tfm = tfm;
desc.desc.info = desc.iv;
desc.desc.flags = 0;
desc.pos = offset;
desc.outbuf = buf;
desc.pages = pages;
desc.fragno = 0;
desc.fraglen = 0;
sg_init_table(desc.infrags, 4);
sg_init_table(desc.outfrags, 4);
ret = xdr_process_buf(buf, offset, buf->len - offset, encryptor, &desc);
return ret;
}
struct decryptor_desc {
u8 iv[GSS_KRB5_MAX_BLOCKSIZE];
struct blkcipher_desc desc;
struct scatterlist frags[4];
int fragno;
int fraglen;
};
static int
decryptor(struct scatterlist *sg, void *data)
{
struct decryptor_desc *desc = data;
int thislen = desc->fraglen + sg->length;
int fraglen, ret;
/* Worst case is 4 fragments: head, end of page 1, start
* of page 2, tail. Anything more is a bug. */
BUG_ON(desc->fragno > 3);
sg_set_page(&desc->frags[desc->fragno], sg_page(sg), sg->length,
sg->offset);
desc->fragno++;
desc->fraglen += sg->length;
fraglen = thislen & (crypto_blkcipher_blocksize(desc->desc.tfm) - 1);
thislen -= fraglen;
if (thislen == 0)
return 0;
sg_mark_end(&desc->frags[desc->fragno - 1]);
ret = crypto_blkcipher_decrypt_iv(&desc->desc, desc->frags,
desc->frags, thislen);
if (ret)
return ret;
sg_init_table(desc->frags, 4);
if (fraglen) {
sg_set_page(&desc->frags[0], sg_page(sg), fraglen,
sg->offset + sg->length - fraglen);
desc->fragno = 1;
desc->fraglen = fraglen;
} else {
desc->fragno = 0;
desc->fraglen = 0;
}
return 0;
}
int
gss_decrypt_xdr_buf(struct crypto_blkcipher *tfm, struct xdr_buf *buf,
int offset)
{
struct decryptor_desc desc;
/* XXXJBF: */
BUG_ON((buf->len - offset) % crypto_blkcipher_blocksize(tfm) != 0);
memset(desc.iv, 0, sizeof(desc.iv));
desc.desc.tfm = tfm;
desc.desc.info = desc.iv;
desc.desc.flags = 0;
desc.fragno = 0;
desc.fraglen = 0;
sg_init_table(desc.frags, 4);
return xdr_process_buf(buf, offset, buf->len - offset, decryptor, &desc);
}
/*
* This function makes the assumption that it was ultimately called
* from gss_wrap().
*
* The client auth_gss code moves any existing tail data into a
* separate page before calling gss_wrap.
* The server svcauth_gss code ensures that both the head and the
* tail have slack space of RPC_MAX_AUTH_SIZE before calling gss_wrap.
*
* Even with that guarantee, this function may be called more than
* once in the processing of gss_wrap(). The best we can do is
* verify at compile-time (see GSS_KRB5_SLACK_CHECK) that the
* largest expected shift will fit within RPC_MAX_AUTH_SIZE.
* At run-time we can verify that a single invocation of this
* function doesn't attempt to use more the RPC_MAX_AUTH_SIZE.
*/
int
xdr_extend_head(struct xdr_buf *buf, unsigned int base, unsigned int shiftlen)
{
u8 *p;
if (shiftlen == 0)
return 0;
BUILD_BUG_ON(GSS_KRB5_MAX_SLACK_NEEDED > RPC_MAX_AUTH_SIZE);
BUG_ON(shiftlen > RPC_MAX_AUTH_SIZE);
p = buf->head[0].iov_base + base;
memmove(p + shiftlen, p, buf->head[0].iov_len - base);
buf->head[0].iov_len += shiftlen;
buf->len += shiftlen;
return 0;
}
static u32
gss_krb5_cts_crypt(struct crypto_blkcipher *cipher, struct xdr_buf *buf,
u32 offset, u8 *iv, struct page **pages, int encrypt)
{
u32 ret;
struct scatterlist sg[1];
struct blkcipher_desc desc = { .tfm = cipher, .info = iv };
u8 data[GSS_KRB5_MAX_BLOCKSIZE * 2];
struct page **save_pages;
u32 len = buf->len - offset;
if (len > ARRAY_SIZE(data)) {
WARN_ON(0);
return -ENOMEM;
}
/*
* For encryption, we want to read from the cleartext
* page cache pages, and write the encrypted data to
* the supplied xdr_buf pages.
*/
save_pages = buf->pages;
if (encrypt)
buf->pages = pages;
ret = read_bytes_from_xdr_buf(buf, offset, data, len);
buf->pages = save_pages;
if (ret)
goto out;
sg_init_one(sg, data, len);
if (encrypt)
ret = crypto_blkcipher_encrypt_iv(&desc, sg, sg, len);
else
ret = crypto_blkcipher_decrypt_iv(&desc, sg, sg, len);
if (ret)
goto out;
ret = write_bytes_to_xdr_buf(buf, offset, data, len);
out:
return ret;
}
u32
gss_krb5_aes_encrypt(struct krb5_ctx *kctx, u32 offset,
struct xdr_buf *buf, int ec, struct page **pages)
{
u32 err;
struct xdr_netobj hmac;
u8 *cksumkey;
u8 *ecptr;
struct crypto_blkcipher *cipher, *aux_cipher;
int blocksize;
struct page **save_pages;
int nblocks, nbytes;
struct encryptor_desc desc;
u32 cbcbytes;
unsigned int usage;
if (kctx->initiate) {
cipher = kctx->initiator_enc;
aux_cipher = kctx->initiator_enc_aux;
cksumkey = kctx->initiator_integ;
usage = KG_USAGE_INITIATOR_SEAL;
} else {
cipher = kctx->acceptor_enc;
aux_cipher = kctx->acceptor_enc_aux;
cksumkey = kctx->acceptor_integ;
usage = KG_USAGE_ACCEPTOR_SEAL;
}
blocksize = crypto_blkcipher_blocksize(cipher);
/* hide the gss token header and insert the confounder */
offset += GSS_KRB5_TOK_HDR_LEN;
if (xdr_extend_head(buf, offset, kctx->gk5e->conflen))
return GSS_S_FAILURE;
gss_krb5_make_confounder(buf->head[0].iov_base + offset, kctx->gk5e->conflen);
offset -= GSS_KRB5_TOK_HDR_LEN;
if (buf->tail[0].iov_base != NULL) {
ecptr = buf->tail[0].iov_base + buf->tail[0].iov_len;
} else {
buf->tail[0].iov_base = buf->head[0].iov_base
+ buf->head[0].iov_len;
buf->tail[0].iov_len = 0;
ecptr = buf->tail[0].iov_base;
}
memset(ecptr, 'X', ec);
buf->tail[0].iov_len += ec;
buf->len += ec;
/* copy plaintext gss token header after filler (if any) */
memcpy(ecptr + ec, buf->head[0].iov_base + offset,
GSS_KRB5_TOK_HDR_LEN);
buf->tail[0].iov_len += GSS_KRB5_TOK_HDR_LEN;
buf->len += GSS_KRB5_TOK_HDR_LEN;
/* Do the HMAC */
hmac.len = GSS_KRB5_MAX_CKSUM_LEN;
hmac.data = buf->tail[0].iov_base + buf->tail[0].iov_len;
/*
* When we are called, pages points to the real page cache
* data -- which we can't go and encrypt! buf->pages points
* to scratch pages which we are going to send off to the
* client/server. Swap in the plaintext pages to calculate
* the hmac.
*/
save_pages = buf->pages;
buf->pages = pages;
err = make_checksum_v2(kctx, NULL, 0, buf,
offset + GSS_KRB5_TOK_HDR_LEN,
cksumkey, usage, &hmac);
buf->pages = save_pages;
if (err)
return GSS_S_FAILURE;
nbytes = buf->len - offset - GSS_KRB5_TOK_HDR_LEN;
nblocks = (nbytes + blocksize - 1) / blocksize;
cbcbytes = 0;
if (nblocks > 2)
cbcbytes = (nblocks - 2) * blocksize;
memset(desc.iv, 0, sizeof(desc.iv));
if (cbcbytes) {
desc.pos = offset + GSS_KRB5_TOK_HDR_LEN;
desc.fragno = 0;
desc.fraglen = 0;
desc.pages = pages;
desc.outbuf = buf;
desc.desc.info = desc.iv;
desc.desc.flags = 0;
desc.desc.tfm = aux_cipher;
sg_init_table(desc.infrags, 4);
sg_init_table(desc.outfrags, 4);
err = xdr_process_buf(buf, offset + GSS_KRB5_TOK_HDR_LEN,
cbcbytes, encryptor, &desc);
if (err)
goto out_err;
}
/* Make sure IV carries forward from any CBC results. */
err = gss_krb5_cts_crypt(cipher, buf,
offset + GSS_KRB5_TOK_HDR_LEN + cbcbytes,
desc.iv, pages, 1);
if (err) {
err = GSS_S_FAILURE;
goto out_err;
}
/* Now update buf to account for HMAC */
buf->tail[0].iov_len += kctx->gk5e->cksumlength;
buf->len += kctx->gk5e->cksumlength;
out_err:
if (err)
err = GSS_S_FAILURE;
return err;
}
u32
gss_krb5_aes_decrypt(struct krb5_ctx *kctx, u32 offset, struct xdr_buf *buf,
u32 *headskip, u32 *tailskip)
{
struct xdr_buf subbuf;
u32 ret = 0;
u8 *cksum_key;
struct crypto_blkcipher *cipher, *aux_cipher;
struct xdr_netobj our_hmac_obj;
u8 our_hmac[GSS_KRB5_MAX_CKSUM_LEN];
u8 pkt_hmac[GSS_KRB5_MAX_CKSUM_LEN];
int nblocks, blocksize, cbcbytes;
struct decryptor_desc desc;
unsigned int usage;
if (kctx->initiate) {
cipher = kctx->acceptor_enc;
aux_cipher = kctx->acceptor_enc_aux;
cksum_key = kctx->acceptor_integ;
usage = KG_USAGE_ACCEPTOR_SEAL;
} else {
cipher = kctx->initiator_enc;
aux_cipher = kctx->initiator_enc_aux;
cksum_key = kctx->initiator_integ;
usage = KG_USAGE_INITIATOR_SEAL;
}
blocksize = crypto_blkcipher_blocksize(cipher);
/* create a segment skipping the header and leaving out the checksum */
xdr_buf_subsegment(buf, &subbuf, offset + GSS_KRB5_TOK_HDR_LEN,
(buf->len - offset - GSS_KRB5_TOK_HDR_LEN -
kctx->gk5e->cksumlength));
nblocks = (subbuf.len + blocksize - 1) / blocksize;
cbcbytes = 0;
if (nblocks > 2)
cbcbytes = (nblocks - 2) * blocksize;
memset(desc.iv, 0, sizeof(desc.iv));
if (cbcbytes) {
desc.fragno = 0;
desc.fraglen = 0;
desc.desc.info = desc.iv;
desc.desc.flags = 0;
desc.desc.tfm = aux_cipher;
sg_init_table(desc.frags, 4);
ret = xdr_process_buf(&subbuf, 0, cbcbytes, decryptor, &desc);
if (ret)
goto out_err;
}
/* Make sure IV carries forward from any CBC results. */
ret = gss_krb5_cts_crypt(cipher, &subbuf, cbcbytes, desc.iv, NULL, 0);
if (ret)
goto out_err;
/* Calculate our hmac over the plaintext data */
our_hmac_obj.len = sizeof(our_hmac);
our_hmac_obj.data = our_hmac;
ret = make_checksum_v2(kctx, NULL, 0, &subbuf, 0,
cksum_key, usage, &our_hmac_obj);
if (ret)
goto out_err;
/* Get the packet's hmac value */
ret = read_bytes_from_xdr_buf(buf, buf->len - kctx->gk5e->cksumlength,
pkt_hmac, kctx->gk5e->cksumlength);
if (ret)
goto out_err;
if (memcmp(pkt_hmac, our_hmac, kctx->gk5e->cksumlength) != 0) {
ret = GSS_S_BAD_SIG;
goto out_err;
}
*headskip = kctx->gk5e->conflen;
*tailskip = kctx->gk5e->cksumlength;
out_err:
if (ret && ret != GSS_S_BAD_SIG)
ret = GSS_S_FAILURE;
return ret;
}
/*
* Compute Kseq given the initial session key and the checksum.
* Set the key of the given cipher.
*/
int
krb5_rc4_setup_seq_key(struct krb5_ctx *kctx, struct crypto_blkcipher *cipher,
unsigned char *cksum)
{
struct crypto_hash *hmac;
struct hash_desc desc;
struct scatterlist sg[1];
u8 Kseq[GSS_KRB5_MAX_KEYLEN];
u32 zeroconstant = 0;
int err;
dprintk("%s: entered\n", __func__);
hmac = crypto_alloc_hash(kctx->gk5e->cksum_name, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hmac)) {
dprintk("%s: error %ld, allocating hash '%s'\n",
__func__, PTR_ERR(hmac), kctx->gk5e->cksum_name);
return PTR_ERR(hmac);
}
desc.tfm = hmac;
desc.flags = 0;
err = crypto_hash_init(&desc);
if (err)
goto out_err;
/* Compute intermediate Kseq from session key */
err = crypto_hash_setkey(hmac, kctx->Ksess, kctx->gk5e->keylength);
if (err)
goto out_err;
sg_init_table(sg, 1);
sg_set_buf(sg, &zeroconstant, 4);
err = crypto_hash_digest(&desc, sg, 4, Kseq);
if (err)
goto out_err;
/* Compute final Kseq from the checksum and intermediate Kseq */
err = crypto_hash_setkey(hmac, Kseq, kctx->gk5e->keylength);
if (err)
goto out_err;
sg_set_buf(sg, cksum, 8);
err = crypto_hash_digest(&desc, sg, 8, Kseq);
if (err)
goto out_err;
err = crypto_blkcipher_setkey(cipher, Kseq, kctx->gk5e->keylength);
if (err)
goto out_err;
err = 0;
out_err:
crypto_free_hash(hmac);
dprintk("%s: returning %d\n", __func__, err);
return err;
}
/*
* Compute Kcrypt given the initial session key and the plaintext seqnum.
* Set the key of cipher kctx->enc.
*/
int
krb5_rc4_setup_enc_key(struct krb5_ctx *kctx, struct crypto_blkcipher *cipher,
s32 seqnum)
{
struct crypto_hash *hmac;
struct hash_desc desc;
struct scatterlist sg[1];
u8 Kcrypt[GSS_KRB5_MAX_KEYLEN];
u8 zeroconstant[4] = {0};
u8 seqnumarray[4];
int err, i;
dprintk("%s: entered, seqnum %u\n", __func__, seqnum);
hmac = crypto_alloc_hash(kctx->gk5e->cksum_name, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hmac)) {
dprintk("%s: error %ld, allocating hash '%s'\n",
__func__, PTR_ERR(hmac), kctx->gk5e->cksum_name);
return PTR_ERR(hmac);
}
desc.tfm = hmac;
desc.flags = 0;
err = crypto_hash_init(&desc);
if (err)
goto out_err;
/* Compute intermediate Kcrypt from session key */
for (i = 0; i < kctx->gk5e->keylength; i++)
Kcrypt[i] = kctx->Ksess[i] ^ 0xf0;
err = crypto_hash_setkey(hmac, Kcrypt, kctx->gk5e->keylength);
if (err)
goto out_err;
sg_init_table(sg, 1);
sg_set_buf(sg, zeroconstant, 4);
err = crypto_hash_digest(&desc, sg, 4, Kcrypt);
if (err)
goto out_err;
/* Compute final Kcrypt from the seqnum and intermediate Kcrypt */
err = crypto_hash_setkey(hmac, Kcrypt, kctx->gk5e->keylength);
if (err)
goto out_err;
seqnumarray[0] = (unsigned char) ((seqnum >> 24) & 0xff);
seqnumarray[1] = (unsigned char) ((seqnum >> 16) & 0xff);
seqnumarray[2] = (unsigned char) ((seqnum >> 8) & 0xff);
seqnumarray[3] = (unsigned char) ((seqnum >> 0) & 0xff);
sg_set_buf(sg, seqnumarray, 4);
err = crypto_hash_digest(&desc, sg, 4, Kcrypt);
if (err)
goto out_err;
err = crypto_blkcipher_setkey(cipher, Kcrypt, kctx->gk5e->keylength);
if (err)
goto out_err;
err = 0;
out_err:
crypto_free_hash(hmac);
dprintk("%s: returning %d\n", __func__, err);
return err;
}
| gpl-2.0 |
RR-msm7x30/samsung-kernel-msm7x30 | arch/mips/sgi-ip22/ip22-time.c | 7815 | 3652 | /*
* 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.
*
* Time operations for IP22 machines. Original code may come from
* Ralf Baechle or David S. Miller (sorry guys, i'm really not sure)
*
* Copyright (C) 2001 by Ladislav Michl
* Copyright (C) 2003, 06 Ralf Baechle (ralf@linux-mips.org)
*/
#include <linux/bcd.h>
#include <linux/i8253.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/time.h>
#include <linux/ftrace.h>
#include <asm/cpu.h>
#include <asm/mipsregs.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/time.h>
#include <asm/sgialib.h>
#include <asm/sgi/ioc.h>
#include <asm/sgi/hpc3.h>
#include <asm/sgi/ip22.h>
static unsigned long dosample(void)
{
u32 ct0, ct1;
u8 msb;
/* Start the counter. */
sgint->tcword = (SGINT_TCWORD_CNT2 | SGINT_TCWORD_CALL |
SGINT_TCWORD_MRGEN);
sgint->tcnt2 = SGINT_TCSAMP_COUNTER & 0xff;
sgint->tcnt2 = SGINT_TCSAMP_COUNTER >> 8;
/* Get initial counter invariant */
ct0 = read_c0_count();
/* Latch and spin until top byte of counter2 is zero */
do {
writeb(SGINT_TCWORD_CNT2 | SGINT_TCWORD_CLAT, &sgint->tcword);
(void) readb(&sgint->tcnt2);
msb = readb(&sgint->tcnt2);
ct1 = read_c0_count();
} while (msb);
/* Stop the counter. */
writeb(SGINT_TCWORD_CNT2 | SGINT_TCWORD_CALL | SGINT_TCWORD_MSWST,
&sgint->tcword);
/*
* Return the difference, this is how far the r4k counter increments
* for every 1/HZ seconds. We round off the nearest 1 MHz of master
* clock (= 1000000 / HZ / 2).
*/
return (ct1 - ct0) / (500000/HZ) * (500000/HZ);
}
/*
* Here we need to calibrate the cycle counter to at least be close.
*/
__init void plat_time_init(void)
{
unsigned long r4k_ticks[3];
unsigned long r4k_tick;
/*
* Figure out the r4k offset, the algorithm is very simple and works in
* _all_ cases as long as the 8254 counter register itself works ok (as
* an interrupt driving timer it does not because of bug, this is why
* we are using the onchip r4k counter/compare register to serve this
* purpose, but for r4k_offset calculation it will work ok for us).
* There are other very complicated ways of performing this calculation
* but this one works just fine so I am not going to futz around. ;-)
*/
printk(KERN_INFO "Calibrating system timer... ");
dosample(); /* Prime cache. */
dosample(); /* Prime cache. */
/* Zero is NOT an option. */
do {
r4k_ticks[0] = dosample();
} while (!r4k_ticks[0]);
do {
r4k_ticks[1] = dosample();
} while (!r4k_ticks[1]);
if (r4k_ticks[0] != r4k_ticks[1]) {
printk("warning: timer counts differ, retrying... ");
r4k_ticks[2] = dosample();
if (r4k_ticks[2] == r4k_ticks[0]
|| r4k_ticks[2] == r4k_ticks[1])
r4k_tick = r4k_ticks[2];
else {
printk("disagreement, using average... ");
r4k_tick = (r4k_ticks[0] + r4k_ticks[1]
+ r4k_ticks[2]) / 3;
}
} else
r4k_tick = r4k_ticks[0];
printk("%d [%d.%04d MHz CPU]\n", (int) r4k_tick,
(int) (r4k_tick / (500000 / HZ)),
(int) (r4k_tick % (500000 / HZ)));
mips_hpt_frequency = r4k_tick * HZ;
if (ip22_is_fullhouse())
setup_pit_timer();
}
/* Generic SGI handler for (spurious) 8254 interrupts */
void __irq_entry indy_8254timer_irq(void)
{
int irq = SGI_8254_0_IRQ;
ULONG cnt;
char c;
irq_enter();
kstat_incr_irqs_this_cpu(irq, irq_to_desc(irq));
printk(KERN_ALERT "Oops, got 8254 interrupt.\n");
ArcRead(0, &c, 1, &cnt);
ArcEnterInteractiveMode();
irq_exit();
}
| gpl-2.0 |
Savaged-Zen/Savaged-Zen-Speedy | drivers/net/wimax/i2400m/sdio-tx.c | 9095 | 5653 | /*
* Intel Wireless WiMAX Connection 2400m
* SDIO TX transaction backends
*
*
* Copyright (C) 2007-2008 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Intel Corporation <linux-wimax@intel.com>
* Dirk Brandewie <dirk.j.brandewie@intel.com>
* - Initial implementation
*
*
* Takes the TX messages in the i2400m's driver TX FIFO and sends them
* to the device until there are no more.
*
* If we fail sending the message, we just drop it. There isn't much
* we can do at this point. Most of the traffic is network, which has
* recovery methods for dropped packets.
*
* The SDIO functions are not atomic, so we can't run from the context
* where i2400m->bus_tx_kick() [i2400ms_bus_tx_kick()] is being called
* (some times atomic). Thus, the actual TX work is deferred to a
* workqueue.
*
* ROADMAP
*
* i2400ms_bus_tx_kick()
* i2400ms_tx_submit() [through workqueue]
*
* i2400m_tx_setup()
*
* i2400m_tx_release()
*/
#include <linux/mmc/sdio_func.h>
#include "i2400m-sdio.h"
#define D_SUBMODULE tx
#include "sdio-debug-levels.h"
/*
* Pull TX transations from the TX FIFO and send them to the device
* until there are no more.
*/
static
void i2400ms_tx_submit(struct work_struct *ws)
{
int result;
struct i2400ms *i2400ms = container_of(ws, struct i2400ms, tx_worker);
struct i2400m *i2400m = &i2400ms->i2400m;
struct sdio_func *func = i2400ms->func;
struct device *dev = &func->dev;
struct i2400m_msg_hdr *tx_msg;
size_t tx_msg_size;
d_fnstart(4, dev, "(i2400ms %p, i2400m %p)\n", i2400ms, i2400ms);
while (NULL != (tx_msg = i2400m_tx_msg_get(i2400m, &tx_msg_size))) {
d_printf(2, dev, "TX: submitting %zu bytes\n", tx_msg_size);
d_dump(5, dev, tx_msg, tx_msg_size);
sdio_claim_host(func);
result = sdio_memcpy_toio(func, 0, tx_msg, tx_msg_size);
sdio_release_host(func);
i2400m_tx_msg_sent(i2400m);
if (result < 0) {
dev_err(dev, "TX: cannot submit TX; tx_msg @%zu %zu B:"
" %d\n", (void *) tx_msg - i2400m->tx_buf,
tx_msg_size, result);
}
if (result == -ETIMEDOUT) {
i2400m_error_recovery(i2400m);
break;
}
d_printf(2, dev, "TX: %zub submitted\n", tx_msg_size);
}
d_fnend(4, dev, "(i2400ms %p) = void\n", i2400ms);
}
/*
* The generic driver notifies us that there is data ready for TX
*
* Schedule a run of i2400ms_tx_submit() to handle it.
*/
void i2400ms_bus_tx_kick(struct i2400m *i2400m)
{
struct i2400ms *i2400ms = container_of(i2400m, struct i2400ms, i2400m);
struct device *dev = &i2400ms->func->dev;
unsigned long flags;
d_fnstart(3, dev, "(i2400m %p) = void\n", i2400m);
/* schedule tx work, this is because tx may block, therefore
* it has to run in a thread context.
*/
spin_lock_irqsave(&i2400m->tx_lock, flags);
if (i2400ms->tx_workqueue != NULL)
queue_work(i2400ms->tx_workqueue, &i2400ms->tx_worker);
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnend(3, dev, "(i2400m %p) = void\n", i2400m);
}
int i2400ms_tx_setup(struct i2400ms *i2400ms)
{
int result;
struct device *dev = &i2400ms->func->dev;
struct i2400m *i2400m = &i2400ms->i2400m;
struct workqueue_struct *tx_workqueue;
unsigned long flags;
d_fnstart(5, dev, "(i2400ms %p)\n", i2400ms);
INIT_WORK(&i2400ms->tx_worker, i2400ms_tx_submit);
snprintf(i2400ms->tx_wq_name, sizeof(i2400ms->tx_wq_name),
"%s-tx", i2400m->wimax_dev.name);
tx_workqueue =
create_singlethread_workqueue(i2400ms->tx_wq_name);
if (tx_workqueue == NULL) {
dev_err(dev, "TX: failed to create workqueue\n");
result = -ENOMEM;
} else
result = 0;
spin_lock_irqsave(&i2400m->tx_lock, flags);
i2400ms->tx_workqueue = tx_workqueue;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnend(5, dev, "(i2400ms %p) = %d\n", i2400ms, result);
return result;
}
void i2400ms_tx_release(struct i2400ms *i2400ms)
{
struct i2400m *i2400m = &i2400ms->i2400m;
struct workqueue_struct *tx_workqueue;
unsigned long flags;
tx_workqueue = i2400ms->tx_workqueue;
spin_lock_irqsave(&i2400m->tx_lock, flags);
i2400ms->tx_workqueue = NULL;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
if (tx_workqueue)
destroy_workqueue(tx_workqueue);
}
| gpl-2.0 |
Entropy512/linux_kernel_sgh-i777 | arch/mips/gt64120/wrppmc/serial.c | 9351 | 2120 | /*
* Registration of WRPPMC UART platform device.
*
* Copyright (C) 2007 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/serial_8250.h>
#include <asm/gt64120.h>
static struct resource wrppmc_uart_resource[] __initdata = {
{
.start = WRPPMC_UART16550_BASE,
.end = WRPPMC_UART16550_BASE + 7,
.flags = IORESOURCE_MEM,
},
{
.start = WRPPMC_UART16550_IRQ,
.end = WRPPMC_UART16550_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct plat_serial8250_port wrppmc_serial8250_port[] = {
{
.irq = WRPPMC_UART16550_IRQ,
.uartclk = WRPPMC_UART16550_CLOCK,
.iotype = UPIO_MEM,
.flags = UPF_IOREMAP | UPF_SKIP_TEST,
.mapbase = WRPPMC_UART16550_BASE,
},
{},
};
static __init int wrppmc_uart_add(void)
{
struct platform_device *pdev;
int retval;
pdev = platform_device_alloc("serial8250", -1);
if (!pdev)
return -ENOMEM;
pdev->id = PLAT8250_DEV_PLATFORM;
pdev->dev.platform_data = wrppmc_serial8250_port;
retval = platform_device_add_resources(pdev, wrppmc_uart_resource,
ARRAY_SIZE(wrppmc_uart_resource));
if (retval)
goto err_free_device;
retval = platform_device_add(pdev);
if (retval)
goto err_free_device;
return 0;
err_free_device:
platform_device_put(pdev);
return retval;
}
device_initcall(wrppmc_uart_add);
| gpl-2.0 |
javelinanddart/kernel_samsung_msm8660-common-1 | arch/s390/kernel/diag.c | 10887 | 1580 | /*
* Implementation of s390 diagnose codes
*
* Copyright IBM Corp. 2007
* Author(s): Michael Holzheu <holzheu@de.ibm.com>
*/
#include <linux/module.h>
#include <asm/diag.h>
/*
* Diagnose 14: Input spool file manipulation
*/
int diag14(unsigned long rx, unsigned long ry1, unsigned long subcode)
{
register unsigned long _ry1 asm("2") = ry1;
register unsigned long _ry2 asm("3") = subcode;
int rc = 0;
asm volatile(
#ifdef CONFIG_64BIT
" sam31\n"
" diag %2,2,0x14\n"
" sam64\n"
#else
" diag %2,2,0x14\n"
#endif
" ipm %0\n"
" srl %0,28\n"
: "=d" (rc), "+d" (_ry2)
: "d" (rx), "d" (_ry1)
: "cc");
return rc;
}
EXPORT_SYMBOL(diag14);
/*
* Diagnose 210: Get information about a virtual device
*/
int diag210(struct diag210 *addr)
{
/*
* diag 210 needs its data below the 2GB border, so we
* use a static data area to be sure
*/
static struct diag210 diag210_tmp;
static DEFINE_SPINLOCK(diag210_lock);
unsigned long flags;
int ccode;
spin_lock_irqsave(&diag210_lock, flags);
diag210_tmp = *addr;
#ifdef CONFIG_64BIT
asm volatile(
" lhi %0,-1\n"
" sam31\n"
" diag %1,0,0x210\n"
"0: ipm %0\n"
" srl %0,28\n"
"1: sam64\n"
EX_TABLE(0b, 1b)
: "=&d" (ccode) : "a" (&diag210_tmp) : "cc", "memory");
#else
asm volatile(
" lhi %0,-1\n"
" diag %1,0,0x210\n"
"0: ipm %0\n"
" srl %0,28\n"
"1:\n"
EX_TABLE(0b, 1b)
: "=&d" (ccode) : "a" (&diag210_tmp) : "cc", "memory");
#endif
*addr = diag210_tmp;
spin_unlock_irqrestore(&diag210_lock, flags);
return ccode;
}
EXPORT_SYMBOL(diag210);
| gpl-2.0 |
zefie/nxt_andx86_kernel | net/sunrpc/auth_gss/auth_gss.c | 136 | 54171 | /*
* linux/net/sunrpc/auth_gss/auth_gss.c
*
* RPCSEC_GSS client authentication.
*
* Copyright (c) 2000 The Regents of the University of Michigan.
* All rights reserved.
*
* Dug Song <dugsong@monkey.org>
* Andy Adamson <andros@umich.edu>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/pagemap.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/auth.h>
#include <linux/sunrpc/auth_gss.h>
#include <linux/sunrpc/svcauth_gss.h>
#include <linux/sunrpc/gss_err.h>
#include <linux/workqueue.h>
#include <linux/sunrpc/rpc_pipe_fs.h>
#include <linux/sunrpc/gss_api.h>
#include <asm/uaccess.h>
#include <linux/hashtable.h>
#include "../netns.h"
static const struct rpc_authops authgss_ops;
static const struct rpc_credops gss_credops;
static const struct rpc_credops gss_nullops;
#define GSS_RETRY_EXPIRED 5
static unsigned int gss_expired_cred_retry_delay = GSS_RETRY_EXPIRED;
#define GSS_KEY_EXPIRE_TIMEO 240
static unsigned int gss_key_expire_timeo = GSS_KEY_EXPIRE_TIMEO;
#if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
# define RPCDBG_FACILITY RPCDBG_AUTH
#endif
#define GSS_CRED_SLACK (RPC_MAX_AUTH_SIZE * 2)
/* length of a krb5 verifier (48), plus data added before arguments when
* using integrity (two 4-byte integers): */
#define GSS_VERF_SLACK 100
static DEFINE_HASHTABLE(gss_auth_hash_table, 4);
static DEFINE_SPINLOCK(gss_auth_hash_lock);
struct gss_pipe {
struct rpc_pipe_dir_object pdo;
struct rpc_pipe *pipe;
struct rpc_clnt *clnt;
const char *name;
struct kref kref;
};
struct gss_auth {
struct kref kref;
struct hlist_node hash;
struct rpc_auth rpc_auth;
struct gss_api_mech *mech;
enum rpc_gss_svc service;
struct rpc_clnt *client;
struct net *net;
/*
* There are two upcall pipes; dentry[1], named "gssd", is used
* for the new text-based upcall; dentry[0] is named after the
* mechanism (for example, "krb5") and exists for
* backwards-compatibility with older gssd's.
*/
struct gss_pipe *gss_pipe[2];
const char *target_name;
};
/* pipe_version >= 0 if and only if someone has a pipe open. */
static DEFINE_SPINLOCK(pipe_version_lock);
static struct rpc_wait_queue pipe_version_rpc_waitqueue;
static DECLARE_WAIT_QUEUE_HEAD(pipe_version_waitqueue);
static void gss_put_auth(struct gss_auth *gss_auth);
static void gss_free_ctx(struct gss_cl_ctx *);
static const struct rpc_pipe_ops gss_upcall_ops_v0;
static const struct rpc_pipe_ops gss_upcall_ops_v1;
static inline struct gss_cl_ctx *
gss_get_ctx(struct gss_cl_ctx *ctx)
{
atomic_inc(&ctx->count);
return ctx;
}
static inline void
gss_put_ctx(struct gss_cl_ctx *ctx)
{
if (atomic_dec_and_test(&ctx->count))
gss_free_ctx(ctx);
}
/* gss_cred_set_ctx:
* called by gss_upcall_callback and gss_create_upcall in order
* to set the gss context. The actual exchange of an old context
* and a new one is protected by the pipe->lock.
*/
static void
gss_cred_set_ctx(struct rpc_cred *cred, struct gss_cl_ctx *ctx)
{
struct gss_cred *gss_cred = container_of(cred, struct gss_cred, gc_base);
if (!test_bit(RPCAUTH_CRED_NEW, &cred->cr_flags))
return;
gss_get_ctx(ctx);
rcu_assign_pointer(gss_cred->gc_ctx, ctx);
set_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags);
smp_mb__before_atomic();
clear_bit(RPCAUTH_CRED_NEW, &cred->cr_flags);
}
static const void *
simple_get_bytes(const void *p, const void *end, void *res, size_t len)
{
const void *q = (const void *)((const char *)p + len);
if (unlikely(q > end || q < p))
return ERR_PTR(-EFAULT);
memcpy(res, p, len);
return q;
}
static inline const void *
simple_get_netobj(const void *p, const void *end, struct xdr_netobj *dest)
{
const void *q;
unsigned int len;
p = simple_get_bytes(p, end, &len, sizeof(len));
if (IS_ERR(p))
return p;
q = (const void *)((const char *)p + len);
if (unlikely(q > end || q < p))
return ERR_PTR(-EFAULT);
dest->data = kmemdup(p, len, GFP_NOFS);
if (unlikely(dest->data == NULL))
return ERR_PTR(-ENOMEM);
dest->len = len;
return q;
}
static struct gss_cl_ctx *
gss_cred_get_ctx(struct rpc_cred *cred)
{
struct gss_cred *gss_cred = container_of(cred, struct gss_cred, gc_base);
struct gss_cl_ctx *ctx = NULL;
rcu_read_lock();
ctx = rcu_dereference(gss_cred->gc_ctx);
if (ctx)
gss_get_ctx(ctx);
rcu_read_unlock();
return ctx;
}
static struct gss_cl_ctx *
gss_alloc_context(void)
{
struct gss_cl_ctx *ctx;
ctx = kzalloc(sizeof(*ctx), GFP_NOFS);
if (ctx != NULL) {
ctx->gc_proc = RPC_GSS_PROC_DATA;
ctx->gc_seq = 1; /* NetApp 6.4R1 doesn't accept seq. no. 0 */
spin_lock_init(&ctx->gc_seq_lock);
atomic_set(&ctx->count,1);
}
return ctx;
}
#define GSSD_MIN_TIMEOUT (60 * 60)
static const void *
gss_fill_context(const void *p, const void *end, struct gss_cl_ctx *ctx, struct gss_api_mech *gm)
{
const void *q;
unsigned int seclen;
unsigned int timeout;
unsigned long now = jiffies;
u32 window_size;
int ret;
/* First unsigned int gives the remaining lifetime in seconds of the
* credential - e.g. the remaining TGT lifetime for Kerberos or
* the -t value passed to GSSD.
*/
p = simple_get_bytes(p, end, &timeout, sizeof(timeout));
if (IS_ERR(p))
goto err;
if (timeout == 0)
timeout = GSSD_MIN_TIMEOUT;
ctx->gc_expiry = now + ((unsigned long)timeout * HZ);
/* Sequence number window. Determines the maximum number of
* simultaneous requests
*/
p = simple_get_bytes(p, end, &window_size, sizeof(window_size));
if (IS_ERR(p))
goto err;
ctx->gc_win = window_size;
/* gssd signals an error by passing ctx->gc_win = 0: */
if (ctx->gc_win == 0) {
/*
* in which case, p points to an error code. Anything other
* than -EKEYEXPIRED gets converted to -EACCES.
*/
p = simple_get_bytes(p, end, &ret, sizeof(ret));
if (!IS_ERR(p))
p = (ret == -EKEYEXPIRED) ? ERR_PTR(-EKEYEXPIRED) :
ERR_PTR(-EACCES);
goto err;
}
/* copy the opaque wire context */
p = simple_get_netobj(p, end, &ctx->gc_wire_ctx);
if (IS_ERR(p))
goto err;
/* import the opaque security context */
p = simple_get_bytes(p, end, &seclen, sizeof(seclen));
if (IS_ERR(p))
goto err;
q = (const void *)((const char *)p + seclen);
if (unlikely(q > end || q < p)) {
p = ERR_PTR(-EFAULT);
goto err;
}
ret = gss_import_sec_context(p, seclen, gm, &ctx->gc_gss_ctx, NULL, GFP_NOFS);
if (ret < 0) {
p = ERR_PTR(ret);
goto err;
}
/* is there any trailing data? */
if (q == end) {
p = q;
goto done;
}
/* pull in acceptor name (if there is one) */
p = simple_get_netobj(q, end, &ctx->gc_acceptor);
if (IS_ERR(p))
goto err;
done:
dprintk("RPC: %s Success. gc_expiry %lu now %lu timeout %u acceptor %.*s\n",
__func__, ctx->gc_expiry, now, timeout, ctx->gc_acceptor.len,
ctx->gc_acceptor.data);
return p;
err:
dprintk("RPC: %s returns error %ld\n", __func__, -PTR_ERR(p));
return p;
}
#define UPCALL_BUF_LEN 128
struct gss_upcall_msg {
atomic_t count;
kuid_t uid;
struct rpc_pipe_msg msg;
struct list_head list;
struct gss_auth *auth;
struct rpc_pipe *pipe;
struct rpc_wait_queue rpc_waitqueue;
wait_queue_head_t waitqueue;
struct gss_cl_ctx *ctx;
char databuf[UPCALL_BUF_LEN];
};
static int get_pipe_version(struct net *net)
{
struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
int ret;
spin_lock(&pipe_version_lock);
if (sn->pipe_version >= 0) {
atomic_inc(&sn->pipe_users);
ret = sn->pipe_version;
} else
ret = -EAGAIN;
spin_unlock(&pipe_version_lock);
return ret;
}
static void put_pipe_version(struct net *net)
{
struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
if (atomic_dec_and_lock(&sn->pipe_users, &pipe_version_lock)) {
sn->pipe_version = -1;
spin_unlock(&pipe_version_lock);
}
}
static void
gss_release_msg(struct gss_upcall_msg *gss_msg)
{
struct net *net = gss_msg->auth->net;
if (!atomic_dec_and_test(&gss_msg->count))
return;
put_pipe_version(net);
BUG_ON(!list_empty(&gss_msg->list));
if (gss_msg->ctx != NULL)
gss_put_ctx(gss_msg->ctx);
rpc_destroy_wait_queue(&gss_msg->rpc_waitqueue);
gss_put_auth(gss_msg->auth);
kfree(gss_msg);
}
static struct gss_upcall_msg *
__gss_find_upcall(struct rpc_pipe *pipe, kuid_t uid)
{
struct gss_upcall_msg *pos;
list_for_each_entry(pos, &pipe->in_downcall, list) {
if (!uid_eq(pos->uid, uid))
continue;
atomic_inc(&pos->count);
dprintk("RPC: %s found msg %p\n", __func__, pos);
return pos;
}
dprintk("RPC: %s found nothing\n", __func__);
return NULL;
}
/* Try to add an upcall to the pipefs queue.
* If an upcall owned by our uid already exists, then we return a reference
* to that upcall instead of adding the new upcall.
*/
static inline struct gss_upcall_msg *
gss_add_msg(struct gss_upcall_msg *gss_msg)
{
struct rpc_pipe *pipe = gss_msg->pipe;
struct gss_upcall_msg *old;
spin_lock(&pipe->lock);
old = __gss_find_upcall(pipe, gss_msg->uid);
if (old == NULL) {
atomic_inc(&gss_msg->count);
list_add(&gss_msg->list, &pipe->in_downcall);
} else
gss_msg = old;
spin_unlock(&pipe->lock);
return gss_msg;
}
static void
__gss_unhash_msg(struct gss_upcall_msg *gss_msg)
{
list_del_init(&gss_msg->list);
rpc_wake_up_status(&gss_msg->rpc_waitqueue, gss_msg->msg.errno);
wake_up_all(&gss_msg->waitqueue);
atomic_dec(&gss_msg->count);
}
static void
gss_unhash_msg(struct gss_upcall_msg *gss_msg)
{
struct rpc_pipe *pipe = gss_msg->pipe;
if (list_empty(&gss_msg->list))
return;
spin_lock(&pipe->lock);
if (!list_empty(&gss_msg->list))
__gss_unhash_msg(gss_msg);
spin_unlock(&pipe->lock);
}
static void
gss_handle_downcall_result(struct gss_cred *gss_cred, struct gss_upcall_msg *gss_msg)
{
switch (gss_msg->msg.errno) {
case 0:
if (gss_msg->ctx == NULL)
break;
clear_bit(RPCAUTH_CRED_NEGATIVE, &gss_cred->gc_base.cr_flags);
gss_cred_set_ctx(&gss_cred->gc_base, gss_msg->ctx);
break;
case -EKEYEXPIRED:
set_bit(RPCAUTH_CRED_NEGATIVE, &gss_cred->gc_base.cr_flags);
}
gss_cred->gc_upcall_timestamp = jiffies;
gss_cred->gc_upcall = NULL;
rpc_wake_up_status(&gss_msg->rpc_waitqueue, gss_msg->msg.errno);
}
static void
gss_upcall_callback(struct rpc_task *task)
{
struct gss_cred *gss_cred = container_of(task->tk_rqstp->rq_cred,
struct gss_cred, gc_base);
struct gss_upcall_msg *gss_msg = gss_cred->gc_upcall;
struct rpc_pipe *pipe = gss_msg->pipe;
spin_lock(&pipe->lock);
gss_handle_downcall_result(gss_cred, gss_msg);
spin_unlock(&pipe->lock);
task->tk_status = gss_msg->msg.errno;
gss_release_msg(gss_msg);
}
static void gss_encode_v0_msg(struct gss_upcall_msg *gss_msg)
{
uid_t uid = from_kuid(&init_user_ns, gss_msg->uid);
memcpy(gss_msg->databuf, &uid, sizeof(uid));
gss_msg->msg.data = gss_msg->databuf;
gss_msg->msg.len = sizeof(uid);
BUILD_BUG_ON(sizeof(uid) > sizeof(gss_msg->databuf));
}
static int gss_encode_v1_msg(struct gss_upcall_msg *gss_msg,
const char *service_name,
const char *target_name)
{
struct gss_api_mech *mech = gss_msg->auth->mech;
char *p = gss_msg->databuf;
size_t buflen = sizeof(gss_msg->databuf);
int len;
len = scnprintf(p, buflen, "mech=%s uid=%d ", mech->gm_name,
from_kuid(&init_user_ns, gss_msg->uid));
buflen -= len;
p += len;
gss_msg->msg.len = len;
if (target_name) {
len = scnprintf(p, buflen, "target=%s ", target_name);
buflen -= len;
p += len;
gss_msg->msg.len += len;
}
if (service_name != NULL) {
len = scnprintf(p, buflen, "service=%s ", service_name);
buflen -= len;
p += len;
gss_msg->msg.len += len;
}
if (mech->gm_upcall_enctypes) {
len = scnprintf(p, buflen, "enctypes=%s ",
mech->gm_upcall_enctypes);
buflen -= len;
p += len;
gss_msg->msg.len += len;
}
len = scnprintf(p, buflen, "\n");
if (len == 0)
goto out_overflow;
gss_msg->msg.len += len;
gss_msg->msg.data = gss_msg->databuf;
return 0;
out_overflow:
WARN_ON_ONCE(1);
return -ENOMEM;
}
static struct gss_upcall_msg *
gss_alloc_msg(struct gss_auth *gss_auth,
kuid_t uid, const char *service_name)
{
struct gss_upcall_msg *gss_msg;
int vers;
int err = -ENOMEM;
gss_msg = kzalloc(sizeof(*gss_msg), GFP_NOFS);
if (gss_msg == NULL)
goto err;
vers = get_pipe_version(gss_auth->net);
err = vers;
if (err < 0)
goto err_free_msg;
gss_msg->pipe = gss_auth->gss_pipe[vers]->pipe;
INIT_LIST_HEAD(&gss_msg->list);
rpc_init_wait_queue(&gss_msg->rpc_waitqueue, "RPCSEC_GSS upcall waitq");
init_waitqueue_head(&gss_msg->waitqueue);
atomic_set(&gss_msg->count, 1);
gss_msg->uid = uid;
gss_msg->auth = gss_auth;
switch (vers) {
case 0:
gss_encode_v0_msg(gss_msg);
break;
default:
err = gss_encode_v1_msg(gss_msg, service_name, gss_auth->target_name);
if (err)
goto err_put_pipe_version;
};
kref_get(&gss_auth->kref);
return gss_msg;
err_put_pipe_version:
put_pipe_version(gss_auth->net);
err_free_msg:
kfree(gss_msg);
err:
return ERR_PTR(err);
}
static struct gss_upcall_msg *
gss_setup_upcall(struct gss_auth *gss_auth, struct rpc_cred *cred)
{
struct gss_cred *gss_cred = container_of(cred,
struct gss_cred, gc_base);
struct gss_upcall_msg *gss_new, *gss_msg;
kuid_t uid = cred->cr_uid;
gss_new = gss_alloc_msg(gss_auth, uid, gss_cred->gc_principal);
if (IS_ERR(gss_new))
return gss_new;
gss_msg = gss_add_msg(gss_new);
if (gss_msg == gss_new) {
int res = rpc_queue_upcall(gss_new->pipe, &gss_new->msg);
if (res) {
gss_unhash_msg(gss_new);
gss_msg = ERR_PTR(res);
}
} else
gss_release_msg(gss_new);
return gss_msg;
}
static void warn_gssd(void)
{
dprintk("AUTH_GSS upcall failed. Please check user daemon is running.\n");
}
static inline int
gss_refresh_upcall(struct rpc_task *task)
{
struct rpc_cred *cred = task->tk_rqstp->rq_cred;
struct gss_auth *gss_auth = container_of(cred->cr_auth,
struct gss_auth, rpc_auth);
struct gss_cred *gss_cred = container_of(cred,
struct gss_cred, gc_base);
struct gss_upcall_msg *gss_msg;
struct rpc_pipe *pipe;
int err = 0;
dprintk("RPC: %5u %s for uid %u\n",
task->tk_pid, __func__, from_kuid(&init_user_ns, cred->cr_uid));
gss_msg = gss_setup_upcall(gss_auth, cred);
if (PTR_ERR(gss_msg) == -EAGAIN) {
/* XXX: warning on the first, under the assumption we
* shouldn't normally hit this case on a refresh. */
warn_gssd();
task->tk_timeout = 15*HZ;
rpc_sleep_on(&pipe_version_rpc_waitqueue, task, NULL);
return -EAGAIN;
}
if (IS_ERR(gss_msg)) {
err = PTR_ERR(gss_msg);
goto out;
}
pipe = gss_msg->pipe;
spin_lock(&pipe->lock);
if (gss_cred->gc_upcall != NULL)
rpc_sleep_on(&gss_cred->gc_upcall->rpc_waitqueue, task, NULL);
else if (gss_msg->ctx == NULL && gss_msg->msg.errno >= 0) {
task->tk_timeout = 0;
gss_cred->gc_upcall = gss_msg;
/* gss_upcall_callback will release the reference to gss_upcall_msg */
atomic_inc(&gss_msg->count);
rpc_sleep_on(&gss_msg->rpc_waitqueue, task, gss_upcall_callback);
} else {
gss_handle_downcall_result(gss_cred, gss_msg);
err = gss_msg->msg.errno;
}
spin_unlock(&pipe->lock);
gss_release_msg(gss_msg);
out:
dprintk("RPC: %5u %s for uid %u result %d\n",
task->tk_pid, __func__,
from_kuid(&init_user_ns, cred->cr_uid), err);
return err;
}
static inline int
gss_create_upcall(struct gss_auth *gss_auth, struct gss_cred *gss_cred)
{
struct net *net = gss_auth->net;
struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
struct rpc_pipe *pipe;
struct rpc_cred *cred = &gss_cred->gc_base;
struct gss_upcall_msg *gss_msg;
DEFINE_WAIT(wait);
int err;
dprintk("RPC: %s for uid %u\n",
__func__, from_kuid(&init_user_ns, cred->cr_uid));
retry:
err = 0;
/* if gssd is down, just skip upcalling altogether */
if (!gssd_running(net)) {
warn_gssd();
return -EACCES;
}
gss_msg = gss_setup_upcall(gss_auth, cred);
if (PTR_ERR(gss_msg) == -EAGAIN) {
err = wait_event_interruptible_timeout(pipe_version_waitqueue,
sn->pipe_version >= 0, 15 * HZ);
if (sn->pipe_version < 0) {
warn_gssd();
err = -EACCES;
}
if (err < 0)
goto out;
goto retry;
}
if (IS_ERR(gss_msg)) {
err = PTR_ERR(gss_msg);
goto out;
}
pipe = gss_msg->pipe;
for (;;) {
prepare_to_wait(&gss_msg->waitqueue, &wait, TASK_KILLABLE);
spin_lock(&pipe->lock);
if (gss_msg->ctx != NULL || gss_msg->msg.errno < 0) {
break;
}
spin_unlock(&pipe->lock);
if (fatal_signal_pending(current)) {
err = -ERESTARTSYS;
goto out_intr;
}
schedule();
}
if (gss_msg->ctx)
gss_cred_set_ctx(cred, gss_msg->ctx);
else
err = gss_msg->msg.errno;
spin_unlock(&pipe->lock);
out_intr:
finish_wait(&gss_msg->waitqueue, &wait);
gss_release_msg(gss_msg);
out:
dprintk("RPC: %s for uid %u result %d\n",
__func__, from_kuid(&init_user_ns, cred->cr_uid), err);
return err;
}
#define MSG_BUF_MAXSIZE 1024
static ssize_t
gss_pipe_downcall(struct file *filp, const char __user *src, size_t mlen)
{
const void *p, *end;
void *buf;
struct gss_upcall_msg *gss_msg;
struct rpc_pipe *pipe = RPC_I(file_inode(filp))->pipe;
struct gss_cl_ctx *ctx;
uid_t id;
kuid_t uid;
ssize_t err = -EFBIG;
if (mlen > MSG_BUF_MAXSIZE)
goto out;
err = -ENOMEM;
buf = kmalloc(mlen, GFP_NOFS);
if (!buf)
goto out;
err = -EFAULT;
if (copy_from_user(buf, src, mlen))
goto err;
end = (const void *)((char *)buf + mlen);
p = simple_get_bytes(buf, end, &id, sizeof(id));
if (IS_ERR(p)) {
err = PTR_ERR(p);
goto err;
}
uid = make_kuid(&init_user_ns, id);
if (!uid_valid(uid)) {
err = -EINVAL;
goto err;
}
err = -ENOMEM;
ctx = gss_alloc_context();
if (ctx == NULL)
goto err;
err = -ENOENT;
/* Find a matching upcall */
spin_lock(&pipe->lock);
gss_msg = __gss_find_upcall(pipe, uid);
if (gss_msg == NULL) {
spin_unlock(&pipe->lock);
goto err_put_ctx;
}
list_del_init(&gss_msg->list);
spin_unlock(&pipe->lock);
p = gss_fill_context(p, end, ctx, gss_msg->auth->mech);
if (IS_ERR(p)) {
err = PTR_ERR(p);
switch (err) {
case -EACCES:
case -EKEYEXPIRED:
gss_msg->msg.errno = err;
err = mlen;
break;
case -EFAULT:
case -ENOMEM:
case -EINVAL:
case -ENOSYS:
gss_msg->msg.errno = -EAGAIN;
break;
default:
printk(KERN_CRIT "%s: bad return from "
"gss_fill_context: %zd\n", __func__, err);
BUG();
}
goto err_release_msg;
}
gss_msg->ctx = gss_get_ctx(ctx);
err = mlen;
err_release_msg:
spin_lock(&pipe->lock);
__gss_unhash_msg(gss_msg);
spin_unlock(&pipe->lock);
gss_release_msg(gss_msg);
err_put_ctx:
gss_put_ctx(ctx);
err:
kfree(buf);
out:
dprintk("RPC: %s returning %Zd\n", __func__, err);
return err;
}
static int gss_pipe_open(struct inode *inode, int new_version)
{
struct net *net = inode->i_sb->s_fs_info;
struct sunrpc_net *sn = net_generic(net, sunrpc_net_id);
int ret = 0;
spin_lock(&pipe_version_lock);
if (sn->pipe_version < 0) {
/* First open of any gss pipe determines the version: */
sn->pipe_version = new_version;
rpc_wake_up(&pipe_version_rpc_waitqueue);
wake_up(&pipe_version_waitqueue);
} else if (sn->pipe_version != new_version) {
/* Trying to open a pipe of a different version */
ret = -EBUSY;
goto out;
}
atomic_inc(&sn->pipe_users);
out:
spin_unlock(&pipe_version_lock);
return ret;
}
static int gss_pipe_open_v0(struct inode *inode)
{
return gss_pipe_open(inode, 0);
}
static int gss_pipe_open_v1(struct inode *inode)
{
return gss_pipe_open(inode, 1);
}
static void
gss_pipe_release(struct inode *inode)
{
struct net *net = inode->i_sb->s_fs_info;
struct rpc_pipe *pipe = RPC_I(inode)->pipe;
struct gss_upcall_msg *gss_msg;
restart:
spin_lock(&pipe->lock);
list_for_each_entry(gss_msg, &pipe->in_downcall, list) {
if (!list_empty(&gss_msg->msg.list))
continue;
gss_msg->msg.errno = -EPIPE;
atomic_inc(&gss_msg->count);
__gss_unhash_msg(gss_msg);
spin_unlock(&pipe->lock);
gss_release_msg(gss_msg);
goto restart;
}
spin_unlock(&pipe->lock);
put_pipe_version(net);
}
static void
gss_pipe_destroy_msg(struct rpc_pipe_msg *msg)
{
struct gss_upcall_msg *gss_msg = container_of(msg, struct gss_upcall_msg, msg);
if (msg->errno < 0) {
dprintk("RPC: %s releasing msg %p\n",
__func__, gss_msg);
atomic_inc(&gss_msg->count);
gss_unhash_msg(gss_msg);
if (msg->errno == -ETIMEDOUT)
warn_gssd();
gss_release_msg(gss_msg);
}
}
static void gss_pipe_dentry_destroy(struct dentry *dir,
struct rpc_pipe_dir_object *pdo)
{
struct gss_pipe *gss_pipe = pdo->pdo_data;
struct rpc_pipe *pipe = gss_pipe->pipe;
if (pipe->dentry != NULL) {
rpc_unlink(pipe->dentry);
pipe->dentry = NULL;
}
}
static int gss_pipe_dentry_create(struct dentry *dir,
struct rpc_pipe_dir_object *pdo)
{
struct gss_pipe *p = pdo->pdo_data;
struct dentry *dentry;
dentry = rpc_mkpipe_dentry(dir, p->name, p->clnt, p->pipe);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
p->pipe->dentry = dentry;
return 0;
}
static const struct rpc_pipe_dir_object_ops gss_pipe_dir_object_ops = {
.create = gss_pipe_dentry_create,
.destroy = gss_pipe_dentry_destroy,
};
static struct gss_pipe *gss_pipe_alloc(struct rpc_clnt *clnt,
const char *name,
const struct rpc_pipe_ops *upcall_ops)
{
struct gss_pipe *p;
int err = -ENOMEM;
p = kmalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL)
goto err;
p->pipe = rpc_mkpipe_data(upcall_ops, RPC_PIPE_WAIT_FOR_OPEN);
if (IS_ERR(p->pipe)) {
err = PTR_ERR(p->pipe);
goto err_free_gss_pipe;
}
p->name = name;
p->clnt = clnt;
kref_init(&p->kref);
rpc_init_pipe_dir_object(&p->pdo,
&gss_pipe_dir_object_ops,
p);
return p;
err_free_gss_pipe:
kfree(p);
err:
return ERR_PTR(err);
}
struct gss_alloc_pdo {
struct rpc_clnt *clnt;
const char *name;
const struct rpc_pipe_ops *upcall_ops;
};
static int gss_pipe_match_pdo(struct rpc_pipe_dir_object *pdo, void *data)
{
struct gss_pipe *gss_pipe;
struct gss_alloc_pdo *args = data;
if (pdo->pdo_ops != &gss_pipe_dir_object_ops)
return 0;
gss_pipe = container_of(pdo, struct gss_pipe, pdo);
if (strcmp(gss_pipe->name, args->name) != 0)
return 0;
if (!kref_get_unless_zero(&gss_pipe->kref))
return 0;
return 1;
}
static struct rpc_pipe_dir_object *gss_pipe_alloc_pdo(void *data)
{
struct gss_pipe *gss_pipe;
struct gss_alloc_pdo *args = data;
gss_pipe = gss_pipe_alloc(args->clnt, args->name, args->upcall_ops);
if (!IS_ERR(gss_pipe))
return &gss_pipe->pdo;
return NULL;
}
static struct gss_pipe *gss_pipe_get(struct rpc_clnt *clnt,
const char *name,
const struct rpc_pipe_ops *upcall_ops)
{
struct net *net = rpc_net_ns(clnt);
struct rpc_pipe_dir_object *pdo;
struct gss_alloc_pdo args = {
.clnt = clnt,
.name = name,
.upcall_ops = upcall_ops,
};
pdo = rpc_find_or_alloc_pipe_dir_object(net,
&clnt->cl_pipedir_objects,
gss_pipe_match_pdo,
gss_pipe_alloc_pdo,
&args);
if (pdo != NULL)
return container_of(pdo, struct gss_pipe, pdo);
return ERR_PTR(-ENOMEM);
}
static void __gss_pipe_free(struct gss_pipe *p)
{
struct rpc_clnt *clnt = p->clnt;
struct net *net = rpc_net_ns(clnt);
rpc_remove_pipe_dir_object(net,
&clnt->cl_pipedir_objects,
&p->pdo);
rpc_destroy_pipe_data(p->pipe);
kfree(p);
}
static void __gss_pipe_release(struct kref *kref)
{
struct gss_pipe *p = container_of(kref, struct gss_pipe, kref);
__gss_pipe_free(p);
}
static void gss_pipe_free(struct gss_pipe *p)
{
if (p != NULL)
kref_put(&p->kref, __gss_pipe_release);
}
/*
* NOTE: we have the opportunity to use different
* parameters based on the input flavor (which must be a pseudoflavor)
*/
static struct gss_auth *
gss_create_new(struct rpc_auth_create_args *args, struct rpc_clnt *clnt)
{
rpc_authflavor_t flavor = args->pseudoflavor;
struct gss_auth *gss_auth;
struct gss_pipe *gss_pipe;
struct rpc_auth * auth;
int err = -ENOMEM; /* XXX? */
dprintk("RPC: creating GSS authenticator for client %p\n", clnt);
if (!try_module_get(THIS_MODULE))
return ERR_PTR(err);
if (!(gss_auth = kmalloc(sizeof(*gss_auth), GFP_KERNEL)))
goto out_dec;
INIT_HLIST_NODE(&gss_auth->hash);
gss_auth->target_name = NULL;
if (args->target_name) {
gss_auth->target_name = kstrdup(args->target_name, GFP_KERNEL);
if (gss_auth->target_name == NULL)
goto err_free;
}
gss_auth->client = clnt;
gss_auth->net = get_net(rpc_net_ns(clnt));
err = -EINVAL;
gss_auth->mech = gss_mech_get_by_pseudoflavor(flavor);
if (!gss_auth->mech) {
dprintk("RPC: Pseudoflavor %d not found!\n", flavor);
goto err_put_net;
}
gss_auth->service = gss_pseudoflavor_to_service(gss_auth->mech, flavor);
if (gss_auth->service == 0)
goto err_put_mech;
if (!gssd_running(gss_auth->net))
goto err_put_mech;
auth = &gss_auth->rpc_auth;
auth->au_cslack = GSS_CRED_SLACK >> 2;
auth->au_rslack = GSS_VERF_SLACK >> 2;
auth->au_ops = &authgss_ops;
auth->au_flavor = flavor;
atomic_set(&auth->au_count, 1);
kref_init(&gss_auth->kref);
err = rpcauth_init_credcache(auth);
if (err)
goto err_put_mech;
/*
* Note: if we created the old pipe first, then someone who
* examined the directory at the right moment might conclude
* that we supported only the old pipe. So we instead create
* the new pipe first.
*/
gss_pipe = gss_pipe_get(clnt, "gssd", &gss_upcall_ops_v1);
if (IS_ERR(gss_pipe)) {
err = PTR_ERR(gss_pipe);
goto err_destroy_credcache;
}
gss_auth->gss_pipe[1] = gss_pipe;
gss_pipe = gss_pipe_get(clnt, gss_auth->mech->gm_name,
&gss_upcall_ops_v0);
if (IS_ERR(gss_pipe)) {
err = PTR_ERR(gss_pipe);
goto err_destroy_pipe_1;
}
gss_auth->gss_pipe[0] = gss_pipe;
return gss_auth;
err_destroy_pipe_1:
gss_pipe_free(gss_auth->gss_pipe[1]);
err_destroy_credcache:
rpcauth_destroy_credcache(auth);
err_put_mech:
gss_mech_put(gss_auth->mech);
err_put_net:
put_net(gss_auth->net);
err_free:
kfree(gss_auth->target_name);
kfree(gss_auth);
out_dec:
module_put(THIS_MODULE);
return ERR_PTR(err);
}
static void
gss_free(struct gss_auth *gss_auth)
{
gss_pipe_free(gss_auth->gss_pipe[0]);
gss_pipe_free(gss_auth->gss_pipe[1]);
gss_mech_put(gss_auth->mech);
put_net(gss_auth->net);
kfree(gss_auth->target_name);
kfree(gss_auth);
module_put(THIS_MODULE);
}
static void
gss_free_callback(struct kref *kref)
{
struct gss_auth *gss_auth = container_of(kref, struct gss_auth, kref);
gss_free(gss_auth);
}
static void
gss_put_auth(struct gss_auth *gss_auth)
{
kref_put(&gss_auth->kref, gss_free_callback);
}
static void
gss_destroy(struct rpc_auth *auth)
{
struct gss_auth *gss_auth = container_of(auth,
struct gss_auth, rpc_auth);
dprintk("RPC: destroying GSS authenticator %p flavor %d\n",
auth, auth->au_flavor);
if (hash_hashed(&gss_auth->hash)) {
spin_lock(&gss_auth_hash_lock);
hash_del(&gss_auth->hash);
spin_unlock(&gss_auth_hash_lock);
}
gss_pipe_free(gss_auth->gss_pipe[0]);
gss_auth->gss_pipe[0] = NULL;
gss_pipe_free(gss_auth->gss_pipe[1]);
gss_auth->gss_pipe[1] = NULL;
rpcauth_destroy_credcache(auth);
gss_put_auth(gss_auth);
}
/*
* Auths may be shared between rpc clients that were cloned from a
* common client with the same xprt, if they also share the flavor and
* target_name.
*
* The auth is looked up from the oldest parent sharing the same
* cl_xprt, and the auth itself references only that common parent
* (which is guaranteed to last as long as any of its descendants).
*/
static struct gss_auth *
gss_auth_find_or_add_hashed(struct rpc_auth_create_args *args,
struct rpc_clnt *clnt,
struct gss_auth *new)
{
struct gss_auth *gss_auth;
unsigned long hashval = (unsigned long)clnt;
spin_lock(&gss_auth_hash_lock);
hash_for_each_possible(gss_auth_hash_table,
gss_auth,
hash,
hashval) {
if (gss_auth->client != clnt)
continue;
if (gss_auth->rpc_auth.au_flavor != args->pseudoflavor)
continue;
if (gss_auth->target_name != args->target_name) {
if (gss_auth->target_name == NULL)
continue;
if (args->target_name == NULL)
continue;
if (strcmp(gss_auth->target_name, args->target_name))
continue;
}
if (!atomic_inc_not_zero(&gss_auth->rpc_auth.au_count))
continue;
goto out;
}
if (new)
hash_add(gss_auth_hash_table, &new->hash, hashval);
gss_auth = new;
out:
spin_unlock(&gss_auth_hash_lock);
return gss_auth;
}
static struct gss_auth *
gss_create_hashed(struct rpc_auth_create_args *args, struct rpc_clnt *clnt)
{
struct gss_auth *gss_auth;
struct gss_auth *new;
gss_auth = gss_auth_find_or_add_hashed(args, clnt, NULL);
if (gss_auth != NULL)
goto out;
new = gss_create_new(args, clnt);
if (IS_ERR(new))
return new;
gss_auth = gss_auth_find_or_add_hashed(args, clnt, new);
if (gss_auth != new)
gss_destroy(&new->rpc_auth);
out:
return gss_auth;
}
static struct rpc_auth *
gss_create(struct rpc_auth_create_args *args, struct rpc_clnt *clnt)
{
struct gss_auth *gss_auth;
struct rpc_xprt *xprt = rcu_access_pointer(clnt->cl_xprt);
while (clnt != clnt->cl_parent) {
struct rpc_clnt *parent = clnt->cl_parent;
/* Find the original parent for this transport */
if (rcu_access_pointer(parent->cl_xprt) != xprt)
break;
clnt = parent;
}
gss_auth = gss_create_hashed(args, clnt);
if (IS_ERR(gss_auth))
return ERR_CAST(gss_auth);
return &gss_auth->rpc_auth;
}
/*
* gss_destroying_context will cause the RPCSEC_GSS to send a NULL RPC call
* to the server with the GSS control procedure field set to
* RPC_GSS_PROC_DESTROY. This should normally cause the server to release
* all RPCSEC_GSS state associated with that context.
*/
static int
gss_destroying_context(struct rpc_cred *cred)
{
struct gss_cred *gss_cred = container_of(cred, struct gss_cred, gc_base);
struct gss_auth *gss_auth = container_of(cred->cr_auth, struct gss_auth, rpc_auth);
struct gss_cl_ctx *ctx = rcu_dereference_protected(gss_cred->gc_ctx, 1);
struct rpc_task *task;
if (test_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags) == 0)
return 0;
ctx->gc_proc = RPC_GSS_PROC_DESTROY;
cred->cr_ops = &gss_nullops;
/* Take a reference to ensure the cred will be destroyed either
* by the RPC call or by the put_rpccred() below */
get_rpccred(cred);
task = rpc_call_null(gss_auth->client, cred, RPC_TASK_ASYNC|RPC_TASK_SOFT);
if (!IS_ERR(task))
rpc_put_task(task);
put_rpccred(cred);
return 1;
}
/* gss_destroy_cred (and gss_free_ctx) are used to clean up after failure
* to create a new cred or context, so they check that things have been
* allocated before freeing them. */
static void
gss_do_free_ctx(struct gss_cl_ctx *ctx)
{
dprintk("RPC: %s\n", __func__);
gss_delete_sec_context(&ctx->gc_gss_ctx);
kfree(ctx->gc_wire_ctx.data);
kfree(ctx->gc_acceptor.data);
kfree(ctx);
}
static void
gss_free_ctx_callback(struct rcu_head *head)
{
struct gss_cl_ctx *ctx = container_of(head, struct gss_cl_ctx, gc_rcu);
gss_do_free_ctx(ctx);
}
static void
gss_free_ctx(struct gss_cl_ctx *ctx)
{
call_rcu(&ctx->gc_rcu, gss_free_ctx_callback);
}
static void
gss_free_cred(struct gss_cred *gss_cred)
{
dprintk("RPC: %s cred=%p\n", __func__, gss_cred);
kfree(gss_cred);
}
static void
gss_free_cred_callback(struct rcu_head *head)
{
struct gss_cred *gss_cred = container_of(head, struct gss_cred, gc_base.cr_rcu);
gss_free_cred(gss_cred);
}
static void
gss_destroy_nullcred(struct rpc_cred *cred)
{
struct gss_cred *gss_cred = container_of(cred, struct gss_cred, gc_base);
struct gss_auth *gss_auth = container_of(cred->cr_auth, struct gss_auth, rpc_auth);
struct gss_cl_ctx *ctx = rcu_dereference_protected(gss_cred->gc_ctx, 1);
RCU_INIT_POINTER(gss_cred->gc_ctx, NULL);
call_rcu(&cred->cr_rcu, gss_free_cred_callback);
if (ctx)
gss_put_ctx(ctx);
gss_put_auth(gss_auth);
}
static void
gss_destroy_cred(struct rpc_cred *cred)
{
if (gss_destroying_context(cred))
return;
gss_destroy_nullcred(cred);
}
/*
* Lookup RPCSEC_GSS cred for the current process
*/
static struct rpc_cred *
gss_lookup_cred(struct rpc_auth *auth, struct auth_cred *acred, int flags)
{
return rpcauth_lookup_credcache(auth, acred, flags);
}
static struct rpc_cred *
gss_create_cred(struct rpc_auth *auth, struct auth_cred *acred, int flags)
{
struct gss_auth *gss_auth = container_of(auth, struct gss_auth, rpc_auth);
struct gss_cred *cred = NULL;
int err = -ENOMEM;
dprintk("RPC: %s for uid %d, flavor %d\n",
__func__, from_kuid(&init_user_ns, acred->uid),
auth->au_flavor);
if (!(cred = kzalloc(sizeof(*cred), GFP_NOFS)))
goto out_err;
rpcauth_init_cred(&cred->gc_base, acred, auth, &gss_credops);
/*
* Note: in order to force a call to call_refresh(), we deliberately
* fail to flag the credential as RPCAUTH_CRED_UPTODATE.
*/
cred->gc_base.cr_flags = 1UL << RPCAUTH_CRED_NEW;
cred->gc_service = gss_auth->service;
cred->gc_principal = NULL;
if (acred->machine_cred)
cred->gc_principal = acred->principal;
kref_get(&gss_auth->kref);
return &cred->gc_base;
out_err:
dprintk("RPC: %s failed with error %d\n", __func__, err);
return ERR_PTR(err);
}
static int
gss_cred_init(struct rpc_auth *auth, struct rpc_cred *cred)
{
struct gss_auth *gss_auth = container_of(auth, struct gss_auth, rpc_auth);
struct gss_cred *gss_cred = container_of(cred,struct gss_cred, gc_base);
int err;
do {
err = gss_create_upcall(gss_auth, gss_cred);
} while (err == -EAGAIN);
return err;
}
static char *
gss_stringify_acceptor(struct rpc_cred *cred)
{
char *string = NULL;
struct gss_cred *gss_cred = container_of(cred, struct gss_cred, gc_base);
struct gss_cl_ctx *ctx;
unsigned int len;
struct xdr_netobj *acceptor;
rcu_read_lock();
ctx = rcu_dereference(gss_cred->gc_ctx);
if (!ctx)
goto out;
len = ctx->gc_acceptor.len;
rcu_read_unlock();
/* no point if there's no string */
if (!len)
return NULL;
realloc:
string = kmalloc(len + 1, GFP_KERNEL);
if (!string)
return NULL;
rcu_read_lock();
ctx = rcu_dereference(gss_cred->gc_ctx);
/* did the ctx disappear or was it replaced by one with no acceptor? */
if (!ctx || !ctx->gc_acceptor.len) {
kfree(string);
string = NULL;
goto out;
}
acceptor = &ctx->gc_acceptor;
/*
* Did we find a new acceptor that's longer than the original? Allocate
* a longer buffer and try again.
*/
if (len < acceptor->len) {
len = acceptor->len;
rcu_read_unlock();
kfree(string);
goto realloc;
}
memcpy(string, acceptor->data, acceptor->len);
string[acceptor->len] = '\0';
out:
rcu_read_unlock();
return string;
}
/*
* Returns -EACCES if GSS context is NULL or will expire within the
* timeout (miliseconds)
*/
static int
gss_key_timeout(struct rpc_cred *rc)
{
struct gss_cred *gss_cred = container_of(rc, struct gss_cred, gc_base);
struct gss_cl_ctx *ctx;
unsigned long timeout = jiffies + (gss_key_expire_timeo * HZ);
int ret = 0;
rcu_read_lock();
ctx = rcu_dereference(gss_cred->gc_ctx);
if (!ctx || time_after(timeout, ctx->gc_expiry))
ret = -EACCES;
rcu_read_unlock();
return ret;
}
static int
gss_match(struct auth_cred *acred, struct rpc_cred *rc, int flags)
{
struct gss_cred *gss_cred = container_of(rc, struct gss_cred, gc_base);
struct gss_cl_ctx *ctx;
int ret;
if (test_bit(RPCAUTH_CRED_NEW, &rc->cr_flags))
goto out;
/* Don't match with creds that have expired. */
rcu_read_lock();
ctx = rcu_dereference(gss_cred->gc_ctx);
if (!ctx || time_after(jiffies, ctx->gc_expiry)) {
rcu_read_unlock();
return 0;
}
rcu_read_unlock();
if (!test_bit(RPCAUTH_CRED_UPTODATE, &rc->cr_flags))
return 0;
out:
if (acred->principal != NULL) {
if (gss_cred->gc_principal == NULL)
return 0;
ret = strcmp(acred->principal, gss_cred->gc_principal) == 0;
goto check_expire;
}
if (gss_cred->gc_principal != NULL)
return 0;
ret = uid_eq(rc->cr_uid, acred->uid);
check_expire:
if (ret == 0)
return ret;
/* Notify acred users of GSS context expiration timeout */
if (test_bit(RPC_CRED_NOTIFY_TIMEOUT, &acred->ac_flags) &&
(gss_key_timeout(rc) != 0)) {
/* test will now be done from generic cred */
test_and_clear_bit(RPC_CRED_NOTIFY_TIMEOUT, &acred->ac_flags);
/* tell NFS layer that key will expire soon */
set_bit(RPC_CRED_KEY_EXPIRE_SOON, &acred->ac_flags);
}
return ret;
}
/*
* Marshal credentials.
* Maybe we should keep a cached credential for performance reasons.
*/
static __be32 *
gss_marshal(struct rpc_task *task, __be32 *p)
{
struct rpc_rqst *req = task->tk_rqstp;
struct rpc_cred *cred = req->rq_cred;
struct gss_cred *gss_cred = container_of(cred, struct gss_cred,
gc_base);
struct gss_cl_ctx *ctx = gss_cred_get_ctx(cred);
__be32 *cred_len;
u32 maj_stat = 0;
struct xdr_netobj mic;
struct kvec iov;
struct xdr_buf verf_buf;
dprintk("RPC: %5u %s\n", task->tk_pid, __func__);
*p++ = htonl(RPC_AUTH_GSS);
cred_len = p++;
spin_lock(&ctx->gc_seq_lock);
req->rq_seqno = ctx->gc_seq++;
spin_unlock(&ctx->gc_seq_lock);
*p++ = htonl((u32) RPC_GSS_VERSION);
*p++ = htonl((u32) ctx->gc_proc);
*p++ = htonl((u32) req->rq_seqno);
*p++ = htonl((u32) gss_cred->gc_service);
p = xdr_encode_netobj(p, &ctx->gc_wire_ctx);
*cred_len = htonl((p - (cred_len + 1)) << 2);
/* We compute the checksum for the verifier over the xdr-encoded bytes
* starting with the xid and ending at the end of the credential: */
iov.iov_base = xprt_skip_transport_header(req->rq_xprt,
req->rq_snd_buf.head[0].iov_base);
iov.iov_len = (u8 *)p - (u8 *)iov.iov_base;
xdr_buf_from_iov(&iov, &verf_buf);
/* set verifier flavor*/
*p++ = htonl(RPC_AUTH_GSS);
mic.data = (u8 *)(p + 1);
maj_stat = gss_get_mic(ctx->gc_gss_ctx, &verf_buf, &mic);
if (maj_stat == GSS_S_CONTEXT_EXPIRED) {
clear_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags);
} else if (maj_stat != 0) {
printk("gss_marshal: gss_get_mic FAILED (%d)\n", maj_stat);
goto out_put_ctx;
}
p = xdr_encode_opaque(p, NULL, mic.len);
gss_put_ctx(ctx);
return p;
out_put_ctx:
gss_put_ctx(ctx);
return NULL;
}
static int gss_renew_cred(struct rpc_task *task)
{
struct rpc_cred *oldcred = task->tk_rqstp->rq_cred;
struct gss_cred *gss_cred = container_of(oldcred,
struct gss_cred,
gc_base);
struct rpc_auth *auth = oldcred->cr_auth;
struct auth_cred acred = {
.uid = oldcred->cr_uid,
.principal = gss_cred->gc_principal,
.machine_cred = (gss_cred->gc_principal != NULL ? 1 : 0),
};
struct rpc_cred *new;
new = gss_lookup_cred(auth, &acred, RPCAUTH_LOOKUP_NEW);
if (IS_ERR(new))
return PTR_ERR(new);
task->tk_rqstp->rq_cred = new;
put_rpccred(oldcred);
return 0;
}
static int gss_cred_is_negative_entry(struct rpc_cred *cred)
{
if (test_bit(RPCAUTH_CRED_NEGATIVE, &cred->cr_flags)) {
unsigned long now = jiffies;
unsigned long begin, expire;
struct gss_cred *gss_cred;
gss_cred = container_of(cred, struct gss_cred, gc_base);
begin = gss_cred->gc_upcall_timestamp;
expire = begin + gss_expired_cred_retry_delay * HZ;
if (time_in_range_open(now, begin, expire))
return 1;
}
return 0;
}
/*
* Refresh credentials. XXX - finish
*/
static int
gss_refresh(struct rpc_task *task)
{
struct rpc_cred *cred = task->tk_rqstp->rq_cred;
int ret = 0;
if (gss_cred_is_negative_entry(cred))
return -EKEYEXPIRED;
if (!test_bit(RPCAUTH_CRED_NEW, &cred->cr_flags) &&
!test_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags)) {
ret = gss_renew_cred(task);
if (ret < 0)
goto out;
cred = task->tk_rqstp->rq_cred;
}
if (test_bit(RPCAUTH_CRED_NEW, &cred->cr_flags))
ret = gss_refresh_upcall(task);
out:
return ret;
}
/* Dummy refresh routine: used only when destroying the context */
static int
gss_refresh_null(struct rpc_task *task)
{
return 0;
}
static __be32 *
gss_validate(struct rpc_task *task, __be32 *p)
{
struct rpc_cred *cred = task->tk_rqstp->rq_cred;
struct gss_cl_ctx *ctx = gss_cred_get_ctx(cred);
__be32 seq;
struct kvec iov;
struct xdr_buf verf_buf;
struct xdr_netobj mic;
u32 flav,len;
u32 maj_stat;
__be32 *ret = ERR_PTR(-EIO);
dprintk("RPC: %5u %s\n", task->tk_pid, __func__);
flav = ntohl(*p++);
if ((len = ntohl(*p++)) > RPC_MAX_AUTH_SIZE)
goto out_bad;
if (flav != RPC_AUTH_GSS)
goto out_bad;
seq = htonl(task->tk_rqstp->rq_seqno);
iov.iov_base = &seq;
iov.iov_len = sizeof(seq);
xdr_buf_from_iov(&iov, &verf_buf);
mic.data = (u8 *)p;
mic.len = len;
ret = ERR_PTR(-EACCES);
maj_stat = gss_verify_mic(ctx->gc_gss_ctx, &verf_buf, &mic);
if (maj_stat == GSS_S_CONTEXT_EXPIRED)
clear_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags);
if (maj_stat) {
dprintk("RPC: %5u %s: gss_verify_mic returned error 0x%08x\n",
task->tk_pid, __func__, maj_stat);
goto out_bad;
}
/* We leave it to unwrap to calculate au_rslack. For now we just
* calculate the length of the verifier: */
cred->cr_auth->au_verfsize = XDR_QUADLEN(len) + 2;
gss_put_ctx(ctx);
dprintk("RPC: %5u %s: gss_verify_mic succeeded.\n",
task->tk_pid, __func__);
return p + XDR_QUADLEN(len);
out_bad:
gss_put_ctx(ctx);
dprintk("RPC: %5u %s failed ret %ld.\n", task->tk_pid, __func__,
PTR_ERR(ret));
return ret;
}
static void gss_wrap_req_encode(kxdreproc_t encode, struct rpc_rqst *rqstp,
__be32 *p, void *obj)
{
struct xdr_stream xdr;
xdr_init_encode(&xdr, &rqstp->rq_snd_buf, p);
encode(rqstp, &xdr, obj);
}
static inline int
gss_wrap_req_integ(struct rpc_cred *cred, struct gss_cl_ctx *ctx,
kxdreproc_t encode, struct rpc_rqst *rqstp,
__be32 *p, void *obj)
{
struct xdr_buf *snd_buf = &rqstp->rq_snd_buf;
struct xdr_buf integ_buf;
__be32 *integ_len = NULL;
struct xdr_netobj mic;
u32 offset;
__be32 *q;
struct kvec *iov;
u32 maj_stat = 0;
int status = -EIO;
integ_len = p++;
offset = (u8 *)p - (u8 *)snd_buf->head[0].iov_base;
*p++ = htonl(rqstp->rq_seqno);
gss_wrap_req_encode(encode, rqstp, p, obj);
if (xdr_buf_subsegment(snd_buf, &integ_buf,
offset, snd_buf->len - offset))
return status;
*integ_len = htonl(integ_buf.len);
/* guess whether we're in the head or the tail: */
if (snd_buf->page_len || snd_buf->tail[0].iov_len)
iov = snd_buf->tail;
else
iov = snd_buf->head;
p = iov->iov_base + iov->iov_len;
mic.data = (u8 *)(p + 1);
maj_stat = gss_get_mic(ctx->gc_gss_ctx, &integ_buf, &mic);
status = -EIO; /* XXX? */
if (maj_stat == GSS_S_CONTEXT_EXPIRED)
clear_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags);
else if (maj_stat)
return status;
q = xdr_encode_opaque(p, NULL, mic.len);
offset = (u8 *)q - (u8 *)p;
iov->iov_len += offset;
snd_buf->len += offset;
return 0;
}
static void
priv_release_snd_buf(struct rpc_rqst *rqstp)
{
int i;
for (i=0; i < rqstp->rq_enc_pages_num; i++)
__free_page(rqstp->rq_enc_pages[i]);
kfree(rqstp->rq_enc_pages);
}
static int
alloc_enc_pages(struct rpc_rqst *rqstp)
{
struct xdr_buf *snd_buf = &rqstp->rq_snd_buf;
int first, last, i;
if (snd_buf->page_len == 0) {
rqstp->rq_enc_pages_num = 0;
return 0;
}
first = snd_buf->page_base >> PAGE_CACHE_SHIFT;
last = (snd_buf->page_base + snd_buf->page_len - 1) >> PAGE_CACHE_SHIFT;
rqstp->rq_enc_pages_num = last - first + 1 + 1;
rqstp->rq_enc_pages
= kmalloc(rqstp->rq_enc_pages_num * sizeof(struct page *),
GFP_NOFS);
if (!rqstp->rq_enc_pages)
goto out;
for (i=0; i < rqstp->rq_enc_pages_num; i++) {
rqstp->rq_enc_pages[i] = alloc_page(GFP_NOFS);
if (rqstp->rq_enc_pages[i] == NULL)
goto out_free;
}
rqstp->rq_release_snd_buf = priv_release_snd_buf;
return 0;
out_free:
rqstp->rq_enc_pages_num = i;
priv_release_snd_buf(rqstp);
out:
return -EAGAIN;
}
static inline int
gss_wrap_req_priv(struct rpc_cred *cred, struct gss_cl_ctx *ctx,
kxdreproc_t encode, struct rpc_rqst *rqstp,
__be32 *p, void *obj)
{
struct xdr_buf *snd_buf = &rqstp->rq_snd_buf;
u32 offset;
u32 maj_stat;
int status;
__be32 *opaque_len;
struct page **inpages;
int first;
int pad;
struct kvec *iov;
char *tmp;
opaque_len = p++;
offset = (u8 *)p - (u8 *)snd_buf->head[0].iov_base;
*p++ = htonl(rqstp->rq_seqno);
gss_wrap_req_encode(encode, rqstp, p, obj);
status = alloc_enc_pages(rqstp);
if (status)
return status;
first = snd_buf->page_base >> PAGE_CACHE_SHIFT;
inpages = snd_buf->pages + first;
snd_buf->pages = rqstp->rq_enc_pages;
snd_buf->page_base -= first << PAGE_CACHE_SHIFT;
/*
* Give the tail its own page, in case we need extra space in the
* head when wrapping:
*
* call_allocate() allocates twice the slack space required
* by the authentication flavor to rq_callsize.
* For GSS, slack is GSS_CRED_SLACK.
*/
if (snd_buf->page_len || snd_buf->tail[0].iov_len) {
tmp = page_address(rqstp->rq_enc_pages[rqstp->rq_enc_pages_num - 1]);
memcpy(tmp, snd_buf->tail[0].iov_base, snd_buf->tail[0].iov_len);
snd_buf->tail[0].iov_base = tmp;
}
maj_stat = gss_wrap(ctx->gc_gss_ctx, offset, snd_buf, inpages);
/* slack space should prevent this ever happening: */
BUG_ON(snd_buf->len > snd_buf->buflen);
status = -EIO;
/* We're assuming that when GSS_S_CONTEXT_EXPIRED, the encryption was
* done anyway, so it's safe to put the request on the wire: */
if (maj_stat == GSS_S_CONTEXT_EXPIRED)
clear_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags);
else if (maj_stat)
return status;
*opaque_len = htonl(snd_buf->len - offset);
/* guess whether we're in the head or the tail: */
if (snd_buf->page_len || snd_buf->tail[0].iov_len)
iov = snd_buf->tail;
else
iov = snd_buf->head;
p = iov->iov_base + iov->iov_len;
pad = 3 - ((snd_buf->len - offset - 1) & 3);
memset(p, 0, pad);
iov->iov_len += pad;
snd_buf->len += pad;
return 0;
}
static int
gss_wrap_req(struct rpc_task *task,
kxdreproc_t encode, void *rqstp, __be32 *p, void *obj)
{
struct rpc_cred *cred = task->tk_rqstp->rq_cred;
struct gss_cred *gss_cred = container_of(cred, struct gss_cred,
gc_base);
struct gss_cl_ctx *ctx = gss_cred_get_ctx(cred);
int status = -EIO;
dprintk("RPC: %5u %s\n", task->tk_pid, __func__);
if (ctx->gc_proc != RPC_GSS_PROC_DATA) {
/* The spec seems a little ambiguous here, but I think that not
* wrapping context destruction requests makes the most sense.
*/
gss_wrap_req_encode(encode, rqstp, p, obj);
status = 0;
goto out;
}
switch (gss_cred->gc_service) {
case RPC_GSS_SVC_NONE:
gss_wrap_req_encode(encode, rqstp, p, obj);
status = 0;
break;
case RPC_GSS_SVC_INTEGRITY:
status = gss_wrap_req_integ(cred, ctx, encode, rqstp, p, obj);
break;
case RPC_GSS_SVC_PRIVACY:
status = gss_wrap_req_priv(cred, ctx, encode, rqstp, p, obj);
break;
}
out:
gss_put_ctx(ctx);
dprintk("RPC: %5u %s returning %d\n", task->tk_pid, __func__, status);
return status;
}
static inline int
gss_unwrap_resp_integ(struct rpc_cred *cred, struct gss_cl_ctx *ctx,
struct rpc_rqst *rqstp, __be32 **p)
{
struct xdr_buf *rcv_buf = &rqstp->rq_rcv_buf;
struct xdr_buf integ_buf;
struct xdr_netobj mic;
u32 data_offset, mic_offset;
u32 integ_len;
u32 maj_stat;
int status = -EIO;
integ_len = ntohl(*(*p)++);
if (integ_len & 3)
return status;
data_offset = (u8 *)(*p) - (u8 *)rcv_buf->head[0].iov_base;
mic_offset = integ_len + data_offset;
if (mic_offset > rcv_buf->len)
return status;
if (ntohl(*(*p)++) != rqstp->rq_seqno)
return status;
if (xdr_buf_subsegment(rcv_buf, &integ_buf, data_offset,
mic_offset - data_offset))
return status;
if (xdr_buf_read_netobj(rcv_buf, &mic, mic_offset))
return status;
maj_stat = gss_verify_mic(ctx->gc_gss_ctx, &integ_buf, &mic);
if (maj_stat == GSS_S_CONTEXT_EXPIRED)
clear_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags);
if (maj_stat != GSS_S_COMPLETE)
return status;
return 0;
}
static inline int
gss_unwrap_resp_priv(struct rpc_cred *cred, struct gss_cl_ctx *ctx,
struct rpc_rqst *rqstp, __be32 **p)
{
struct xdr_buf *rcv_buf = &rqstp->rq_rcv_buf;
u32 offset;
u32 opaque_len;
u32 maj_stat;
int status = -EIO;
opaque_len = ntohl(*(*p)++);
offset = (u8 *)(*p) - (u8 *)rcv_buf->head[0].iov_base;
if (offset + opaque_len > rcv_buf->len)
return status;
/* remove padding: */
rcv_buf->len = offset + opaque_len;
maj_stat = gss_unwrap(ctx->gc_gss_ctx, offset, rcv_buf);
if (maj_stat == GSS_S_CONTEXT_EXPIRED)
clear_bit(RPCAUTH_CRED_UPTODATE, &cred->cr_flags);
if (maj_stat != GSS_S_COMPLETE)
return status;
if (ntohl(*(*p)++) != rqstp->rq_seqno)
return status;
return 0;
}
static int
gss_unwrap_req_decode(kxdrdproc_t decode, struct rpc_rqst *rqstp,
__be32 *p, void *obj)
{
struct xdr_stream xdr;
xdr_init_decode(&xdr, &rqstp->rq_rcv_buf, p);
return decode(rqstp, &xdr, obj);
}
static int
gss_unwrap_resp(struct rpc_task *task,
kxdrdproc_t decode, void *rqstp, __be32 *p, void *obj)
{
struct rpc_cred *cred = task->tk_rqstp->rq_cred;
struct gss_cred *gss_cred = container_of(cred, struct gss_cred,
gc_base);
struct gss_cl_ctx *ctx = gss_cred_get_ctx(cred);
__be32 *savedp = p;
struct kvec *head = ((struct rpc_rqst *)rqstp)->rq_rcv_buf.head;
int savedlen = head->iov_len;
int status = -EIO;
if (ctx->gc_proc != RPC_GSS_PROC_DATA)
goto out_decode;
switch (gss_cred->gc_service) {
case RPC_GSS_SVC_NONE:
break;
case RPC_GSS_SVC_INTEGRITY:
status = gss_unwrap_resp_integ(cred, ctx, rqstp, &p);
if (status)
goto out;
break;
case RPC_GSS_SVC_PRIVACY:
status = gss_unwrap_resp_priv(cred, ctx, rqstp, &p);
if (status)
goto out;
break;
}
/* take into account extra slack for integrity and privacy cases: */
cred->cr_auth->au_rslack = cred->cr_auth->au_verfsize + (p - savedp)
+ (savedlen - head->iov_len);
out_decode:
status = gss_unwrap_req_decode(decode, rqstp, p, obj);
out:
gss_put_ctx(ctx);
dprintk("RPC: %5u %s returning %d\n",
task->tk_pid, __func__, status);
return status;
}
static const struct rpc_authops authgss_ops = {
.owner = THIS_MODULE,
.au_flavor = RPC_AUTH_GSS,
.au_name = "RPCSEC_GSS",
.create = gss_create,
.destroy = gss_destroy,
.lookup_cred = gss_lookup_cred,
.crcreate = gss_create_cred,
.list_pseudoflavors = gss_mech_list_pseudoflavors,
.info2flavor = gss_mech_info2flavor,
.flavor2info = gss_mech_flavor2info,
};
static const struct rpc_credops gss_credops = {
.cr_name = "AUTH_GSS",
.crdestroy = gss_destroy_cred,
.cr_init = gss_cred_init,
.crbind = rpcauth_generic_bind_cred,
.crmatch = gss_match,
.crmarshal = gss_marshal,
.crrefresh = gss_refresh,
.crvalidate = gss_validate,
.crwrap_req = gss_wrap_req,
.crunwrap_resp = gss_unwrap_resp,
.crkey_timeout = gss_key_timeout,
.crstringify_acceptor = gss_stringify_acceptor,
};
static const struct rpc_credops gss_nullops = {
.cr_name = "AUTH_GSS",
.crdestroy = gss_destroy_nullcred,
.crbind = rpcauth_generic_bind_cred,
.crmatch = gss_match,
.crmarshal = gss_marshal,
.crrefresh = gss_refresh_null,
.crvalidate = gss_validate,
.crwrap_req = gss_wrap_req,
.crunwrap_resp = gss_unwrap_resp,
.crstringify_acceptor = gss_stringify_acceptor,
};
static const struct rpc_pipe_ops gss_upcall_ops_v0 = {
.upcall = rpc_pipe_generic_upcall,
.downcall = gss_pipe_downcall,
.destroy_msg = gss_pipe_destroy_msg,
.open_pipe = gss_pipe_open_v0,
.release_pipe = gss_pipe_release,
};
static const struct rpc_pipe_ops gss_upcall_ops_v1 = {
.upcall = rpc_pipe_generic_upcall,
.downcall = gss_pipe_downcall,
.destroy_msg = gss_pipe_destroy_msg,
.open_pipe = gss_pipe_open_v1,
.release_pipe = gss_pipe_release,
};
static __net_init int rpcsec_gss_init_net(struct net *net)
{
return gss_svc_init_net(net);
}
static __net_exit void rpcsec_gss_exit_net(struct net *net)
{
gss_svc_shutdown_net(net);
}
static struct pernet_operations rpcsec_gss_net_ops = {
.init = rpcsec_gss_init_net,
.exit = rpcsec_gss_exit_net,
};
/*
* Initialize RPCSEC_GSS module
*/
static int __init init_rpcsec_gss(void)
{
int err = 0;
err = rpcauth_register(&authgss_ops);
if (err)
goto out;
err = gss_svc_init();
if (err)
goto out_unregister;
err = register_pernet_subsys(&rpcsec_gss_net_ops);
if (err)
goto out_svc_exit;
rpc_init_wait_queue(&pipe_version_rpc_waitqueue, "gss pipe version");
return 0;
out_svc_exit:
gss_svc_shutdown();
out_unregister:
rpcauth_unregister(&authgss_ops);
out:
return err;
}
static void __exit exit_rpcsec_gss(void)
{
unregister_pernet_subsys(&rpcsec_gss_net_ops);
gss_svc_shutdown();
rpcauth_unregister(&authgss_ops);
rcu_barrier(); /* Wait for completion of call_rcu()'s */
}
MODULE_ALIAS("rpc-auth-6");
MODULE_LICENSE("GPL");
module_param_named(expired_cred_retry_delay,
gss_expired_cred_retry_delay,
uint, 0644);
MODULE_PARM_DESC(expired_cred_retry_delay, "Timeout (in seconds) until "
"the RPC engine retries an expired credential");
module_param_named(key_expire_timeo,
gss_key_expire_timeo,
uint, 0644);
MODULE_PARM_DESC(key_expire_timeo, "Time (in seconds) at the end of a "
"credential keys lifetime where the NFS layer cleans up "
"prior to key expiration");
module_init(init_rpcsec_gss)
module_exit(exit_rpcsec_gss)
| gpl-2.0 |
skywave/caf-zte-blade | net/atm/atm_sysfs.c | 136 | 4017 | /* ATM driver model support. */
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/kobject.h>
#include <linux/atmdev.h>
#include "common.h"
#include "resources.h"
#define to_atm_dev(cldev) container_of(cldev, struct atm_dev, class_dev)
static ssize_t show_type(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct atm_dev *adev = to_atm_dev(cdev);
return sprintf(buf, "%s\n", adev->type);
}
static ssize_t show_address(struct device *cdev,
struct device_attribute *attr, char *buf)
{
char *pos = buf;
struct atm_dev *adev = to_atm_dev(cdev);
int i;
for (i = 0; i < (ESI_LEN - 1); i++)
pos += sprintf(pos, "%02x:", adev->esi[i]);
pos += sprintf(pos, "%02x\n", adev->esi[i]);
return pos - buf;
}
static ssize_t show_atmaddress(struct device *cdev,
struct device_attribute *attr, char *buf)
{
unsigned long flags;
char *pos = buf;
struct atm_dev *adev = to_atm_dev(cdev);
struct atm_dev_addr *aaddr;
int bin[] = { 1, 2, 10, 6, 1 }, *fmt = bin;
int i, j;
spin_lock_irqsave(&adev->lock, flags);
list_for_each_entry(aaddr, &adev->local, entry) {
for (i = 0, j = 0; i < ATM_ESA_LEN; ++i, ++j) {
if (j == *fmt) {
pos += sprintf(pos, ".");
++fmt;
j = 0;
}
pos += sprintf(pos, "%02x",
aaddr->addr.sas_addr.prv[i]);
}
pos += sprintf(pos, "\n");
}
spin_unlock_irqrestore(&adev->lock, flags);
return pos - buf;
}
static ssize_t show_carrier(struct device *cdev,
struct device_attribute *attr, char *buf)
{
char *pos = buf;
struct atm_dev *adev = to_atm_dev(cdev);
pos += sprintf(pos, "%d\n",
adev->signal == ATM_PHY_SIG_LOST ? 0 : 1);
return pos - buf;
}
static ssize_t show_link_rate(struct device *cdev,
struct device_attribute *attr, char *buf)
{
char *pos = buf;
struct atm_dev *adev = to_atm_dev(cdev);
int link_rate;
/* show the link rate, not the data rate */
switch (adev->link_rate) {
case ATM_OC3_PCR:
link_rate = 155520000;
break;
case ATM_OC12_PCR:
link_rate = 622080000;
break;
case ATM_25_PCR:
link_rate = 25600000;
break;
default:
link_rate = adev->link_rate * 8 * 53;
}
pos += sprintf(pos, "%d\n", link_rate);
return pos - buf;
}
static DEVICE_ATTR(address, S_IRUGO, show_address, NULL);
static DEVICE_ATTR(atmaddress, S_IRUGO, show_atmaddress, NULL);
static DEVICE_ATTR(carrier, S_IRUGO, show_carrier, NULL);
static DEVICE_ATTR(type, S_IRUGO, show_type, NULL);
static DEVICE_ATTR(link_rate, S_IRUGO, show_link_rate, NULL);
static struct device_attribute *atm_attrs[] = {
&dev_attr_atmaddress,
&dev_attr_address,
&dev_attr_carrier,
&dev_attr_type,
&dev_attr_link_rate,
NULL
};
static int atm_uevent(struct device *cdev, struct kobj_uevent_env *env)
{
struct atm_dev *adev;
if (!cdev)
return -ENODEV;
adev = to_atm_dev(cdev);
if (!adev)
return -ENODEV;
if (add_uevent_var(env, "NAME=%s%d", adev->type, adev->number))
return -ENOMEM;
return 0;
}
static void atm_release(struct device *cdev)
{
struct atm_dev *adev = to_atm_dev(cdev);
kfree(adev);
}
static struct class atm_class = {
.name = "atm",
.dev_release = atm_release,
.dev_uevent = atm_uevent,
};
int atm_register_sysfs(struct atm_dev *adev, struct device *parent)
{
struct device *cdev = &adev->class_dev;
int i, j, err;
cdev->class = &atm_class;
cdev->parent = parent;
dev_set_drvdata(cdev, adev);
dev_set_name(cdev, "%s%d", adev->type, adev->number);
err = device_register(cdev);
if (err < 0)
return err;
for (i = 0; atm_attrs[i]; i++) {
err = device_create_file(cdev, atm_attrs[i]);
if (err)
goto err_out;
}
return 0;
err_out:
for (j = 0; j < i; j++)
device_remove_file(cdev, atm_attrs[j]);
device_del(cdev);
return err;
}
void atm_unregister_sysfs(struct atm_dev *adev)
{
struct device *cdev = &adev->class_dev;
device_del(cdev);
}
int __init atm_sysfs_init(void)
{
return class_register(&atm_class);
}
void __exit atm_sysfs_exit(void)
{
class_unregister(&atm_class);
}
| gpl-2.0 |
vvanpo/linux | drivers/staging/lustre/lustre/ptlrpc/sec.c | 392 | 63875 | /*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* as published by the Free Software Foundation.
*
* This 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 version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see
* http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* GPL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* Copyright (c) 2011, 2012, Intel Corporation.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*
* lustre/ptlrpc/sec.c
*
* Author: Eric Mei <ericm@clusterfs.com>
*/
#define DEBUG_SUBSYSTEM S_SEC
#include "../../include/linux/libcfs/libcfs.h"
#include <linux/crypto.h>
#include <linux/key.h>
#include "../include/obd.h"
#include "../include/obd_class.h"
#include "../include/obd_support.h"
#include "../include/lustre_net.h"
#include "../include/lustre_import.h"
#include "../include/lustre_dlm.h"
#include "../include/lustre_sec.h"
#include "ptlrpc_internal.h"
/***********************************************
* policy registers *
***********************************************/
static rwlock_t policy_lock;
static struct ptlrpc_sec_policy *policies[SPTLRPC_POLICY_MAX] = {
NULL,
};
int sptlrpc_register_policy(struct ptlrpc_sec_policy *policy)
{
__u16 number = policy->sp_policy;
LASSERT(policy->sp_name);
LASSERT(policy->sp_cops);
LASSERT(policy->sp_sops);
if (number >= SPTLRPC_POLICY_MAX)
return -EINVAL;
write_lock(&policy_lock);
if (unlikely(policies[number])) {
write_unlock(&policy_lock);
return -EALREADY;
}
policies[number] = policy;
write_unlock(&policy_lock);
CDEBUG(D_SEC, "%s: registered\n", policy->sp_name);
return 0;
}
EXPORT_SYMBOL(sptlrpc_register_policy);
int sptlrpc_unregister_policy(struct ptlrpc_sec_policy *policy)
{
__u16 number = policy->sp_policy;
LASSERT(number < SPTLRPC_POLICY_MAX);
write_lock(&policy_lock);
if (unlikely(policies[number] == NULL)) {
write_unlock(&policy_lock);
CERROR("%s: already unregistered\n", policy->sp_name);
return -EINVAL;
}
LASSERT(policies[number] == policy);
policies[number] = NULL;
write_unlock(&policy_lock);
CDEBUG(D_SEC, "%s: unregistered\n", policy->sp_name);
return 0;
}
EXPORT_SYMBOL(sptlrpc_unregister_policy);
static
struct ptlrpc_sec_policy *sptlrpc_wireflavor2policy(__u32 flavor)
{
static DEFINE_MUTEX(load_mutex);
static atomic_t loaded = ATOMIC_INIT(0);
struct ptlrpc_sec_policy *policy;
__u16 number = SPTLRPC_FLVR_POLICY(flavor);
__u16 flag = 0;
if (number >= SPTLRPC_POLICY_MAX)
return NULL;
while (1) {
read_lock(&policy_lock);
policy = policies[number];
if (policy && !try_module_get(policy->sp_owner))
policy = NULL;
if (policy == NULL)
flag = atomic_read(&loaded);
read_unlock(&policy_lock);
if (policy != NULL || flag != 0 ||
number != SPTLRPC_POLICY_GSS)
break;
/* try to load gss module, once */
mutex_lock(&load_mutex);
if (atomic_read(&loaded) == 0) {
if (request_module("ptlrpc_gss") == 0)
CDEBUG(D_SEC,
"module ptlrpc_gss loaded on demand\n");
else
CERROR("Unable to load module ptlrpc_gss\n");
atomic_set(&loaded, 1);
}
mutex_unlock(&load_mutex);
}
return policy;
}
__u32 sptlrpc_name2flavor_base(const char *name)
{
if (!strcmp(name, "null"))
return SPTLRPC_FLVR_NULL;
if (!strcmp(name, "plain"))
return SPTLRPC_FLVR_PLAIN;
if (!strcmp(name, "krb5n"))
return SPTLRPC_FLVR_KRB5N;
if (!strcmp(name, "krb5a"))
return SPTLRPC_FLVR_KRB5A;
if (!strcmp(name, "krb5i"))
return SPTLRPC_FLVR_KRB5I;
if (!strcmp(name, "krb5p"))
return SPTLRPC_FLVR_KRB5P;
return SPTLRPC_FLVR_INVALID;
}
EXPORT_SYMBOL(sptlrpc_name2flavor_base);
const char *sptlrpc_flavor2name_base(__u32 flvr)
{
__u32 base = SPTLRPC_FLVR_BASE(flvr);
if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_NULL))
return "null";
else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_PLAIN))
return "plain";
else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5N))
return "krb5n";
else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5A))
return "krb5a";
else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5I))
return "krb5i";
else if (base == SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_KRB5P))
return "krb5p";
CERROR("invalid wire flavor 0x%x\n", flvr);
return "invalid";
}
EXPORT_SYMBOL(sptlrpc_flavor2name_base);
char *sptlrpc_flavor2name_bulk(struct sptlrpc_flavor *sf,
char *buf, int bufsize)
{
if (SPTLRPC_FLVR_POLICY(sf->sf_rpc) == SPTLRPC_POLICY_PLAIN)
snprintf(buf, bufsize, "hash:%s",
sptlrpc_get_hash_name(sf->u_bulk.hash.hash_alg));
else
snprintf(buf, bufsize, "%s",
sptlrpc_flavor2name_base(sf->sf_rpc));
buf[bufsize - 1] = '\0';
return buf;
}
EXPORT_SYMBOL(sptlrpc_flavor2name_bulk);
char *sptlrpc_flavor2name(struct sptlrpc_flavor *sf, char *buf, int bufsize)
{
strlcpy(buf, sptlrpc_flavor2name_base(sf->sf_rpc), bufsize);
/*
* currently we don't support customized bulk specification for
* flavors other than plain
*/
if (SPTLRPC_FLVR_POLICY(sf->sf_rpc) == SPTLRPC_POLICY_PLAIN) {
char bspec[16];
bspec[0] = '-';
sptlrpc_flavor2name_bulk(sf, &bspec[1], sizeof(bspec) - 1);
strlcat(buf, bspec, bufsize);
}
return buf;
}
EXPORT_SYMBOL(sptlrpc_flavor2name);
char *sptlrpc_secflags2str(__u32 flags, char *buf, int bufsize)
{
buf[0] = '\0';
if (flags & PTLRPC_SEC_FL_REVERSE)
strlcat(buf, "reverse,", bufsize);
if (flags & PTLRPC_SEC_FL_ROOTONLY)
strlcat(buf, "rootonly,", bufsize);
if (flags & PTLRPC_SEC_FL_UDESC)
strlcat(buf, "udesc,", bufsize);
if (flags & PTLRPC_SEC_FL_BULK)
strlcat(buf, "bulk,", bufsize);
if (buf[0] == '\0')
strlcat(buf, "-,", bufsize);
return buf;
}
EXPORT_SYMBOL(sptlrpc_secflags2str);
/**************************************************
* client context APIs *
**************************************************/
static
struct ptlrpc_cli_ctx *get_my_ctx(struct ptlrpc_sec *sec)
{
struct vfs_cred vcred;
int create = 1, remove_dead = 1;
LASSERT(sec);
LASSERT(sec->ps_policy->sp_cops->lookup_ctx);
if (sec->ps_flvr.sf_flags & (PTLRPC_SEC_FL_REVERSE |
PTLRPC_SEC_FL_ROOTONLY)) {
vcred.vc_uid = 0;
vcred.vc_gid = 0;
if (sec->ps_flvr.sf_flags & PTLRPC_SEC_FL_REVERSE) {
create = 0;
remove_dead = 0;
}
} else {
vcred.vc_uid = from_kuid(&init_user_ns, current_uid());
vcred.vc_gid = from_kgid(&init_user_ns, current_gid());
}
return sec->ps_policy->sp_cops->lookup_ctx(sec, &vcred,
create, remove_dead);
}
struct ptlrpc_cli_ctx *sptlrpc_cli_ctx_get(struct ptlrpc_cli_ctx *ctx)
{
atomic_inc(&ctx->cc_refcount);
return ctx;
}
EXPORT_SYMBOL(sptlrpc_cli_ctx_get);
void sptlrpc_cli_ctx_put(struct ptlrpc_cli_ctx *ctx, int sync)
{
struct ptlrpc_sec *sec = ctx->cc_sec;
LASSERT(sec);
LASSERT_ATOMIC_POS(&ctx->cc_refcount);
if (!atomic_dec_and_test(&ctx->cc_refcount))
return;
sec->ps_policy->sp_cops->release_ctx(sec, ctx, sync);
}
EXPORT_SYMBOL(sptlrpc_cli_ctx_put);
/**
* Expire the client context immediately.
*
* \pre Caller must hold at least 1 reference on the \a ctx.
*/
void sptlrpc_cli_ctx_expire(struct ptlrpc_cli_ctx *ctx)
{
LASSERT(ctx->cc_ops->force_die);
ctx->cc_ops->force_die(ctx, 0);
}
EXPORT_SYMBOL(sptlrpc_cli_ctx_expire);
/**
* To wake up the threads who are waiting for this client context. Called
* after some status change happened on \a ctx.
*/
void sptlrpc_cli_ctx_wakeup(struct ptlrpc_cli_ctx *ctx)
{
struct ptlrpc_request *req, *next;
spin_lock(&ctx->cc_lock);
list_for_each_entry_safe(req, next, &ctx->cc_req_list,
rq_ctx_chain) {
list_del_init(&req->rq_ctx_chain);
ptlrpc_client_wake_req(req);
}
spin_unlock(&ctx->cc_lock);
}
EXPORT_SYMBOL(sptlrpc_cli_ctx_wakeup);
int sptlrpc_cli_ctx_display(struct ptlrpc_cli_ctx *ctx, char *buf, int bufsize)
{
LASSERT(ctx->cc_ops);
if (ctx->cc_ops->display == NULL)
return 0;
return ctx->cc_ops->display(ctx, buf, bufsize);
}
static int import_sec_check_expire(struct obd_import *imp)
{
int adapt = 0;
spin_lock(&imp->imp_lock);
if (imp->imp_sec_expire &&
imp->imp_sec_expire < get_seconds()) {
adapt = 1;
imp->imp_sec_expire = 0;
}
spin_unlock(&imp->imp_lock);
if (!adapt)
return 0;
CDEBUG(D_SEC, "found delayed sec adapt expired, do it now\n");
return sptlrpc_import_sec_adapt(imp, NULL, NULL);
}
static int import_sec_validate_get(struct obd_import *imp,
struct ptlrpc_sec **sec)
{
int rc;
if (unlikely(imp->imp_sec_expire)) {
rc = import_sec_check_expire(imp);
if (rc)
return rc;
}
*sec = sptlrpc_import_sec_ref(imp);
if (*sec == NULL) {
CERROR("import %p (%s) with no sec\n",
imp, ptlrpc_import_state_name(imp->imp_state));
return -EACCES;
}
if (unlikely((*sec)->ps_dying)) {
CERROR("attempt to use dying sec %p\n", sec);
sptlrpc_sec_put(*sec);
return -EACCES;
}
return 0;
}
/**
* Given a \a req, find or allocate a appropriate context for it.
* \pre req->rq_cli_ctx == NULL.
*
* \retval 0 succeed, and req->rq_cli_ctx is set.
* \retval -ev error number, and req->rq_cli_ctx == NULL.
*/
int sptlrpc_req_get_ctx(struct ptlrpc_request *req)
{
struct obd_import *imp = req->rq_import;
struct ptlrpc_sec *sec;
int rc;
LASSERT(!req->rq_cli_ctx);
LASSERT(imp);
rc = import_sec_validate_get(imp, &sec);
if (rc)
return rc;
req->rq_cli_ctx = get_my_ctx(sec);
sptlrpc_sec_put(sec);
if (!req->rq_cli_ctx) {
CERROR("req %p: fail to get context\n", req);
return -ENOMEM;
}
return 0;
}
/**
* Drop the context for \a req.
* \pre req->rq_cli_ctx != NULL.
* \post req->rq_cli_ctx == NULL.
*
* If \a sync == 0, this function should return quickly without sleep;
* otherwise it might trigger and wait for the whole process of sending
* an context-destroying rpc to server.
*/
void sptlrpc_req_put_ctx(struct ptlrpc_request *req, int sync)
{
LASSERT(req);
LASSERT(req->rq_cli_ctx);
/* request might be asked to release earlier while still
* in the context waiting list.
*/
if (!list_empty(&req->rq_ctx_chain)) {
spin_lock(&req->rq_cli_ctx->cc_lock);
list_del_init(&req->rq_ctx_chain);
spin_unlock(&req->rq_cli_ctx->cc_lock);
}
sptlrpc_cli_ctx_put(req->rq_cli_ctx, sync);
req->rq_cli_ctx = NULL;
}
static
int sptlrpc_req_ctx_switch(struct ptlrpc_request *req,
struct ptlrpc_cli_ctx *oldctx,
struct ptlrpc_cli_ctx *newctx)
{
struct sptlrpc_flavor old_flvr;
char *reqmsg = NULL; /* to workaround old gcc */
int reqmsg_size;
int rc = 0;
LASSERT(req->rq_reqmsg);
LASSERT(req->rq_reqlen);
LASSERT(req->rq_replen);
CDEBUG(D_SEC, "req %p: switch ctx %p(%u->%s) -> %p(%u->%s), switch sec %p(%s) -> %p(%s)\n",
req,
oldctx, oldctx->cc_vcred.vc_uid, sec2target_str(oldctx->cc_sec),
newctx, newctx->cc_vcred.vc_uid, sec2target_str(newctx->cc_sec),
oldctx->cc_sec, oldctx->cc_sec->ps_policy->sp_name,
newctx->cc_sec, newctx->cc_sec->ps_policy->sp_name);
/* save flavor */
old_flvr = req->rq_flvr;
/* save request message */
reqmsg_size = req->rq_reqlen;
if (reqmsg_size != 0) {
reqmsg = libcfs_kvzalloc(reqmsg_size, GFP_NOFS);
if (reqmsg == NULL)
return -ENOMEM;
memcpy(reqmsg, req->rq_reqmsg, reqmsg_size);
}
/* release old req/rep buf */
req->rq_cli_ctx = oldctx;
sptlrpc_cli_free_reqbuf(req);
sptlrpc_cli_free_repbuf(req);
req->rq_cli_ctx = newctx;
/* recalculate the flavor */
sptlrpc_req_set_flavor(req, 0);
/* alloc new request buffer
* we don't need to alloc reply buffer here, leave it to the
* rest procedure of ptlrpc */
if (reqmsg_size != 0) {
rc = sptlrpc_cli_alloc_reqbuf(req, reqmsg_size);
if (!rc) {
LASSERT(req->rq_reqmsg);
memcpy(req->rq_reqmsg, reqmsg, reqmsg_size);
} else {
CWARN("failed to alloc reqbuf: %d\n", rc);
req->rq_flvr = old_flvr;
}
kvfree(reqmsg);
}
return rc;
}
/**
* If current context of \a req is dead somehow, e.g. we just switched flavor
* thus marked original contexts dead, we'll find a new context for it. if
* no switch is needed, \a req will end up with the same context.
*
* \note a request must have a context, to keep other parts of code happy.
* In any case of failure during the switching, we must restore the old one.
*/
int sptlrpc_req_replace_dead_ctx(struct ptlrpc_request *req)
{
struct ptlrpc_cli_ctx *oldctx = req->rq_cli_ctx;
struct ptlrpc_cli_ctx *newctx;
int rc;
LASSERT(oldctx);
sptlrpc_cli_ctx_get(oldctx);
sptlrpc_req_put_ctx(req, 0);
rc = sptlrpc_req_get_ctx(req);
if (unlikely(rc)) {
LASSERT(!req->rq_cli_ctx);
/* restore old ctx */
req->rq_cli_ctx = oldctx;
return rc;
}
newctx = req->rq_cli_ctx;
LASSERT(newctx);
if (unlikely(newctx == oldctx &&
test_bit(PTLRPC_CTX_DEAD_BIT, &oldctx->cc_flags))) {
/*
* still get the old dead ctx, usually means system too busy
*/
CDEBUG(D_SEC,
"ctx (%p, fl %lx) doesn't switch, relax a little bit\n",
newctx, newctx->cc_flags);
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(HZ);
} else {
/*
* it's possible newctx == oldctx if we're switching
* subflavor with the same sec.
*/
rc = sptlrpc_req_ctx_switch(req, oldctx, newctx);
if (rc) {
/* restore old ctx */
sptlrpc_req_put_ctx(req, 0);
req->rq_cli_ctx = oldctx;
return rc;
}
LASSERT(req->rq_cli_ctx == newctx);
}
sptlrpc_cli_ctx_put(oldctx, 1);
return 0;
}
EXPORT_SYMBOL(sptlrpc_req_replace_dead_ctx);
static
int ctx_check_refresh(struct ptlrpc_cli_ctx *ctx)
{
if (cli_ctx_is_refreshed(ctx))
return 1;
return 0;
}
static
int ctx_refresh_timeout(void *data)
{
struct ptlrpc_request *req = data;
int rc;
/* conn_cnt is needed in expire_one_request */
lustre_msg_set_conn_cnt(req->rq_reqmsg, req->rq_import->imp_conn_cnt);
rc = ptlrpc_expire_one_request(req, 1);
/* if we started recovery, we should mark this ctx dead; otherwise
* in case of lgssd died nobody would retire this ctx, following
* connecting will still find the same ctx thus cause deadlock.
* there's an assumption that expire time of the request should be
* later than the context refresh expire time.
*/
if (rc == 0)
req->rq_cli_ctx->cc_ops->force_die(req->rq_cli_ctx, 0);
return rc;
}
static
void ctx_refresh_interrupt(void *data)
{
struct ptlrpc_request *req = data;
spin_lock(&req->rq_lock);
req->rq_intr = 1;
spin_unlock(&req->rq_lock);
}
static
void req_off_ctx_list(struct ptlrpc_request *req, struct ptlrpc_cli_ctx *ctx)
{
spin_lock(&ctx->cc_lock);
if (!list_empty(&req->rq_ctx_chain))
list_del_init(&req->rq_ctx_chain);
spin_unlock(&ctx->cc_lock);
}
/**
* To refresh the context of \req, if it's not up-to-date.
* \param timeout
* - < 0: don't wait
* - = 0: wait until success or fatal error occur
* - > 0: timeout value (in seconds)
*
* The status of the context could be subject to be changed by other threads
* at any time. We allow this race, but once we return with 0, the caller will
* suppose it's uptodated and keep using it until the owning rpc is done.
*
* \retval 0 only if the context is uptodated.
* \retval -ev error number.
*/
int sptlrpc_req_refresh_ctx(struct ptlrpc_request *req, long timeout)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
struct ptlrpc_sec *sec;
struct l_wait_info lwi;
int rc;
LASSERT(ctx);
if (req->rq_ctx_init || req->rq_ctx_fini)
return 0;
/*
* during the process a request's context might change type even
* (e.g. from gss ctx to null ctx), so each loop we need to re-check
* everything
*/
again:
rc = import_sec_validate_get(req->rq_import, &sec);
if (rc)
return rc;
if (sec->ps_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
CDEBUG(D_SEC, "req %p: flavor has changed %x -> %x\n",
req, req->rq_flvr.sf_rpc, sec->ps_flvr.sf_rpc);
req_off_ctx_list(req, ctx);
sptlrpc_req_replace_dead_ctx(req);
ctx = req->rq_cli_ctx;
}
sptlrpc_sec_put(sec);
if (cli_ctx_is_eternal(ctx))
return 0;
if (unlikely(test_bit(PTLRPC_CTX_NEW_BIT, &ctx->cc_flags))) {
LASSERT(ctx->cc_ops->refresh);
ctx->cc_ops->refresh(ctx);
}
LASSERT(test_bit(PTLRPC_CTX_NEW_BIT, &ctx->cc_flags) == 0);
LASSERT(ctx->cc_ops->validate);
if (ctx->cc_ops->validate(ctx) == 0) {
req_off_ctx_list(req, ctx);
return 0;
}
if (unlikely(test_bit(PTLRPC_CTX_ERROR_BIT, &ctx->cc_flags))) {
spin_lock(&req->rq_lock);
req->rq_err = 1;
spin_unlock(&req->rq_lock);
req_off_ctx_list(req, ctx);
return -EPERM;
}
/*
* There's a subtle issue for resending RPCs, suppose following
* situation:
* 1. the request was sent to server.
* 2. recovery was kicked start, after finished the request was
* marked as resent.
* 3. resend the request.
* 4. old reply from server received, we accept and verify the reply.
* this has to be success, otherwise the error will be aware
* by application.
* 5. new reply from server received, dropped by LNet.
*
* Note the xid of old & new request is the same. We can't simply
* change xid for the resent request because the server replies on
* it for reply reconstruction.
*
* Commonly the original context should be uptodate because we
* have a expiry nice time; server will keep its context because
* we at least hold a ref of old context which prevent context
* destroying RPC being sent. So server still can accept the request
* and finish the RPC. But if that's not the case:
* 1. If server side context has been trimmed, a NO_CONTEXT will
* be returned, gss_cli_ctx_verify/unseal will switch to new
* context by force.
* 2. Current context never be refreshed, then we are fine: we
* never really send request with old context before.
*/
if (test_bit(PTLRPC_CTX_UPTODATE_BIT, &ctx->cc_flags) &&
unlikely(req->rq_reqmsg) &&
lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT) {
req_off_ctx_list(req, ctx);
return 0;
}
if (unlikely(test_bit(PTLRPC_CTX_DEAD_BIT, &ctx->cc_flags))) {
req_off_ctx_list(req, ctx);
/*
* don't switch ctx if import was deactivated
*/
if (req->rq_import->imp_deactive) {
spin_lock(&req->rq_lock);
req->rq_err = 1;
spin_unlock(&req->rq_lock);
return -EINTR;
}
rc = sptlrpc_req_replace_dead_ctx(req);
if (rc) {
LASSERT(ctx == req->rq_cli_ctx);
CERROR("req %p: failed to replace dead ctx %p: %d\n",
req, ctx, rc);
spin_lock(&req->rq_lock);
req->rq_err = 1;
spin_unlock(&req->rq_lock);
return rc;
}
ctx = req->rq_cli_ctx;
goto again;
}
/*
* Now we're sure this context is during upcall, add myself into
* waiting list
*/
spin_lock(&ctx->cc_lock);
if (list_empty(&req->rq_ctx_chain))
list_add(&req->rq_ctx_chain, &ctx->cc_req_list);
spin_unlock(&ctx->cc_lock);
if (timeout < 0)
return -EWOULDBLOCK;
/* Clear any flags that may be present from previous sends */
LASSERT(req->rq_receiving_reply == 0);
spin_lock(&req->rq_lock);
req->rq_err = 0;
req->rq_timedout = 0;
req->rq_resend = 0;
req->rq_restart = 0;
spin_unlock(&req->rq_lock);
lwi = LWI_TIMEOUT_INTR(timeout * HZ, ctx_refresh_timeout,
ctx_refresh_interrupt, req);
rc = l_wait_event(req->rq_reply_waitq, ctx_check_refresh(ctx), &lwi);
/*
* following cases could lead us here:
* - successfully refreshed;
* - interrupted;
* - timedout, and we don't want recover from the failure;
* - timedout, and waked up upon recovery finished;
* - someone else mark this ctx dead by force;
* - someone invalidate the req and call ptlrpc_client_wake_req(),
* e.g. ptlrpc_abort_inflight();
*/
if (!cli_ctx_is_refreshed(ctx)) {
/* timed out or interrupted */
req_off_ctx_list(req, ctx);
LASSERT(rc != 0);
return rc;
}
goto again;
}
/**
* Initialize flavor settings for \a req, according to \a opcode.
*
* \note this could be called in two situations:
* - new request from ptlrpc_pre_req(), with proper @opcode
* - old request which changed ctx in the middle, with @opcode == 0
*/
void sptlrpc_req_set_flavor(struct ptlrpc_request *req, int opcode)
{
struct ptlrpc_sec *sec;
LASSERT(req->rq_import);
LASSERT(req->rq_cli_ctx);
LASSERT(req->rq_cli_ctx->cc_sec);
LASSERT(req->rq_bulk_read == 0 || req->rq_bulk_write == 0);
/* special security flags according to opcode */
switch (opcode) {
case OST_READ:
case MDS_READPAGE:
case MGS_CONFIG_READ:
case OBD_IDX_READ:
req->rq_bulk_read = 1;
break;
case OST_WRITE:
case MDS_WRITEPAGE:
req->rq_bulk_write = 1;
break;
case SEC_CTX_INIT:
req->rq_ctx_init = 1;
break;
case SEC_CTX_FINI:
req->rq_ctx_fini = 1;
break;
case 0:
/* init/fini rpc won't be resend, so can't be here */
LASSERT(req->rq_ctx_init == 0);
LASSERT(req->rq_ctx_fini == 0);
/* cleanup flags, which should be recalculated */
req->rq_pack_udesc = 0;
req->rq_pack_bulk = 0;
break;
}
sec = req->rq_cli_ctx->cc_sec;
spin_lock(&sec->ps_lock);
req->rq_flvr = sec->ps_flvr;
spin_unlock(&sec->ps_lock);
/* force SVC_NULL for context initiation rpc, SVC_INTG for context
* destruction rpc */
if (unlikely(req->rq_ctx_init))
flvr_set_svc(&req->rq_flvr.sf_rpc, SPTLRPC_SVC_NULL);
else if (unlikely(req->rq_ctx_fini))
flvr_set_svc(&req->rq_flvr.sf_rpc, SPTLRPC_SVC_INTG);
/* user descriptor flag, null security can't do it anyway */
if ((sec->ps_flvr.sf_flags & PTLRPC_SEC_FL_UDESC) &&
(req->rq_flvr.sf_rpc != SPTLRPC_FLVR_NULL))
req->rq_pack_udesc = 1;
/* bulk security flag */
if ((req->rq_bulk_read || req->rq_bulk_write) &&
sptlrpc_flavor_has_bulk(&req->rq_flvr))
req->rq_pack_bulk = 1;
}
void sptlrpc_request_out_callback(struct ptlrpc_request *req)
{
if (SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc) != SPTLRPC_SVC_PRIV)
return;
LASSERT(req->rq_clrbuf);
if (req->rq_pool || !req->rq_reqbuf)
return;
kfree(req->rq_reqbuf);
req->rq_reqbuf = NULL;
req->rq_reqbuf_len = 0;
}
/**
* Given an import \a imp, check whether current user has a valid context
* or not. We may create a new context and try to refresh it, and try
* repeatedly try in case of non-fatal errors. Return 0 means success.
*/
int sptlrpc_import_check_ctx(struct obd_import *imp)
{
struct ptlrpc_sec *sec;
struct ptlrpc_cli_ctx *ctx;
struct ptlrpc_request *req = NULL;
int rc;
might_sleep();
sec = sptlrpc_import_sec_ref(imp);
ctx = get_my_ctx(sec);
sptlrpc_sec_put(sec);
if (!ctx)
return -ENOMEM;
if (cli_ctx_is_eternal(ctx) ||
ctx->cc_ops->validate(ctx) == 0) {
sptlrpc_cli_ctx_put(ctx, 1);
return 0;
}
if (cli_ctx_is_error(ctx)) {
sptlrpc_cli_ctx_put(ctx, 1);
return -EACCES;
}
req = ptlrpc_request_cache_alloc(GFP_NOFS);
if (!req)
return -ENOMEM;
spin_lock_init(&req->rq_lock);
atomic_set(&req->rq_refcount, 10000);
INIT_LIST_HEAD(&req->rq_ctx_chain);
init_waitqueue_head(&req->rq_reply_waitq);
init_waitqueue_head(&req->rq_set_waitq);
req->rq_import = imp;
req->rq_flvr = sec->ps_flvr;
req->rq_cli_ctx = ctx;
rc = sptlrpc_req_refresh_ctx(req, 0);
LASSERT(list_empty(&req->rq_ctx_chain));
sptlrpc_cli_ctx_put(req->rq_cli_ctx, 1);
ptlrpc_request_cache_free(req);
return rc;
}
/**
* Used by ptlrpc client, to perform the pre-defined security transformation
* upon the request message of \a req. After this function called,
* req->rq_reqmsg is still accessible as clear text.
*/
int sptlrpc_cli_wrap_request(struct ptlrpc_request *req)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
int rc = 0;
LASSERT(ctx);
LASSERT(ctx->cc_sec);
LASSERT(req->rq_reqbuf || req->rq_clrbuf);
/* we wrap bulk request here because now we can be sure
* the context is uptodate.
*/
if (req->rq_bulk) {
rc = sptlrpc_cli_wrap_bulk(req, req->rq_bulk);
if (rc)
return rc;
}
switch (SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc)) {
case SPTLRPC_SVC_NULL:
case SPTLRPC_SVC_AUTH:
case SPTLRPC_SVC_INTG:
LASSERT(ctx->cc_ops->sign);
rc = ctx->cc_ops->sign(ctx, req);
break;
case SPTLRPC_SVC_PRIV:
LASSERT(ctx->cc_ops->seal);
rc = ctx->cc_ops->seal(ctx, req);
break;
default:
LBUG();
}
if (rc == 0) {
LASSERT(req->rq_reqdata_len);
LASSERT(req->rq_reqdata_len % 8 == 0);
LASSERT(req->rq_reqdata_len <= req->rq_reqbuf_len);
}
return rc;
}
static int do_cli_unwrap_reply(struct ptlrpc_request *req)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
int rc;
LASSERT(ctx);
LASSERT(ctx->cc_sec);
LASSERT(req->rq_repbuf);
LASSERT(req->rq_repdata);
LASSERT(req->rq_repmsg == NULL);
req->rq_rep_swab_mask = 0;
rc = __lustre_unpack_msg(req->rq_repdata, req->rq_repdata_len);
switch (rc) {
case 1:
lustre_set_rep_swabbed(req, MSG_PTLRPC_HEADER_OFF);
case 0:
break;
default:
CERROR("failed unpack reply: x%llu\n", req->rq_xid);
return -EPROTO;
}
if (req->rq_repdata_len < sizeof(struct lustre_msg)) {
CERROR("replied data length %d too small\n",
req->rq_repdata_len);
return -EPROTO;
}
if (SPTLRPC_FLVR_POLICY(req->rq_repdata->lm_secflvr) !=
SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc)) {
CERROR("reply policy %u doesn't match request policy %u\n",
SPTLRPC_FLVR_POLICY(req->rq_repdata->lm_secflvr),
SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc));
return -EPROTO;
}
switch (SPTLRPC_FLVR_SVC(req->rq_flvr.sf_rpc)) {
case SPTLRPC_SVC_NULL:
case SPTLRPC_SVC_AUTH:
case SPTLRPC_SVC_INTG:
LASSERT(ctx->cc_ops->verify);
rc = ctx->cc_ops->verify(ctx, req);
break;
case SPTLRPC_SVC_PRIV:
LASSERT(ctx->cc_ops->unseal);
rc = ctx->cc_ops->unseal(ctx, req);
break;
default:
LBUG();
}
LASSERT(rc || req->rq_repmsg || req->rq_resend);
if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL &&
!req->rq_ctx_init)
req->rq_rep_swab_mask = 0;
return rc;
}
/**
* Used by ptlrpc client, to perform security transformation upon the reply
* message of \a req. After return successfully, req->rq_repmsg points to
* the reply message in clear text.
*
* \pre the reply buffer should have been un-posted from LNet, so nothing is
* going to change.
*/
int sptlrpc_cli_unwrap_reply(struct ptlrpc_request *req)
{
LASSERT(req->rq_repbuf);
LASSERT(req->rq_repdata == NULL);
LASSERT(req->rq_repmsg == NULL);
LASSERT(req->rq_reply_off + req->rq_nob_received <= req->rq_repbuf_len);
if (req->rq_reply_off == 0 &&
(lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT)) {
CERROR("real reply with offset 0\n");
return -EPROTO;
}
if (req->rq_reply_off % 8 != 0) {
CERROR("reply at odd offset %u\n", req->rq_reply_off);
return -EPROTO;
}
req->rq_repdata = (struct lustre_msg *)
(req->rq_repbuf + req->rq_reply_off);
req->rq_repdata_len = req->rq_nob_received;
return do_cli_unwrap_reply(req);
}
/**
* Used by ptlrpc client, to perform security transformation upon the early
* reply message of \a req. We expect the rq_reply_off is 0, and
* rq_nob_received is the early reply size.
*
* Because the receive buffer might be still posted, the reply data might be
* changed at any time, no matter we're holding rq_lock or not. For this reason
* we allocate a separate ptlrpc_request and reply buffer for early reply
* processing.
*
* \retval 0 success, \a req_ret is filled with a duplicated ptlrpc_request.
* Later the caller must call sptlrpc_cli_finish_early_reply() on the returned
* \a *req_ret to release it.
* \retval -ev error number, and \a req_ret will not be set.
*/
int sptlrpc_cli_unwrap_early_reply(struct ptlrpc_request *req,
struct ptlrpc_request **req_ret)
{
struct ptlrpc_request *early_req;
char *early_buf;
int early_bufsz, early_size;
int rc;
early_req = ptlrpc_request_cache_alloc(GFP_NOFS);
if (early_req == NULL)
return -ENOMEM;
early_size = req->rq_nob_received;
early_bufsz = size_roundup_power2(early_size);
early_buf = libcfs_kvzalloc(early_bufsz, GFP_NOFS);
if (early_buf == NULL) {
rc = -ENOMEM;
goto err_req;
}
/* sanity checkings and copy data out, do it inside spinlock */
spin_lock(&req->rq_lock);
if (req->rq_replied) {
spin_unlock(&req->rq_lock);
rc = -EALREADY;
goto err_buf;
}
LASSERT(req->rq_repbuf);
LASSERT(req->rq_repdata == NULL);
LASSERT(req->rq_repmsg == NULL);
if (req->rq_reply_off != 0) {
CERROR("early reply with offset %u\n", req->rq_reply_off);
spin_unlock(&req->rq_lock);
rc = -EPROTO;
goto err_buf;
}
if (req->rq_nob_received != early_size) {
/* even another early arrived the size should be the same */
CERROR("data size has changed from %u to %u\n",
early_size, req->rq_nob_received);
spin_unlock(&req->rq_lock);
rc = -EINVAL;
goto err_buf;
}
if (req->rq_nob_received < sizeof(struct lustre_msg)) {
CERROR("early reply length %d too small\n",
req->rq_nob_received);
spin_unlock(&req->rq_lock);
rc = -EALREADY;
goto err_buf;
}
memcpy(early_buf, req->rq_repbuf, early_size);
spin_unlock(&req->rq_lock);
spin_lock_init(&early_req->rq_lock);
early_req->rq_cli_ctx = sptlrpc_cli_ctx_get(req->rq_cli_ctx);
early_req->rq_flvr = req->rq_flvr;
early_req->rq_repbuf = early_buf;
early_req->rq_repbuf_len = early_bufsz;
early_req->rq_repdata = (struct lustre_msg *) early_buf;
early_req->rq_repdata_len = early_size;
early_req->rq_early = 1;
early_req->rq_reqmsg = req->rq_reqmsg;
rc = do_cli_unwrap_reply(early_req);
if (rc) {
DEBUG_REQ(D_ADAPTTO, early_req,
"error %d unwrap early reply", rc);
goto err_ctx;
}
LASSERT(early_req->rq_repmsg);
*req_ret = early_req;
return 0;
err_ctx:
sptlrpc_cli_ctx_put(early_req->rq_cli_ctx, 1);
err_buf:
kvfree(early_buf);
err_req:
ptlrpc_request_cache_free(early_req);
return rc;
}
/**
* Used by ptlrpc client, to release a processed early reply \a early_req.
*
* \pre \a early_req was obtained from calling sptlrpc_cli_unwrap_early_reply().
*/
void sptlrpc_cli_finish_early_reply(struct ptlrpc_request *early_req)
{
LASSERT(early_req->rq_repbuf);
LASSERT(early_req->rq_repdata);
LASSERT(early_req->rq_repmsg);
sptlrpc_cli_ctx_put(early_req->rq_cli_ctx, 1);
kvfree(early_req->rq_repbuf);
ptlrpc_request_cache_free(early_req);
}
/**************************************************
* sec ID *
**************************************************/
/*
* "fixed" sec (e.g. null) use sec_id < 0
*/
static atomic_t sptlrpc_sec_id = ATOMIC_INIT(1);
int sptlrpc_get_next_secid(void)
{
return atomic_inc_return(&sptlrpc_sec_id);
}
EXPORT_SYMBOL(sptlrpc_get_next_secid);
/**************************************************
* client side high-level security APIs *
**************************************************/
static int sec_cop_flush_ctx_cache(struct ptlrpc_sec *sec, uid_t uid,
int grace, int force)
{
struct ptlrpc_sec_policy *policy = sec->ps_policy;
LASSERT(policy->sp_cops);
LASSERT(policy->sp_cops->flush_ctx_cache);
return policy->sp_cops->flush_ctx_cache(sec, uid, grace, force);
}
static void sec_cop_destroy_sec(struct ptlrpc_sec *sec)
{
struct ptlrpc_sec_policy *policy = sec->ps_policy;
LASSERT_ATOMIC_ZERO(&sec->ps_refcount);
LASSERT_ATOMIC_ZERO(&sec->ps_nctx);
LASSERT(policy->sp_cops->destroy_sec);
CDEBUG(D_SEC, "%s@%p: being destroyed\n", sec->ps_policy->sp_name, sec);
policy->sp_cops->destroy_sec(sec);
sptlrpc_policy_put(policy);
}
void sptlrpc_sec_destroy(struct ptlrpc_sec *sec)
{
sec_cop_destroy_sec(sec);
}
EXPORT_SYMBOL(sptlrpc_sec_destroy);
static void sptlrpc_sec_kill(struct ptlrpc_sec *sec)
{
LASSERT_ATOMIC_POS(&sec->ps_refcount);
if (sec->ps_policy->sp_cops->kill_sec) {
sec->ps_policy->sp_cops->kill_sec(sec);
sec_cop_flush_ctx_cache(sec, -1, 1, 1);
}
}
struct ptlrpc_sec *sptlrpc_sec_get(struct ptlrpc_sec *sec)
{
if (sec)
atomic_inc(&sec->ps_refcount);
return sec;
}
EXPORT_SYMBOL(sptlrpc_sec_get);
void sptlrpc_sec_put(struct ptlrpc_sec *sec)
{
if (sec) {
LASSERT_ATOMIC_POS(&sec->ps_refcount);
if (atomic_dec_and_test(&sec->ps_refcount)) {
sptlrpc_gc_del_sec(sec);
sec_cop_destroy_sec(sec);
}
}
}
EXPORT_SYMBOL(sptlrpc_sec_put);
/*
* policy module is responsible for taking reference of import
*/
static
struct ptlrpc_sec *sptlrpc_sec_create(struct obd_import *imp,
struct ptlrpc_svc_ctx *svc_ctx,
struct sptlrpc_flavor *sf,
enum lustre_sec_part sp)
{
struct ptlrpc_sec_policy *policy;
struct ptlrpc_sec *sec;
char str[32];
if (svc_ctx) {
LASSERT(imp->imp_dlm_fake == 1);
CDEBUG(D_SEC, "%s %s: reverse sec using flavor %s\n",
imp->imp_obd->obd_type->typ_name,
imp->imp_obd->obd_name,
sptlrpc_flavor2name(sf, str, sizeof(str)));
policy = sptlrpc_policy_get(svc_ctx->sc_policy);
sf->sf_flags |= PTLRPC_SEC_FL_REVERSE | PTLRPC_SEC_FL_ROOTONLY;
} else {
LASSERT(imp->imp_dlm_fake == 0);
CDEBUG(D_SEC, "%s %s: select security flavor %s\n",
imp->imp_obd->obd_type->typ_name,
imp->imp_obd->obd_name,
sptlrpc_flavor2name(sf, str, sizeof(str)));
policy = sptlrpc_wireflavor2policy(sf->sf_rpc);
if (!policy) {
CERROR("invalid flavor 0x%x\n", sf->sf_rpc);
return NULL;
}
}
sec = policy->sp_cops->create_sec(imp, svc_ctx, sf);
if (sec) {
atomic_inc(&sec->ps_refcount);
sec->ps_part = sp;
if (sec->ps_gc_interval && policy->sp_cops->gc_ctx)
sptlrpc_gc_add_sec(sec);
} else {
sptlrpc_policy_put(policy);
}
return sec;
}
struct ptlrpc_sec *sptlrpc_import_sec_ref(struct obd_import *imp)
{
struct ptlrpc_sec *sec;
spin_lock(&imp->imp_lock);
sec = sptlrpc_sec_get(imp->imp_sec);
spin_unlock(&imp->imp_lock);
return sec;
}
EXPORT_SYMBOL(sptlrpc_import_sec_ref);
static void sptlrpc_import_sec_install(struct obd_import *imp,
struct ptlrpc_sec *sec)
{
struct ptlrpc_sec *old_sec;
LASSERT_ATOMIC_POS(&sec->ps_refcount);
spin_lock(&imp->imp_lock);
old_sec = imp->imp_sec;
imp->imp_sec = sec;
spin_unlock(&imp->imp_lock);
if (old_sec) {
sptlrpc_sec_kill(old_sec);
/* balance the ref taken by this import */
sptlrpc_sec_put(old_sec);
}
}
static inline
int flavor_equal(struct sptlrpc_flavor *sf1, struct sptlrpc_flavor *sf2)
{
return (memcmp(sf1, sf2, sizeof(*sf1)) == 0);
}
static inline
void flavor_copy(struct sptlrpc_flavor *dst, struct sptlrpc_flavor *src)
{
*dst = *src;
}
static void sptlrpc_import_sec_adapt_inplace(struct obd_import *imp,
struct ptlrpc_sec *sec,
struct sptlrpc_flavor *sf)
{
char str1[32], str2[32];
if (sec->ps_flvr.sf_flags != sf->sf_flags)
CDEBUG(D_SEC, "changing sec flags: %s -> %s\n",
sptlrpc_secflags2str(sec->ps_flvr.sf_flags,
str1, sizeof(str1)),
sptlrpc_secflags2str(sf->sf_flags,
str2, sizeof(str2)));
spin_lock(&sec->ps_lock);
flavor_copy(&sec->ps_flvr, sf);
spin_unlock(&sec->ps_lock);
}
/**
* To get an appropriate ptlrpc_sec for the \a imp, according to the current
* configuration. Upon called, imp->imp_sec may or may not be NULL.
*
* - regular import: \a svc_ctx should be NULL and \a flvr is ignored;
* - reverse import: \a svc_ctx and \a flvr are obtained from incoming request.
*/
int sptlrpc_import_sec_adapt(struct obd_import *imp,
struct ptlrpc_svc_ctx *svc_ctx,
struct sptlrpc_flavor *flvr)
{
struct ptlrpc_connection *conn;
struct sptlrpc_flavor sf;
struct ptlrpc_sec *sec, *newsec;
enum lustre_sec_part sp;
char str[24];
int rc = 0;
might_sleep();
if (imp == NULL)
return 0;
conn = imp->imp_connection;
if (svc_ctx == NULL) {
struct client_obd *cliobd = &imp->imp_obd->u.cli;
/*
* normal import, determine flavor from rule set, except
* for mgc the flavor is predetermined.
*/
if (cliobd->cl_sp_me == LUSTRE_SP_MGC)
sf = cliobd->cl_flvr_mgc;
else
sptlrpc_conf_choose_flavor(cliobd->cl_sp_me,
cliobd->cl_sp_to,
&cliobd->cl_target_uuid,
conn->c_self, &sf);
sp = imp->imp_obd->u.cli.cl_sp_me;
} else {
/* reverse import, determine flavor from incoming request */
sf = *flvr;
if (sf.sf_rpc != SPTLRPC_FLVR_NULL)
sf.sf_flags = PTLRPC_SEC_FL_REVERSE |
PTLRPC_SEC_FL_ROOTONLY;
sp = sptlrpc_target_sec_part(imp->imp_obd);
}
sec = sptlrpc_import_sec_ref(imp);
if (sec) {
char str2[24];
if (flavor_equal(&sf, &sec->ps_flvr))
goto out;
CDEBUG(D_SEC, "import %s->%s: changing flavor %s -> %s\n",
imp->imp_obd->obd_name,
obd_uuid2str(&conn->c_remote_uuid),
sptlrpc_flavor2name(&sec->ps_flvr, str, sizeof(str)),
sptlrpc_flavor2name(&sf, str2, sizeof(str2)));
if (SPTLRPC_FLVR_POLICY(sf.sf_rpc) ==
SPTLRPC_FLVR_POLICY(sec->ps_flvr.sf_rpc) &&
SPTLRPC_FLVR_MECH(sf.sf_rpc) ==
SPTLRPC_FLVR_MECH(sec->ps_flvr.sf_rpc)) {
sptlrpc_import_sec_adapt_inplace(imp, sec, &sf);
goto out;
}
} else if (SPTLRPC_FLVR_BASE(sf.sf_rpc) !=
SPTLRPC_FLVR_BASE(SPTLRPC_FLVR_NULL)) {
CDEBUG(D_SEC, "import %s->%s netid %x: select flavor %s\n",
imp->imp_obd->obd_name,
obd_uuid2str(&conn->c_remote_uuid),
LNET_NIDNET(conn->c_self),
sptlrpc_flavor2name(&sf, str, sizeof(str)));
}
mutex_lock(&imp->imp_sec_mutex);
newsec = sptlrpc_sec_create(imp, svc_ctx, &sf, sp);
if (newsec) {
sptlrpc_import_sec_install(imp, newsec);
} else {
CERROR("import %s->%s: failed to create new sec\n",
imp->imp_obd->obd_name,
obd_uuid2str(&conn->c_remote_uuid));
rc = -EPERM;
}
mutex_unlock(&imp->imp_sec_mutex);
out:
sptlrpc_sec_put(sec);
return rc;
}
void sptlrpc_import_sec_put(struct obd_import *imp)
{
if (imp->imp_sec) {
sptlrpc_sec_kill(imp->imp_sec);
sptlrpc_sec_put(imp->imp_sec);
imp->imp_sec = NULL;
}
}
static void import_flush_ctx_common(struct obd_import *imp,
uid_t uid, int grace, int force)
{
struct ptlrpc_sec *sec;
if (imp == NULL)
return;
sec = sptlrpc_import_sec_ref(imp);
if (sec == NULL)
return;
sec_cop_flush_ctx_cache(sec, uid, grace, force);
sptlrpc_sec_put(sec);
}
void sptlrpc_import_flush_root_ctx(struct obd_import *imp)
{
/* it's important to use grace mode, see explain in
* sptlrpc_req_refresh_ctx() */
import_flush_ctx_common(imp, 0, 1, 1);
}
void sptlrpc_import_flush_my_ctx(struct obd_import *imp)
{
import_flush_ctx_common(imp, from_kuid(&init_user_ns, current_uid()),
1, 1);
}
EXPORT_SYMBOL(sptlrpc_import_flush_my_ctx);
void sptlrpc_import_flush_all_ctx(struct obd_import *imp)
{
import_flush_ctx_common(imp, -1, 1, 1);
}
EXPORT_SYMBOL(sptlrpc_import_flush_all_ctx);
/**
* Used by ptlrpc client to allocate request buffer of \a req. Upon return
* successfully, req->rq_reqmsg points to a buffer with size \a msgsize.
*/
int sptlrpc_cli_alloc_reqbuf(struct ptlrpc_request *req, int msgsize)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
struct ptlrpc_sec_policy *policy;
int rc;
LASSERT(ctx);
LASSERT(ctx->cc_sec);
LASSERT(ctx->cc_sec->ps_policy);
LASSERT(req->rq_reqmsg == NULL);
LASSERT_ATOMIC_POS(&ctx->cc_refcount);
policy = ctx->cc_sec->ps_policy;
rc = policy->sp_cops->alloc_reqbuf(ctx->cc_sec, req, msgsize);
if (!rc) {
LASSERT(req->rq_reqmsg);
LASSERT(req->rq_reqbuf || req->rq_clrbuf);
/* zeroing preallocated buffer */
if (req->rq_pool)
memset(req->rq_reqmsg, 0, msgsize);
}
return rc;
}
/**
* Used by ptlrpc client to free request buffer of \a req. After this
* req->rq_reqmsg is set to NULL and should not be accessed anymore.
*/
void sptlrpc_cli_free_reqbuf(struct ptlrpc_request *req)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
struct ptlrpc_sec_policy *policy;
LASSERT(ctx);
LASSERT(ctx->cc_sec);
LASSERT(ctx->cc_sec->ps_policy);
LASSERT_ATOMIC_POS(&ctx->cc_refcount);
if (req->rq_reqbuf == NULL && req->rq_clrbuf == NULL)
return;
policy = ctx->cc_sec->ps_policy;
policy->sp_cops->free_reqbuf(ctx->cc_sec, req);
req->rq_reqmsg = NULL;
}
/*
* NOTE caller must guarantee the buffer size is enough for the enlargement
*/
void _sptlrpc_enlarge_msg_inplace(struct lustre_msg *msg,
int segment, int newsize)
{
void *src, *dst;
int oldsize, oldmsg_size, movesize;
LASSERT(segment < msg->lm_bufcount);
LASSERT(msg->lm_buflens[segment] <= newsize);
if (msg->lm_buflens[segment] == newsize)
return;
/* nothing to do if we are enlarging the last segment */
if (segment == msg->lm_bufcount - 1) {
msg->lm_buflens[segment] = newsize;
return;
}
oldsize = msg->lm_buflens[segment];
src = lustre_msg_buf(msg, segment + 1, 0);
msg->lm_buflens[segment] = newsize;
dst = lustre_msg_buf(msg, segment + 1, 0);
msg->lm_buflens[segment] = oldsize;
/* move from segment + 1 to end segment */
LASSERT(msg->lm_magic == LUSTRE_MSG_MAGIC_V2);
oldmsg_size = lustre_msg_size_v2(msg->lm_bufcount, msg->lm_buflens);
movesize = oldmsg_size - ((unsigned long) src - (unsigned long) msg);
LASSERT(movesize >= 0);
if (movesize)
memmove(dst, src, movesize);
/* note we don't clear the ares where old data live, not secret */
/* finally set new segment size */
msg->lm_buflens[segment] = newsize;
}
EXPORT_SYMBOL(_sptlrpc_enlarge_msg_inplace);
/**
* Used by ptlrpc client to enlarge the \a segment of request message pointed
* by req->rq_reqmsg to size \a newsize, all previously filled-in data will be
* preserved after the enlargement. this must be called after original request
* buffer being allocated.
*
* \note after this be called, rq_reqmsg and rq_reqlen might have been changed,
* so caller should refresh its local pointers if needed.
*/
int sptlrpc_cli_enlarge_reqbuf(struct ptlrpc_request *req,
int segment, int newsize)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
struct ptlrpc_sec_cops *cops;
struct lustre_msg *msg = req->rq_reqmsg;
LASSERT(ctx);
LASSERT(msg);
LASSERT(msg->lm_bufcount > segment);
LASSERT(msg->lm_buflens[segment] <= newsize);
if (msg->lm_buflens[segment] == newsize)
return 0;
cops = ctx->cc_sec->ps_policy->sp_cops;
LASSERT(cops->enlarge_reqbuf);
return cops->enlarge_reqbuf(ctx->cc_sec, req, segment, newsize);
}
EXPORT_SYMBOL(sptlrpc_cli_enlarge_reqbuf);
/**
* Used by ptlrpc client to allocate reply buffer of \a req.
*
* \note After this, req->rq_repmsg is still not accessible.
*/
int sptlrpc_cli_alloc_repbuf(struct ptlrpc_request *req, int msgsize)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
struct ptlrpc_sec_policy *policy;
LASSERT(ctx);
LASSERT(ctx->cc_sec);
LASSERT(ctx->cc_sec->ps_policy);
if (req->rq_repbuf)
return 0;
policy = ctx->cc_sec->ps_policy;
return policy->sp_cops->alloc_repbuf(ctx->cc_sec, req, msgsize);
}
/**
* Used by ptlrpc client to free reply buffer of \a req. After this
* req->rq_repmsg is set to NULL and should not be accessed anymore.
*/
void sptlrpc_cli_free_repbuf(struct ptlrpc_request *req)
{
struct ptlrpc_cli_ctx *ctx = req->rq_cli_ctx;
struct ptlrpc_sec_policy *policy;
LASSERT(ctx);
LASSERT(ctx->cc_sec);
LASSERT(ctx->cc_sec->ps_policy);
LASSERT_ATOMIC_POS(&ctx->cc_refcount);
if (req->rq_repbuf == NULL)
return;
LASSERT(req->rq_repbuf_len);
policy = ctx->cc_sec->ps_policy;
policy->sp_cops->free_repbuf(ctx->cc_sec, req);
req->rq_repmsg = NULL;
}
int sptlrpc_cli_install_rvs_ctx(struct obd_import *imp,
struct ptlrpc_cli_ctx *ctx)
{
struct ptlrpc_sec_policy *policy = ctx->cc_sec->ps_policy;
if (!policy->sp_cops->install_rctx)
return 0;
return policy->sp_cops->install_rctx(imp, ctx->cc_sec, ctx);
}
int sptlrpc_svc_install_rvs_ctx(struct obd_import *imp,
struct ptlrpc_svc_ctx *ctx)
{
struct ptlrpc_sec_policy *policy = ctx->sc_policy;
if (!policy->sp_sops->install_rctx)
return 0;
return policy->sp_sops->install_rctx(imp, ctx);
}
/****************************************
* server side security *
****************************************/
static int flavor_allowed(struct sptlrpc_flavor *exp,
struct ptlrpc_request *req)
{
struct sptlrpc_flavor *flvr = &req->rq_flvr;
if (exp->sf_rpc == SPTLRPC_FLVR_ANY || exp->sf_rpc == flvr->sf_rpc)
return 1;
if ((req->rq_ctx_init || req->rq_ctx_fini) &&
SPTLRPC_FLVR_POLICY(exp->sf_rpc) ==
SPTLRPC_FLVR_POLICY(flvr->sf_rpc) &&
SPTLRPC_FLVR_MECH(exp->sf_rpc) == SPTLRPC_FLVR_MECH(flvr->sf_rpc))
return 1;
return 0;
}
#define EXP_FLVR_UPDATE_EXPIRE (OBD_TIMEOUT_DEFAULT + 10)
/**
* Given an export \a exp, check whether the flavor of incoming \a req
* is allowed by the export \a exp. Main logic is about taking care of
* changing configurations. Return 0 means success.
*/
int sptlrpc_target_export_check(struct obd_export *exp,
struct ptlrpc_request *req)
{
struct sptlrpc_flavor flavor;
if (exp == NULL)
return 0;
/* client side export has no imp_reverse, skip
* FIXME maybe we should check flavor this as well??? */
if (exp->exp_imp_reverse == NULL)
return 0;
/* don't care about ctx fini rpc */
if (req->rq_ctx_fini)
return 0;
spin_lock(&exp->exp_lock);
/* if flavor just changed (exp->exp_flvr_changed != 0), we wait for
* the first req with the new flavor, then treat it as current flavor,
* adapt reverse sec according to it.
* note the first rpc with new flavor might not be with root ctx, in
* which case delay the sec_adapt by leaving exp_flvr_adapt == 1. */
if (unlikely(exp->exp_flvr_changed) &&
flavor_allowed(&exp->exp_flvr_old[1], req)) {
/* make the new flavor as "current", and old ones as
* about-to-expire */
CDEBUG(D_SEC, "exp %p: just changed: %x->%x\n", exp,
exp->exp_flvr.sf_rpc, exp->exp_flvr_old[1].sf_rpc);
flavor = exp->exp_flvr_old[1];
exp->exp_flvr_old[1] = exp->exp_flvr_old[0];
exp->exp_flvr_expire[1] = exp->exp_flvr_expire[0];
exp->exp_flvr_old[0] = exp->exp_flvr;
exp->exp_flvr_expire[0] = get_seconds() +
EXP_FLVR_UPDATE_EXPIRE;
exp->exp_flvr = flavor;
/* flavor change finished */
exp->exp_flvr_changed = 0;
LASSERT(exp->exp_flvr_adapt == 1);
/* if it's gss, we only interested in root ctx init */
if (req->rq_auth_gss &&
!(req->rq_ctx_init &&
(req->rq_auth_usr_root || req->rq_auth_usr_mdt ||
req->rq_auth_usr_ost))) {
spin_unlock(&exp->exp_lock);
CDEBUG(D_SEC, "is good but not root(%d:%d:%d:%d:%d)\n",
req->rq_auth_gss, req->rq_ctx_init,
req->rq_auth_usr_root, req->rq_auth_usr_mdt,
req->rq_auth_usr_ost);
return 0;
}
exp->exp_flvr_adapt = 0;
spin_unlock(&exp->exp_lock);
return sptlrpc_import_sec_adapt(exp->exp_imp_reverse,
req->rq_svc_ctx, &flavor);
}
/* if it equals to the current flavor, we accept it, but need to
* dealing with reverse sec/ctx */
if (likely(flavor_allowed(&exp->exp_flvr, req))) {
/* most cases should return here, we only interested in
* gss root ctx init */
if (!req->rq_auth_gss || !req->rq_ctx_init ||
(!req->rq_auth_usr_root && !req->rq_auth_usr_mdt &&
!req->rq_auth_usr_ost)) {
spin_unlock(&exp->exp_lock);
return 0;
}
/* if flavor just changed, we should not proceed, just leave
* it and current flavor will be discovered and replaced
* shortly, and let _this_ rpc pass through */
if (exp->exp_flvr_changed) {
LASSERT(exp->exp_flvr_adapt);
spin_unlock(&exp->exp_lock);
return 0;
}
if (exp->exp_flvr_adapt) {
exp->exp_flvr_adapt = 0;
CDEBUG(D_SEC, "exp %p (%x|%x|%x): do delayed adapt\n",
exp, exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[0].sf_rpc,
exp->exp_flvr_old[1].sf_rpc);
flavor = exp->exp_flvr;
spin_unlock(&exp->exp_lock);
return sptlrpc_import_sec_adapt(exp->exp_imp_reverse,
req->rq_svc_ctx,
&flavor);
} else {
CDEBUG(D_SEC, "exp %p (%x|%x|%x): is current flavor, install rvs ctx\n",
exp, exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[0].sf_rpc,
exp->exp_flvr_old[1].sf_rpc);
spin_unlock(&exp->exp_lock);
return sptlrpc_svc_install_rvs_ctx(exp->exp_imp_reverse,
req->rq_svc_ctx);
}
}
if (exp->exp_flvr_expire[0]) {
if (exp->exp_flvr_expire[0] >= get_seconds()) {
if (flavor_allowed(&exp->exp_flvr_old[0], req)) {
CDEBUG(D_SEC, "exp %p (%x|%x|%x): match the middle one (" CFS_DURATION_T ")\n", exp,
exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[0].sf_rpc,
exp->exp_flvr_old[1].sf_rpc,
exp->exp_flvr_expire[0] -
get_seconds());
spin_unlock(&exp->exp_lock);
return 0;
}
} else {
CDEBUG(D_SEC, "mark middle expired\n");
exp->exp_flvr_expire[0] = 0;
}
CDEBUG(D_SEC, "exp %p (%x|%x|%x): %x not match middle\n", exp,
exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[0].sf_rpc, exp->exp_flvr_old[1].sf_rpc,
req->rq_flvr.sf_rpc);
}
/* now it doesn't match the current flavor, the only chance we can
* accept it is match the old flavors which is not expired. */
if (exp->exp_flvr_changed == 0 && exp->exp_flvr_expire[1]) {
if (exp->exp_flvr_expire[1] >= get_seconds()) {
if (flavor_allowed(&exp->exp_flvr_old[1], req)) {
CDEBUG(D_SEC, "exp %p (%x|%x|%x): match the oldest one (" CFS_DURATION_T ")\n",
exp,
exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[0].sf_rpc,
exp->exp_flvr_old[1].sf_rpc,
exp->exp_flvr_expire[1] -
get_seconds());
spin_unlock(&exp->exp_lock);
return 0;
}
} else {
CDEBUG(D_SEC, "mark oldest expired\n");
exp->exp_flvr_expire[1] = 0;
}
CDEBUG(D_SEC, "exp %p (%x|%x|%x): %x not match found\n",
exp, exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[0].sf_rpc, exp->exp_flvr_old[1].sf_rpc,
req->rq_flvr.sf_rpc);
} else {
CDEBUG(D_SEC, "exp %p (%x|%x|%x): skip the last one\n",
exp, exp->exp_flvr.sf_rpc, exp->exp_flvr_old[0].sf_rpc,
exp->exp_flvr_old[1].sf_rpc);
}
spin_unlock(&exp->exp_lock);
CWARN("exp %p(%s): req %p (%u|%u|%u|%u|%u|%u) with unauthorized flavor %x, expect %x|%x(%+ld)|%x(%+ld)\n",
exp, exp->exp_obd->obd_name,
req, req->rq_auth_gss, req->rq_ctx_init, req->rq_ctx_fini,
req->rq_auth_usr_root, req->rq_auth_usr_mdt, req->rq_auth_usr_ost,
req->rq_flvr.sf_rpc,
exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[0].sf_rpc,
exp->exp_flvr_expire[0] ?
(unsigned long) (exp->exp_flvr_expire[0] -
get_seconds()) : 0,
exp->exp_flvr_old[1].sf_rpc,
exp->exp_flvr_expire[1] ?
(unsigned long) (exp->exp_flvr_expire[1] -
get_seconds()) : 0);
return -EACCES;
}
EXPORT_SYMBOL(sptlrpc_target_export_check);
void sptlrpc_target_update_exp_flavor(struct obd_device *obd,
struct sptlrpc_rule_set *rset)
{
struct obd_export *exp;
struct sptlrpc_flavor new_flvr;
LASSERT(obd);
spin_lock(&obd->obd_dev_lock);
list_for_each_entry(exp, &obd->obd_exports, exp_obd_chain) {
if (exp->exp_connection == NULL)
continue;
/* note if this export had just been updated flavor
* (exp_flvr_changed == 1), this will override the
* previous one. */
spin_lock(&exp->exp_lock);
sptlrpc_target_choose_flavor(rset, exp->exp_sp_peer,
exp->exp_connection->c_peer.nid,
&new_flvr);
if (exp->exp_flvr_changed ||
!flavor_equal(&new_flvr, &exp->exp_flvr)) {
exp->exp_flvr_old[1] = new_flvr;
exp->exp_flvr_expire[1] = 0;
exp->exp_flvr_changed = 1;
exp->exp_flvr_adapt = 1;
CDEBUG(D_SEC, "exp %p (%s): updated flavor %x->%x\n",
exp, sptlrpc_part2name(exp->exp_sp_peer),
exp->exp_flvr.sf_rpc,
exp->exp_flvr_old[1].sf_rpc);
}
spin_unlock(&exp->exp_lock);
}
spin_unlock(&obd->obd_dev_lock);
}
EXPORT_SYMBOL(sptlrpc_target_update_exp_flavor);
static int sptlrpc_svc_check_from(struct ptlrpc_request *req, int svc_rc)
{
/* peer's claim is unreliable unless gss is being used */
if (!req->rq_auth_gss || svc_rc == SECSVC_DROP)
return svc_rc;
switch (req->rq_sp_from) {
case LUSTRE_SP_CLI:
if (req->rq_auth_usr_mdt || req->rq_auth_usr_ost) {
DEBUG_REQ(D_ERROR, req, "faked source CLI");
svc_rc = SECSVC_DROP;
}
break;
case LUSTRE_SP_MDT:
if (!req->rq_auth_usr_mdt) {
DEBUG_REQ(D_ERROR, req, "faked source MDT");
svc_rc = SECSVC_DROP;
}
break;
case LUSTRE_SP_OST:
if (!req->rq_auth_usr_ost) {
DEBUG_REQ(D_ERROR, req, "faked source OST");
svc_rc = SECSVC_DROP;
}
break;
case LUSTRE_SP_MGS:
case LUSTRE_SP_MGC:
if (!req->rq_auth_usr_root && !req->rq_auth_usr_mdt &&
!req->rq_auth_usr_ost) {
DEBUG_REQ(D_ERROR, req, "faked source MGC/MGS");
svc_rc = SECSVC_DROP;
}
break;
case LUSTRE_SP_ANY:
default:
DEBUG_REQ(D_ERROR, req, "invalid source %u", req->rq_sp_from);
svc_rc = SECSVC_DROP;
}
return svc_rc;
}
/**
* Used by ptlrpc server, to perform transformation upon request message of
* incoming \a req. This must be the first thing to do with a incoming
* request in ptlrpc layer.
*
* \retval SECSVC_OK success, and req->rq_reqmsg point to request message in
* clear text, size is req->rq_reqlen; also req->rq_svc_ctx is set.
* \retval SECSVC_COMPLETE success, the request has been fully processed, and
* reply message has been prepared.
* \retval SECSVC_DROP failed, this request should be dropped.
*/
int sptlrpc_svc_unwrap_request(struct ptlrpc_request *req)
{
struct ptlrpc_sec_policy *policy;
struct lustre_msg *msg = req->rq_reqbuf;
int rc;
LASSERT(msg);
LASSERT(req->rq_reqmsg == NULL);
LASSERT(req->rq_repmsg == NULL);
LASSERT(req->rq_svc_ctx == NULL);
req->rq_req_swab_mask = 0;
rc = __lustre_unpack_msg(msg, req->rq_reqdata_len);
switch (rc) {
case 1:
lustre_set_req_swabbed(req, MSG_PTLRPC_HEADER_OFF);
case 0:
break;
default:
CERROR("error unpacking request from %s x%llu\n",
libcfs_id2str(req->rq_peer), req->rq_xid);
return SECSVC_DROP;
}
req->rq_flvr.sf_rpc = WIRE_FLVR(msg->lm_secflvr);
req->rq_sp_from = LUSTRE_SP_ANY;
req->rq_auth_uid = -1;
req->rq_auth_mapped_uid = -1;
policy = sptlrpc_wireflavor2policy(req->rq_flvr.sf_rpc);
if (!policy) {
CERROR("unsupported rpc flavor %x\n", req->rq_flvr.sf_rpc);
return SECSVC_DROP;
}
LASSERT(policy->sp_sops->accept);
rc = policy->sp_sops->accept(req);
sptlrpc_policy_put(policy);
LASSERT(req->rq_reqmsg || rc != SECSVC_OK);
LASSERT(req->rq_svc_ctx || rc == SECSVC_DROP);
/*
* if it's not null flavor (which means embedded packing msg),
* reset the swab mask for the coming inner msg unpacking.
*/
if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL)
req->rq_req_swab_mask = 0;
/* sanity check for the request source */
rc = sptlrpc_svc_check_from(req, rc);
return rc;
}
/**
* Used by ptlrpc server, to allocate reply buffer for \a req. If succeed,
* req->rq_reply_state is set, and req->rq_reply_state->rs_msg point to
* a buffer of \a msglen size.
*/
int sptlrpc_svc_alloc_rs(struct ptlrpc_request *req, int msglen)
{
struct ptlrpc_sec_policy *policy;
struct ptlrpc_reply_state *rs;
int rc;
LASSERT(req->rq_svc_ctx);
LASSERT(req->rq_svc_ctx->sc_policy);
policy = req->rq_svc_ctx->sc_policy;
LASSERT(policy->sp_sops->alloc_rs);
rc = policy->sp_sops->alloc_rs(req, msglen);
if (unlikely(rc == -ENOMEM)) {
struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
if (svcpt->scp_service->srv_max_reply_size <
msglen + sizeof(struct ptlrpc_reply_state)) {
/* Just return failure if the size is too big */
CERROR("size of message is too big (%zd), %d allowed",
msglen + sizeof(struct ptlrpc_reply_state),
svcpt->scp_service->srv_max_reply_size);
return -ENOMEM;
}
/* failed alloc, try emergency pool */
rs = lustre_get_emerg_rs(svcpt);
if (rs == NULL)
return -ENOMEM;
req->rq_reply_state = rs;
rc = policy->sp_sops->alloc_rs(req, msglen);
if (rc) {
lustre_put_emerg_rs(rs);
req->rq_reply_state = NULL;
}
}
LASSERT(rc != 0 ||
(req->rq_reply_state && req->rq_reply_state->rs_msg));
return rc;
}
/**
* Used by ptlrpc server, to perform transformation upon reply message.
*
* \post req->rq_reply_off is set to appropriate server-controlled reply offset.
* \post req->rq_repmsg and req->rq_reply_state->rs_msg becomes inaccessible.
*/
int sptlrpc_svc_wrap_reply(struct ptlrpc_request *req)
{
struct ptlrpc_sec_policy *policy;
int rc;
LASSERT(req->rq_svc_ctx);
LASSERT(req->rq_svc_ctx->sc_policy);
policy = req->rq_svc_ctx->sc_policy;
LASSERT(policy->sp_sops->authorize);
rc = policy->sp_sops->authorize(req);
LASSERT(rc || req->rq_reply_state->rs_repdata_len);
return rc;
}
/**
* Used by ptlrpc server, to free reply_state.
*/
void sptlrpc_svc_free_rs(struct ptlrpc_reply_state *rs)
{
struct ptlrpc_sec_policy *policy;
unsigned int prealloc;
LASSERT(rs->rs_svc_ctx);
LASSERT(rs->rs_svc_ctx->sc_policy);
policy = rs->rs_svc_ctx->sc_policy;
LASSERT(policy->sp_sops->free_rs);
prealloc = rs->rs_prealloc;
policy->sp_sops->free_rs(rs);
if (prealloc)
lustre_put_emerg_rs(rs);
}
void sptlrpc_svc_ctx_addref(struct ptlrpc_request *req)
{
struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
if (ctx != NULL)
atomic_inc(&ctx->sc_refcount);
}
void sptlrpc_svc_ctx_decref(struct ptlrpc_request *req)
{
struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
if (ctx == NULL)
return;
LASSERT_ATOMIC_POS(&ctx->sc_refcount);
if (atomic_dec_and_test(&ctx->sc_refcount)) {
if (ctx->sc_policy->sp_sops->free_ctx)
ctx->sc_policy->sp_sops->free_ctx(ctx);
}
req->rq_svc_ctx = NULL;
}
void sptlrpc_svc_ctx_invalidate(struct ptlrpc_request *req)
{
struct ptlrpc_svc_ctx *ctx = req->rq_svc_ctx;
if (ctx == NULL)
return;
LASSERT_ATOMIC_POS(&ctx->sc_refcount);
if (ctx->sc_policy->sp_sops->invalidate_ctx)
ctx->sc_policy->sp_sops->invalidate_ctx(ctx);
}
EXPORT_SYMBOL(sptlrpc_svc_ctx_invalidate);
/****************************************
* bulk security *
****************************************/
/**
* Perform transformation upon bulk data pointed by \a desc. This is called
* before transforming the request message.
*/
int sptlrpc_cli_wrap_bulk(struct ptlrpc_request *req,
struct ptlrpc_bulk_desc *desc)
{
struct ptlrpc_cli_ctx *ctx;
LASSERT(req->rq_bulk_read || req->rq_bulk_write);
if (!req->rq_pack_bulk)
return 0;
ctx = req->rq_cli_ctx;
if (ctx->cc_ops->wrap_bulk)
return ctx->cc_ops->wrap_bulk(ctx, req, desc);
return 0;
}
EXPORT_SYMBOL(sptlrpc_cli_wrap_bulk);
/**
* This is called after unwrap the reply message.
* return nob of actual plain text size received, or error code.
*/
int sptlrpc_cli_unwrap_bulk_read(struct ptlrpc_request *req,
struct ptlrpc_bulk_desc *desc,
int nob)
{
struct ptlrpc_cli_ctx *ctx;
int rc;
LASSERT(req->rq_bulk_read && !req->rq_bulk_write);
if (!req->rq_pack_bulk)
return desc->bd_nob_transferred;
ctx = req->rq_cli_ctx;
if (ctx->cc_ops->unwrap_bulk) {
rc = ctx->cc_ops->unwrap_bulk(ctx, req, desc);
if (rc < 0)
return rc;
}
return desc->bd_nob_transferred;
}
EXPORT_SYMBOL(sptlrpc_cli_unwrap_bulk_read);
/**
* This is called after unwrap the reply message.
* return 0 for success or error code.
*/
int sptlrpc_cli_unwrap_bulk_write(struct ptlrpc_request *req,
struct ptlrpc_bulk_desc *desc)
{
struct ptlrpc_cli_ctx *ctx;
int rc;
LASSERT(!req->rq_bulk_read && req->rq_bulk_write);
if (!req->rq_pack_bulk)
return 0;
ctx = req->rq_cli_ctx;
if (ctx->cc_ops->unwrap_bulk) {
rc = ctx->cc_ops->unwrap_bulk(ctx, req, desc);
if (rc < 0)
return rc;
}
/*
* if everything is going right, nob should equals to nob_transferred.
* in case of privacy mode, nob_transferred needs to be adjusted.
*/
if (desc->bd_nob != desc->bd_nob_transferred) {
CERROR("nob %d doesn't match transferred nob %d",
desc->bd_nob, desc->bd_nob_transferred);
return -EPROTO;
}
return 0;
}
EXPORT_SYMBOL(sptlrpc_cli_unwrap_bulk_write);
/****************************************
* user descriptor helpers *
****************************************/
int sptlrpc_current_user_desc_size(void)
{
int ngroups;
ngroups = current_ngroups;
if (ngroups > LUSTRE_MAX_GROUPS)
ngroups = LUSTRE_MAX_GROUPS;
return sptlrpc_user_desc_size(ngroups);
}
EXPORT_SYMBOL(sptlrpc_current_user_desc_size);
int sptlrpc_pack_user_desc(struct lustre_msg *msg, int offset)
{
struct ptlrpc_user_desc *pud;
pud = lustre_msg_buf(msg, offset, 0);
pud->pud_uid = from_kuid(&init_user_ns, current_uid());
pud->pud_gid = from_kgid(&init_user_ns, current_gid());
pud->pud_fsuid = from_kuid(&init_user_ns, current_fsuid());
pud->pud_fsgid = from_kgid(&init_user_ns, current_fsgid());
pud->pud_cap = cfs_curproc_cap_pack();
pud->pud_ngroups = (msg->lm_buflens[offset] - sizeof(*pud)) / 4;
task_lock(current);
if (pud->pud_ngroups > current_ngroups)
pud->pud_ngroups = current_ngroups;
memcpy(pud->pud_groups, current_cred()->group_info->blocks[0],
pud->pud_ngroups * sizeof(__u32));
task_unlock(current);
return 0;
}
EXPORT_SYMBOL(sptlrpc_pack_user_desc);
int sptlrpc_unpack_user_desc(struct lustre_msg *msg, int offset, int swabbed)
{
struct ptlrpc_user_desc *pud;
int i;
pud = lustre_msg_buf(msg, offset, sizeof(*pud));
if (!pud)
return -EINVAL;
if (swabbed) {
__swab32s(&pud->pud_uid);
__swab32s(&pud->pud_gid);
__swab32s(&pud->pud_fsuid);
__swab32s(&pud->pud_fsgid);
__swab32s(&pud->pud_cap);
__swab32s(&pud->pud_ngroups);
}
if (pud->pud_ngroups > LUSTRE_MAX_GROUPS) {
CERROR("%u groups is too large\n", pud->pud_ngroups);
return -EINVAL;
}
if (sizeof(*pud) + pud->pud_ngroups * sizeof(__u32) >
msg->lm_buflens[offset]) {
CERROR("%u groups are claimed but bufsize only %u\n",
pud->pud_ngroups, msg->lm_buflens[offset]);
return -EINVAL;
}
if (swabbed) {
for (i = 0; i < pud->pud_ngroups; i++)
__swab32s(&pud->pud_groups[i]);
}
return 0;
}
EXPORT_SYMBOL(sptlrpc_unpack_user_desc);
/****************************************
* misc helpers *
****************************************/
const char *sec2target_str(struct ptlrpc_sec *sec)
{
if (!sec || !sec->ps_import || !sec->ps_import->imp_obd)
return "*";
if (sec_is_reverse(sec))
return "c";
return obd_uuid2str(&sec->ps_import->imp_obd->u.cli.cl_target_uuid);
}
EXPORT_SYMBOL(sec2target_str);
/*
* return true if the bulk data is protected
*/
int sptlrpc_flavor_has_bulk(struct sptlrpc_flavor *flvr)
{
switch (SPTLRPC_FLVR_BULK_SVC(flvr->sf_rpc)) {
case SPTLRPC_BULK_SVC_INTG:
case SPTLRPC_BULK_SVC_PRIV:
return 1;
default:
return 0;
}
}
EXPORT_SYMBOL(sptlrpc_flavor_has_bulk);
/****************************************
* crypto API helper/alloc blkciper *
****************************************/
/****************************************
* initialize/finalize *
****************************************/
int sptlrpc_init(void)
{
int rc;
rwlock_init(&policy_lock);
rc = sptlrpc_gc_init();
if (rc)
goto out;
rc = sptlrpc_conf_init();
if (rc)
goto out_gc;
rc = sptlrpc_enc_pool_init();
if (rc)
goto out_conf;
rc = sptlrpc_null_init();
if (rc)
goto out_pool;
rc = sptlrpc_plain_init();
if (rc)
goto out_null;
rc = sptlrpc_lproc_init();
if (rc)
goto out_plain;
return 0;
out_plain:
sptlrpc_plain_fini();
out_null:
sptlrpc_null_fini();
out_pool:
sptlrpc_enc_pool_fini();
out_conf:
sptlrpc_conf_fini();
out_gc:
sptlrpc_gc_fini();
out:
return rc;
}
void sptlrpc_fini(void)
{
sptlrpc_lproc_fini();
sptlrpc_plain_fini();
sptlrpc_null_fini();
sptlrpc_enc_pool_fini();
sptlrpc_conf_fini();
sptlrpc_gc_fini();
}
| gpl-2.0 |
gqk289/linux | drivers/staging/lustre/lustre/lov/lov_pack.c | 392 | 14531 | /*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* as published by the Free Software Foundation.
*
* This 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 version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see
* http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* GPL HEADER END
*/
/*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* Copyright (c) 2011, 2012, Intel Corporation.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*
* lustre/lov/lov_pack.c
*
* (Un)packing of OST/MDS requests
*
* Author: Andreas Dilger <adilger@clusterfs.com>
*/
#define DEBUG_SUBSYSTEM S_LOV
#include "../include/lustre_net.h"
#include "../include/obd.h"
#include "../include/obd_class.h"
#include "../include/obd_support.h"
#include "../include/lustre/lustre_user.h"
#include "lov_internal.h"
void lov_dump_lmm_common(int level, void *lmmp)
{
struct lov_mds_md *lmm = lmmp;
struct ost_id oi;
lmm_oi_le_to_cpu(&oi, &lmm->lmm_oi);
CDEBUG(level, "objid "DOSTID", magic 0x%08x, pattern %#x\n",
POSTID(&oi), le32_to_cpu(lmm->lmm_magic),
le32_to_cpu(lmm->lmm_pattern));
CDEBUG(level, "stripe_size %u, stripe_count %u, layout_gen %u\n",
le32_to_cpu(lmm->lmm_stripe_size),
le16_to_cpu(lmm->lmm_stripe_count),
le16_to_cpu(lmm->lmm_layout_gen));
}
static void lov_dump_lmm_objects(int level, struct lov_ost_data *lod,
int stripe_count)
{
int i;
if (stripe_count > LOV_V1_INSANE_STRIPE_COUNT) {
CDEBUG(level, "bad stripe_count %u > max_stripe_count %u\n",
stripe_count, LOV_V1_INSANE_STRIPE_COUNT);
return;
}
for (i = 0; i < stripe_count; ++i, ++lod) {
struct ost_id oi;
ostid_le_to_cpu(&lod->l_ost_oi, &oi);
CDEBUG(level, "stripe %u idx %u subobj "DOSTID"\n", i,
le32_to_cpu(lod->l_ost_idx), POSTID(&oi));
}
}
void lov_dump_lmm_v1(int level, struct lov_mds_md_v1 *lmm)
{
lov_dump_lmm_common(level, lmm);
lov_dump_lmm_objects(level, lmm->lmm_objects,
le16_to_cpu(lmm->lmm_stripe_count));
}
void lov_dump_lmm_v3(int level, struct lov_mds_md_v3 *lmm)
{
lov_dump_lmm_common(level, lmm);
CDEBUG(level, "pool_name "LOV_POOLNAMEF"\n", lmm->lmm_pool_name);
lov_dump_lmm_objects(level, lmm->lmm_objects,
le16_to_cpu(lmm->lmm_stripe_count));
}
void lov_dump_lmm(int level, void *lmm)
{
int magic;
magic = le32_to_cpu(((struct lov_mds_md *)lmm)->lmm_magic);
switch (magic) {
case LOV_MAGIC_V1:
lov_dump_lmm_v1(level, (struct lov_mds_md_v1 *)lmm);
break;
case LOV_MAGIC_V3:
lov_dump_lmm_v3(level, (struct lov_mds_md_v3 *)lmm);
break;
default:
CDEBUG(level, "unrecognized lmm_magic %x, assuming %x\n",
magic, LOV_MAGIC_V1);
lov_dump_lmm_common(level, lmm);
break;
}
}
/* Pack LOV object metadata for disk storage. It is packed in LE byte
* order and is opaque to the networking layer.
*
* XXX In the future, this will be enhanced to get the EA size from the
* underlying OSC device(s) to get their EA sizes so we can stack
* LOVs properly. For now lov_mds_md_size() just assumes one u64
* per stripe.
*/
int lov_packmd(struct obd_export *exp, struct lov_mds_md **lmmp,
struct lov_stripe_md *lsm)
{
struct obd_device *obd = class_exp2obd(exp);
struct lov_obd *lov = &obd->u.lov;
struct lov_mds_md_v1 *lmmv1;
struct lov_mds_md_v3 *lmmv3;
__u16 stripe_count;
struct lov_ost_data_v1 *lmm_objects;
int lmm_size, lmm_magic;
int i;
int cplen = 0;
if (lsm) {
lmm_magic = lsm->lsm_magic;
} else {
if (lmmp && *lmmp)
lmm_magic = le32_to_cpu((*lmmp)->lmm_magic);
else
/* lsm == NULL and lmmp == NULL */
lmm_magic = LOV_MAGIC;
}
if ((lmm_magic != LOV_MAGIC_V1) &&
(lmm_magic != LOV_MAGIC_V3)) {
CERROR("bad mem LOV MAGIC: 0x%08X != 0x%08X nor 0x%08X\n",
lmm_magic, LOV_MAGIC_V1, LOV_MAGIC_V3);
return -EINVAL;
}
if (lsm) {
/* If we are just sizing the EA, limit the stripe count
* to the actual number of OSTs in this filesystem. */
if (!lmmp) {
stripe_count = lov_get_stripecnt(lov, lmm_magic,
lsm->lsm_stripe_count);
lsm->lsm_stripe_count = stripe_count;
} else if (!lsm_is_released(lsm)) {
stripe_count = lsm->lsm_stripe_count;
} else {
stripe_count = 0;
}
} else {
/* No need to allocate more than maximum supported stripes.
* Anyway, this is pretty inaccurate since ld_tgt_count now
* represents max index and we should rely on the actual number
* of OSTs instead */
stripe_count = lov_mds_md_max_stripe_count(
lov->lov_ocd.ocd_max_easize, lmm_magic);
if (stripe_count > lov->desc.ld_tgt_count)
stripe_count = lov->desc.ld_tgt_count;
}
/* XXX LOV STACKING call into osc for sizes */
lmm_size = lov_mds_md_size(stripe_count, lmm_magic);
if (!lmmp)
return lmm_size;
if (*lmmp && !lsm) {
stripe_count = le16_to_cpu((*lmmp)->lmm_stripe_count);
lmm_size = lov_mds_md_size(stripe_count, lmm_magic);
kvfree(*lmmp);
*lmmp = NULL;
return 0;
}
if (!*lmmp) {
*lmmp = libcfs_kvzalloc(lmm_size, GFP_NOFS);
if (!*lmmp)
return -ENOMEM;
}
CDEBUG(D_INFO, "lov_packmd: LOV_MAGIC 0x%08X, lmm_size = %d \n",
lmm_magic, lmm_size);
lmmv1 = *lmmp;
lmmv3 = (struct lov_mds_md_v3 *)*lmmp;
if (lmm_magic == LOV_MAGIC_V3)
lmmv3->lmm_magic = cpu_to_le32(LOV_MAGIC_V3);
else
lmmv1->lmm_magic = cpu_to_le32(LOV_MAGIC_V1);
if (!lsm)
return lmm_size;
/* lmmv1 and lmmv3 point to the same struct and have the
* same first fields
*/
lmm_oi_cpu_to_le(&lmmv1->lmm_oi, &lsm->lsm_oi);
lmmv1->lmm_stripe_size = cpu_to_le32(lsm->lsm_stripe_size);
lmmv1->lmm_stripe_count = cpu_to_le16(stripe_count);
lmmv1->lmm_pattern = cpu_to_le32(lsm->lsm_pattern);
lmmv1->lmm_layout_gen = cpu_to_le16(lsm->lsm_layout_gen);
if (lsm->lsm_magic == LOV_MAGIC_V3) {
cplen = strlcpy(lmmv3->lmm_pool_name, lsm->lsm_pool_name,
sizeof(lmmv3->lmm_pool_name));
if (cplen >= sizeof(lmmv3->lmm_pool_name))
return -E2BIG;
lmm_objects = lmmv3->lmm_objects;
} else {
lmm_objects = lmmv1->lmm_objects;
}
for (i = 0; i < stripe_count; i++) {
struct lov_oinfo *loi = lsm->lsm_oinfo[i];
/* XXX LOV STACKING call down to osc_packmd() to do packing */
LASSERTF(ostid_id(&loi->loi_oi) != 0, "lmm_oi "DOSTID
" stripe %u/%u idx %u\n", POSTID(&lmmv1->lmm_oi),
i, stripe_count, loi->loi_ost_idx);
ostid_cpu_to_le(&loi->loi_oi, &lmm_objects[i].l_ost_oi);
lmm_objects[i].l_ost_gen = cpu_to_le32(loi->loi_ost_gen);
lmm_objects[i].l_ost_idx = cpu_to_le32(loi->loi_ost_idx);
}
return lmm_size;
}
/* Find the max stripecount we should use */
__u16 lov_get_stripecnt(struct lov_obd *lov, __u32 magic, __u16 stripe_count)
{
__u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
if (!stripe_count)
stripe_count = lov->desc.ld_default_stripe_count;
if (stripe_count > lov->desc.ld_active_tgt_count)
stripe_count = lov->desc.ld_active_tgt_count;
if (!stripe_count)
stripe_count = 1;
/* stripe count is based on whether ldiskfs can handle
* larger EA sizes */
if (lov->lov_ocd.ocd_connect_flags & OBD_CONNECT_MAX_EASIZE &&
lov->lov_ocd.ocd_max_easize)
max_stripes = lov_mds_md_max_stripe_count(
lov->lov_ocd.ocd_max_easize, magic);
if (stripe_count > max_stripes)
stripe_count = max_stripes;
return stripe_count;
}
static int lov_verify_lmm(void *lmm, int lmm_bytes, __u16 *stripe_count)
{
int rc;
if (lsm_op_find(le32_to_cpu(*(__u32 *)lmm)) == NULL) {
char *buffer;
int sz;
CERROR("bad disk LOV MAGIC: 0x%08X; dumping LMM (size=%d):\n",
le32_to_cpu(*(__u32 *)lmm), lmm_bytes);
sz = lmm_bytes * 2 + 1;
buffer = libcfs_kvzalloc(sz, GFP_NOFS);
if (buffer != NULL) {
int i;
for (i = 0; i < lmm_bytes; i++)
sprintf(buffer+2*i, "%.2X", ((char *)lmm)[i]);
buffer[sz - 1] = '\0';
CERROR("%s\n", buffer);
kvfree(buffer);
}
return -EINVAL;
}
rc = lsm_op_find(le32_to_cpu(*(__u32 *)lmm))->lsm_lmm_verify(lmm,
lmm_bytes, stripe_count);
return rc;
}
int lov_alloc_memmd(struct lov_stripe_md **lsmp, __u16 stripe_count,
int pattern, int magic)
{
int i, lsm_size;
CDEBUG(D_INFO, "alloc lsm, stripe_count %d\n", stripe_count);
*lsmp = lsm_alloc_plain(stripe_count, &lsm_size);
if (!*lsmp) {
CERROR("can't allocate lsmp stripe_count %d\n", stripe_count);
return -ENOMEM;
}
atomic_set(&(*lsmp)->lsm_refc, 1);
spin_lock_init(&(*lsmp)->lsm_lock);
(*lsmp)->lsm_magic = magic;
(*lsmp)->lsm_stripe_count = stripe_count;
(*lsmp)->lsm_maxbytes = LUSTRE_STRIPE_MAXBYTES * stripe_count;
(*lsmp)->lsm_pattern = pattern;
(*lsmp)->lsm_pool_name[0] = '\0';
(*lsmp)->lsm_layout_gen = 0;
if (stripe_count > 0)
(*lsmp)->lsm_oinfo[0]->loi_ost_idx = ~0;
for (i = 0; i < stripe_count; i++)
loi_init((*lsmp)->lsm_oinfo[i]);
return lsm_size;
}
int lov_free_memmd(struct lov_stripe_md **lsmp)
{
struct lov_stripe_md *lsm = *lsmp;
int refc;
*lsmp = NULL;
LASSERT(atomic_read(&lsm->lsm_refc) > 0);
refc = atomic_dec_return(&lsm->lsm_refc);
if (refc == 0) {
LASSERT(lsm_op_find(lsm->lsm_magic) != NULL);
lsm_op_find(lsm->lsm_magic)->lsm_free(lsm);
}
return refc;
}
/* Unpack LOV object metadata from disk storage. It is packed in LE byte
* order and is opaque to the networking layer.
*/
int lov_unpackmd(struct obd_export *exp, struct lov_stripe_md **lsmp,
struct lov_mds_md *lmm, int lmm_bytes)
{
struct obd_device *obd = class_exp2obd(exp);
struct lov_obd *lov = &obd->u.lov;
int rc = 0, lsm_size;
__u16 stripe_count;
__u32 magic;
__u32 pattern;
/* If passed an MDS struct use values from there, otherwise defaults */
if (lmm) {
rc = lov_verify_lmm(lmm, lmm_bytes, &stripe_count);
if (rc)
return rc;
magic = le32_to_cpu(lmm->lmm_magic);
pattern = le32_to_cpu(lmm->lmm_pattern);
} else {
magic = LOV_MAGIC;
stripe_count = lov_get_stripecnt(lov, magic, 0);
pattern = LOV_PATTERN_RAID0;
}
/* If we aren't passed an lsmp struct, we just want the size */
if (!lsmp) {
/* XXX LOV STACKING call into osc for sizes */
LBUG();
return lov_stripe_md_size(stripe_count);
}
/* If we are passed an allocated struct but nothing to unpack, free */
if (*lsmp && !lmm) {
lov_free_memmd(lsmp);
return 0;
}
lsm_size = lov_alloc_memmd(lsmp, stripe_count, pattern, magic);
if (lsm_size < 0)
return lsm_size;
/* If we are passed a pointer but nothing to unpack, we only alloc */
if (!lmm)
return lsm_size;
LASSERT(lsm_op_find(magic) != NULL);
rc = lsm_op_find(magic)->lsm_unpackmd(lov, *lsmp, lmm);
if (rc) {
lov_free_memmd(lsmp);
return rc;
}
return lsm_size;
}
/* Retrieve object striping information.
*
* @lump is a pointer to an in-core struct with lmm_ost_count indicating
* the maximum number of OST indices which will fit in the user buffer.
* lmm_magic must be LOV_USER_MAGIC.
*/
int lov_getstripe(struct obd_export *exp, struct lov_stripe_md *lsm,
struct lov_user_md *lump)
{
/*
* XXX huge struct allocated on stack.
*/
/* we use lov_user_md_v3 because it is larger than lov_user_md_v1 */
struct lov_user_md_v3 lum;
struct lov_mds_md *lmmk = NULL;
int rc, lmm_size;
int lum_size;
mm_segment_t seg;
if (!lsm)
return -ENODATA;
/*
* "Switch to kernel segment" to allow copying from kernel space by
* copy_{to,from}_user().
*/
seg = get_fs();
set_fs(KERNEL_DS);
/* we only need the header part from user space to get lmm_magic and
* lmm_stripe_count, (the header part is common to v1 and v3) */
lum_size = sizeof(struct lov_user_md_v1);
if (copy_from_user(&lum, lump, lum_size)) {
rc = -EFAULT;
goto out_set;
} else if ((lum.lmm_magic != LOV_USER_MAGIC) &&
(lum.lmm_magic != LOV_USER_MAGIC_V3)) {
rc = -EINVAL;
goto out_set;
}
if (lum.lmm_stripe_count &&
(lum.lmm_stripe_count < lsm->lsm_stripe_count)) {
/* Return right size of stripe to user */
lum.lmm_stripe_count = lsm->lsm_stripe_count;
rc = copy_to_user(lump, &lum, lum_size);
rc = -EOVERFLOW;
goto out_set;
}
rc = lov_packmd(exp, &lmmk, lsm);
if (rc < 0)
goto out_set;
lmm_size = rc;
rc = 0;
/* FIXME: Bug 1185 - copy fields properly when structs change */
/* struct lov_user_md_v3 and struct lov_mds_md_v3 must be the same */
CLASSERT(sizeof(lum) == sizeof(struct lov_mds_md_v3));
CLASSERT(sizeof(lum.lmm_objects[0]) == sizeof(lmmk->lmm_objects[0]));
if ((cpu_to_le32(LOV_MAGIC) != LOV_MAGIC) &&
((lmmk->lmm_magic == cpu_to_le32(LOV_MAGIC_V1)) ||
(lmmk->lmm_magic == cpu_to_le32(LOV_MAGIC_V3)))) {
lustre_swab_lov_mds_md(lmmk);
lustre_swab_lov_user_md_objects(
(struct lov_user_ost_data *)lmmk->lmm_objects,
lmmk->lmm_stripe_count);
}
if (lum.lmm_magic == LOV_USER_MAGIC) {
/* User request for v1, we need skip lmm_pool_name */
if (lmmk->lmm_magic == LOV_MAGIC_V3) {
memmove((char *)(&lmmk->lmm_stripe_count) +
sizeof(lmmk->lmm_stripe_count),
((struct lov_mds_md_v3 *)lmmk)->lmm_objects,
lmmk->lmm_stripe_count *
sizeof(struct lov_ost_data_v1));
lmm_size -= LOV_MAXPOOLNAME;
}
} else {
/* if v3 we just have to update the lum_size */
lum_size = sizeof(struct lov_user_md_v3);
}
/* User wasn't expecting this many OST entries */
if (lum.lmm_stripe_count == 0)
lmm_size = lum_size;
else if (lum.lmm_stripe_count < lmmk->lmm_stripe_count) {
rc = -EOVERFLOW;
goto out_set;
}
/*
* Have a difference between lov_mds_md & lov_user_md.
* So we have to re-order the data before copy to user.
*/
lum.lmm_stripe_count = lmmk->lmm_stripe_count;
lum.lmm_layout_gen = lmmk->lmm_layout_gen;
((struct lov_user_md *)lmmk)->lmm_layout_gen = lum.lmm_layout_gen;
((struct lov_user_md *)lmmk)->lmm_stripe_count = lum.lmm_stripe_count;
if (copy_to_user(lump, lmmk, lmm_size))
rc = -EFAULT;
obd_free_diskmd(exp, &lmmk);
out_set:
set_fs(seg);
return rc;
}
| gpl-2.0 |
elkingtonmcb/linux | net/netfilter/xt_addrtype.c | 392 | 6788 | /*
* iptables module to match inet_addr_type() of an ip.
*
* Copyright (c) 2004 Patrick McHardy <kaber@trash.net>
* (C) 2007 Laszlo Attila Toth <panther@balabit.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/ip.h>
#include <net/route.h>
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <net/ip6_fib.h>
#endif
#include <linux/netfilter_ipv6.h>
#include <linux/netfilter/xt_addrtype.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_DESCRIPTION("Xtables: address type match");
MODULE_ALIAS("ipt_addrtype");
MODULE_ALIAS("ip6t_addrtype");
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
static u32 match_lookup_rt6(struct net *net, const struct net_device *dev,
const struct in6_addr *addr, u16 mask)
{
const struct nf_afinfo *afinfo;
struct flowi6 flow;
struct rt6_info *rt;
u32 ret = 0;
int route_err;
memset(&flow, 0, sizeof(flow));
flow.daddr = *addr;
if (dev)
flow.flowi6_oif = dev->ifindex;
rcu_read_lock();
afinfo = nf_get_afinfo(NFPROTO_IPV6);
if (afinfo != NULL) {
const struct nf_ipv6_ops *v6ops;
if (dev && (mask & XT_ADDRTYPE_LOCAL)) {
v6ops = nf_get_ipv6_ops();
if (v6ops && v6ops->chk_addr(net, addr, dev, true))
ret = XT_ADDRTYPE_LOCAL;
}
route_err = afinfo->route(net, (struct dst_entry **)&rt,
flowi6_to_flowi(&flow), false);
} else {
route_err = 1;
}
rcu_read_unlock();
if (route_err)
return XT_ADDRTYPE_UNREACHABLE;
if (rt->rt6i_flags & RTF_REJECT)
ret = XT_ADDRTYPE_UNREACHABLE;
if (dev == NULL && rt->rt6i_flags & RTF_LOCAL)
ret |= XT_ADDRTYPE_LOCAL;
if (ipv6_anycast_destination((struct dst_entry *)rt, addr))
ret |= XT_ADDRTYPE_ANYCAST;
dst_release(&rt->dst);
return ret;
}
static bool match_type6(struct net *net, const struct net_device *dev,
const struct in6_addr *addr, u16 mask)
{
int addr_type = ipv6_addr_type(addr);
if ((mask & XT_ADDRTYPE_MULTICAST) &&
!(addr_type & IPV6_ADDR_MULTICAST))
return false;
if ((mask & XT_ADDRTYPE_UNICAST) && !(addr_type & IPV6_ADDR_UNICAST))
return false;
if ((mask & XT_ADDRTYPE_UNSPEC) && addr_type != IPV6_ADDR_ANY)
return false;
if ((XT_ADDRTYPE_LOCAL | XT_ADDRTYPE_ANYCAST |
XT_ADDRTYPE_UNREACHABLE) & mask)
return !!(mask & match_lookup_rt6(net, dev, addr, mask));
return true;
}
static bool
addrtype_mt6(struct net *net, const struct net_device *dev,
const struct sk_buff *skb, const struct xt_addrtype_info_v1 *info)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
bool ret = true;
if (info->source)
ret &= match_type6(net, dev, &iph->saddr, info->source) ^
(info->flags & XT_ADDRTYPE_INVERT_SOURCE);
if (ret && info->dest)
ret &= match_type6(net, dev, &iph->daddr, info->dest) ^
!!(info->flags & XT_ADDRTYPE_INVERT_DEST);
return ret;
}
#endif
static inline bool match_type(struct net *net, const struct net_device *dev,
__be32 addr, u_int16_t mask)
{
return !!(mask & (1 << inet_dev_addr_type(net, dev, addr)));
}
static bool
addrtype_mt_v0(const struct sk_buff *skb, struct xt_action_param *par)
{
struct net *net = dev_net(par->in ? par->in : par->out);
const struct xt_addrtype_info *info = par->matchinfo;
const struct iphdr *iph = ip_hdr(skb);
bool ret = true;
if (info->source)
ret &= match_type(net, NULL, iph->saddr, info->source) ^
info->invert_source;
if (info->dest)
ret &= match_type(net, NULL, iph->daddr, info->dest) ^
info->invert_dest;
return ret;
}
static bool
addrtype_mt_v1(const struct sk_buff *skb, struct xt_action_param *par)
{
struct net *net = dev_net(par->in ? par->in : par->out);
const struct xt_addrtype_info_v1 *info = par->matchinfo;
const struct iphdr *iph;
const struct net_device *dev = NULL;
bool ret = true;
if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN)
dev = par->in;
else if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT)
dev = par->out;
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
if (par->family == NFPROTO_IPV6)
return addrtype_mt6(net, dev, skb, info);
#endif
iph = ip_hdr(skb);
if (info->source)
ret &= match_type(net, dev, iph->saddr, info->source) ^
(info->flags & XT_ADDRTYPE_INVERT_SOURCE);
if (ret && info->dest)
ret &= match_type(net, dev, iph->daddr, info->dest) ^
!!(info->flags & XT_ADDRTYPE_INVERT_DEST);
return ret;
}
static int addrtype_mt_checkentry_v1(const struct xt_mtchk_param *par)
{
struct xt_addrtype_info_v1 *info = par->matchinfo;
if (info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT) {
pr_info("both incoming and outgoing "
"interface limitation cannot be selected\n");
return -EINVAL;
}
if (par->hook_mask & ((1 << NF_INET_PRE_ROUTING) |
(1 << NF_INET_LOCAL_IN)) &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_OUT) {
pr_info("output interface limitation "
"not valid in PREROUTING and INPUT\n");
return -EINVAL;
}
if (par->hook_mask & ((1 << NF_INET_POST_ROUTING) |
(1 << NF_INET_LOCAL_OUT)) &&
info->flags & XT_ADDRTYPE_LIMIT_IFACE_IN) {
pr_info("input interface limitation "
"not valid in POSTROUTING and OUTPUT\n");
return -EINVAL;
}
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
if (par->family == NFPROTO_IPV6) {
if ((info->source | info->dest) & XT_ADDRTYPE_BLACKHOLE) {
pr_err("ipv6 BLACKHOLE matching not supported\n");
return -EINVAL;
}
if ((info->source | info->dest) >= XT_ADDRTYPE_PROHIBIT) {
pr_err("ipv6 PROHIBIT (THROW, NAT ..) matching not supported\n");
return -EINVAL;
}
if ((info->source | info->dest) & XT_ADDRTYPE_BROADCAST) {
pr_err("ipv6 does not support BROADCAST matching\n");
return -EINVAL;
}
}
#endif
return 0;
}
static struct xt_match addrtype_mt_reg[] __read_mostly = {
{
.name = "addrtype",
.family = NFPROTO_IPV4,
.match = addrtype_mt_v0,
.matchsize = sizeof(struct xt_addrtype_info),
.me = THIS_MODULE
},
{
.name = "addrtype",
.family = NFPROTO_UNSPEC,
.revision = 1,
.match = addrtype_mt_v1,
.checkentry = addrtype_mt_checkentry_v1,
.matchsize = sizeof(struct xt_addrtype_info_v1),
.me = THIS_MODULE
}
};
static int __init addrtype_mt_init(void)
{
return xt_register_matches(addrtype_mt_reg,
ARRAY_SIZE(addrtype_mt_reg));
}
static void __exit addrtype_mt_exit(void)
{
xt_unregister_matches(addrtype_mt_reg, ARRAY_SIZE(addrtype_mt_reg));
}
module_init(addrtype_mt_init);
module_exit(addrtype_mt_exit);
| gpl-2.0 |
cm-a7lte/kernel_samsung_a7lte | arch/parisc/kernel/setup.c | 1928 | 10029 | /*
* Initial setup-routines for HP 9000 based hardware.
*
* Copyright (C) 1991, 1992, 1995 Linus Torvalds
* Modifications for PA-RISC (C) 1999 Helge Deller <deller@gmx.de>
* Modifications copyright 1999 SuSE GmbH (Philipp Rumpf)
* Modifications copyright 2000 Martin K. Petersen <mkp@mkp.net>
* Modifications copyright 2000 Philipp Rumpf <prumpf@tux.org>
* Modifications copyright 2001 Ryan Bradetich <rbradetich@uswest.net>
*
* Initial PA-RISC Version: 04-23-1999 by Helge Deller
*
* 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/kernel.h>
#include <linux/initrd.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/seq_file.h>
#define PCI_DEBUG
#include <linux/pci.h>
#undef PCI_DEBUG
#include <linux/proc_fs.h>
#include <linux/export.h>
#include <asm/processor.h>
#include <asm/pdc.h>
#include <asm/led.h>
#include <asm/machdep.h> /* for pa7300lc_init() proto */
#include <asm/pdc_chassis.h>
#include <asm/io.h>
#include <asm/setup.h>
#include <asm/unwind.h>
static char __initdata command_line[COMMAND_LINE_SIZE];
/* Intended for ccio/sba/cpu statistics under /proc/bus/{runway|gsc} */
struct proc_dir_entry * proc_runway_root __read_mostly = NULL;
struct proc_dir_entry * proc_gsc_root __read_mostly = NULL;
struct proc_dir_entry * proc_mckinley_root __read_mostly = NULL;
#if !defined(CONFIG_PA20) && (defined(CONFIG_IOMMU_CCIO) || defined(CONFIG_IOMMU_SBA))
int parisc_bus_is_phys __read_mostly = 1; /* Assume no IOMMU is present */
EXPORT_SYMBOL(parisc_bus_is_phys);
#endif
void __init setup_cmdline(char **cmdline_p)
{
extern unsigned int boot_args[];
/* Collect stuff passed in from the boot loader */
/* boot_args[0] is free-mem start, boot_args[1] is ptr to command line */
if (boot_args[0] < 64) {
/* called from hpux boot loader */
boot_command_line[0] = '\0';
} else {
strlcpy(boot_command_line, (char *)__va(boot_args[1]),
COMMAND_LINE_SIZE);
#ifdef CONFIG_BLK_DEV_INITRD
if (boot_args[2] != 0) /* did palo pass us a ramdisk? */
{
initrd_start = (unsigned long)__va(boot_args[2]);
initrd_end = (unsigned long)__va(boot_args[3]);
}
#endif
}
strcpy(command_line, boot_command_line);
*cmdline_p = command_line;
}
#ifdef CONFIG_PA11
void __init dma_ops_init(void)
{
switch (boot_cpu_data.cpu_type) {
case pcx:
/*
* We've got way too many dependencies on 1.1 semantics
* to support 1.0 boxes at this point.
*/
panic( "PA-RISC Linux currently only supports machines that conform to\n"
"the PA-RISC 1.1 or 2.0 architecture specification.\n");
case pcxs:
case pcxt:
hppa_dma_ops = &pcx_dma_ops;
break;
case pcxl2:
pa7300lc_init();
case pcxl: /* falls through */
hppa_dma_ops = &pcxl_dma_ops;
break;
default:
break;
}
}
#endif
extern int init_per_cpu(int cpuid);
extern void collect_boot_cpu_data(void);
void __init setup_arch(char **cmdline_p)
{
#ifdef CONFIG_64BIT
extern int parisc_narrow_firmware;
#endif
unwind_init();
init_per_cpu(smp_processor_id()); /* Set Modes & Enable FP */
#ifdef CONFIG_64BIT
printk(KERN_INFO "The 64-bit Kernel has started...\n");
#else
printk(KERN_INFO "The 32-bit Kernel has started...\n");
#endif
printk(KERN_INFO "Default page size is %dKB.\n", (int)(PAGE_SIZE / 1024));
pdc_console_init();
#ifdef CONFIG_64BIT
if(parisc_narrow_firmware) {
printk(KERN_INFO "Kernel is using PDC in 32-bit mode.\n");
}
#endif
setup_pdc();
setup_cmdline(cmdline_p);
collect_boot_cpu_data();
do_memory_inventory(); /* probe for physical memory */
parisc_cache_init();
paging_init();
#ifdef CONFIG_CHASSIS_LCD_LED
/* initialize the LCD/LED after boot_cpu_data is available ! */
led_init(); /* LCD/LED initialization */
#endif
#ifdef CONFIG_PA11
dma_ops_init();
#endif
#if defined(CONFIG_VT) && defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con; /* we use take_over_console() later ! */
#endif
}
/*
* Display CPU info for all CPUs.
* for parisc this is in processor.c
*/
extern int show_cpuinfo (struct seq_file *m, void *v);
static void *
c_start (struct seq_file *m, loff_t *pos)
{
/* Looks like the caller will call repeatedly until we return
* 0, signaling EOF perhaps. This could be used to sequence
* through CPUs for example. Since we print all cpu info in our
* show_cpuinfo() disregarding 'pos' (which I assume is 'v' above)
* we only allow for one "position". */
return ((long)*pos < 1) ? (void *)1 : NULL;
}
static void *
c_next (struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void
c_stop (struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo
};
static void __init parisc_proc_mkdir(void)
{
/*
** Can't call proc_mkdir() until after proc_root_init() has been
** called by start_kernel(). In other words, this code can't
** live in arch/.../setup.c because start_parisc() calls
** start_kernel().
*/
switch (boot_cpu_data.cpu_type) {
case pcxl:
case pcxl2:
if (NULL == proc_gsc_root)
{
proc_gsc_root = proc_mkdir("bus/gsc", NULL);
}
break;
case pcxt_:
case pcxu:
case pcxu_:
case pcxw:
case pcxw_:
case pcxw2:
if (NULL == proc_runway_root)
{
proc_runway_root = proc_mkdir("bus/runway", NULL);
}
break;
case mako:
case mako2:
if (NULL == proc_mckinley_root)
{
proc_mckinley_root = proc_mkdir("bus/mckinley", NULL);
}
break;
default:
/* FIXME: this was added to prevent the compiler
* complaining about missing pcx, pcxs and pcxt
* I'm assuming they have neither gsc nor runway */
break;
}
}
static struct resource central_bus = {
.name = "Central Bus",
.start = F_EXTEND(0xfff80000),
.end = F_EXTEND(0xfffaffff),
.flags = IORESOURCE_MEM,
};
static struct resource local_broadcast = {
.name = "Local Broadcast",
.start = F_EXTEND(0xfffb0000),
.end = F_EXTEND(0xfffdffff),
.flags = IORESOURCE_MEM,
};
static struct resource global_broadcast = {
.name = "Global Broadcast",
.start = F_EXTEND(0xfffe0000),
.end = F_EXTEND(0xffffffff),
.flags = IORESOURCE_MEM,
};
static int __init parisc_init_resources(void)
{
int result;
result = request_resource(&iomem_resource, ¢ral_bus);
if (result < 0) {
printk(KERN_ERR
"%s: failed to claim %s address space!\n",
__FILE__, central_bus.name);
return result;
}
result = request_resource(&iomem_resource, &local_broadcast);
if (result < 0) {
printk(KERN_ERR
"%s: failed to claim %saddress space!\n",
__FILE__, local_broadcast.name);
return result;
}
result = request_resource(&iomem_resource, &global_broadcast);
if (result < 0) {
printk(KERN_ERR
"%s: failed to claim %s address space!\n",
__FILE__, global_broadcast.name);
return result;
}
return 0;
}
extern void gsc_init(void);
extern void processor_init(void);
extern void ccio_init(void);
extern void hppb_init(void);
extern void dino_init(void);
extern void iosapic_init(void);
extern void lba_init(void);
extern void sba_init(void);
extern void eisa_init(void);
static int __init parisc_init(void)
{
u32 osid = (OS_ID_LINUX << 16);
parisc_proc_mkdir();
parisc_init_resources();
do_device_inventory(); /* probe for hardware */
parisc_pdc_chassis_init();
/* set up a new led state on systems shipped LED State panel */
pdc_chassis_send_status(PDC_CHASSIS_DIRECT_BSTART);
/* tell PDC we're Linux. Nevermind failure. */
pdc_stable_write(0x40, &osid, sizeof(osid));
processor_init();
printk(KERN_INFO "CPU(s): %d x %s at %d.%06d MHz\n",
num_present_cpus(),
boot_cpu_data.cpu_name,
boot_cpu_data.cpu_hz / 1000000,
boot_cpu_data.cpu_hz % 1000000 );
parisc_setup_cache_timing();
/* These are in a non-obvious order, will fix when we have an iotree */
#if defined(CONFIG_IOSAPIC)
iosapic_init();
#endif
#if defined(CONFIG_IOMMU_SBA)
sba_init();
#endif
#if defined(CONFIG_PCI_LBA)
lba_init();
#endif
/* CCIO before any potential subdevices */
#if defined(CONFIG_IOMMU_CCIO)
ccio_init();
#endif
/*
* Need to register Asp & Wax before the EISA adapters for the IRQ
* regions. EISA must come before PCI to be sure it gets IRQ region
* 0.
*/
#if defined(CONFIG_GSC_LASI) || defined(CONFIG_GSC_WAX)
gsc_init();
#endif
#ifdef CONFIG_EISA
eisa_init();
#endif
#if defined(CONFIG_HPPB)
hppb_init();
#endif
#if defined(CONFIG_GSC_DINO)
dino_init();
#endif
#ifdef CONFIG_CHASSIS_LCD_LED
register_led_regions(); /* register LED port info in procfs */
#endif
return 0;
}
arch_initcall(parisc_init);
void start_parisc(void)
{
extern void start_kernel(void);
int ret, cpunum;
struct pdc_coproc_cfg coproc_cfg;
cpunum = smp_processor_id();
set_firmware_width_unlocked();
ret = pdc_coproc_cfg_unlocked(&coproc_cfg);
if (ret >= 0 && coproc_cfg.ccr_functional) {
mtctl(coproc_cfg.ccr_functional, 10);
per_cpu(cpu_data, cpunum).fp_rev = coproc_cfg.revision;
per_cpu(cpu_data, cpunum).fp_model = coproc_cfg.model;
asm volatile ("fstd %fr0,8(%sp)");
} else {
panic("must have an fpu to boot linux");
}
start_kernel();
// not reached
}
| gpl-2.0 |
STR4NG3R/android_kernel_motorola_msm8226 | drivers/gpu/drm/gma500/oaktrail_device.c | 5256 | 15027 | /**************************************************************************
* Copyright (c) 2011, Intel Corporation.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
**************************************************************************/
#include <linux/backlight.h>
#include <linux/module.h>
#include <linux/dmi.h>
#include <drm/drmP.h>
#include <drm/drm.h>
#include "gma_drm.h"
#include "psb_drv.h"
#include "psb_reg.h"
#include "psb_intel_reg.h"
#include <asm/mrst.h>
#include <asm/intel_scu_ipc.h>
#include "mid_bios.h"
#include "intel_bios.h"
static int oaktrail_output_init(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
if (dev_priv->iLVDS_enable)
oaktrail_lvds_init(dev, &dev_priv->mode_dev);
else
dev_err(dev->dev, "DSI is not supported\n");
if (dev_priv->hdmi_priv)
oaktrail_hdmi_init(dev, &dev_priv->mode_dev);
return 0;
}
/*
* Provide the low level interfaces for the Moorestown backlight
*/
#ifdef CONFIG_BACKLIGHT_CLASS_DEVICE
#define MRST_BLC_MAX_PWM_REG_FREQ 0xFFFF
#define BLC_PWM_PRECISION_FACTOR 100 /* 10000000 */
#define BLC_PWM_FREQ_CALC_CONSTANT 32
#define MHz 1000000
#define BLC_ADJUSTMENT_MAX 100
static struct backlight_device *oaktrail_backlight_device;
static int oaktrail_brightness;
static int oaktrail_set_brightness(struct backlight_device *bd)
{
struct drm_device *dev = bl_get_data(oaktrail_backlight_device);
struct drm_psb_private *dev_priv = dev->dev_private;
int level = bd->props.brightness;
u32 blc_pwm_ctl;
u32 max_pwm_blc;
/* Percentage 1-100% being valid */
if (level < 1)
level = 1;
if (gma_power_begin(dev, 0)) {
/* Calculate and set the brightness value */
max_pwm_blc = REG_READ(BLC_PWM_CTL) >> 16;
blc_pwm_ctl = level * max_pwm_blc / 100;
/* Adjust the backlight level with the percent in
* dev_priv->blc_adj1;
*/
blc_pwm_ctl = blc_pwm_ctl * dev_priv->blc_adj1;
blc_pwm_ctl = blc_pwm_ctl / 100;
/* Adjust the backlight level with the percent in
* dev_priv->blc_adj2;
*/
blc_pwm_ctl = blc_pwm_ctl * dev_priv->blc_adj2;
blc_pwm_ctl = blc_pwm_ctl / 100;
/* force PWM bit on */
REG_WRITE(BLC_PWM_CTL2, (0x80000000 | REG_READ(BLC_PWM_CTL2)));
REG_WRITE(BLC_PWM_CTL, (max_pwm_blc << 16) | blc_pwm_ctl);
gma_power_end(dev);
}
oaktrail_brightness = level;
return 0;
}
static int oaktrail_get_brightness(struct backlight_device *bd)
{
/* return locally cached var instead of HW read (due to DPST etc.) */
/* FIXME: ideally return actual value in case firmware fiddled with
it */
return oaktrail_brightness;
}
static int device_backlight_init(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
unsigned long core_clock;
u16 bl_max_freq;
uint32_t value;
uint32_t blc_pwm_precision_factor;
dev_priv->blc_adj1 = BLC_ADJUSTMENT_MAX;
dev_priv->blc_adj2 = BLC_ADJUSTMENT_MAX;
bl_max_freq = 256;
/* this needs to be set elsewhere */
blc_pwm_precision_factor = BLC_PWM_PRECISION_FACTOR;
core_clock = dev_priv->core_freq;
value = (core_clock * MHz) / BLC_PWM_FREQ_CALC_CONSTANT;
value *= blc_pwm_precision_factor;
value /= bl_max_freq;
value /= blc_pwm_precision_factor;
if (value > (unsigned long long)MRST_BLC_MAX_PWM_REG_FREQ)
return -ERANGE;
if (gma_power_begin(dev, false)) {
REG_WRITE(BLC_PWM_CTL2, (0x80000000 | REG_READ(BLC_PWM_CTL2)));
REG_WRITE(BLC_PWM_CTL, value | (value << 16));
gma_power_end(dev);
}
return 0;
}
static const struct backlight_ops oaktrail_ops = {
.get_brightness = oaktrail_get_brightness,
.update_status = oaktrail_set_brightness,
};
static int oaktrail_backlight_init(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
int ret;
struct backlight_properties props;
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = 100;
props.type = BACKLIGHT_PLATFORM;
oaktrail_backlight_device = backlight_device_register("oaktrail-bl",
NULL, (void *)dev, &oaktrail_ops, &props);
if (IS_ERR(oaktrail_backlight_device))
return PTR_ERR(oaktrail_backlight_device);
ret = device_backlight_init(dev);
if (ret < 0) {
backlight_device_unregister(oaktrail_backlight_device);
return ret;
}
oaktrail_backlight_device->props.brightness = 100;
oaktrail_backlight_device->props.max_brightness = 100;
backlight_update_status(oaktrail_backlight_device);
dev_priv->backlight_device = oaktrail_backlight_device;
return 0;
}
#endif
/*
* Provide the Moorestown specific chip logic and low level methods
* for power management
*/
/**
* oaktrail_save_display_registers - save registers lost on suspend
* @dev: our DRM device
*
* Save the state we need in order to be able to restore the interface
* upon resume from suspend
*/
static int oaktrail_save_display_registers(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
struct psb_save_area *regs = &dev_priv->regs;
int i;
u32 pp_stat;
/* Display arbitration control + watermarks */
regs->psb.saveDSPARB = PSB_RVDC32(DSPARB);
regs->psb.saveDSPFW1 = PSB_RVDC32(DSPFW1);
regs->psb.saveDSPFW2 = PSB_RVDC32(DSPFW2);
regs->psb.saveDSPFW3 = PSB_RVDC32(DSPFW3);
regs->psb.saveDSPFW4 = PSB_RVDC32(DSPFW4);
regs->psb.saveDSPFW5 = PSB_RVDC32(DSPFW5);
regs->psb.saveDSPFW6 = PSB_RVDC32(DSPFW6);
regs->psb.saveCHICKENBIT = PSB_RVDC32(DSPCHICKENBIT);
/* Pipe & plane A info */
regs->psb.savePIPEACONF = PSB_RVDC32(PIPEACONF);
regs->psb.savePIPEASRC = PSB_RVDC32(PIPEASRC);
regs->psb.saveFPA0 = PSB_RVDC32(MRST_FPA0);
regs->psb.saveFPA1 = PSB_RVDC32(MRST_FPA1);
regs->psb.saveDPLL_A = PSB_RVDC32(MRST_DPLL_A);
regs->psb.saveHTOTAL_A = PSB_RVDC32(HTOTAL_A);
regs->psb.saveHBLANK_A = PSB_RVDC32(HBLANK_A);
regs->psb.saveHSYNC_A = PSB_RVDC32(HSYNC_A);
regs->psb.saveVTOTAL_A = PSB_RVDC32(VTOTAL_A);
regs->psb.saveVBLANK_A = PSB_RVDC32(VBLANK_A);
regs->psb.saveVSYNC_A = PSB_RVDC32(VSYNC_A);
regs->psb.saveBCLRPAT_A = PSB_RVDC32(BCLRPAT_A);
regs->psb.saveDSPACNTR = PSB_RVDC32(DSPACNTR);
regs->psb.saveDSPASTRIDE = PSB_RVDC32(DSPASTRIDE);
regs->psb.saveDSPAADDR = PSB_RVDC32(DSPABASE);
regs->psb.saveDSPASURF = PSB_RVDC32(DSPASURF);
regs->psb.saveDSPALINOFF = PSB_RVDC32(DSPALINOFF);
regs->psb.saveDSPATILEOFF = PSB_RVDC32(DSPATILEOFF);
/* Save cursor regs */
regs->psb.saveDSPACURSOR_CTRL = PSB_RVDC32(CURACNTR);
regs->psb.saveDSPACURSOR_BASE = PSB_RVDC32(CURABASE);
regs->psb.saveDSPACURSOR_POS = PSB_RVDC32(CURAPOS);
/* Save palette (gamma) */
for (i = 0; i < 256; i++)
regs->psb.save_palette_a[i] = PSB_RVDC32(PALETTE_A + (i << 2));
if (dev_priv->hdmi_priv)
oaktrail_hdmi_save(dev);
/* Save performance state */
regs->psb.savePERF_MODE = PSB_RVDC32(MRST_PERF_MODE);
/* LVDS state */
regs->psb.savePP_CONTROL = PSB_RVDC32(PP_CONTROL);
regs->psb.savePFIT_PGM_RATIOS = PSB_RVDC32(PFIT_PGM_RATIOS);
regs->psb.savePFIT_AUTO_RATIOS = PSB_RVDC32(PFIT_AUTO_RATIOS);
regs->saveBLC_PWM_CTL = PSB_RVDC32(BLC_PWM_CTL);
regs->saveBLC_PWM_CTL2 = PSB_RVDC32(BLC_PWM_CTL2);
regs->psb.saveLVDS = PSB_RVDC32(LVDS);
regs->psb.savePFIT_CONTROL = PSB_RVDC32(PFIT_CONTROL);
regs->psb.savePP_ON_DELAYS = PSB_RVDC32(LVDSPP_ON);
regs->psb.savePP_OFF_DELAYS = PSB_RVDC32(LVDSPP_OFF);
regs->psb.savePP_DIVISOR = PSB_RVDC32(PP_CYCLE);
/* HW overlay */
regs->psb.saveOV_OVADD = PSB_RVDC32(OV_OVADD);
regs->psb.saveOV_OGAMC0 = PSB_RVDC32(OV_OGAMC0);
regs->psb.saveOV_OGAMC1 = PSB_RVDC32(OV_OGAMC1);
regs->psb.saveOV_OGAMC2 = PSB_RVDC32(OV_OGAMC2);
regs->psb.saveOV_OGAMC3 = PSB_RVDC32(OV_OGAMC3);
regs->psb.saveOV_OGAMC4 = PSB_RVDC32(OV_OGAMC4);
regs->psb.saveOV_OGAMC5 = PSB_RVDC32(OV_OGAMC5);
/* DPST registers */
regs->psb.saveHISTOGRAM_INT_CONTROL_REG =
PSB_RVDC32(HISTOGRAM_INT_CONTROL);
regs->psb.saveHISTOGRAM_LOGIC_CONTROL_REG =
PSB_RVDC32(HISTOGRAM_LOGIC_CONTROL);
regs->psb.savePWM_CONTROL_LOGIC = PSB_RVDC32(PWM_CONTROL_LOGIC);
if (dev_priv->iLVDS_enable) {
/* Shut down the panel */
PSB_WVDC32(0, PP_CONTROL);
do {
pp_stat = PSB_RVDC32(PP_STATUS);
} while (pp_stat & 0x80000000);
/* Turn off the plane */
PSB_WVDC32(0x58000000, DSPACNTR);
/* Trigger the plane disable */
PSB_WVDC32(0, DSPASURF);
/* Wait ~4 ticks */
msleep(4);
/* Turn off pipe */
PSB_WVDC32(0x0, PIPEACONF);
/* Wait ~8 ticks */
msleep(8);
/* Turn off PLLs */
PSB_WVDC32(0, MRST_DPLL_A);
}
return 0;
}
/**
* oaktrail_restore_display_registers - restore lost register state
* @dev: our DRM device
*
* Restore register state that was lost during suspend and resume.
*/
static int oaktrail_restore_display_registers(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
struct psb_save_area *regs = &dev_priv->regs;
u32 pp_stat;
int i;
/* Display arbitration + watermarks */
PSB_WVDC32(regs->psb.saveDSPARB, DSPARB);
PSB_WVDC32(regs->psb.saveDSPFW1, DSPFW1);
PSB_WVDC32(regs->psb.saveDSPFW2, DSPFW2);
PSB_WVDC32(regs->psb.saveDSPFW3, DSPFW3);
PSB_WVDC32(regs->psb.saveDSPFW4, DSPFW4);
PSB_WVDC32(regs->psb.saveDSPFW5, DSPFW5);
PSB_WVDC32(regs->psb.saveDSPFW6, DSPFW6);
PSB_WVDC32(regs->psb.saveCHICKENBIT, DSPCHICKENBIT);
/* Make sure VGA plane is off. it initializes to on after reset!*/
PSB_WVDC32(0x80000000, VGACNTRL);
/* set the plls */
PSB_WVDC32(regs->psb.saveFPA0, MRST_FPA0);
PSB_WVDC32(regs->psb.saveFPA1, MRST_FPA1);
/* Actually enable it */
PSB_WVDC32(regs->psb.saveDPLL_A, MRST_DPLL_A);
DRM_UDELAY(150);
/* Restore mode */
PSB_WVDC32(regs->psb.saveHTOTAL_A, HTOTAL_A);
PSB_WVDC32(regs->psb.saveHBLANK_A, HBLANK_A);
PSB_WVDC32(regs->psb.saveHSYNC_A, HSYNC_A);
PSB_WVDC32(regs->psb.saveVTOTAL_A, VTOTAL_A);
PSB_WVDC32(regs->psb.saveVBLANK_A, VBLANK_A);
PSB_WVDC32(regs->psb.saveVSYNC_A, VSYNC_A);
PSB_WVDC32(regs->psb.savePIPEASRC, PIPEASRC);
PSB_WVDC32(regs->psb.saveBCLRPAT_A, BCLRPAT_A);
/* Restore performance mode*/
PSB_WVDC32(regs->psb.savePERF_MODE, MRST_PERF_MODE);
/* Enable the pipe*/
if (dev_priv->iLVDS_enable)
PSB_WVDC32(regs->psb.savePIPEACONF, PIPEACONF);
/* Set up the plane*/
PSB_WVDC32(regs->psb.saveDSPALINOFF, DSPALINOFF);
PSB_WVDC32(regs->psb.saveDSPASTRIDE, DSPASTRIDE);
PSB_WVDC32(regs->psb.saveDSPATILEOFF, DSPATILEOFF);
/* Enable the plane */
PSB_WVDC32(regs->psb.saveDSPACNTR, DSPACNTR);
PSB_WVDC32(regs->psb.saveDSPASURF, DSPASURF);
/* Enable Cursor A */
PSB_WVDC32(regs->psb.saveDSPACURSOR_CTRL, CURACNTR);
PSB_WVDC32(regs->psb.saveDSPACURSOR_POS, CURAPOS);
PSB_WVDC32(regs->psb.saveDSPACURSOR_BASE, CURABASE);
/* Restore palette (gamma) */
for (i = 0; i < 256; i++)
PSB_WVDC32(regs->psb.save_palette_a[i], PALETTE_A + (i << 2));
if (dev_priv->hdmi_priv)
oaktrail_hdmi_restore(dev);
if (dev_priv->iLVDS_enable) {
PSB_WVDC32(regs->saveBLC_PWM_CTL2, BLC_PWM_CTL2);
PSB_WVDC32(regs->psb.saveLVDS, LVDS); /*port 61180h*/
PSB_WVDC32(regs->psb.savePFIT_CONTROL, PFIT_CONTROL);
PSB_WVDC32(regs->psb.savePFIT_PGM_RATIOS, PFIT_PGM_RATIOS);
PSB_WVDC32(regs->psb.savePFIT_AUTO_RATIOS, PFIT_AUTO_RATIOS);
PSB_WVDC32(regs->saveBLC_PWM_CTL, BLC_PWM_CTL);
PSB_WVDC32(regs->psb.savePP_ON_DELAYS, LVDSPP_ON);
PSB_WVDC32(regs->psb.savePP_OFF_DELAYS, LVDSPP_OFF);
PSB_WVDC32(regs->psb.savePP_DIVISOR, PP_CYCLE);
PSB_WVDC32(regs->psb.savePP_CONTROL, PP_CONTROL);
}
/* Wait for cycle delay */
do {
pp_stat = PSB_RVDC32(PP_STATUS);
} while (pp_stat & 0x08000000);
/* Wait for panel power up */
do {
pp_stat = PSB_RVDC32(PP_STATUS);
} while (pp_stat & 0x10000000);
/* Restore HW overlay */
PSB_WVDC32(regs->psb.saveOV_OVADD, OV_OVADD);
PSB_WVDC32(regs->psb.saveOV_OGAMC0, OV_OGAMC0);
PSB_WVDC32(regs->psb.saveOV_OGAMC1, OV_OGAMC1);
PSB_WVDC32(regs->psb.saveOV_OGAMC2, OV_OGAMC2);
PSB_WVDC32(regs->psb.saveOV_OGAMC3, OV_OGAMC3);
PSB_WVDC32(regs->psb.saveOV_OGAMC4, OV_OGAMC4);
PSB_WVDC32(regs->psb.saveOV_OGAMC5, OV_OGAMC5);
/* DPST registers */
PSB_WVDC32(regs->psb.saveHISTOGRAM_INT_CONTROL_REG,
HISTOGRAM_INT_CONTROL);
PSB_WVDC32(regs->psb.saveHISTOGRAM_LOGIC_CONTROL_REG,
HISTOGRAM_LOGIC_CONTROL);
PSB_WVDC32(regs->psb.savePWM_CONTROL_LOGIC, PWM_CONTROL_LOGIC);
return 0;
}
/**
* oaktrail_power_down - power down the display island
* @dev: our DRM device
*
* Power down the display interface of our device
*/
static int oaktrail_power_down(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
u32 pwr_mask ;
u32 pwr_sts;
pwr_mask = PSB_PWRGT_DISPLAY_MASK;
outl(pwr_mask, dev_priv->ospm_base + PSB_PM_SSC);
while (true) {
pwr_sts = inl(dev_priv->ospm_base + PSB_PM_SSS);
if ((pwr_sts & pwr_mask) == pwr_mask)
break;
else
udelay(10);
}
return 0;
}
/*
* oaktrail_power_up
*
* Restore power to the specified island(s) (powergating)
*/
static int oaktrail_power_up(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
u32 pwr_mask = PSB_PWRGT_DISPLAY_MASK;
u32 pwr_sts, pwr_cnt;
pwr_cnt = inl(dev_priv->ospm_base + PSB_PM_SSC);
pwr_cnt &= ~pwr_mask;
outl(pwr_cnt, (dev_priv->ospm_base + PSB_PM_SSC));
while (true) {
pwr_sts = inl(dev_priv->ospm_base + PSB_PM_SSS);
if ((pwr_sts & pwr_mask) == 0)
break;
else
udelay(10);
}
return 0;
}
static int oaktrail_chip_setup(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
struct oaktrail_vbt *vbt = &dev_priv->vbt_data;
int ret;
ret = mid_chip_setup(dev);
if (ret < 0)
return ret;
if (vbt->size == 0) {
/* Now pull the BIOS data */
gma_intel_opregion_init(dev);
psb_intel_init_bios(dev);
}
return 0;
}
static void oaktrail_teardown(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
struct oaktrail_vbt *vbt = &dev_priv->vbt_data;
oaktrail_hdmi_teardown(dev);
if (vbt->size == 0)
psb_intel_destroy_bios(dev);
}
const struct psb_ops oaktrail_chip_ops = {
.name = "Oaktrail",
.accel_2d = 1,
.pipes = 2,
.crtcs = 2,
.sgx_offset = MRST_SGX_OFFSET,
.chip_setup = oaktrail_chip_setup,
.chip_teardown = oaktrail_teardown,
.crtc_helper = &oaktrail_helper_funcs,
.crtc_funcs = &psb_intel_crtc_funcs,
.output_init = oaktrail_output_init,
#ifdef CONFIG_BACKLIGHT_CLASS_DEVICE
.backlight_init = oaktrail_backlight_init,
#endif
.save_regs = oaktrail_save_display_registers,
.restore_regs = oaktrail_restore_display_registers,
.power_down = oaktrail_power_down,
.power_up = oaktrail_power_up,
.i2c_bus = 1,
};
| gpl-2.0 |
chrisch1974/android_kernel_htc_b2 | arch/sparc/prom/ranges.c | 8840 | 3703 | /*
* ranges.c: Handle ranges in newer proms for obio/sbus.
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1997 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
*/
#include <linux/init.h>
#include <linux/module.h>
#include <asm/openprom.h>
#include <asm/oplib.h>
#include <asm/types.h>
static struct linux_prom_ranges promlib_obio_ranges[PROMREG_MAX];
static int num_obio_ranges;
/* Adjust register values based upon the ranges parameters. */
static void
prom_adjust_regs(struct linux_prom_registers *regp, int nregs,
struct linux_prom_ranges *rangep, int nranges)
{
int regc, rngc;
for (regc = 0; regc < nregs; regc++) {
for (rngc = 0; rngc < nranges; rngc++)
if (regp[regc].which_io == rangep[rngc].ot_child_space)
break; /* Fount it */
if (rngc == nranges) /* oops */
prom_printf("adjust_regs: Could not find range with matching bus type...\n");
regp[regc].which_io = rangep[rngc].ot_parent_space;
regp[regc].phys_addr -= rangep[rngc].ot_child_base;
regp[regc].phys_addr += rangep[rngc].ot_parent_base;
}
}
static void
prom_adjust_ranges(struct linux_prom_ranges *ranges1, int nranges1,
struct linux_prom_ranges *ranges2, int nranges2)
{
int rng1c, rng2c;
for(rng1c=0; rng1c < nranges1; rng1c++) {
for(rng2c=0; rng2c < nranges2; rng2c++)
if(ranges1[rng1c].ot_parent_space == ranges2[rng2c].ot_child_space &&
ranges1[rng1c].ot_parent_base >= ranges2[rng2c].ot_child_base &&
ranges2[rng2c].ot_child_base + ranges2[rng2c].or_size - ranges1[rng1c].ot_parent_base > 0U)
break;
if(rng2c == nranges2) /* oops */
prom_printf("adjust_ranges: Could not find matching bus type...\n");
else if (ranges1[rng1c].ot_parent_base + ranges1[rng1c].or_size > ranges2[rng2c].ot_child_base + ranges2[rng2c].or_size)
ranges1[rng1c].or_size =
ranges2[rng2c].ot_child_base + ranges2[rng2c].or_size - ranges1[rng1c].ot_parent_base;
ranges1[rng1c].ot_parent_space = ranges2[rng2c].ot_parent_space;
ranges1[rng1c].ot_parent_base += ranges2[rng2c].ot_parent_base;
}
}
/* Apply probed obio ranges to registers passed, if no ranges return. */
void
prom_apply_obio_ranges(struct linux_prom_registers *regs, int nregs)
{
if(num_obio_ranges)
prom_adjust_regs(regs, nregs, promlib_obio_ranges, num_obio_ranges);
}
EXPORT_SYMBOL(prom_apply_obio_ranges);
void __init prom_ranges_init(void)
{
phandle node, obio_node;
int success;
num_obio_ranges = 0;
/* Check for obio and sbus ranges. */
node = prom_getchild(prom_root_node);
obio_node = prom_searchsiblings(node, "obio");
if(obio_node) {
success = prom_getproperty(obio_node, "ranges",
(char *) promlib_obio_ranges,
sizeof(promlib_obio_ranges));
if(success != -1)
num_obio_ranges = (success/sizeof(struct linux_prom_ranges));
}
if(num_obio_ranges)
prom_printf("PROMLIB: obio_ranges %d\n", num_obio_ranges);
}
void prom_apply_generic_ranges(phandle node, phandle parent,
struct linux_prom_registers *regs, int nregs)
{
int success;
int num_ranges;
struct linux_prom_ranges ranges[PROMREG_MAX];
success = prom_getproperty(node, "ranges",
(char *) ranges,
sizeof (ranges));
if (success != -1) {
num_ranges = (success/sizeof(struct linux_prom_ranges));
if (parent) {
struct linux_prom_ranges parent_ranges[PROMREG_MAX];
int num_parent_ranges;
success = prom_getproperty(parent, "ranges",
(char *) parent_ranges,
sizeof (parent_ranges));
if (success != -1) {
num_parent_ranges = (success/sizeof(struct linux_prom_ranges));
prom_adjust_ranges (ranges, num_ranges, parent_ranges, num_parent_ranges);
}
}
prom_adjust_regs(regs, nregs, ranges, num_ranges);
}
}
| gpl-2.0 |
igloocommunity/igloo-kernel | sound/oss/midibuf.c | 10632 | 8827 | /*
* sound/oss/midibuf.c
*
* Device file manager for /dev/midi#
*/
/*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*/
/*
* Thomas Sailer : ioctl code reworked (vmalloc/vfree removed)
*/
#include <linux/stddef.h>
#include <linux/kmod.h>
#include <linux/spinlock.h>
#define MIDIBUF_C
#include "sound_config.h"
/*
* Don't make MAX_QUEUE_SIZE larger than 4000
*/
#define MAX_QUEUE_SIZE 4000
static wait_queue_head_t midi_sleeper[MAX_MIDI_DEV];
static wait_queue_head_t input_sleeper[MAX_MIDI_DEV];
struct midi_buf
{
int len, head, tail;
unsigned char queue[MAX_QUEUE_SIZE];
};
struct midi_parms
{
long prech_timeout; /*
* Timeout before the first ch
*/
};
static struct midi_buf *midi_out_buf[MAX_MIDI_DEV] = {NULL};
static struct midi_buf *midi_in_buf[MAX_MIDI_DEV] = {NULL};
static struct midi_parms parms[MAX_MIDI_DEV];
static void midi_poll(unsigned long dummy);
static DEFINE_TIMER(poll_timer, midi_poll, 0, 0);
static volatile int open_devs;
static DEFINE_SPINLOCK(lock);
#define DATA_AVAIL(q) (q->len)
#define SPACE_AVAIL(q) (MAX_QUEUE_SIZE - q->len)
#define QUEUE_BYTE(q, data) \
if (SPACE_AVAIL(q)) \
{ \
unsigned long flags; \
spin_lock_irqsave(&lock, flags); \
q->queue[q->tail] = (data); \
q->len++; q->tail = (q->tail+1) % MAX_QUEUE_SIZE; \
spin_unlock_irqrestore(&lock, flags); \
}
#define REMOVE_BYTE(q, data) \
if (DATA_AVAIL(q)) \
{ \
unsigned long flags; \
spin_lock_irqsave(&lock, flags); \
data = q->queue[q->head]; \
q->len--; q->head = (q->head+1) % MAX_QUEUE_SIZE; \
spin_unlock_irqrestore(&lock, flags); \
}
static void drain_midi_queue(int dev)
{
/*
* Give the Midi driver time to drain its output queues
*/
if (midi_devs[dev]->buffer_status != NULL)
while (!signal_pending(current) && midi_devs[dev]->buffer_status(dev))
interruptible_sleep_on_timeout(&midi_sleeper[dev],
HZ/10);
}
static void midi_input_intr(int dev, unsigned char data)
{
if (midi_in_buf[dev] == NULL)
return;
if (data == 0xfe) /*
* Active sensing
*/
return; /*
* Ignore
*/
if (SPACE_AVAIL(midi_in_buf[dev])) {
QUEUE_BYTE(midi_in_buf[dev], data);
wake_up(&input_sleeper[dev]);
}
}
static void midi_output_intr(int dev)
{
/*
* Currently NOP
*/
}
static void midi_poll(unsigned long dummy)
{
unsigned long flags;
int dev;
spin_lock_irqsave(&lock, flags);
if (open_devs)
{
for (dev = 0; dev < num_midis; dev++)
if (midi_devs[dev] != NULL && midi_out_buf[dev] != NULL)
{
while (DATA_AVAIL(midi_out_buf[dev]))
{
int ok;
int c = midi_out_buf[dev]->queue[midi_out_buf[dev]->head];
spin_unlock_irqrestore(&lock,flags);/* Give some time to others */
ok = midi_devs[dev]->outputc(dev, c);
spin_lock_irqsave(&lock, flags);
if (!ok)
break;
midi_out_buf[dev]->head = (midi_out_buf[dev]->head + 1) % MAX_QUEUE_SIZE;
midi_out_buf[dev]->len--;
}
if (DATA_AVAIL(midi_out_buf[dev]) < 100)
wake_up(&midi_sleeper[dev]);
}
poll_timer.expires = (1) + jiffies;
add_timer(&poll_timer);
/*
* Come back later
*/
}
spin_unlock_irqrestore(&lock, flags);
}
int MIDIbuf_open(int dev, struct file *file)
{
int mode, err;
dev = dev >> 4;
mode = translate_mode(file);
if (num_midis > MAX_MIDI_DEV)
{
printk(KERN_ERR "midi: Too many midi interfaces\n");
num_midis = MAX_MIDI_DEV;
}
if (dev < 0 || dev >= num_midis || midi_devs[dev] == NULL)
return -ENXIO;
/*
* Interrupts disabled. Be careful
*/
module_put(midi_devs[dev]->owner);
if ((err = midi_devs[dev]->open(dev, mode,
midi_input_intr, midi_output_intr)) < 0)
return err;
parms[dev].prech_timeout = MAX_SCHEDULE_TIMEOUT;
midi_in_buf[dev] = vmalloc(sizeof(struct midi_buf));
if (midi_in_buf[dev] == NULL)
{
printk(KERN_WARNING "midi: Can't allocate buffer\n");
midi_devs[dev]->close(dev);
return -EIO;
}
midi_in_buf[dev]->len = midi_in_buf[dev]->head = midi_in_buf[dev]->tail = 0;
midi_out_buf[dev] = vmalloc(sizeof(struct midi_buf));
if (midi_out_buf[dev] == NULL)
{
printk(KERN_WARNING "midi: Can't allocate buffer\n");
midi_devs[dev]->close(dev);
vfree(midi_in_buf[dev]);
midi_in_buf[dev] = NULL;
return -EIO;
}
midi_out_buf[dev]->len = midi_out_buf[dev]->head = midi_out_buf[dev]->tail = 0;
open_devs++;
init_waitqueue_head(&midi_sleeper[dev]);
init_waitqueue_head(&input_sleeper[dev]);
if (open_devs < 2) /* This was first open */
{
poll_timer.expires = 1 + jiffies;
add_timer(&poll_timer); /* Start polling */
}
return err;
}
void MIDIbuf_release(int dev, struct file *file)
{
int mode;
dev = dev >> 4;
mode = translate_mode(file);
if (dev < 0 || dev >= num_midis || midi_devs[dev] == NULL)
return;
/*
* Wait until the queue is empty
*/
if (mode != OPEN_READ)
{
midi_devs[dev]->outputc(dev, 0xfe); /*
* Active sensing to shut the
* devices
*/
while (!signal_pending(current) && DATA_AVAIL(midi_out_buf[dev]))
interruptible_sleep_on(&midi_sleeper[dev]);
/*
* Sync
*/
drain_midi_queue(dev); /*
* Ensure the output queues are empty
*/
}
midi_devs[dev]->close(dev);
open_devs--;
if (open_devs == 0)
del_timer_sync(&poll_timer);
vfree(midi_in_buf[dev]);
vfree(midi_out_buf[dev]);
midi_in_buf[dev] = NULL;
midi_out_buf[dev] = NULL;
module_put(midi_devs[dev]->owner);
}
int MIDIbuf_write(int dev, struct file *file, const char __user *buf, int count)
{
int c, n, i;
unsigned char tmp_data;
dev = dev >> 4;
if (!count)
return 0;
c = 0;
while (c < count)
{
n = SPACE_AVAIL(midi_out_buf[dev]);
if (n == 0) { /*
* No space just now.
*/
if (file->f_flags & O_NONBLOCK) {
c = -EAGAIN;
goto out;
}
interruptible_sleep_on(&midi_sleeper[dev]);
if (signal_pending(current))
{
c = -EINTR;
goto out;
}
n = SPACE_AVAIL(midi_out_buf[dev]);
}
if (n > (count - c))
n = count - c;
for (i = 0; i < n; i++)
{
/* BROKE BROKE BROKE - CAN'T DO THIS WITH CLI !! */
/* yes, think the same, so I removed the cli() brackets
QUEUE_BYTE is protected against interrupts */
if (copy_from_user((char *) &tmp_data, &(buf)[c], 1)) {
c = -EFAULT;
goto out;
}
QUEUE_BYTE(midi_out_buf[dev], tmp_data);
c++;
}
}
out:
return c;
}
int MIDIbuf_read(int dev, struct file *file, char __user *buf, int count)
{
int n, c = 0;
unsigned char tmp_data;
dev = dev >> 4;
if (!DATA_AVAIL(midi_in_buf[dev])) { /*
* No data yet, wait
*/
if (file->f_flags & O_NONBLOCK) {
c = -EAGAIN;
goto out;
}
interruptible_sleep_on_timeout(&input_sleeper[dev],
parms[dev].prech_timeout);
if (signal_pending(current))
c = -EINTR; /* The user is getting restless */
}
if (c == 0 && DATA_AVAIL(midi_in_buf[dev])) /*
* Got some bytes
*/
{
n = DATA_AVAIL(midi_in_buf[dev]);
if (n > count)
n = count;
c = 0;
while (c < n)
{
char *fixit;
REMOVE_BYTE(midi_in_buf[dev], tmp_data);
fixit = (char *) &tmp_data;
/* BROKE BROKE BROKE */
/* yes removed the cli() brackets again
should q->len,tail&head be atomic_t? */
if (copy_to_user(&(buf)[c], fixit, 1)) {
c = -EFAULT;
goto out;
}
c++;
}
}
out:
return c;
}
int MIDIbuf_ioctl(int dev, struct file *file,
unsigned int cmd, void __user *arg)
{
int val;
dev = dev >> 4;
if (((cmd >> 8) & 0xff) == 'C')
{
if (midi_devs[dev]->coproc) /* Coprocessor ioctl */
return midi_devs[dev]->coproc->ioctl(midi_devs[dev]->coproc->devc, cmd, arg, 0);
/* printk("/dev/midi%d: No coprocessor for this device\n", dev);*/
return -ENXIO;
}
else
{
switch (cmd)
{
case SNDCTL_MIDI_PRETIME:
if (get_user(val, (int __user *)arg))
return -EFAULT;
if (val < 0)
val = 0;
val = (HZ * val) / 10;
parms[dev].prech_timeout = val;
return put_user(val, (int __user *)arg);
default:
if (!midi_devs[dev]->ioctl)
return -EINVAL;
return midi_devs[dev]->ioctl(dev, cmd, arg);
}
}
}
/* No kernel lock - fine */
unsigned int MIDIbuf_poll(int dev, struct file *file, poll_table * wait)
{
unsigned int mask = 0;
dev = dev >> 4;
/* input */
poll_wait(file, &input_sleeper[dev], wait);
if (DATA_AVAIL(midi_in_buf[dev]))
mask |= POLLIN | POLLRDNORM;
/* output */
poll_wait(file, &midi_sleeper[dev], wait);
if (!SPACE_AVAIL(midi_out_buf[dev]))
mask |= POLLOUT | POLLWRNORM;
return mask;
}
int MIDIbuf_avail(int dev)
{
if (midi_in_buf[dev])
return DATA_AVAIL (midi_in_buf[dev]);
return 0;
}
EXPORT_SYMBOL(MIDIbuf_avail);
| gpl-2.0 |
AICP/kernel_htc_m7 | drivers/net/fddi/skfp/ess.c | 12680 | 19287 | /******************************************************************************
*
* (C)Copyright 1998,1999 SysKonnect,
* a business unit of Schneider & Koch & Co. Datensysteme GmbH.
*
* See the file "skfddi.c" for further information.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The information in this file is provided "AS IS" without warranty.
*
******************************************************************************/
/*
* *******************************************************************
* This SBA code implements the Synchronous Bandwidth Allocation
* functions described in the "FDDI Synchronous Forum Implementer's
* Agreement" dated December 1th, 1993.
* *******************************************************************
*
* PURPOSE: The purpose of this function is to control
* synchronous allocations on a single FDDI segment.
* Allocations are limited to the primary FDDI ring.
* The SBM provides recovery mechanisms to recover
* unused bandwidth also resolves T_Neg and
* reconfiguration changes. Many of the SBM state
* machine inputs are sourced by the underlying
* FDDI sub-system supporting the SBA application.
*
* *******************************************************************
*/
#include "h/types.h"
#include "h/fddi.h"
#include "h/smc.h"
#include "h/smt_p.h"
#ifndef SLIM_SMT
#ifdef ESS
#ifndef lint
static const char ID_sccs[] = "@(#)ess.c 1.10 96/02/23 (C) SK" ;
#define LINT_USE(x)
#else
#define LINT_USE(x) (x)=(x)
#endif
#define MS2BCLK(x) ((x)*12500L)
/*
-------------------------------------------------------------
LOCAL VARIABLES:
-------------------------------------------------------------
*/
static const u_short plist_raf_alc_res[] = { SMT_P0012, SMT_P320B, SMT_P320F,
SMT_P3210, SMT_P0019, SMT_P001A,
SMT_P001D, 0 } ;
static const u_short plist_raf_chg_req[] = { SMT_P320B, SMT_P320F, SMT_P3210,
SMT_P001A, 0 } ;
static const struct fddi_addr smt_sba_da = {{0x80,0x01,0x43,0x00,0x80,0x0C}} ;
static const struct fddi_addr null_addr = {{0,0,0,0,0,0}} ;
/*
-------------------------------------------------------------
GLOBAL VARIABLES:
-------------------------------------------------------------
*/
/*
-------------------------------------------------------------
LOCAL FUNCTIONS:
-------------------------------------------------------------
*/
static void ess_send_response(struct s_smc *smc, struct smt_header *sm,
int sba_cmd);
static void ess_config_fifo(struct s_smc *smc);
static void ess_send_alc_req(struct s_smc *smc);
static void ess_send_frame(struct s_smc *smc, SMbuf *mb);
/*
-------------------------------------------------------------
EXTERNAL FUNCTIONS:
-------------------------------------------------------------
*/
/*
-------------------------------------------------------------
PUBLIC FUNCTIONS:
-------------------------------------------------------------
*/
void ess_timer_poll(struct s_smc *smc);
void ess_para_change(struct s_smc *smc);
int ess_raf_received_pack(struct s_smc *smc, SMbuf *mb, struct smt_header *sm,
int fs);
static int process_bw_alloc(struct s_smc *smc, long int payload, long int overhead);
/*
* --------------------------------------------------------------------------
* End Station Support (ESS)
* --------------------------------------------------------------------------
*/
/*
* evaluate the RAF frame
*/
int ess_raf_received_pack(struct s_smc *smc, SMbuf *mb, struct smt_header *sm,
int fs)
{
void *p ; /* universal pointer */
struct smt_p_0016 *cmd ; /* para: command for the ESS */
SMbuf *db ;
u_long msg_res_type ; /* recource type */
u_long payload, overhead ;
int local ;
int i ;
/*
* Message Processing Code
*/
local = ((fs & L_INDICATOR) != 0) ;
/*
* get the resource type
*/
if (!(p = (void *) sm_to_para(smc,sm,SMT_P0015))) {
DB_ESS("ESS: RAF frame error, parameter type not found\n",0,0) ;
return fs;
}
msg_res_type = ((struct smt_p_0015 *)p)->res_type ;
/*
* get the pointer to the ESS command
*/
if (!(cmd = (struct smt_p_0016 *) sm_to_para(smc,sm,SMT_P0016))) {
/*
* error in frame: para ESS command was not found
*/
DB_ESS("ESS: RAF frame error, parameter command not found\n",0,0);
return fs;
}
DB_ESSN(2,"fc %x ft %x\n",sm->smt_class,sm->smt_type) ;
DB_ESSN(2,"ver %x tran %lx\n",sm->smt_version,sm->smt_tid) ;
DB_ESSN(2,"stn_id %s\n",addr_to_string(&sm->smt_source),0) ;
DB_ESSN(2,"infolen %x res %x\n",sm->smt_len, msg_res_type) ;
DB_ESSN(2,"sbacmd %x\n",cmd->sba_cmd,0) ;
/*
* evaluate the ESS command
*/
switch (cmd->sba_cmd) {
/*
* Process an ESS Allocation Request
*/
case REQUEST_ALLOCATION :
/*
* check for an RAF Request (Allocation Request)
*/
if (sm->smt_type == SMT_REQUEST) {
/*
* process the Allocation request only if the frame is
* local and no static allocation is used
*/
if (!local || smc->mib.fddiESSPayload)
return fs;
p = (void *) sm_to_para(smc,sm,SMT_P0019) ;
for (i = 0; i < 5; i++) {
if (((struct smt_p_0019 *)p)->alloc_addr.a[i]) {
return fs;
}
}
/*
* Note: The Application should send a LAN_LOC_FRAME.
* The ESS do not send the Frame to the network!
*/
smc->ess.alloc_trans_id = sm->smt_tid ;
DB_ESS("ESS: save Alloc Req Trans ID %lx\n",sm->smt_tid,0);
p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
((struct smt_p_320f *)p)->mib_payload =
smc->mib.a[PATH0].fddiPATHSbaPayload ;
p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
((struct smt_p_3210 *)p)->mib_overhead =
smc->mib.a[PATH0].fddiPATHSbaOverhead ;
sm->smt_dest = smt_sba_da ;
if (smc->ess.local_sba_active)
return fs | I_INDICATOR;
if (!(db = smt_get_mbuf(smc)))
return fs;
db->sm_len = mb->sm_len ;
db->sm_off = mb->sm_off ;
memcpy(((char *)(db->sm_data+db->sm_off)),(char *)sm,
(int)db->sm_len) ;
dump_smt(smc,
(struct smt_header *)(db->sm_data+db->sm_off),
"RAF") ;
smt_send_frame(smc,db,FC_SMT_INFO,0) ;
return fs;
}
/*
* The RAF frame is an Allocation Response !
* check the parameters
*/
if (smt_check_para(smc,sm,plist_raf_alc_res)) {
DB_ESS("ESS: RAF with para problem, ignoring\n",0,0) ;
return fs;
}
/*
* VERIFY THE FRAME IS WELL BUILT:
*
* 1. path index = primary ring only
* 2. resource type = sync bw only
* 3. trans action id = alloc_trans_id
* 4. reason code = success
*
* If any are violated, discard the RAF frame
*/
if ((((struct smt_p_320b *)sm_to_para(smc,sm,SMT_P320B))->path_index
!= PRIMARY_RING) ||
(msg_res_type != SYNC_BW) ||
(((struct smt_p_reason *)sm_to_para(smc,sm,SMT_P0012))->rdf_reason
!= SMT_RDF_SUCCESS) ||
(sm->smt_tid != smc->ess.alloc_trans_id)) {
DB_ESS("ESS: Allocation Response not accepted\n",0,0) ;
return fs;
}
/*
* Extract message parameters
*/
p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
if (!p) {
printk(KERN_ERR "ESS: sm_to_para failed");
return fs;
}
payload = ((struct smt_p_320f *)p)->mib_payload ;
p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
if (!p) {
printk(KERN_ERR "ESS: sm_to_para failed");
return fs;
}
overhead = ((struct smt_p_3210 *)p)->mib_overhead ;
DB_ESSN(2,"payload= %lx overhead= %lx\n",payload,overhead) ;
/*
* process the bandwidth allocation
*/
(void)process_bw_alloc(smc,(long)payload,(long)overhead) ;
return fs;
/* end of Process Allocation Request */
/*
* Process an ESS Change Request
*/
case CHANGE_ALLOCATION :
/*
* except only replies
*/
if (sm->smt_type != SMT_REQUEST) {
DB_ESS("ESS: Do not process Change Responses\n",0,0) ;
return fs;
}
/*
* check the para for the Change Request
*/
if (smt_check_para(smc,sm,plist_raf_chg_req)) {
DB_ESS("ESS: RAF with para problem, ignoring\n",0,0) ;
return fs;
}
/*
* Verify the path index and resource
* type are correct. If any of
* these are false, don't process this
* change request frame.
*/
if ((((struct smt_p_320b *)sm_to_para(smc,sm,SMT_P320B))->path_index
!= PRIMARY_RING) || (msg_res_type != SYNC_BW)) {
DB_ESS("ESS: RAF frame with para problem, ignoring\n",0,0) ;
return fs;
}
/*
* Extract message queue parameters
*/
p = (void *) sm_to_para(smc,sm,SMT_P320F) ;
payload = ((struct smt_p_320f *)p)->mib_payload ;
p = (void *) sm_to_para(smc,sm,SMT_P3210) ;
overhead = ((struct smt_p_3210 *)p)->mib_overhead ;
DB_ESSN(2,"ESS: Change Request from %s\n",
addr_to_string(&sm->smt_source),0) ;
DB_ESSN(2,"payload= %lx overhead= %lx\n",payload,overhead) ;
/*
* process the bandwidth allocation
*/
if(!process_bw_alloc(smc,(long)payload,(long)overhead))
return fs;
/*
* send an RAF Change Reply
*/
ess_send_response(smc,sm,CHANGE_ALLOCATION) ;
return fs;
/* end of Process Change Request */
/*
* Process Report Response
*/
case REPORT_ALLOCATION :
/*
* except only requests
*/
if (sm->smt_type != SMT_REQUEST) {
DB_ESS("ESS: Do not process a Report Reply\n",0,0) ;
return fs;
}
DB_ESSN(2,"ESS: Report Request from %s\n",
addr_to_string(&(sm->smt_source)),0) ;
/*
* verify that the resource type is sync bw only
*/
if (msg_res_type != SYNC_BW) {
DB_ESS("ESS: ignoring RAF with para problem\n",0,0) ;
return fs;
}
/*
* send an RAF Change Reply
*/
ess_send_response(smc,sm,REPORT_ALLOCATION) ;
return fs;
/* end of Process Report Request */
default:
/*
* error in frame
*/
DB_ESS("ESS: ignoring RAF with bad sba_cmd\n",0,0) ;
break ;
}
return fs;
}
/*
* determines the synchronous bandwidth, set the TSYNC register and the
* mib variables SBAPayload, SBAOverhead and fddiMACT-NEG.
*/
static int process_bw_alloc(struct s_smc *smc, long int payload, long int overhead)
{
/*
* determine the synchronous bandwidth (sync_bw) in bytes per T-NEG,
* if the payload is greater than zero.
* For the SBAPayload and the SBAOverhead we have the following
* unite quations
* _ _
* | bytes |
* SBAPayload = | 8000 ------ |
* | s |
* - -
* _ _
* | bytes |
* SBAOverhead = | ------ |
* | T-NEG |
* - -
*
* T-NEG is described by the equation:
*
* (-) fddiMACT-NEG
* T-NEG = -------------------
* 12500000 1/s
*
* The number of bytes we are able to send is the payload
* plus the overhead.
*
* bytes T-NEG SBAPayload 8000 bytes/s
* sync_bw = SBAOverhead ------ + -----------------------------
* T-NEG T-NEG
*
*
* 1
* sync_bw = SBAOverhead + ---- (-)fddiMACT-NEG * SBAPayload
* 1562
*
*/
/*
* set the mib attributes fddiPATHSbaOverhead, fddiPATHSbaPayload
*/
/* if (smt_set_obj(smc,SMT_P320F,payload,S_SET)) {
DB_ESS("ESS: SMT does not accept the payload value\n",0,0) ;
return FALSE;
}
if (smt_set_obj(smc,SMT_P3210,overhead,S_SET)) {
DB_ESS("ESS: SMT does not accept the overhead value\n",0,0) ;
return FALSE;
} */
/* premliminary */
if (payload > MAX_PAYLOAD || overhead > 5000) {
DB_ESS("ESS: payload / overhead not accepted\n",0,0) ;
return FALSE;
}
/*
* start the iterative allocation process if the payload or the overhead
* are smaller than the parsed values
*/
if (smc->mib.fddiESSPayload &&
((u_long)payload != smc->mib.fddiESSPayload ||
(u_long)overhead != smc->mib.fddiESSOverhead)) {
smc->ess.raf_act_timer_poll = TRUE ;
smc->ess.timer_count = 0 ;
}
/*
* evulate the Payload
*/
if (payload) {
DB_ESSN(2,"ESS: turn SMT_ST_SYNC_SERVICE bit on\n",0,0) ;
smc->ess.sync_bw_available = TRUE ;
smc->ess.sync_bw = overhead -
(long)smc->mib.m[MAC0].fddiMACT_Neg *
payload / 1562 ;
}
else {
DB_ESSN(2,"ESS: turn SMT_ST_SYNC_SERVICE bit off\n",0,0) ;
smc->ess.sync_bw_available = FALSE ;
smc->ess.sync_bw = 0 ;
overhead = 0 ;
}
smc->mib.a[PATH0].fddiPATHSbaPayload = payload ;
smc->mib.a[PATH0].fddiPATHSbaOverhead = overhead ;
DB_ESSN(2,"tsync = %lx\n",smc->ess.sync_bw,0) ;
ess_config_fifo(smc) ;
set_formac_tsync(smc,smc->ess.sync_bw) ;
return TRUE;
}
static void ess_send_response(struct s_smc *smc, struct smt_header *sm,
int sba_cmd)
{
struct smt_sba_chg *chg ;
SMbuf *mb ;
void *p ;
/*
* get and initialize the response frame
*/
if (sba_cmd == CHANGE_ALLOCATION) {
if (!(mb=smt_build_frame(smc,SMT_RAF,SMT_REPLY,
sizeof(struct smt_sba_chg))))
return ;
}
else {
if (!(mb=smt_build_frame(smc,SMT_RAF,SMT_REPLY,
sizeof(struct smt_sba_rep_res))))
return ;
}
chg = smtod(mb,struct smt_sba_chg *) ;
chg->smt.smt_tid = sm->smt_tid ;
chg->smt.smt_dest = sm->smt_source ;
/* set P15 */
chg->s_type.para.p_type = SMT_P0015 ;
chg->s_type.para.p_len = sizeof(struct smt_p_0015) - PARA_LEN ;
chg->s_type.res_type = SYNC_BW ;
/* set P16 */
chg->cmd.para.p_type = SMT_P0016 ;
chg->cmd.para.p_len = sizeof(struct smt_p_0016) - PARA_LEN ;
chg->cmd.sba_cmd = sba_cmd ;
/* set P320B */
chg->path.para.p_type = SMT_P320B ;
chg->path.para.p_len = sizeof(struct smt_p_320b) - PARA_LEN ;
chg->path.mib_index = SBAPATHINDEX ;
chg->path.path_pad = 0;
chg->path.path_index = PRIMARY_RING ;
/* set P320F */
chg->payload.para.p_type = SMT_P320F ;
chg->payload.para.p_len = sizeof(struct smt_p_320f) - PARA_LEN ;
chg->payload.mib_index = SBAPATHINDEX ;
chg->payload.mib_payload = smc->mib.a[PATH0].fddiPATHSbaPayload ;
/* set P3210 */
chg->overhead.para.p_type = SMT_P3210 ;
chg->overhead.para.p_len = sizeof(struct smt_p_3210) - PARA_LEN ;
chg->overhead.mib_index = SBAPATHINDEX ;
chg->overhead.mib_overhead = smc->mib.a[PATH0].fddiPATHSbaOverhead ;
if (sba_cmd == CHANGE_ALLOCATION) {
/* set P1A */
chg->cat.para.p_type = SMT_P001A ;
chg->cat.para.p_len = sizeof(struct smt_p_001a) - PARA_LEN ;
p = (void *) sm_to_para(smc,sm,SMT_P001A) ;
chg->cat.category = ((struct smt_p_001a *)p)->category ;
}
dump_smt(smc,(struct smt_header *)chg,"RAF") ;
ess_send_frame(smc,mb) ;
}
void ess_timer_poll(struct s_smc *smc)
{
if (!smc->ess.raf_act_timer_poll)
return ;
DB_ESSN(2,"ESS: timer_poll\n",0,0) ;
smc->ess.timer_count++ ;
if (smc->ess.timer_count == 10) {
smc->ess.timer_count = 0 ;
ess_send_alc_req(smc) ;
}
}
static void ess_send_alc_req(struct s_smc *smc)
{
struct smt_sba_alc_req *req ;
SMbuf *mb ;
/*
* send never allocation request where the requested payload and
* overhead is zero or deallocate bandwidth when no bandwidth is
* parsed
*/
if (!smc->mib.fddiESSPayload) {
smc->mib.fddiESSOverhead = 0 ;
}
else {
if (!smc->mib.fddiESSOverhead)
smc->mib.fddiESSOverhead = DEFAULT_OV ;
}
if (smc->mib.fddiESSOverhead ==
smc->mib.a[PATH0].fddiPATHSbaOverhead &&
smc->mib.fddiESSPayload ==
smc->mib.a[PATH0].fddiPATHSbaPayload){
smc->ess.raf_act_timer_poll = FALSE ;
smc->ess.timer_count = 7 ; /* next RAF alc req after 3 s */
return ;
}
/*
* get and initialize the response frame
*/
if (!(mb=smt_build_frame(smc,SMT_RAF,SMT_REQUEST,
sizeof(struct smt_sba_alc_req))))
return ;
req = smtod(mb,struct smt_sba_alc_req *) ;
req->smt.smt_tid = smc->ess.alloc_trans_id = smt_get_tid(smc) ;
req->smt.smt_dest = smt_sba_da ;
/* set P15 */
req->s_type.para.p_type = SMT_P0015 ;
req->s_type.para.p_len = sizeof(struct smt_p_0015) - PARA_LEN ;
req->s_type.res_type = SYNC_BW ;
/* set P16 */
req->cmd.para.p_type = SMT_P0016 ;
req->cmd.para.p_len = sizeof(struct smt_p_0016) - PARA_LEN ;
req->cmd.sba_cmd = REQUEST_ALLOCATION ;
/*
* set the parameter type and parameter length of all used
* parameters
*/
/* set P320B */
req->path.para.p_type = SMT_P320B ;
req->path.para.p_len = sizeof(struct smt_p_320b) - PARA_LEN ;
req->path.mib_index = SBAPATHINDEX ;
req->path.path_pad = 0;
req->path.path_index = PRIMARY_RING ;
/* set P0017 */
req->pl_req.para.p_type = SMT_P0017 ;
req->pl_req.para.p_len = sizeof(struct smt_p_0017) - PARA_LEN ;
req->pl_req.sba_pl_req = smc->mib.fddiESSPayload -
smc->mib.a[PATH0].fddiPATHSbaPayload ;
/* set P0018 */
req->ov_req.para.p_type = SMT_P0018 ;
req->ov_req.para.p_len = sizeof(struct smt_p_0018) - PARA_LEN ;
req->ov_req.sba_ov_req = smc->mib.fddiESSOverhead -
smc->mib.a[PATH0].fddiPATHSbaOverhead ;
/* set P320F */
req->payload.para.p_type = SMT_P320F ;
req->payload.para.p_len = sizeof(struct smt_p_320f) - PARA_LEN ;
req->payload.mib_index = SBAPATHINDEX ;
req->payload.mib_payload = smc->mib.a[PATH0].fddiPATHSbaPayload ;
/* set P3210 */
req->overhead.para.p_type = SMT_P3210 ;
req->overhead.para.p_len = sizeof(struct smt_p_3210) - PARA_LEN ;
req->overhead.mib_index = SBAPATHINDEX ;
req->overhead.mib_overhead = smc->mib.a[PATH0].fddiPATHSbaOverhead ;
/* set P19 */
req->a_addr.para.p_type = SMT_P0019 ;
req->a_addr.para.p_len = sizeof(struct smt_p_0019) - PARA_LEN ;
req->a_addr.sba_pad = 0;
req->a_addr.alloc_addr = null_addr ;
/* set P1A */
req->cat.para.p_type = SMT_P001A ;
req->cat.para.p_len = sizeof(struct smt_p_001a) - PARA_LEN ;
req->cat.category = smc->mib.fddiESSCategory ;
/* set P1B */
req->tneg.para.p_type = SMT_P001B ;
req->tneg.para.p_len = sizeof(struct smt_p_001b) - PARA_LEN ;
req->tneg.max_t_neg = smc->mib.fddiESSMaxTNeg ;
/* set P1C */
req->segm.para.p_type = SMT_P001C ;
req->segm.para.p_len = sizeof(struct smt_p_001c) - PARA_LEN ;
req->segm.min_seg_siz = smc->mib.fddiESSMinSegmentSize ;
dump_smt(smc,(struct smt_header *)req,"RAF") ;
ess_send_frame(smc,mb) ;
}
static void ess_send_frame(struct s_smc *smc, SMbuf *mb)
{
/*
* check if the frame must be send to the own ESS
*/
if (smc->ess.local_sba_active) {
/*
* Send the Change Reply to the local SBA
*/
DB_ESS("ESS:Send to the local SBA\n",0,0) ;
if (!smc->ess.sba_reply_pend)
smc->ess.sba_reply_pend = mb ;
else {
DB_ESS("Frame is lost - another frame was pending\n",0,0);
smt_free_mbuf(smc,mb) ;
}
}
else {
/*
* Send the SBA RAF Change Reply to the network
*/
DB_ESS("ESS:Send to the network\n",0,0) ;
smt_send_frame(smc,mb,FC_SMT_INFO,0) ;
}
}
void ess_para_change(struct s_smc *smc)
{
(void)process_bw_alloc(smc,(long)smc->mib.a[PATH0].fddiPATHSbaPayload,
(long)smc->mib.a[PATH0].fddiPATHSbaOverhead) ;
}
static void ess_config_fifo(struct s_smc *smc)
{
/*
* if nothing to do exit
*/
if (smc->mib.a[PATH0].fddiPATHSbaPayload) {
if (smc->hw.fp.fifo.fifo_config_mode & SYNC_TRAFFIC_ON &&
(smc->hw.fp.fifo.fifo_config_mode&SEND_ASYNC_AS_SYNC) ==
smc->mib.fddiESSSynchTxMode) {
return ;
}
}
else {
if (!(smc->hw.fp.fifo.fifo_config_mode & SYNC_TRAFFIC_ON)) {
return ;
}
}
/*
* split up the FIFO and reinitialize the queues
*/
formac_reinit_tx(smc) ;
}
#endif /* ESS */
#endif /* no SLIM_SMT */
| gpl-2.0 |
veo-labs/linux-veobox | drivers/media/usb/uvc/uvc_driver.c | 137 | 70777 | /*
* uvc_driver.c -- USB Video Class driver
*
* Copyright (C) 2005-2010
* Laurent Pinchart (laurent.pinchart@ideasonboard.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include <linux/atomic.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
#include <linux/version.h>
#include <asm/unaligned.h>
#include <media/v4l2-common.h>
#include "uvcvideo.h"
#define DRIVER_AUTHOR "Laurent Pinchart " \
"<laurent.pinchart@ideasonboard.com>"
#define DRIVER_DESC "USB Video Class driver"
unsigned int uvc_clock_param = CLOCK_MONOTONIC;
unsigned int uvc_no_drop_param;
static unsigned int uvc_quirks_param = -1;
unsigned int uvc_trace_param;
unsigned int uvc_timeout_param = UVC_CTRL_STREAMING_TIMEOUT;
/* ------------------------------------------------------------------------
* Video formats
*/
static struct uvc_format_desc uvc_fmts[] = {
{
.name = "YUV 4:2:2 (YUYV)",
.guid = UVC_GUID_FORMAT_YUY2,
.fcc = V4L2_PIX_FMT_YUYV,
},
{
.name = "YUV 4:2:2 (YUYV)",
.guid = UVC_GUID_FORMAT_YUY2_ISIGHT,
.fcc = V4L2_PIX_FMT_YUYV,
},
{
.name = "YUV 4:2:0 (NV12)",
.guid = UVC_GUID_FORMAT_NV12,
.fcc = V4L2_PIX_FMT_NV12,
},
{
.name = "MJPEG",
.guid = UVC_GUID_FORMAT_MJPEG,
.fcc = V4L2_PIX_FMT_MJPEG,
},
{
.name = "YVU 4:2:0 (YV12)",
.guid = UVC_GUID_FORMAT_YV12,
.fcc = V4L2_PIX_FMT_YVU420,
},
{
.name = "YUV 4:2:0 (I420)",
.guid = UVC_GUID_FORMAT_I420,
.fcc = V4L2_PIX_FMT_YUV420,
},
{
.name = "YUV 4:2:0 (M420)",
.guid = UVC_GUID_FORMAT_M420,
.fcc = V4L2_PIX_FMT_M420,
},
{
.name = "YUV 4:2:2 (UYVY)",
.guid = UVC_GUID_FORMAT_UYVY,
.fcc = V4L2_PIX_FMT_UYVY,
},
{
.name = "Greyscale 8-bit (Y800)",
.guid = UVC_GUID_FORMAT_Y800,
.fcc = V4L2_PIX_FMT_GREY,
},
{
.name = "Greyscale 8-bit (Y8 )",
.guid = UVC_GUID_FORMAT_Y8,
.fcc = V4L2_PIX_FMT_GREY,
},
{
.name = "Greyscale 10-bit (Y10 )",
.guid = UVC_GUID_FORMAT_Y10,
.fcc = V4L2_PIX_FMT_Y10,
},
{
.name = "Greyscale 12-bit (Y12 )",
.guid = UVC_GUID_FORMAT_Y12,
.fcc = V4L2_PIX_FMT_Y12,
},
{
.name = "Greyscale 16-bit (Y16 )",
.guid = UVC_GUID_FORMAT_Y16,
.fcc = V4L2_PIX_FMT_Y16,
},
{
.name = "BGGR Bayer (BY8 )",
.guid = UVC_GUID_FORMAT_BY8,
.fcc = V4L2_PIX_FMT_SBGGR8,
},
{
.name = "BGGR Bayer (BA81)",
.guid = UVC_GUID_FORMAT_BA81,
.fcc = V4L2_PIX_FMT_SBGGR8,
},
{
.name = "GBRG Bayer (GBRG)",
.guid = UVC_GUID_FORMAT_GBRG,
.fcc = V4L2_PIX_FMT_SGBRG8,
},
{
.name = "GRBG Bayer (GRBG)",
.guid = UVC_GUID_FORMAT_GRBG,
.fcc = V4L2_PIX_FMT_SGRBG8,
},
{
.name = "RGGB Bayer (RGGB)",
.guid = UVC_GUID_FORMAT_RGGB,
.fcc = V4L2_PIX_FMT_SRGGB8,
},
{
.name = "RGB565",
.guid = UVC_GUID_FORMAT_RGBP,
.fcc = V4L2_PIX_FMT_RGB565,
},
{
.name = "BGR 8:8:8 (BGR3)",
.guid = UVC_GUID_FORMAT_BGR3,
.fcc = V4L2_PIX_FMT_BGR24,
},
{
.name = "H.264",
.guid = UVC_GUID_FORMAT_H264,
.fcc = V4L2_PIX_FMT_H264,
},
};
/* ------------------------------------------------------------------------
* Utility functions
*/
struct usb_host_endpoint *uvc_find_endpoint(struct usb_host_interface *alts,
__u8 epaddr)
{
struct usb_host_endpoint *ep;
unsigned int i;
for (i = 0; i < alts->desc.bNumEndpoints; ++i) {
ep = &alts->endpoint[i];
if (ep->desc.bEndpointAddress == epaddr)
return ep;
}
return NULL;
}
static struct uvc_format_desc *uvc_format_by_guid(const __u8 guid[16])
{
unsigned int len = ARRAY_SIZE(uvc_fmts);
unsigned int i;
for (i = 0; i < len; ++i) {
if (memcmp(guid, uvc_fmts[i].guid, 16) == 0)
return &uvc_fmts[i];
}
return NULL;
}
static __u32 uvc_colorspace(const __u8 primaries)
{
static const __u8 colorprimaries[] = {
0,
V4L2_COLORSPACE_SRGB,
V4L2_COLORSPACE_470_SYSTEM_M,
V4L2_COLORSPACE_470_SYSTEM_BG,
V4L2_COLORSPACE_SMPTE170M,
V4L2_COLORSPACE_SMPTE240M,
};
if (primaries < ARRAY_SIZE(colorprimaries))
return colorprimaries[primaries];
return 0;
}
/* Simplify a fraction using a simple continued fraction decomposition. The
* idea here is to convert fractions such as 333333/10000000 to 1/30 using
* 32 bit arithmetic only. The algorithm is not perfect and relies upon two
* arbitrary parameters to remove non-significative terms from the simple
* continued fraction decomposition. Using 8 and 333 for n_terms and threshold
* respectively seems to give nice results.
*/
void uvc_simplify_fraction(uint32_t *numerator, uint32_t *denominator,
unsigned int n_terms, unsigned int threshold)
{
uint32_t *an;
uint32_t x, y, r;
unsigned int i, n;
an = kmalloc(n_terms * sizeof *an, GFP_KERNEL);
if (an == NULL)
return;
/* Convert the fraction to a simple continued fraction. See
* http://mathforum.org/dr.math/faq/faq.fractions.html
* Stop if the current term is bigger than or equal to the given
* threshold.
*/
x = *numerator;
y = *denominator;
for (n = 0; n < n_terms && y != 0; ++n) {
an[n] = x / y;
if (an[n] >= threshold) {
if (n < 2)
n++;
break;
}
r = x - an[n] * y;
x = y;
y = r;
}
/* Expand the simple continued fraction back to an integer fraction. */
x = 0;
y = 1;
for (i = n; i > 0; --i) {
r = y;
y = an[i-1] * y + x;
x = r;
}
*numerator = y;
*denominator = x;
kfree(an);
}
/* Convert a fraction to a frame interval in 100ns multiples. The idea here is
* to compute numerator / denominator * 10000000 using 32 bit fixed point
* arithmetic only.
*/
uint32_t uvc_fraction_to_interval(uint32_t numerator, uint32_t denominator)
{
uint32_t multiplier;
/* Saturate the result if the operation would overflow. */
if (denominator == 0 ||
numerator/denominator >= ((uint32_t)-1)/10000000)
return (uint32_t)-1;
/* Divide both the denominator and the multiplier by two until
* numerator * multiplier doesn't overflow. If anyone knows a better
* algorithm please let me know.
*/
multiplier = 10000000;
while (numerator > ((uint32_t)-1)/multiplier) {
multiplier /= 2;
denominator /= 2;
}
return denominator ? numerator * multiplier / denominator : 0;
}
/* ------------------------------------------------------------------------
* Terminal and unit management
*/
struct uvc_entity *uvc_entity_by_id(struct uvc_device *dev, int id)
{
struct uvc_entity *entity;
list_for_each_entry(entity, &dev->entities, list) {
if (entity->id == id)
return entity;
}
return NULL;
}
static struct uvc_entity *uvc_entity_by_reference(struct uvc_device *dev,
int id, struct uvc_entity *entity)
{
unsigned int i;
if (entity == NULL)
entity = list_entry(&dev->entities, struct uvc_entity, list);
list_for_each_entry_continue(entity, &dev->entities, list) {
for (i = 0; i < entity->bNrInPins; ++i)
if (entity->baSourceID[i] == id)
return entity;
}
return NULL;
}
static struct uvc_streaming *uvc_stream_by_id(struct uvc_device *dev, int id)
{
struct uvc_streaming *stream;
list_for_each_entry(stream, &dev->streams, list) {
if (stream->header.bTerminalLink == id)
return stream;
}
return NULL;
}
/* ------------------------------------------------------------------------
* Descriptors parsing
*/
static int uvc_parse_format(struct uvc_device *dev,
struct uvc_streaming *streaming, struct uvc_format *format,
__u32 **intervals, unsigned char *buffer, int buflen)
{
struct usb_interface *intf = streaming->intf;
struct usb_host_interface *alts = intf->cur_altsetting;
struct uvc_format_desc *fmtdesc;
struct uvc_frame *frame;
const unsigned char *start = buffer;
unsigned int width_multiplier = 1;
unsigned int interval;
unsigned int i, n;
__u8 ftype;
format->type = buffer[2];
format->index = buffer[3];
switch (buffer[2]) {
case UVC_VS_FORMAT_UNCOMPRESSED:
case UVC_VS_FORMAT_FRAME_BASED:
n = buffer[2] == UVC_VS_FORMAT_UNCOMPRESSED ? 27 : 28;
if (buflen < n) {
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d FORMAT error\n",
dev->udev->devnum,
alts->desc.bInterfaceNumber);
return -EINVAL;
}
/* Find the format descriptor from its GUID. */
fmtdesc = uvc_format_by_guid(&buffer[5]);
if (fmtdesc != NULL) {
strlcpy(format->name, fmtdesc->name,
sizeof format->name);
format->fcc = fmtdesc->fcc;
} else {
uvc_printk(KERN_INFO, "Unknown video format %pUl\n",
&buffer[5]);
snprintf(format->name, sizeof(format->name), "%pUl\n",
&buffer[5]);
format->fcc = 0;
}
format->bpp = buffer[21];
/* Some devices report a format that doesn't match what they
* really send.
*/
if (dev->quirks & UVC_QUIRK_FORCE_Y8) {
if (format->fcc == V4L2_PIX_FMT_YUYV) {
strlcpy(format->name, "Greyscale 8-bit (Y8 )",
sizeof(format->name));
format->fcc = V4L2_PIX_FMT_GREY;
format->bpp = 8;
width_multiplier = 2;
}
}
if (buffer[2] == UVC_VS_FORMAT_UNCOMPRESSED) {
ftype = UVC_VS_FRAME_UNCOMPRESSED;
} else {
ftype = UVC_VS_FRAME_FRAME_BASED;
if (buffer[27])
format->flags = UVC_FMT_FLAG_COMPRESSED;
}
break;
case UVC_VS_FORMAT_MJPEG:
if (buflen < 11) {
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d FORMAT error\n",
dev->udev->devnum,
alts->desc.bInterfaceNumber);
return -EINVAL;
}
strlcpy(format->name, "MJPEG", sizeof format->name);
format->fcc = V4L2_PIX_FMT_MJPEG;
format->flags = UVC_FMT_FLAG_COMPRESSED;
format->bpp = 0;
ftype = UVC_VS_FRAME_MJPEG;
break;
case UVC_VS_FORMAT_DV:
if (buflen < 9) {
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d FORMAT error\n",
dev->udev->devnum,
alts->desc.bInterfaceNumber);
return -EINVAL;
}
switch (buffer[8] & 0x7f) {
case 0:
strlcpy(format->name, "SD-DV", sizeof format->name);
break;
case 1:
strlcpy(format->name, "SDL-DV", sizeof format->name);
break;
case 2:
strlcpy(format->name, "HD-DV", sizeof format->name);
break;
default:
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d: unknown DV format %u\n",
dev->udev->devnum,
alts->desc.bInterfaceNumber, buffer[8]);
return -EINVAL;
}
strlcat(format->name, buffer[8] & (1 << 7) ? " 60Hz" : " 50Hz",
sizeof format->name);
format->fcc = V4L2_PIX_FMT_DV;
format->flags = UVC_FMT_FLAG_COMPRESSED | UVC_FMT_FLAG_STREAM;
format->bpp = 0;
ftype = 0;
/* Create a dummy frame descriptor. */
frame = &format->frame[0];
memset(&format->frame[0], 0, sizeof format->frame[0]);
frame->bFrameIntervalType = 1;
frame->dwDefaultFrameInterval = 1;
frame->dwFrameInterval = *intervals;
*(*intervals)++ = 1;
format->nframes = 1;
break;
case UVC_VS_FORMAT_MPEG2TS:
case UVC_VS_FORMAT_STREAM_BASED:
/* Not supported yet. */
default:
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d unsupported format %u\n",
dev->udev->devnum, alts->desc.bInterfaceNumber,
buffer[2]);
return -EINVAL;
}
uvc_trace(UVC_TRACE_DESCR, "Found format %s.\n", format->name);
buflen -= buffer[0];
buffer += buffer[0];
/* Parse the frame descriptors. Only uncompressed, MJPEG and frame
* based formats have frame descriptors.
*/
while (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE &&
buffer[2] == ftype) {
frame = &format->frame[format->nframes];
if (ftype != UVC_VS_FRAME_FRAME_BASED)
n = buflen > 25 ? buffer[25] : 0;
else
n = buflen > 21 ? buffer[21] : 0;
n = n ? n : 3;
if (buflen < 26 + 4*n) {
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d FRAME error\n", dev->udev->devnum,
alts->desc.bInterfaceNumber);
return -EINVAL;
}
frame->bFrameIndex = buffer[3];
frame->bmCapabilities = buffer[4];
frame->wWidth = get_unaligned_le16(&buffer[5])
* width_multiplier;
frame->wHeight = get_unaligned_le16(&buffer[7]);
frame->dwMinBitRate = get_unaligned_le32(&buffer[9]);
frame->dwMaxBitRate = get_unaligned_le32(&buffer[13]);
if (ftype != UVC_VS_FRAME_FRAME_BASED) {
frame->dwMaxVideoFrameBufferSize =
get_unaligned_le32(&buffer[17]);
frame->dwDefaultFrameInterval =
get_unaligned_le32(&buffer[21]);
frame->bFrameIntervalType = buffer[25];
} else {
frame->dwMaxVideoFrameBufferSize = 0;
frame->dwDefaultFrameInterval =
get_unaligned_le32(&buffer[17]);
frame->bFrameIntervalType = buffer[21];
}
frame->dwFrameInterval = *intervals;
/* Several UVC chipsets screw up dwMaxVideoFrameBufferSize
* completely. Observed behaviours range from setting the
* value to 1.1x the actual frame size to hardwiring the
* 16 low bits to 0. This results in a higher than necessary
* memory usage as well as a wrong image size information. For
* uncompressed formats this can be fixed by computing the
* value from the frame size.
*/
if (!(format->flags & UVC_FMT_FLAG_COMPRESSED))
frame->dwMaxVideoFrameBufferSize = format->bpp
* frame->wWidth * frame->wHeight / 8;
/* Some bogus devices report dwMinFrameInterval equal to
* dwMaxFrameInterval and have dwFrameIntervalStep set to
* zero. Setting all null intervals to 1 fixes the problem and
* some other divisions by zero that could happen.
*/
for (i = 0; i < n; ++i) {
interval = get_unaligned_le32(&buffer[26+4*i]);
*(*intervals)++ = interval ? interval : 1;
}
/* Make sure that the default frame interval stays between
* the boundaries.
*/
n -= frame->bFrameIntervalType ? 1 : 2;
frame->dwDefaultFrameInterval =
min(frame->dwFrameInterval[n],
max(frame->dwFrameInterval[0],
frame->dwDefaultFrameInterval));
if (dev->quirks & UVC_QUIRK_RESTRICT_FRAME_RATE) {
frame->bFrameIntervalType = 1;
frame->dwFrameInterval[0] =
frame->dwDefaultFrameInterval;
}
uvc_trace(UVC_TRACE_DESCR, "- %ux%u (%u.%u fps)\n",
frame->wWidth, frame->wHeight,
10000000/frame->dwDefaultFrameInterval,
(100000000/frame->dwDefaultFrameInterval)%10);
format->nframes++;
buflen -= buffer[0];
buffer += buffer[0];
}
if (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE &&
buffer[2] == UVC_VS_STILL_IMAGE_FRAME) {
buflen -= buffer[0];
buffer += buffer[0];
}
if (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE &&
buffer[2] == UVC_VS_COLORFORMAT) {
if (buflen < 6) {
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d COLORFORMAT error\n",
dev->udev->devnum,
alts->desc.bInterfaceNumber);
return -EINVAL;
}
format->colorspace = uvc_colorspace(buffer[3]);
buflen -= buffer[0];
buffer += buffer[0];
}
return buffer - start;
}
static int uvc_parse_streaming(struct uvc_device *dev,
struct usb_interface *intf)
{
struct uvc_streaming *streaming = NULL;
struct uvc_format *format;
struct uvc_frame *frame;
struct usb_host_interface *alts = &intf->altsetting[0];
unsigned char *_buffer, *buffer = alts->extra;
int _buflen, buflen = alts->extralen;
unsigned int nformats = 0, nframes = 0, nintervals = 0;
unsigned int size, i, n, p;
__u32 *interval;
__u16 psize;
int ret = -EINVAL;
if (intf->cur_altsetting->desc.bInterfaceSubClass
!= UVC_SC_VIDEOSTREAMING) {
uvc_trace(UVC_TRACE_DESCR, "device %d interface %d isn't a "
"video streaming interface\n", dev->udev->devnum,
intf->altsetting[0].desc.bInterfaceNumber);
return -EINVAL;
}
if (usb_driver_claim_interface(&uvc_driver.driver, intf, dev)) {
uvc_trace(UVC_TRACE_DESCR, "device %d interface %d is already "
"claimed\n", dev->udev->devnum,
intf->altsetting[0].desc.bInterfaceNumber);
return -EINVAL;
}
streaming = kzalloc(sizeof *streaming, GFP_KERNEL);
if (streaming == NULL) {
usb_driver_release_interface(&uvc_driver.driver, intf);
return -EINVAL;
}
mutex_init(&streaming->mutex);
streaming->dev = dev;
streaming->intf = usb_get_intf(intf);
streaming->intfnum = intf->cur_altsetting->desc.bInterfaceNumber;
/* The Pico iMage webcam has its class-specific interface descriptors
* after the endpoint descriptors.
*/
if (buflen == 0) {
for (i = 0; i < alts->desc.bNumEndpoints; ++i) {
struct usb_host_endpoint *ep = &alts->endpoint[i];
if (ep->extralen == 0)
continue;
if (ep->extralen > 2 &&
ep->extra[1] == USB_DT_CS_INTERFACE) {
uvc_trace(UVC_TRACE_DESCR, "trying extra data "
"from endpoint %u.\n", i);
buffer = alts->endpoint[i].extra;
buflen = alts->endpoint[i].extralen;
break;
}
}
}
/* Skip the standard interface descriptors. */
while (buflen > 2 && buffer[1] != USB_DT_CS_INTERFACE) {
buflen -= buffer[0];
buffer += buffer[0];
}
if (buflen <= 2) {
uvc_trace(UVC_TRACE_DESCR, "no class-specific streaming "
"interface descriptors found.\n");
goto error;
}
/* Parse the header descriptor. */
switch (buffer[2]) {
case UVC_VS_OUTPUT_HEADER:
streaming->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
size = 9;
break;
case UVC_VS_INPUT_HEADER:
streaming->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
size = 13;
break;
default:
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming interface "
"%d HEADER descriptor not found.\n", dev->udev->devnum,
alts->desc.bInterfaceNumber);
goto error;
}
p = buflen >= 4 ? buffer[3] : 0;
n = buflen >= size ? buffer[size-1] : 0;
if (buflen < size + p*n) {
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d HEADER descriptor is invalid.\n",
dev->udev->devnum, alts->desc.bInterfaceNumber);
goto error;
}
streaming->header.bNumFormats = p;
streaming->header.bEndpointAddress = buffer[6];
if (buffer[2] == UVC_VS_INPUT_HEADER) {
streaming->header.bmInfo = buffer[7];
streaming->header.bTerminalLink = buffer[8];
streaming->header.bStillCaptureMethod = buffer[9];
streaming->header.bTriggerSupport = buffer[10];
streaming->header.bTriggerUsage = buffer[11];
} else {
streaming->header.bTerminalLink = buffer[7];
}
streaming->header.bControlSize = n;
streaming->header.bmaControls = kmemdup(&buffer[size], p * n,
GFP_KERNEL);
if (streaming->header.bmaControls == NULL) {
ret = -ENOMEM;
goto error;
}
buflen -= buffer[0];
buffer += buffer[0];
_buffer = buffer;
_buflen = buflen;
/* Count the format and frame descriptors. */
while (_buflen > 2 && _buffer[1] == USB_DT_CS_INTERFACE) {
switch (_buffer[2]) {
case UVC_VS_FORMAT_UNCOMPRESSED:
case UVC_VS_FORMAT_MJPEG:
case UVC_VS_FORMAT_FRAME_BASED:
nformats++;
break;
case UVC_VS_FORMAT_DV:
/* DV format has no frame descriptor. We will create a
* dummy frame descriptor with a dummy frame interval.
*/
nformats++;
nframes++;
nintervals++;
break;
case UVC_VS_FORMAT_MPEG2TS:
case UVC_VS_FORMAT_STREAM_BASED:
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming "
"interface %d FORMAT %u is not supported.\n",
dev->udev->devnum,
alts->desc.bInterfaceNumber, _buffer[2]);
break;
case UVC_VS_FRAME_UNCOMPRESSED:
case UVC_VS_FRAME_MJPEG:
nframes++;
if (_buflen > 25)
nintervals += _buffer[25] ? _buffer[25] : 3;
break;
case UVC_VS_FRAME_FRAME_BASED:
nframes++;
if (_buflen > 21)
nintervals += _buffer[21] ? _buffer[21] : 3;
break;
}
_buflen -= _buffer[0];
_buffer += _buffer[0];
}
if (nformats == 0) {
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming interface "
"%d has no supported formats defined.\n",
dev->udev->devnum, alts->desc.bInterfaceNumber);
goto error;
}
size = nformats * sizeof *format + nframes * sizeof *frame
+ nintervals * sizeof *interval;
format = kzalloc(size, GFP_KERNEL);
if (format == NULL) {
ret = -ENOMEM;
goto error;
}
frame = (struct uvc_frame *)&format[nformats];
interval = (__u32 *)&frame[nframes];
streaming->format = format;
streaming->nformats = nformats;
/* Parse the format descriptors. */
while (buflen > 2 && buffer[1] == USB_DT_CS_INTERFACE) {
switch (buffer[2]) {
case UVC_VS_FORMAT_UNCOMPRESSED:
case UVC_VS_FORMAT_MJPEG:
case UVC_VS_FORMAT_DV:
case UVC_VS_FORMAT_FRAME_BASED:
format->frame = frame;
ret = uvc_parse_format(dev, streaming, format,
&interval, buffer, buflen);
if (ret < 0)
goto error;
frame += format->nframes;
format++;
buflen -= ret;
buffer += ret;
continue;
default:
break;
}
buflen -= buffer[0];
buffer += buffer[0];
}
if (buflen)
uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming interface "
"%d has %u bytes of trailing descriptor garbage.\n",
dev->udev->devnum, alts->desc.bInterfaceNumber, buflen);
/* Parse the alternate settings to find the maximum bandwidth. */
for (i = 0; i < intf->num_altsetting; ++i) {
struct usb_host_endpoint *ep;
alts = &intf->altsetting[i];
ep = uvc_find_endpoint(alts,
streaming->header.bEndpointAddress);
if (ep == NULL)
continue;
psize = le16_to_cpu(ep->desc.wMaxPacketSize);
psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
if (psize > streaming->maxpsize)
streaming->maxpsize = psize;
}
list_add_tail(&streaming->list, &dev->streams);
return 0;
error:
usb_driver_release_interface(&uvc_driver.driver, intf);
usb_put_intf(intf);
kfree(streaming->format);
kfree(streaming->header.bmaControls);
kfree(streaming);
return ret;
}
static struct uvc_entity *uvc_alloc_entity(u16 type, u8 id,
unsigned int num_pads, unsigned int extra_size)
{
struct uvc_entity *entity;
unsigned int num_inputs;
unsigned int size;
unsigned int i;
extra_size = ALIGN(extra_size, sizeof(*entity->pads));
num_inputs = (type & UVC_TERM_OUTPUT) ? num_pads : num_pads - 1;
size = sizeof(*entity) + extra_size + sizeof(*entity->pads) * num_pads
+ num_inputs;
entity = kzalloc(size, GFP_KERNEL);
if (entity == NULL)
return NULL;
entity->id = id;
entity->type = type;
entity->num_links = 0;
entity->num_pads = num_pads;
entity->pads = ((void *)(entity + 1)) + extra_size;
for (i = 0; i < num_inputs; ++i)
entity->pads[i].flags = MEDIA_PAD_FL_SINK;
if (!UVC_ENTITY_IS_OTERM(entity))
entity->pads[num_pads-1].flags = MEDIA_PAD_FL_SOURCE;
entity->bNrInPins = num_inputs;
entity->baSourceID = (__u8 *)(&entity->pads[num_pads]);
return entity;
}
/* Parse vendor-specific extensions. */
static int uvc_parse_vendor_control(struct uvc_device *dev,
const unsigned char *buffer, int buflen)
{
struct usb_device *udev = dev->udev;
struct usb_host_interface *alts = dev->intf->cur_altsetting;
struct uvc_entity *unit;
unsigned int n, p;
int handled = 0;
switch (le16_to_cpu(dev->udev->descriptor.idVendor)) {
case 0x046d: /* Logitech */
if (buffer[1] != 0x41 || buffer[2] != 0x01)
break;
/* Logitech implements several vendor specific functions
* through vendor specific extension units (LXU).
*
* The LXU descriptors are similar to XU descriptors
* (see "USB Device Video Class for Video Devices", section
* 3.7.2.6 "Extension Unit Descriptor") with the following
* differences:
*
* ----------------------------------------------------------
* 0 bLength 1 Number
* Size of this descriptor, in bytes: 24+p+n*2
* ----------------------------------------------------------
* 23+p+n bmControlsType N Bitmap
* Individual bits in the set are defined:
* 0: Absolute
* 1: Relative
*
* This bitset is mapped exactly the same as bmControls.
* ----------------------------------------------------------
* 23+p+n*2 bReserved 1 Boolean
* ----------------------------------------------------------
* 24+p+n*2 iExtension 1 Index
* Index of a string descriptor that describes this
* extension unit.
* ----------------------------------------------------------
*/
p = buflen >= 22 ? buffer[21] : 0;
n = buflen >= 25 + p ? buffer[22+p] : 0;
if (buflen < 25 + p + 2*n) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d EXTENSION_UNIT error\n",
udev->devnum, alts->desc.bInterfaceNumber);
break;
}
unit = uvc_alloc_entity(UVC_VC_EXTENSION_UNIT, buffer[3],
p + 1, 2*n);
if (unit == NULL)
return -ENOMEM;
memcpy(unit->extension.guidExtensionCode, &buffer[4], 16);
unit->extension.bNumControls = buffer[20];
memcpy(unit->baSourceID, &buffer[22], p);
unit->extension.bControlSize = buffer[22+p];
unit->extension.bmControls = (__u8 *)unit + sizeof(*unit);
unit->extension.bmControlsType = (__u8 *)unit + sizeof(*unit)
+ n;
memcpy(unit->extension.bmControls, &buffer[23+p], 2*n);
if (buffer[24+p+2*n] != 0)
usb_string(udev, buffer[24+p+2*n], unit->name,
sizeof unit->name);
else
sprintf(unit->name, "Extension %u", buffer[3]);
list_add_tail(&unit->list, &dev->entities);
handled = 1;
break;
}
return handled;
}
static int uvc_parse_standard_control(struct uvc_device *dev,
const unsigned char *buffer, int buflen)
{
struct usb_device *udev = dev->udev;
struct uvc_entity *unit, *term;
struct usb_interface *intf;
struct usb_host_interface *alts = dev->intf->cur_altsetting;
unsigned int i, n, p, len;
__u16 type;
switch (buffer[2]) {
case UVC_VC_HEADER:
n = buflen >= 12 ? buffer[11] : 0;
if (buflen < 12 + n) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d HEADER error\n", udev->devnum,
alts->desc.bInterfaceNumber);
return -EINVAL;
}
dev->uvc_version = get_unaligned_le16(&buffer[3]);
dev->clock_frequency = get_unaligned_le32(&buffer[7]);
/* Parse all USB Video Streaming interfaces. */
for (i = 0; i < n; ++i) {
intf = usb_ifnum_to_if(udev, buffer[12+i]);
if (intf == NULL) {
uvc_trace(UVC_TRACE_DESCR, "device %d "
"interface %d doesn't exists\n",
udev->devnum, i);
continue;
}
uvc_parse_streaming(dev, intf);
}
break;
case UVC_VC_INPUT_TERMINAL:
if (buflen < 8) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d INPUT_TERMINAL error\n",
udev->devnum, alts->desc.bInterfaceNumber);
return -EINVAL;
}
/* Make sure the terminal type MSB is not null, otherwise it
* could be confused with a unit.
*/
type = get_unaligned_le16(&buffer[4]);
if ((type & 0xff00) == 0) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d INPUT_TERMINAL %d has invalid "
"type 0x%04x, skipping\n", udev->devnum,
alts->desc.bInterfaceNumber,
buffer[3], type);
return 0;
}
n = 0;
p = 0;
len = 8;
if (type == UVC_ITT_CAMERA) {
n = buflen >= 15 ? buffer[14] : 0;
len = 15;
} else if (type == UVC_ITT_MEDIA_TRANSPORT_INPUT) {
n = buflen >= 9 ? buffer[8] : 0;
p = buflen >= 10 + n ? buffer[9+n] : 0;
len = 10;
}
if (buflen < len + n + p) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d INPUT_TERMINAL error\n",
udev->devnum, alts->desc.bInterfaceNumber);
return -EINVAL;
}
term = uvc_alloc_entity(type | UVC_TERM_INPUT, buffer[3],
1, n + p);
if (term == NULL)
return -ENOMEM;
if (UVC_ENTITY_TYPE(term) == UVC_ITT_CAMERA) {
term->camera.bControlSize = n;
term->camera.bmControls = (__u8 *)term + sizeof *term;
term->camera.wObjectiveFocalLengthMin =
get_unaligned_le16(&buffer[8]);
term->camera.wObjectiveFocalLengthMax =
get_unaligned_le16(&buffer[10]);
term->camera.wOcularFocalLength =
get_unaligned_le16(&buffer[12]);
memcpy(term->camera.bmControls, &buffer[15], n);
} else if (UVC_ENTITY_TYPE(term) ==
UVC_ITT_MEDIA_TRANSPORT_INPUT) {
term->media.bControlSize = n;
term->media.bmControls = (__u8 *)term + sizeof *term;
term->media.bTransportModeSize = p;
term->media.bmTransportModes = (__u8 *)term
+ sizeof *term + n;
memcpy(term->media.bmControls, &buffer[9], n);
memcpy(term->media.bmTransportModes, &buffer[10+n], p);
}
if (buffer[7] != 0)
usb_string(udev, buffer[7], term->name,
sizeof term->name);
else if (UVC_ENTITY_TYPE(term) == UVC_ITT_CAMERA)
sprintf(term->name, "Camera %u", buffer[3]);
else if (UVC_ENTITY_TYPE(term) == UVC_ITT_MEDIA_TRANSPORT_INPUT)
sprintf(term->name, "Media %u", buffer[3]);
else
sprintf(term->name, "Input %u", buffer[3]);
list_add_tail(&term->list, &dev->entities);
break;
case UVC_VC_OUTPUT_TERMINAL:
if (buflen < 9) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d OUTPUT_TERMINAL error\n",
udev->devnum, alts->desc.bInterfaceNumber);
return -EINVAL;
}
/* Make sure the terminal type MSB is not null, otherwise it
* could be confused with a unit.
*/
type = get_unaligned_le16(&buffer[4]);
if ((type & 0xff00) == 0) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d OUTPUT_TERMINAL %d has invalid "
"type 0x%04x, skipping\n", udev->devnum,
alts->desc.bInterfaceNumber, buffer[3], type);
return 0;
}
term = uvc_alloc_entity(type | UVC_TERM_OUTPUT, buffer[3],
1, 0);
if (term == NULL)
return -ENOMEM;
memcpy(term->baSourceID, &buffer[7], 1);
if (buffer[8] != 0)
usb_string(udev, buffer[8], term->name,
sizeof term->name);
else
sprintf(term->name, "Output %u", buffer[3]);
list_add_tail(&term->list, &dev->entities);
break;
case UVC_VC_SELECTOR_UNIT:
p = buflen >= 5 ? buffer[4] : 0;
if (buflen < 5 || buflen < 6 + p) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d SELECTOR_UNIT error\n",
udev->devnum, alts->desc.bInterfaceNumber);
return -EINVAL;
}
unit = uvc_alloc_entity(buffer[2], buffer[3], p + 1, 0);
if (unit == NULL)
return -ENOMEM;
memcpy(unit->baSourceID, &buffer[5], p);
if (buffer[5+p] != 0)
usb_string(udev, buffer[5+p], unit->name,
sizeof unit->name);
else
sprintf(unit->name, "Selector %u", buffer[3]);
list_add_tail(&unit->list, &dev->entities);
break;
case UVC_VC_PROCESSING_UNIT:
n = buflen >= 8 ? buffer[7] : 0;
p = dev->uvc_version >= 0x0110 ? 10 : 9;
if (buflen < p + n) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d PROCESSING_UNIT error\n",
udev->devnum, alts->desc.bInterfaceNumber);
return -EINVAL;
}
unit = uvc_alloc_entity(buffer[2], buffer[3], 2, n);
if (unit == NULL)
return -ENOMEM;
memcpy(unit->baSourceID, &buffer[4], 1);
unit->processing.wMaxMultiplier =
get_unaligned_le16(&buffer[5]);
unit->processing.bControlSize = buffer[7];
unit->processing.bmControls = (__u8 *)unit + sizeof *unit;
memcpy(unit->processing.bmControls, &buffer[8], n);
if (dev->uvc_version >= 0x0110)
unit->processing.bmVideoStandards = buffer[9+n];
if (buffer[8+n] != 0)
usb_string(udev, buffer[8+n], unit->name,
sizeof unit->name);
else
sprintf(unit->name, "Processing %u", buffer[3]);
list_add_tail(&unit->list, &dev->entities);
break;
case UVC_VC_EXTENSION_UNIT:
p = buflen >= 22 ? buffer[21] : 0;
n = buflen >= 24 + p ? buffer[22+p] : 0;
if (buflen < 24 + p + n) {
uvc_trace(UVC_TRACE_DESCR, "device %d videocontrol "
"interface %d EXTENSION_UNIT error\n",
udev->devnum, alts->desc.bInterfaceNumber);
return -EINVAL;
}
unit = uvc_alloc_entity(buffer[2], buffer[3], p + 1, n);
if (unit == NULL)
return -ENOMEM;
memcpy(unit->extension.guidExtensionCode, &buffer[4], 16);
unit->extension.bNumControls = buffer[20];
memcpy(unit->baSourceID, &buffer[22], p);
unit->extension.bControlSize = buffer[22+p];
unit->extension.bmControls = (__u8 *)unit + sizeof *unit;
memcpy(unit->extension.bmControls, &buffer[23+p], n);
if (buffer[23+p+n] != 0)
usb_string(udev, buffer[23+p+n], unit->name,
sizeof unit->name);
else
sprintf(unit->name, "Extension %u", buffer[3]);
list_add_tail(&unit->list, &dev->entities);
break;
default:
uvc_trace(UVC_TRACE_DESCR, "Found an unknown CS_INTERFACE "
"descriptor (%u)\n", buffer[2]);
break;
}
return 0;
}
static int uvc_parse_control(struct uvc_device *dev)
{
struct usb_host_interface *alts = dev->intf->cur_altsetting;
unsigned char *buffer = alts->extra;
int buflen = alts->extralen;
int ret;
/* Parse the default alternate setting only, as the UVC specification
* defines a single alternate setting, the default alternate setting
* zero.
*/
while (buflen > 2) {
if (uvc_parse_vendor_control(dev, buffer, buflen) ||
buffer[1] != USB_DT_CS_INTERFACE)
goto next_descriptor;
if ((ret = uvc_parse_standard_control(dev, buffer, buflen)) < 0)
return ret;
next_descriptor:
buflen -= buffer[0];
buffer += buffer[0];
}
/* Check if the optional status endpoint is present. Built-in iSight
* webcams have an interrupt endpoint but spit proprietary data that
* don't conform to the UVC status endpoint messages. Don't try to
* handle the interrupt endpoint for those cameras.
*/
if (alts->desc.bNumEndpoints == 1 &&
!(dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)) {
struct usb_host_endpoint *ep = &alts->endpoint[0];
struct usb_endpoint_descriptor *desc = &ep->desc;
if (usb_endpoint_is_int_in(desc) &&
le16_to_cpu(desc->wMaxPacketSize) >= 8 &&
desc->bInterval != 0) {
uvc_trace(UVC_TRACE_DESCR, "Found a Status endpoint "
"(addr %02x).\n", desc->bEndpointAddress);
dev->int_ep = ep;
}
}
return 0;
}
/* ------------------------------------------------------------------------
* UVC device scan
*/
/*
* Scan the UVC descriptors to locate a chain starting at an Output Terminal
* and containing the following units:
*
* - one or more Output Terminals (USB Streaming or Display)
* - zero or one Processing Unit
* - zero, one or more single-input Selector Units
* - zero or one multiple-input Selector Units, provided all inputs are
* connected to input terminals
* - zero, one or mode single-input Extension Units
* - one or more Input Terminals (Camera, External or USB Streaming)
*
* The terminal and units must match on of the following structures:
*
* ITT_*(0) -> +---------+ +---------+ +---------+ -> TT_STREAMING(0)
* ... | SU{0,1} | -> | PU{0,1} | -> | XU{0,n} | ...
* ITT_*(n) -> +---------+ +---------+ +---------+ -> TT_STREAMING(n)
*
* +---------+ +---------+ -> OTT_*(0)
* TT_STREAMING -> | PU{0,1} | -> | XU{0,n} | ...
* +---------+ +---------+ -> OTT_*(n)
*
* The Processing Unit and Extension Units can be in any order. Additional
* Extension Units connected to the main chain as single-unit branches are
* also supported. Single-input Selector Units are ignored.
*/
static int uvc_scan_chain_entity(struct uvc_video_chain *chain,
struct uvc_entity *entity)
{
switch (UVC_ENTITY_TYPE(entity)) {
case UVC_VC_EXTENSION_UNIT:
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" <- XU %d", entity->id);
if (entity->bNrInPins != 1) {
uvc_trace(UVC_TRACE_DESCR, "Extension unit %d has more "
"than 1 input pin.\n", entity->id);
return -1;
}
break;
case UVC_VC_PROCESSING_UNIT:
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" <- PU %d", entity->id);
if (chain->processing != NULL) {
uvc_trace(UVC_TRACE_DESCR, "Found multiple "
"Processing Units in chain.\n");
return -1;
}
chain->processing = entity;
break;
case UVC_VC_SELECTOR_UNIT:
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" <- SU %d", entity->id);
/* Single-input selector units are ignored. */
if (entity->bNrInPins == 1)
break;
if (chain->selector != NULL) {
uvc_trace(UVC_TRACE_DESCR, "Found multiple Selector "
"Units in chain.\n");
return -1;
}
chain->selector = entity;
break;
case UVC_ITT_VENDOR_SPECIFIC:
case UVC_ITT_CAMERA:
case UVC_ITT_MEDIA_TRANSPORT_INPUT:
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" <- IT %d\n", entity->id);
break;
case UVC_OTT_VENDOR_SPECIFIC:
case UVC_OTT_DISPLAY:
case UVC_OTT_MEDIA_TRANSPORT_OUTPUT:
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" OT %d", entity->id);
break;
case UVC_TT_STREAMING:
if (UVC_ENTITY_IS_ITERM(entity)) {
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" <- IT %d\n", entity->id);
} else {
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" OT %d", entity->id);
}
break;
default:
uvc_trace(UVC_TRACE_DESCR, "Unsupported entity type "
"0x%04x found in chain.\n", UVC_ENTITY_TYPE(entity));
return -1;
}
list_add_tail(&entity->chain, &chain->entities);
return 0;
}
static int uvc_scan_chain_forward(struct uvc_video_chain *chain,
struct uvc_entity *entity, struct uvc_entity *prev)
{
struct uvc_entity *forward;
int found;
/* Forward scan */
forward = NULL;
found = 0;
while (1) {
forward = uvc_entity_by_reference(chain->dev, entity->id,
forward);
if (forward == NULL)
break;
if (forward == prev)
continue;
switch (UVC_ENTITY_TYPE(forward)) {
case UVC_VC_EXTENSION_UNIT:
if (forward->bNrInPins != 1) {
uvc_trace(UVC_TRACE_DESCR, "Extension unit %d "
"has more than 1 input pin.\n",
entity->id);
return -EINVAL;
}
list_add_tail(&forward->chain, &chain->entities);
if (uvc_trace_param & UVC_TRACE_PROBE) {
if (!found)
printk(" (->");
printk(" XU %d", forward->id);
found = 1;
}
break;
case UVC_OTT_VENDOR_SPECIFIC:
case UVC_OTT_DISPLAY:
case UVC_OTT_MEDIA_TRANSPORT_OUTPUT:
case UVC_TT_STREAMING:
if (UVC_ENTITY_IS_ITERM(forward)) {
uvc_trace(UVC_TRACE_DESCR, "Unsupported input "
"terminal %u.\n", forward->id);
return -EINVAL;
}
list_add_tail(&forward->chain, &chain->entities);
if (uvc_trace_param & UVC_TRACE_PROBE) {
if (!found)
printk(" (->");
printk(" OT %d", forward->id);
found = 1;
}
break;
}
}
if (found)
printk(")");
return 0;
}
static int uvc_scan_chain_backward(struct uvc_video_chain *chain,
struct uvc_entity **_entity)
{
struct uvc_entity *entity = *_entity;
struct uvc_entity *term;
int id = -EINVAL, i;
switch (UVC_ENTITY_TYPE(entity)) {
case UVC_VC_EXTENSION_UNIT:
case UVC_VC_PROCESSING_UNIT:
id = entity->baSourceID[0];
break;
case UVC_VC_SELECTOR_UNIT:
/* Single-input selector units are ignored. */
if (entity->bNrInPins == 1) {
id = entity->baSourceID[0];
break;
}
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" <- IT");
chain->selector = entity;
for (i = 0; i < entity->bNrInPins; ++i) {
id = entity->baSourceID[i];
term = uvc_entity_by_id(chain->dev, id);
if (term == NULL || !UVC_ENTITY_IS_ITERM(term)) {
uvc_trace(UVC_TRACE_DESCR, "Selector unit %d "
"input %d isn't connected to an "
"input terminal\n", entity->id, i);
return -1;
}
if (uvc_trace_param & UVC_TRACE_PROBE)
printk(" %d", term->id);
list_add_tail(&term->chain, &chain->entities);
uvc_scan_chain_forward(chain, term, entity);
}
if (uvc_trace_param & UVC_TRACE_PROBE)
printk("\n");
id = 0;
break;
case UVC_ITT_VENDOR_SPECIFIC:
case UVC_ITT_CAMERA:
case UVC_ITT_MEDIA_TRANSPORT_INPUT:
case UVC_OTT_VENDOR_SPECIFIC:
case UVC_OTT_DISPLAY:
case UVC_OTT_MEDIA_TRANSPORT_OUTPUT:
case UVC_TT_STREAMING:
id = UVC_ENTITY_IS_OTERM(entity) ? entity->baSourceID[0] : 0;
break;
}
if (id <= 0) {
*_entity = NULL;
return id;
}
entity = uvc_entity_by_id(chain->dev, id);
if (entity == NULL) {
uvc_trace(UVC_TRACE_DESCR, "Found reference to "
"unknown entity %d.\n", id);
return -EINVAL;
}
*_entity = entity;
return 0;
}
static int uvc_scan_chain(struct uvc_video_chain *chain,
struct uvc_entity *term)
{
struct uvc_entity *entity, *prev;
uvc_trace(UVC_TRACE_PROBE, "Scanning UVC chain:");
entity = term;
prev = NULL;
while (entity != NULL) {
/* Entity must not be part of an existing chain */
if (entity->chain.next || entity->chain.prev) {
uvc_trace(UVC_TRACE_DESCR, "Found reference to "
"entity %d already in chain.\n", entity->id);
return -EINVAL;
}
/* Process entity */
if (uvc_scan_chain_entity(chain, entity) < 0)
return -EINVAL;
/* Forward scan */
if (uvc_scan_chain_forward(chain, entity, prev) < 0)
return -EINVAL;
/* Backward scan */
prev = entity;
if (uvc_scan_chain_backward(chain, &entity) < 0)
return -EINVAL;
}
return 0;
}
static unsigned int uvc_print_terms(struct list_head *terms, u16 dir,
char *buffer)
{
struct uvc_entity *term;
unsigned int nterms = 0;
char *p = buffer;
list_for_each_entry(term, terms, chain) {
if (!UVC_ENTITY_IS_TERM(term) ||
UVC_TERM_DIRECTION(term) != dir)
continue;
if (nterms)
p += sprintf(p, ",");
if (++nterms >= 4) {
p += sprintf(p, "...");
break;
}
p += sprintf(p, "%u", term->id);
}
return p - buffer;
}
static const char *uvc_print_chain(struct uvc_video_chain *chain)
{
static char buffer[43];
char *p = buffer;
p += uvc_print_terms(&chain->entities, UVC_TERM_INPUT, p);
p += sprintf(p, " -> ");
uvc_print_terms(&chain->entities, UVC_TERM_OUTPUT, p);
return buffer;
}
/*
* Scan the device for video chains and register video devices.
*
* Chains are scanned starting at their output terminals and walked backwards.
*/
static int uvc_scan_device(struct uvc_device *dev)
{
struct uvc_video_chain *chain;
struct uvc_entity *term;
list_for_each_entry(term, &dev->entities, list) {
if (!UVC_ENTITY_IS_OTERM(term))
continue;
/* If the terminal is already included in a chain, skip it.
* This can happen for chains that have multiple output
* terminals, where all output terminals beside the first one
* will be inserted in the chain in forward scans.
*/
if (term->chain.next || term->chain.prev)
continue;
chain = kzalloc(sizeof(*chain), GFP_KERNEL);
if (chain == NULL)
return -ENOMEM;
INIT_LIST_HEAD(&chain->entities);
mutex_init(&chain->ctrl_mutex);
chain->dev = dev;
v4l2_prio_init(&chain->prio);
term->flags |= UVC_ENTITY_FLAG_DEFAULT;
if (uvc_scan_chain(chain, term) < 0) {
kfree(chain);
continue;
}
uvc_trace(UVC_TRACE_PROBE, "Found a valid video chain (%s).\n",
uvc_print_chain(chain));
list_add_tail(&chain->list, &dev->chains);
}
if (list_empty(&dev->chains)) {
uvc_printk(KERN_INFO, "No valid video chain found.\n");
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------
* Video device registration and unregistration
*/
/*
* Delete the UVC device.
*
* Called by the kernel when the last reference to the uvc_device structure
* is released.
*
* As this function is called after or during disconnect(), all URBs have
* already been canceled by the USB core. There is no need to kill the
* interrupt URB manually.
*/
static void uvc_delete(struct uvc_device *dev)
{
struct list_head *p, *n;
uvc_status_cleanup(dev);
uvc_ctrl_cleanup_device(dev);
usb_put_intf(dev->intf);
usb_put_dev(dev->udev);
if (dev->vdev.dev)
v4l2_device_unregister(&dev->vdev);
#ifdef CONFIG_MEDIA_CONTROLLER
if (media_devnode_is_registered(&dev->mdev.devnode))
media_device_unregister(&dev->mdev);
#endif
list_for_each_safe(p, n, &dev->chains) {
struct uvc_video_chain *chain;
chain = list_entry(p, struct uvc_video_chain, list);
kfree(chain);
}
list_for_each_safe(p, n, &dev->entities) {
struct uvc_entity *entity;
entity = list_entry(p, struct uvc_entity, list);
#ifdef CONFIG_MEDIA_CONTROLLER
uvc_mc_cleanup_entity(entity);
#endif
if (entity->vdev) {
video_device_release(entity->vdev);
entity->vdev = NULL;
}
kfree(entity);
}
list_for_each_safe(p, n, &dev->streams) {
struct uvc_streaming *streaming;
streaming = list_entry(p, struct uvc_streaming, list);
usb_driver_release_interface(&uvc_driver.driver,
streaming->intf);
usb_put_intf(streaming->intf);
kfree(streaming->format);
kfree(streaming->header.bmaControls);
kfree(streaming);
}
kfree(dev);
}
static void uvc_release(struct video_device *vdev)
{
struct uvc_streaming *stream = video_get_drvdata(vdev);
struct uvc_device *dev = stream->dev;
/* Decrement the registered streams count and delete the device when it
* reaches zero.
*/
if (atomic_dec_and_test(&dev->nstreams))
uvc_delete(dev);
}
/*
* Unregister the video devices.
*/
static void uvc_unregister_video(struct uvc_device *dev)
{
struct uvc_streaming *stream;
/* Unregistering all video devices might result in uvc_delete() being
* called from inside the loop if there's no open file handle. To avoid
* that, increment the stream count before iterating over the streams
* and decrement it when done.
*/
atomic_inc(&dev->nstreams);
list_for_each_entry(stream, &dev->streams, list) {
if (stream->vdev == NULL)
continue;
video_unregister_device(stream->vdev);
stream->vdev = NULL;
uvc_debugfs_cleanup_stream(stream);
}
/* Decrement the stream count and call uvc_delete explicitly if there
* are no stream left.
*/
if (atomic_dec_and_test(&dev->nstreams))
uvc_delete(dev);
}
static int uvc_register_video(struct uvc_device *dev,
struct uvc_streaming *stream)
{
struct video_device *vdev;
int ret;
/* Initialize the video buffers queue. */
ret = uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
if (ret)
return ret;
/* Initialize the streaming interface with default streaming
* parameters.
*/
ret = uvc_video_init(stream);
if (ret < 0) {
uvc_printk(KERN_ERR, "Failed to initialize the device "
"(%d).\n", ret);
return ret;
}
uvc_debugfs_init_stream(stream);
/* Register the device with V4L. */
vdev = video_device_alloc();
if (vdev == NULL) {
uvc_printk(KERN_ERR, "Failed to allocate video device (%d).\n",
ret);
return -ENOMEM;
}
/* We already hold a reference to dev->udev. The video device will be
* unregistered before the reference is released, so we don't need to
* get another one.
*/
vdev->v4l2_dev = &dev->vdev;
vdev->fops = &uvc_fops;
vdev->ioctl_ops = &uvc_ioctl_ops;
vdev->release = uvc_release;
vdev->prio = &stream->chain->prio;
if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
vdev->vfl_dir = VFL_DIR_TX;
strlcpy(vdev->name, dev->name, sizeof vdev->name);
/* Set the driver data before calling video_register_device, otherwise
* uvc_v4l2_open might race us.
*/
stream->vdev = vdev;
video_set_drvdata(vdev, stream);
ret = video_register_device(vdev, VFL_TYPE_GRABBER, -1);
if (ret < 0) {
uvc_printk(KERN_ERR, "Failed to register video device (%d).\n",
ret);
stream->vdev = NULL;
video_device_release(vdev);
return ret;
}
if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
stream->chain->caps |= V4L2_CAP_VIDEO_CAPTURE;
else
stream->chain->caps |= V4L2_CAP_VIDEO_OUTPUT;
atomic_inc(&dev->nstreams);
return 0;
}
/*
* Register all video devices in all chains.
*/
static int uvc_register_terms(struct uvc_device *dev,
struct uvc_video_chain *chain)
{
struct uvc_streaming *stream;
struct uvc_entity *term;
int ret;
list_for_each_entry(term, &chain->entities, chain) {
if (UVC_ENTITY_TYPE(term) != UVC_TT_STREAMING)
continue;
stream = uvc_stream_by_id(dev, term->id);
if (stream == NULL) {
uvc_printk(KERN_INFO, "No streaming interface found "
"for terminal %u.", term->id);
continue;
}
stream->chain = chain;
ret = uvc_register_video(dev, stream);
if (ret < 0)
return ret;
term->vdev = stream->vdev;
}
return 0;
}
static int uvc_register_chains(struct uvc_device *dev)
{
struct uvc_video_chain *chain;
int ret;
list_for_each_entry(chain, &dev->chains, list) {
ret = uvc_register_terms(dev, chain);
if (ret < 0)
return ret;
#ifdef CONFIG_MEDIA_CONTROLLER
ret = uvc_mc_register_entities(chain);
if (ret < 0) {
uvc_printk(KERN_INFO, "Failed to register entites "
"(%d).\n", ret);
}
#endif
}
return 0;
}
/* ------------------------------------------------------------------------
* USB probe, disconnect, suspend and resume
*/
static int uvc_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct uvc_device *dev;
int ret;
if (id->idVendor && id->idProduct)
uvc_trace(UVC_TRACE_PROBE, "Probing known UVC device %s "
"(%04x:%04x)\n", udev->devpath, id->idVendor,
id->idProduct);
else
uvc_trace(UVC_TRACE_PROBE, "Probing generic UVC device %s\n",
udev->devpath);
/* Allocate memory for the device and initialize it. */
if ((dev = kzalloc(sizeof *dev, GFP_KERNEL)) == NULL)
return -ENOMEM;
INIT_LIST_HEAD(&dev->entities);
INIT_LIST_HEAD(&dev->chains);
INIT_LIST_HEAD(&dev->streams);
atomic_set(&dev->nstreams, 0);
atomic_set(&dev->nmappings, 0);
mutex_init(&dev->lock);
dev->udev = usb_get_dev(udev);
dev->intf = usb_get_intf(intf);
dev->intfnum = intf->cur_altsetting->desc.bInterfaceNumber;
dev->quirks = (uvc_quirks_param == -1)
? id->driver_info : uvc_quirks_param;
if (udev->product != NULL)
strlcpy(dev->name, udev->product, sizeof dev->name);
else
snprintf(dev->name, sizeof dev->name,
"UVC Camera (%04x:%04x)",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct));
/* Parse the Video Class control descriptor. */
if (uvc_parse_control(dev) < 0) {
uvc_trace(UVC_TRACE_PROBE, "Unable to parse UVC "
"descriptors.\n");
goto error;
}
uvc_printk(KERN_INFO, "Found UVC %u.%02x device %s (%04x:%04x)\n",
dev->uvc_version >> 8, dev->uvc_version & 0xff,
udev->product ? udev->product : "<unnamed>",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct));
if (dev->quirks != id->driver_info) {
uvc_printk(KERN_INFO, "Forcing device quirks to 0x%x by module "
"parameter for testing purpose.\n", dev->quirks);
uvc_printk(KERN_INFO, "Please report required quirks to the "
"linux-uvc-devel mailing list.\n");
}
/* Register the media and V4L2 devices. */
#ifdef CONFIG_MEDIA_CONTROLLER
dev->mdev.dev = &intf->dev;
strlcpy(dev->mdev.model, dev->name, sizeof(dev->mdev.model));
if (udev->serial)
strlcpy(dev->mdev.serial, udev->serial,
sizeof(dev->mdev.serial));
strcpy(dev->mdev.bus_info, udev->devpath);
dev->mdev.hw_revision = le16_to_cpu(udev->descriptor.bcdDevice);
dev->mdev.driver_version = LINUX_VERSION_CODE;
if (media_device_register(&dev->mdev) < 0)
goto error;
dev->vdev.mdev = &dev->mdev;
#endif
if (v4l2_device_register(&intf->dev, &dev->vdev) < 0)
goto error;
/* Initialize controls. */
if (uvc_ctrl_init_device(dev) < 0)
goto error;
/* Scan the device for video chains. */
if (uvc_scan_device(dev) < 0)
goto error;
/* Register video device nodes. */
if (uvc_register_chains(dev) < 0)
goto error;
/* Save our data pointer in the interface data. */
usb_set_intfdata(intf, dev);
/* Initialize the interrupt URB. */
if ((ret = uvc_status_init(dev)) < 0) {
uvc_printk(KERN_INFO, "Unable to initialize the status "
"endpoint (%d), status interrupt will not be "
"supported.\n", ret);
}
uvc_trace(UVC_TRACE_PROBE, "UVC device initialized.\n");
usb_enable_autosuspend(udev);
return 0;
error:
uvc_unregister_video(dev);
return -ENODEV;
}
static void uvc_disconnect(struct usb_interface *intf)
{
struct uvc_device *dev = usb_get_intfdata(intf);
/* Set the USB interface data to NULL. This can be done outside the
* lock, as there's no other reader.
*/
usb_set_intfdata(intf, NULL);
if (intf->cur_altsetting->desc.bInterfaceSubClass ==
UVC_SC_VIDEOSTREAMING)
return;
dev->state |= UVC_DEV_DISCONNECTED;
uvc_unregister_video(dev);
}
static int uvc_suspend(struct usb_interface *intf, pm_message_t message)
{
struct uvc_device *dev = usb_get_intfdata(intf);
struct uvc_streaming *stream;
uvc_trace(UVC_TRACE_SUSPEND, "Suspending interface %u\n",
intf->cur_altsetting->desc.bInterfaceNumber);
/* Controls are cached on the fly so they don't need to be saved. */
if (intf->cur_altsetting->desc.bInterfaceSubClass ==
UVC_SC_VIDEOCONTROL) {
mutex_lock(&dev->lock);
if (dev->users)
uvc_status_stop(dev);
mutex_unlock(&dev->lock);
return 0;
}
list_for_each_entry(stream, &dev->streams, list) {
if (stream->intf == intf)
return uvc_video_suspend(stream);
}
uvc_trace(UVC_TRACE_SUSPEND, "Suspend: video streaming USB interface "
"mismatch.\n");
return -EINVAL;
}
static int __uvc_resume(struct usb_interface *intf, int reset)
{
struct uvc_device *dev = usb_get_intfdata(intf);
struct uvc_streaming *stream;
int ret = 0;
uvc_trace(UVC_TRACE_SUSPEND, "Resuming interface %u\n",
intf->cur_altsetting->desc.bInterfaceNumber);
if (intf->cur_altsetting->desc.bInterfaceSubClass ==
UVC_SC_VIDEOCONTROL) {
if (reset) {
ret = uvc_ctrl_restore_values(dev);
if (ret < 0)
return ret;
}
mutex_lock(&dev->lock);
if (dev->users)
ret = uvc_status_start(dev, GFP_NOIO);
mutex_unlock(&dev->lock);
return ret;
}
list_for_each_entry(stream, &dev->streams, list) {
if (stream->intf == intf) {
ret = uvc_video_resume(stream, reset);
if (ret < 0)
uvc_queue_streamoff(&stream->queue,
stream->queue.queue.type);
return ret;
}
}
uvc_trace(UVC_TRACE_SUSPEND, "Resume: video streaming USB interface "
"mismatch.\n");
return -EINVAL;
}
static int uvc_resume(struct usb_interface *intf)
{
return __uvc_resume(intf, 0);
}
static int uvc_reset_resume(struct usb_interface *intf)
{
return __uvc_resume(intf, 1);
}
/* ------------------------------------------------------------------------
* Module parameters
*/
static int uvc_clock_param_get(char *buffer, struct kernel_param *kp)
{
if (uvc_clock_param == CLOCK_MONOTONIC)
return sprintf(buffer, "CLOCK_MONOTONIC");
else
return sprintf(buffer, "CLOCK_REALTIME");
}
static int uvc_clock_param_set(const char *val, struct kernel_param *kp)
{
if (strncasecmp(val, "clock_", strlen("clock_")) == 0)
val += strlen("clock_");
if (strcasecmp(val, "monotonic") == 0)
uvc_clock_param = CLOCK_MONOTONIC;
else if (strcasecmp(val, "realtime") == 0)
uvc_clock_param = CLOCK_REALTIME;
else
return -EINVAL;
return 0;
}
module_param_call(clock, uvc_clock_param_set, uvc_clock_param_get,
&uvc_clock_param, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(clock, "Video buffers timestamp clock");
module_param_named(nodrop, uvc_no_drop_param, uint, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(nodrop, "Don't drop incomplete frames");
module_param_named(quirks, uvc_quirks_param, uint, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(quirks, "Forced device quirks");
module_param_named(trace, uvc_trace_param, uint, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(trace, "Trace level bitmask");
module_param_named(timeout, uvc_timeout_param, uint, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(timeout, "Streaming control requests timeout");
/* ------------------------------------------------------------------------
* Driver initialization and cleanup
*/
/*
* The Logitech cameras listed below have their interface class set to
* VENDOR_SPEC because they don't announce themselves as UVC devices, even
* though they are compliant.
*/
static struct usb_device_id uvc_ids[] = {
/* LogiLink Wireless Webcam */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x0416,
.idProduct = 0xa91a,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* Genius eFace 2025 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x0458,
.idProduct = 0x706e,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* Microsoft Lifecam NX-6000 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x045e,
.idProduct = 0x00f8,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* Microsoft Lifecam NX-3000 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x045e,
.idProduct = 0x0721,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_DEF },
/* Microsoft Lifecam VX-7000 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x045e,
.idProduct = 0x0723,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* Logitech Quickcam Fusion */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x046d,
.idProduct = 0x08c1,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0 },
/* Logitech Quickcam Orbit MP */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x046d,
.idProduct = 0x08c2,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0 },
/* Logitech Quickcam Pro for Notebook */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x046d,
.idProduct = 0x08c3,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0 },
/* Logitech Quickcam Pro 5000 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x046d,
.idProduct = 0x08c5,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0 },
/* Logitech Quickcam OEM Dell Notebook */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x046d,
.idProduct = 0x08c6,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0 },
/* Logitech Quickcam OEM Cisco VT Camera II */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x046d,
.idProduct = 0x08c7,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0 },
/* Logitech HD Pro Webcam C920 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x046d,
.idProduct = 0x082d,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_RESTORE_CTRLS_ON_INIT },
/* Chicony CNF7129 (Asus EEE 100HE) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x04f2,
.idProduct = 0xb071,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_RESTRICT_FRAME_RATE },
/* Alcor Micro AU3820 (Future Boy PC USB Webcam) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x058f,
.idProduct = 0x3820,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* Dell XPS m1530 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05a9,
.idProduct = 0x2640,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_DEF },
/* Dell SP2008WFP Monitor */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05a9,
.idProduct = 0x2641,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_DEF },
/* Dell Alienware X51 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05a9,
.idProduct = 0x2643,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_DEF },
/* Dell Studio Hybrid 140g (OmniVision webcam) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05a9,
.idProduct = 0x264a,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_DEF },
/* Dell XPS M1330 (OmniVision OV7670 webcam) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05a9,
.idProduct = 0x7670,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_DEF },
/* Apple Built-In iSight */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05ac,
.idProduct = 0x8501,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX
| UVC_QUIRK_BUILTIN_ISIGHT },
/* Foxlink ("HP Webcam" on HP Mini 5103) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05c8,
.idProduct = 0x0403,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_FIX_BANDWIDTH },
/* Genesys Logic USB 2.0 PC Camera */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x05e3,
.idProduct = 0x0505,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Hercules Classic Silver */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x06f8,
.idProduct = 0x300c,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_FIX_BANDWIDTH },
/* ViMicro Vega */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x0ac8,
.idProduct = 0x332d,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_FIX_BANDWIDTH },
/* ViMicro - Minoru3D */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x0ac8,
.idProduct = 0x3410,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_FIX_BANDWIDTH },
/* ViMicro Venus - Minoru3D */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x0ac8,
.idProduct = 0x3420,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_FIX_BANDWIDTH },
/* Ophir Optronics - SPCAM 620U */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x0bd3,
.idProduct = 0x0555,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* MT6227 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x0e8d,
.idProduct = 0x0004,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX
| UVC_QUIRK_PROBE_DEF },
/* IMC Networks (Medion Akoya) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x13d3,
.idProduct = 0x5103,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* JMicron USB2.0 XGA WebCam */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x152d,
.idProduct = 0x0310,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* Syntek (HP Spartan) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x174f,
.idProduct = 0x5212,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Syntek (Samsung Q310) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x174f,
.idProduct = 0x5931,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Syntek (Packard Bell EasyNote MX52 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x174f,
.idProduct = 0x8a12,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Syntek (Asus F9SG) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x174f,
.idProduct = 0x8a31,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Syntek (Asus U3S) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x174f,
.idProduct = 0x8a33,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Syntek (JAOtech Smart Terminal) */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x174f,
.idProduct = 0x8a34,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Miricle 307K */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x17dc,
.idProduct = 0x0202,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Lenovo Thinkpad SL400/SL500 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x17ef,
.idProduct = 0x480b,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STREAM_NO_FID },
/* Aveo Technology USB 2.0 Camera */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x1871,
.idProduct = 0x0306,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX
| UVC_QUIRK_PROBE_EXTRAFIELDS },
/* Ecamm Pico iMage */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x18cd,
.idProduct = 0xcafe,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_EXTRAFIELDS },
/* Manta MM-353 Plako */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x18ec,
.idProduct = 0x3188,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* FSC WebCam V30S */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x18ec,
.idProduct = 0x3288,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* Arkmicro unbranded */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x18ec,
.idProduct = 0x3290,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_DEF },
/* The Imaging Source USB CCD cameras */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x199e,
.idProduct = 0x8102,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0 },
/* Bodelin ProScopeHR */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_DEV_HI
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x19ab,
.idProduct = 0x1000,
.bcdDevice_hi = 0x0126,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_STATUS_INTERVAL },
/* MSI StarCam 370i */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x1b3b,
.idProduct = 0x2951,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX },
/* SiGma Micro USB Web Camera */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x1c4f,
.idProduct = 0x3000,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_PROBE_MINMAX
| UVC_QUIRK_IGNORE_SELECTOR_UNIT },
/* Oculus VR Positional Tracker DK2 */
{ .match_flags = USB_DEVICE_ID_MATCH_DEVICE
| USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = 0x2833,
.idProduct = 0x0201,
.bInterfaceClass = USB_CLASS_VIDEO,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 0,
.driver_info = UVC_QUIRK_FORCE_Y8 },
/* Generic USB Video Class */
{ USB_INTERFACE_INFO(USB_CLASS_VIDEO, 1, 0) },
{}
};
MODULE_DEVICE_TABLE(usb, uvc_ids);
struct uvc_driver uvc_driver = {
.driver = {
.name = "uvcvideo",
.probe = uvc_probe,
.disconnect = uvc_disconnect,
.suspend = uvc_suspend,
.resume = uvc_resume,
.reset_resume = uvc_reset_resume,
.id_table = uvc_ids,
.supports_autosuspend = 1,
},
};
static int __init uvc_init(void)
{
int ret;
uvc_debugfs_init();
ret = usb_register(&uvc_driver.driver);
if (ret < 0) {
uvc_debugfs_cleanup();
return ret;
}
printk(KERN_INFO DRIVER_DESC " (" DRIVER_VERSION ")\n");
return 0;
}
static void __exit uvc_cleanup(void)
{
usb_deregister(&uvc_driver.driver);
uvc_debugfs_cleanup();
}
module_init(uvc_init);
module_exit(uvc_cleanup);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
| gpl-2.0 |
kerlnel/newlib | newlib/libm/math/wf_remainder.c | 137 | 1649 | /* wf_remainder.c -- float version of w_remainder.c.
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
* wrapper remainderf(x,p)
*/
#include "fdlibm.h"
#include <errno.h>
#ifdef __STDC__
float remainderf(float x, float y) /* wrapper remainder */
#else
float remainderf(x,y) /* wrapper remainder */
float x,y;
#endif
{
#ifdef _IEEE_LIBM
return __ieee754_remainderf(x,y);
#else
float z;
struct exception exc;
z = __ieee754_remainderf(x,y);
if(_LIB_VERSION == _IEEE_ || isnan(y)) return z;
if(y==(float)0.0) {
/* remainderf(x,0) */
exc.type = DOMAIN;
exc.name = "remainderf";
exc.err = 0;
exc.arg1 = (double)x;
exc.arg2 = (double)y;
exc.retval = 0.0/0.0;
if (_LIB_VERSION == _POSIX_)
errno = EDOM;
else if (!matherr(&exc)) {
errno = EDOM;
}
if (exc.err != 0)
errno = exc.err;
return (float)exc.retval;
} else
return z;
#endif
}
#ifdef _DOUBLE_IS_32BITS
#ifdef __STDC__
double remainder(double x, double y)
#else
double remainder(x,y)
double x,y;
#endif
{
return (double) remainderf((float) x, (float) y);
}
#endif /* defined(_DOUBLE_IS_32BITS) */
| gpl-2.0 |
TheCollective/android_kernel_samsung_i927 | arch/arm/mach-omap2/omap_hwmod_3xxx_data.c | 393 | 85109 | /*
* omap_hwmod_3xxx_data.c - hardware modules present on the OMAP3xxx chips
*
* Copyright (C) 2009-2011 Nokia Corporation
* Paul Walmsley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* The data in this file should be completely autogeneratable from
* the TI hardware database or other technical documentation.
*
* XXX these should be marked initdata for multi-OMAP kernels
*/
#include <plat/omap_hwmod.h>
#include <mach/irqs.h>
#include <plat/cpu.h>
#include <plat/dma.h>
#include <plat/serial.h>
#include <plat/l3_3xxx.h>
#include <plat/l4_3xxx.h>
#include <plat/i2c.h>
#include <plat/gpio.h>
#include <plat/mmc.h>
#include <plat/mcbsp.h>
#include <plat/mcspi.h>
#include <plat/dmtimer.h>
#include "omap_hwmod_common_data.h"
#include "prm-regbits-34xx.h"
#include "cm-regbits-34xx.h"
#include "wd_timer.h"
#include <mach/am35xx.h>
/*
* OMAP3xxx hardware module integration data
*
* ALl of the data in this section should be autogeneratable from the
* TI hardware database or other technical documentation. Data that
* is driver-specific or driver-kernel integration-specific belongs
* elsewhere.
*/
static struct omap_hwmod omap3xxx_mpu_hwmod;
static struct omap_hwmod omap3xxx_iva_hwmod;
static struct omap_hwmod omap3xxx_l3_main_hwmod;
static struct omap_hwmod omap3xxx_l4_core_hwmod;
static struct omap_hwmod omap3xxx_l4_per_hwmod;
static struct omap_hwmod omap3xxx_wd_timer2_hwmod;
static struct omap_hwmod omap3430es1_dss_core_hwmod;
static struct omap_hwmod omap3xxx_dss_core_hwmod;
static struct omap_hwmod omap3xxx_dss_dispc_hwmod;
static struct omap_hwmod omap3xxx_dss_dsi1_hwmod;
static struct omap_hwmod omap3xxx_dss_rfbi_hwmod;
static struct omap_hwmod omap3xxx_dss_venc_hwmod;
static struct omap_hwmod omap3xxx_i2c1_hwmod;
static struct omap_hwmod omap3xxx_i2c2_hwmod;
static struct omap_hwmod omap3xxx_i2c3_hwmod;
static struct omap_hwmod omap3xxx_gpio1_hwmod;
static struct omap_hwmod omap3xxx_gpio2_hwmod;
static struct omap_hwmod omap3xxx_gpio3_hwmod;
static struct omap_hwmod omap3xxx_gpio4_hwmod;
static struct omap_hwmod omap3xxx_gpio5_hwmod;
static struct omap_hwmod omap3xxx_gpio6_hwmod;
static struct omap_hwmod omap34xx_sr1_hwmod;
static struct omap_hwmod omap34xx_sr2_hwmod;
static struct omap_hwmod omap34xx_mcspi1;
static struct omap_hwmod omap34xx_mcspi2;
static struct omap_hwmod omap34xx_mcspi3;
static struct omap_hwmod omap34xx_mcspi4;
static struct omap_hwmod omap3xxx_mmc1_hwmod;
static struct omap_hwmod omap3xxx_mmc2_hwmod;
static struct omap_hwmod omap3xxx_mmc3_hwmod;
static struct omap_hwmod am35xx_usbhsotg_hwmod;
static struct omap_hwmod omap3xxx_dma_system_hwmod;
static struct omap_hwmod omap3xxx_mcbsp1_hwmod;
static struct omap_hwmod omap3xxx_mcbsp2_hwmod;
static struct omap_hwmod omap3xxx_mcbsp3_hwmod;
static struct omap_hwmod omap3xxx_mcbsp4_hwmod;
static struct omap_hwmod omap3xxx_mcbsp5_hwmod;
static struct omap_hwmod omap3xxx_mcbsp2_sidetone_hwmod;
static struct omap_hwmod omap3xxx_mcbsp3_sidetone_hwmod;
/* L3 -> L4_CORE interface */
static struct omap_hwmod_ocp_if omap3xxx_l3_main__l4_core = {
.master = &omap3xxx_l3_main_hwmod,
.slave = &omap3xxx_l4_core_hwmod,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L3 -> L4_PER interface */
static struct omap_hwmod_ocp_if omap3xxx_l3_main__l4_per = {
.master = &omap3xxx_l3_main_hwmod,
.slave = &omap3xxx_l4_per_hwmod,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L3 taret configuration and error log registers */
static struct omap_hwmod_irq_info omap3xxx_l3_main_irqs[] = {
{ .irq = INT_34XX_L3_DBG_IRQ },
{ .irq = INT_34XX_L3_APP_IRQ },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_l3_main_addrs[] = {
{
.pa_start = 0x68000000,
.pa_end = 0x6800ffff,
.flags = ADDR_TYPE_RT,
},
{ }
};
/* MPU -> L3 interface */
static struct omap_hwmod_ocp_if omap3xxx_mpu__l3_main = {
.master = &omap3xxx_mpu_hwmod,
.slave = &omap3xxx_l3_main_hwmod,
.addr = omap3xxx_l3_main_addrs,
.user = OCP_USER_MPU,
};
/* Slave interfaces on the L3 interconnect */
static struct omap_hwmod_ocp_if *omap3xxx_l3_main_slaves[] = {
&omap3xxx_mpu__l3_main,
};
/* DSS -> l3 */
static struct omap_hwmod_ocp_if omap3xxx_dss__l3 = {
.master = &omap3xxx_dss_core_hwmod,
.slave = &omap3xxx_l3_main_hwmod,
.fw = {
.omap2 = {
.l3_perm_bit = OMAP3_L3_CORE_FW_INIT_ID_DSS,
.flags = OMAP_FIREWALL_L3,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* Master interfaces on the L3 interconnect */
static struct omap_hwmod_ocp_if *omap3xxx_l3_main_masters[] = {
&omap3xxx_l3_main__l4_core,
&omap3xxx_l3_main__l4_per,
};
/* L3 */
static struct omap_hwmod omap3xxx_l3_main_hwmod = {
.name = "l3_main",
.class = &l3_hwmod_class,
.mpu_irqs = omap3xxx_l3_main_irqs,
.masters = omap3xxx_l3_main_masters,
.masters_cnt = ARRAY_SIZE(omap3xxx_l3_main_masters),
.slaves = omap3xxx_l3_main_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_l3_main_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
.flags = HWMOD_NO_IDLEST,
};
static struct omap_hwmod omap3xxx_l4_wkup_hwmod;
static struct omap_hwmod omap3xxx_uart1_hwmod;
static struct omap_hwmod omap3xxx_uart2_hwmod;
static struct omap_hwmod omap3xxx_uart3_hwmod;
static struct omap_hwmod omap3xxx_uart4_hwmod;
static struct omap_hwmod omap3xxx_usbhsotg_hwmod;
/* l3_core -> usbhsotg interface */
static struct omap_hwmod_ocp_if omap3xxx_usbhsotg__l3 = {
.master = &omap3xxx_usbhsotg_hwmod,
.slave = &omap3xxx_l3_main_hwmod,
.clk = "core_l3_ick",
.user = OCP_USER_MPU,
};
/* l3_core -> am35xx_usbhsotg interface */
static struct omap_hwmod_ocp_if am35xx_usbhsotg__l3 = {
.master = &am35xx_usbhsotg_hwmod,
.slave = &omap3xxx_l3_main_hwmod,
.clk = "core_l3_ick",
.user = OCP_USER_MPU,
};
/* L4_CORE -> L4_WKUP interface */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__l4_wkup = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_l4_wkup_hwmod,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 CORE -> MMC1 interface */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__mmc1 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_mmc1_hwmod,
.clk = "mmchs1_ick",
.addr = omap2430_mmc1_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
.flags = OMAP_FIREWALL_L4
};
/* L4 CORE -> MMC2 interface */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__mmc2 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_mmc2_hwmod,
.clk = "mmchs2_ick",
.addr = omap2430_mmc2_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
.flags = OMAP_FIREWALL_L4
};
/* L4 CORE -> MMC3 interface */
static struct omap_hwmod_addr_space omap3xxx_mmc3_addr_space[] = {
{
.pa_start = 0x480ad000,
.pa_end = 0x480ad1ff,
.flags = ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_core__mmc3 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_mmc3_hwmod,
.clk = "mmchs3_ick",
.addr = omap3xxx_mmc3_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
.flags = OMAP_FIREWALL_L4
};
/* L4 CORE -> UART1 interface */
static struct omap_hwmod_addr_space omap3xxx_uart1_addr_space[] = {
{
.pa_start = OMAP3_UART1_BASE,
.pa_end = OMAP3_UART1_BASE + SZ_8K - 1,
.flags = ADDR_MAP_ON_INIT | ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3_l4_core__uart1 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_uart1_hwmod,
.clk = "uart1_ick",
.addr = omap3xxx_uart1_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 CORE -> UART2 interface */
static struct omap_hwmod_addr_space omap3xxx_uart2_addr_space[] = {
{
.pa_start = OMAP3_UART2_BASE,
.pa_end = OMAP3_UART2_BASE + SZ_1K - 1,
.flags = ADDR_MAP_ON_INIT | ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3_l4_core__uart2 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_uart2_hwmod,
.clk = "uart2_ick",
.addr = omap3xxx_uart2_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 PER -> UART3 interface */
static struct omap_hwmod_addr_space omap3xxx_uart3_addr_space[] = {
{
.pa_start = OMAP3_UART3_BASE,
.pa_end = OMAP3_UART3_BASE + SZ_1K - 1,
.flags = ADDR_MAP_ON_INIT | ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3_l4_per__uart3 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_uart3_hwmod,
.clk = "uart3_ick",
.addr = omap3xxx_uart3_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 PER -> UART4 interface */
static struct omap_hwmod_addr_space omap3xxx_uart4_addr_space[] = {
{
.pa_start = OMAP3_UART4_BASE,
.pa_end = OMAP3_UART4_BASE + SZ_1K - 1,
.flags = ADDR_MAP_ON_INIT | ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3_l4_per__uart4 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_uart4_hwmod,
.clk = "uart4_ick",
.addr = omap3xxx_uart4_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 CORE -> I2C1 interface */
static struct omap_hwmod_ocp_if omap3_l4_core__i2c1 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_i2c1_hwmod,
.clk = "i2c1_ick",
.addr = omap2_i2c1_addr_space,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_I2C1_REGION,
.l4_prot_group = 7,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 CORE -> I2C2 interface */
static struct omap_hwmod_ocp_if omap3_l4_core__i2c2 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_i2c2_hwmod,
.clk = "i2c2_ick",
.addr = omap2_i2c2_addr_space,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_I2C2_REGION,
.l4_prot_group = 7,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 CORE -> I2C3 interface */
static struct omap_hwmod_addr_space omap3xxx_i2c3_addr_space[] = {
{
.pa_start = 0x48060000,
.pa_end = 0x48060000 + SZ_128 - 1,
.flags = ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3_l4_core__i2c3 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_i2c3_hwmod,
.clk = "i2c3_ick",
.addr = omap3xxx_i2c3_addr_space,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_I2C3_REGION,
.l4_prot_group = 7,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* L4 CORE -> SR1 interface */
static struct omap_hwmod_addr_space omap3_sr1_addr_space[] = {
{
.pa_start = OMAP34XX_SR1_BASE,
.pa_end = OMAP34XX_SR1_BASE + SZ_1K - 1,
.flags = ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3_l4_core__sr1 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap34xx_sr1_hwmod,
.clk = "sr_l4_ick",
.addr = omap3_sr1_addr_space,
.user = OCP_USER_MPU,
};
/* L4 CORE -> SR1 interface */
static struct omap_hwmod_addr_space omap3_sr2_addr_space[] = {
{
.pa_start = OMAP34XX_SR2_BASE,
.pa_end = OMAP34XX_SR2_BASE + SZ_1K - 1,
.flags = ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap3_l4_core__sr2 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap34xx_sr2_hwmod,
.clk = "sr_l4_ick",
.addr = omap3_sr2_addr_space,
.user = OCP_USER_MPU,
};
/*
* usbhsotg interface data
*/
static struct omap_hwmod_addr_space omap3xxx_usbhsotg_addrs[] = {
{
.pa_start = OMAP34XX_HSUSB_OTG_BASE,
.pa_end = OMAP34XX_HSUSB_OTG_BASE + SZ_4K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_core -> usbhsotg */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__usbhsotg = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_usbhsotg_hwmod,
.clk = "l4_ick",
.addr = omap3xxx_usbhsotg_addrs,
.user = OCP_USER_MPU,
};
static struct omap_hwmod_ocp_if *omap3xxx_usbhsotg_masters[] = {
&omap3xxx_usbhsotg__l3,
};
static struct omap_hwmod_ocp_if *omap3xxx_usbhsotg_slaves[] = {
&omap3xxx_l4_core__usbhsotg,
};
static struct omap_hwmod_addr_space am35xx_usbhsotg_addrs[] = {
{
.pa_start = AM35XX_IPSS_USBOTGSS_BASE,
.pa_end = AM35XX_IPSS_USBOTGSS_BASE + SZ_4K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_core -> usbhsotg */
static struct omap_hwmod_ocp_if am35xx_l4_core__usbhsotg = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &am35xx_usbhsotg_hwmod,
.clk = "l4_ick",
.addr = am35xx_usbhsotg_addrs,
.user = OCP_USER_MPU,
};
static struct omap_hwmod_ocp_if *am35xx_usbhsotg_masters[] = {
&am35xx_usbhsotg__l3,
};
static struct omap_hwmod_ocp_if *am35xx_usbhsotg_slaves[] = {
&am35xx_l4_core__usbhsotg,
};
/* Slave interfaces on the L4_CORE interconnect */
static struct omap_hwmod_ocp_if *omap3xxx_l4_core_slaves[] = {
&omap3xxx_l3_main__l4_core,
};
/* L4 CORE */
static struct omap_hwmod omap3xxx_l4_core_hwmod = {
.name = "l4_core",
.class = &l4_hwmod_class,
.slaves = omap3xxx_l4_core_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_l4_core_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
.flags = HWMOD_NO_IDLEST,
};
/* Slave interfaces on the L4_PER interconnect */
static struct omap_hwmod_ocp_if *omap3xxx_l4_per_slaves[] = {
&omap3xxx_l3_main__l4_per,
};
/* L4 PER */
static struct omap_hwmod omap3xxx_l4_per_hwmod = {
.name = "l4_per",
.class = &l4_hwmod_class,
.slaves = omap3xxx_l4_per_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_l4_per_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
.flags = HWMOD_NO_IDLEST,
};
/* Slave interfaces on the L4_WKUP interconnect */
static struct omap_hwmod_ocp_if *omap3xxx_l4_wkup_slaves[] = {
&omap3xxx_l4_core__l4_wkup,
};
/* L4 WKUP */
static struct omap_hwmod omap3xxx_l4_wkup_hwmod = {
.name = "l4_wkup",
.class = &l4_hwmod_class,
.slaves = omap3xxx_l4_wkup_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_l4_wkup_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
.flags = HWMOD_NO_IDLEST,
};
/* Master interfaces on the MPU device */
static struct omap_hwmod_ocp_if *omap3xxx_mpu_masters[] = {
&omap3xxx_mpu__l3_main,
};
/* MPU */
static struct omap_hwmod omap3xxx_mpu_hwmod = {
.name = "mpu",
.class = &mpu_hwmod_class,
.main_clk = "arm_fck",
.masters = omap3xxx_mpu_masters,
.masters_cnt = ARRAY_SIZE(omap3xxx_mpu_masters),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/*
* IVA2_2 interface data
*/
/* IVA2 <- L3 interface */
static struct omap_hwmod_ocp_if omap3xxx_l3__iva = {
.master = &omap3xxx_l3_main_hwmod,
.slave = &omap3xxx_iva_hwmod,
.clk = "iva2_ck",
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
static struct omap_hwmod_ocp_if *omap3xxx_iva_masters[] = {
&omap3xxx_l3__iva,
};
/*
* IVA2 (IVA2)
*/
static struct omap_hwmod omap3xxx_iva_hwmod = {
.name = "iva",
.class = &iva_hwmod_class,
.masters = omap3xxx_iva_masters,
.masters_cnt = ARRAY_SIZE(omap3xxx_iva_masters),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer class */
static struct omap_hwmod_class_sysconfig omap3xxx_timer_1ms_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_CLOCKACTIVITY |
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_EMUFREE | SYSC_HAS_AUTOIDLE),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap3xxx_timer_1ms_hwmod_class = {
.name = "timer",
.sysc = &omap3xxx_timer_1ms_sysc,
.rev = OMAP_TIMER_IP_VERSION_1,
};
static struct omap_hwmod_class_sysconfig omap3xxx_timer_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_ENAWAKEUP |
SYSC_HAS_SOFTRESET | SYSC_HAS_AUTOIDLE),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap3xxx_timer_hwmod_class = {
.name = "timer",
.sysc = &omap3xxx_timer_sysc,
.rev = OMAP_TIMER_IP_VERSION_1,
};
/* timer1 */
static struct omap_hwmod omap3xxx_timer1_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer1_addrs[] = {
{
.pa_start = 0x48318000,
.pa_end = 0x48318000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_wkup -> timer1 */
static struct omap_hwmod_ocp_if omap3xxx_l4_wkup__timer1 = {
.master = &omap3xxx_l4_wkup_hwmod,
.slave = &omap3xxx_timer1_hwmod,
.clk = "gpt1_ick",
.addr = omap3xxx_timer1_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer1 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer1_slaves[] = {
&omap3xxx_l4_wkup__timer1,
};
/* timer1 hwmod */
static struct omap_hwmod omap3xxx_timer1_hwmod = {
.name = "timer1",
.mpu_irqs = omap2_timer1_mpu_irqs,
.main_clk = "gpt1_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT1_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT1_SHIFT,
},
},
.slaves = omap3xxx_timer1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer1_slaves),
.class = &omap3xxx_timer_1ms_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer2 */
static struct omap_hwmod omap3xxx_timer2_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer2_addrs[] = {
{
.pa_start = 0x49032000,
.pa_end = 0x49032000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer2 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer2 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer2_hwmod,
.clk = "gpt2_ick",
.addr = omap3xxx_timer2_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer2 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer2_slaves[] = {
&omap3xxx_l4_per__timer2,
};
/* timer2 hwmod */
static struct omap_hwmod omap3xxx_timer2_hwmod = {
.name = "timer2",
.mpu_irqs = omap2_timer2_mpu_irqs,
.main_clk = "gpt2_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT2_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT2_SHIFT,
},
},
.slaves = omap3xxx_timer2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer2_slaves),
.class = &omap3xxx_timer_1ms_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer3 */
static struct omap_hwmod omap3xxx_timer3_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer3_addrs[] = {
{
.pa_start = 0x49034000,
.pa_end = 0x49034000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer3 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer3 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer3_hwmod,
.clk = "gpt3_ick",
.addr = omap3xxx_timer3_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer3 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer3_slaves[] = {
&omap3xxx_l4_per__timer3,
};
/* timer3 hwmod */
static struct omap_hwmod omap3xxx_timer3_hwmod = {
.name = "timer3",
.mpu_irqs = omap2_timer3_mpu_irqs,
.main_clk = "gpt3_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT3_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT3_SHIFT,
},
},
.slaves = omap3xxx_timer3_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer3_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer4 */
static struct omap_hwmod omap3xxx_timer4_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer4_addrs[] = {
{
.pa_start = 0x49036000,
.pa_end = 0x49036000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer4 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer4 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer4_hwmod,
.clk = "gpt4_ick",
.addr = omap3xxx_timer4_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer4 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer4_slaves[] = {
&omap3xxx_l4_per__timer4,
};
/* timer4 hwmod */
static struct omap_hwmod omap3xxx_timer4_hwmod = {
.name = "timer4",
.mpu_irqs = omap2_timer4_mpu_irqs,
.main_clk = "gpt4_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT4_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT4_SHIFT,
},
},
.slaves = omap3xxx_timer4_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer4_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer5 */
static struct omap_hwmod omap3xxx_timer5_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer5_addrs[] = {
{
.pa_start = 0x49038000,
.pa_end = 0x49038000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer5 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer5 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer5_hwmod,
.clk = "gpt5_ick",
.addr = omap3xxx_timer5_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer5 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer5_slaves[] = {
&omap3xxx_l4_per__timer5,
};
/* timer5 hwmod */
static struct omap_hwmod omap3xxx_timer5_hwmod = {
.name = "timer5",
.mpu_irqs = omap2_timer5_mpu_irqs,
.main_clk = "gpt5_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT5_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT5_SHIFT,
},
},
.slaves = omap3xxx_timer5_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer5_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer6 */
static struct omap_hwmod omap3xxx_timer6_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer6_addrs[] = {
{
.pa_start = 0x4903A000,
.pa_end = 0x4903A000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer6 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer6 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer6_hwmod,
.clk = "gpt6_ick",
.addr = omap3xxx_timer6_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer6 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer6_slaves[] = {
&omap3xxx_l4_per__timer6,
};
/* timer6 hwmod */
static struct omap_hwmod omap3xxx_timer6_hwmod = {
.name = "timer6",
.mpu_irqs = omap2_timer6_mpu_irqs,
.main_clk = "gpt6_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT6_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT6_SHIFT,
},
},
.slaves = omap3xxx_timer6_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer6_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer7 */
static struct omap_hwmod omap3xxx_timer7_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer7_addrs[] = {
{
.pa_start = 0x4903C000,
.pa_end = 0x4903C000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer7 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer7 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer7_hwmod,
.clk = "gpt7_ick",
.addr = omap3xxx_timer7_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer7 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer7_slaves[] = {
&omap3xxx_l4_per__timer7,
};
/* timer7 hwmod */
static struct omap_hwmod omap3xxx_timer7_hwmod = {
.name = "timer7",
.mpu_irqs = omap2_timer7_mpu_irqs,
.main_clk = "gpt7_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT7_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT7_SHIFT,
},
},
.slaves = omap3xxx_timer7_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer7_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer8 */
static struct omap_hwmod omap3xxx_timer8_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer8_addrs[] = {
{
.pa_start = 0x4903E000,
.pa_end = 0x4903E000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer8 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer8 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer8_hwmod,
.clk = "gpt8_ick",
.addr = omap3xxx_timer8_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer8 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer8_slaves[] = {
&omap3xxx_l4_per__timer8,
};
/* timer8 hwmod */
static struct omap_hwmod omap3xxx_timer8_hwmod = {
.name = "timer8",
.mpu_irqs = omap2_timer8_mpu_irqs,
.main_clk = "gpt8_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT8_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT8_SHIFT,
},
},
.slaves = omap3xxx_timer8_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer8_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer9 */
static struct omap_hwmod omap3xxx_timer9_hwmod;
static struct omap_hwmod_addr_space omap3xxx_timer9_addrs[] = {
{
.pa_start = 0x49040000,
.pa_end = 0x49040000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> timer9 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__timer9 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_timer9_hwmod,
.clk = "gpt9_ick",
.addr = omap3xxx_timer9_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer9 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer9_slaves[] = {
&omap3xxx_l4_per__timer9,
};
/* timer9 hwmod */
static struct omap_hwmod omap3xxx_timer9_hwmod = {
.name = "timer9",
.mpu_irqs = omap2_timer9_mpu_irqs,
.main_clk = "gpt9_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT9_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT9_SHIFT,
},
},
.slaves = omap3xxx_timer9_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer9_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer10 */
static struct omap_hwmod omap3xxx_timer10_hwmod;
/* l4_core -> timer10 */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__timer10 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_timer10_hwmod,
.clk = "gpt10_ick",
.addr = omap2_timer10_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer10 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer10_slaves[] = {
&omap3xxx_l4_core__timer10,
};
/* timer10 hwmod */
static struct omap_hwmod omap3xxx_timer10_hwmod = {
.name = "timer10",
.mpu_irqs = omap2_timer10_mpu_irqs,
.main_clk = "gpt10_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT10_SHIFT,
.module_offs = CORE_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT10_SHIFT,
},
},
.slaves = omap3xxx_timer10_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer10_slaves),
.class = &omap3xxx_timer_1ms_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer11 */
static struct omap_hwmod omap3xxx_timer11_hwmod;
/* l4_core -> timer11 */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__timer11 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_timer11_hwmod,
.clk = "gpt11_ick",
.addr = omap2_timer11_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer11 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer11_slaves[] = {
&omap3xxx_l4_core__timer11,
};
/* timer11 hwmod */
static struct omap_hwmod omap3xxx_timer11_hwmod = {
.name = "timer11",
.mpu_irqs = omap2_timer11_mpu_irqs,
.main_clk = "gpt11_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT11_SHIFT,
.module_offs = CORE_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT11_SHIFT,
},
},
.slaves = omap3xxx_timer11_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer11_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* timer12*/
static struct omap_hwmod omap3xxx_timer12_hwmod;
static struct omap_hwmod_irq_info omap3xxx_timer12_mpu_irqs[] = {
{ .irq = 95, },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_timer12_addrs[] = {
{
.pa_start = 0x48304000,
.pa_end = 0x48304000 + SZ_1K - 1,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_core -> timer12 */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__timer12 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_timer12_hwmod,
.clk = "gpt12_ick",
.addr = omap3xxx_timer12_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* timer12 slave port */
static struct omap_hwmod_ocp_if *omap3xxx_timer12_slaves[] = {
&omap3xxx_l4_core__timer12,
};
/* timer12 hwmod */
static struct omap_hwmod omap3xxx_timer12_hwmod = {
.name = "timer12",
.mpu_irqs = omap3xxx_timer12_mpu_irqs,
.main_clk = "gpt12_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPT12_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPT12_SHIFT,
},
},
.slaves = omap3xxx_timer12_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_timer12_slaves),
.class = &omap3xxx_timer_hwmod_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* l4_wkup -> wd_timer2 */
static struct omap_hwmod_addr_space omap3xxx_wd_timer2_addrs[] = {
{
.pa_start = 0x48314000,
.pa_end = 0x4831407f,
.flags = ADDR_TYPE_RT
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_wkup__wd_timer2 = {
.master = &omap3xxx_l4_wkup_hwmod,
.slave = &omap3xxx_wd_timer2_hwmod,
.clk = "wdt2_ick",
.addr = omap3xxx_wd_timer2_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/*
* 'wd_timer' class
* 32-bit watchdog upward counter that generates a pulse on the reset pin on
* overflow condition
*/
static struct omap_hwmod_class_sysconfig omap3xxx_wd_timer_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_EMUFREE |
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE | SYSC_HAS_CLOCKACTIVITY |
SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
/* I2C common */
static struct omap_hwmod_class_sysconfig i2c_sysc = {
.rev_offs = 0x00,
.sysc_offs = 0x20,
.syss_offs = 0x10,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_SIDLEMODE |
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE | SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap3xxx_wd_timer_hwmod_class = {
.name = "wd_timer",
.sysc = &omap3xxx_wd_timer_sysc,
.pre_shutdown = &omap2_wd_timer_disable
};
/* wd_timer2 */
static struct omap_hwmod_ocp_if *omap3xxx_wd_timer2_slaves[] = {
&omap3xxx_l4_wkup__wd_timer2,
};
static struct omap_hwmod omap3xxx_wd_timer2_hwmod = {
.name = "wd_timer2",
.class = &omap3xxx_wd_timer_hwmod_class,
.main_clk = "wdt2_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_WDT2_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_WDT2_SHIFT,
},
},
.slaves = omap3xxx_wd_timer2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_wd_timer2_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
/*
* XXX: Use software supervised mode, HW supervised smartidle seems to
* block CORE power domain idle transitions. Maybe a HW bug in wdt2?
*/
.flags = HWMOD_SWSUP_SIDLE,
};
/* UART1 */
static struct omap_hwmod_ocp_if *omap3xxx_uart1_slaves[] = {
&omap3_l4_core__uart1,
};
static struct omap_hwmod omap3xxx_uart1_hwmod = {
.name = "uart1",
.mpu_irqs = omap2_uart1_mpu_irqs,
.sdma_reqs = omap2_uart1_sdma_reqs,
.main_clk = "uart1_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_UART1_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_EN_UART1_SHIFT,
},
},
.slaves = omap3xxx_uart1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_uart1_slaves),
.class = &omap2_uart_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* UART2 */
static struct omap_hwmod_ocp_if *omap3xxx_uart2_slaves[] = {
&omap3_l4_core__uart2,
};
static struct omap_hwmod omap3xxx_uart2_hwmod = {
.name = "uart2",
.mpu_irqs = omap2_uart2_mpu_irqs,
.sdma_reqs = omap2_uart2_sdma_reqs,
.main_clk = "uart2_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_UART2_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_EN_UART2_SHIFT,
},
},
.slaves = omap3xxx_uart2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_uart2_slaves),
.class = &omap2_uart_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* UART3 */
static struct omap_hwmod_ocp_if *omap3xxx_uart3_slaves[] = {
&omap3_l4_per__uart3,
};
static struct omap_hwmod omap3xxx_uart3_hwmod = {
.name = "uart3",
.mpu_irqs = omap2_uart3_mpu_irqs,
.sdma_reqs = omap2_uart3_sdma_reqs,
.main_clk = "uart3_fck",
.prcm = {
.omap2 = {
.module_offs = OMAP3430_PER_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_UART3_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_EN_UART3_SHIFT,
},
},
.slaves = omap3xxx_uart3_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_uart3_slaves),
.class = &omap2_uart_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* UART4 */
static struct omap_hwmod_irq_info uart4_mpu_irqs[] = {
{ .irq = INT_36XX_UART4_IRQ, },
{ .irq = -1 }
};
static struct omap_hwmod_dma_info uart4_sdma_reqs[] = {
{ .name = "rx", .dma_req = OMAP36XX_DMA_UART4_RX, },
{ .name = "tx", .dma_req = OMAP36XX_DMA_UART4_TX, },
{ .dma_req = -1 }
};
static struct omap_hwmod_ocp_if *omap3xxx_uart4_slaves[] = {
&omap3_l4_per__uart4,
};
static struct omap_hwmod omap3xxx_uart4_hwmod = {
.name = "uart4",
.mpu_irqs = uart4_mpu_irqs,
.sdma_reqs = uart4_sdma_reqs,
.main_clk = "uart4_fck",
.prcm = {
.omap2 = {
.module_offs = OMAP3430_PER_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3630_EN_UART4_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3630_EN_UART4_SHIFT,
},
},
.slaves = omap3xxx_uart4_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_uart4_slaves),
.class = &omap2_uart_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3630ES1),
};
static struct omap_hwmod_class i2c_class = {
.name = "i2c",
.sysc = &i2c_sysc,
.rev = OMAP_I2C_IP_VERSION_1,
.reset = &omap_i2c_reset,
};
static struct omap_hwmod_dma_info omap3xxx_dss_sdma_chs[] = {
{ .name = "dispc", .dma_req = 5 },
{ .name = "dsi1", .dma_req = 74 },
{ .dma_req = -1 }
};
/* dss */
/* dss master ports */
static struct omap_hwmod_ocp_if *omap3xxx_dss_masters[] = {
&omap3xxx_dss__l3,
};
/* l4_core -> dss */
static struct omap_hwmod_ocp_if omap3430es1_l4_core__dss = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3430es1_dss_core_hwmod,
.clk = "dss_ick",
.addr = omap2_dss_addrs,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3ES1_L4_CORE_FW_DSS_CORE_REGION,
.l4_prot_group = OMAP3_L4_CORE_FW_DSS_PROT_GROUP,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
static struct omap_hwmod_ocp_if omap3xxx_l4_core__dss = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_dss_core_hwmod,
.clk = "dss_ick",
.addr = omap2_dss_addrs,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_DSS_CORE_REGION,
.l4_prot_group = OMAP3_L4_CORE_FW_DSS_PROT_GROUP,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* dss slave ports */
static struct omap_hwmod_ocp_if *omap3430es1_dss_slaves[] = {
&omap3430es1_l4_core__dss,
};
static struct omap_hwmod_ocp_if *omap3xxx_dss_slaves[] = {
&omap3xxx_l4_core__dss,
};
static struct omap_hwmod_opt_clk dss_opt_clks[] = {
{ .role = "tv_clk", .clk = "dss_tv_fck" },
{ .role = "video_clk", .clk = "dss_96m_fck" },
{ .role = "sys_clk", .clk = "dss2_alwon_fck" },
};
static struct omap_hwmod omap3430es1_dss_core_hwmod = {
.name = "dss_core",
.class = &omap2_dss_hwmod_class,
.main_clk = "dss1_alwon_fck", /* instead of dss_fck */
.sdma_reqs = omap3xxx_dss_sdma_chs,
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_DSS1_SHIFT,
.module_offs = OMAP3430_DSS_MOD,
.idlest_reg_id = 1,
.idlest_stdby_bit = OMAP3430ES1_ST_DSS_SHIFT,
},
},
.opt_clks = dss_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(dss_opt_clks),
.slaves = omap3430es1_dss_slaves,
.slaves_cnt = ARRAY_SIZE(omap3430es1_dss_slaves),
.masters = omap3xxx_dss_masters,
.masters_cnt = ARRAY_SIZE(omap3xxx_dss_masters),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES1),
.flags = HWMOD_NO_IDLEST,
};
static struct omap_hwmod omap3xxx_dss_core_hwmod = {
.name = "dss_core",
.class = &omap2_dss_hwmod_class,
.main_clk = "dss1_alwon_fck", /* instead of dss_fck */
.sdma_reqs = omap3xxx_dss_sdma_chs,
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_DSS1_SHIFT,
.module_offs = OMAP3430_DSS_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430ES2_ST_DSS_IDLE_SHIFT,
.idlest_stdby_bit = OMAP3430ES2_ST_DSS_STDBY_SHIFT,
},
},
.opt_clks = dss_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(dss_opt_clks),
.slaves = omap3xxx_dss_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_dss_slaves),
.masters = omap3xxx_dss_masters,
.masters_cnt = ARRAY_SIZE(omap3xxx_dss_masters),
.omap_chip = OMAP_CHIP_INIT(CHIP_GE_OMAP3430ES2 |
CHIP_IS_OMAP3630ES1 | CHIP_GE_OMAP3630ES1_1),
};
/* l4_core -> dss_dispc */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__dss_dispc = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_dss_dispc_hwmod,
.clk = "dss_ick",
.addr = omap2_dss_dispc_addrs,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_DSS_DISPC_REGION,
.l4_prot_group = OMAP3_L4_CORE_FW_DSS_PROT_GROUP,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* dss_dispc slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_dss_dispc_slaves[] = {
&omap3xxx_l4_core__dss_dispc,
};
static struct omap_hwmod omap3xxx_dss_dispc_hwmod = {
.name = "dss_dispc",
.class = &omap2_dispc_hwmod_class,
.mpu_irqs = omap2_dispc_irqs,
.main_clk = "dss1_alwon_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_DSS1_SHIFT,
.module_offs = OMAP3430_DSS_MOD,
},
},
.slaves = omap3xxx_dss_dispc_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_dss_dispc_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES1 |
CHIP_GE_OMAP3430ES2 | CHIP_IS_OMAP3630ES1 |
CHIP_GE_OMAP3630ES1_1),
.flags = HWMOD_NO_IDLEST,
};
/*
* 'dsi' class
* display serial interface controller
*/
static struct omap_hwmod_class omap3xxx_dsi_hwmod_class = {
.name = "dsi",
};
static struct omap_hwmod_irq_info omap3xxx_dsi1_irqs[] = {
{ .irq = 25 },
{ .irq = -1 }
};
/* dss_dsi1 */
static struct omap_hwmod_addr_space omap3xxx_dss_dsi1_addrs[] = {
{
.pa_start = 0x4804FC00,
.pa_end = 0x4804FFFF,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_core -> dss_dsi1 */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__dss_dsi1 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_dss_dsi1_hwmod,
.addr = omap3xxx_dss_dsi1_addrs,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_DSS_DSI_REGION,
.l4_prot_group = OMAP3_L4_CORE_FW_DSS_PROT_GROUP,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* dss_dsi1 slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_dss_dsi1_slaves[] = {
&omap3xxx_l4_core__dss_dsi1,
};
static struct omap_hwmod omap3xxx_dss_dsi1_hwmod = {
.name = "dss_dsi1",
.class = &omap3xxx_dsi_hwmod_class,
.mpu_irqs = omap3xxx_dsi1_irqs,
.main_clk = "dss1_alwon_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_DSS1_SHIFT,
.module_offs = OMAP3430_DSS_MOD,
},
},
.slaves = omap3xxx_dss_dsi1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_dss_dsi1_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES1 |
CHIP_GE_OMAP3430ES2 | CHIP_IS_OMAP3630ES1 |
CHIP_GE_OMAP3630ES1_1),
.flags = HWMOD_NO_IDLEST,
};
/* l4_core -> dss_rfbi */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__dss_rfbi = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_dss_rfbi_hwmod,
.clk = "dss_ick",
.addr = omap2_dss_rfbi_addrs,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_DSS_RFBI_REGION,
.l4_prot_group = OMAP3_L4_CORE_FW_DSS_PROT_GROUP ,
.flags = OMAP_FIREWALL_L4,
}
},
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* dss_rfbi slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_dss_rfbi_slaves[] = {
&omap3xxx_l4_core__dss_rfbi,
};
static struct omap_hwmod omap3xxx_dss_rfbi_hwmod = {
.name = "dss_rfbi",
.class = &omap2_rfbi_hwmod_class,
.main_clk = "dss1_alwon_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_DSS1_SHIFT,
.module_offs = OMAP3430_DSS_MOD,
},
},
.slaves = omap3xxx_dss_rfbi_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_dss_rfbi_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES1 |
CHIP_GE_OMAP3430ES2 | CHIP_IS_OMAP3630ES1 |
CHIP_GE_OMAP3630ES1_1),
.flags = HWMOD_NO_IDLEST,
};
/* l4_core -> dss_venc */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__dss_venc = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_dss_venc_hwmod,
.clk = "dss_tv_fck",
.addr = omap2_dss_venc_addrs,
.fw = {
.omap2 = {
.l4_fw_region = OMAP3_L4_CORE_FW_DSS_VENC_REGION,
.l4_prot_group = OMAP3_L4_CORE_FW_DSS_PROT_GROUP,
.flags = OMAP_FIREWALL_L4,
}
},
.flags = OCPIF_SWSUP_IDLE,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* dss_venc slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_dss_venc_slaves[] = {
&omap3xxx_l4_core__dss_venc,
};
static struct omap_hwmod omap3xxx_dss_venc_hwmod = {
.name = "dss_venc",
.class = &omap2_venc_hwmod_class,
.main_clk = "dss1_alwon_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_DSS1_SHIFT,
.module_offs = OMAP3430_DSS_MOD,
},
},
.slaves = omap3xxx_dss_venc_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_dss_venc_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES1 |
CHIP_GE_OMAP3430ES2 | CHIP_IS_OMAP3630ES1 |
CHIP_GE_OMAP3630ES1_1),
.flags = HWMOD_NO_IDLEST,
};
/* I2C1 */
static struct omap_i2c_dev_attr i2c1_dev_attr = {
.fifo_depth = 8, /* bytes */
.flags = OMAP_I2C_FLAG_APPLY_ERRATA_I207 |
OMAP_I2C_FLAG_RESET_REGS_POSTIDLE |
OMAP_I2C_FLAG_BUS_SHIFT_2,
};
static struct omap_hwmod_ocp_if *omap3xxx_i2c1_slaves[] = {
&omap3_l4_core__i2c1,
};
static struct omap_hwmod omap3xxx_i2c1_hwmod = {
.name = "i2c1",
.flags = HWMOD_16BIT_REG,
.mpu_irqs = omap2_i2c1_mpu_irqs,
.sdma_reqs = omap2_i2c1_sdma_reqs,
.main_clk = "i2c1_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_I2C1_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_I2C1_SHIFT,
},
},
.slaves = omap3xxx_i2c1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_i2c1_slaves),
.class = &i2c_class,
.dev_attr = &i2c1_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* I2C2 */
static struct omap_i2c_dev_attr i2c2_dev_attr = {
.fifo_depth = 8, /* bytes */
.flags = OMAP_I2C_FLAG_APPLY_ERRATA_I207 |
OMAP_I2C_FLAG_RESET_REGS_POSTIDLE |
OMAP_I2C_FLAG_BUS_SHIFT_2,
};
static struct omap_hwmod_ocp_if *omap3xxx_i2c2_slaves[] = {
&omap3_l4_core__i2c2,
};
static struct omap_hwmod omap3xxx_i2c2_hwmod = {
.name = "i2c2",
.flags = HWMOD_16BIT_REG,
.mpu_irqs = omap2_i2c2_mpu_irqs,
.sdma_reqs = omap2_i2c2_sdma_reqs,
.main_clk = "i2c2_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_I2C2_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_I2C2_SHIFT,
},
},
.slaves = omap3xxx_i2c2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_i2c2_slaves),
.class = &i2c_class,
.dev_attr = &i2c2_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* I2C3 */
static struct omap_i2c_dev_attr i2c3_dev_attr = {
.fifo_depth = 64, /* bytes */
.flags = OMAP_I2C_FLAG_APPLY_ERRATA_I207 |
OMAP_I2C_FLAG_RESET_REGS_POSTIDLE |
OMAP_I2C_FLAG_BUS_SHIFT_2,
};
static struct omap_hwmod_irq_info i2c3_mpu_irqs[] = {
{ .irq = INT_34XX_I2C3_IRQ, },
{ .irq = -1 }
};
static struct omap_hwmod_dma_info i2c3_sdma_reqs[] = {
{ .name = "tx", .dma_req = OMAP34XX_DMA_I2C3_TX },
{ .name = "rx", .dma_req = OMAP34XX_DMA_I2C3_RX },
{ .dma_req = -1 }
};
static struct omap_hwmod_ocp_if *omap3xxx_i2c3_slaves[] = {
&omap3_l4_core__i2c3,
};
static struct omap_hwmod omap3xxx_i2c3_hwmod = {
.name = "i2c3",
.flags = HWMOD_16BIT_REG,
.mpu_irqs = i2c3_mpu_irqs,
.sdma_reqs = i2c3_sdma_reqs,
.main_clk = "i2c3_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_I2C3_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_I2C3_SHIFT,
},
},
.slaves = omap3xxx_i2c3_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_i2c3_slaves),
.class = &i2c_class,
.dev_attr = &i2c3_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* l4_wkup -> gpio1 */
static struct omap_hwmod_addr_space omap3xxx_gpio1_addrs[] = {
{
.pa_start = 0x48310000,
.pa_end = 0x483101ff,
.flags = ADDR_TYPE_RT
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_wkup__gpio1 = {
.master = &omap3xxx_l4_wkup_hwmod,
.slave = &omap3xxx_gpio1_hwmod,
.addr = omap3xxx_gpio1_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4_per -> gpio2 */
static struct omap_hwmod_addr_space omap3xxx_gpio2_addrs[] = {
{
.pa_start = 0x49050000,
.pa_end = 0x490501ff,
.flags = ADDR_TYPE_RT
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_per__gpio2 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_gpio2_hwmod,
.addr = omap3xxx_gpio2_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4_per -> gpio3 */
static struct omap_hwmod_addr_space omap3xxx_gpio3_addrs[] = {
{
.pa_start = 0x49052000,
.pa_end = 0x490521ff,
.flags = ADDR_TYPE_RT
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_per__gpio3 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_gpio3_hwmod,
.addr = omap3xxx_gpio3_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4_per -> gpio4 */
static struct omap_hwmod_addr_space omap3xxx_gpio4_addrs[] = {
{
.pa_start = 0x49054000,
.pa_end = 0x490541ff,
.flags = ADDR_TYPE_RT
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_per__gpio4 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_gpio4_hwmod,
.addr = omap3xxx_gpio4_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4_per -> gpio5 */
static struct omap_hwmod_addr_space omap3xxx_gpio5_addrs[] = {
{
.pa_start = 0x49056000,
.pa_end = 0x490561ff,
.flags = ADDR_TYPE_RT
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_per__gpio5 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_gpio5_hwmod,
.addr = omap3xxx_gpio5_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4_per -> gpio6 */
static struct omap_hwmod_addr_space omap3xxx_gpio6_addrs[] = {
{
.pa_start = 0x49058000,
.pa_end = 0x490581ff,
.flags = ADDR_TYPE_RT
},
{ }
};
static struct omap_hwmod_ocp_if omap3xxx_l4_per__gpio6 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_gpio6_hwmod,
.addr = omap3xxx_gpio6_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/*
* 'gpio' class
* general purpose io module
*/
static struct omap_hwmod_class_sysconfig omap3xxx_gpio_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_ENAWAKEUP | SYSC_HAS_SIDLEMODE |
SYSC_HAS_SOFTRESET | SYSC_HAS_AUTOIDLE |
SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap3xxx_gpio_hwmod_class = {
.name = "gpio",
.sysc = &omap3xxx_gpio_sysc,
.rev = 1,
};
/* gpio_dev_attr*/
static struct omap_gpio_dev_attr gpio_dev_attr = {
.bank_width = 32,
.dbck_flag = true,
};
/* gpio1 */
static struct omap_hwmod_opt_clk gpio1_opt_clks[] = {
{ .role = "dbclk", .clk = "gpio1_dbck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_gpio1_slaves[] = {
&omap3xxx_l4_wkup__gpio1,
};
static struct omap_hwmod omap3xxx_gpio1_hwmod = {
.name = "gpio1",
.flags = HWMOD_CONTROL_OPT_CLKS_IN_RESET,
.mpu_irqs = omap2_gpio1_irqs,
.main_clk = "gpio1_ick",
.opt_clks = gpio1_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(gpio1_opt_clks),
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPIO1_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPIO1_SHIFT,
},
},
.slaves = omap3xxx_gpio1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_gpio1_slaves),
.class = &omap3xxx_gpio_hwmod_class,
.dev_attr = &gpio_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* gpio2 */
static struct omap_hwmod_opt_clk gpio2_opt_clks[] = {
{ .role = "dbclk", .clk = "gpio2_dbck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_gpio2_slaves[] = {
&omap3xxx_l4_per__gpio2,
};
static struct omap_hwmod omap3xxx_gpio2_hwmod = {
.name = "gpio2",
.flags = HWMOD_CONTROL_OPT_CLKS_IN_RESET,
.mpu_irqs = omap2_gpio2_irqs,
.main_clk = "gpio2_ick",
.opt_clks = gpio2_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(gpio2_opt_clks),
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPIO2_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPIO2_SHIFT,
},
},
.slaves = omap3xxx_gpio2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_gpio2_slaves),
.class = &omap3xxx_gpio_hwmod_class,
.dev_attr = &gpio_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* gpio3 */
static struct omap_hwmod_opt_clk gpio3_opt_clks[] = {
{ .role = "dbclk", .clk = "gpio3_dbck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_gpio3_slaves[] = {
&omap3xxx_l4_per__gpio3,
};
static struct omap_hwmod omap3xxx_gpio3_hwmod = {
.name = "gpio3",
.flags = HWMOD_CONTROL_OPT_CLKS_IN_RESET,
.mpu_irqs = omap2_gpio3_irqs,
.main_clk = "gpio3_ick",
.opt_clks = gpio3_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(gpio3_opt_clks),
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPIO3_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPIO3_SHIFT,
},
},
.slaves = omap3xxx_gpio3_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_gpio3_slaves),
.class = &omap3xxx_gpio_hwmod_class,
.dev_attr = &gpio_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* gpio4 */
static struct omap_hwmod_opt_clk gpio4_opt_clks[] = {
{ .role = "dbclk", .clk = "gpio4_dbck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_gpio4_slaves[] = {
&omap3xxx_l4_per__gpio4,
};
static struct omap_hwmod omap3xxx_gpio4_hwmod = {
.name = "gpio4",
.flags = HWMOD_CONTROL_OPT_CLKS_IN_RESET,
.mpu_irqs = omap2_gpio4_irqs,
.main_clk = "gpio4_ick",
.opt_clks = gpio4_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(gpio4_opt_clks),
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPIO4_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPIO4_SHIFT,
},
},
.slaves = omap3xxx_gpio4_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_gpio4_slaves),
.class = &omap3xxx_gpio_hwmod_class,
.dev_attr = &gpio_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* gpio5 */
static struct omap_hwmod_irq_info omap3xxx_gpio5_irqs[] = {
{ .irq = 33 }, /* INT_34XX_GPIO_BANK5 */
{ .irq = -1 }
};
static struct omap_hwmod_opt_clk gpio5_opt_clks[] = {
{ .role = "dbclk", .clk = "gpio5_dbck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_gpio5_slaves[] = {
&omap3xxx_l4_per__gpio5,
};
static struct omap_hwmod omap3xxx_gpio5_hwmod = {
.name = "gpio5",
.flags = HWMOD_CONTROL_OPT_CLKS_IN_RESET,
.mpu_irqs = omap3xxx_gpio5_irqs,
.main_clk = "gpio5_ick",
.opt_clks = gpio5_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(gpio5_opt_clks),
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPIO5_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPIO5_SHIFT,
},
},
.slaves = omap3xxx_gpio5_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_gpio5_slaves),
.class = &omap3xxx_gpio_hwmod_class,
.dev_attr = &gpio_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* gpio6 */
static struct omap_hwmod_irq_info omap3xxx_gpio6_irqs[] = {
{ .irq = 34 }, /* INT_34XX_GPIO_BANK6 */
{ .irq = -1 }
};
static struct omap_hwmod_opt_clk gpio6_opt_clks[] = {
{ .role = "dbclk", .clk = "gpio6_dbck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_gpio6_slaves[] = {
&omap3xxx_l4_per__gpio6,
};
static struct omap_hwmod omap3xxx_gpio6_hwmod = {
.name = "gpio6",
.flags = HWMOD_CONTROL_OPT_CLKS_IN_RESET,
.mpu_irqs = omap3xxx_gpio6_irqs,
.main_clk = "gpio6_ick",
.opt_clks = gpio6_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(gpio6_opt_clks),
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_GPIO6_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_GPIO6_SHIFT,
},
},
.slaves = omap3xxx_gpio6_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_gpio6_slaves),
.class = &omap3xxx_gpio_hwmod_class,
.dev_attr = &gpio_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* dma_system -> L3 */
static struct omap_hwmod_ocp_if omap3xxx_dma_system__l3 = {
.master = &omap3xxx_dma_system_hwmod,
.slave = &omap3xxx_l3_main_hwmod,
.clk = "core_l3_ick",
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* dma attributes */
static struct omap_dma_dev_attr dma_dev_attr = {
.dev_caps = RESERVE_CHANNEL | DMA_LINKED_LCH | GLOBAL_PRIORITY |
IS_CSSA_32 | IS_CDSA_32 | IS_RW_PRIORITY,
.lch_count = 32,
};
static struct omap_hwmod_class_sysconfig omap3xxx_dma_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x002c,
.syss_offs = 0x0028,
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_SOFTRESET |
SYSC_HAS_MIDLEMODE | SYSC_HAS_CLOCKACTIVITY |
SYSC_HAS_EMUFREE | SYSC_HAS_AUTOIDLE |
SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART |
MSTANDBY_FORCE | MSTANDBY_NO | MSTANDBY_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap3xxx_dma_hwmod_class = {
.name = "dma",
.sysc = &omap3xxx_dma_sysc,
};
/* dma_system */
static struct omap_hwmod_addr_space omap3xxx_dma_system_addrs[] = {
{
.pa_start = 0x48056000,
.pa_end = 0x48056fff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* dma_system master ports */
static struct omap_hwmod_ocp_if *omap3xxx_dma_system_masters[] = {
&omap3xxx_dma_system__l3,
};
/* l4_cfg -> dma_system */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__dma_system = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_dma_system_hwmod,
.clk = "core_l4_ick",
.addr = omap3xxx_dma_system_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* dma_system slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_dma_system_slaves[] = {
&omap3xxx_l4_core__dma_system,
};
static struct omap_hwmod omap3xxx_dma_system_hwmod = {
.name = "dma",
.class = &omap3xxx_dma_hwmod_class,
.mpu_irqs = omap2_dma_system_irqs,
.main_clk = "core_l3_ick",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_ST_SDMA_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_SDMA_SHIFT,
},
},
.slaves = omap3xxx_dma_system_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_dma_system_slaves),
.masters = omap3xxx_dma_system_masters,
.masters_cnt = ARRAY_SIZE(omap3xxx_dma_system_masters),
.dev_attr = &dma_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
.flags = HWMOD_NO_IDLEST,
};
/*
* 'mcbsp' class
* multi channel buffered serial port controller
*/
static struct omap_hwmod_class_sysconfig omap3xxx_mcbsp_sysc = {
.sysc_offs = 0x008c,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_ENAWAKEUP |
SYSC_HAS_SIDLEMODE | SYSC_HAS_SOFTRESET),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
.clockact = 0x2,
};
static struct omap_hwmod_class omap3xxx_mcbsp_hwmod_class = {
.name = "mcbsp",
.sysc = &omap3xxx_mcbsp_sysc,
.rev = MCBSP_CONFIG_TYPE3,
};
/* mcbsp1 */
static struct omap_hwmod_irq_info omap3xxx_mcbsp1_irqs[] = {
{ .name = "irq", .irq = 16 },
{ .name = "tx", .irq = 59 },
{ .name = "rx", .irq = 60 },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mcbsp1_addrs[] = {
{
.name = "mpu",
.pa_start = 0x48074000,
.pa_end = 0x480740ff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_core -> mcbsp1 */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__mcbsp1 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_mcbsp1_hwmod,
.clk = "mcbsp1_ick",
.addr = omap3xxx_mcbsp1_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* mcbsp1 slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mcbsp1_slaves[] = {
&omap3xxx_l4_core__mcbsp1,
};
static struct omap_hwmod omap3xxx_mcbsp1_hwmod = {
.name = "mcbsp1",
.class = &omap3xxx_mcbsp_hwmod_class,
.mpu_irqs = omap3xxx_mcbsp1_irqs,
.sdma_reqs = omap2_mcbsp1_sdma_reqs,
.main_clk = "mcbsp1_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCBSP1_SHIFT,
.module_offs = CORE_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCBSP1_SHIFT,
},
},
.slaves = omap3xxx_mcbsp1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mcbsp1_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* mcbsp2 */
static struct omap_hwmod_irq_info omap3xxx_mcbsp2_irqs[] = {
{ .name = "irq", .irq = 17 },
{ .name = "tx", .irq = 62 },
{ .name = "rx", .irq = 63 },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mcbsp2_addrs[] = {
{
.name = "mpu",
.pa_start = 0x49022000,
.pa_end = 0x490220ff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> mcbsp2 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__mcbsp2 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_mcbsp2_hwmod,
.clk = "mcbsp2_ick",
.addr = omap3xxx_mcbsp2_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* mcbsp2 slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mcbsp2_slaves[] = {
&omap3xxx_l4_per__mcbsp2,
};
static struct omap_mcbsp_dev_attr omap34xx_mcbsp2_dev_attr = {
.sidetone = "mcbsp2_sidetone",
};
static struct omap_hwmod omap3xxx_mcbsp2_hwmod = {
.name = "mcbsp2",
.class = &omap3xxx_mcbsp_hwmod_class,
.mpu_irqs = omap3xxx_mcbsp2_irqs,
.sdma_reqs = omap2_mcbsp2_sdma_reqs,
.main_clk = "mcbsp2_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCBSP2_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCBSP2_SHIFT,
},
},
.slaves = omap3xxx_mcbsp2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mcbsp2_slaves),
.dev_attr = &omap34xx_mcbsp2_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* mcbsp3 */
static struct omap_hwmod_irq_info omap3xxx_mcbsp3_irqs[] = {
{ .name = "irq", .irq = 22 },
{ .name = "tx", .irq = 89 },
{ .name = "rx", .irq = 90 },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mcbsp3_addrs[] = {
{
.name = "mpu",
.pa_start = 0x49024000,
.pa_end = 0x490240ff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> mcbsp3 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__mcbsp3 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_mcbsp3_hwmod,
.clk = "mcbsp3_ick",
.addr = omap3xxx_mcbsp3_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* mcbsp3 slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mcbsp3_slaves[] = {
&omap3xxx_l4_per__mcbsp3,
};
static struct omap_mcbsp_dev_attr omap34xx_mcbsp3_dev_attr = {
.sidetone = "mcbsp3_sidetone",
};
static struct omap_hwmod omap3xxx_mcbsp3_hwmod = {
.name = "mcbsp3",
.class = &omap3xxx_mcbsp_hwmod_class,
.mpu_irqs = omap3xxx_mcbsp3_irqs,
.sdma_reqs = omap2_mcbsp3_sdma_reqs,
.main_clk = "mcbsp3_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCBSP3_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCBSP3_SHIFT,
},
},
.slaves = omap3xxx_mcbsp3_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mcbsp3_slaves),
.dev_attr = &omap34xx_mcbsp3_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* mcbsp4 */
static struct omap_hwmod_irq_info omap3xxx_mcbsp4_irqs[] = {
{ .name = "irq", .irq = 23 },
{ .name = "tx", .irq = 54 },
{ .name = "rx", .irq = 55 },
{ .irq = -1 }
};
static struct omap_hwmod_dma_info omap3xxx_mcbsp4_sdma_chs[] = {
{ .name = "rx", .dma_req = 20 },
{ .name = "tx", .dma_req = 19 },
{ .dma_req = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mcbsp4_addrs[] = {
{
.name = "mpu",
.pa_start = 0x49026000,
.pa_end = 0x490260ff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> mcbsp4 */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__mcbsp4 = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_mcbsp4_hwmod,
.clk = "mcbsp4_ick",
.addr = omap3xxx_mcbsp4_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* mcbsp4 slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mcbsp4_slaves[] = {
&omap3xxx_l4_per__mcbsp4,
};
static struct omap_hwmod omap3xxx_mcbsp4_hwmod = {
.name = "mcbsp4",
.class = &omap3xxx_mcbsp_hwmod_class,
.mpu_irqs = omap3xxx_mcbsp4_irqs,
.sdma_reqs = omap3xxx_mcbsp4_sdma_chs,
.main_clk = "mcbsp4_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCBSP4_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCBSP4_SHIFT,
},
},
.slaves = omap3xxx_mcbsp4_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mcbsp4_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* mcbsp5 */
static struct omap_hwmod_irq_info omap3xxx_mcbsp5_irqs[] = {
{ .name = "irq", .irq = 27 },
{ .name = "tx", .irq = 81 },
{ .name = "rx", .irq = 82 },
{ .irq = -1 }
};
static struct omap_hwmod_dma_info omap3xxx_mcbsp5_sdma_chs[] = {
{ .name = "rx", .dma_req = 22 },
{ .name = "tx", .dma_req = 21 },
{ .dma_req = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mcbsp5_addrs[] = {
{
.name = "mpu",
.pa_start = 0x48096000,
.pa_end = 0x480960ff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_core -> mcbsp5 */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__mcbsp5 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_mcbsp5_hwmod,
.clk = "mcbsp5_ick",
.addr = omap3xxx_mcbsp5_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* mcbsp5 slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mcbsp5_slaves[] = {
&omap3xxx_l4_core__mcbsp5,
};
static struct omap_hwmod omap3xxx_mcbsp5_hwmod = {
.name = "mcbsp5",
.class = &omap3xxx_mcbsp_hwmod_class,
.mpu_irqs = omap3xxx_mcbsp5_irqs,
.sdma_reqs = omap3xxx_mcbsp5_sdma_chs,
.main_clk = "mcbsp5_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCBSP5_SHIFT,
.module_offs = CORE_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCBSP5_SHIFT,
},
},
.slaves = omap3xxx_mcbsp5_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mcbsp5_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* 'mcbsp sidetone' class */
static struct omap_hwmod_class_sysconfig omap3xxx_mcbsp_sidetone_sysc = {
.sysc_offs = 0x0010,
.sysc_flags = SYSC_HAS_AUTOIDLE,
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap3xxx_mcbsp_sidetone_hwmod_class = {
.name = "mcbsp_sidetone",
.sysc = &omap3xxx_mcbsp_sidetone_sysc,
};
/* mcbsp2_sidetone */
static struct omap_hwmod_irq_info omap3xxx_mcbsp2_sidetone_irqs[] = {
{ .name = "irq", .irq = 4 },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mcbsp2_sidetone_addrs[] = {
{
.name = "sidetone",
.pa_start = 0x49028000,
.pa_end = 0x490280ff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> mcbsp2_sidetone */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__mcbsp2_sidetone = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_mcbsp2_sidetone_hwmod,
.clk = "mcbsp2_ick",
.addr = omap3xxx_mcbsp2_sidetone_addrs,
.user = OCP_USER_MPU,
};
/* mcbsp2_sidetone slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mcbsp2_sidetone_slaves[] = {
&omap3xxx_l4_per__mcbsp2_sidetone,
};
static struct omap_hwmod omap3xxx_mcbsp2_sidetone_hwmod = {
.name = "mcbsp2_sidetone",
.class = &omap3xxx_mcbsp_sidetone_hwmod_class,
.mpu_irqs = omap3xxx_mcbsp2_sidetone_irqs,
.main_clk = "mcbsp2_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCBSP2_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCBSP2_SHIFT,
},
},
.slaves = omap3xxx_mcbsp2_sidetone_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mcbsp2_sidetone_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* mcbsp3_sidetone */
static struct omap_hwmod_irq_info omap3xxx_mcbsp3_sidetone_irqs[] = {
{ .name = "irq", .irq = 5 },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mcbsp3_sidetone_addrs[] = {
{
.name = "sidetone",
.pa_start = 0x4902A000,
.pa_end = 0x4902A0ff,
.flags = ADDR_TYPE_RT
},
{ }
};
/* l4_per -> mcbsp3_sidetone */
static struct omap_hwmod_ocp_if omap3xxx_l4_per__mcbsp3_sidetone = {
.master = &omap3xxx_l4_per_hwmod,
.slave = &omap3xxx_mcbsp3_sidetone_hwmod,
.clk = "mcbsp3_ick",
.addr = omap3xxx_mcbsp3_sidetone_addrs,
.user = OCP_USER_MPU,
};
/* mcbsp3_sidetone slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mcbsp3_sidetone_slaves[] = {
&omap3xxx_l4_per__mcbsp3_sidetone,
};
static struct omap_hwmod omap3xxx_mcbsp3_sidetone_hwmod = {
.name = "mcbsp3_sidetone",
.class = &omap3xxx_mcbsp_sidetone_hwmod_class,
.mpu_irqs = omap3xxx_mcbsp3_sidetone_irqs,
.main_clk = "mcbsp3_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCBSP3_SHIFT,
.module_offs = OMAP3430_PER_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCBSP3_SHIFT,
},
},
.slaves = omap3xxx_mcbsp3_sidetone_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mcbsp3_sidetone_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* SR common */
static struct omap_hwmod_sysc_fields omap34xx_sr_sysc_fields = {
.clkact_shift = 20,
};
static struct omap_hwmod_class_sysconfig omap34xx_sr_sysc = {
.sysc_offs = 0x24,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_NO_CACHE),
.clockact = CLOCKACT_TEST_ICLK,
.sysc_fields = &omap34xx_sr_sysc_fields,
};
static struct omap_hwmod_class omap34xx_smartreflex_hwmod_class = {
.name = "smartreflex",
.sysc = &omap34xx_sr_sysc,
.rev = 1,
};
static struct omap_hwmod_sysc_fields omap36xx_sr_sysc_fields = {
.sidle_shift = 24,
.enwkup_shift = 26
};
static struct omap_hwmod_class_sysconfig omap36xx_sr_sysc = {
.sysc_offs = 0x38,
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_ENAWAKEUP |
SYSC_NO_CACHE),
.sysc_fields = &omap36xx_sr_sysc_fields,
};
static struct omap_hwmod_class omap36xx_smartreflex_hwmod_class = {
.name = "smartreflex",
.sysc = &omap36xx_sr_sysc,
.rev = 2,
};
/* SR1 */
static struct omap_hwmod_ocp_if *omap3_sr1_slaves[] = {
&omap3_l4_core__sr1,
};
static struct omap_hwmod omap34xx_sr1_hwmod = {
.name = "sr1_hwmod",
.class = &omap34xx_smartreflex_hwmod_class,
.main_clk = "sr1_fck",
.vdd_name = "mpu",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_SR1_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_EN_SR1_SHIFT,
},
},
.slaves = omap3_sr1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3_sr1_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES2 |
CHIP_IS_OMAP3430ES3_0 |
CHIP_IS_OMAP3430ES3_1),
.flags = HWMOD_SET_DEFAULT_CLOCKACT,
};
static struct omap_hwmod omap36xx_sr1_hwmod = {
.name = "sr1_hwmod",
.class = &omap36xx_smartreflex_hwmod_class,
.main_clk = "sr1_fck",
.vdd_name = "mpu",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_SR1_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_EN_SR1_SHIFT,
},
},
.slaves = omap3_sr1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3_sr1_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3630ES1),
};
/* SR2 */
static struct omap_hwmod_ocp_if *omap3_sr2_slaves[] = {
&omap3_l4_core__sr2,
};
static struct omap_hwmod omap34xx_sr2_hwmod = {
.name = "sr2_hwmod",
.class = &omap34xx_smartreflex_hwmod_class,
.main_clk = "sr2_fck",
.vdd_name = "core",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_SR2_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_EN_SR2_SHIFT,
},
},
.slaves = omap3_sr2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3_sr2_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES2 |
CHIP_IS_OMAP3430ES3_0 |
CHIP_IS_OMAP3430ES3_1),
.flags = HWMOD_SET_DEFAULT_CLOCKACT,
};
static struct omap_hwmod omap36xx_sr2_hwmod = {
.name = "sr2_hwmod",
.class = &omap36xx_smartreflex_hwmod_class,
.main_clk = "sr2_fck",
.vdd_name = "core",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_SR2_SHIFT,
.module_offs = WKUP_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_EN_SR2_SHIFT,
},
},
.slaves = omap3_sr2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3_sr2_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3630ES1),
};
/*
* 'mailbox' class
* mailbox module allowing communication between the on-chip processors
* using a queued mailbox-interrupt mechanism.
*/
static struct omap_hwmod_class_sysconfig omap3xxx_mailbox_sysc = {
.rev_offs = 0x000,
.sysc_offs = 0x010,
.syss_offs = 0x014,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_SIDLEMODE |
SYSC_HAS_SOFTRESET | SYSC_HAS_AUTOIDLE),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap3xxx_mailbox_hwmod_class = {
.name = "mailbox",
.sysc = &omap3xxx_mailbox_sysc,
};
static struct omap_hwmod omap3xxx_mailbox_hwmod;
static struct omap_hwmod_irq_info omap3xxx_mailbox_irqs[] = {
{ .irq = 26 },
{ .irq = -1 }
};
static struct omap_hwmod_addr_space omap3xxx_mailbox_addrs[] = {
{
.pa_start = 0x48094000,
.pa_end = 0x480941ff,
.flags = ADDR_TYPE_RT,
},
{ }
};
/* l4_core -> mailbox */
static struct omap_hwmod_ocp_if omap3xxx_l4_core__mailbox = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap3xxx_mailbox_hwmod,
.addr = omap3xxx_mailbox_addrs,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* mailbox slave ports */
static struct omap_hwmod_ocp_if *omap3xxx_mailbox_slaves[] = {
&omap3xxx_l4_core__mailbox,
};
static struct omap_hwmod omap3xxx_mailbox_hwmod = {
.name = "mailbox",
.class = &omap3xxx_mailbox_hwmod_class,
.mpu_irqs = omap3xxx_mailbox_irqs,
.main_clk = "mailboxes_ick",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MAILBOXES_SHIFT,
.module_offs = CORE_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MAILBOXES_SHIFT,
},
},
.slaves = omap3xxx_mailbox_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mailbox_slaves),
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* l4 core -> mcspi1 interface */
static struct omap_hwmod_ocp_if omap34xx_l4_core__mcspi1 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap34xx_mcspi1,
.clk = "mcspi1_ick",
.addr = omap2_mcspi1_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4 core -> mcspi2 interface */
static struct omap_hwmod_ocp_if omap34xx_l4_core__mcspi2 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap34xx_mcspi2,
.clk = "mcspi2_ick",
.addr = omap2_mcspi2_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4 core -> mcspi3 interface */
static struct omap_hwmod_ocp_if omap34xx_l4_core__mcspi3 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap34xx_mcspi3,
.clk = "mcspi3_ick",
.addr = omap2430_mcspi3_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/* l4 core -> mcspi4 interface */
static struct omap_hwmod_addr_space omap34xx_mcspi4_addr_space[] = {
{
.pa_start = 0x480ba000,
.pa_end = 0x480ba0ff,
.flags = ADDR_TYPE_RT,
},
{ }
};
static struct omap_hwmod_ocp_if omap34xx_l4_core__mcspi4 = {
.master = &omap3xxx_l4_core_hwmod,
.slave = &omap34xx_mcspi4,
.clk = "mcspi4_ick",
.addr = omap34xx_mcspi4_addr_space,
.user = OCP_USER_MPU | OCP_USER_SDMA,
};
/*
* 'mcspi' class
* multichannel serial port interface (mcspi) / master/slave synchronous serial
* bus
*/
static struct omap_hwmod_class_sysconfig omap34xx_mcspi_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_SIDLEMODE |
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE | SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap34xx_mcspi_class = {
.name = "mcspi",
.sysc = &omap34xx_mcspi_sysc,
.rev = OMAP3_MCSPI_REV,
};
/* mcspi1 */
static struct omap_hwmod_ocp_if *omap34xx_mcspi1_slaves[] = {
&omap34xx_l4_core__mcspi1,
};
static struct omap2_mcspi_dev_attr omap_mcspi1_dev_attr = {
.num_chipselect = 4,
};
static struct omap_hwmod omap34xx_mcspi1 = {
.name = "mcspi1",
.mpu_irqs = omap2_mcspi1_mpu_irqs,
.sdma_reqs = omap2_mcspi1_sdma_reqs,
.main_clk = "mcspi1_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCSPI1_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCSPI1_SHIFT,
},
},
.slaves = omap34xx_mcspi1_slaves,
.slaves_cnt = ARRAY_SIZE(omap34xx_mcspi1_slaves),
.class = &omap34xx_mcspi_class,
.dev_attr = &omap_mcspi1_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* mcspi2 */
static struct omap_hwmod_ocp_if *omap34xx_mcspi2_slaves[] = {
&omap34xx_l4_core__mcspi2,
};
static struct omap2_mcspi_dev_attr omap_mcspi2_dev_attr = {
.num_chipselect = 2,
};
static struct omap_hwmod omap34xx_mcspi2 = {
.name = "mcspi2",
.mpu_irqs = omap2_mcspi2_mpu_irqs,
.sdma_reqs = omap2_mcspi2_sdma_reqs,
.main_clk = "mcspi2_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCSPI2_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCSPI2_SHIFT,
},
},
.slaves = omap34xx_mcspi2_slaves,
.slaves_cnt = ARRAY_SIZE(omap34xx_mcspi2_slaves),
.class = &omap34xx_mcspi_class,
.dev_attr = &omap_mcspi2_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* mcspi3 */
static struct omap_hwmod_irq_info omap34xx_mcspi3_mpu_irqs[] = {
{ .name = "irq", .irq = 91 }, /* 91 */
{ .irq = -1 }
};
static struct omap_hwmod_dma_info omap34xx_mcspi3_sdma_reqs[] = {
{ .name = "tx0", .dma_req = 15 },
{ .name = "rx0", .dma_req = 16 },
{ .name = "tx1", .dma_req = 23 },
{ .name = "rx1", .dma_req = 24 },
{ .dma_req = -1 }
};
static struct omap_hwmod_ocp_if *omap34xx_mcspi3_slaves[] = {
&omap34xx_l4_core__mcspi3,
};
static struct omap2_mcspi_dev_attr omap_mcspi3_dev_attr = {
.num_chipselect = 2,
};
static struct omap_hwmod omap34xx_mcspi3 = {
.name = "mcspi3",
.mpu_irqs = omap34xx_mcspi3_mpu_irqs,
.sdma_reqs = omap34xx_mcspi3_sdma_reqs,
.main_clk = "mcspi3_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCSPI3_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCSPI3_SHIFT,
},
},
.slaves = omap34xx_mcspi3_slaves,
.slaves_cnt = ARRAY_SIZE(omap34xx_mcspi3_slaves),
.class = &omap34xx_mcspi_class,
.dev_attr = &omap_mcspi3_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* SPI4 */
static struct omap_hwmod_irq_info omap34xx_mcspi4_mpu_irqs[] = {
{ .name = "irq", .irq = INT_34XX_SPI4_IRQ }, /* 48 */
{ .irq = -1 }
};
static struct omap_hwmod_dma_info omap34xx_mcspi4_sdma_reqs[] = {
{ .name = "tx0", .dma_req = 70 }, /* DMA_SPI4_TX0 */
{ .name = "rx0", .dma_req = 71 }, /* DMA_SPI4_RX0 */
{ .dma_req = -1 }
};
static struct omap_hwmod_ocp_if *omap34xx_mcspi4_slaves[] = {
&omap34xx_l4_core__mcspi4,
};
static struct omap2_mcspi_dev_attr omap_mcspi4_dev_attr = {
.num_chipselect = 1,
};
static struct omap_hwmod omap34xx_mcspi4 = {
.name = "mcspi4",
.mpu_irqs = omap34xx_mcspi4_mpu_irqs,
.sdma_reqs = omap34xx_mcspi4_sdma_reqs,
.main_clk = "mcspi4_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MCSPI4_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MCSPI4_SHIFT,
},
},
.slaves = omap34xx_mcspi4_slaves,
.slaves_cnt = ARRAY_SIZE(omap34xx_mcspi4_slaves),
.class = &omap34xx_mcspi_class,
.dev_attr = &omap_mcspi4_dev_attr,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/*
* usbhsotg
*/
static struct omap_hwmod_class_sysconfig omap3xxx_usbhsotg_sysc = {
.rev_offs = 0x0400,
.sysc_offs = 0x0404,
.syss_offs = 0x0408,
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_MIDLEMODE|
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART |
MSTANDBY_FORCE | MSTANDBY_NO | MSTANDBY_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class usbotg_class = {
.name = "usbotg",
.sysc = &omap3xxx_usbhsotg_sysc,
};
/* usb_otg_hs */
static struct omap_hwmod_irq_info omap3xxx_usbhsotg_mpu_irqs[] = {
{ .name = "mc", .irq = 92 },
{ .name = "dma", .irq = 93 },
{ .irq = -1 }
};
static struct omap_hwmod omap3xxx_usbhsotg_hwmod = {
.name = "usb_otg_hs",
.mpu_irqs = omap3xxx_usbhsotg_mpu_irqs,
.main_clk = "hsotgusb_ick",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_HSOTGUSB_SHIFT,
.module_offs = CORE_MOD,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430ES2_ST_HSOTGUSB_IDLE_SHIFT,
.idlest_stdby_bit = OMAP3430ES2_ST_HSOTGUSB_STDBY_SHIFT
},
},
.masters = omap3xxx_usbhsotg_masters,
.masters_cnt = ARRAY_SIZE(omap3xxx_usbhsotg_masters),
.slaves = omap3xxx_usbhsotg_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_usbhsotg_slaves),
.class = &usbotg_class,
/*
* Erratum ID: i479 idle_req / idle_ack mechanism potentially
* broken when autoidle is enabled
* workaround is to disable the autoidle bit at module level.
*/
.flags = HWMOD_NO_OCP_AUTOIDLE | HWMOD_SWSUP_SIDLE
| HWMOD_SWSUP_MSTANDBY,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430)
};
/* usb_otg_hs */
static struct omap_hwmod_irq_info am35xx_usbhsotg_mpu_irqs[] = {
{ .name = "mc", .irq = 71 },
{ .irq = -1 }
};
static struct omap_hwmod_class am35xx_usbotg_class = {
.name = "am35xx_usbotg",
.sysc = NULL,
};
static struct omap_hwmod am35xx_usbhsotg_hwmod = {
.name = "am35x_otg_hs",
.mpu_irqs = am35xx_usbhsotg_mpu_irqs,
.main_clk = NULL,
.prcm = {
.omap2 = {
},
},
.masters = am35xx_usbhsotg_masters,
.masters_cnt = ARRAY_SIZE(am35xx_usbhsotg_masters),
.slaves = am35xx_usbhsotg_slaves,
.slaves_cnt = ARRAY_SIZE(am35xx_usbhsotg_slaves),
.class = &am35xx_usbotg_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430ES3_1)
};
/* MMC/SD/SDIO common */
static struct omap_hwmod_class_sysconfig omap34xx_mmc_sysc = {
.rev_offs = 0x1fc,
.sysc_offs = 0x10,
.syss_offs = 0x14,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_SIDLEMODE |
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE | SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
static struct omap_hwmod_class omap34xx_mmc_class = {
.name = "mmc",
.sysc = &omap34xx_mmc_sysc,
};
/* MMC/SD/SDIO1 */
static struct omap_hwmod_irq_info omap34xx_mmc1_mpu_irqs[] = {
{ .irq = 83, },
{ .irq = -1 }
};
static struct omap_hwmod_dma_info omap34xx_mmc1_sdma_reqs[] = {
{ .name = "tx", .dma_req = 61, },
{ .name = "rx", .dma_req = 62, },
{ .dma_req = -1 }
};
static struct omap_hwmod_opt_clk omap34xx_mmc1_opt_clks[] = {
{ .role = "dbck", .clk = "omap_32k_fck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_mmc1_slaves[] = {
&omap3xxx_l4_core__mmc1,
};
static struct omap_mmc_dev_attr mmc1_dev_attr = {
.flags = OMAP_HSMMC_SUPPORTS_DUAL_VOLT,
};
static struct omap_hwmod omap3xxx_mmc1_hwmod = {
.name = "mmc1",
.mpu_irqs = omap34xx_mmc1_mpu_irqs,
.sdma_reqs = omap34xx_mmc1_sdma_reqs,
.opt_clks = omap34xx_mmc1_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(omap34xx_mmc1_opt_clks),
.main_clk = "mmchs1_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MMC1_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MMC1_SHIFT,
},
},
.dev_attr = &mmc1_dev_attr,
.slaves = omap3xxx_mmc1_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mmc1_slaves),
.class = &omap34xx_mmc_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* MMC/SD/SDIO2 */
static struct omap_hwmod_irq_info omap34xx_mmc2_mpu_irqs[] = {
{ .irq = INT_24XX_MMC2_IRQ, },
{ .irq = -1 }
};
static struct omap_hwmod_dma_info omap34xx_mmc2_sdma_reqs[] = {
{ .name = "tx", .dma_req = 47, },
{ .name = "rx", .dma_req = 48, },
{ .dma_req = -1 }
};
static struct omap_hwmod_opt_clk omap34xx_mmc2_opt_clks[] = {
{ .role = "dbck", .clk = "omap_32k_fck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_mmc2_slaves[] = {
&omap3xxx_l4_core__mmc2,
};
static struct omap_hwmod omap3xxx_mmc2_hwmod = {
.name = "mmc2",
.mpu_irqs = omap34xx_mmc2_mpu_irqs,
.sdma_reqs = omap34xx_mmc2_sdma_reqs,
.opt_clks = omap34xx_mmc2_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(omap34xx_mmc2_opt_clks),
.main_clk = "mmchs2_fck",
.prcm = {
.omap2 = {
.module_offs = CORE_MOD,
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MMC2_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MMC2_SHIFT,
},
},
.slaves = omap3xxx_mmc2_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mmc2_slaves),
.class = &omap34xx_mmc_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
/* MMC/SD/SDIO3 */
static struct omap_hwmod_irq_info omap34xx_mmc3_mpu_irqs[] = {
{ .irq = 94, },
{ .irq = -1 }
};
static struct omap_hwmod_dma_info omap34xx_mmc3_sdma_reqs[] = {
{ .name = "tx", .dma_req = 77, },
{ .name = "rx", .dma_req = 78, },
{ .dma_req = -1 }
};
static struct omap_hwmod_opt_clk omap34xx_mmc3_opt_clks[] = {
{ .role = "dbck", .clk = "omap_32k_fck", },
};
static struct omap_hwmod_ocp_if *omap3xxx_mmc3_slaves[] = {
&omap3xxx_l4_core__mmc3,
};
static struct omap_hwmod omap3xxx_mmc3_hwmod = {
.name = "mmc3",
.mpu_irqs = omap34xx_mmc3_mpu_irqs,
.sdma_reqs = omap34xx_mmc3_sdma_reqs,
.opt_clks = omap34xx_mmc3_opt_clks,
.opt_clks_cnt = ARRAY_SIZE(omap34xx_mmc3_opt_clks),
.main_clk = "mmchs3_fck",
.prcm = {
.omap2 = {
.prcm_reg_id = 1,
.module_bit = OMAP3430_EN_MMC3_SHIFT,
.idlest_reg_id = 1,
.idlest_idle_bit = OMAP3430_ST_MMC3_SHIFT,
},
},
.slaves = omap3xxx_mmc3_slaves,
.slaves_cnt = ARRAY_SIZE(omap3xxx_mmc3_slaves),
.class = &omap34xx_mmc_class,
.omap_chip = OMAP_CHIP_INIT(CHIP_IS_OMAP3430),
};
static __initdata struct omap_hwmod *omap3xxx_hwmods[] = {
&omap3xxx_l3_main_hwmod,
&omap3xxx_l4_core_hwmod,
&omap3xxx_l4_per_hwmod,
&omap3xxx_l4_wkup_hwmod,
&omap3xxx_mmc1_hwmod,
&omap3xxx_mmc2_hwmod,
&omap3xxx_mmc3_hwmod,
&omap3xxx_mpu_hwmod,
&omap3xxx_iva_hwmod,
&omap3xxx_timer1_hwmod,
&omap3xxx_timer2_hwmod,
&omap3xxx_timer3_hwmod,
&omap3xxx_timer4_hwmod,
&omap3xxx_timer5_hwmod,
&omap3xxx_timer6_hwmod,
&omap3xxx_timer7_hwmod,
&omap3xxx_timer8_hwmod,
&omap3xxx_timer9_hwmod,
&omap3xxx_timer10_hwmod,
&omap3xxx_timer11_hwmod,
&omap3xxx_timer12_hwmod,
&omap3xxx_wd_timer2_hwmod,
&omap3xxx_uart1_hwmod,
&omap3xxx_uart2_hwmod,
&omap3xxx_uart3_hwmod,
&omap3xxx_uart4_hwmod,
/* dss class */
&omap3430es1_dss_core_hwmod,
&omap3xxx_dss_core_hwmod,
&omap3xxx_dss_dispc_hwmod,
&omap3xxx_dss_dsi1_hwmod,
&omap3xxx_dss_rfbi_hwmod,
&omap3xxx_dss_venc_hwmod,
/* i2c class */
&omap3xxx_i2c1_hwmod,
&omap3xxx_i2c2_hwmod,
&omap3xxx_i2c3_hwmod,
&omap34xx_sr1_hwmod,
&omap34xx_sr2_hwmod,
&omap36xx_sr1_hwmod,
&omap36xx_sr2_hwmod,
/* gpio class */
&omap3xxx_gpio1_hwmod,
&omap3xxx_gpio2_hwmod,
&omap3xxx_gpio3_hwmod,
&omap3xxx_gpio4_hwmod,
&omap3xxx_gpio5_hwmod,
&omap3xxx_gpio6_hwmod,
/* dma_system class*/
&omap3xxx_dma_system_hwmod,
/* mcbsp class */
&omap3xxx_mcbsp1_hwmod,
&omap3xxx_mcbsp2_hwmod,
&omap3xxx_mcbsp3_hwmod,
&omap3xxx_mcbsp4_hwmod,
&omap3xxx_mcbsp5_hwmod,
&omap3xxx_mcbsp2_sidetone_hwmod,
&omap3xxx_mcbsp3_sidetone_hwmod,
/* mailbox class */
&omap3xxx_mailbox_hwmod,
/* mcspi class */
&omap34xx_mcspi1,
&omap34xx_mcspi2,
&omap34xx_mcspi3,
&omap34xx_mcspi4,
/* usbotg class */
&omap3xxx_usbhsotg_hwmod,
/* usbotg for am35x */
&am35xx_usbhsotg_hwmod,
NULL,
};
int __init omap3xxx_hwmod_init(void)
{
return omap_hwmod_register(omap3xxx_hwmods);
}
| gpl-2.0 |
BigBrother1984/android_kernel_samsung_tuna | drivers/net/sfc/efx.c | 649 | 72793 | /****************************************************************************
* Driver for Solarflare Solarstorm network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2005-2011 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/delay.h>
#include <linux/notifier.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/in.h>
#include <linux/crc32.h>
#include <linux/ethtool.h>
#include <linux/topology.h>
#include <linux/gfp.h>
#include <linux/cpu_rmap.h>
#include "net_driver.h"
#include "efx.h"
#include "nic.h"
#include "mcdi.h"
#include "workarounds.h"
/**************************************************************************
*
* Type name strings
*
**************************************************************************
*/
/* Loopback mode names (see LOOPBACK_MODE()) */
const unsigned int efx_loopback_mode_max = LOOPBACK_MAX;
const char *efx_loopback_mode_names[] = {
[LOOPBACK_NONE] = "NONE",
[LOOPBACK_DATA] = "DATAPATH",
[LOOPBACK_GMAC] = "GMAC",
[LOOPBACK_XGMII] = "XGMII",
[LOOPBACK_XGXS] = "XGXS",
[LOOPBACK_XAUI] = "XAUI",
[LOOPBACK_GMII] = "GMII",
[LOOPBACK_SGMII] = "SGMII",
[LOOPBACK_XGBR] = "XGBR",
[LOOPBACK_XFI] = "XFI",
[LOOPBACK_XAUI_FAR] = "XAUI_FAR",
[LOOPBACK_GMII_FAR] = "GMII_FAR",
[LOOPBACK_SGMII_FAR] = "SGMII_FAR",
[LOOPBACK_XFI_FAR] = "XFI_FAR",
[LOOPBACK_GPHY] = "GPHY",
[LOOPBACK_PHYXS] = "PHYXS",
[LOOPBACK_PCS] = "PCS",
[LOOPBACK_PMAPMD] = "PMA/PMD",
[LOOPBACK_XPORT] = "XPORT",
[LOOPBACK_XGMII_WS] = "XGMII_WS",
[LOOPBACK_XAUI_WS] = "XAUI_WS",
[LOOPBACK_XAUI_WS_FAR] = "XAUI_WS_FAR",
[LOOPBACK_XAUI_WS_NEAR] = "XAUI_WS_NEAR",
[LOOPBACK_GMII_WS] = "GMII_WS",
[LOOPBACK_XFI_WS] = "XFI_WS",
[LOOPBACK_XFI_WS_FAR] = "XFI_WS_FAR",
[LOOPBACK_PHYXS_WS] = "PHYXS_WS",
};
const unsigned int efx_reset_type_max = RESET_TYPE_MAX;
const char *efx_reset_type_names[] = {
[RESET_TYPE_INVISIBLE] = "INVISIBLE",
[RESET_TYPE_ALL] = "ALL",
[RESET_TYPE_WORLD] = "WORLD",
[RESET_TYPE_DISABLE] = "DISABLE",
[RESET_TYPE_TX_WATCHDOG] = "TX_WATCHDOG",
[RESET_TYPE_INT_ERROR] = "INT_ERROR",
[RESET_TYPE_RX_RECOVERY] = "RX_RECOVERY",
[RESET_TYPE_RX_DESC_FETCH] = "RX_DESC_FETCH",
[RESET_TYPE_TX_DESC_FETCH] = "TX_DESC_FETCH",
[RESET_TYPE_TX_SKIP] = "TX_SKIP",
[RESET_TYPE_MC_FAILURE] = "MC_FAILURE",
};
#define EFX_MAX_MTU (9 * 1024)
/* Reset workqueue. If any NIC has a hardware failure then a reset will be
* queued onto this work queue. This is not a per-nic work queue, because
* efx_reset_work() acquires the rtnl lock, so resets are naturally serialised.
*/
static struct workqueue_struct *reset_workqueue;
/**************************************************************************
*
* Configurable values
*
*************************************************************************/
/*
* Use separate channels for TX and RX events
*
* Set this to 1 to use separate channels for TX and RX. It allows us
* to control interrupt affinity separately for TX and RX.
*
* This is only used in MSI-X interrupt mode
*/
static unsigned int separate_tx_channels;
module_param(separate_tx_channels, uint, 0444);
MODULE_PARM_DESC(separate_tx_channels,
"Use separate channels for TX and RX");
/* This is the weight assigned to each of the (per-channel) virtual
* NAPI devices.
*/
static int napi_weight = 64;
/* This is the time (in jiffies) between invocations of the hardware
* monitor. On Falcon-based NICs, this will:
* - Check the on-board hardware monitor;
* - Poll the link state and reconfigure the hardware as necessary.
*/
static unsigned int efx_monitor_interval = 1 * HZ;
/* This controls whether or not the driver will initialise devices
* with invalid MAC addresses stored in the EEPROM or flash. If true,
* such devices will be initialised with a random locally-generated
* MAC address. This allows for loading the sfc_mtd driver to
* reprogram the flash, even if the flash contents (including the MAC
* address) have previously been erased.
*/
static unsigned int allow_bad_hwaddr;
/* Initial interrupt moderation settings. They can be modified after
* module load with ethtool.
*
* The default for RX should strike a balance between increasing the
* round-trip latency and reducing overhead.
*/
static unsigned int rx_irq_mod_usec = 60;
/* Initial interrupt moderation settings. They can be modified after
* module load with ethtool.
*
* This default is chosen to ensure that a 10G link does not go idle
* while a TX queue is stopped after it has become full. A queue is
* restarted when it drops below half full. The time this takes (assuming
* worst case 3 descriptors per packet and 1024 descriptors) is
* 512 / 3 * 1.2 = 205 usec.
*/
static unsigned int tx_irq_mod_usec = 150;
/* This is the first interrupt mode to try out of:
* 0 => MSI-X
* 1 => MSI
* 2 => legacy
*/
static unsigned int interrupt_mode;
/* This is the requested number of CPUs to use for Receive-Side Scaling (RSS),
* i.e. the number of CPUs among which we may distribute simultaneous
* interrupt handling.
*
* Cards without MSI-X will only target one CPU via legacy or MSI interrupt.
* The default (0) means to assign an interrupt to each package (level II cache)
*/
static unsigned int rss_cpus;
module_param(rss_cpus, uint, 0444);
MODULE_PARM_DESC(rss_cpus, "Number of CPUs to use for Receive-Side Scaling");
static int phy_flash_cfg;
module_param(phy_flash_cfg, int, 0644);
MODULE_PARM_DESC(phy_flash_cfg, "Set PHYs into reflash mode initially");
static unsigned irq_adapt_low_thresh = 10000;
module_param(irq_adapt_low_thresh, uint, 0644);
MODULE_PARM_DESC(irq_adapt_low_thresh,
"Threshold score for reducing IRQ moderation");
static unsigned irq_adapt_high_thresh = 20000;
module_param(irq_adapt_high_thresh, uint, 0644);
MODULE_PARM_DESC(irq_adapt_high_thresh,
"Threshold score for increasing IRQ moderation");
static unsigned debug = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFDOWN |
NETIF_MSG_IFUP | NETIF_MSG_RX_ERR |
NETIF_MSG_TX_ERR | NETIF_MSG_HW);
module_param(debug, uint, 0);
MODULE_PARM_DESC(debug, "Bitmapped debugging message enable value");
/**************************************************************************
*
* Utility functions and prototypes
*
*************************************************************************/
static void efx_remove_channels(struct efx_nic *efx);
static void efx_remove_port(struct efx_nic *efx);
static void efx_init_napi(struct efx_nic *efx);
static void efx_fini_napi(struct efx_nic *efx);
static void efx_fini_napi_channel(struct efx_channel *channel);
static void efx_fini_struct(struct efx_nic *efx);
static void efx_start_all(struct efx_nic *efx);
static void efx_stop_all(struct efx_nic *efx);
#define EFX_ASSERT_RESET_SERIALISED(efx) \
do { \
if ((efx->state == STATE_RUNNING) || \
(efx->state == STATE_DISABLED)) \
ASSERT_RTNL(); \
} while (0)
/**************************************************************************
*
* Event queue processing
*
*************************************************************************/
/* Process channel's event queue
*
* This function is responsible for processing the event queue of a
* single channel. The caller must guarantee that this function will
* never be concurrently called more than once on the same channel,
* though different channels may be being processed concurrently.
*/
static int efx_process_channel(struct efx_channel *channel, int budget)
{
struct efx_nic *efx = channel->efx;
int spent;
if (unlikely(efx->reset_pending != RESET_TYPE_NONE ||
!channel->enabled))
return 0;
spent = efx_nic_process_eventq(channel, budget);
if (spent == 0)
return 0;
/* Deliver last RX packet. */
if (channel->rx_pkt) {
__efx_rx_packet(channel, channel->rx_pkt,
channel->rx_pkt_csummed);
channel->rx_pkt = NULL;
}
efx_rx_strategy(channel);
efx_fast_push_rx_descriptors(efx_channel_get_rx_queue(channel));
return spent;
}
/* Mark channel as finished processing
*
* Note that since we will not receive further interrupts for this
* channel before we finish processing and call the eventq_read_ack()
* method, there is no need to use the interrupt hold-off timers.
*/
static inline void efx_channel_processed(struct efx_channel *channel)
{
/* The interrupt handler for this channel may set work_pending
* as soon as we acknowledge the events we've seen. Make sure
* it's cleared before then. */
channel->work_pending = false;
smp_wmb();
efx_nic_eventq_read_ack(channel);
}
/* NAPI poll handler
*
* NAPI guarantees serialisation of polls of the same device, which
* provides the guarantee required by efx_process_channel().
*/
static int efx_poll(struct napi_struct *napi, int budget)
{
struct efx_channel *channel =
container_of(napi, struct efx_channel, napi_str);
struct efx_nic *efx = channel->efx;
int spent;
netif_vdbg(efx, intr, efx->net_dev,
"channel %d NAPI poll executing on CPU %d\n",
channel->channel, raw_smp_processor_id());
spent = efx_process_channel(channel, budget);
if (spent < budget) {
if (channel->channel < efx->n_rx_channels &&
efx->irq_rx_adaptive &&
unlikely(++channel->irq_count == 1000)) {
if (unlikely(channel->irq_mod_score <
irq_adapt_low_thresh)) {
if (channel->irq_moderation > 1) {
channel->irq_moderation -= 1;
efx->type->push_irq_moderation(channel);
}
} else if (unlikely(channel->irq_mod_score >
irq_adapt_high_thresh)) {
if (channel->irq_moderation <
efx->irq_rx_moderation) {
channel->irq_moderation += 1;
efx->type->push_irq_moderation(channel);
}
}
channel->irq_count = 0;
channel->irq_mod_score = 0;
}
efx_filter_rfs_expire(channel);
/* There is no race here; although napi_disable() will
* only wait for napi_complete(), this isn't a problem
* since efx_channel_processed() will have no effect if
* interrupts have already been disabled.
*/
napi_complete(napi);
efx_channel_processed(channel);
}
return spent;
}
/* Process the eventq of the specified channel immediately on this CPU
*
* Disable hardware generated interrupts, wait for any existing
* processing to finish, then directly poll (and ack ) the eventq.
* Finally reenable NAPI and interrupts.
*
* This is for use only during a loopback self-test. It must not
* deliver any packets up the stack as this can result in deadlock.
*/
void efx_process_channel_now(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
BUG_ON(channel->channel >= efx->n_channels);
BUG_ON(!channel->enabled);
BUG_ON(!efx->loopback_selftest);
/* Disable interrupts and wait for ISRs to complete */
efx_nic_disable_interrupts(efx);
if (efx->legacy_irq) {
synchronize_irq(efx->legacy_irq);
efx->legacy_irq_enabled = false;
}
if (channel->irq)
synchronize_irq(channel->irq);
/* Wait for any NAPI processing to complete */
napi_disable(&channel->napi_str);
/* Poll the channel */
efx_process_channel(channel, channel->eventq_mask + 1);
/* Ack the eventq. This may cause an interrupt to be generated
* when they are reenabled */
efx_channel_processed(channel);
napi_enable(&channel->napi_str);
if (efx->legacy_irq)
efx->legacy_irq_enabled = true;
efx_nic_enable_interrupts(efx);
}
/* Create event queue
* Event queue memory allocations are done only once. If the channel
* is reset, the memory buffer will be reused; this guards against
* errors during channel reset and also simplifies interrupt handling.
*/
static int efx_probe_eventq(struct efx_channel *channel)
{
struct efx_nic *efx = channel->efx;
unsigned long entries;
netif_dbg(channel->efx, probe, channel->efx->net_dev,
"chan %d create event queue\n", channel->channel);
/* Build an event queue with room for one event per tx and rx buffer,
* plus some extra for link state events and MCDI completions. */
entries = roundup_pow_of_two(efx->rxq_entries + efx->txq_entries + 128);
EFX_BUG_ON_PARANOID(entries > EFX_MAX_EVQ_SIZE);
channel->eventq_mask = max(entries, EFX_MIN_EVQ_SIZE) - 1;
return efx_nic_probe_eventq(channel);
}
/* Prepare channel's event queue */
static void efx_init_eventq(struct efx_channel *channel)
{
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"chan %d init event queue\n", channel->channel);
channel->eventq_read_ptr = 0;
efx_nic_init_eventq(channel);
}
static void efx_fini_eventq(struct efx_channel *channel)
{
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"chan %d fini event queue\n", channel->channel);
efx_nic_fini_eventq(channel);
}
static void efx_remove_eventq(struct efx_channel *channel)
{
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"chan %d remove event queue\n", channel->channel);
efx_nic_remove_eventq(channel);
}
/**************************************************************************
*
* Channel handling
*
*************************************************************************/
/* Allocate and initialise a channel structure, optionally copying
* parameters (but not resources) from an old channel structure. */
static struct efx_channel *
efx_alloc_channel(struct efx_nic *efx, int i, struct efx_channel *old_channel)
{
struct efx_channel *channel;
struct efx_rx_queue *rx_queue;
struct efx_tx_queue *tx_queue;
int j;
if (old_channel) {
channel = kmalloc(sizeof(*channel), GFP_KERNEL);
if (!channel)
return NULL;
*channel = *old_channel;
channel->napi_dev = NULL;
memset(&channel->eventq, 0, sizeof(channel->eventq));
rx_queue = &channel->rx_queue;
rx_queue->buffer = NULL;
memset(&rx_queue->rxd, 0, sizeof(rx_queue->rxd));
for (j = 0; j < EFX_TXQ_TYPES; j++) {
tx_queue = &channel->tx_queue[j];
if (tx_queue->channel)
tx_queue->channel = channel;
tx_queue->buffer = NULL;
memset(&tx_queue->txd, 0, sizeof(tx_queue->txd));
}
} else {
channel = kzalloc(sizeof(*channel), GFP_KERNEL);
if (!channel)
return NULL;
channel->efx = efx;
channel->channel = i;
for (j = 0; j < EFX_TXQ_TYPES; j++) {
tx_queue = &channel->tx_queue[j];
tx_queue->efx = efx;
tx_queue->queue = i * EFX_TXQ_TYPES + j;
tx_queue->channel = channel;
}
}
rx_queue = &channel->rx_queue;
rx_queue->efx = efx;
setup_timer(&rx_queue->slow_fill, efx_rx_slow_fill,
(unsigned long)rx_queue);
return channel;
}
static int efx_probe_channel(struct efx_channel *channel)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
int rc;
netif_dbg(channel->efx, probe, channel->efx->net_dev,
"creating channel %d\n", channel->channel);
rc = efx_probe_eventq(channel);
if (rc)
goto fail1;
efx_for_each_channel_tx_queue(tx_queue, channel) {
rc = efx_probe_tx_queue(tx_queue);
if (rc)
goto fail2;
}
efx_for_each_channel_rx_queue(rx_queue, channel) {
rc = efx_probe_rx_queue(rx_queue);
if (rc)
goto fail3;
}
channel->n_rx_frm_trunc = 0;
return 0;
fail3:
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_remove_rx_queue(rx_queue);
fail2:
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_remove_tx_queue(tx_queue);
fail1:
return rc;
}
static void efx_set_channel_names(struct efx_nic *efx)
{
struct efx_channel *channel;
const char *type = "";
int number;
efx_for_each_channel(channel, efx) {
number = channel->channel;
if (efx->n_channels > efx->n_rx_channels) {
if (channel->channel < efx->n_rx_channels) {
type = "-rx";
} else {
type = "-tx";
number -= efx->n_rx_channels;
}
}
snprintf(efx->channel_name[channel->channel],
sizeof(efx->channel_name[0]),
"%s%s-%d", efx->name, type, number);
}
}
static int efx_probe_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
int rc;
/* Restart special buffer allocation */
efx->next_buffer_table = 0;
efx_for_each_channel(channel, efx) {
rc = efx_probe_channel(channel);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create channel %d\n",
channel->channel);
goto fail;
}
}
efx_set_channel_names(efx);
return 0;
fail:
efx_remove_channels(efx);
return rc;
}
/* Channels are shutdown and reinitialised whilst the NIC is running
* to propagate configuration changes (mtu, checksum offload), or
* to clear hardware error conditions
*/
static void efx_init_channels(struct efx_nic *efx)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
struct efx_channel *channel;
/* Calculate the rx buffer allocation parameters required to
* support the current MTU, including padding for header
* alignment and overruns.
*/
efx->rx_buffer_len = (max(EFX_PAGE_IP_ALIGN, NET_IP_ALIGN) +
EFX_MAX_FRAME_LEN(efx->net_dev->mtu) +
efx->type->rx_buffer_hash_size +
efx->type->rx_buffer_padding);
efx->rx_buffer_order = get_order(efx->rx_buffer_len +
sizeof(struct efx_rx_page_state));
/* Initialise the channels */
efx_for_each_channel(channel, efx) {
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"init chan %d\n", channel->channel);
efx_init_eventq(channel);
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_init_tx_queue(tx_queue);
/* The rx buffer allocation strategy is MTU dependent */
efx_rx_strategy(channel);
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_init_rx_queue(rx_queue);
WARN_ON(channel->rx_pkt != NULL);
efx_rx_strategy(channel);
}
}
/* This enables event queue processing and packet transmission.
*
* Note that this function is not allowed to fail, since that would
* introduce too much complexity into the suspend/resume path.
*/
static void efx_start_channel(struct efx_channel *channel)
{
struct efx_rx_queue *rx_queue;
netif_dbg(channel->efx, ifup, channel->efx->net_dev,
"starting chan %d\n", channel->channel);
/* The interrupt handler for this channel may set work_pending
* as soon as we enable it. Make sure it's cleared before
* then. Similarly, make sure it sees the enabled flag set. */
channel->work_pending = false;
channel->enabled = true;
smp_wmb();
/* Fill the queues before enabling NAPI */
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_fast_push_rx_descriptors(rx_queue);
napi_enable(&channel->napi_str);
}
/* This disables event queue processing and packet transmission.
* This function does not guarantee that all queue processing
* (e.g. RX refill) is complete.
*/
static void efx_stop_channel(struct efx_channel *channel)
{
if (!channel->enabled)
return;
netif_dbg(channel->efx, ifdown, channel->efx->net_dev,
"stop chan %d\n", channel->channel);
channel->enabled = false;
napi_disable(&channel->napi_str);
}
static void efx_fini_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
struct pci_dev *dev = efx->pci_dev;
int rc;
EFX_ASSERT_RESET_SERIALISED(efx);
BUG_ON(efx->port_enabled);
/* Only perform flush if dma is enabled */
if (dev->is_busmaster) {
rc = efx_nic_flush_queues(efx);
if (rc && EFX_WORKAROUND_7803(efx)) {
/* Schedule a reset to recover from the flush failure. The
* descriptor caches reference memory we're about to free,
* but falcon_reconfigure_mac_wrapper() won't reconnect
* the MACs because of the pending reset. */
netif_err(efx, drv, efx->net_dev,
"Resetting to recover from flush failure\n");
efx_schedule_reset(efx, RESET_TYPE_ALL);
} else if (rc) {
netif_err(efx, drv, efx->net_dev, "failed to flush queues\n");
} else {
netif_dbg(efx, drv, efx->net_dev,
"successfully flushed all queues\n");
}
}
efx_for_each_channel(channel, efx) {
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"shut down chan %d\n", channel->channel);
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_fini_rx_queue(rx_queue);
efx_for_each_possible_channel_tx_queue(tx_queue, channel)
efx_fini_tx_queue(tx_queue);
efx_fini_eventq(channel);
}
}
static void efx_remove_channel(struct efx_channel *channel)
{
struct efx_tx_queue *tx_queue;
struct efx_rx_queue *rx_queue;
netif_dbg(channel->efx, drv, channel->efx->net_dev,
"destroy chan %d\n", channel->channel);
efx_for_each_channel_rx_queue(rx_queue, channel)
efx_remove_rx_queue(rx_queue);
efx_for_each_possible_channel_tx_queue(tx_queue, channel)
efx_remove_tx_queue(tx_queue);
efx_remove_eventq(channel);
}
static void efx_remove_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_remove_channel(channel);
}
int
efx_realloc_channels(struct efx_nic *efx, u32 rxq_entries, u32 txq_entries)
{
struct efx_channel *other_channel[EFX_MAX_CHANNELS], *channel;
u32 old_rxq_entries, old_txq_entries;
unsigned i;
int rc;
efx_device_detach_sync(efx);
efx_stop_all(efx);
efx_fini_channels(efx);
/* Clone channels */
memset(other_channel, 0, sizeof(other_channel));
for (i = 0; i < efx->n_channels; i++) {
channel = efx_alloc_channel(efx, i, efx->channel[i]);
if (!channel) {
rc = -ENOMEM;
goto out;
}
other_channel[i] = channel;
}
/* Swap entry counts and channel pointers */
old_rxq_entries = efx->rxq_entries;
old_txq_entries = efx->txq_entries;
efx->rxq_entries = rxq_entries;
efx->txq_entries = txq_entries;
for (i = 0; i < efx->n_channels; i++) {
channel = efx->channel[i];
efx->channel[i] = other_channel[i];
other_channel[i] = channel;
}
rc = efx_probe_channels(efx);
if (rc)
goto rollback;
efx_init_napi(efx);
/* Destroy old channels */
for (i = 0; i < efx->n_channels; i++) {
efx_fini_napi_channel(other_channel[i]);
efx_remove_channel(other_channel[i]);
}
out:
/* Free unused channel structures */
for (i = 0; i < efx->n_channels; i++)
kfree(other_channel[i]);
efx_init_channels(efx);
efx_start_all(efx);
netif_device_attach(efx->net_dev);
return rc;
rollback:
/* Swap back */
efx->rxq_entries = old_rxq_entries;
efx->txq_entries = old_txq_entries;
for (i = 0; i < efx->n_channels; i++) {
channel = efx->channel[i];
efx->channel[i] = other_channel[i];
other_channel[i] = channel;
}
goto out;
}
void efx_schedule_slow_fill(struct efx_rx_queue *rx_queue)
{
mod_timer(&rx_queue->slow_fill, jiffies + msecs_to_jiffies(100));
}
/**************************************************************************
*
* Port handling
*
**************************************************************************/
/* This ensures that the kernel is kept informed (via
* netif_carrier_on/off) of the link status, and also maintains the
* link status's stop on the port's TX queue.
*/
void efx_link_status_changed(struct efx_nic *efx)
{
struct efx_link_state *link_state = &efx->link_state;
/* SFC Bug 5356: A net_dev notifier is registered, so we must ensure
* that no events are triggered between unregister_netdev() and the
* driver unloading. A more general condition is that NETDEV_CHANGE
* can only be generated between NETDEV_UP and NETDEV_DOWN */
if (!netif_running(efx->net_dev))
return;
if (link_state->up != netif_carrier_ok(efx->net_dev)) {
efx->n_link_state_changes++;
if (link_state->up)
netif_carrier_on(efx->net_dev);
else
netif_carrier_off(efx->net_dev);
}
/* Status message for kernel log */
if (link_state->up) {
netif_info(efx, link, efx->net_dev,
"link up at %uMbps %s-duplex (MTU %d)%s\n",
link_state->speed, link_state->fd ? "full" : "half",
efx->net_dev->mtu,
(efx->promiscuous ? " [PROMISC]" : ""));
} else {
netif_info(efx, link, efx->net_dev, "link down\n");
}
}
void efx_link_set_advertising(struct efx_nic *efx, u32 advertising)
{
efx->link_advertising = advertising;
if (advertising) {
if (advertising & ADVERTISED_Pause)
efx->wanted_fc |= (EFX_FC_TX | EFX_FC_RX);
else
efx->wanted_fc &= ~(EFX_FC_TX | EFX_FC_RX);
if (advertising & ADVERTISED_Asym_Pause)
efx->wanted_fc ^= EFX_FC_TX;
}
}
void efx_link_set_wanted_fc(struct efx_nic *efx, u8 wanted_fc)
{
efx->wanted_fc = wanted_fc;
if (efx->link_advertising) {
if (wanted_fc & EFX_FC_RX)
efx->link_advertising |= (ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
else
efx->link_advertising &= ~(ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
if (wanted_fc & EFX_FC_TX)
efx->link_advertising ^= ADVERTISED_Asym_Pause;
}
}
static void efx_fini_port(struct efx_nic *efx);
/* Push loopback/power/transmit disable settings to the PHY, and reconfigure
* the MAC appropriately. All other PHY configuration changes are pushed
* through phy_op->set_settings(), and pushed asynchronously to the MAC
* through efx_monitor().
*
* Callers must hold the mac_lock
*/
int __efx_reconfigure_port(struct efx_nic *efx)
{
enum efx_phy_mode phy_mode;
int rc;
WARN_ON(!mutex_is_locked(&efx->mac_lock));
/* Serialise the promiscuous flag with efx_set_multicast_list. */
if (efx_dev_registered(efx)) {
netif_addr_lock_bh(efx->net_dev);
netif_addr_unlock_bh(efx->net_dev);
}
/* Disable PHY transmit in mac level loopbacks */
phy_mode = efx->phy_mode;
if (LOOPBACK_INTERNAL(efx))
efx->phy_mode |= PHY_MODE_TX_DISABLED;
else
efx->phy_mode &= ~PHY_MODE_TX_DISABLED;
rc = efx->type->reconfigure_port(efx);
if (rc)
efx->phy_mode = phy_mode;
return rc;
}
/* Reinitialise the MAC to pick up new PHY settings, even if the port is
* disabled. */
int efx_reconfigure_port(struct efx_nic *efx)
{
int rc;
EFX_ASSERT_RESET_SERIALISED(efx);
mutex_lock(&efx->mac_lock);
rc = __efx_reconfigure_port(efx);
mutex_unlock(&efx->mac_lock);
return rc;
}
/* Asynchronous work item for changing MAC promiscuity and multicast
* hash. Avoid a drain/rx_ingress enable by reconfiguring the current
* MAC directly. */
static void efx_mac_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic, mac_work);
mutex_lock(&efx->mac_lock);
if (efx->port_enabled) {
efx->type->push_multicast_hash(efx);
efx->mac_op->reconfigure(efx);
}
mutex_unlock(&efx->mac_lock);
}
static int efx_probe_port(struct efx_nic *efx)
{
unsigned char *perm_addr;
int rc;
netif_dbg(efx, probe, efx->net_dev, "create port\n");
if (phy_flash_cfg)
efx->phy_mode = PHY_MODE_SPECIAL;
/* Connect up MAC/PHY operations table */
rc = efx->type->probe_port(efx);
if (rc)
return rc;
/* Sanity check MAC address */
perm_addr = efx->net_dev->perm_addr;
if (is_valid_ether_addr(perm_addr)) {
memcpy(efx->net_dev->dev_addr, perm_addr, ETH_ALEN);
} else {
netif_err(efx, probe, efx->net_dev, "invalid MAC address %pM\n",
perm_addr);
if (!allow_bad_hwaddr) {
rc = -EINVAL;
goto err;
}
random_ether_addr(efx->net_dev->dev_addr);
netif_info(efx, probe, efx->net_dev,
"using locally-generated MAC %pM\n",
efx->net_dev->dev_addr);
}
return 0;
err:
efx->type->remove_port(efx);
return rc;
}
static int efx_init_port(struct efx_nic *efx)
{
int rc;
netif_dbg(efx, drv, efx->net_dev, "init port\n");
mutex_lock(&efx->mac_lock);
rc = efx->phy_op->init(efx);
if (rc)
goto fail1;
efx->port_initialized = true;
/* Reconfigure the MAC before creating dma queues (required for
* Falcon/A1 where RX_INGR_EN/TX_DRAIN_EN isn't supported) */
efx->mac_op->reconfigure(efx);
/* Ensure the PHY advertises the correct flow control settings */
rc = efx->phy_op->reconfigure(efx);
if (rc)
goto fail2;
mutex_unlock(&efx->mac_lock);
return 0;
fail2:
efx->phy_op->fini(efx);
fail1:
mutex_unlock(&efx->mac_lock);
return rc;
}
static void efx_start_port(struct efx_nic *efx)
{
netif_dbg(efx, ifup, efx->net_dev, "start port\n");
BUG_ON(efx->port_enabled);
mutex_lock(&efx->mac_lock);
efx->port_enabled = true;
/* efx_mac_work() might have been scheduled after efx_stop_port(),
* and then cancelled by efx_flush_all() */
efx->type->push_multicast_hash(efx);
efx->mac_op->reconfigure(efx);
mutex_unlock(&efx->mac_lock);
}
/* Prevent efx_mac_work() and efx_monitor() from working */
static void efx_stop_port(struct efx_nic *efx)
{
netif_dbg(efx, ifdown, efx->net_dev, "stop port\n");
mutex_lock(&efx->mac_lock);
efx->port_enabled = false;
mutex_unlock(&efx->mac_lock);
/* Serialise against efx_set_multicast_list() */
if (efx_dev_registered(efx)) {
netif_addr_lock_bh(efx->net_dev);
netif_addr_unlock_bh(efx->net_dev);
}
}
static void efx_fini_port(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "shut down port\n");
if (!efx->port_initialized)
return;
efx->phy_op->fini(efx);
efx->port_initialized = false;
efx->link_state.up = false;
efx_link_status_changed(efx);
}
static void efx_remove_port(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "destroying port\n");
efx->type->remove_port(efx);
}
/**************************************************************************
*
* NIC handling
*
**************************************************************************/
/* This configures the PCI device to enable I/O and DMA. */
static int efx_init_io(struct efx_nic *efx)
{
struct pci_dev *pci_dev = efx->pci_dev;
dma_addr_t dma_mask = efx->type->max_dma_mask;
int rc;
netif_dbg(efx, probe, efx->net_dev, "initialising I/O\n");
rc = pci_enable_device(pci_dev);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to enable PCI device\n");
goto fail1;
}
pci_set_master(pci_dev);
/* Set the PCI DMA mask. Try all possibilities from our
* genuine mask down to 32 bits, because some architectures
* (e.g. x86_64 with iommu_sac_force set) will allow 40 bit
* masks event though they reject 46 bit masks.
*/
while (dma_mask > 0x7fffffffUL) {
if (pci_dma_supported(pci_dev, dma_mask) &&
((rc = pci_set_dma_mask(pci_dev, dma_mask)) == 0))
break;
dma_mask >>= 1;
}
if (rc) {
netif_err(efx, probe, efx->net_dev,
"could not find a suitable DMA mask\n");
goto fail2;
}
netif_dbg(efx, probe, efx->net_dev,
"using DMA mask %llx\n", (unsigned long long) dma_mask);
rc = pci_set_consistent_dma_mask(pci_dev, dma_mask);
if (rc) {
/* pci_set_consistent_dma_mask() is not *allowed* to
* fail with a mask that pci_set_dma_mask() accepted,
* but just in case...
*/
netif_err(efx, probe, efx->net_dev,
"failed to set consistent DMA mask\n");
goto fail2;
}
efx->membase_phys = pci_resource_start(efx->pci_dev, EFX_MEM_BAR);
rc = pci_request_region(pci_dev, EFX_MEM_BAR, "sfc");
if (rc) {
netif_err(efx, probe, efx->net_dev,
"request for memory BAR failed\n");
rc = -EIO;
goto fail3;
}
efx->membase = ioremap_nocache(efx->membase_phys,
efx->type->mem_map_size);
if (!efx->membase) {
netif_err(efx, probe, efx->net_dev,
"could not map memory BAR at %llx+%x\n",
(unsigned long long)efx->membase_phys,
efx->type->mem_map_size);
rc = -ENOMEM;
goto fail4;
}
netif_dbg(efx, probe, efx->net_dev,
"memory BAR at %llx+%x (virtual %p)\n",
(unsigned long long)efx->membase_phys,
efx->type->mem_map_size, efx->membase);
return 0;
fail4:
pci_release_region(efx->pci_dev, EFX_MEM_BAR);
fail3:
efx->membase_phys = 0;
fail2:
pci_disable_device(efx->pci_dev);
fail1:
return rc;
}
static void efx_fini_io(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "shutting down I/O\n");
if (efx->membase) {
iounmap(efx->membase);
efx->membase = NULL;
}
if (efx->membase_phys) {
pci_release_region(efx->pci_dev, EFX_MEM_BAR);
efx->membase_phys = 0;
}
pci_disable_device(efx->pci_dev);
}
/* Get number of channels wanted. Each channel will have its own IRQ,
* 1 RX queue and/or 2 TX queues. */
static int efx_wanted_channels(void)
{
cpumask_var_t core_mask;
int count;
int cpu;
if (rss_cpus)
return rss_cpus;
if (unlikely(!zalloc_cpumask_var(&core_mask, GFP_KERNEL))) {
printk(KERN_WARNING
"sfc: RSS disabled due to allocation failure\n");
return 1;
}
count = 0;
for_each_online_cpu(cpu) {
if (!cpumask_test_cpu(cpu, core_mask)) {
++count;
cpumask_or(core_mask, core_mask,
topology_core_cpumask(cpu));
}
}
free_cpumask_var(core_mask);
return count;
}
static int
efx_init_rx_cpu_rmap(struct efx_nic *efx, struct msix_entry *xentries)
{
#ifdef CONFIG_RFS_ACCEL
int i, rc;
efx->net_dev->rx_cpu_rmap = alloc_irq_cpu_rmap(efx->n_rx_channels);
if (!efx->net_dev->rx_cpu_rmap)
return -ENOMEM;
for (i = 0; i < efx->n_rx_channels; i++) {
rc = irq_cpu_rmap_add(efx->net_dev->rx_cpu_rmap,
xentries[i].vector);
if (rc) {
free_irq_cpu_rmap(efx->net_dev->rx_cpu_rmap);
efx->net_dev->rx_cpu_rmap = NULL;
return rc;
}
}
#endif
return 0;
}
/* Probe the number and type of interrupts we are able to obtain, and
* the resulting numbers of channels and RX queues.
*/
static int efx_probe_interrupts(struct efx_nic *efx)
{
int max_channels =
min_t(int, efx->type->phys_addr_channels, EFX_MAX_CHANNELS);
int rc, i;
if (efx->interrupt_mode == EFX_INT_MODE_MSIX) {
struct msix_entry xentries[EFX_MAX_CHANNELS];
int n_channels;
n_channels = efx_wanted_channels();
if (separate_tx_channels)
n_channels *= 2;
n_channels = min(n_channels, max_channels);
for (i = 0; i < n_channels; i++)
xentries[i].entry = i;
rc = pci_enable_msix(efx->pci_dev, xentries, n_channels);
if (rc > 0) {
netif_err(efx, drv, efx->net_dev,
"WARNING: Insufficient MSI-X vectors"
" available (%d < %d).\n", rc, n_channels);
netif_err(efx, drv, efx->net_dev,
"WARNING: Performance may be reduced.\n");
EFX_BUG_ON_PARANOID(rc >= n_channels);
n_channels = rc;
rc = pci_enable_msix(efx->pci_dev, xentries,
n_channels);
}
if (rc == 0) {
efx->n_channels = n_channels;
if (separate_tx_channels) {
efx->n_tx_channels =
max(efx->n_channels / 2, 1U);
efx->n_rx_channels =
max(efx->n_channels -
efx->n_tx_channels, 1U);
} else {
efx->n_tx_channels = efx->n_channels;
efx->n_rx_channels = efx->n_channels;
}
rc = efx_init_rx_cpu_rmap(efx, xentries);
if (rc) {
pci_disable_msix(efx->pci_dev);
return rc;
}
for (i = 0; i < n_channels; i++)
efx_get_channel(efx, i)->irq =
xentries[i].vector;
} else {
/* Fall back to single channel MSI */
efx->interrupt_mode = EFX_INT_MODE_MSI;
netif_err(efx, drv, efx->net_dev,
"could not enable MSI-X\n");
}
}
/* Try single interrupt MSI */
if (efx->interrupt_mode == EFX_INT_MODE_MSI) {
efx->n_channels = 1;
efx->n_rx_channels = 1;
efx->n_tx_channels = 1;
rc = pci_enable_msi(efx->pci_dev);
if (rc == 0) {
efx_get_channel(efx, 0)->irq = efx->pci_dev->irq;
} else {
netif_err(efx, drv, efx->net_dev,
"could not enable MSI\n");
efx->interrupt_mode = EFX_INT_MODE_LEGACY;
}
}
/* Assume legacy interrupts */
if (efx->interrupt_mode == EFX_INT_MODE_LEGACY) {
efx->n_channels = 1 + (separate_tx_channels ? 1 : 0);
efx->n_rx_channels = 1;
efx->n_tx_channels = 1;
efx->legacy_irq = efx->pci_dev->irq;
}
return 0;
}
static void efx_remove_interrupts(struct efx_nic *efx)
{
struct efx_channel *channel;
/* Remove MSI/MSI-X interrupts */
efx_for_each_channel(channel, efx)
channel->irq = 0;
pci_disable_msi(efx->pci_dev);
pci_disable_msix(efx->pci_dev);
/* Remove legacy interrupt */
efx->legacy_irq = 0;
}
static void efx_set_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
efx->tx_channel_offset =
separate_tx_channels ? efx->n_channels - efx->n_tx_channels : 0;
/* We need to adjust the TX queue numbers if we have separate
* RX-only and TX-only channels.
*/
efx_for_each_channel(channel, efx) {
efx_for_each_channel_tx_queue(tx_queue, channel)
tx_queue->queue -= (efx->tx_channel_offset *
EFX_TXQ_TYPES);
}
}
static int efx_probe_nic(struct efx_nic *efx)
{
size_t i;
int rc;
netif_dbg(efx, probe, efx->net_dev, "creating NIC\n");
/* Carry out hardware-type specific initialisation */
rc = efx->type->probe(efx);
if (rc)
return rc;
/* Determine the number of channels and queues by trying to hook
* in MSI-X interrupts. */
rc = efx_probe_interrupts(efx);
if (rc)
goto fail;
if (efx->n_channels > 1)
get_random_bytes(&efx->rx_hash_key, sizeof(efx->rx_hash_key));
for (i = 0; i < ARRAY_SIZE(efx->rx_indir_table); i++)
efx->rx_indir_table[i] = i % efx->n_rx_channels;
efx_set_channels(efx);
netif_set_real_num_tx_queues(efx->net_dev, efx->n_tx_channels);
netif_set_real_num_rx_queues(efx->net_dev, efx->n_rx_channels);
/* Initialise the interrupt moderation settings */
efx_init_irq_moderation(efx, tx_irq_mod_usec, rx_irq_mod_usec, true);
return 0;
fail:
efx->type->remove(efx);
return rc;
}
static void efx_remove_nic(struct efx_nic *efx)
{
netif_dbg(efx, drv, efx->net_dev, "destroying NIC\n");
efx_remove_interrupts(efx);
efx->type->remove(efx);
}
/**************************************************************************
*
* NIC startup/shutdown
*
*************************************************************************/
static int efx_probe_all(struct efx_nic *efx)
{
int rc;
rc = efx_probe_nic(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create NIC\n");
goto fail1;
}
rc = efx_probe_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev, "failed to create port\n");
goto fail2;
}
BUILD_BUG_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_RXQ_MIN_ENT);
if (WARN_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_TXQ_MIN_ENT(efx))) {
rc = -EINVAL;
goto fail3;
}
efx->rxq_entries = efx->txq_entries = EFX_DEFAULT_DMAQ_SIZE;
rc = efx_probe_channels(efx);
if (rc)
goto fail3;
rc = efx_probe_filters(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create filter tables\n");
goto fail4;
}
return 0;
fail4:
efx_remove_channels(efx);
fail3:
efx_remove_port(efx);
fail2:
efx_remove_nic(efx);
fail1:
return rc;
}
/* Called after previous invocation(s) of efx_stop_all, restarts the
* port, kernel transmit queue, NAPI processing and hardware interrupts,
* and ensures that the port is scheduled to be reconfigured.
* This function is safe to call multiple times when the NIC is in any
* state. */
static void efx_start_all(struct efx_nic *efx)
{
struct efx_channel *channel;
EFX_ASSERT_RESET_SERIALISED(efx);
/* Check that it is appropriate to restart the interface. All
* of these flags are safe to read under just the rtnl lock */
if (efx->port_enabled)
return;
if ((efx->state != STATE_RUNNING) && (efx->state != STATE_INIT))
return;
if (efx_dev_registered(efx) && !netif_running(efx->net_dev))
return;
/* Mark the port as enabled so port reconfigurations can start, then
* restart the transmit interface early so the watchdog timer stops */
efx_start_port(efx);
if (efx_dev_registered(efx) && netif_device_present(efx->net_dev))
netif_tx_wake_all_queues(efx->net_dev);
efx_for_each_channel(channel, efx)
efx_start_channel(channel);
if (efx->legacy_irq)
efx->legacy_irq_enabled = true;
efx_nic_enable_interrupts(efx);
/* Switch to event based MCDI completions after enabling interrupts.
* If a reset has been scheduled, then we need to stay in polled mode.
* Rather than serialising efx_mcdi_mode_event() [which sleeps] and
* reset_pending [modified from an atomic context], we instead guarantee
* that efx_mcdi_mode_poll() isn't reverted erroneously */
efx_mcdi_mode_event(efx);
if (efx->reset_pending != RESET_TYPE_NONE)
efx_mcdi_mode_poll(efx);
/* Start the hardware monitor if there is one. Otherwise (we're link
* event driven), we have to poll the PHY because after an event queue
* flush, we could have a missed a link state change */
if (efx->type->monitor != NULL) {
queue_delayed_work(efx->workqueue, &efx->monitor_work,
efx_monitor_interval);
} else {
mutex_lock(&efx->mac_lock);
if (efx->phy_op->poll(efx))
efx_link_status_changed(efx);
mutex_unlock(&efx->mac_lock);
}
efx->type->start_stats(efx);
}
/* Flush all delayed work. Should only be called when no more delayed work
* will be scheduled. This doesn't flush pending online resets (efx_reset),
* since we're holding the rtnl_lock at this point. */
static void efx_flush_all(struct efx_nic *efx)
{
/* Make sure the hardware monitor is stopped */
cancel_delayed_work_sync(&efx->monitor_work);
/* Stop scheduled port reconfigurations */
cancel_work_sync(&efx->mac_work);
}
/* Quiesce hardware and software without bringing the link down.
* Safe to call multiple times, when the nic and interface is in any
* state. The caller is guaranteed to subsequently be in a position
* to modify any hardware and software state they see fit without
* taking locks. */
static void efx_stop_all(struct efx_nic *efx)
{
struct efx_channel *channel;
EFX_ASSERT_RESET_SERIALISED(efx);
/* port_enabled can be read safely under the rtnl lock */
if (!efx->port_enabled)
return;
efx->type->stop_stats(efx);
/* Switch to MCDI polling on Siena before disabling interrupts */
efx_mcdi_mode_poll(efx);
/* Disable interrupts and wait for ISR to complete */
efx_nic_disable_interrupts(efx);
if (efx->legacy_irq) {
synchronize_irq(efx->legacy_irq);
efx->legacy_irq_enabled = false;
}
efx_for_each_channel(channel, efx) {
if (channel->irq)
synchronize_irq(channel->irq);
}
/* Stop all NAPI processing and synchronous rx refills */
efx_for_each_channel(channel, efx)
efx_stop_channel(channel);
/* Stop all asynchronous port reconfigurations. Since all
* event processing has already been stopped, there is no
* window to loose phy events */
efx_stop_port(efx);
/* Flush efx_mac_work(), refill_workqueue, monitor_work */
efx_flush_all(efx);
/* Stop the kernel transmit interface. This is only valid if
* the device is stopped or detached; otherwise the watchdog
* may fire immediately.
*/
WARN_ON(netif_running(efx->net_dev) &&
netif_device_present(efx->net_dev));
if (efx_dev_registered(efx)) {
netif_tx_stop_all_queues(efx->net_dev);
netif_tx_lock_bh(efx->net_dev);
netif_tx_unlock_bh(efx->net_dev);
}
}
static void efx_remove_all(struct efx_nic *efx)
{
efx_remove_filters(efx);
efx_remove_channels(efx);
efx_remove_port(efx);
efx_remove_nic(efx);
}
/**************************************************************************
*
* Interrupt moderation
*
**************************************************************************/
static unsigned irq_mod_ticks(int usecs, int resolution)
{
if (usecs <= 0)
return 0; /* cannot receive interrupts ahead of time :-) */
if (usecs < resolution)
return 1; /* never round down to 0 */
return usecs / resolution;
}
/* Set interrupt moderation parameters */
void efx_init_irq_moderation(struct efx_nic *efx, int tx_usecs, int rx_usecs,
bool rx_adaptive)
{
struct efx_channel *channel;
unsigned tx_ticks = irq_mod_ticks(tx_usecs, EFX_IRQ_MOD_RESOLUTION);
unsigned rx_ticks = irq_mod_ticks(rx_usecs, EFX_IRQ_MOD_RESOLUTION);
EFX_ASSERT_RESET_SERIALISED(efx);
efx->irq_rx_adaptive = rx_adaptive;
efx->irq_rx_moderation = rx_ticks;
efx_for_each_channel(channel, efx) {
if (efx_channel_has_rx_queue(channel))
channel->irq_moderation = rx_ticks;
else if (efx_channel_has_tx_queues(channel))
channel->irq_moderation = tx_ticks;
}
}
/**************************************************************************
*
* Hardware monitor
*
**************************************************************************/
/* Run periodically off the general workqueue */
static void efx_monitor(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic,
monitor_work.work);
netif_vdbg(efx, timer, efx->net_dev,
"hardware monitor executing on CPU %d\n",
raw_smp_processor_id());
BUG_ON(efx->type->monitor == NULL);
/* If the mac_lock is already held then it is likely a port
* reconfiguration is already in place, which will likely do
* most of the work of monitor() anyway. */
if (mutex_trylock(&efx->mac_lock)) {
if (efx->port_enabled)
efx->type->monitor(efx);
mutex_unlock(&efx->mac_lock);
}
queue_delayed_work(efx->workqueue, &efx->monitor_work,
efx_monitor_interval);
}
/**************************************************************************
*
* ioctls
*
*************************************************************************/
/* Net device ioctl
* Context: process, rtnl_lock() held.
*/
static int efx_ioctl(struct net_device *net_dev, struct ifreq *ifr, int cmd)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct mii_ioctl_data *data = if_mii(ifr);
EFX_ASSERT_RESET_SERIALISED(efx);
/* Convert phy_id from older PRTAD/DEVAD format */
if ((cmd == SIOCGMIIREG || cmd == SIOCSMIIREG) &&
(data->phy_id & 0xfc00) == 0x0400)
data->phy_id ^= MDIO_PHY_ID_C45 | 0x0400;
return mdio_mii_ioctl(&efx->mdio, data, cmd);
}
/**************************************************************************
*
* NAPI interface
*
**************************************************************************/
static void efx_init_napi(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx) {
channel->napi_dev = efx->net_dev;
netif_napi_add(channel->napi_dev, &channel->napi_str,
efx_poll, napi_weight);
}
}
static void efx_fini_napi_channel(struct efx_channel *channel)
{
if (channel->napi_dev)
netif_napi_del(&channel->napi_str);
channel->napi_dev = NULL;
}
static void efx_fini_napi(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_fini_napi_channel(channel);
}
/**************************************************************************
*
* Kernel netpoll interface
*
*************************************************************************/
#ifdef CONFIG_NET_POLL_CONTROLLER
/* Although in the common case interrupts will be disabled, this is not
* guaranteed. However, all our work happens inside the NAPI callback,
* so no locking is required.
*/
static void efx_netpoll(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_schedule_channel(channel);
}
#endif
/**************************************************************************
*
* Kernel net device interface
*
*************************************************************************/
/* Context: process, rtnl_lock() held. */
static int efx_net_open(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
EFX_ASSERT_RESET_SERIALISED(efx);
netif_dbg(efx, ifup, efx->net_dev, "opening device on CPU %d\n",
raw_smp_processor_id());
if (efx->state == STATE_DISABLED)
return -EIO;
if (efx->phy_mode & PHY_MODE_SPECIAL)
return -EBUSY;
if (efx_mcdi_poll_reboot(efx) && efx_reset(efx, RESET_TYPE_ALL))
return -EIO;
/* Notify the kernel of the link state polled during driver load,
* before the monitor starts running */
efx_link_status_changed(efx);
efx_start_all(efx);
return 0;
}
/* Context: process, rtnl_lock() held.
* Note that the kernel will ignore our return code; this method
* should really be a void.
*/
static int efx_net_stop(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
netif_dbg(efx, ifdown, efx->net_dev, "closing on CPU %d\n",
raw_smp_processor_id());
if (efx->state != STATE_DISABLED) {
/* Stop the device and flush all the channels */
efx_stop_all(efx);
efx_fini_channels(efx);
efx_init_channels(efx);
}
return 0;
}
/* Context: process, dev_base_lock or RTNL held, non-blocking. */
static struct rtnl_link_stats64 *efx_net_stats(struct net_device *net_dev, struct rtnl_link_stats64 *stats)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct efx_mac_stats *mac_stats = &efx->mac_stats;
spin_lock_bh(&efx->stats_lock);
efx->type->update_stats(efx);
spin_unlock_bh(&efx->stats_lock);
stats->rx_packets = mac_stats->rx_packets;
stats->tx_packets = mac_stats->tx_packets;
stats->rx_bytes = mac_stats->rx_bytes;
stats->tx_bytes = mac_stats->tx_bytes;
stats->rx_dropped = efx->n_rx_nodesc_drop_cnt;
stats->multicast = mac_stats->rx_multicast;
stats->collisions = mac_stats->tx_collision;
stats->rx_length_errors = (mac_stats->rx_gtjumbo +
mac_stats->rx_length_error);
stats->rx_crc_errors = mac_stats->rx_bad;
stats->rx_frame_errors = mac_stats->rx_align_error;
stats->rx_fifo_errors = mac_stats->rx_overflow;
stats->rx_missed_errors = mac_stats->rx_missed;
stats->tx_window_errors = mac_stats->tx_late_collision;
stats->rx_errors = (stats->rx_length_errors +
stats->rx_crc_errors +
stats->rx_frame_errors +
mac_stats->rx_symbol_error);
stats->tx_errors = (stats->tx_window_errors +
mac_stats->tx_bad);
return stats;
}
/* Context: netif_tx_lock held, BHs disabled. */
static void efx_watchdog(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
netif_err(efx, tx_err, efx->net_dev,
"TX stuck with port_enabled=%d: resetting channels\n",
efx->port_enabled);
efx_schedule_reset(efx, RESET_TYPE_TX_WATCHDOG);
}
/* Context: process, rtnl_lock() held. */
static int efx_change_mtu(struct net_device *net_dev, int new_mtu)
{
struct efx_nic *efx = netdev_priv(net_dev);
int rc = 0;
EFX_ASSERT_RESET_SERIALISED(efx);
if (new_mtu > EFX_MAX_MTU)
return -EINVAL;
netif_dbg(efx, drv, efx->net_dev, "changing MTU to %d\n", new_mtu);
efx_device_detach_sync(efx);
efx_stop_all(efx);
efx_fini_channels(efx);
mutex_lock(&efx->mac_lock);
/* Reconfigure the MAC before enabling the dma queues so that
* the RX buffers don't overflow */
net_dev->mtu = new_mtu;
efx->mac_op->reconfigure(efx);
mutex_unlock(&efx->mac_lock);
efx_init_channels(efx);
efx_start_all(efx);
netif_device_attach(efx->net_dev);
return rc;
}
static int efx_set_mac_address(struct net_device *net_dev, void *data)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct sockaddr *addr = data;
char *new_addr = addr->sa_data;
EFX_ASSERT_RESET_SERIALISED(efx);
if (!is_valid_ether_addr(new_addr)) {
netif_err(efx, drv, efx->net_dev,
"invalid ethernet MAC address requested: %pM\n",
new_addr);
return -EINVAL;
}
memcpy(net_dev->dev_addr, new_addr, net_dev->addr_len);
/* Reconfigure the MAC */
mutex_lock(&efx->mac_lock);
efx->mac_op->reconfigure(efx);
mutex_unlock(&efx->mac_lock);
return 0;
}
/* Context: netif_addr_lock held, BHs disabled. */
static void efx_set_multicast_list(struct net_device *net_dev)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct netdev_hw_addr *ha;
union efx_multicast_hash *mc_hash = &efx->multicast_hash;
u32 crc;
int bit;
efx->promiscuous = !!(net_dev->flags & IFF_PROMISC);
/* Build multicast hash table */
if (efx->promiscuous || (net_dev->flags & IFF_ALLMULTI)) {
memset(mc_hash, 0xff, sizeof(*mc_hash));
} else {
memset(mc_hash, 0x00, sizeof(*mc_hash));
netdev_for_each_mc_addr(ha, net_dev) {
crc = ether_crc_le(ETH_ALEN, ha->addr);
bit = crc & (EFX_MCAST_HASH_ENTRIES - 1);
set_bit_le(bit, mc_hash->byte);
}
/* Broadcast packets go through the multicast hash filter.
* ether_crc_le() of the broadcast address is 0xbe2612ff
* so we always add bit 0xff to the mask.
*/
set_bit_le(0xff, mc_hash->byte);
}
if (efx->port_enabled)
queue_work(efx->workqueue, &efx->mac_work);
/* Otherwise efx_start_port() will do this */
}
static int efx_set_features(struct net_device *net_dev, u32 data)
{
struct efx_nic *efx = netdev_priv(net_dev);
/* If disabling RX n-tuple filtering, clear existing filters */
if (net_dev->features & ~data & NETIF_F_NTUPLE)
efx_filter_clear_rx(efx, EFX_FILTER_PRI_MANUAL);
return 0;
}
static const struct net_device_ops efx_netdev_ops = {
.ndo_open = efx_net_open,
.ndo_stop = efx_net_stop,
.ndo_get_stats64 = efx_net_stats,
.ndo_tx_timeout = efx_watchdog,
.ndo_start_xmit = efx_hard_start_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_do_ioctl = efx_ioctl,
.ndo_change_mtu = efx_change_mtu,
.ndo_set_mac_address = efx_set_mac_address,
.ndo_set_multicast_list = efx_set_multicast_list,
.ndo_set_features = efx_set_features,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = efx_netpoll,
#endif
.ndo_setup_tc = efx_setup_tc,
#ifdef CONFIG_RFS_ACCEL
.ndo_rx_flow_steer = efx_filter_rfs,
#endif
};
static void efx_update_name(struct efx_nic *efx)
{
strcpy(efx->name, efx->net_dev->name);
efx_mtd_rename(efx);
efx_set_channel_names(efx);
}
static int efx_netdev_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *net_dev = ptr;
if (net_dev->netdev_ops == &efx_netdev_ops &&
event == NETDEV_CHANGENAME)
efx_update_name(netdev_priv(net_dev));
return NOTIFY_DONE;
}
static struct notifier_block efx_netdev_notifier = {
.notifier_call = efx_netdev_event,
};
static ssize_t
show_phy_type(struct device *dev, struct device_attribute *attr, char *buf)
{
struct efx_nic *efx = pci_get_drvdata(to_pci_dev(dev));
return sprintf(buf, "%d\n", efx->phy_type);
}
static DEVICE_ATTR(phy_type, 0644, show_phy_type, NULL);
static int efx_register_netdev(struct efx_nic *efx)
{
struct net_device *net_dev = efx->net_dev;
struct efx_channel *channel;
int rc;
net_dev->watchdog_timeo = 5 * HZ;
net_dev->irq = efx->pci_dev->irq;
net_dev->netdev_ops = &efx_netdev_ops;
SET_ETHTOOL_OPS(net_dev, &efx_ethtool_ops);
net_dev->gso_max_segs = EFX_TSO_MAX_SEGS;
/* Clear MAC statistics */
efx->mac_op->update_stats(efx);
memset(&efx->mac_stats, 0, sizeof(efx->mac_stats));
rtnl_lock();
rc = dev_alloc_name(net_dev, net_dev->name);
if (rc < 0)
goto fail_locked;
efx_update_name(efx);
rc = register_netdevice(net_dev);
if (rc)
goto fail_locked;
efx_for_each_channel(channel, efx) {
struct efx_tx_queue *tx_queue;
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_init_tx_queue_core_txq(tx_queue);
}
/* Always start with carrier off; PHY events will detect the link */
netif_carrier_off(efx->net_dev);
rtnl_unlock();
rc = device_create_file(&efx->pci_dev->dev, &dev_attr_phy_type);
if (rc) {
netif_err(efx, drv, efx->net_dev,
"failed to init net dev attributes\n");
goto fail_registered;
}
return 0;
fail_locked:
rtnl_unlock();
netif_err(efx, drv, efx->net_dev, "could not register net dev\n");
return rc;
fail_registered:
unregister_netdev(net_dev);
return rc;
}
static void efx_unregister_netdev(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_tx_queue *tx_queue;
if (!efx->net_dev)
return;
BUG_ON(netdev_priv(efx->net_dev) != efx);
/* Free up any skbs still remaining. This has to happen before
* we try to unregister the netdev as running their destructors
* may be needed to get the device ref. count to 0. */
efx_for_each_channel(channel, efx) {
efx_for_each_channel_tx_queue(tx_queue, channel)
efx_release_tx_buffers(tx_queue);
}
if (efx_dev_registered(efx)) {
strlcpy(efx->name, pci_name(efx->pci_dev), sizeof(efx->name));
device_remove_file(&efx->pci_dev->dev, &dev_attr_phy_type);
unregister_netdev(efx->net_dev);
}
}
/**************************************************************************
*
* Device reset and suspend
*
**************************************************************************/
/* Tears down the entire software state and most of the hardware state
* before reset. */
void efx_reset_down(struct efx_nic *efx, enum reset_type method)
{
EFX_ASSERT_RESET_SERIALISED(efx);
efx_stop_all(efx);
mutex_lock(&efx->mac_lock);
efx_fini_channels(efx);
if (efx->port_initialized && method != RESET_TYPE_INVISIBLE)
efx->phy_op->fini(efx);
efx->type->fini(efx);
}
/* This function will always ensure that the locks acquired in
* efx_reset_down() are released. A failure return code indicates
* that we were unable to reinitialise the hardware, and the
* driver should be disabled. If ok is false, then the rx and tx
* engines are not restarted, pending a RESET_DISABLE. */
int efx_reset_up(struct efx_nic *efx, enum reset_type method, bool ok)
{
int rc;
EFX_ASSERT_RESET_SERIALISED(efx);
rc = efx->type->init(efx);
if (rc) {
netif_err(efx, drv, efx->net_dev, "failed to initialise NIC\n");
goto fail;
}
if (!ok)
goto fail;
if (efx->port_initialized && method != RESET_TYPE_INVISIBLE) {
rc = efx->phy_op->init(efx);
if (rc)
goto fail;
if (efx->phy_op->reconfigure(efx))
netif_err(efx, drv, efx->net_dev,
"could not restore PHY settings\n");
}
efx->mac_op->reconfigure(efx);
efx_init_channels(efx);
efx_restore_filters(efx);
mutex_unlock(&efx->mac_lock);
efx_start_all(efx);
return 0;
fail:
efx->port_initialized = false;
mutex_unlock(&efx->mac_lock);
return rc;
}
/* Reset the NIC using the specified method. Note that the reset may
* fail, in which case the card will be left in an unusable state.
*
* Caller must hold the rtnl_lock.
*/
int efx_reset(struct efx_nic *efx, enum reset_type method)
{
int rc, rc2;
bool disabled;
netif_info(efx, drv, efx->net_dev, "resetting (%s)\n",
RESET_TYPE(method));
efx_device_detach_sync(efx);
efx_reset_down(efx, method);
rc = efx->type->reset(efx, method);
if (rc) {
netif_err(efx, drv, efx->net_dev, "failed to reset hardware\n");
goto out;
}
/* Allow resets to be rescheduled. */
efx->reset_pending = RESET_TYPE_NONE;
/* Reinitialise bus-mastering, which may have been turned off before
* the reset was scheduled. This is still appropriate, even in the
* RESET_TYPE_DISABLE since this driver generally assumes the hardware
* can respond to requests. */
pci_set_master(efx->pci_dev);
out:
/* Leave device stopped if necessary */
disabled = rc || method == RESET_TYPE_DISABLE;
rc2 = efx_reset_up(efx, method, !disabled);
if (rc2) {
disabled = true;
if (!rc)
rc = rc2;
}
if (disabled) {
dev_close(efx->net_dev);
netif_err(efx, drv, efx->net_dev, "has been disabled\n");
efx->state = STATE_DISABLED;
} else {
netif_dbg(efx, drv, efx->net_dev, "reset complete\n");
netif_device_attach(efx->net_dev);
}
return rc;
}
/* The worker thread exists so that code that cannot sleep can
* schedule a reset for later.
*/
static void efx_reset_work(struct work_struct *data)
{
struct efx_nic *efx = container_of(data, struct efx_nic, reset_work);
if (efx->reset_pending == RESET_TYPE_NONE)
return;
/* If we're not RUNNING then don't reset. Leave the reset_pending
* flag set so that efx_pci_probe_main will be retried */
if (efx->state != STATE_RUNNING) {
netif_info(efx, drv, efx->net_dev,
"scheduled reset quenched. NIC not RUNNING\n");
return;
}
rtnl_lock();
(void)efx_reset(efx, efx->reset_pending);
rtnl_unlock();
}
void efx_schedule_reset(struct efx_nic *efx, enum reset_type type)
{
enum reset_type method;
if (efx->reset_pending != RESET_TYPE_NONE) {
netif_info(efx, drv, efx->net_dev,
"quenching already scheduled reset\n");
return;
}
switch (type) {
case RESET_TYPE_INVISIBLE:
case RESET_TYPE_ALL:
case RESET_TYPE_WORLD:
case RESET_TYPE_DISABLE:
method = type;
break;
case RESET_TYPE_RX_RECOVERY:
case RESET_TYPE_RX_DESC_FETCH:
case RESET_TYPE_TX_DESC_FETCH:
case RESET_TYPE_TX_SKIP:
method = RESET_TYPE_INVISIBLE;
break;
case RESET_TYPE_MC_FAILURE:
default:
method = RESET_TYPE_ALL;
break;
}
if (method != type)
netif_dbg(efx, drv, efx->net_dev,
"scheduling %s reset for %s\n",
RESET_TYPE(method), RESET_TYPE(type));
else
netif_dbg(efx, drv, efx->net_dev, "scheduling %s reset\n",
RESET_TYPE(method));
efx->reset_pending = method;
/* efx_process_channel() will no longer read events once a
* reset is scheduled. So switch back to poll'd MCDI completions. */
efx_mcdi_mode_poll(efx);
queue_work(reset_workqueue, &efx->reset_work);
}
/**************************************************************************
*
* List of NICs we support
*
**************************************************************************/
/* PCI device ID table */
static DEFINE_PCI_DEVICE_TABLE(efx_pci_table) = {
{PCI_DEVICE(EFX_VENDID_SFC, FALCON_A_P_DEVID),
.driver_data = (unsigned long) &falcon_a1_nic_type},
{PCI_DEVICE(EFX_VENDID_SFC, FALCON_B_P_DEVID),
.driver_data = (unsigned long) &falcon_b0_nic_type},
{PCI_DEVICE(EFX_VENDID_SFC, BETHPAGE_A_P_DEVID),
.driver_data = (unsigned long) &siena_a0_nic_type},
{PCI_DEVICE(EFX_VENDID_SFC, SIENA_A_P_DEVID),
.driver_data = (unsigned long) &siena_a0_nic_type},
{0} /* end of list */
};
/**************************************************************************
*
* Dummy PHY/MAC operations
*
* Can be used for some unimplemented operations
* Needed so all function pointers are valid and do not have to be tested
* before use
*
**************************************************************************/
int efx_port_dummy_op_int(struct efx_nic *efx)
{
return 0;
}
void efx_port_dummy_op_void(struct efx_nic *efx) {}
static bool efx_port_dummy_op_poll(struct efx_nic *efx)
{
return false;
}
static const struct efx_phy_operations efx_dummy_phy_operations = {
.init = efx_port_dummy_op_int,
.reconfigure = efx_port_dummy_op_int,
.poll = efx_port_dummy_op_poll,
.fini = efx_port_dummy_op_void,
};
/**************************************************************************
*
* Data housekeeping
*
**************************************************************************/
/* This zeroes out and then fills in the invariants in a struct
* efx_nic (including all sub-structures).
*/
static int efx_init_struct(struct efx_nic *efx, const struct efx_nic_type *type,
struct pci_dev *pci_dev, struct net_device *net_dev)
{
int i;
/* Initialise common structures */
memset(efx, 0, sizeof(*efx));
spin_lock_init(&efx->biu_lock);
#ifdef CONFIG_SFC_MTD
INIT_LIST_HEAD(&efx->mtd_list);
#endif
INIT_WORK(&efx->reset_work, efx_reset_work);
INIT_DELAYED_WORK(&efx->monitor_work, efx_monitor);
efx->pci_dev = pci_dev;
efx->msg_enable = debug;
efx->state = STATE_INIT;
efx->reset_pending = RESET_TYPE_NONE;
strlcpy(efx->name, pci_name(pci_dev), sizeof(efx->name));
efx->net_dev = net_dev;
spin_lock_init(&efx->stats_lock);
mutex_init(&efx->mac_lock);
efx->mac_op = type->default_mac_ops;
efx->phy_op = &efx_dummy_phy_operations;
efx->mdio.dev = net_dev;
INIT_WORK(&efx->mac_work, efx_mac_work);
for (i = 0; i < EFX_MAX_CHANNELS; i++) {
efx->channel[i] = efx_alloc_channel(efx, i, NULL);
if (!efx->channel[i])
goto fail;
}
efx->type = type;
EFX_BUG_ON_PARANOID(efx->type->phys_addr_channels > EFX_MAX_CHANNELS);
/* Higher numbered interrupt modes are less capable! */
efx->interrupt_mode = max(efx->type->max_interrupt_mode,
interrupt_mode);
/* Would be good to use the net_dev name, but we're too early */
snprintf(efx->workqueue_name, sizeof(efx->workqueue_name), "sfc%s",
pci_name(pci_dev));
efx->workqueue = create_singlethread_workqueue(efx->workqueue_name);
if (!efx->workqueue)
goto fail;
return 0;
fail:
efx_fini_struct(efx);
return -ENOMEM;
}
static void efx_fini_struct(struct efx_nic *efx)
{
int i;
for (i = 0; i < EFX_MAX_CHANNELS; i++)
kfree(efx->channel[i]);
if (efx->workqueue) {
destroy_workqueue(efx->workqueue);
efx->workqueue = NULL;
}
}
/**************************************************************************
*
* PCI interface
*
**************************************************************************/
/* Main body of final NIC shutdown code
* This is called only at module unload (or hotplug removal).
*/
static void efx_pci_remove_main(struct efx_nic *efx)
{
#ifdef CONFIG_RFS_ACCEL
free_irq_cpu_rmap(efx->net_dev->rx_cpu_rmap);
efx->net_dev->rx_cpu_rmap = NULL;
#endif
efx_nic_fini_interrupt(efx);
efx_fini_channels(efx);
efx_fini_port(efx);
efx->type->fini(efx);
efx_fini_napi(efx);
efx_remove_all(efx);
}
/* Final NIC shutdown
* This is called only at module unload (or hotplug removal).
*/
static void efx_pci_remove(struct pci_dev *pci_dev)
{
struct efx_nic *efx;
efx = pci_get_drvdata(pci_dev);
if (!efx)
return;
/* Mark the NIC as fini, then stop the interface */
rtnl_lock();
efx->state = STATE_FINI;
dev_close(efx->net_dev);
/* Allow any queued efx_resets() to complete */
rtnl_unlock();
efx_unregister_netdev(efx);
efx_mtd_remove(efx);
/* Wait for any scheduled resets to complete. No more will be
* scheduled from this point because efx_stop_all() has been
* called, we are no longer registered with driverlink, and
* the net_device's have been removed. */
cancel_work_sync(&efx->reset_work);
efx_pci_remove_main(efx);
efx_fini_io(efx);
netif_dbg(efx, drv, efx->net_dev, "shutdown successful\n");
pci_set_drvdata(pci_dev, NULL);
efx_fini_struct(efx);
free_netdev(efx->net_dev);
};
/* Main body of NIC initialisation
* This is called at module load (or hotplug insertion, theoretically).
*/
static int efx_pci_probe_main(struct efx_nic *efx)
{
int rc;
/* Do start-of-day initialisation */
rc = efx_probe_all(efx);
if (rc)
goto fail1;
efx_init_napi(efx);
rc = efx->type->init(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to initialise NIC\n");
goto fail3;
}
rc = efx_init_port(efx);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to initialise port\n");
goto fail4;
}
efx_init_channels(efx);
rc = efx_nic_init_interrupt(efx);
if (rc)
goto fail5;
return 0;
fail5:
efx_fini_channels(efx);
efx_fini_port(efx);
fail4:
efx->type->fini(efx);
fail3:
efx_fini_napi(efx);
efx_remove_all(efx);
fail1:
return rc;
}
/* NIC initialisation
*
* This is called at module load (or hotplug insertion,
* theoretically). It sets up PCI mappings, tests and resets the NIC,
* sets up and registers the network devices with the kernel and hooks
* the interrupt service routine. It does not prepare the device for
* transmission; this is left to the first time one of the network
* interfaces is brought up (i.e. efx_net_open).
*/
static int __devinit efx_pci_probe(struct pci_dev *pci_dev,
const struct pci_device_id *entry)
{
const struct efx_nic_type *type = (const struct efx_nic_type *) entry->driver_data;
struct net_device *net_dev;
struct efx_nic *efx;
int i, rc;
/* Allocate and initialise a struct net_device and struct efx_nic */
net_dev = alloc_etherdev_mqs(sizeof(*efx), EFX_MAX_CORE_TX_QUEUES,
EFX_MAX_RX_QUEUES);
if (!net_dev)
return -ENOMEM;
net_dev->features |= (type->offload_features | NETIF_F_SG |
NETIF_F_HIGHDMA | NETIF_F_TSO |
NETIF_F_RXCSUM);
if (type->offload_features & NETIF_F_V6_CSUM)
net_dev->features |= NETIF_F_TSO6;
/* Mask for features that also apply to VLAN devices */
net_dev->vlan_features |= (NETIF_F_ALL_CSUM | NETIF_F_SG |
NETIF_F_HIGHDMA | NETIF_F_ALL_TSO |
NETIF_F_RXCSUM);
/* All offloads can be toggled */
net_dev->hw_features = net_dev->features & ~NETIF_F_HIGHDMA;
efx = netdev_priv(net_dev);
pci_set_drvdata(pci_dev, efx);
SET_NETDEV_DEV(net_dev, &pci_dev->dev);
rc = efx_init_struct(efx, type, pci_dev, net_dev);
if (rc)
goto fail1;
netif_info(efx, probe, efx->net_dev,
"Solarflare Communications NIC detected\n");
/* Set up basic I/O (BAR mappings etc) */
rc = efx_init_io(efx);
if (rc)
goto fail2;
/* No serialisation is required with the reset path because
* we're in STATE_INIT. */
for (i = 0; i < 5; i++) {
rc = efx_pci_probe_main(efx);
/* Serialise against efx_reset(). No more resets will be
* scheduled since efx_stop_all() has been called, and we
* have not and never have been registered with either
* the rtnetlink or driverlink layers. */
cancel_work_sync(&efx->reset_work);
if (rc == 0) {
if (efx->reset_pending != RESET_TYPE_NONE) {
/* If there was a scheduled reset during
* probe, the NIC is probably hosed anyway */
efx_pci_remove_main(efx);
rc = -EIO;
} else {
break;
}
}
/* Retry if a recoverably reset event has been scheduled */
if ((efx->reset_pending != RESET_TYPE_INVISIBLE) &&
(efx->reset_pending != RESET_TYPE_ALL))
goto fail3;
efx->reset_pending = RESET_TYPE_NONE;
}
if (rc) {
netif_err(efx, probe, efx->net_dev, "Could not reset NIC\n");
goto fail4;
}
/* Switch to the running state before we expose the device to the OS,
* so that dev_open()|efx_start_all() will actually start the device */
efx->state = STATE_RUNNING;
rc = efx_register_netdev(efx);
if (rc)
goto fail5;
netif_dbg(efx, probe, efx->net_dev, "initialisation successful\n");
rtnl_lock();
efx_mtd_probe(efx); /* allowed to fail */
rtnl_unlock();
return 0;
fail5:
efx_pci_remove_main(efx);
fail4:
fail3:
efx_fini_io(efx);
fail2:
efx_fini_struct(efx);
fail1:
WARN_ON(rc > 0);
netif_dbg(efx, drv, efx->net_dev, "initialisation failed. rc=%d\n", rc);
free_netdev(net_dev);
return rc;
}
static int efx_pm_freeze(struct device *dev)
{
struct efx_nic *efx = pci_get_drvdata(to_pci_dev(dev));
efx->state = STATE_FINI;
efx_device_detach_sync(efx);
efx_stop_all(efx);
efx_fini_channels(efx);
return 0;
}
static int efx_pm_thaw(struct device *dev)
{
struct efx_nic *efx = pci_get_drvdata(to_pci_dev(dev));
efx->state = STATE_INIT;
efx_init_channels(efx);
mutex_lock(&efx->mac_lock);
efx->phy_op->reconfigure(efx);
mutex_unlock(&efx->mac_lock);
efx_start_all(efx);
netif_device_attach(efx->net_dev);
efx->state = STATE_RUNNING;
efx->type->resume_wol(efx);
/* Reschedule any quenched resets scheduled during efx_pm_freeze() */
queue_work(reset_workqueue, &efx->reset_work);
return 0;
}
static int efx_pm_poweroff(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct efx_nic *efx = pci_get_drvdata(pci_dev);
efx->type->fini(efx);
efx->reset_pending = RESET_TYPE_NONE;
pci_save_state(pci_dev);
return pci_set_power_state(pci_dev, PCI_D3hot);
}
/* Used for both resume and restore */
static int efx_pm_resume(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct efx_nic *efx = pci_get_drvdata(pci_dev);
int rc;
rc = pci_set_power_state(pci_dev, PCI_D0);
if (rc)
return rc;
pci_restore_state(pci_dev);
rc = pci_enable_device(pci_dev);
if (rc)
return rc;
pci_set_master(efx->pci_dev);
rc = efx->type->reset(efx, RESET_TYPE_ALL);
if (rc)
return rc;
rc = efx->type->init(efx);
if (rc)
return rc;
efx_pm_thaw(dev);
return 0;
}
static int efx_pm_suspend(struct device *dev)
{
int rc;
efx_pm_freeze(dev);
rc = efx_pm_poweroff(dev);
if (rc)
efx_pm_resume(dev);
return rc;
}
static struct dev_pm_ops efx_pm_ops = {
.suspend = efx_pm_suspend,
.resume = efx_pm_resume,
.freeze = efx_pm_freeze,
.thaw = efx_pm_thaw,
.poweroff = efx_pm_poweroff,
.restore = efx_pm_resume,
};
static struct pci_driver efx_pci_driver = {
.name = KBUILD_MODNAME,
.id_table = efx_pci_table,
.probe = efx_pci_probe,
.remove = efx_pci_remove,
.driver.pm = &efx_pm_ops,
};
/**************************************************************************
*
* Kernel module interface
*
*************************************************************************/
module_param(interrupt_mode, uint, 0444);
MODULE_PARM_DESC(interrupt_mode,
"Interrupt mode (0=>MSIX 1=>MSI 2=>legacy)");
static int __init efx_init_module(void)
{
int rc;
printk(KERN_INFO "Solarflare NET driver v" EFX_DRIVER_VERSION "\n");
rc = register_netdevice_notifier(&efx_netdev_notifier);
if (rc)
goto err_notifier;
reset_workqueue = create_singlethread_workqueue("sfc_reset");
if (!reset_workqueue) {
rc = -ENOMEM;
goto err_reset;
}
rc = pci_register_driver(&efx_pci_driver);
if (rc < 0)
goto err_pci;
return 0;
err_pci:
destroy_workqueue(reset_workqueue);
err_reset:
unregister_netdevice_notifier(&efx_netdev_notifier);
err_notifier:
return rc;
}
static void __exit efx_exit_module(void)
{
printk(KERN_INFO "Solarflare NET driver unloading\n");
pci_unregister_driver(&efx_pci_driver);
destroy_workqueue(reset_workqueue);
unregister_netdevice_notifier(&efx_netdev_notifier);
}
module_init(efx_init_module);
module_exit(efx_exit_module);
MODULE_AUTHOR("Solarflare Communications and "
"Michael Brown <mbrown@fensystems.co.uk>");
MODULE_DESCRIPTION("Solarflare Communications network driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, efx_pci_table);
| gpl-2.0 |
rdeva31/kernel-msm-3.10 | drivers/mfd/db8500-prcmu.c | 1161 | 84247 | /*
* Copyright (C) STMicroelectronics 2009
* Copyright (C) ST-Ericsson SA 2010
*
* License Terms: GNU General Public License v2
* Author: Kumar Sanghvi <kumar.sanghvi@stericsson.com>
* Author: Sundar Iyer <sundar.iyer@stericsson.com>
* Author: Mattias Nilsson <mattias.i.nilsson@stericsson.com>
*
* U8500 PRCM Unit interface driver
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/completion.h>
#include <linux/irq.h>
#include <linux/jiffies.h>
#include <linux/bitops.h>
#include <linux/fs.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/uaccess.h>
#include <linux/mfd/core.h>
#include <linux/mfd/dbx500-prcmu.h>
#include <linux/mfd/abx500/ab8500.h>
#include <linux/regulator/db8500-prcmu.h>
#include <linux/regulator/machine.h>
#include <linux/cpufreq.h>
#include <linux/platform_data/ux500_wdt.h>
#include <linux/platform_data/db8500_thermal.h>
#include "dbx500-prcmu-regs.h"
/* Index of different voltages to be used when accessing AVSData */
#define PRCM_AVS_BASE 0x2FC
#define PRCM_AVS_VBB_RET (PRCM_AVS_BASE + 0x0)
#define PRCM_AVS_VBB_MAX_OPP (PRCM_AVS_BASE + 0x1)
#define PRCM_AVS_VBB_100_OPP (PRCM_AVS_BASE + 0x2)
#define PRCM_AVS_VBB_50_OPP (PRCM_AVS_BASE + 0x3)
#define PRCM_AVS_VARM_MAX_OPP (PRCM_AVS_BASE + 0x4)
#define PRCM_AVS_VARM_100_OPP (PRCM_AVS_BASE + 0x5)
#define PRCM_AVS_VARM_50_OPP (PRCM_AVS_BASE + 0x6)
#define PRCM_AVS_VARM_RET (PRCM_AVS_BASE + 0x7)
#define PRCM_AVS_VAPE_100_OPP (PRCM_AVS_BASE + 0x8)
#define PRCM_AVS_VAPE_50_OPP (PRCM_AVS_BASE + 0x9)
#define PRCM_AVS_VMOD_100_OPP (PRCM_AVS_BASE + 0xA)
#define PRCM_AVS_VMOD_50_OPP (PRCM_AVS_BASE + 0xB)
#define PRCM_AVS_VSAFE (PRCM_AVS_BASE + 0xC)
#define PRCM_AVS_VOLTAGE 0
#define PRCM_AVS_VOLTAGE_MASK 0x3f
#define PRCM_AVS_ISSLOWSTARTUP 6
#define PRCM_AVS_ISSLOWSTARTUP_MASK (1 << PRCM_AVS_ISSLOWSTARTUP)
#define PRCM_AVS_ISMODEENABLE 7
#define PRCM_AVS_ISMODEENABLE_MASK (1 << PRCM_AVS_ISMODEENABLE)
#define PRCM_BOOT_STATUS 0xFFF
#define PRCM_ROMCODE_A2P 0xFFE
#define PRCM_ROMCODE_P2A 0xFFD
#define PRCM_XP70_CUR_PWR_STATE 0xFFC /* 4 BYTES */
#define PRCM_SW_RST_REASON 0xFF8 /* 2 bytes */
#define _PRCM_MBOX_HEADER 0xFE8 /* 16 bytes */
#define PRCM_MBOX_HEADER_REQ_MB0 (_PRCM_MBOX_HEADER + 0x0)
#define PRCM_MBOX_HEADER_REQ_MB1 (_PRCM_MBOX_HEADER + 0x1)
#define PRCM_MBOX_HEADER_REQ_MB2 (_PRCM_MBOX_HEADER + 0x2)
#define PRCM_MBOX_HEADER_REQ_MB3 (_PRCM_MBOX_HEADER + 0x3)
#define PRCM_MBOX_HEADER_REQ_MB4 (_PRCM_MBOX_HEADER + 0x4)
#define PRCM_MBOX_HEADER_REQ_MB5 (_PRCM_MBOX_HEADER + 0x5)
#define PRCM_MBOX_HEADER_ACK_MB0 (_PRCM_MBOX_HEADER + 0x8)
/* Req Mailboxes */
#define PRCM_REQ_MB0 0xFDC /* 12 bytes */
#define PRCM_REQ_MB1 0xFD0 /* 12 bytes */
#define PRCM_REQ_MB2 0xFC0 /* 16 bytes */
#define PRCM_REQ_MB3 0xE4C /* 372 bytes */
#define PRCM_REQ_MB4 0xE48 /* 4 bytes */
#define PRCM_REQ_MB5 0xE44 /* 4 bytes */
/* Ack Mailboxes */
#define PRCM_ACK_MB0 0xE08 /* 52 bytes */
#define PRCM_ACK_MB1 0xE04 /* 4 bytes */
#define PRCM_ACK_MB2 0xE00 /* 4 bytes */
#define PRCM_ACK_MB3 0xDFC /* 4 bytes */
#define PRCM_ACK_MB4 0xDF8 /* 4 bytes */
#define PRCM_ACK_MB5 0xDF4 /* 4 bytes */
/* Mailbox 0 headers */
#define MB0H_POWER_STATE_TRANS 0
#define MB0H_CONFIG_WAKEUPS_EXE 1
#define MB0H_READ_WAKEUP_ACK 3
#define MB0H_CONFIG_WAKEUPS_SLEEP 4
#define MB0H_WAKEUP_EXE 2
#define MB0H_WAKEUP_SLEEP 5
/* Mailbox 0 REQs */
#define PRCM_REQ_MB0_AP_POWER_STATE (PRCM_REQ_MB0 + 0x0)
#define PRCM_REQ_MB0_AP_PLL_STATE (PRCM_REQ_MB0 + 0x1)
#define PRCM_REQ_MB0_ULP_CLOCK_STATE (PRCM_REQ_MB0 + 0x2)
#define PRCM_REQ_MB0_DO_NOT_WFI (PRCM_REQ_MB0 + 0x3)
#define PRCM_REQ_MB0_WAKEUP_8500 (PRCM_REQ_MB0 + 0x4)
#define PRCM_REQ_MB0_WAKEUP_4500 (PRCM_REQ_MB0 + 0x8)
/* Mailbox 0 ACKs */
#define PRCM_ACK_MB0_AP_PWRSTTR_STATUS (PRCM_ACK_MB0 + 0x0)
#define PRCM_ACK_MB0_READ_POINTER (PRCM_ACK_MB0 + 0x1)
#define PRCM_ACK_MB0_WAKEUP_0_8500 (PRCM_ACK_MB0 + 0x4)
#define PRCM_ACK_MB0_WAKEUP_0_4500 (PRCM_ACK_MB0 + 0x8)
#define PRCM_ACK_MB0_WAKEUP_1_8500 (PRCM_ACK_MB0 + 0x1C)
#define PRCM_ACK_MB0_WAKEUP_1_4500 (PRCM_ACK_MB0 + 0x20)
#define PRCM_ACK_MB0_EVENT_4500_NUMBERS 20
/* Mailbox 1 headers */
#define MB1H_ARM_APE_OPP 0x0
#define MB1H_RESET_MODEM 0x2
#define MB1H_REQUEST_APE_OPP_100_VOLT 0x3
#define MB1H_RELEASE_APE_OPP_100_VOLT 0x4
#define MB1H_RELEASE_USB_WAKEUP 0x5
#define MB1H_PLL_ON_OFF 0x6
/* Mailbox 1 Requests */
#define PRCM_REQ_MB1_ARM_OPP (PRCM_REQ_MB1 + 0x0)
#define PRCM_REQ_MB1_APE_OPP (PRCM_REQ_MB1 + 0x1)
#define PRCM_REQ_MB1_PLL_ON_OFF (PRCM_REQ_MB1 + 0x4)
#define PLL_SOC0_OFF 0x1
#define PLL_SOC0_ON 0x2
#define PLL_SOC1_OFF 0x4
#define PLL_SOC1_ON 0x8
/* Mailbox 1 ACKs */
#define PRCM_ACK_MB1_CURRENT_ARM_OPP (PRCM_ACK_MB1 + 0x0)
#define PRCM_ACK_MB1_CURRENT_APE_OPP (PRCM_ACK_MB1 + 0x1)
#define PRCM_ACK_MB1_APE_VOLTAGE_STATUS (PRCM_ACK_MB1 + 0x2)
#define PRCM_ACK_MB1_DVFS_STATUS (PRCM_ACK_MB1 + 0x3)
/* Mailbox 2 headers */
#define MB2H_DPS 0x0
#define MB2H_AUTO_PWR 0x1
/* Mailbox 2 REQs */
#define PRCM_REQ_MB2_SVA_MMDSP (PRCM_REQ_MB2 + 0x0)
#define PRCM_REQ_MB2_SVA_PIPE (PRCM_REQ_MB2 + 0x1)
#define PRCM_REQ_MB2_SIA_MMDSP (PRCM_REQ_MB2 + 0x2)
#define PRCM_REQ_MB2_SIA_PIPE (PRCM_REQ_MB2 + 0x3)
#define PRCM_REQ_MB2_SGA (PRCM_REQ_MB2 + 0x4)
#define PRCM_REQ_MB2_B2R2_MCDE (PRCM_REQ_MB2 + 0x5)
#define PRCM_REQ_MB2_ESRAM12 (PRCM_REQ_MB2 + 0x6)
#define PRCM_REQ_MB2_ESRAM34 (PRCM_REQ_MB2 + 0x7)
#define PRCM_REQ_MB2_AUTO_PM_SLEEP (PRCM_REQ_MB2 + 0x8)
#define PRCM_REQ_MB2_AUTO_PM_IDLE (PRCM_REQ_MB2 + 0xC)
/* Mailbox 2 ACKs */
#define PRCM_ACK_MB2_DPS_STATUS (PRCM_ACK_MB2 + 0x0)
#define HWACC_PWR_ST_OK 0xFE
/* Mailbox 3 headers */
#define MB3H_ANC 0x0
#define MB3H_SIDETONE 0x1
#define MB3H_SYSCLK 0xE
/* Mailbox 3 Requests */
#define PRCM_REQ_MB3_ANC_FIR_COEFF (PRCM_REQ_MB3 + 0x0)
#define PRCM_REQ_MB3_ANC_IIR_COEFF (PRCM_REQ_MB3 + 0x20)
#define PRCM_REQ_MB3_ANC_SHIFTER (PRCM_REQ_MB3 + 0x60)
#define PRCM_REQ_MB3_ANC_WARP (PRCM_REQ_MB3 + 0x64)
#define PRCM_REQ_MB3_SIDETONE_FIR_GAIN (PRCM_REQ_MB3 + 0x68)
#define PRCM_REQ_MB3_SIDETONE_FIR_COEFF (PRCM_REQ_MB3 + 0x6C)
#define PRCM_REQ_MB3_SYSCLK_MGT (PRCM_REQ_MB3 + 0x16C)
/* Mailbox 4 headers */
#define MB4H_DDR_INIT 0x0
#define MB4H_MEM_ST 0x1
#define MB4H_HOTDOG 0x12
#define MB4H_HOTMON 0x13
#define MB4H_HOT_PERIOD 0x14
#define MB4H_A9WDOG_CONF 0x16
#define MB4H_A9WDOG_EN 0x17
#define MB4H_A9WDOG_DIS 0x18
#define MB4H_A9WDOG_LOAD 0x19
#define MB4H_A9WDOG_KICK 0x20
/* Mailbox 4 Requests */
#define PRCM_REQ_MB4_DDR_ST_AP_SLEEP_IDLE (PRCM_REQ_MB4 + 0x0)
#define PRCM_REQ_MB4_DDR_ST_AP_DEEP_IDLE (PRCM_REQ_MB4 + 0x1)
#define PRCM_REQ_MB4_ESRAM0_ST (PRCM_REQ_MB4 + 0x3)
#define PRCM_REQ_MB4_HOTDOG_THRESHOLD (PRCM_REQ_MB4 + 0x0)
#define PRCM_REQ_MB4_HOTMON_LOW (PRCM_REQ_MB4 + 0x0)
#define PRCM_REQ_MB4_HOTMON_HIGH (PRCM_REQ_MB4 + 0x1)
#define PRCM_REQ_MB4_HOTMON_CONFIG (PRCM_REQ_MB4 + 0x2)
#define PRCM_REQ_MB4_HOT_PERIOD (PRCM_REQ_MB4 + 0x0)
#define HOTMON_CONFIG_LOW BIT(0)
#define HOTMON_CONFIG_HIGH BIT(1)
#define PRCM_REQ_MB4_A9WDOG_0 (PRCM_REQ_MB4 + 0x0)
#define PRCM_REQ_MB4_A9WDOG_1 (PRCM_REQ_MB4 + 0x1)
#define PRCM_REQ_MB4_A9WDOG_2 (PRCM_REQ_MB4 + 0x2)
#define PRCM_REQ_MB4_A9WDOG_3 (PRCM_REQ_MB4 + 0x3)
#define A9WDOG_AUTO_OFF_EN BIT(7)
#define A9WDOG_AUTO_OFF_DIS 0
#define A9WDOG_ID_MASK 0xf
/* Mailbox 5 Requests */
#define PRCM_REQ_MB5_I2C_SLAVE_OP (PRCM_REQ_MB5 + 0x0)
#define PRCM_REQ_MB5_I2C_HW_BITS (PRCM_REQ_MB5 + 0x1)
#define PRCM_REQ_MB5_I2C_REG (PRCM_REQ_MB5 + 0x2)
#define PRCM_REQ_MB5_I2C_VAL (PRCM_REQ_MB5 + 0x3)
#define PRCMU_I2C_WRITE(slave) (((slave) << 1) | BIT(6))
#define PRCMU_I2C_READ(slave) (((slave) << 1) | BIT(0) | BIT(6))
#define PRCMU_I2C_STOP_EN BIT(3)
/* Mailbox 5 ACKs */
#define PRCM_ACK_MB5_I2C_STATUS (PRCM_ACK_MB5 + 0x1)
#define PRCM_ACK_MB5_I2C_VAL (PRCM_ACK_MB5 + 0x3)
#define I2C_WR_OK 0x1
#define I2C_RD_OK 0x2
#define NUM_MB 8
#define MBOX_BIT BIT
#define ALL_MBOX_BITS (MBOX_BIT(NUM_MB) - 1)
/*
* Wakeups/IRQs
*/
#define WAKEUP_BIT_RTC BIT(0)
#define WAKEUP_BIT_RTT0 BIT(1)
#define WAKEUP_BIT_RTT1 BIT(2)
#define WAKEUP_BIT_HSI0 BIT(3)
#define WAKEUP_BIT_HSI1 BIT(4)
#define WAKEUP_BIT_CA_WAKE BIT(5)
#define WAKEUP_BIT_USB BIT(6)
#define WAKEUP_BIT_ABB BIT(7)
#define WAKEUP_BIT_ABB_FIFO BIT(8)
#define WAKEUP_BIT_SYSCLK_OK BIT(9)
#define WAKEUP_BIT_CA_SLEEP BIT(10)
#define WAKEUP_BIT_AC_WAKE_ACK BIT(11)
#define WAKEUP_BIT_SIDE_TONE_OK BIT(12)
#define WAKEUP_BIT_ANC_OK BIT(13)
#define WAKEUP_BIT_SW_ERROR BIT(14)
#define WAKEUP_BIT_AC_SLEEP_ACK BIT(15)
#define WAKEUP_BIT_ARM BIT(17)
#define WAKEUP_BIT_HOTMON_LOW BIT(18)
#define WAKEUP_BIT_HOTMON_HIGH BIT(19)
#define WAKEUP_BIT_MODEM_SW_RESET_REQ BIT(20)
#define WAKEUP_BIT_GPIO0 BIT(23)
#define WAKEUP_BIT_GPIO1 BIT(24)
#define WAKEUP_BIT_GPIO2 BIT(25)
#define WAKEUP_BIT_GPIO3 BIT(26)
#define WAKEUP_BIT_GPIO4 BIT(27)
#define WAKEUP_BIT_GPIO5 BIT(28)
#define WAKEUP_BIT_GPIO6 BIT(29)
#define WAKEUP_BIT_GPIO7 BIT(30)
#define WAKEUP_BIT_GPIO8 BIT(31)
static struct {
bool valid;
struct prcmu_fw_version version;
} fw_info;
static struct irq_domain *db8500_irq_domain;
/*
* This vector maps irq numbers to the bits in the bit field used in
* communication with the PRCMU firmware.
*
* The reason for having this is to keep the irq numbers contiguous even though
* the bits in the bit field are not. (The bits also have a tendency to move
* around, to further complicate matters.)
*/
#define IRQ_INDEX(_name) ((IRQ_PRCMU_##_name))
#define IRQ_ENTRY(_name)[IRQ_INDEX(_name)] = (WAKEUP_BIT_##_name)
#define IRQ_PRCMU_RTC 0
#define IRQ_PRCMU_RTT0 1
#define IRQ_PRCMU_RTT1 2
#define IRQ_PRCMU_HSI0 3
#define IRQ_PRCMU_HSI1 4
#define IRQ_PRCMU_CA_WAKE 5
#define IRQ_PRCMU_USB 6
#define IRQ_PRCMU_ABB 7
#define IRQ_PRCMU_ABB_FIFO 8
#define IRQ_PRCMU_ARM 9
#define IRQ_PRCMU_MODEM_SW_RESET_REQ 10
#define IRQ_PRCMU_GPIO0 11
#define IRQ_PRCMU_GPIO1 12
#define IRQ_PRCMU_GPIO2 13
#define IRQ_PRCMU_GPIO3 14
#define IRQ_PRCMU_GPIO4 15
#define IRQ_PRCMU_GPIO5 16
#define IRQ_PRCMU_GPIO6 17
#define IRQ_PRCMU_GPIO7 18
#define IRQ_PRCMU_GPIO8 19
#define IRQ_PRCMU_CA_SLEEP 20
#define IRQ_PRCMU_HOTMON_LOW 21
#define IRQ_PRCMU_HOTMON_HIGH 22
#define NUM_PRCMU_WAKEUPS 23
static u32 prcmu_irq_bit[NUM_PRCMU_WAKEUPS] = {
IRQ_ENTRY(RTC),
IRQ_ENTRY(RTT0),
IRQ_ENTRY(RTT1),
IRQ_ENTRY(HSI0),
IRQ_ENTRY(HSI1),
IRQ_ENTRY(CA_WAKE),
IRQ_ENTRY(USB),
IRQ_ENTRY(ABB),
IRQ_ENTRY(ABB_FIFO),
IRQ_ENTRY(CA_SLEEP),
IRQ_ENTRY(ARM),
IRQ_ENTRY(HOTMON_LOW),
IRQ_ENTRY(HOTMON_HIGH),
IRQ_ENTRY(MODEM_SW_RESET_REQ),
IRQ_ENTRY(GPIO0),
IRQ_ENTRY(GPIO1),
IRQ_ENTRY(GPIO2),
IRQ_ENTRY(GPIO3),
IRQ_ENTRY(GPIO4),
IRQ_ENTRY(GPIO5),
IRQ_ENTRY(GPIO6),
IRQ_ENTRY(GPIO7),
IRQ_ENTRY(GPIO8)
};
#define VALID_WAKEUPS (BIT(NUM_PRCMU_WAKEUP_INDICES) - 1)
#define WAKEUP_ENTRY(_name)[PRCMU_WAKEUP_INDEX_##_name] = (WAKEUP_BIT_##_name)
static u32 prcmu_wakeup_bit[NUM_PRCMU_WAKEUP_INDICES] = {
WAKEUP_ENTRY(RTC),
WAKEUP_ENTRY(RTT0),
WAKEUP_ENTRY(RTT1),
WAKEUP_ENTRY(HSI0),
WAKEUP_ENTRY(HSI1),
WAKEUP_ENTRY(USB),
WAKEUP_ENTRY(ABB),
WAKEUP_ENTRY(ABB_FIFO),
WAKEUP_ENTRY(ARM)
};
/*
* mb0_transfer - state needed for mailbox 0 communication.
* @lock: The transaction lock.
* @dbb_events_lock: A lock used to handle concurrent access to (parts of)
* the request data.
* @mask_work: Work structure used for (un)masking wakeup interrupts.
* @req: Request data that need to persist between requests.
*/
static struct {
spinlock_t lock;
spinlock_t dbb_irqs_lock;
struct work_struct mask_work;
struct mutex ac_wake_lock;
struct completion ac_wake_work;
struct {
u32 dbb_irqs;
u32 dbb_wakeups;
u32 abb_events;
} req;
} mb0_transfer;
/*
* mb1_transfer - state needed for mailbox 1 communication.
* @lock: The transaction lock.
* @work: The transaction completion structure.
* @ape_opp: The current APE OPP.
* @ack: Reply ("acknowledge") data.
*/
static struct {
struct mutex lock;
struct completion work;
u8 ape_opp;
struct {
u8 header;
u8 arm_opp;
u8 ape_opp;
u8 ape_voltage_status;
} ack;
} mb1_transfer;
/*
* mb2_transfer - state needed for mailbox 2 communication.
* @lock: The transaction lock.
* @work: The transaction completion structure.
* @auto_pm_lock: The autonomous power management configuration lock.
* @auto_pm_enabled: A flag indicating whether autonomous PM is enabled.
* @req: Request data that need to persist between requests.
* @ack: Reply ("acknowledge") data.
*/
static struct {
struct mutex lock;
struct completion work;
spinlock_t auto_pm_lock;
bool auto_pm_enabled;
struct {
u8 status;
} ack;
} mb2_transfer;
/*
* mb3_transfer - state needed for mailbox 3 communication.
* @lock: The request lock.
* @sysclk_lock: A lock used to handle concurrent sysclk requests.
* @sysclk_work: Work structure used for sysclk requests.
*/
static struct {
spinlock_t lock;
struct mutex sysclk_lock;
struct completion sysclk_work;
} mb3_transfer;
/*
* mb4_transfer - state needed for mailbox 4 communication.
* @lock: The transaction lock.
* @work: The transaction completion structure.
*/
static struct {
struct mutex lock;
struct completion work;
} mb4_transfer;
/*
* mb5_transfer - state needed for mailbox 5 communication.
* @lock: The transaction lock.
* @work: The transaction completion structure.
* @ack: Reply ("acknowledge") data.
*/
static struct {
struct mutex lock;
struct completion work;
struct {
u8 status;
u8 value;
} ack;
} mb5_transfer;
static atomic_t ac_wake_req_state = ATOMIC_INIT(0);
/* Spinlocks */
static DEFINE_SPINLOCK(prcmu_lock);
static DEFINE_SPINLOCK(clkout_lock);
/* Global var to runtime determine TCDM base for v2 or v1 */
static __iomem void *tcdm_base;
static __iomem void *prcmu_base;
struct clk_mgt {
u32 offset;
u32 pllsw;
int branch;
bool clk38div;
};
enum {
PLL_RAW,
PLL_FIX,
PLL_DIV
};
static DEFINE_SPINLOCK(clk_mgt_lock);
#define CLK_MGT_ENTRY(_name, _branch, _clk38div)[PRCMU_##_name] = \
{ (PRCM_##_name##_MGT), 0 , _branch, _clk38div}
struct clk_mgt clk_mgt[PRCMU_NUM_REG_CLOCKS] = {
CLK_MGT_ENTRY(SGACLK, PLL_DIV, false),
CLK_MGT_ENTRY(UARTCLK, PLL_FIX, true),
CLK_MGT_ENTRY(MSP02CLK, PLL_FIX, true),
CLK_MGT_ENTRY(MSP1CLK, PLL_FIX, true),
CLK_MGT_ENTRY(I2CCLK, PLL_FIX, true),
CLK_MGT_ENTRY(SDMMCCLK, PLL_DIV, true),
CLK_MGT_ENTRY(SLIMCLK, PLL_FIX, true),
CLK_MGT_ENTRY(PER1CLK, PLL_DIV, true),
CLK_MGT_ENTRY(PER2CLK, PLL_DIV, true),
CLK_MGT_ENTRY(PER3CLK, PLL_DIV, true),
CLK_MGT_ENTRY(PER5CLK, PLL_DIV, true),
CLK_MGT_ENTRY(PER6CLK, PLL_DIV, true),
CLK_MGT_ENTRY(PER7CLK, PLL_DIV, true),
CLK_MGT_ENTRY(LCDCLK, PLL_FIX, true),
CLK_MGT_ENTRY(BMLCLK, PLL_DIV, true),
CLK_MGT_ENTRY(HSITXCLK, PLL_DIV, true),
CLK_MGT_ENTRY(HSIRXCLK, PLL_DIV, true),
CLK_MGT_ENTRY(HDMICLK, PLL_FIX, false),
CLK_MGT_ENTRY(APEATCLK, PLL_DIV, true),
CLK_MGT_ENTRY(APETRACECLK, PLL_DIV, true),
CLK_MGT_ENTRY(MCDECLK, PLL_DIV, true),
CLK_MGT_ENTRY(IPI2CCLK, PLL_FIX, true),
CLK_MGT_ENTRY(DSIALTCLK, PLL_FIX, false),
CLK_MGT_ENTRY(DMACLK, PLL_DIV, true),
CLK_MGT_ENTRY(B2R2CLK, PLL_DIV, true),
CLK_MGT_ENTRY(TVCLK, PLL_FIX, true),
CLK_MGT_ENTRY(SSPCLK, PLL_FIX, true),
CLK_MGT_ENTRY(RNGCLK, PLL_FIX, true),
CLK_MGT_ENTRY(UICCCLK, PLL_FIX, false),
};
struct dsiclk {
u32 divsel_mask;
u32 divsel_shift;
u32 divsel;
};
static struct dsiclk dsiclk[2] = {
{
.divsel_mask = PRCM_DSI_PLLOUT_SEL_DSI0_PLLOUT_DIVSEL_MASK,
.divsel_shift = PRCM_DSI_PLLOUT_SEL_DSI0_PLLOUT_DIVSEL_SHIFT,
.divsel = PRCM_DSI_PLLOUT_SEL_PHI,
},
{
.divsel_mask = PRCM_DSI_PLLOUT_SEL_DSI1_PLLOUT_DIVSEL_MASK,
.divsel_shift = PRCM_DSI_PLLOUT_SEL_DSI1_PLLOUT_DIVSEL_SHIFT,
.divsel = PRCM_DSI_PLLOUT_SEL_PHI,
}
};
struct dsiescclk {
u32 en;
u32 div_mask;
u32 div_shift;
};
static struct dsiescclk dsiescclk[3] = {
{
.en = PRCM_DSITVCLK_DIV_DSI0_ESC_CLK_EN,
.div_mask = PRCM_DSITVCLK_DIV_DSI0_ESC_CLK_DIV_MASK,
.div_shift = PRCM_DSITVCLK_DIV_DSI0_ESC_CLK_DIV_SHIFT,
},
{
.en = PRCM_DSITVCLK_DIV_DSI1_ESC_CLK_EN,
.div_mask = PRCM_DSITVCLK_DIV_DSI1_ESC_CLK_DIV_MASK,
.div_shift = PRCM_DSITVCLK_DIV_DSI1_ESC_CLK_DIV_SHIFT,
},
{
.en = PRCM_DSITVCLK_DIV_DSI2_ESC_CLK_EN,
.div_mask = PRCM_DSITVCLK_DIV_DSI2_ESC_CLK_DIV_MASK,
.div_shift = PRCM_DSITVCLK_DIV_DSI2_ESC_CLK_DIV_SHIFT,
}
};
/*
* Used by MCDE to setup all necessary PRCMU registers
*/
#define PRCMU_RESET_DSIPLL 0x00004000
#define PRCMU_UNCLAMP_DSIPLL 0x00400800
#define PRCMU_CLK_PLL_DIV_SHIFT 0
#define PRCMU_CLK_PLL_SW_SHIFT 5
#define PRCMU_CLK_38 (1 << 9)
#define PRCMU_CLK_38_SRC (1 << 10)
#define PRCMU_CLK_38_DIV (1 << 11)
/* PLLDIV=12, PLLSW=4 (PLLDDR) */
#define PRCMU_DSI_CLOCK_SETTING 0x0000008C
/* DPI 50000000 Hz */
#define PRCMU_DPI_CLOCK_SETTING ((1 << PRCMU_CLK_PLL_SW_SHIFT) | \
(16 << PRCMU_CLK_PLL_DIV_SHIFT))
#define PRCMU_DSI_LP_CLOCK_SETTING 0x00000E00
/* D=101, N=1, R=4, SELDIV2=0 */
#define PRCMU_PLLDSI_FREQ_SETTING 0x00040165
#define PRCMU_ENABLE_PLLDSI 0x00000001
#define PRCMU_DISABLE_PLLDSI 0x00000000
#define PRCMU_RELEASE_RESET_DSS 0x0000400C
#define PRCMU_DSI_PLLOUT_SEL_SETTING 0x00000202
/* ESC clk, div0=1, div1=1, div2=3 */
#define PRCMU_ENABLE_ESCAPE_CLOCK_DIV 0x07030101
#define PRCMU_DISABLE_ESCAPE_CLOCK_DIV 0x00030101
#define PRCMU_DSI_RESET_SW 0x00000007
#define PRCMU_PLLDSI_LOCKP_LOCKED 0x3
int db8500_prcmu_enable_dsipll(void)
{
int i;
/* Clear DSIPLL_RESETN */
writel(PRCMU_RESET_DSIPLL, PRCM_APE_RESETN_CLR);
/* Unclamp DSIPLL in/out */
writel(PRCMU_UNCLAMP_DSIPLL, PRCM_MMIP_LS_CLAMP_CLR);
/* Set DSI PLL FREQ */
writel(PRCMU_PLLDSI_FREQ_SETTING, PRCM_PLLDSI_FREQ);
writel(PRCMU_DSI_PLLOUT_SEL_SETTING, PRCM_DSI_PLLOUT_SEL);
/* Enable Escape clocks */
writel(PRCMU_ENABLE_ESCAPE_CLOCK_DIV, PRCM_DSITVCLK_DIV);
/* Start DSI PLL */
writel(PRCMU_ENABLE_PLLDSI, PRCM_PLLDSI_ENABLE);
/* Reset DSI PLL */
writel(PRCMU_DSI_RESET_SW, PRCM_DSI_SW_RESET);
for (i = 0; i < 10; i++) {
if ((readl(PRCM_PLLDSI_LOCKP) & PRCMU_PLLDSI_LOCKP_LOCKED)
== PRCMU_PLLDSI_LOCKP_LOCKED)
break;
udelay(100);
}
/* Set DSIPLL_RESETN */
writel(PRCMU_RESET_DSIPLL, PRCM_APE_RESETN_SET);
return 0;
}
int db8500_prcmu_disable_dsipll(void)
{
/* Disable dsi pll */
writel(PRCMU_DISABLE_PLLDSI, PRCM_PLLDSI_ENABLE);
/* Disable escapeclock */
writel(PRCMU_DISABLE_ESCAPE_CLOCK_DIV, PRCM_DSITVCLK_DIV);
return 0;
}
int db8500_prcmu_set_display_clocks(void)
{
unsigned long flags;
spin_lock_irqsave(&clk_mgt_lock, flags);
/* Grab the HW semaphore. */
while ((readl(PRCM_SEM) & PRCM_SEM_PRCM_SEM) != 0)
cpu_relax();
writel(PRCMU_DSI_CLOCK_SETTING, prcmu_base + PRCM_HDMICLK_MGT);
writel(PRCMU_DSI_LP_CLOCK_SETTING, prcmu_base + PRCM_TVCLK_MGT);
writel(PRCMU_DPI_CLOCK_SETTING, prcmu_base + PRCM_LCDCLK_MGT);
/* Release the HW semaphore. */
writel(0, PRCM_SEM);
spin_unlock_irqrestore(&clk_mgt_lock, flags);
return 0;
}
u32 db8500_prcmu_read(unsigned int reg)
{
return readl(prcmu_base + reg);
}
void db8500_prcmu_write(unsigned int reg, u32 value)
{
unsigned long flags;
spin_lock_irqsave(&prcmu_lock, flags);
writel(value, (prcmu_base + reg));
spin_unlock_irqrestore(&prcmu_lock, flags);
}
void db8500_prcmu_write_masked(unsigned int reg, u32 mask, u32 value)
{
u32 val;
unsigned long flags;
spin_lock_irqsave(&prcmu_lock, flags);
val = readl(prcmu_base + reg);
val = ((val & ~mask) | (value & mask));
writel(val, (prcmu_base + reg));
spin_unlock_irqrestore(&prcmu_lock, flags);
}
struct prcmu_fw_version *prcmu_get_fw_version(void)
{
return fw_info.valid ? &fw_info.version : NULL;
}
bool prcmu_has_arm_maxopp(void)
{
return (readb(tcdm_base + PRCM_AVS_VARM_MAX_OPP) &
PRCM_AVS_ISMODEENABLE_MASK) == PRCM_AVS_ISMODEENABLE_MASK;
}
/**
* prcmu_get_boot_status - PRCMU boot status checking
* Returns: the current PRCMU boot status
*/
int prcmu_get_boot_status(void)
{
return readb(tcdm_base + PRCM_BOOT_STATUS);
}
/**
* prcmu_set_rc_a2p - This function is used to run few power state sequences
* @val: Value to be set, i.e. transition requested
* Returns: 0 on success, -EINVAL on invalid argument
*
* This function is used to run the following power state sequences -
* any state to ApReset, ApDeepSleep to ApExecute, ApExecute to ApDeepSleep
*/
int prcmu_set_rc_a2p(enum romcode_write val)
{
if (val < RDY_2_DS || val > RDY_2_XP70_RST)
return -EINVAL;
writeb(val, (tcdm_base + PRCM_ROMCODE_A2P));
return 0;
}
/**
* prcmu_get_rc_p2a - This function is used to get power state sequences
* Returns: the power transition that has last happened
*
* This function can return the following transitions-
* any state to ApReset, ApDeepSleep to ApExecute, ApExecute to ApDeepSleep
*/
enum romcode_read prcmu_get_rc_p2a(void)
{
return readb(tcdm_base + PRCM_ROMCODE_P2A);
}
/**
* prcmu_get_current_mode - Return the current XP70 power mode
* Returns: Returns the current AP(ARM) power mode: init,
* apBoot, apExecute, apDeepSleep, apSleep, apIdle, apReset
*/
enum ap_pwrst prcmu_get_xp70_current_state(void)
{
return readb(tcdm_base + PRCM_XP70_CUR_PWR_STATE);
}
/**
* prcmu_config_clkout - Configure one of the programmable clock outputs.
* @clkout: The CLKOUT number (0 or 1).
* @source: The clock to be used (one of the PRCMU_CLKSRC_*).
* @div: The divider to be applied.
*
* Configures one of the programmable clock outputs (CLKOUTs).
* @div should be in the range [1,63] to request a configuration, or 0 to
* inform that the configuration is no longer requested.
*/
int prcmu_config_clkout(u8 clkout, u8 source, u8 div)
{
static int requests[2];
int r = 0;
unsigned long flags;
u32 val;
u32 bits;
u32 mask;
u32 div_mask;
BUG_ON(clkout > 1);
BUG_ON(div > 63);
BUG_ON((clkout == 0) && (source > PRCMU_CLKSRC_CLK009));
if (!div && !requests[clkout])
return -EINVAL;
switch (clkout) {
case 0:
div_mask = PRCM_CLKOCR_CLKODIV0_MASK;
mask = (PRCM_CLKOCR_CLKODIV0_MASK | PRCM_CLKOCR_CLKOSEL0_MASK);
bits = ((source << PRCM_CLKOCR_CLKOSEL0_SHIFT) |
(div << PRCM_CLKOCR_CLKODIV0_SHIFT));
break;
case 1:
div_mask = PRCM_CLKOCR_CLKODIV1_MASK;
mask = (PRCM_CLKOCR_CLKODIV1_MASK | PRCM_CLKOCR_CLKOSEL1_MASK |
PRCM_CLKOCR_CLK1TYPE);
bits = ((source << PRCM_CLKOCR_CLKOSEL1_SHIFT) |
(div << PRCM_CLKOCR_CLKODIV1_SHIFT));
break;
}
bits &= mask;
spin_lock_irqsave(&clkout_lock, flags);
val = readl(PRCM_CLKOCR);
if (val & div_mask) {
if (div) {
if ((val & mask) != bits) {
r = -EBUSY;
goto unlock_and_return;
}
} else {
if ((val & mask & ~div_mask) != bits) {
r = -EINVAL;
goto unlock_and_return;
}
}
}
writel((bits | (val & ~mask)), PRCM_CLKOCR);
requests[clkout] += (div ? 1 : -1);
unlock_and_return:
spin_unlock_irqrestore(&clkout_lock, flags);
return r;
}
int db8500_prcmu_set_power_state(u8 state, bool keep_ulp_clk, bool keep_ap_pll)
{
unsigned long flags;
BUG_ON((state < PRCMU_AP_SLEEP) || (PRCMU_AP_DEEP_IDLE < state));
spin_lock_irqsave(&mb0_transfer.lock, flags);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(0))
cpu_relax();
writeb(MB0H_POWER_STATE_TRANS, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB0));
writeb(state, (tcdm_base + PRCM_REQ_MB0_AP_POWER_STATE));
writeb((keep_ap_pll ? 1 : 0), (tcdm_base + PRCM_REQ_MB0_AP_PLL_STATE));
writeb((keep_ulp_clk ? 1 : 0),
(tcdm_base + PRCM_REQ_MB0_ULP_CLOCK_STATE));
writeb(0, (tcdm_base + PRCM_REQ_MB0_DO_NOT_WFI));
writel(MBOX_BIT(0), PRCM_MBOX_CPU_SET);
spin_unlock_irqrestore(&mb0_transfer.lock, flags);
return 0;
}
u8 db8500_prcmu_get_power_state_result(void)
{
return readb(tcdm_base + PRCM_ACK_MB0_AP_PWRSTTR_STATUS);
}
/* This function should only be called while mb0_transfer.lock is held. */
static void config_wakeups(void)
{
const u8 header[2] = {
MB0H_CONFIG_WAKEUPS_EXE,
MB0H_CONFIG_WAKEUPS_SLEEP
};
static u32 last_dbb_events;
static u32 last_abb_events;
u32 dbb_events;
u32 abb_events;
unsigned int i;
dbb_events = mb0_transfer.req.dbb_irqs | mb0_transfer.req.dbb_wakeups;
dbb_events |= (WAKEUP_BIT_AC_WAKE_ACK | WAKEUP_BIT_AC_SLEEP_ACK);
abb_events = mb0_transfer.req.abb_events;
if ((dbb_events == last_dbb_events) && (abb_events == last_abb_events))
return;
for (i = 0; i < 2; i++) {
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(0))
cpu_relax();
writel(dbb_events, (tcdm_base + PRCM_REQ_MB0_WAKEUP_8500));
writel(abb_events, (tcdm_base + PRCM_REQ_MB0_WAKEUP_4500));
writeb(header[i], (tcdm_base + PRCM_MBOX_HEADER_REQ_MB0));
writel(MBOX_BIT(0), PRCM_MBOX_CPU_SET);
}
last_dbb_events = dbb_events;
last_abb_events = abb_events;
}
void db8500_prcmu_enable_wakeups(u32 wakeups)
{
unsigned long flags;
u32 bits;
int i;
BUG_ON(wakeups != (wakeups & VALID_WAKEUPS));
for (i = 0, bits = 0; i < NUM_PRCMU_WAKEUP_INDICES; i++) {
if (wakeups & BIT(i))
bits |= prcmu_wakeup_bit[i];
}
spin_lock_irqsave(&mb0_transfer.lock, flags);
mb0_transfer.req.dbb_wakeups = bits;
config_wakeups();
spin_unlock_irqrestore(&mb0_transfer.lock, flags);
}
void db8500_prcmu_config_abb_event_readout(u32 abb_events)
{
unsigned long flags;
spin_lock_irqsave(&mb0_transfer.lock, flags);
mb0_transfer.req.abb_events = abb_events;
config_wakeups();
spin_unlock_irqrestore(&mb0_transfer.lock, flags);
}
void db8500_prcmu_get_abb_event_buffer(void __iomem **buf)
{
if (readb(tcdm_base + PRCM_ACK_MB0_READ_POINTER) & 1)
*buf = (tcdm_base + PRCM_ACK_MB0_WAKEUP_1_4500);
else
*buf = (tcdm_base + PRCM_ACK_MB0_WAKEUP_0_4500);
}
/**
* db8500_prcmu_set_arm_opp - set the appropriate ARM OPP
* @opp: The new ARM operating point to which transition is to be made
* Returns: 0 on success, non-zero on failure
*
* This function sets the the operating point of the ARM.
*/
int db8500_prcmu_set_arm_opp(u8 opp)
{
int r;
if (opp < ARM_NO_CHANGE || opp > ARM_EXTCLK)
return -EINVAL;
r = 0;
mutex_lock(&mb1_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(1))
cpu_relax();
writeb(MB1H_ARM_APE_OPP, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB1));
writeb(opp, (tcdm_base + PRCM_REQ_MB1_ARM_OPP));
writeb(APE_NO_CHANGE, (tcdm_base + PRCM_REQ_MB1_APE_OPP));
writel(MBOX_BIT(1), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb1_transfer.work);
if ((mb1_transfer.ack.header != MB1H_ARM_APE_OPP) ||
(mb1_transfer.ack.arm_opp != opp))
r = -EIO;
mutex_unlock(&mb1_transfer.lock);
return r;
}
/**
* db8500_prcmu_get_arm_opp - get the current ARM OPP
*
* Returns: the current ARM OPP
*/
int db8500_prcmu_get_arm_opp(void)
{
return readb(tcdm_base + PRCM_ACK_MB1_CURRENT_ARM_OPP);
}
/**
* db8500_prcmu_get_ddr_opp - get the current DDR OPP
*
* Returns: the current DDR OPP
*/
int db8500_prcmu_get_ddr_opp(void)
{
return readb(PRCM_DDR_SUBSYS_APE_MINBW);
}
/**
* db8500_set_ddr_opp - set the appropriate DDR OPP
* @opp: The new DDR operating point to which transition is to be made
* Returns: 0 on success, non-zero on failure
*
* This function sets the operating point of the DDR.
*/
static bool enable_set_ddr_opp;
int db8500_prcmu_set_ddr_opp(u8 opp)
{
if (opp < DDR_100_OPP || opp > DDR_25_OPP)
return -EINVAL;
/* Changing the DDR OPP can hang the hardware pre-v21 */
if (enable_set_ddr_opp)
writeb(opp, PRCM_DDR_SUBSYS_APE_MINBW);
return 0;
}
/* Divide the frequency of certain clocks by 2 for APE_50_PARTLY_25_OPP. */
static void request_even_slower_clocks(bool enable)
{
u32 clock_reg[] = {
PRCM_ACLK_MGT,
PRCM_DMACLK_MGT
};
unsigned long flags;
unsigned int i;
spin_lock_irqsave(&clk_mgt_lock, flags);
/* Grab the HW semaphore. */
while ((readl(PRCM_SEM) & PRCM_SEM_PRCM_SEM) != 0)
cpu_relax();
for (i = 0; i < ARRAY_SIZE(clock_reg); i++) {
u32 val;
u32 div;
val = readl(prcmu_base + clock_reg[i]);
div = (val & PRCM_CLK_MGT_CLKPLLDIV_MASK);
if (enable) {
if ((div <= 1) || (div > 15)) {
pr_err("prcmu: Bad clock divider %d in %s\n",
div, __func__);
goto unlock_and_return;
}
div <<= 1;
} else {
if (div <= 2)
goto unlock_and_return;
div >>= 1;
}
val = ((val & ~PRCM_CLK_MGT_CLKPLLDIV_MASK) |
(div & PRCM_CLK_MGT_CLKPLLDIV_MASK));
writel(val, prcmu_base + clock_reg[i]);
}
unlock_and_return:
/* Release the HW semaphore. */
writel(0, PRCM_SEM);
spin_unlock_irqrestore(&clk_mgt_lock, flags);
}
/**
* db8500_set_ape_opp - set the appropriate APE OPP
* @opp: The new APE operating point to which transition is to be made
* Returns: 0 on success, non-zero on failure
*
* This function sets the operating point of the APE.
*/
int db8500_prcmu_set_ape_opp(u8 opp)
{
int r = 0;
if (opp == mb1_transfer.ape_opp)
return 0;
mutex_lock(&mb1_transfer.lock);
if (mb1_transfer.ape_opp == APE_50_PARTLY_25_OPP)
request_even_slower_clocks(false);
if ((opp != APE_100_OPP) && (mb1_transfer.ape_opp != APE_100_OPP))
goto skip_message;
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(1))
cpu_relax();
writeb(MB1H_ARM_APE_OPP, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB1));
writeb(ARM_NO_CHANGE, (tcdm_base + PRCM_REQ_MB1_ARM_OPP));
writeb(((opp == APE_50_PARTLY_25_OPP) ? APE_50_OPP : opp),
(tcdm_base + PRCM_REQ_MB1_APE_OPP));
writel(MBOX_BIT(1), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb1_transfer.work);
if ((mb1_transfer.ack.header != MB1H_ARM_APE_OPP) ||
(mb1_transfer.ack.ape_opp != opp))
r = -EIO;
skip_message:
if ((!r && (opp == APE_50_PARTLY_25_OPP)) ||
(r && (mb1_transfer.ape_opp == APE_50_PARTLY_25_OPP)))
request_even_slower_clocks(true);
if (!r)
mb1_transfer.ape_opp = opp;
mutex_unlock(&mb1_transfer.lock);
return r;
}
/**
* db8500_prcmu_get_ape_opp - get the current APE OPP
*
* Returns: the current APE OPP
*/
int db8500_prcmu_get_ape_opp(void)
{
return readb(tcdm_base + PRCM_ACK_MB1_CURRENT_APE_OPP);
}
/**
* db8500_prcmu_request_ape_opp_100_voltage - Request APE OPP 100% voltage
* @enable: true to request the higher voltage, false to drop a request.
*
* Calls to this function to enable and disable requests must be balanced.
*/
int db8500_prcmu_request_ape_opp_100_voltage(bool enable)
{
int r = 0;
u8 header;
static unsigned int requests;
mutex_lock(&mb1_transfer.lock);
if (enable) {
if (0 != requests++)
goto unlock_and_return;
header = MB1H_REQUEST_APE_OPP_100_VOLT;
} else {
if (requests == 0) {
r = -EIO;
goto unlock_and_return;
} else if (1 != requests--) {
goto unlock_and_return;
}
header = MB1H_RELEASE_APE_OPP_100_VOLT;
}
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(1))
cpu_relax();
writeb(header, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB1));
writel(MBOX_BIT(1), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb1_transfer.work);
if ((mb1_transfer.ack.header != header) ||
((mb1_transfer.ack.ape_voltage_status & BIT(0)) != 0))
r = -EIO;
unlock_and_return:
mutex_unlock(&mb1_transfer.lock);
return r;
}
/**
* prcmu_release_usb_wakeup_state - release the state required by a USB wakeup
*
* This function releases the power state requirements of a USB wakeup.
*/
int prcmu_release_usb_wakeup_state(void)
{
int r = 0;
mutex_lock(&mb1_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(1))
cpu_relax();
writeb(MB1H_RELEASE_USB_WAKEUP,
(tcdm_base + PRCM_MBOX_HEADER_REQ_MB1));
writel(MBOX_BIT(1), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb1_transfer.work);
if ((mb1_transfer.ack.header != MB1H_RELEASE_USB_WAKEUP) ||
((mb1_transfer.ack.ape_voltage_status & BIT(0)) != 0))
r = -EIO;
mutex_unlock(&mb1_transfer.lock);
return r;
}
static int request_pll(u8 clock, bool enable)
{
int r = 0;
if (clock == PRCMU_PLLSOC0)
clock = (enable ? PLL_SOC0_ON : PLL_SOC0_OFF);
else if (clock == PRCMU_PLLSOC1)
clock = (enable ? PLL_SOC1_ON : PLL_SOC1_OFF);
else
return -EINVAL;
mutex_lock(&mb1_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(1))
cpu_relax();
writeb(MB1H_PLL_ON_OFF, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB1));
writeb(clock, (tcdm_base + PRCM_REQ_MB1_PLL_ON_OFF));
writel(MBOX_BIT(1), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb1_transfer.work);
if (mb1_transfer.ack.header != MB1H_PLL_ON_OFF)
r = -EIO;
mutex_unlock(&mb1_transfer.lock);
return r;
}
/**
* db8500_prcmu_set_epod - set the state of a EPOD (power domain)
* @epod_id: The EPOD to set
* @epod_state: The new EPOD state
*
* This function sets the state of a EPOD (power domain). It may not be called
* from interrupt context.
*/
int db8500_prcmu_set_epod(u16 epod_id, u8 epod_state)
{
int r = 0;
bool ram_retention = false;
int i;
/* check argument */
BUG_ON(epod_id >= NUM_EPOD_ID);
/* set flag if retention is possible */
switch (epod_id) {
case EPOD_ID_SVAMMDSP:
case EPOD_ID_SIAMMDSP:
case EPOD_ID_ESRAM12:
case EPOD_ID_ESRAM34:
ram_retention = true;
break;
}
/* check argument */
BUG_ON(epod_state > EPOD_STATE_ON);
BUG_ON(epod_state == EPOD_STATE_RAMRET && !ram_retention);
/* get lock */
mutex_lock(&mb2_transfer.lock);
/* wait for mailbox */
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(2))
cpu_relax();
/* fill in mailbox */
for (i = 0; i < NUM_EPOD_ID; i++)
writeb(EPOD_STATE_NO_CHANGE, (tcdm_base + PRCM_REQ_MB2 + i));
writeb(epod_state, (tcdm_base + PRCM_REQ_MB2 + epod_id));
writeb(MB2H_DPS, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB2));
writel(MBOX_BIT(2), PRCM_MBOX_CPU_SET);
/*
* The current firmware version does not handle errors correctly,
* and we cannot recover if there is an error.
* This is expected to change when the firmware is updated.
*/
if (!wait_for_completion_timeout(&mb2_transfer.work,
msecs_to_jiffies(20000))) {
pr_err("prcmu: %s timed out (20 s) waiting for a reply.\n",
__func__);
r = -EIO;
goto unlock_and_return;
}
if (mb2_transfer.ack.status != HWACC_PWR_ST_OK)
r = -EIO;
unlock_and_return:
mutex_unlock(&mb2_transfer.lock);
return r;
}
/**
* prcmu_configure_auto_pm - Configure autonomous power management.
* @sleep: Configuration for ApSleep.
* @idle: Configuration for ApIdle.
*/
void prcmu_configure_auto_pm(struct prcmu_auto_pm_config *sleep,
struct prcmu_auto_pm_config *idle)
{
u32 sleep_cfg;
u32 idle_cfg;
unsigned long flags;
BUG_ON((sleep == NULL) || (idle == NULL));
sleep_cfg = (sleep->sva_auto_pm_enable & 0xF);
sleep_cfg = ((sleep_cfg << 4) | (sleep->sia_auto_pm_enable & 0xF));
sleep_cfg = ((sleep_cfg << 8) | (sleep->sva_power_on & 0xFF));
sleep_cfg = ((sleep_cfg << 8) | (sleep->sia_power_on & 0xFF));
sleep_cfg = ((sleep_cfg << 4) | (sleep->sva_policy & 0xF));
sleep_cfg = ((sleep_cfg << 4) | (sleep->sia_policy & 0xF));
idle_cfg = (idle->sva_auto_pm_enable & 0xF);
idle_cfg = ((idle_cfg << 4) | (idle->sia_auto_pm_enable & 0xF));
idle_cfg = ((idle_cfg << 8) | (idle->sva_power_on & 0xFF));
idle_cfg = ((idle_cfg << 8) | (idle->sia_power_on & 0xFF));
idle_cfg = ((idle_cfg << 4) | (idle->sva_policy & 0xF));
idle_cfg = ((idle_cfg << 4) | (idle->sia_policy & 0xF));
spin_lock_irqsave(&mb2_transfer.auto_pm_lock, flags);
/*
* The autonomous power management configuration is done through
* fields in mailbox 2, but these fields are only used as shared
* variables - i.e. there is no need to send a message.
*/
writel(sleep_cfg, (tcdm_base + PRCM_REQ_MB2_AUTO_PM_SLEEP));
writel(idle_cfg, (tcdm_base + PRCM_REQ_MB2_AUTO_PM_IDLE));
mb2_transfer.auto_pm_enabled =
((sleep->sva_auto_pm_enable == PRCMU_AUTO_PM_ON) ||
(sleep->sia_auto_pm_enable == PRCMU_AUTO_PM_ON) ||
(idle->sva_auto_pm_enable == PRCMU_AUTO_PM_ON) ||
(idle->sia_auto_pm_enable == PRCMU_AUTO_PM_ON));
spin_unlock_irqrestore(&mb2_transfer.auto_pm_lock, flags);
}
EXPORT_SYMBOL(prcmu_configure_auto_pm);
bool prcmu_is_auto_pm_enabled(void)
{
return mb2_transfer.auto_pm_enabled;
}
static int request_sysclk(bool enable)
{
int r;
unsigned long flags;
r = 0;
mutex_lock(&mb3_transfer.sysclk_lock);
spin_lock_irqsave(&mb3_transfer.lock, flags);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(3))
cpu_relax();
writeb((enable ? ON : OFF), (tcdm_base + PRCM_REQ_MB3_SYSCLK_MGT));
writeb(MB3H_SYSCLK, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB3));
writel(MBOX_BIT(3), PRCM_MBOX_CPU_SET);
spin_unlock_irqrestore(&mb3_transfer.lock, flags);
/*
* The firmware only sends an ACK if we want to enable the
* SysClk, and it succeeds.
*/
if (enable && !wait_for_completion_timeout(&mb3_transfer.sysclk_work,
msecs_to_jiffies(20000))) {
pr_err("prcmu: %s timed out (20 s) waiting for a reply.\n",
__func__);
r = -EIO;
}
mutex_unlock(&mb3_transfer.sysclk_lock);
return r;
}
static int request_timclk(bool enable)
{
u32 val = (PRCM_TCR_DOZE_MODE | PRCM_TCR_TENSEL_MASK);
if (!enable)
val |= PRCM_TCR_STOP_TIMERS;
writel(val, PRCM_TCR);
return 0;
}
static int request_clock(u8 clock, bool enable)
{
u32 val;
unsigned long flags;
spin_lock_irqsave(&clk_mgt_lock, flags);
/* Grab the HW semaphore. */
while ((readl(PRCM_SEM) & PRCM_SEM_PRCM_SEM) != 0)
cpu_relax();
val = readl(prcmu_base + clk_mgt[clock].offset);
if (enable) {
val |= (PRCM_CLK_MGT_CLKEN | clk_mgt[clock].pllsw);
} else {
clk_mgt[clock].pllsw = (val & PRCM_CLK_MGT_CLKPLLSW_MASK);
val &= ~(PRCM_CLK_MGT_CLKEN | PRCM_CLK_MGT_CLKPLLSW_MASK);
}
writel(val, prcmu_base + clk_mgt[clock].offset);
/* Release the HW semaphore. */
writel(0, PRCM_SEM);
spin_unlock_irqrestore(&clk_mgt_lock, flags);
return 0;
}
static int request_sga_clock(u8 clock, bool enable)
{
u32 val;
int ret;
if (enable) {
val = readl(PRCM_CGATING_BYPASS);
writel(val | PRCM_CGATING_BYPASS_ICN2, PRCM_CGATING_BYPASS);
}
ret = request_clock(clock, enable);
if (!ret && !enable) {
val = readl(PRCM_CGATING_BYPASS);
writel(val & ~PRCM_CGATING_BYPASS_ICN2, PRCM_CGATING_BYPASS);
}
return ret;
}
static inline bool plldsi_locked(void)
{
return (readl(PRCM_PLLDSI_LOCKP) &
(PRCM_PLLDSI_LOCKP_PRCM_PLLDSI_LOCKP10 |
PRCM_PLLDSI_LOCKP_PRCM_PLLDSI_LOCKP3)) ==
(PRCM_PLLDSI_LOCKP_PRCM_PLLDSI_LOCKP10 |
PRCM_PLLDSI_LOCKP_PRCM_PLLDSI_LOCKP3);
}
static int request_plldsi(bool enable)
{
int r = 0;
u32 val;
writel((PRCM_MMIP_LS_CLAMP_DSIPLL_CLAMP |
PRCM_MMIP_LS_CLAMP_DSIPLL_CLAMPI), (enable ?
PRCM_MMIP_LS_CLAMP_CLR : PRCM_MMIP_LS_CLAMP_SET));
val = readl(PRCM_PLLDSI_ENABLE);
if (enable)
val |= PRCM_PLLDSI_ENABLE_PRCM_PLLDSI_ENABLE;
else
val &= ~PRCM_PLLDSI_ENABLE_PRCM_PLLDSI_ENABLE;
writel(val, PRCM_PLLDSI_ENABLE);
if (enable) {
unsigned int i;
bool locked = plldsi_locked();
for (i = 10; !locked && (i > 0); --i) {
udelay(100);
locked = plldsi_locked();
}
if (locked) {
writel(PRCM_APE_RESETN_DSIPLL_RESETN,
PRCM_APE_RESETN_SET);
} else {
writel((PRCM_MMIP_LS_CLAMP_DSIPLL_CLAMP |
PRCM_MMIP_LS_CLAMP_DSIPLL_CLAMPI),
PRCM_MMIP_LS_CLAMP_SET);
val &= ~PRCM_PLLDSI_ENABLE_PRCM_PLLDSI_ENABLE;
writel(val, PRCM_PLLDSI_ENABLE);
r = -EAGAIN;
}
} else {
writel(PRCM_APE_RESETN_DSIPLL_RESETN, PRCM_APE_RESETN_CLR);
}
return r;
}
static int request_dsiclk(u8 n, bool enable)
{
u32 val;
val = readl(PRCM_DSI_PLLOUT_SEL);
val &= ~dsiclk[n].divsel_mask;
val |= ((enable ? dsiclk[n].divsel : PRCM_DSI_PLLOUT_SEL_OFF) <<
dsiclk[n].divsel_shift);
writel(val, PRCM_DSI_PLLOUT_SEL);
return 0;
}
static int request_dsiescclk(u8 n, bool enable)
{
u32 val;
val = readl(PRCM_DSITVCLK_DIV);
enable ? (val |= dsiescclk[n].en) : (val &= ~dsiescclk[n].en);
writel(val, PRCM_DSITVCLK_DIV);
return 0;
}
/**
* db8500_prcmu_request_clock() - Request for a clock to be enabled or disabled.
* @clock: The clock for which the request is made.
* @enable: Whether the clock should be enabled (true) or disabled (false).
*
* This function should only be used by the clock implementation.
* Do not use it from any other place!
*/
int db8500_prcmu_request_clock(u8 clock, bool enable)
{
if (clock == PRCMU_SGACLK)
return request_sga_clock(clock, enable);
else if (clock < PRCMU_NUM_REG_CLOCKS)
return request_clock(clock, enable);
else if (clock == PRCMU_TIMCLK)
return request_timclk(enable);
else if ((clock == PRCMU_DSI0CLK) || (clock == PRCMU_DSI1CLK))
return request_dsiclk((clock - PRCMU_DSI0CLK), enable);
else if ((PRCMU_DSI0ESCCLK <= clock) && (clock <= PRCMU_DSI2ESCCLK))
return request_dsiescclk((clock - PRCMU_DSI0ESCCLK), enable);
else if (clock == PRCMU_PLLDSI)
return request_plldsi(enable);
else if (clock == PRCMU_SYSCLK)
return request_sysclk(enable);
else if ((clock == PRCMU_PLLSOC0) || (clock == PRCMU_PLLSOC1))
return request_pll(clock, enable);
else
return -EINVAL;
}
static unsigned long pll_rate(void __iomem *reg, unsigned long src_rate,
int branch)
{
u64 rate;
u32 val;
u32 d;
u32 div = 1;
val = readl(reg);
rate = src_rate;
rate *= ((val & PRCM_PLL_FREQ_D_MASK) >> PRCM_PLL_FREQ_D_SHIFT);
d = ((val & PRCM_PLL_FREQ_N_MASK) >> PRCM_PLL_FREQ_N_SHIFT);
if (d > 1)
div *= d;
d = ((val & PRCM_PLL_FREQ_R_MASK) >> PRCM_PLL_FREQ_R_SHIFT);
if (d > 1)
div *= d;
if (val & PRCM_PLL_FREQ_SELDIV2)
div *= 2;
if ((branch == PLL_FIX) || ((branch == PLL_DIV) &&
(val & PRCM_PLL_FREQ_DIV2EN) &&
((reg == PRCM_PLLSOC0_FREQ) ||
(reg == PRCM_PLLARM_FREQ) ||
(reg == PRCM_PLLDDR_FREQ))))
div *= 2;
(void)do_div(rate, div);
return (unsigned long)rate;
}
#define ROOT_CLOCK_RATE 38400000
static unsigned long clock_rate(u8 clock)
{
u32 val;
u32 pllsw;
unsigned long rate = ROOT_CLOCK_RATE;
val = readl(prcmu_base + clk_mgt[clock].offset);
if (val & PRCM_CLK_MGT_CLK38) {
if (clk_mgt[clock].clk38div && (val & PRCM_CLK_MGT_CLK38DIV))
rate /= 2;
return rate;
}
val |= clk_mgt[clock].pllsw;
pllsw = (val & PRCM_CLK_MGT_CLKPLLSW_MASK);
if (pllsw == PRCM_CLK_MGT_CLKPLLSW_SOC0)
rate = pll_rate(PRCM_PLLSOC0_FREQ, rate, clk_mgt[clock].branch);
else if (pllsw == PRCM_CLK_MGT_CLKPLLSW_SOC1)
rate = pll_rate(PRCM_PLLSOC1_FREQ, rate, clk_mgt[clock].branch);
else if (pllsw == PRCM_CLK_MGT_CLKPLLSW_DDR)
rate = pll_rate(PRCM_PLLDDR_FREQ, rate, clk_mgt[clock].branch);
else
return 0;
if ((clock == PRCMU_SGACLK) &&
(val & PRCM_SGACLK_MGT_SGACLKDIV_BY_2_5_EN)) {
u64 r = (rate * 10);
(void)do_div(r, 25);
return (unsigned long)r;
}
val &= PRCM_CLK_MGT_CLKPLLDIV_MASK;
if (val)
return rate / val;
else
return 0;
}
static unsigned long armss_rate(void)
{
u32 r;
unsigned long rate;
r = readl(PRCM_ARM_CHGCLKREQ);
if (r & PRCM_ARM_CHGCLKREQ_PRCM_ARM_CHGCLKREQ) {
/* External ARMCLKFIX clock */
rate = pll_rate(PRCM_PLLDDR_FREQ, ROOT_CLOCK_RATE, PLL_FIX);
/* Check PRCM_ARM_CHGCLKREQ divider */
if (!(r & PRCM_ARM_CHGCLKREQ_PRCM_ARM_DIVSEL))
rate /= 2;
/* Check PRCM_ARMCLKFIX_MGT divider */
r = readl(PRCM_ARMCLKFIX_MGT);
r &= PRCM_CLK_MGT_CLKPLLDIV_MASK;
rate /= r;
} else {/* ARM PLL */
rate = pll_rate(PRCM_PLLARM_FREQ, ROOT_CLOCK_RATE, PLL_DIV);
}
return rate;
}
static unsigned long dsiclk_rate(u8 n)
{
u32 divsel;
u32 div = 1;
divsel = readl(PRCM_DSI_PLLOUT_SEL);
divsel = ((divsel & dsiclk[n].divsel_mask) >> dsiclk[n].divsel_shift);
if (divsel == PRCM_DSI_PLLOUT_SEL_OFF)
divsel = dsiclk[n].divsel;
else
dsiclk[n].divsel = divsel;
switch (divsel) {
case PRCM_DSI_PLLOUT_SEL_PHI_4:
div *= 2;
case PRCM_DSI_PLLOUT_SEL_PHI_2:
div *= 2;
case PRCM_DSI_PLLOUT_SEL_PHI:
return pll_rate(PRCM_PLLDSI_FREQ, clock_rate(PRCMU_HDMICLK),
PLL_RAW) / div;
default:
return 0;
}
}
static unsigned long dsiescclk_rate(u8 n)
{
u32 div;
div = readl(PRCM_DSITVCLK_DIV);
div = ((div & dsiescclk[n].div_mask) >> (dsiescclk[n].div_shift));
return clock_rate(PRCMU_TVCLK) / max((u32)1, div);
}
unsigned long prcmu_clock_rate(u8 clock)
{
if (clock < PRCMU_NUM_REG_CLOCKS)
return clock_rate(clock);
else if (clock == PRCMU_TIMCLK)
return ROOT_CLOCK_RATE / 16;
else if (clock == PRCMU_SYSCLK)
return ROOT_CLOCK_RATE;
else if (clock == PRCMU_PLLSOC0)
return pll_rate(PRCM_PLLSOC0_FREQ, ROOT_CLOCK_RATE, PLL_RAW);
else if (clock == PRCMU_PLLSOC1)
return pll_rate(PRCM_PLLSOC1_FREQ, ROOT_CLOCK_RATE, PLL_RAW);
else if (clock == PRCMU_ARMSS)
return armss_rate();
else if (clock == PRCMU_PLLDDR)
return pll_rate(PRCM_PLLDDR_FREQ, ROOT_CLOCK_RATE, PLL_RAW);
else if (clock == PRCMU_PLLDSI)
return pll_rate(PRCM_PLLDSI_FREQ, clock_rate(PRCMU_HDMICLK),
PLL_RAW);
else if ((clock == PRCMU_DSI0CLK) || (clock == PRCMU_DSI1CLK))
return dsiclk_rate(clock - PRCMU_DSI0CLK);
else if ((PRCMU_DSI0ESCCLK <= clock) && (clock <= PRCMU_DSI2ESCCLK))
return dsiescclk_rate(clock - PRCMU_DSI0ESCCLK);
else
return 0;
}
static unsigned long clock_source_rate(u32 clk_mgt_val, int branch)
{
if (clk_mgt_val & PRCM_CLK_MGT_CLK38)
return ROOT_CLOCK_RATE;
clk_mgt_val &= PRCM_CLK_MGT_CLKPLLSW_MASK;
if (clk_mgt_val == PRCM_CLK_MGT_CLKPLLSW_SOC0)
return pll_rate(PRCM_PLLSOC0_FREQ, ROOT_CLOCK_RATE, branch);
else if (clk_mgt_val == PRCM_CLK_MGT_CLKPLLSW_SOC1)
return pll_rate(PRCM_PLLSOC1_FREQ, ROOT_CLOCK_RATE, branch);
else if (clk_mgt_val == PRCM_CLK_MGT_CLKPLLSW_DDR)
return pll_rate(PRCM_PLLDDR_FREQ, ROOT_CLOCK_RATE, branch);
else
return 0;
}
static u32 clock_divider(unsigned long src_rate, unsigned long rate)
{
u32 div;
div = (src_rate / rate);
if (div == 0)
return 1;
if (rate < (src_rate / div))
div++;
return div;
}
static long round_clock_rate(u8 clock, unsigned long rate)
{
u32 val;
u32 div;
unsigned long src_rate;
long rounded_rate;
val = readl(prcmu_base + clk_mgt[clock].offset);
src_rate = clock_source_rate((val | clk_mgt[clock].pllsw),
clk_mgt[clock].branch);
div = clock_divider(src_rate, rate);
if (val & PRCM_CLK_MGT_CLK38) {
if (clk_mgt[clock].clk38div) {
if (div > 2)
div = 2;
} else {
div = 1;
}
} else if ((clock == PRCMU_SGACLK) && (div == 3)) {
u64 r = (src_rate * 10);
(void)do_div(r, 25);
if (r <= rate)
return (unsigned long)r;
}
rounded_rate = (src_rate / min(div, (u32)31));
return rounded_rate;
}
/* CPU FREQ table, may be changed due to if MAX_OPP is supported. */
static struct cpufreq_frequency_table db8500_cpufreq_table[] = {
{ .frequency = 200000, .driver_data = ARM_EXTCLK,},
{ .frequency = 400000, .driver_data = ARM_50_OPP,},
{ .frequency = 800000, .driver_data = ARM_100_OPP,},
{ .frequency = CPUFREQ_TABLE_END,}, /* To be used for MAX_OPP. */
{ .frequency = CPUFREQ_TABLE_END,},
};
static long round_armss_rate(unsigned long rate)
{
long freq = 0;
int i = 0;
/* cpufreq table frequencies is in KHz. */
rate = rate / 1000;
/* Find the corresponding arm opp from the cpufreq table. */
while (db8500_cpufreq_table[i].frequency != CPUFREQ_TABLE_END) {
freq = db8500_cpufreq_table[i].frequency;
if (freq == rate)
break;
i++;
}
/* Return the last valid value, even if a match was not found. */
return freq * 1000;
}
#define MIN_PLL_VCO_RATE 600000000ULL
#define MAX_PLL_VCO_RATE 1680640000ULL
static long round_plldsi_rate(unsigned long rate)
{
long rounded_rate = 0;
unsigned long src_rate;
unsigned long rem;
u32 r;
src_rate = clock_rate(PRCMU_HDMICLK);
rem = rate;
for (r = 7; (rem > 0) && (r > 0); r--) {
u64 d;
d = (r * rate);
(void)do_div(d, src_rate);
if (d < 6)
d = 6;
else if (d > 255)
d = 255;
d *= src_rate;
if (((2 * d) < (r * MIN_PLL_VCO_RATE)) ||
((r * MAX_PLL_VCO_RATE) < (2 * d)))
continue;
(void)do_div(d, r);
if (rate < d) {
if (rounded_rate == 0)
rounded_rate = (long)d;
break;
}
if ((rate - d) < rem) {
rem = (rate - d);
rounded_rate = (long)d;
}
}
return rounded_rate;
}
static long round_dsiclk_rate(unsigned long rate)
{
u32 div;
unsigned long src_rate;
long rounded_rate;
src_rate = pll_rate(PRCM_PLLDSI_FREQ, clock_rate(PRCMU_HDMICLK),
PLL_RAW);
div = clock_divider(src_rate, rate);
rounded_rate = (src_rate / ((div > 2) ? 4 : div));
return rounded_rate;
}
static long round_dsiescclk_rate(unsigned long rate)
{
u32 div;
unsigned long src_rate;
long rounded_rate;
src_rate = clock_rate(PRCMU_TVCLK);
div = clock_divider(src_rate, rate);
rounded_rate = (src_rate / min(div, (u32)255));
return rounded_rate;
}
long prcmu_round_clock_rate(u8 clock, unsigned long rate)
{
if (clock < PRCMU_NUM_REG_CLOCKS)
return round_clock_rate(clock, rate);
else if (clock == PRCMU_ARMSS)
return round_armss_rate(rate);
else if (clock == PRCMU_PLLDSI)
return round_plldsi_rate(rate);
else if ((clock == PRCMU_DSI0CLK) || (clock == PRCMU_DSI1CLK))
return round_dsiclk_rate(rate);
else if ((PRCMU_DSI0ESCCLK <= clock) && (clock <= PRCMU_DSI2ESCCLK))
return round_dsiescclk_rate(rate);
else
return (long)prcmu_clock_rate(clock);
}
static void set_clock_rate(u8 clock, unsigned long rate)
{
u32 val;
u32 div;
unsigned long src_rate;
unsigned long flags;
spin_lock_irqsave(&clk_mgt_lock, flags);
/* Grab the HW semaphore. */
while ((readl(PRCM_SEM) & PRCM_SEM_PRCM_SEM) != 0)
cpu_relax();
val = readl(prcmu_base + clk_mgt[clock].offset);
src_rate = clock_source_rate((val | clk_mgt[clock].pllsw),
clk_mgt[clock].branch);
div = clock_divider(src_rate, rate);
if (val & PRCM_CLK_MGT_CLK38) {
if (clk_mgt[clock].clk38div) {
if (div > 1)
val |= PRCM_CLK_MGT_CLK38DIV;
else
val &= ~PRCM_CLK_MGT_CLK38DIV;
}
} else if (clock == PRCMU_SGACLK) {
val &= ~(PRCM_CLK_MGT_CLKPLLDIV_MASK |
PRCM_SGACLK_MGT_SGACLKDIV_BY_2_5_EN);
if (div == 3) {
u64 r = (src_rate * 10);
(void)do_div(r, 25);
if (r <= rate) {
val |= PRCM_SGACLK_MGT_SGACLKDIV_BY_2_5_EN;
div = 0;
}
}
val |= min(div, (u32)31);
} else {
val &= ~PRCM_CLK_MGT_CLKPLLDIV_MASK;
val |= min(div, (u32)31);
}
writel(val, prcmu_base + clk_mgt[clock].offset);
/* Release the HW semaphore. */
writel(0, PRCM_SEM);
spin_unlock_irqrestore(&clk_mgt_lock, flags);
}
static int set_armss_rate(unsigned long rate)
{
int i = 0;
/* cpufreq table frequencies is in KHz. */
rate = rate / 1000;
/* Find the corresponding arm opp from the cpufreq table. */
while (db8500_cpufreq_table[i].frequency != CPUFREQ_TABLE_END) {
if (db8500_cpufreq_table[i].frequency == rate)
break;
i++;
}
if (db8500_cpufreq_table[i].frequency != rate)
return -EINVAL;
/* Set the new arm opp. */
return db8500_prcmu_set_arm_opp(db8500_cpufreq_table[i].driver_data);
}
static int set_plldsi_rate(unsigned long rate)
{
unsigned long src_rate;
unsigned long rem;
u32 pll_freq = 0;
u32 r;
src_rate = clock_rate(PRCMU_HDMICLK);
rem = rate;
for (r = 7; (rem > 0) && (r > 0); r--) {
u64 d;
u64 hwrate;
d = (r * rate);
(void)do_div(d, src_rate);
if (d < 6)
d = 6;
else if (d > 255)
d = 255;
hwrate = (d * src_rate);
if (((2 * hwrate) < (r * MIN_PLL_VCO_RATE)) ||
((r * MAX_PLL_VCO_RATE) < (2 * hwrate)))
continue;
(void)do_div(hwrate, r);
if (rate < hwrate) {
if (pll_freq == 0)
pll_freq = (((u32)d << PRCM_PLL_FREQ_D_SHIFT) |
(r << PRCM_PLL_FREQ_R_SHIFT));
break;
}
if ((rate - hwrate) < rem) {
rem = (rate - hwrate);
pll_freq = (((u32)d << PRCM_PLL_FREQ_D_SHIFT) |
(r << PRCM_PLL_FREQ_R_SHIFT));
}
}
if (pll_freq == 0)
return -EINVAL;
pll_freq |= (1 << PRCM_PLL_FREQ_N_SHIFT);
writel(pll_freq, PRCM_PLLDSI_FREQ);
return 0;
}
static void set_dsiclk_rate(u8 n, unsigned long rate)
{
u32 val;
u32 div;
div = clock_divider(pll_rate(PRCM_PLLDSI_FREQ,
clock_rate(PRCMU_HDMICLK), PLL_RAW), rate);
dsiclk[n].divsel = (div == 1) ? PRCM_DSI_PLLOUT_SEL_PHI :
(div == 2) ? PRCM_DSI_PLLOUT_SEL_PHI_2 :
/* else */ PRCM_DSI_PLLOUT_SEL_PHI_4;
val = readl(PRCM_DSI_PLLOUT_SEL);
val &= ~dsiclk[n].divsel_mask;
val |= (dsiclk[n].divsel << dsiclk[n].divsel_shift);
writel(val, PRCM_DSI_PLLOUT_SEL);
}
static void set_dsiescclk_rate(u8 n, unsigned long rate)
{
u32 val;
u32 div;
div = clock_divider(clock_rate(PRCMU_TVCLK), rate);
val = readl(PRCM_DSITVCLK_DIV);
val &= ~dsiescclk[n].div_mask;
val |= (min(div, (u32)255) << dsiescclk[n].div_shift);
writel(val, PRCM_DSITVCLK_DIV);
}
int prcmu_set_clock_rate(u8 clock, unsigned long rate)
{
if (clock < PRCMU_NUM_REG_CLOCKS)
set_clock_rate(clock, rate);
else if (clock == PRCMU_ARMSS)
return set_armss_rate(rate);
else if (clock == PRCMU_PLLDSI)
return set_plldsi_rate(rate);
else if ((clock == PRCMU_DSI0CLK) || (clock == PRCMU_DSI1CLK))
set_dsiclk_rate((clock - PRCMU_DSI0CLK), rate);
else if ((PRCMU_DSI0ESCCLK <= clock) && (clock <= PRCMU_DSI2ESCCLK))
set_dsiescclk_rate((clock - PRCMU_DSI0ESCCLK), rate);
return 0;
}
int db8500_prcmu_config_esram0_deep_sleep(u8 state)
{
if ((state > ESRAM0_DEEP_SLEEP_STATE_RET) ||
(state < ESRAM0_DEEP_SLEEP_STATE_OFF))
return -EINVAL;
mutex_lock(&mb4_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(4))
cpu_relax();
writeb(MB4H_MEM_ST, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB4));
writeb(((DDR_PWR_STATE_OFFHIGHLAT << 4) | DDR_PWR_STATE_ON),
(tcdm_base + PRCM_REQ_MB4_DDR_ST_AP_SLEEP_IDLE));
writeb(DDR_PWR_STATE_ON,
(tcdm_base + PRCM_REQ_MB4_DDR_ST_AP_DEEP_IDLE));
writeb(state, (tcdm_base + PRCM_REQ_MB4_ESRAM0_ST));
writel(MBOX_BIT(4), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb4_transfer.work);
mutex_unlock(&mb4_transfer.lock);
return 0;
}
int db8500_prcmu_config_hotdog(u8 threshold)
{
mutex_lock(&mb4_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(4))
cpu_relax();
writeb(threshold, (tcdm_base + PRCM_REQ_MB4_HOTDOG_THRESHOLD));
writeb(MB4H_HOTDOG, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB4));
writel(MBOX_BIT(4), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb4_transfer.work);
mutex_unlock(&mb4_transfer.lock);
return 0;
}
int db8500_prcmu_config_hotmon(u8 low, u8 high)
{
mutex_lock(&mb4_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(4))
cpu_relax();
writeb(low, (tcdm_base + PRCM_REQ_MB4_HOTMON_LOW));
writeb(high, (tcdm_base + PRCM_REQ_MB4_HOTMON_HIGH));
writeb((HOTMON_CONFIG_LOW | HOTMON_CONFIG_HIGH),
(tcdm_base + PRCM_REQ_MB4_HOTMON_CONFIG));
writeb(MB4H_HOTMON, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB4));
writel(MBOX_BIT(4), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb4_transfer.work);
mutex_unlock(&mb4_transfer.lock);
return 0;
}
static int config_hot_period(u16 val)
{
mutex_lock(&mb4_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(4))
cpu_relax();
writew(val, (tcdm_base + PRCM_REQ_MB4_HOT_PERIOD));
writeb(MB4H_HOT_PERIOD, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB4));
writel(MBOX_BIT(4), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb4_transfer.work);
mutex_unlock(&mb4_transfer.lock);
return 0;
}
int db8500_prcmu_start_temp_sense(u16 cycles32k)
{
if (cycles32k == 0xFFFF)
return -EINVAL;
return config_hot_period(cycles32k);
}
int db8500_prcmu_stop_temp_sense(void)
{
return config_hot_period(0xFFFF);
}
static int prcmu_a9wdog(u8 cmd, u8 d0, u8 d1, u8 d2, u8 d3)
{
mutex_lock(&mb4_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(4))
cpu_relax();
writeb(d0, (tcdm_base + PRCM_REQ_MB4_A9WDOG_0));
writeb(d1, (tcdm_base + PRCM_REQ_MB4_A9WDOG_1));
writeb(d2, (tcdm_base + PRCM_REQ_MB4_A9WDOG_2));
writeb(d3, (tcdm_base + PRCM_REQ_MB4_A9WDOG_3));
writeb(cmd, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB4));
writel(MBOX_BIT(4), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb4_transfer.work);
mutex_unlock(&mb4_transfer.lock);
return 0;
}
int db8500_prcmu_config_a9wdog(u8 num, bool sleep_auto_off)
{
BUG_ON(num == 0 || num > 0xf);
return prcmu_a9wdog(MB4H_A9WDOG_CONF, num, 0, 0,
sleep_auto_off ? A9WDOG_AUTO_OFF_EN :
A9WDOG_AUTO_OFF_DIS);
}
EXPORT_SYMBOL(db8500_prcmu_config_a9wdog);
int db8500_prcmu_enable_a9wdog(u8 id)
{
return prcmu_a9wdog(MB4H_A9WDOG_EN, id, 0, 0, 0);
}
EXPORT_SYMBOL(db8500_prcmu_enable_a9wdog);
int db8500_prcmu_disable_a9wdog(u8 id)
{
return prcmu_a9wdog(MB4H_A9WDOG_DIS, id, 0, 0, 0);
}
EXPORT_SYMBOL(db8500_prcmu_disable_a9wdog);
int db8500_prcmu_kick_a9wdog(u8 id)
{
return prcmu_a9wdog(MB4H_A9WDOG_KICK, id, 0, 0, 0);
}
EXPORT_SYMBOL(db8500_prcmu_kick_a9wdog);
/*
* timeout is 28 bit, in ms.
*/
int db8500_prcmu_load_a9wdog(u8 id, u32 timeout)
{
return prcmu_a9wdog(MB4H_A9WDOG_LOAD,
(id & A9WDOG_ID_MASK) |
/*
* Put the lowest 28 bits of timeout at
* offset 4. Four first bits are used for id.
*/
(u8)((timeout << 4) & 0xf0),
(u8)((timeout >> 4) & 0xff),
(u8)((timeout >> 12) & 0xff),
(u8)((timeout >> 20) & 0xff));
}
EXPORT_SYMBOL(db8500_prcmu_load_a9wdog);
/**
* prcmu_abb_read() - Read register value(s) from the ABB.
* @slave: The I2C slave address.
* @reg: The (start) register address.
* @value: The read out value(s).
* @size: The number of registers to read.
*
* Reads register value(s) from the ABB.
* @size has to be 1 for the current firmware version.
*/
int prcmu_abb_read(u8 slave, u8 reg, u8 *value, u8 size)
{
int r;
if (size != 1)
return -EINVAL;
mutex_lock(&mb5_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(5))
cpu_relax();
writeb(0, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB5));
writeb(PRCMU_I2C_READ(slave), (tcdm_base + PRCM_REQ_MB5_I2C_SLAVE_OP));
writeb(PRCMU_I2C_STOP_EN, (tcdm_base + PRCM_REQ_MB5_I2C_HW_BITS));
writeb(reg, (tcdm_base + PRCM_REQ_MB5_I2C_REG));
writeb(0, (tcdm_base + PRCM_REQ_MB5_I2C_VAL));
writel(MBOX_BIT(5), PRCM_MBOX_CPU_SET);
if (!wait_for_completion_timeout(&mb5_transfer.work,
msecs_to_jiffies(20000))) {
pr_err("prcmu: %s timed out (20 s) waiting for a reply.\n",
__func__);
r = -EIO;
} else {
r = ((mb5_transfer.ack.status == I2C_RD_OK) ? 0 : -EIO);
}
if (!r)
*value = mb5_transfer.ack.value;
mutex_unlock(&mb5_transfer.lock);
return r;
}
/**
* prcmu_abb_write_masked() - Write masked register value(s) to the ABB.
* @slave: The I2C slave address.
* @reg: The (start) register address.
* @value: The value(s) to write.
* @mask: The mask(s) to use.
* @size: The number of registers to write.
*
* Writes masked register value(s) to the ABB.
* For each @value, only the bits set to 1 in the corresponding @mask
* will be written. The other bits are not changed.
* @size has to be 1 for the current firmware version.
*/
int prcmu_abb_write_masked(u8 slave, u8 reg, u8 *value, u8 *mask, u8 size)
{
int r;
if (size != 1)
return -EINVAL;
mutex_lock(&mb5_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(5))
cpu_relax();
writeb(~*mask, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB5));
writeb(PRCMU_I2C_WRITE(slave), (tcdm_base + PRCM_REQ_MB5_I2C_SLAVE_OP));
writeb(PRCMU_I2C_STOP_EN, (tcdm_base + PRCM_REQ_MB5_I2C_HW_BITS));
writeb(reg, (tcdm_base + PRCM_REQ_MB5_I2C_REG));
writeb(*value, (tcdm_base + PRCM_REQ_MB5_I2C_VAL));
writel(MBOX_BIT(5), PRCM_MBOX_CPU_SET);
if (!wait_for_completion_timeout(&mb5_transfer.work,
msecs_to_jiffies(20000))) {
pr_err("prcmu: %s timed out (20 s) waiting for a reply.\n",
__func__);
r = -EIO;
} else {
r = ((mb5_transfer.ack.status == I2C_WR_OK) ? 0 : -EIO);
}
mutex_unlock(&mb5_transfer.lock);
return r;
}
/**
* prcmu_abb_write() - Write register value(s) to the ABB.
* @slave: The I2C slave address.
* @reg: The (start) register address.
* @value: The value(s) to write.
* @size: The number of registers to write.
*
* Writes register value(s) to the ABB.
* @size has to be 1 for the current firmware version.
*/
int prcmu_abb_write(u8 slave, u8 reg, u8 *value, u8 size)
{
u8 mask = ~0;
return prcmu_abb_write_masked(slave, reg, value, &mask, size);
}
/**
* prcmu_ac_wake_req - should be called whenever ARM wants to wakeup Modem
*/
int prcmu_ac_wake_req(void)
{
u32 val;
int ret = 0;
mutex_lock(&mb0_transfer.ac_wake_lock);
val = readl(PRCM_HOSTACCESS_REQ);
if (val & PRCM_HOSTACCESS_REQ_HOSTACCESS_REQ)
goto unlock_and_return;
atomic_set(&ac_wake_req_state, 1);
/*
* Force Modem Wake-up before hostaccess_req ping-pong.
* It prevents Modem to enter in Sleep while acking the hostaccess
* request. The 31us delay has been calculated by HWI.
*/
val |= PRCM_HOSTACCESS_REQ_WAKE_REQ;
writel(val, PRCM_HOSTACCESS_REQ);
udelay(31);
val |= PRCM_HOSTACCESS_REQ_HOSTACCESS_REQ;
writel(val, PRCM_HOSTACCESS_REQ);
if (!wait_for_completion_timeout(&mb0_transfer.ac_wake_work,
msecs_to_jiffies(5000))) {
#if defined(CONFIG_DBX500_PRCMU_DEBUG)
db8500_prcmu_debug_dump(__func__, true, true);
#endif
pr_crit("prcmu: %s timed out (5 s) waiting for a reply.\n",
__func__);
ret = -EFAULT;
}
unlock_and_return:
mutex_unlock(&mb0_transfer.ac_wake_lock);
return ret;
}
/**
* prcmu_ac_sleep_req - called when ARM no longer needs to talk to modem
*/
void prcmu_ac_sleep_req()
{
u32 val;
mutex_lock(&mb0_transfer.ac_wake_lock);
val = readl(PRCM_HOSTACCESS_REQ);
if (!(val & PRCM_HOSTACCESS_REQ_HOSTACCESS_REQ))
goto unlock_and_return;
writel((val & ~PRCM_HOSTACCESS_REQ_HOSTACCESS_REQ),
PRCM_HOSTACCESS_REQ);
if (!wait_for_completion_timeout(&mb0_transfer.ac_wake_work,
msecs_to_jiffies(5000))) {
pr_crit("prcmu: %s timed out (5 s) waiting for a reply.\n",
__func__);
}
atomic_set(&ac_wake_req_state, 0);
unlock_and_return:
mutex_unlock(&mb0_transfer.ac_wake_lock);
}
bool db8500_prcmu_is_ac_wake_requested(void)
{
return (atomic_read(&ac_wake_req_state) != 0);
}
/**
* db8500_prcmu_system_reset - System reset
*
* Saves the reset reason code and then sets the APE_SOFTRST register which
* fires interrupt to fw
*/
void db8500_prcmu_system_reset(u16 reset_code)
{
writew(reset_code, (tcdm_base + PRCM_SW_RST_REASON));
writel(1, PRCM_APE_SOFTRST);
}
/**
* db8500_prcmu_get_reset_code - Retrieve SW reset reason code
*
* Retrieves the reset reason code stored by prcmu_system_reset() before
* last restart.
*/
u16 db8500_prcmu_get_reset_code(void)
{
return readw(tcdm_base + PRCM_SW_RST_REASON);
}
/**
* db8500_prcmu_reset_modem - ask the PRCMU to reset modem
*/
void db8500_prcmu_modem_reset(void)
{
mutex_lock(&mb1_transfer.lock);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(1))
cpu_relax();
writeb(MB1H_RESET_MODEM, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB1));
writel(MBOX_BIT(1), PRCM_MBOX_CPU_SET);
wait_for_completion(&mb1_transfer.work);
/*
* No need to check return from PRCMU as modem should go in reset state
* This state is already managed by upper layer
*/
mutex_unlock(&mb1_transfer.lock);
}
static void ack_dbb_wakeup(void)
{
unsigned long flags;
spin_lock_irqsave(&mb0_transfer.lock, flags);
while (readl(PRCM_MBOX_CPU_VAL) & MBOX_BIT(0))
cpu_relax();
writeb(MB0H_READ_WAKEUP_ACK, (tcdm_base + PRCM_MBOX_HEADER_REQ_MB0));
writel(MBOX_BIT(0), PRCM_MBOX_CPU_SET);
spin_unlock_irqrestore(&mb0_transfer.lock, flags);
}
static inline void print_unknown_header_warning(u8 n, u8 header)
{
pr_warning("prcmu: Unknown message header (%d) in mailbox %d.\n",
header, n);
}
static bool read_mailbox_0(void)
{
bool r;
u32 ev;
unsigned int n;
u8 header;
header = readb(tcdm_base + PRCM_MBOX_HEADER_ACK_MB0);
switch (header) {
case MB0H_WAKEUP_EXE:
case MB0H_WAKEUP_SLEEP:
if (readb(tcdm_base + PRCM_ACK_MB0_READ_POINTER) & 1)
ev = readl(tcdm_base + PRCM_ACK_MB0_WAKEUP_1_8500);
else
ev = readl(tcdm_base + PRCM_ACK_MB0_WAKEUP_0_8500);
if (ev & (WAKEUP_BIT_AC_WAKE_ACK | WAKEUP_BIT_AC_SLEEP_ACK))
complete(&mb0_transfer.ac_wake_work);
if (ev & WAKEUP_BIT_SYSCLK_OK)
complete(&mb3_transfer.sysclk_work);
ev &= mb0_transfer.req.dbb_irqs;
for (n = 0; n < NUM_PRCMU_WAKEUPS; n++) {
if (ev & prcmu_irq_bit[n])
generic_handle_irq(irq_find_mapping(db8500_irq_domain, n));
}
r = true;
break;
default:
print_unknown_header_warning(0, header);
r = false;
break;
}
writel(MBOX_BIT(0), PRCM_ARM_IT1_CLR);
return r;
}
static bool read_mailbox_1(void)
{
mb1_transfer.ack.header = readb(tcdm_base + PRCM_MBOX_HEADER_REQ_MB1);
mb1_transfer.ack.arm_opp = readb(tcdm_base +
PRCM_ACK_MB1_CURRENT_ARM_OPP);
mb1_transfer.ack.ape_opp = readb(tcdm_base +
PRCM_ACK_MB1_CURRENT_APE_OPP);
mb1_transfer.ack.ape_voltage_status = readb(tcdm_base +
PRCM_ACK_MB1_APE_VOLTAGE_STATUS);
writel(MBOX_BIT(1), PRCM_ARM_IT1_CLR);
complete(&mb1_transfer.work);
return false;
}
static bool read_mailbox_2(void)
{
mb2_transfer.ack.status = readb(tcdm_base + PRCM_ACK_MB2_DPS_STATUS);
writel(MBOX_BIT(2), PRCM_ARM_IT1_CLR);
complete(&mb2_transfer.work);
return false;
}
static bool read_mailbox_3(void)
{
writel(MBOX_BIT(3), PRCM_ARM_IT1_CLR);
return false;
}
static bool read_mailbox_4(void)
{
u8 header;
bool do_complete = true;
header = readb(tcdm_base + PRCM_MBOX_HEADER_REQ_MB4);
switch (header) {
case MB4H_MEM_ST:
case MB4H_HOTDOG:
case MB4H_HOTMON:
case MB4H_HOT_PERIOD:
case MB4H_A9WDOG_CONF:
case MB4H_A9WDOG_EN:
case MB4H_A9WDOG_DIS:
case MB4H_A9WDOG_LOAD:
case MB4H_A9WDOG_KICK:
break;
default:
print_unknown_header_warning(4, header);
do_complete = false;
break;
}
writel(MBOX_BIT(4), PRCM_ARM_IT1_CLR);
if (do_complete)
complete(&mb4_transfer.work);
return false;
}
static bool read_mailbox_5(void)
{
mb5_transfer.ack.status = readb(tcdm_base + PRCM_ACK_MB5_I2C_STATUS);
mb5_transfer.ack.value = readb(tcdm_base + PRCM_ACK_MB5_I2C_VAL);
writel(MBOX_BIT(5), PRCM_ARM_IT1_CLR);
complete(&mb5_transfer.work);
return false;
}
static bool read_mailbox_6(void)
{
writel(MBOX_BIT(6), PRCM_ARM_IT1_CLR);
return false;
}
static bool read_mailbox_7(void)
{
writel(MBOX_BIT(7), PRCM_ARM_IT1_CLR);
return false;
}
static bool (* const read_mailbox[NUM_MB])(void) = {
read_mailbox_0,
read_mailbox_1,
read_mailbox_2,
read_mailbox_3,
read_mailbox_4,
read_mailbox_5,
read_mailbox_6,
read_mailbox_7
};
static irqreturn_t prcmu_irq_handler(int irq, void *data)
{
u32 bits;
u8 n;
irqreturn_t r;
bits = (readl(PRCM_ARM_IT1_VAL) & ALL_MBOX_BITS);
if (unlikely(!bits))
return IRQ_NONE;
r = IRQ_HANDLED;
for (n = 0; bits; n++) {
if (bits & MBOX_BIT(n)) {
bits -= MBOX_BIT(n);
if (read_mailbox[n]())
r = IRQ_WAKE_THREAD;
}
}
return r;
}
static irqreturn_t prcmu_irq_thread_fn(int irq, void *data)
{
ack_dbb_wakeup();
return IRQ_HANDLED;
}
static void prcmu_mask_work(struct work_struct *work)
{
unsigned long flags;
spin_lock_irqsave(&mb0_transfer.lock, flags);
config_wakeups();
spin_unlock_irqrestore(&mb0_transfer.lock, flags);
}
static void prcmu_irq_mask(struct irq_data *d)
{
unsigned long flags;
spin_lock_irqsave(&mb0_transfer.dbb_irqs_lock, flags);
mb0_transfer.req.dbb_irqs &= ~prcmu_irq_bit[d->hwirq];
spin_unlock_irqrestore(&mb0_transfer.dbb_irqs_lock, flags);
if (d->irq != IRQ_PRCMU_CA_SLEEP)
schedule_work(&mb0_transfer.mask_work);
}
static void prcmu_irq_unmask(struct irq_data *d)
{
unsigned long flags;
spin_lock_irqsave(&mb0_transfer.dbb_irqs_lock, flags);
mb0_transfer.req.dbb_irqs |= prcmu_irq_bit[d->hwirq];
spin_unlock_irqrestore(&mb0_transfer.dbb_irqs_lock, flags);
if (d->irq != IRQ_PRCMU_CA_SLEEP)
schedule_work(&mb0_transfer.mask_work);
}
static void noop(struct irq_data *d)
{
}
static struct irq_chip prcmu_irq_chip = {
.name = "prcmu",
.irq_disable = prcmu_irq_mask,
.irq_ack = noop,
.irq_mask = prcmu_irq_mask,
.irq_unmask = prcmu_irq_unmask,
};
static __init char *fw_project_name(u32 project)
{
switch (project) {
case PRCMU_FW_PROJECT_U8500:
return "U8500";
case PRCMU_FW_PROJECT_U8400:
return "U8400";
case PRCMU_FW_PROJECT_U9500:
return "U9500";
case PRCMU_FW_PROJECT_U8500_MBB:
return "U8500 MBB";
case PRCMU_FW_PROJECT_U8500_C1:
return "U8500 C1";
case PRCMU_FW_PROJECT_U8500_C2:
return "U8500 C2";
case PRCMU_FW_PROJECT_U8500_C3:
return "U8500 C3";
case PRCMU_FW_PROJECT_U8500_C4:
return "U8500 C4";
case PRCMU_FW_PROJECT_U9500_MBL:
return "U9500 MBL";
case PRCMU_FW_PROJECT_U8500_MBL:
return "U8500 MBL";
case PRCMU_FW_PROJECT_U8500_MBL2:
return "U8500 MBL2";
case PRCMU_FW_PROJECT_U8520:
return "U8520 MBL";
case PRCMU_FW_PROJECT_U8420:
return "U8420";
case PRCMU_FW_PROJECT_U9540:
return "U9540";
case PRCMU_FW_PROJECT_A9420:
return "A9420";
case PRCMU_FW_PROJECT_L8540:
return "L8540";
case PRCMU_FW_PROJECT_L8580:
return "L8580";
default:
return "Unknown";
}
}
static int db8500_irq_map(struct irq_domain *d, unsigned int virq,
irq_hw_number_t hwirq)
{
irq_set_chip_and_handler(virq, &prcmu_irq_chip,
handle_simple_irq);
set_irq_flags(virq, IRQF_VALID);
return 0;
}
static struct irq_domain_ops db8500_irq_ops = {
.map = db8500_irq_map,
.xlate = irq_domain_xlate_twocell,
};
static int db8500_irq_init(struct device_node *np, int irq_base)
{
int i;
/* In the device tree case, just take some IRQs */
if (np)
irq_base = 0;
db8500_irq_domain = irq_domain_add_simple(
np, NUM_PRCMU_WAKEUPS, irq_base,
&db8500_irq_ops, NULL);
if (!db8500_irq_domain) {
pr_err("Failed to create irqdomain\n");
return -ENOSYS;
}
/* All wakeups will be used, so create mappings for all */
for (i = 0; i < NUM_PRCMU_WAKEUPS; i++)
irq_create_mapping(db8500_irq_domain, i);
return 0;
}
static void dbx500_fw_version_init(struct platform_device *pdev,
u32 version_offset)
{
struct resource *res;
void __iomem *tcpm_base;
u32 version;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"prcmu-tcpm");
if (!res) {
dev_err(&pdev->dev,
"Error: no prcmu tcpm memory region provided\n");
return;
}
tcpm_base = ioremap(res->start, resource_size(res));
if (!tcpm_base) {
dev_err(&pdev->dev, "no prcmu tcpm mem region provided\n");
return;
}
version = readl(tcpm_base + version_offset);
fw_info.version.project = (version & 0xFF);
fw_info.version.api_version = (version >> 8) & 0xFF;
fw_info.version.func_version = (version >> 16) & 0xFF;
fw_info.version.errata = (version >> 24) & 0xFF;
strncpy(fw_info.version.project_name,
fw_project_name(fw_info.version.project),
PRCMU_FW_PROJECT_NAME_LEN);
fw_info.valid = true;
pr_info("PRCMU firmware: %s(%d), version %d.%d.%d\n",
fw_info.version.project_name,
fw_info.version.project,
fw_info.version.api_version,
fw_info.version.func_version,
fw_info.version.errata);
iounmap(tcpm_base);
}
void __init db8500_prcmu_early_init(u32 phy_base, u32 size)
{
/*
* This is a temporary remap to bring up the clocks. It is
* subsequently replaces with a real remap. After the merge of
* the mailbox subsystem all of this early code goes away, and the
* clock driver can probe independently. An early initcall will
* still be needed, but it can be diverted into drivers/clk/ux500.
*/
prcmu_base = ioremap(phy_base, size);
if (!prcmu_base)
pr_err("%s: ioremap() of prcmu registers failed!\n", __func__);
spin_lock_init(&mb0_transfer.lock);
spin_lock_init(&mb0_transfer.dbb_irqs_lock);
mutex_init(&mb0_transfer.ac_wake_lock);
init_completion(&mb0_transfer.ac_wake_work);
mutex_init(&mb1_transfer.lock);
init_completion(&mb1_transfer.work);
mb1_transfer.ape_opp = APE_NO_CHANGE;
mutex_init(&mb2_transfer.lock);
init_completion(&mb2_transfer.work);
spin_lock_init(&mb2_transfer.auto_pm_lock);
spin_lock_init(&mb3_transfer.lock);
mutex_init(&mb3_transfer.sysclk_lock);
init_completion(&mb3_transfer.sysclk_work);
mutex_init(&mb4_transfer.lock);
init_completion(&mb4_transfer.work);
mutex_init(&mb5_transfer.lock);
init_completion(&mb5_transfer.work);
INIT_WORK(&mb0_transfer.mask_work, prcmu_mask_work);
}
static void __init init_prcm_registers(void)
{
u32 val;
val = readl(PRCM_A9PL_FORCE_CLKEN);
val &= ~(PRCM_A9PL_FORCE_CLKEN_PRCM_A9PL_FORCE_CLKEN |
PRCM_A9PL_FORCE_CLKEN_PRCM_A9AXI_FORCE_CLKEN);
writel(val, (PRCM_A9PL_FORCE_CLKEN));
}
/*
* Power domain switches (ePODs) modeled as regulators for the DB8500 SoC
*/
static struct regulator_consumer_supply db8500_vape_consumers[] = {
REGULATOR_SUPPLY("v-ape", NULL),
REGULATOR_SUPPLY("v-i2c", "nmk-i2c.0"),
REGULATOR_SUPPLY("v-i2c", "nmk-i2c.1"),
REGULATOR_SUPPLY("v-i2c", "nmk-i2c.2"),
REGULATOR_SUPPLY("v-i2c", "nmk-i2c.3"),
REGULATOR_SUPPLY("v-i2c", "nmk-i2c.4"),
/* "v-mmc" changed to "vcore" in the mainline kernel */
REGULATOR_SUPPLY("vcore", "sdi0"),
REGULATOR_SUPPLY("vcore", "sdi1"),
REGULATOR_SUPPLY("vcore", "sdi2"),
REGULATOR_SUPPLY("vcore", "sdi3"),
REGULATOR_SUPPLY("vcore", "sdi4"),
REGULATOR_SUPPLY("v-dma", "dma40.0"),
REGULATOR_SUPPLY("v-ape", "ab8500-usb.0"),
/* "v-uart" changed to "vcore" in the mainline kernel */
REGULATOR_SUPPLY("vcore", "uart0"),
REGULATOR_SUPPLY("vcore", "uart1"),
REGULATOR_SUPPLY("vcore", "uart2"),
REGULATOR_SUPPLY("v-ape", "nmk-ske-keypad.0"),
REGULATOR_SUPPLY("v-hsi", "ste_hsi.0"),
REGULATOR_SUPPLY("vddvario", "smsc911x.0"),
};
static struct regulator_consumer_supply db8500_vsmps2_consumers[] = {
REGULATOR_SUPPLY("musb_1v8", "ab8500-usb.0"),
/* AV8100 regulator */
REGULATOR_SUPPLY("hdmi_1v8", "0-0070"),
};
static struct regulator_consumer_supply db8500_b2r2_mcde_consumers[] = {
REGULATOR_SUPPLY("vsupply", "b2r2_bus"),
REGULATOR_SUPPLY("vsupply", "mcde"),
};
/* SVA MMDSP regulator switch */
static struct regulator_consumer_supply db8500_svammdsp_consumers[] = {
REGULATOR_SUPPLY("sva-mmdsp", "cm_control"),
};
/* SVA pipe regulator switch */
static struct regulator_consumer_supply db8500_svapipe_consumers[] = {
REGULATOR_SUPPLY("sva-pipe", "cm_control"),
};
/* SIA MMDSP regulator switch */
static struct regulator_consumer_supply db8500_siammdsp_consumers[] = {
REGULATOR_SUPPLY("sia-mmdsp", "cm_control"),
};
/* SIA pipe regulator switch */
static struct regulator_consumer_supply db8500_siapipe_consumers[] = {
REGULATOR_SUPPLY("sia-pipe", "cm_control"),
};
static struct regulator_consumer_supply db8500_sga_consumers[] = {
REGULATOR_SUPPLY("v-mali", NULL),
};
/* ESRAM1 and 2 regulator switch */
static struct regulator_consumer_supply db8500_esram12_consumers[] = {
REGULATOR_SUPPLY("esram12", "cm_control"),
};
/* ESRAM3 and 4 regulator switch */
static struct regulator_consumer_supply db8500_esram34_consumers[] = {
REGULATOR_SUPPLY("v-esram34", "mcde"),
REGULATOR_SUPPLY("esram34", "cm_control"),
REGULATOR_SUPPLY("lcla_esram", "dma40.0"),
};
static struct regulator_init_data db8500_regulators[DB8500_NUM_REGULATORS] = {
[DB8500_REGULATOR_VAPE] = {
.constraints = {
.name = "db8500-vape",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.always_on = true,
},
.consumer_supplies = db8500_vape_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_vape_consumers),
},
[DB8500_REGULATOR_VARM] = {
.constraints = {
.name = "db8500-varm",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_VMODEM] = {
.constraints = {
.name = "db8500-vmodem",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_VPLL] = {
.constraints = {
.name = "db8500-vpll",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_VSMPS1] = {
.constraints = {
.name = "db8500-vsmps1",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_VSMPS2] = {
.constraints = {
.name = "db8500-vsmps2",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_vsmps2_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_vsmps2_consumers),
},
[DB8500_REGULATOR_VSMPS3] = {
.constraints = {
.name = "db8500-vsmps3",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_VRF1] = {
.constraints = {
.name = "db8500-vrf1",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_SWITCH_SVAMMDSP] = {
/* dependency to u8500-vape is handled outside regulator framework */
.constraints = {
.name = "db8500-sva-mmdsp",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_svammdsp_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_svammdsp_consumers),
},
[DB8500_REGULATOR_SWITCH_SVAMMDSPRET] = {
.constraints = {
/* "ret" means "retention" */
.name = "db8500-sva-mmdsp-ret",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_SWITCH_SVAPIPE] = {
/* dependency to u8500-vape is handled outside regulator framework */
.constraints = {
.name = "db8500-sva-pipe",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_svapipe_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_svapipe_consumers),
},
[DB8500_REGULATOR_SWITCH_SIAMMDSP] = {
/* dependency to u8500-vape is handled outside regulator framework */
.constraints = {
.name = "db8500-sia-mmdsp",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_siammdsp_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_siammdsp_consumers),
},
[DB8500_REGULATOR_SWITCH_SIAMMDSPRET] = {
.constraints = {
.name = "db8500-sia-mmdsp-ret",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_SWITCH_SIAPIPE] = {
/* dependency to u8500-vape is handled outside regulator framework */
.constraints = {
.name = "db8500-sia-pipe",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_siapipe_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_siapipe_consumers),
},
[DB8500_REGULATOR_SWITCH_SGA] = {
.supply_regulator = "db8500-vape",
.constraints = {
.name = "db8500-sga",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_sga_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_sga_consumers),
},
[DB8500_REGULATOR_SWITCH_B2R2_MCDE] = {
.supply_regulator = "db8500-vape",
.constraints = {
.name = "db8500-b2r2-mcde",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_b2r2_mcde_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_b2r2_mcde_consumers),
},
[DB8500_REGULATOR_SWITCH_ESRAM12] = {
/*
* esram12 is set in retention and supplied by Vsafe when Vape is off,
* no need to hold Vape
*/
.constraints = {
.name = "db8500-esram12",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_esram12_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_esram12_consumers),
},
[DB8500_REGULATOR_SWITCH_ESRAM12RET] = {
.constraints = {
.name = "db8500-esram12-ret",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
[DB8500_REGULATOR_SWITCH_ESRAM34] = {
/*
* esram34 is set in retention and supplied by Vsafe when Vape is off,
* no need to hold Vape
*/
.constraints = {
.name = "db8500-esram34",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = db8500_esram34_consumers,
.num_consumer_supplies = ARRAY_SIZE(db8500_esram34_consumers),
},
[DB8500_REGULATOR_SWITCH_ESRAM34RET] = {
.constraints = {
.name = "db8500-esram34-ret",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
},
};
static struct ux500_wdt_data db8500_wdt_pdata = {
.timeout = 600, /* 10 minutes */
.has_28_bits_resolution = true,
};
/*
* Thermal Sensor
*/
static struct resource db8500_thsens_resources[] = {
{
.name = "IRQ_HOTMON_LOW",
.start = IRQ_PRCMU_HOTMON_LOW,
.end = IRQ_PRCMU_HOTMON_LOW,
.flags = IORESOURCE_IRQ,
},
{
.name = "IRQ_HOTMON_HIGH",
.start = IRQ_PRCMU_HOTMON_HIGH,
.end = IRQ_PRCMU_HOTMON_HIGH,
.flags = IORESOURCE_IRQ,
},
};
static struct db8500_thsens_platform_data db8500_thsens_data = {
.trip_points[0] = {
.temp = 70000,
.type = THERMAL_TRIP_ACTIVE,
.cdev_name = {
[0] = "thermal-cpufreq-0",
},
},
.trip_points[1] = {
.temp = 75000,
.type = THERMAL_TRIP_ACTIVE,
.cdev_name = {
[0] = "thermal-cpufreq-0",
},
},
.trip_points[2] = {
.temp = 80000,
.type = THERMAL_TRIP_ACTIVE,
.cdev_name = {
[0] = "thermal-cpufreq-0",
},
},
.trip_points[3] = {
.temp = 85000,
.type = THERMAL_TRIP_CRITICAL,
},
.num_trips = 4,
};
static struct mfd_cell common_prcmu_devs[] = {
{
.name = "ux500_wdt",
.platform_data = &db8500_wdt_pdata,
.pdata_size = sizeof(db8500_wdt_pdata),
.id = -1,
},
};
static struct mfd_cell db8500_prcmu_devs[] = {
{
.name = "db8500-prcmu-regulators",
.of_compatible = "stericsson,db8500-prcmu-regulator",
.platform_data = &db8500_regulators,
.pdata_size = sizeof(db8500_regulators),
},
{
.name = "cpufreq-ux500",
.of_compatible = "stericsson,cpufreq-ux500",
.platform_data = &db8500_cpufreq_table,
.pdata_size = sizeof(db8500_cpufreq_table),
},
{
.name = "db8500-thermal",
.num_resources = ARRAY_SIZE(db8500_thsens_resources),
.resources = db8500_thsens_resources,
.platform_data = &db8500_thsens_data,
.pdata_size = sizeof(db8500_thsens_data),
},
};
static void db8500_prcmu_update_cpufreq(void)
{
if (prcmu_has_arm_maxopp()) {
db8500_cpufreq_table[3].frequency = 1000000;
db8500_cpufreq_table[3].driver_data = ARM_MAX_OPP;
}
}
static int db8500_prcmu_register_ab8500(struct device *parent,
struct ab8500_platform_data *pdata,
int irq)
{
struct resource ab8500_resource = DEFINE_RES_IRQ(irq);
struct mfd_cell ab8500_cell = {
.name = "ab8500-core",
.of_compatible = "stericsson,ab8500",
.id = AB8500_VERSION_AB8500,
.platform_data = pdata,
.pdata_size = sizeof(struct ab8500_platform_data),
.resources = &ab8500_resource,
.num_resources = 1,
};
return mfd_add_devices(parent, 0, &ab8500_cell, 1, NULL, 0, NULL);
}
/**
* prcmu_fw_init - arch init call for the Linux PRCMU fw init logic
*
*/
static int db8500_prcmu_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct prcmu_pdata *pdata = dev_get_platdata(&pdev->dev);
int irq = 0, err = 0;
struct resource *res;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "prcmu");
if (!res) {
dev_err(&pdev->dev, "no prcmu memory region provided\n");
return -ENOENT;
}
prcmu_base = devm_ioremap(&pdev->dev, res->start, resource_size(res));
if (!prcmu_base) {
dev_err(&pdev->dev,
"failed to ioremap prcmu register memory\n");
return -ENOENT;
}
init_prcm_registers();
dbx500_fw_version_init(pdev, pdata->version_offset);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "prcmu-tcdm");
if (!res) {
dev_err(&pdev->dev, "no prcmu tcdm region provided\n");
return -ENOENT;
}
tcdm_base = devm_ioremap(&pdev->dev, res->start,
resource_size(res));
/* Clean up the mailbox interrupts after pre-kernel code. */
writel(ALL_MBOX_BITS, PRCM_ARM_IT1_CLR);
irq = platform_get_irq(pdev, 0);
if (irq <= 0) {
dev_err(&pdev->dev, "no prcmu irq provided\n");
return -ENOENT;
}
err = request_threaded_irq(irq, prcmu_irq_handler,
prcmu_irq_thread_fn, IRQF_NO_SUSPEND, "prcmu", NULL);
if (err < 0) {
pr_err("prcmu: Failed to allocate IRQ_DB8500_PRCMU1.\n");
err = -EBUSY;
goto no_irq_return;
}
db8500_irq_init(np, pdata->irq_base);
prcmu_config_esram0_deep_sleep(ESRAM0_DEEP_SLEEP_STATE_RET);
db8500_prcmu_update_cpufreq();
err = mfd_add_devices(&pdev->dev, 0, common_prcmu_devs,
ARRAY_SIZE(common_prcmu_devs), NULL, 0, db8500_irq_domain);
if (err) {
pr_err("prcmu: Failed to add subdevices\n");
return err;
}
/* TODO: Remove restriction when clk definitions are available. */
if (!of_machine_is_compatible("st-ericsson,u8540")) {
err = mfd_add_devices(&pdev->dev, 0, db8500_prcmu_devs,
ARRAY_SIZE(db8500_prcmu_devs), NULL, 0,
db8500_irq_domain);
if (err) {
mfd_remove_devices(&pdev->dev);
pr_err("prcmu: Failed to add subdevices\n");
goto no_irq_return;
}
}
err = db8500_prcmu_register_ab8500(&pdev->dev, pdata->ab_platdata,
pdata->ab_irq);
if (err) {
mfd_remove_devices(&pdev->dev);
pr_err("prcmu: Failed to add ab8500 subdevice\n");
goto no_irq_return;
}
pr_info("DB8500 PRCMU initialized\n");
no_irq_return:
return err;
}
static const struct of_device_id db8500_prcmu_match[] = {
{ .compatible = "stericsson,db8500-prcmu"},
{ },
};
static struct platform_driver db8500_prcmu_driver = {
.driver = {
.name = "db8500-prcmu",
.owner = THIS_MODULE,
.of_match_table = db8500_prcmu_match,
},
.probe = db8500_prcmu_probe,
};
static int __init db8500_prcmu_init(void)
{
return platform_driver_register(&db8500_prcmu_driver);
}
core_initcall(db8500_prcmu_init);
MODULE_AUTHOR("Mattias Nilsson <mattias.i.nilsson@stericsson.com>");
MODULE_DESCRIPTION("DB8500 PRCM Unit driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
daeiron/kenzo_caf_kernel | fs/jfs/jfs_logmgr.c | 2185 | 60889 | /*
* Copyright (C) International Business Machines Corp., 2000-2004
* Portions Copyright (C) Christoph Hellwig, 2001-2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* jfs_logmgr.c: log manager
*
* for related information, see transaction manager (jfs_txnmgr.c), and
* recovery manager (jfs_logredo.c).
*
* note: for detail, RTFS.
*
* log buffer manager:
* special purpose buffer manager supporting log i/o requirements.
* per log serial pageout of logpage
* queuing i/o requests and redrive i/o at iodone
* maintain current logpage buffer
* no caching since append only
* appropriate jfs buffer cache buffers as needed
*
* group commit:
* transactions which wrote COMMIT records in the same in-memory
* log page during the pageout of previous/current log page(s) are
* committed together by the pageout of the page.
*
* TBD lazy commit:
* transactions are committed asynchronously when the log page
* containing it COMMIT is paged out when it becomes full;
*
* serialization:
* . a per log lock serialize log write.
* . a per log lock serialize group commit.
* . a per log lock serialize log open/close;
*
* TBD log integrity:
* careful-write (ping-pong) of last logpage to recover from crash
* in overwrite.
* detection of split (out-of-order) write of physical sectors
* of last logpage via timestamp at end of each sector
* with its mirror data array at trailer).
*
* alternatives:
* lsn - 64-bit monotonically increasing integer vs
* 32-bit lspn and page eor.
*/
#include <linux/fs.h>
#include <linux/blkdev.h>
#include <linux/interrupt.h>
#include <linux/completion.h>
#include <linux/kthread.h>
#include <linux/buffer_head.h> /* for sync_blockdev() */
#include <linux/bio.h>
#include <linux/freezer.h>
#include <linux/export.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include "jfs_incore.h"
#include "jfs_filsys.h"
#include "jfs_metapage.h"
#include "jfs_superblock.h"
#include "jfs_txnmgr.h"
#include "jfs_debug.h"
/*
* lbuf's ready to be redriven. Protected by log_redrive_lock (jfsIO thread)
*/
static struct lbuf *log_redrive_list;
static DEFINE_SPINLOCK(log_redrive_lock);
/*
* log read/write serialization (per log)
*/
#define LOG_LOCK_INIT(log) mutex_init(&(log)->loglock)
#define LOG_LOCK(log) mutex_lock(&((log)->loglock))
#define LOG_UNLOCK(log) mutex_unlock(&((log)->loglock))
/*
* log group commit serialization (per log)
*/
#define LOGGC_LOCK_INIT(log) spin_lock_init(&(log)->gclock)
#define LOGGC_LOCK(log) spin_lock_irq(&(log)->gclock)
#define LOGGC_UNLOCK(log) spin_unlock_irq(&(log)->gclock)
#define LOGGC_WAKEUP(tblk) wake_up_all(&(tblk)->gcwait)
/*
* log sync serialization (per log)
*/
#define LOGSYNC_DELTA(logsize) min((logsize)/8, 128*LOGPSIZE)
#define LOGSYNC_BARRIER(logsize) ((logsize)/4)
/*
#define LOGSYNC_DELTA(logsize) min((logsize)/4, 256*LOGPSIZE)
#define LOGSYNC_BARRIER(logsize) ((logsize)/2)
*/
/*
* log buffer cache synchronization
*/
static DEFINE_SPINLOCK(jfsLCacheLock);
#define LCACHE_LOCK(flags) spin_lock_irqsave(&jfsLCacheLock, flags)
#define LCACHE_UNLOCK(flags) spin_unlock_irqrestore(&jfsLCacheLock, flags)
/*
* See __SLEEP_COND in jfs_locks.h
*/
#define LCACHE_SLEEP_COND(wq, cond, flags) \
do { \
if (cond) \
break; \
__SLEEP_COND(wq, cond, LCACHE_LOCK(flags), LCACHE_UNLOCK(flags)); \
} while (0)
#define LCACHE_WAKEUP(event) wake_up(event)
/*
* lbuf buffer cache (lCache) control
*/
/* log buffer manager pageout control (cumulative, inclusive) */
#define lbmREAD 0x0001
#define lbmWRITE 0x0002 /* enqueue at tail of write queue;
* init pageout if at head of queue;
*/
#define lbmRELEASE 0x0004 /* remove from write queue
* at completion of pageout;
* do not free/recycle it yet:
* caller will free it;
*/
#define lbmSYNC 0x0008 /* do not return to freelist
* when removed from write queue;
*/
#define lbmFREE 0x0010 /* return to freelist
* at completion of pageout;
* the buffer may be recycled;
*/
#define lbmDONE 0x0020
#define lbmERROR 0x0040
#define lbmGC 0x0080 /* lbmIODone to perform post-GC processing
* of log page
*/
#define lbmDIRECT 0x0100
/*
* Global list of active external journals
*/
static LIST_HEAD(jfs_external_logs);
static struct jfs_log *dummy_log = NULL;
static DEFINE_MUTEX(jfs_log_mutex);
/*
* forward references
*/
static int lmWriteRecord(struct jfs_log * log, struct tblock * tblk,
struct lrd * lrd, struct tlock * tlck);
static int lmNextPage(struct jfs_log * log);
static int lmLogFileSystem(struct jfs_log * log, struct jfs_sb_info *sbi,
int activate);
static int open_inline_log(struct super_block *sb);
static int open_dummy_log(struct super_block *sb);
static int lbmLogInit(struct jfs_log * log);
static void lbmLogShutdown(struct jfs_log * log);
static struct lbuf *lbmAllocate(struct jfs_log * log, int);
static void lbmFree(struct lbuf * bp);
static void lbmfree(struct lbuf * bp);
static int lbmRead(struct jfs_log * log, int pn, struct lbuf ** bpp);
static void lbmWrite(struct jfs_log * log, struct lbuf * bp, int flag, int cant_block);
static void lbmDirectWrite(struct jfs_log * log, struct lbuf * bp, int flag);
static int lbmIOWait(struct lbuf * bp, int flag);
static bio_end_io_t lbmIODone;
static void lbmStartIO(struct lbuf * bp);
static void lmGCwrite(struct jfs_log * log, int cant_block);
static int lmLogSync(struct jfs_log * log, int hard_sync);
/*
* statistics
*/
#ifdef CONFIG_JFS_STATISTICS
static struct lmStat {
uint commit; /* # of commit */
uint pagedone; /* # of page written */
uint submitted; /* # of pages submitted */
uint full_page; /* # of full pages submitted */
uint partial_page; /* # of partial pages submitted */
} lmStat;
#endif
static void write_special_inodes(struct jfs_log *log,
int (*writer)(struct address_space *))
{
struct jfs_sb_info *sbi;
list_for_each_entry(sbi, &log->sb_list, log_list) {
writer(sbi->ipbmap->i_mapping);
writer(sbi->ipimap->i_mapping);
writer(sbi->direct_inode->i_mapping);
}
}
/*
* NAME: lmLog()
*
* FUNCTION: write a log record;
*
* PARAMETER:
*
* RETURN: lsn - offset to the next log record to write (end-of-log);
* -1 - error;
*
* note: todo: log error handler
*/
int lmLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
int lsn;
int diffp, difft;
struct metapage *mp = NULL;
unsigned long flags;
jfs_info("lmLog: log:0x%p tblk:0x%p, lrd:0x%p tlck:0x%p",
log, tblk, lrd, tlck);
LOG_LOCK(log);
/* log by (out-of-transaction) JFS ? */
if (tblk == NULL)
goto writeRecord;
/* log from page ? */
if (tlck == NULL ||
tlck->type & tlckBTROOT || (mp = tlck->mp) == NULL)
goto writeRecord;
/*
* initialize/update page/transaction recovery lsn
*/
lsn = log->lsn;
LOGSYNC_LOCK(log, flags);
/*
* initialize page lsn if first log write of the page
*/
if (mp->lsn == 0) {
mp->log = log;
mp->lsn = lsn;
log->count++;
/* insert page at tail of logsynclist */
list_add_tail(&mp->synclist, &log->synclist);
}
/*
* initialize/update lsn of tblock of the page
*
* transaction inherits oldest lsn of pages associated
* with allocation/deallocation of resources (their
* log records are used to reconstruct allocation map
* at recovery time: inode for inode allocation map,
* B+-tree index of extent descriptors for block
* allocation map);
* allocation map pages inherit transaction lsn at
* commit time to allow forwarding log syncpt past log
* records associated with allocation/deallocation of
* resources only after persistent map of these map pages
* have been updated and propagated to home.
*/
/*
* initialize transaction lsn:
*/
if (tblk->lsn == 0) {
/* inherit lsn of its first page logged */
tblk->lsn = mp->lsn;
log->count++;
/* insert tblock after the page on logsynclist */
list_add(&tblk->synclist, &mp->synclist);
}
/*
* update transaction lsn:
*/
else {
/* inherit oldest/smallest lsn of page */
logdiff(diffp, mp->lsn, log);
logdiff(difft, tblk->lsn, log);
if (diffp < difft) {
/* update tblock lsn with page lsn */
tblk->lsn = mp->lsn;
/* move tblock after page on logsynclist */
list_move(&tblk->synclist, &mp->synclist);
}
}
LOGSYNC_UNLOCK(log, flags);
/*
* write the log record
*/
writeRecord:
lsn = lmWriteRecord(log, tblk, lrd, tlck);
/*
* forward log syncpt if log reached next syncpt trigger
*/
logdiff(diffp, lsn, log);
if (diffp >= log->nextsync)
lsn = lmLogSync(log, 0);
/* update end-of-log lsn */
log->lsn = lsn;
LOG_UNLOCK(log);
/* return end-of-log address */
return lsn;
}
/*
* NAME: lmWriteRecord()
*
* FUNCTION: move the log record to current log page
*
* PARAMETER: cd - commit descriptor
*
* RETURN: end-of-log address
*
* serialization: LOG_LOCK() held on entry/exit
*/
static int
lmWriteRecord(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
int lsn = 0; /* end-of-log address */
struct lbuf *bp; /* dst log page buffer */
struct logpage *lp; /* dst log page */
caddr_t dst; /* destination address in log page */
int dstoffset; /* end-of-log offset in log page */
int freespace; /* free space in log page */
caddr_t p; /* src meta-data page */
caddr_t src;
int srclen;
int nbytes; /* number of bytes to move */
int i;
int len;
struct linelock *linelock;
struct lv *lv;
struct lvd *lvd;
int l2linesize;
len = 0;
/* retrieve destination log page to write */
bp = (struct lbuf *) log->bp;
lp = (struct logpage *) bp->l_ldata;
dstoffset = log->eor;
/* any log data to write ? */
if (tlck == NULL)
goto moveLrd;
/*
* move log record data
*/
/* retrieve source meta-data page to log */
if (tlck->flag & tlckPAGELOCK) {
p = (caddr_t) (tlck->mp->data);
linelock = (struct linelock *) & tlck->lock;
}
/* retrieve source in-memory inode to log */
else if (tlck->flag & tlckINODELOCK) {
if (tlck->type & tlckDTREE)
p = (caddr_t) &JFS_IP(tlck->ip)->i_dtroot;
else
p = (caddr_t) &JFS_IP(tlck->ip)->i_xtroot;
linelock = (struct linelock *) & tlck->lock;
}
#ifdef _JFS_WIP
else if (tlck->flag & tlckINLINELOCK) {
inlinelock = (struct inlinelock *) & tlck;
p = (caddr_t) & inlinelock->pxd;
linelock = (struct linelock *) & tlck;
}
#endif /* _JFS_WIP */
else {
jfs_err("lmWriteRecord: UFO tlck:0x%p", tlck);
return 0; /* Probably should trap */
}
l2linesize = linelock->l2linesize;
moveData:
ASSERT(linelock->index <= linelock->maxcnt);
lv = linelock->lv;
for (i = 0; i < linelock->index; i++, lv++) {
if (lv->length == 0)
continue;
/* is page full ? */
if (dstoffset >= LOGPSIZE - LOGPTLRSIZE) {
/* page become full: move on to next page */
lmNextPage(log);
bp = log->bp;
lp = (struct logpage *) bp->l_ldata;
dstoffset = LOGPHDRSIZE;
}
/*
* move log vector data
*/
src = (u8 *) p + (lv->offset << l2linesize);
srclen = lv->length << l2linesize;
len += srclen;
while (srclen > 0) {
freespace = (LOGPSIZE - LOGPTLRSIZE) - dstoffset;
nbytes = min(freespace, srclen);
dst = (caddr_t) lp + dstoffset;
memcpy(dst, src, nbytes);
dstoffset += nbytes;
/* is page not full ? */
if (dstoffset < LOGPSIZE - LOGPTLRSIZE)
break;
/* page become full: move on to next page */
lmNextPage(log);
bp = (struct lbuf *) log->bp;
lp = (struct logpage *) bp->l_ldata;
dstoffset = LOGPHDRSIZE;
srclen -= nbytes;
src += nbytes;
}
/*
* move log vector descriptor
*/
len += 4;
lvd = (struct lvd *) ((caddr_t) lp + dstoffset);
lvd->offset = cpu_to_le16(lv->offset);
lvd->length = cpu_to_le16(lv->length);
dstoffset += 4;
jfs_info("lmWriteRecord: lv offset:%d length:%d",
lv->offset, lv->length);
}
if ((i = linelock->next)) {
linelock = (struct linelock *) lid_to_tlock(i);
goto moveData;
}
/*
* move log record descriptor
*/
moveLrd:
lrd->length = cpu_to_le16(len);
src = (caddr_t) lrd;
srclen = LOGRDSIZE;
while (srclen > 0) {
freespace = (LOGPSIZE - LOGPTLRSIZE) - dstoffset;
nbytes = min(freespace, srclen);
dst = (caddr_t) lp + dstoffset;
memcpy(dst, src, nbytes);
dstoffset += nbytes;
srclen -= nbytes;
/* are there more to move than freespace of page ? */
if (srclen)
goto pageFull;
/*
* end of log record descriptor
*/
/* update last log record eor */
log->eor = dstoffset;
bp->l_eor = dstoffset;
lsn = (log->page << L2LOGPSIZE) + dstoffset;
if (lrd->type & cpu_to_le16(LOG_COMMIT)) {
tblk->clsn = lsn;
jfs_info("wr: tclsn:0x%x, beor:0x%x", tblk->clsn,
bp->l_eor);
INCREMENT(lmStat.commit); /* # of commit */
/*
* enqueue tblock for group commit:
*
* enqueue tblock of non-trivial/synchronous COMMIT
* at tail of group commit queue
* (trivial/asynchronous COMMITs are ignored by
* group commit.)
*/
LOGGC_LOCK(log);
/* init tblock gc state */
tblk->flag = tblkGC_QUEUE;
tblk->bp = log->bp;
tblk->pn = log->page;
tblk->eor = log->eor;
/* enqueue transaction to commit queue */
list_add_tail(&tblk->cqueue, &log->cqueue);
LOGGC_UNLOCK(log);
}
jfs_info("lmWriteRecord: lrd:0x%04x bp:0x%p pn:%d eor:0x%x",
le16_to_cpu(lrd->type), log->bp, log->page, dstoffset);
/* page not full ? */
if (dstoffset < LOGPSIZE - LOGPTLRSIZE)
return lsn;
pageFull:
/* page become full: move on to next page */
lmNextPage(log);
bp = (struct lbuf *) log->bp;
lp = (struct logpage *) bp->l_ldata;
dstoffset = LOGPHDRSIZE;
src += nbytes;
}
return lsn;
}
/*
* NAME: lmNextPage()
*
* FUNCTION: write current page and allocate next page.
*
* PARAMETER: log
*
* RETURN: 0
*
* serialization: LOG_LOCK() held on entry/exit
*/
static int lmNextPage(struct jfs_log * log)
{
struct logpage *lp;
int lspn; /* log sequence page number */
int pn; /* current page number */
struct lbuf *bp;
struct lbuf *nextbp;
struct tblock *tblk;
/* get current log page number and log sequence page number */
pn = log->page;
bp = log->bp;
lp = (struct logpage *) bp->l_ldata;
lspn = le32_to_cpu(lp->h.page);
LOGGC_LOCK(log);
/*
* write or queue the full page at the tail of write queue
*/
/* get the tail tblk on commit queue */
if (list_empty(&log->cqueue))
tblk = NULL;
else
tblk = list_entry(log->cqueue.prev, struct tblock, cqueue);
/* every tblk who has COMMIT record on the current page,
* and has not been committed, must be on commit queue
* since tblk is queued at commit queueu at the time
* of writing its COMMIT record on the page before
* page becomes full (even though the tblk thread
* who wrote COMMIT record may have been suspended
* currently);
*/
/* is page bound with outstanding tail tblk ? */
if (tblk && tblk->pn == pn) {
/* mark tblk for end-of-page */
tblk->flag |= tblkGC_EOP;
if (log->cflag & logGC_PAGEOUT) {
/* if page is not already on write queue,
* just enqueue (no lbmWRITE to prevent redrive)
* buffer to wqueue to ensure correct serial order
* of the pages since log pages will be added
* continuously
*/
if (bp->l_wqnext == NULL)
lbmWrite(log, bp, 0, 0);
} else {
/*
* No current GC leader, initiate group commit
*/
log->cflag |= logGC_PAGEOUT;
lmGCwrite(log, 0);
}
}
/* page is not bound with outstanding tblk:
* init write or mark it to be redriven (lbmWRITE)
*/
else {
/* finalize the page */
bp->l_ceor = bp->l_eor;
lp->h.eor = lp->t.eor = cpu_to_le16(bp->l_ceor);
lbmWrite(log, bp, lbmWRITE | lbmRELEASE | lbmFREE, 0);
}
LOGGC_UNLOCK(log);
/*
* allocate/initialize next page
*/
/* if log wraps, the first data page of log is 2
* (0 never used, 1 is superblock).
*/
log->page = (pn == log->size - 1) ? 2 : pn + 1;
log->eor = LOGPHDRSIZE; /* ? valid page empty/full at logRedo() */
/* allocate/initialize next log page buffer */
nextbp = lbmAllocate(log, log->page);
nextbp->l_eor = log->eor;
log->bp = nextbp;
/* initialize next log page */
lp = (struct logpage *) nextbp->l_ldata;
lp->h.page = lp->t.page = cpu_to_le32(lspn + 1);
lp->h.eor = lp->t.eor = cpu_to_le16(LOGPHDRSIZE);
return 0;
}
/*
* NAME: lmGroupCommit()
*
* FUNCTION: group commit
* initiate pageout of the pages with COMMIT in the order of
* page number - redrive pageout of the page at the head of
* pageout queue until full page has been written.
*
* RETURN:
*
* NOTE:
* LOGGC_LOCK serializes log group commit queue, and
* transaction blocks on the commit queue.
* N.B. LOG_LOCK is NOT held during lmGroupCommit().
*/
int lmGroupCommit(struct jfs_log * log, struct tblock * tblk)
{
int rc = 0;
LOGGC_LOCK(log);
/* group committed already ? */
if (tblk->flag & tblkGC_COMMITTED) {
if (tblk->flag & tblkGC_ERROR)
rc = -EIO;
LOGGC_UNLOCK(log);
return rc;
}
jfs_info("lmGroup Commit: tblk = 0x%p, gcrtc = %d", tblk, log->gcrtc);
if (tblk->xflag & COMMIT_LAZY)
tblk->flag |= tblkGC_LAZY;
if ((!(log->cflag & logGC_PAGEOUT)) && (!list_empty(&log->cqueue)) &&
(!(tblk->xflag & COMMIT_LAZY) || test_bit(log_FLUSH, &log->flag)
|| jfs_tlocks_low)) {
/*
* No pageout in progress
*
* start group commit as its group leader.
*/
log->cflag |= logGC_PAGEOUT;
lmGCwrite(log, 0);
}
if (tblk->xflag & COMMIT_LAZY) {
/*
* Lazy transactions can leave now
*/
LOGGC_UNLOCK(log);
return 0;
}
/* lmGCwrite gives up LOGGC_LOCK, check again */
if (tblk->flag & tblkGC_COMMITTED) {
if (tblk->flag & tblkGC_ERROR)
rc = -EIO;
LOGGC_UNLOCK(log);
return rc;
}
/* upcount transaction waiting for completion
*/
log->gcrtc++;
tblk->flag |= tblkGC_READY;
__SLEEP_COND(tblk->gcwait, (tblk->flag & tblkGC_COMMITTED),
LOGGC_LOCK(log), LOGGC_UNLOCK(log));
/* removed from commit queue */
if (tblk->flag & tblkGC_ERROR)
rc = -EIO;
LOGGC_UNLOCK(log);
return rc;
}
/*
* NAME: lmGCwrite()
*
* FUNCTION: group commit write
* initiate write of log page, building a group of all transactions
* with commit records on that page.
*
* RETURN: None
*
* NOTE:
* LOGGC_LOCK must be held by caller.
* N.B. LOG_LOCK is NOT held during lmGroupCommit().
*/
static void lmGCwrite(struct jfs_log * log, int cant_write)
{
struct lbuf *bp;
struct logpage *lp;
int gcpn; /* group commit page number */
struct tblock *tblk;
struct tblock *xtblk = NULL;
/*
* build the commit group of a log page
*
* scan commit queue and make a commit group of all
* transactions with COMMIT records on the same log page.
*/
/* get the head tblk on the commit queue */
gcpn = list_entry(log->cqueue.next, struct tblock, cqueue)->pn;
list_for_each_entry(tblk, &log->cqueue, cqueue) {
if (tblk->pn != gcpn)
break;
xtblk = tblk;
/* state transition: (QUEUE, READY) -> COMMIT */
tblk->flag |= tblkGC_COMMIT;
}
tblk = xtblk; /* last tblk of the page */
/*
* pageout to commit transactions on the log page.
*/
bp = (struct lbuf *) tblk->bp;
lp = (struct logpage *) bp->l_ldata;
/* is page already full ? */
if (tblk->flag & tblkGC_EOP) {
/* mark page to free at end of group commit of the page */
tblk->flag &= ~tblkGC_EOP;
tblk->flag |= tblkGC_FREE;
bp->l_ceor = bp->l_eor;
lp->h.eor = lp->t.eor = cpu_to_le16(bp->l_ceor);
lbmWrite(log, bp, lbmWRITE | lbmRELEASE | lbmGC,
cant_write);
INCREMENT(lmStat.full_page);
}
/* page is not yet full */
else {
bp->l_ceor = tblk->eor; /* ? bp->l_ceor = bp->l_eor; */
lp->h.eor = lp->t.eor = cpu_to_le16(bp->l_ceor);
lbmWrite(log, bp, lbmWRITE | lbmGC, cant_write);
INCREMENT(lmStat.partial_page);
}
}
/*
* NAME: lmPostGC()
*
* FUNCTION: group commit post-processing
* Processes transactions after their commit records have been written
* to disk, redriving log I/O if necessary.
*
* RETURN: None
*
* NOTE:
* This routine is called a interrupt time by lbmIODone
*/
static void lmPostGC(struct lbuf * bp)
{
unsigned long flags;
struct jfs_log *log = bp->l_log;
struct logpage *lp;
struct tblock *tblk, *temp;
//LOGGC_LOCK(log);
spin_lock_irqsave(&log->gclock, flags);
/*
* current pageout of group commit completed.
*
* remove/wakeup transactions from commit queue who were
* group committed with the current log page
*/
list_for_each_entry_safe(tblk, temp, &log->cqueue, cqueue) {
if (!(tblk->flag & tblkGC_COMMIT))
break;
/* if transaction was marked GC_COMMIT then
* it has been shipped in the current pageout
* and made it to disk - it is committed.
*/
if (bp->l_flag & lbmERROR)
tblk->flag |= tblkGC_ERROR;
/* remove it from the commit queue */
list_del(&tblk->cqueue);
tblk->flag &= ~tblkGC_QUEUE;
if (tblk == log->flush_tblk) {
/* we can stop flushing the log now */
clear_bit(log_FLUSH, &log->flag);
log->flush_tblk = NULL;
}
jfs_info("lmPostGC: tblk = 0x%p, flag = 0x%x", tblk,
tblk->flag);
if (!(tblk->xflag & COMMIT_FORCE))
/*
* Hand tblk over to lazy commit thread
*/
txLazyUnlock(tblk);
else {
/* state transition: COMMIT -> COMMITTED */
tblk->flag |= tblkGC_COMMITTED;
if (tblk->flag & tblkGC_READY)
log->gcrtc--;
LOGGC_WAKEUP(tblk);
}
/* was page full before pageout ?
* (and this is the last tblk bound with the page)
*/
if (tblk->flag & tblkGC_FREE)
lbmFree(bp);
/* did page become full after pageout ?
* (and this is the last tblk bound with the page)
*/
else if (tblk->flag & tblkGC_EOP) {
/* finalize the page */
lp = (struct logpage *) bp->l_ldata;
bp->l_ceor = bp->l_eor;
lp->h.eor = lp->t.eor = cpu_to_le16(bp->l_eor);
jfs_info("lmPostGC: calling lbmWrite");
lbmWrite(log, bp, lbmWRITE | lbmRELEASE | lbmFREE,
1);
}
}
/* are there any transactions who have entered lnGroupCommit()
* (whose COMMITs are after that of the last log page written.
* They are waiting for new group commit (above at (SLEEP 1))
* or lazy transactions are on a full (queued) log page,
* select the latest ready transaction as new group leader and
* wake her up to lead her group.
*/
if ((!list_empty(&log->cqueue)) &&
((log->gcrtc > 0) || (tblk->bp->l_wqnext != NULL) ||
test_bit(log_FLUSH, &log->flag) || jfs_tlocks_low))
/*
* Call lmGCwrite with new group leader
*/
lmGCwrite(log, 1);
/* no transaction are ready yet (transactions are only just
* queued (GC_QUEUE) and not entered for group commit yet).
* the first transaction entering group commit
* will elect herself as new group leader.
*/
else
log->cflag &= ~logGC_PAGEOUT;
//LOGGC_UNLOCK(log);
spin_unlock_irqrestore(&log->gclock, flags);
return;
}
/*
* NAME: lmLogSync()
*
* FUNCTION: write log SYNCPT record for specified log
* if new sync address is available
* (normally the case if sync() is executed by back-ground
* process).
* calculate new value of i_nextsync which determines when
* this code is called again.
*
* PARAMETERS: log - log structure
* hard_sync - 1 to force all metadata to be written
*
* RETURN: 0
*
* serialization: LOG_LOCK() held on entry/exit
*/
static int lmLogSync(struct jfs_log * log, int hard_sync)
{
int logsize;
int written; /* written since last syncpt */
int free; /* free space left available */
int delta; /* additional delta to write normally */
int more; /* additional write granted */
struct lrd lrd;
int lsn;
struct logsyncblk *lp;
unsigned long flags;
/* push dirty metapages out to disk */
if (hard_sync)
write_special_inodes(log, filemap_fdatawrite);
else
write_special_inodes(log, filemap_flush);
/*
* forward syncpt
*/
/* if last sync is same as last syncpt,
* invoke sync point forward processing to update sync.
*/
if (log->sync == log->syncpt) {
LOGSYNC_LOCK(log, flags);
if (list_empty(&log->synclist))
log->sync = log->lsn;
else {
lp = list_entry(log->synclist.next,
struct logsyncblk, synclist);
log->sync = lp->lsn;
}
LOGSYNC_UNLOCK(log, flags);
}
/* if sync is different from last syncpt,
* write a SYNCPT record with syncpt = sync.
* reset syncpt = sync
*/
if (log->sync != log->syncpt) {
lrd.logtid = 0;
lrd.backchain = 0;
lrd.type = cpu_to_le16(LOG_SYNCPT);
lrd.length = 0;
lrd.log.syncpt.sync = cpu_to_le32(log->sync);
lsn = lmWriteRecord(log, NULL, &lrd, NULL);
log->syncpt = log->sync;
} else
lsn = log->lsn;
/*
* setup next syncpt trigger (SWAG)
*/
logsize = log->logsize;
logdiff(written, lsn, log);
free = logsize - written;
delta = LOGSYNC_DELTA(logsize);
more = min(free / 2, delta);
if (more < 2 * LOGPSIZE) {
jfs_warn("\n ... Log Wrap ... Log Wrap ... Log Wrap ...\n");
/*
* log wrapping
*
* option 1 - panic ? No.!
* option 2 - shutdown file systems
* associated with log ?
* option 3 - extend log ?
* option 4 - second chance
*
* mark log wrapped, and continue.
* when all active transactions are completed,
* mark log valid for recovery.
* if crashed during invalid state, log state
* implies invalid log, forcing fsck().
*/
/* mark log state log wrap in log superblock */
/* log->state = LOGWRAP; */
/* reset sync point computation */
log->syncpt = log->sync = lsn;
log->nextsync = delta;
} else
/* next syncpt trigger = written + more */
log->nextsync = written + more;
/* if number of bytes written from last sync point is more
* than 1/4 of the log size, stop new transactions from
* starting until all current transactions are completed
* by setting syncbarrier flag.
*/
if (!test_bit(log_SYNCBARRIER, &log->flag) &&
(written > LOGSYNC_BARRIER(logsize)) && log->active) {
set_bit(log_SYNCBARRIER, &log->flag);
jfs_info("log barrier on: lsn=0x%x syncpt=0x%x", lsn,
log->syncpt);
/*
* We may have to initiate group commit
*/
jfs_flush_journal(log, 0);
}
return lsn;
}
/*
* NAME: jfs_syncpt
*
* FUNCTION: write log SYNCPT record for specified log
*
* PARAMETERS: log - log structure
* hard_sync - set to 1 to force metadata to be written
*/
void jfs_syncpt(struct jfs_log *log, int hard_sync)
{ LOG_LOCK(log);
if (!test_bit(log_QUIESCE, &log->flag))
lmLogSync(log, hard_sync);
LOG_UNLOCK(log);
}
/*
* NAME: lmLogOpen()
*
* FUNCTION: open the log on first open;
* insert filesystem in the active list of the log.
*
* PARAMETER: ipmnt - file system mount inode
* iplog - log inode (out)
*
* RETURN:
*
* serialization:
*/
int lmLogOpen(struct super_block *sb)
{
int rc;
struct block_device *bdev;
struct jfs_log *log;
struct jfs_sb_info *sbi = JFS_SBI(sb);
if (sbi->flag & JFS_NOINTEGRITY)
return open_dummy_log(sb);
if (sbi->mntflag & JFS_INLINELOG)
return open_inline_log(sb);
mutex_lock(&jfs_log_mutex);
list_for_each_entry(log, &jfs_external_logs, journal_list) {
if (log->bdev->bd_dev == sbi->logdev) {
if (memcmp(log->uuid, sbi->loguuid,
sizeof(log->uuid))) {
jfs_warn("wrong uuid on JFS journal\n");
mutex_unlock(&jfs_log_mutex);
return -EINVAL;
}
/*
* add file system to log active file system list
*/
if ((rc = lmLogFileSystem(log, sbi, 1))) {
mutex_unlock(&jfs_log_mutex);
return rc;
}
goto journal_found;
}
}
if (!(log = kzalloc(sizeof(struct jfs_log), GFP_KERNEL))) {
mutex_unlock(&jfs_log_mutex);
return -ENOMEM;
}
INIT_LIST_HEAD(&log->sb_list);
init_waitqueue_head(&log->syncwait);
/*
* external log as separate logical volume
*
* file systems to log may have n-to-1 relationship;
*/
bdev = blkdev_get_by_dev(sbi->logdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
log);
if (IS_ERR(bdev)) {
rc = PTR_ERR(bdev);
goto free;
}
log->bdev = bdev;
memcpy(log->uuid, sbi->loguuid, sizeof(log->uuid));
/*
* initialize log:
*/
if ((rc = lmLogInit(log)))
goto close;
list_add(&log->journal_list, &jfs_external_logs);
/*
* add file system to log active file system list
*/
if ((rc = lmLogFileSystem(log, sbi, 1)))
goto shutdown;
journal_found:
LOG_LOCK(log);
list_add(&sbi->log_list, &log->sb_list);
sbi->log = log;
LOG_UNLOCK(log);
mutex_unlock(&jfs_log_mutex);
return 0;
/*
* unwind on error
*/
shutdown: /* unwind lbmLogInit() */
list_del(&log->journal_list);
lbmLogShutdown(log);
close: /* close external log device */
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
free: /* free log descriptor */
mutex_unlock(&jfs_log_mutex);
kfree(log);
jfs_warn("lmLogOpen: exit(%d)", rc);
return rc;
}
static int open_inline_log(struct super_block *sb)
{
struct jfs_log *log;
int rc;
if (!(log = kzalloc(sizeof(struct jfs_log), GFP_KERNEL)))
return -ENOMEM;
INIT_LIST_HEAD(&log->sb_list);
init_waitqueue_head(&log->syncwait);
set_bit(log_INLINELOG, &log->flag);
log->bdev = sb->s_bdev;
log->base = addressPXD(&JFS_SBI(sb)->logpxd);
log->size = lengthPXD(&JFS_SBI(sb)->logpxd) >>
(L2LOGPSIZE - sb->s_blocksize_bits);
log->l2bsize = sb->s_blocksize_bits;
ASSERT(L2LOGPSIZE >= sb->s_blocksize_bits);
/*
* initialize log.
*/
if ((rc = lmLogInit(log))) {
kfree(log);
jfs_warn("lmLogOpen: exit(%d)", rc);
return rc;
}
list_add(&JFS_SBI(sb)->log_list, &log->sb_list);
JFS_SBI(sb)->log = log;
return rc;
}
static int open_dummy_log(struct super_block *sb)
{
int rc;
mutex_lock(&jfs_log_mutex);
if (!dummy_log) {
dummy_log = kzalloc(sizeof(struct jfs_log), GFP_KERNEL);
if (!dummy_log) {
mutex_unlock(&jfs_log_mutex);
return -ENOMEM;
}
INIT_LIST_HEAD(&dummy_log->sb_list);
init_waitqueue_head(&dummy_log->syncwait);
dummy_log->no_integrity = 1;
/* Make up some stuff */
dummy_log->base = 0;
dummy_log->size = 1024;
rc = lmLogInit(dummy_log);
if (rc) {
kfree(dummy_log);
dummy_log = NULL;
mutex_unlock(&jfs_log_mutex);
return rc;
}
}
LOG_LOCK(dummy_log);
list_add(&JFS_SBI(sb)->log_list, &dummy_log->sb_list);
JFS_SBI(sb)->log = dummy_log;
LOG_UNLOCK(dummy_log);
mutex_unlock(&jfs_log_mutex);
return 0;
}
/*
* NAME: lmLogInit()
*
* FUNCTION: log initialization at first log open.
*
* logredo() (or logformat()) should have been run previously.
* initialize the log from log superblock.
* set the log state in the superblock to LOGMOUNT and
* write SYNCPT log record.
*
* PARAMETER: log - log structure
*
* RETURN: 0 - if ok
* -EINVAL - bad log magic number or superblock dirty
* error returned from logwait()
*
* serialization: single first open thread
*/
int lmLogInit(struct jfs_log * log)
{
int rc = 0;
struct lrd lrd;
struct logsuper *logsuper;
struct lbuf *bpsuper;
struct lbuf *bp;
struct logpage *lp;
int lsn = 0;
jfs_info("lmLogInit: log:0x%p", log);
/* initialize the group commit serialization lock */
LOGGC_LOCK_INIT(log);
/* allocate/initialize the log write serialization lock */
LOG_LOCK_INIT(log);
LOGSYNC_LOCK_INIT(log);
INIT_LIST_HEAD(&log->synclist);
INIT_LIST_HEAD(&log->cqueue);
log->flush_tblk = NULL;
log->count = 0;
/*
* initialize log i/o
*/
if ((rc = lbmLogInit(log)))
return rc;
if (!test_bit(log_INLINELOG, &log->flag))
log->l2bsize = L2LOGPSIZE;
/* check for disabled journaling to disk */
if (log->no_integrity) {
/*
* Journal pages will still be filled. When the time comes
* to actually do the I/O, the write is not done, and the
* endio routine is called directly.
*/
bp = lbmAllocate(log , 0);
log->bp = bp;
bp->l_pn = bp->l_eor = 0;
} else {
/*
* validate log superblock
*/
if ((rc = lbmRead(log, 1, &bpsuper)))
goto errout10;
logsuper = (struct logsuper *) bpsuper->l_ldata;
if (logsuper->magic != cpu_to_le32(LOGMAGIC)) {
jfs_warn("*** Log Format Error ! ***");
rc = -EINVAL;
goto errout20;
}
/* logredo() should have been run successfully. */
if (logsuper->state != cpu_to_le32(LOGREDONE)) {
jfs_warn("*** Log Is Dirty ! ***");
rc = -EINVAL;
goto errout20;
}
/* initialize log from log superblock */
if (test_bit(log_INLINELOG,&log->flag)) {
if (log->size != le32_to_cpu(logsuper->size)) {
rc = -EINVAL;
goto errout20;
}
jfs_info("lmLogInit: inline log:0x%p base:0x%Lx "
"size:0x%x", log,
(unsigned long long) log->base, log->size);
} else {
if (memcmp(logsuper->uuid, log->uuid, 16)) {
jfs_warn("wrong uuid on JFS log device");
goto errout20;
}
log->size = le32_to_cpu(logsuper->size);
log->l2bsize = le32_to_cpu(logsuper->l2bsize);
jfs_info("lmLogInit: external log:0x%p base:0x%Lx "
"size:0x%x", log,
(unsigned long long) log->base, log->size);
}
log->page = le32_to_cpu(logsuper->end) / LOGPSIZE;
log->eor = le32_to_cpu(logsuper->end) - (LOGPSIZE * log->page);
/*
* initialize for log append write mode
*/
/* establish current/end-of-log page/buffer */
if ((rc = lbmRead(log, log->page, &bp)))
goto errout20;
lp = (struct logpage *) bp->l_ldata;
jfs_info("lmLogInit: lsn:0x%x page:%d eor:%d:%d",
le32_to_cpu(logsuper->end), log->page, log->eor,
le16_to_cpu(lp->h.eor));
log->bp = bp;
bp->l_pn = log->page;
bp->l_eor = log->eor;
/* if current page is full, move on to next page */
if (log->eor >= LOGPSIZE - LOGPTLRSIZE)
lmNextPage(log);
/*
* initialize log syncpoint
*/
/*
* write the first SYNCPT record with syncpoint = 0
* (i.e., log redo up to HERE !);
* remove current page from lbm write queue at end of pageout
* (to write log superblock update), but do not release to
* freelist;
*/
lrd.logtid = 0;
lrd.backchain = 0;
lrd.type = cpu_to_le16(LOG_SYNCPT);
lrd.length = 0;
lrd.log.syncpt.sync = 0;
lsn = lmWriteRecord(log, NULL, &lrd, NULL);
bp = log->bp;
bp->l_ceor = bp->l_eor;
lp = (struct logpage *) bp->l_ldata;
lp->h.eor = lp->t.eor = cpu_to_le16(bp->l_eor);
lbmWrite(log, bp, lbmWRITE | lbmSYNC, 0);
if ((rc = lbmIOWait(bp, 0)))
goto errout30;
/*
* update/write superblock
*/
logsuper->state = cpu_to_le32(LOGMOUNT);
log->serial = le32_to_cpu(logsuper->serial) + 1;
logsuper->serial = cpu_to_le32(log->serial);
lbmDirectWrite(log, bpsuper, lbmWRITE | lbmRELEASE | lbmSYNC);
if ((rc = lbmIOWait(bpsuper, lbmFREE)))
goto errout30;
}
/* initialize logsync parameters */
log->logsize = (log->size - 2) << L2LOGPSIZE;
log->lsn = lsn;
log->syncpt = lsn;
log->sync = log->syncpt;
log->nextsync = LOGSYNC_DELTA(log->logsize);
jfs_info("lmLogInit: lsn:0x%x syncpt:0x%x sync:0x%x",
log->lsn, log->syncpt, log->sync);
/*
* initialize for lazy/group commit
*/
log->clsn = lsn;
return 0;
/*
* unwind on error
*/
errout30: /* release log page */
log->wqueue = NULL;
bp->l_wqnext = NULL;
lbmFree(bp);
errout20: /* release log superblock */
lbmFree(bpsuper);
errout10: /* unwind lbmLogInit() */
lbmLogShutdown(log);
jfs_warn("lmLogInit: exit(%d)", rc);
return rc;
}
/*
* NAME: lmLogClose()
*
* FUNCTION: remove file system <ipmnt> from active list of log <iplog>
* and close it on last close.
*
* PARAMETER: sb - superblock
*
* RETURN: errors from subroutines
*
* serialization:
*/
int lmLogClose(struct super_block *sb)
{
struct jfs_sb_info *sbi = JFS_SBI(sb);
struct jfs_log *log = sbi->log;
struct block_device *bdev;
int rc = 0;
jfs_info("lmLogClose: log:0x%p", log);
mutex_lock(&jfs_log_mutex);
LOG_LOCK(log);
list_del(&sbi->log_list);
LOG_UNLOCK(log);
sbi->log = NULL;
/*
* We need to make sure all of the "written" metapages
* actually make it to disk
*/
sync_blockdev(sb->s_bdev);
if (test_bit(log_INLINELOG, &log->flag)) {
/*
* in-line log in host file system
*/
rc = lmLogShutdown(log);
kfree(log);
goto out;
}
if (!log->no_integrity)
lmLogFileSystem(log, sbi, 0);
if (!list_empty(&log->sb_list))
goto out;
/*
* TODO: ensure that the dummy_log is in a state to allow
* lbmLogShutdown to deallocate all the buffers and call
* kfree against dummy_log. For now, leave dummy_log & its
* buffers in memory, and resuse if another no-integrity mount
* is requested.
*/
if (log->no_integrity)
goto out;
/*
* external log as separate logical volume
*/
list_del(&log->journal_list);
bdev = log->bdev;
rc = lmLogShutdown(log);
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
kfree(log);
out:
mutex_unlock(&jfs_log_mutex);
jfs_info("lmLogClose: exit(%d)", rc);
return rc;
}
/*
* NAME: jfs_flush_journal()
*
* FUNCTION: initiate write of any outstanding transactions to the journal
* and optionally wait until they are all written to disk
*
* wait == 0 flush until latest txn is committed, don't wait
* wait == 1 flush until latest txn is committed, wait
* wait > 1 flush until all txn's are complete, wait
*/
void jfs_flush_journal(struct jfs_log *log, int wait)
{
int i;
struct tblock *target = NULL;
/* jfs_write_inode may call us during read-only mount */
if (!log)
return;
jfs_info("jfs_flush_journal: log:0x%p wait=%d", log, wait);
LOGGC_LOCK(log);
if (!list_empty(&log->cqueue)) {
/*
* This ensures that we will keep writing to the journal as long
* as there are unwritten commit records
*/
target = list_entry(log->cqueue.prev, struct tblock, cqueue);
if (test_bit(log_FLUSH, &log->flag)) {
/*
* We're already flushing.
* if flush_tblk is NULL, we are flushing everything,
* so leave it that way. Otherwise, update it to the
* latest transaction
*/
if (log->flush_tblk)
log->flush_tblk = target;
} else {
/* Only flush until latest transaction is committed */
log->flush_tblk = target;
set_bit(log_FLUSH, &log->flag);
/*
* Initiate I/O on outstanding transactions
*/
if (!(log->cflag & logGC_PAGEOUT)) {
log->cflag |= logGC_PAGEOUT;
lmGCwrite(log, 0);
}
}
}
if ((wait > 1) || test_bit(log_SYNCBARRIER, &log->flag)) {
/* Flush until all activity complete */
set_bit(log_FLUSH, &log->flag);
log->flush_tblk = NULL;
}
if (wait && target && !(target->flag & tblkGC_COMMITTED)) {
DECLARE_WAITQUEUE(__wait, current);
add_wait_queue(&target->gcwait, &__wait);
set_current_state(TASK_UNINTERRUPTIBLE);
LOGGC_UNLOCK(log);
schedule();
__set_current_state(TASK_RUNNING);
LOGGC_LOCK(log);
remove_wait_queue(&target->gcwait, &__wait);
}
LOGGC_UNLOCK(log);
if (wait < 2)
return;
write_special_inodes(log, filemap_fdatawrite);
/*
* If there was recent activity, we may need to wait
* for the lazycommit thread to catch up
*/
if ((!list_empty(&log->cqueue)) || !list_empty(&log->synclist)) {
for (i = 0; i < 200; i++) { /* Too much? */
msleep(250);
write_special_inodes(log, filemap_fdatawrite);
if (list_empty(&log->cqueue) &&
list_empty(&log->synclist))
break;
}
}
assert(list_empty(&log->cqueue));
#ifdef CONFIG_JFS_DEBUG
if (!list_empty(&log->synclist)) {
struct logsyncblk *lp;
printk(KERN_ERR "jfs_flush_journal: synclist not empty\n");
list_for_each_entry(lp, &log->synclist, synclist) {
if (lp->xflag & COMMIT_PAGE) {
struct metapage *mp = (struct metapage *)lp;
print_hex_dump(KERN_ERR, "metapage: ",
DUMP_PREFIX_ADDRESS, 16, 4,
mp, sizeof(struct metapage), 0);
print_hex_dump(KERN_ERR, "page: ",
DUMP_PREFIX_ADDRESS, 16,
sizeof(long), mp->page,
sizeof(struct page), 0);
} else
print_hex_dump(KERN_ERR, "tblock:",
DUMP_PREFIX_ADDRESS, 16, 4,
lp, sizeof(struct tblock), 0);
}
}
#else
WARN_ON(!list_empty(&log->synclist));
#endif
clear_bit(log_FLUSH, &log->flag);
}
/*
* NAME: lmLogShutdown()
*
* FUNCTION: log shutdown at last LogClose().
*
* write log syncpt record.
* update super block to set redone flag to 0.
*
* PARAMETER: log - log inode
*
* RETURN: 0 - success
*
* serialization: single last close thread
*/
int lmLogShutdown(struct jfs_log * log)
{
int rc;
struct lrd lrd;
int lsn;
struct logsuper *logsuper;
struct lbuf *bpsuper;
struct lbuf *bp;
struct logpage *lp;
jfs_info("lmLogShutdown: log:0x%p", log);
jfs_flush_journal(log, 2);
/*
* write the last SYNCPT record with syncpoint = 0
* (i.e., log redo up to HERE !)
*/
lrd.logtid = 0;
lrd.backchain = 0;
lrd.type = cpu_to_le16(LOG_SYNCPT);
lrd.length = 0;
lrd.log.syncpt.sync = 0;
lsn = lmWriteRecord(log, NULL, &lrd, NULL);
bp = log->bp;
lp = (struct logpage *) bp->l_ldata;
lp->h.eor = lp->t.eor = cpu_to_le16(bp->l_eor);
lbmWrite(log, log->bp, lbmWRITE | lbmRELEASE | lbmSYNC, 0);
lbmIOWait(log->bp, lbmFREE);
log->bp = NULL;
/*
* synchronous update log superblock
* mark log state as shutdown cleanly
* (i.e., Log does not need to be replayed).
*/
if ((rc = lbmRead(log, 1, &bpsuper)))
goto out;
logsuper = (struct logsuper *) bpsuper->l_ldata;
logsuper->state = cpu_to_le32(LOGREDONE);
logsuper->end = cpu_to_le32(lsn);
lbmDirectWrite(log, bpsuper, lbmWRITE | lbmRELEASE | lbmSYNC);
rc = lbmIOWait(bpsuper, lbmFREE);
jfs_info("lmLogShutdown: lsn:0x%x page:%d eor:%d",
lsn, log->page, log->eor);
out:
/*
* shutdown per log i/o
*/
lbmLogShutdown(log);
if (rc) {
jfs_warn("lmLogShutdown: exit(%d)", rc);
}
return rc;
}
/*
* NAME: lmLogFileSystem()
*
* FUNCTION: insert (<activate> = true)/remove (<activate> = false)
* file system into/from log active file system list.
*
* PARAMETE: log - pointer to logs inode.
* fsdev - kdev_t of filesystem.
* serial - pointer to returned log serial number
* activate - insert/remove device from active list.
*
* RETURN: 0 - success
* errors returned by vms_iowait().
*/
static int lmLogFileSystem(struct jfs_log * log, struct jfs_sb_info *sbi,
int activate)
{
int rc = 0;
int i;
struct logsuper *logsuper;
struct lbuf *bpsuper;
char *uuid = sbi->uuid;
/*
* insert/remove file system device to log active file system list.
*/
if ((rc = lbmRead(log, 1, &bpsuper)))
return rc;
logsuper = (struct logsuper *) bpsuper->l_ldata;
if (activate) {
for (i = 0; i < MAX_ACTIVE; i++)
if (!memcmp(logsuper->active[i].uuid, NULL_UUID, 16)) {
memcpy(logsuper->active[i].uuid, uuid, 16);
sbi->aggregate = i;
break;
}
if (i == MAX_ACTIVE) {
jfs_warn("Too many file systems sharing journal!");
lbmFree(bpsuper);
return -EMFILE; /* Is there a better rc? */
}
} else {
for (i = 0; i < MAX_ACTIVE; i++)
if (!memcmp(logsuper->active[i].uuid, uuid, 16)) {
memcpy(logsuper->active[i].uuid, NULL_UUID, 16);
break;
}
if (i == MAX_ACTIVE) {
jfs_warn("Somebody stomped on the journal!");
lbmFree(bpsuper);
return -EIO;
}
}
/*
* synchronous write log superblock:
*
* write sidestream bypassing write queue:
* at file system mount, log super block is updated for
* activation of the file system before any log record
* (MOUNT record) of the file system, and at file system
* unmount, all meta data for the file system has been
* flushed before log super block is updated for deactivation
* of the file system.
*/
lbmDirectWrite(log, bpsuper, lbmWRITE | lbmRELEASE | lbmSYNC);
rc = lbmIOWait(bpsuper, lbmFREE);
return rc;
}
/*
* log buffer manager (lbm)
* ------------------------
*
* special purpose buffer manager supporting log i/o requirements.
*
* per log write queue:
* log pageout occurs in serial order by fifo write queue and
* restricting to a single i/o in pregress at any one time.
* a circular singly-linked list
* (log->wrqueue points to the tail, and buffers are linked via
* bp->wrqueue field), and
* maintains log page in pageout ot waiting for pageout in serial pageout.
*/
/*
* lbmLogInit()
*
* initialize per log I/O setup at lmLogInit()
*/
static int lbmLogInit(struct jfs_log * log)
{ /* log inode */
int i;
struct lbuf *lbuf;
jfs_info("lbmLogInit: log:0x%p", log);
/* initialize current buffer cursor */
log->bp = NULL;
/* initialize log device write queue */
log->wqueue = NULL;
/*
* Each log has its own buffer pages allocated to it. These are
* not managed by the page cache. This ensures that a transaction
* writing to the log does not block trying to allocate a page from
* the page cache (for the log). This would be bad, since page
* allocation waits on the kswapd thread that may be committing inodes
* which would cause log activity. Was that clear? I'm trying to
* avoid deadlock here.
*/
init_waitqueue_head(&log->free_wait);
log->lbuf_free = NULL;
for (i = 0; i < LOGPAGES;) {
char *buffer;
uint offset;
struct page *page;
buffer = (char *) get_zeroed_page(GFP_KERNEL);
if (buffer == NULL)
goto error;
page = virt_to_page(buffer);
for (offset = 0; offset < PAGE_SIZE; offset += LOGPSIZE) {
lbuf = kmalloc(sizeof(struct lbuf), GFP_KERNEL);
if (lbuf == NULL) {
if (offset == 0)
free_page((unsigned long) buffer);
goto error;
}
if (offset) /* we already have one reference */
get_page(page);
lbuf->l_offset = offset;
lbuf->l_ldata = buffer + offset;
lbuf->l_page = page;
lbuf->l_log = log;
init_waitqueue_head(&lbuf->l_ioevent);
lbuf->l_freelist = log->lbuf_free;
log->lbuf_free = lbuf;
i++;
}
}
return (0);
error:
lbmLogShutdown(log);
return -ENOMEM;
}
/*
* lbmLogShutdown()
*
* finalize per log I/O setup at lmLogShutdown()
*/
static void lbmLogShutdown(struct jfs_log * log)
{
struct lbuf *lbuf;
jfs_info("lbmLogShutdown: log:0x%p", log);
lbuf = log->lbuf_free;
while (lbuf) {
struct lbuf *next = lbuf->l_freelist;
__free_page(lbuf->l_page);
kfree(lbuf);
lbuf = next;
}
}
/*
* lbmAllocate()
*
* allocate an empty log buffer
*/
static struct lbuf *lbmAllocate(struct jfs_log * log, int pn)
{
struct lbuf *bp;
unsigned long flags;
/*
* recycle from log buffer freelist if any
*/
LCACHE_LOCK(flags);
LCACHE_SLEEP_COND(log->free_wait, (bp = log->lbuf_free), flags);
log->lbuf_free = bp->l_freelist;
LCACHE_UNLOCK(flags);
bp->l_flag = 0;
bp->l_wqnext = NULL;
bp->l_freelist = NULL;
bp->l_pn = pn;
bp->l_blkno = log->base + (pn << (L2LOGPSIZE - log->l2bsize));
bp->l_ceor = 0;
return bp;
}
/*
* lbmFree()
*
* release a log buffer to freelist
*/
static void lbmFree(struct lbuf * bp)
{
unsigned long flags;
LCACHE_LOCK(flags);
lbmfree(bp);
LCACHE_UNLOCK(flags);
}
static void lbmfree(struct lbuf * bp)
{
struct jfs_log *log = bp->l_log;
assert(bp->l_wqnext == NULL);
/*
* return the buffer to head of freelist
*/
bp->l_freelist = log->lbuf_free;
log->lbuf_free = bp;
wake_up(&log->free_wait);
return;
}
/*
* NAME: lbmRedrive
*
* FUNCTION: add a log buffer to the log redrive list
*
* PARAMETER:
* bp - log buffer
*
* NOTES:
* Takes log_redrive_lock.
*/
static inline void lbmRedrive(struct lbuf *bp)
{
unsigned long flags;
spin_lock_irqsave(&log_redrive_lock, flags);
bp->l_redrive_next = log_redrive_list;
log_redrive_list = bp;
spin_unlock_irqrestore(&log_redrive_lock, flags);
wake_up_process(jfsIOthread);
}
/*
* lbmRead()
*/
static int lbmRead(struct jfs_log * log, int pn, struct lbuf ** bpp)
{
struct bio *bio;
struct lbuf *bp;
/*
* allocate a log buffer
*/
*bpp = bp = lbmAllocate(log, pn);
jfs_info("lbmRead: bp:0x%p pn:0x%x", bp, pn);
bp->l_flag |= lbmREAD;
bio = bio_alloc(GFP_NOFS, 1);
bio->bi_sector = bp->l_blkno << (log->l2bsize - 9);
bio->bi_bdev = log->bdev;
bio->bi_io_vec[0].bv_page = bp->l_page;
bio->bi_io_vec[0].bv_len = LOGPSIZE;
bio->bi_io_vec[0].bv_offset = bp->l_offset;
bio->bi_vcnt = 1;
bio->bi_size = LOGPSIZE;
bio->bi_end_io = lbmIODone;
bio->bi_private = bp;
/*check if journaling to disk has been disabled*/
if (log->no_integrity) {
bio->bi_size = 0;
lbmIODone(bio, 0);
} else {
submit_bio(READ_SYNC, bio);
}
wait_event(bp->l_ioevent, (bp->l_flag != lbmREAD));
return 0;
}
/*
* lbmWrite()
*
* buffer at head of pageout queue stays after completion of
* partial-page pageout and redriven by explicit initiation of
* pageout by caller until full-page pageout is completed and
* released.
*
* device driver i/o done redrives pageout of new buffer at
* head of pageout queue when current buffer at head of pageout
* queue is released at the completion of its full-page pageout.
*
* LOGGC_LOCK() serializes lbmWrite() by lmNextPage() and lmGroupCommit().
* LCACHE_LOCK() serializes xflag between lbmWrite() and lbmIODone()
*/
static void lbmWrite(struct jfs_log * log, struct lbuf * bp, int flag,
int cant_block)
{
struct lbuf *tail;
unsigned long flags;
jfs_info("lbmWrite: bp:0x%p flag:0x%x pn:0x%x", bp, flag, bp->l_pn);
/* map the logical block address to physical block address */
bp->l_blkno =
log->base + (bp->l_pn << (L2LOGPSIZE - log->l2bsize));
LCACHE_LOCK(flags); /* disable+lock */
/*
* initialize buffer for device driver
*/
bp->l_flag = flag;
/*
* insert bp at tail of write queue associated with log
*
* (request is either for bp already/currently at head of queue
* or new bp to be inserted at tail)
*/
tail = log->wqueue;
/* is buffer not already on write queue ? */
if (bp->l_wqnext == NULL) {
/* insert at tail of wqueue */
if (tail == NULL) {
log->wqueue = bp;
bp->l_wqnext = bp;
} else {
log->wqueue = bp;
bp->l_wqnext = tail->l_wqnext;
tail->l_wqnext = bp;
}
tail = bp;
}
/* is buffer at head of wqueue and for write ? */
if ((bp != tail->l_wqnext) || !(flag & lbmWRITE)) {
LCACHE_UNLOCK(flags); /* unlock+enable */
return;
}
LCACHE_UNLOCK(flags); /* unlock+enable */
if (cant_block)
lbmRedrive(bp);
else if (flag & lbmSYNC)
lbmStartIO(bp);
else {
LOGGC_UNLOCK(log);
lbmStartIO(bp);
LOGGC_LOCK(log);
}
}
/*
* lbmDirectWrite()
*
* initiate pageout bypassing write queue for sidestream
* (e.g., log superblock) write;
*/
static void lbmDirectWrite(struct jfs_log * log, struct lbuf * bp, int flag)
{
jfs_info("lbmDirectWrite: bp:0x%p flag:0x%x pn:0x%x",
bp, flag, bp->l_pn);
/*
* initialize buffer for device driver
*/
bp->l_flag = flag | lbmDIRECT;
/* map the logical block address to physical block address */
bp->l_blkno =
log->base + (bp->l_pn << (L2LOGPSIZE - log->l2bsize));
/*
* initiate pageout of the page
*/
lbmStartIO(bp);
}
/*
* NAME: lbmStartIO()
*
* FUNCTION: Interface to DD strategy routine
*
* RETURN: none
*
* serialization: LCACHE_LOCK() is NOT held during log i/o;
*/
static void lbmStartIO(struct lbuf * bp)
{
struct bio *bio;
struct jfs_log *log = bp->l_log;
jfs_info("lbmStartIO\n");
bio = bio_alloc(GFP_NOFS, 1);
bio->bi_sector = bp->l_blkno << (log->l2bsize - 9);
bio->bi_bdev = log->bdev;
bio->bi_io_vec[0].bv_page = bp->l_page;
bio->bi_io_vec[0].bv_len = LOGPSIZE;
bio->bi_io_vec[0].bv_offset = bp->l_offset;
bio->bi_vcnt = 1;
bio->bi_size = LOGPSIZE;
bio->bi_end_io = lbmIODone;
bio->bi_private = bp;
/* check if journaling to disk has been disabled */
if (log->no_integrity) {
bio->bi_size = 0;
lbmIODone(bio, 0);
} else {
submit_bio(WRITE_SYNC, bio);
INCREMENT(lmStat.submitted);
}
}
/*
* lbmIOWait()
*/
static int lbmIOWait(struct lbuf * bp, int flag)
{
unsigned long flags;
int rc = 0;
jfs_info("lbmIOWait1: bp:0x%p flag:0x%x:0x%x", bp, bp->l_flag, flag);
LCACHE_LOCK(flags); /* disable+lock */
LCACHE_SLEEP_COND(bp->l_ioevent, (bp->l_flag & lbmDONE), flags);
rc = (bp->l_flag & lbmERROR) ? -EIO : 0;
if (flag & lbmFREE)
lbmfree(bp);
LCACHE_UNLOCK(flags); /* unlock+enable */
jfs_info("lbmIOWait2: bp:0x%p flag:0x%x:0x%x", bp, bp->l_flag, flag);
return rc;
}
/*
* lbmIODone()
*
* executed at INTIODONE level
*/
static void lbmIODone(struct bio *bio, int error)
{
struct lbuf *bp = bio->bi_private;
struct lbuf *nextbp, *tail;
struct jfs_log *log;
unsigned long flags;
/*
* get back jfs buffer bound to the i/o buffer
*/
jfs_info("lbmIODone: bp:0x%p flag:0x%x", bp, bp->l_flag);
LCACHE_LOCK(flags); /* disable+lock */
bp->l_flag |= lbmDONE;
if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) {
bp->l_flag |= lbmERROR;
jfs_err("lbmIODone: I/O error in JFS log");
}
bio_put(bio);
/*
* pagein completion
*/
if (bp->l_flag & lbmREAD) {
bp->l_flag &= ~lbmREAD;
LCACHE_UNLOCK(flags); /* unlock+enable */
/* wakeup I/O initiator */
LCACHE_WAKEUP(&bp->l_ioevent);
return;
}
/*
* pageout completion
*
* the bp at the head of write queue has completed pageout.
*
* if single-commit/full-page pageout, remove the current buffer
* from head of pageout queue, and redrive pageout with
* the new buffer at head of pageout queue;
* otherwise, the partial-page pageout buffer stays at
* the head of pageout queue to be redriven for pageout
* by lmGroupCommit() until full-page pageout is completed.
*/
bp->l_flag &= ~lbmWRITE;
INCREMENT(lmStat.pagedone);
/* update committed lsn */
log = bp->l_log;
log->clsn = (bp->l_pn << L2LOGPSIZE) + bp->l_ceor;
if (bp->l_flag & lbmDIRECT) {
LCACHE_WAKEUP(&bp->l_ioevent);
LCACHE_UNLOCK(flags);
return;
}
tail = log->wqueue;
/* single element queue */
if (bp == tail) {
/* remove head buffer of full-page pageout
* from log device write queue
*/
if (bp->l_flag & lbmRELEASE) {
log->wqueue = NULL;
bp->l_wqnext = NULL;
}
}
/* multi element queue */
else {
/* remove head buffer of full-page pageout
* from log device write queue
*/
if (bp->l_flag & lbmRELEASE) {
nextbp = tail->l_wqnext = bp->l_wqnext;
bp->l_wqnext = NULL;
/*
* redrive pageout of next page at head of write queue:
* redrive next page without any bound tblk
* (i.e., page w/o any COMMIT records), or
* first page of new group commit which has been
* queued after current page (subsequent pageout
* is performed synchronously, except page without
* any COMMITs) by lmGroupCommit() as indicated
* by lbmWRITE flag;
*/
if (nextbp->l_flag & lbmWRITE) {
/*
* We can't do the I/O at interrupt time.
* The jfsIO thread can do it
*/
lbmRedrive(nextbp);
}
}
}
/*
* synchronous pageout:
*
* buffer has not necessarily been removed from write queue
* (e.g., synchronous write of partial-page with COMMIT):
* leave buffer for i/o initiator to dispose
*/
if (bp->l_flag & lbmSYNC) {
LCACHE_UNLOCK(flags); /* unlock+enable */
/* wakeup I/O initiator */
LCACHE_WAKEUP(&bp->l_ioevent);
}
/*
* Group Commit pageout:
*/
else if (bp->l_flag & lbmGC) {
LCACHE_UNLOCK(flags);
lmPostGC(bp);
}
/*
* asynchronous pageout:
*
* buffer must have been removed from write queue:
* insert buffer at head of freelist where it can be recycled
*/
else {
assert(bp->l_flag & lbmRELEASE);
assert(bp->l_flag & lbmFREE);
lbmfree(bp);
LCACHE_UNLOCK(flags); /* unlock+enable */
}
}
int jfsIOWait(void *arg)
{
struct lbuf *bp;
do {
spin_lock_irq(&log_redrive_lock);
while ((bp = log_redrive_list)) {
log_redrive_list = bp->l_redrive_next;
bp->l_redrive_next = NULL;
spin_unlock_irq(&log_redrive_lock);
lbmStartIO(bp);
spin_lock_irq(&log_redrive_lock);
}
if (freezing(current)) {
spin_unlock_irq(&log_redrive_lock);
try_to_freeze();
} else {
set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_irq(&log_redrive_lock);
schedule();
__set_current_state(TASK_RUNNING);
}
} while (!kthread_should_stop());
jfs_info("jfsIOWait being killed!");
return 0;
}
/*
* NAME: lmLogFormat()/jfs_logform()
*
* FUNCTION: format file system log
*
* PARAMETERS:
* log - volume log
* logAddress - start address of log space in FS block
* logSize - length of log space in FS block;
*
* RETURN: 0 - success
* -EIO - i/o error
*
* XXX: We're synchronously writing one page at a time. This needs to
* be improved by writing multiple pages at once.
*/
int lmLogFormat(struct jfs_log *log, s64 logAddress, int logSize)
{
int rc = -EIO;
struct jfs_sb_info *sbi;
struct logsuper *logsuper;
struct logpage *lp;
int lspn; /* log sequence page number */
struct lrd *lrd_ptr;
int npages = 0;
struct lbuf *bp;
jfs_info("lmLogFormat: logAddress:%Ld logSize:%d",
(long long)logAddress, logSize);
sbi = list_entry(log->sb_list.next, struct jfs_sb_info, log_list);
/* allocate a log buffer */
bp = lbmAllocate(log, 1);
npages = logSize >> sbi->l2nbperpage;
/*
* log space:
*
* page 0 - reserved;
* page 1 - log superblock;
* page 2 - log data page: A SYNC log record is written
* into this page at logform time;
* pages 3-N - log data page: set to empty log data pages;
*/
/*
* init log superblock: log page 1
*/
logsuper = (struct logsuper *) bp->l_ldata;
logsuper->magic = cpu_to_le32(LOGMAGIC);
logsuper->version = cpu_to_le32(LOGVERSION);
logsuper->state = cpu_to_le32(LOGREDONE);
logsuper->flag = cpu_to_le32(sbi->mntflag); /* ? */
logsuper->size = cpu_to_le32(npages);
logsuper->bsize = cpu_to_le32(sbi->bsize);
logsuper->l2bsize = cpu_to_le32(sbi->l2bsize);
logsuper->end = cpu_to_le32(2 * LOGPSIZE + LOGPHDRSIZE + LOGRDSIZE);
bp->l_flag = lbmWRITE | lbmSYNC | lbmDIRECT;
bp->l_blkno = logAddress + sbi->nbperpage;
lbmStartIO(bp);
if ((rc = lbmIOWait(bp, 0)))
goto exit;
/*
* init pages 2 to npages-1 as log data pages:
*
* log page sequence number (lpsn) initialization:
*
* pn: 0 1 2 3 n-1
* +-----+-----+=====+=====+===.....===+=====+
* lspn: N-1 0 1 N-2
* <--- N page circular file ---->
*
* the N (= npages-2) data pages of the log is maintained as
* a circular file for the log records;
* lpsn grows by 1 monotonically as each log page is written
* to the circular file of the log;
* and setLogpage() will not reset the page number even if
* the eor is equal to LOGPHDRSIZE. In order for binary search
* still work in find log end process, we have to simulate the
* log wrap situation at the log format time.
* The 1st log page written will have the highest lpsn. Then
* the succeeding log pages will have ascending order of
* the lspn starting from 0, ... (N-2)
*/
lp = (struct logpage *) bp->l_ldata;
/*
* initialize 1st log page to be written: lpsn = N - 1,
* write a SYNCPT log record is written to this page
*/
lp->h.page = lp->t.page = cpu_to_le32(npages - 3);
lp->h.eor = lp->t.eor = cpu_to_le16(LOGPHDRSIZE + LOGRDSIZE);
lrd_ptr = (struct lrd *) &lp->data;
lrd_ptr->logtid = 0;
lrd_ptr->backchain = 0;
lrd_ptr->type = cpu_to_le16(LOG_SYNCPT);
lrd_ptr->length = 0;
lrd_ptr->log.syncpt.sync = 0;
bp->l_blkno += sbi->nbperpage;
bp->l_flag = lbmWRITE | lbmSYNC | lbmDIRECT;
lbmStartIO(bp);
if ((rc = lbmIOWait(bp, 0)))
goto exit;
/*
* initialize succeeding log pages: lpsn = 0, 1, ..., (N-2)
*/
for (lspn = 0; lspn < npages - 3; lspn++) {
lp->h.page = lp->t.page = cpu_to_le32(lspn);
lp->h.eor = lp->t.eor = cpu_to_le16(LOGPHDRSIZE);
bp->l_blkno += sbi->nbperpage;
bp->l_flag = lbmWRITE | lbmSYNC | lbmDIRECT;
lbmStartIO(bp);
if ((rc = lbmIOWait(bp, 0)))
goto exit;
}
rc = 0;
exit:
/*
* finalize log
*/
/* release the buffer */
lbmFree(bp);
return rc;
}
#ifdef CONFIG_JFS_STATISTICS
static int jfs_lmstats_proc_show(struct seq_file *m, void *v)
{
seq_printf(m,
"JFS Logmgr stats\n"
"================\n"
"commits = %d\n"
"writes submitted = %d\n"
"writes completed = %d\n"
"full pages submitted = %d\n"
"partial pages submitted = %d\n",
lmStat.commit,
lmStat.submitted,
lmStat.pagedone,
lmStat.full_page,
lmStat.partial_page);
return 0;
}
static int jfs_lmstats_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, jfs_lmstats_proc_show, NULL);
}
const struct file_operations jfs_lmstats_proc_fops = {
.owner = THIS_MODULE,
.open = jfs_lmstats_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_JFS_STATISTICS */
| gpl-2.0 |
Octane70/SGH-T989D_JB_4.1.2_Kernel | arch/powerpc/platforms/86xx/mpc8610_hpcd.c | 2185 | 10493 | /*
* MPC8610 HPCD board specific routines
*
* Initial author: Xianghua Xiao <x.xiao@freescale.com>
* Recode: Jason Jin <jason.jin@freescale.com>
* York Sun <yorksun@freescale.com>
*
* Rewrite the interrupt routing. remove the 8259PIC support,
* All the integrated device in ULI use sideband interrupt.
*
* Copyright 2008 Freescale Semiconductor Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/stddef.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/kdev_t.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/of.h>
#include <asm/system.h>
#include <asm/time.h>
#include <asm/machdep.h>
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#include <mm/mmu_decl.h>
#include <asm/udbg.h>
#include <asm/mpic.h>
#include <linux/of_platform.h>
#include <sysdev/fsl_pci.h>
#include <sysdev/fsl_soc.h>
#include <sysdev/simple_gpio.h>
#include "mpc86xx.h"
static struct device_node *pixis_node;
static unsigned char *pixis_bdcfg0, *pixis_arch;
#ifdef CONFIG_SUSPEND
static irqreturn_t mpc8610_sw9_irq(int irq, void *data)
{
pr_debug("%s: PIXIS' event (sw9/wakeup) IRQ handled\n", __func__);
return IRQ_HANDLED;
}
static void __init mpc8610_suspend_init(void)
{
int irq;
int ret;
if (!pixis_node)
return;
irq = irq_of_parse_and_map(pixis_node, 0);
if (!irq) {
pr_err("%s: can't map pixis event IRQ.\n", __func__);
return;
}
ret = request_irq(irq, mpc8610_sw9_irq, 0, "sw9:wakeup", NULL);
if (ret) {
pr_err("%s: can't request pixis event IRQ: %d\n",
__func__, ret);
irq_dispose_mapping(irq);
}
enable_irq_wake(irq);
}
#else
static inline void mpc8610_suspend_init(void) { }
#endif /* CONFIG_SUSPEND */
static struct of_device_id __initdata mpc8610_ids[] = {
{ .compatible = "fsl,mpc8610-immr", },
{ .compatible = "fsl,mpc8610-guts", },
{ .compatible = "simple-bus", },
/* So that the DMA channel nodes can be probed individually: */
{ .compatible = "fsl,eloplus-dma", },
{}
};
static int __init mpc8610_declare_of_platform_devices(void)
{
/* Firstly, register PIXIS GPIOs. */
simple_gpiochip_init("fsl,fpga-pixis-gpio-bank");
/* Enable wakeup on PIXIS' event IRQ. */
mpc8610_suspend_init();
/* Without this call, the SSI device driver won't get probed. */
of_platform_bus_probe(NULL, mpc8610_ids, NULL);
return 0;
}
machine_device_initcall(mpc86xx_hpcd, mpc8610_declare_of_platform_devices);
#if defined(CONFIG_FB_FSL_DIU) || defined(CONFIG_FB_FSL_DIU_MODULE)
/*
* DIU Area Descriptor
*
* The MPC8610 reference manual shows the bits of the AD register in
* little-endian order, which causes the BLUE_C field to be split into two
* parts. To simplify the definition of the MAKE_AD() macro, we define the
* fields in big-endian order and byte-swap the result.
*
* So even though the registers don't look like they're in the
* same bit positions as they are on the P1022, the same value is written to
* the AD register on the MPC8610 and on the P1022.
*/
#define AD_BYTE_F 0x10000000
#define AD_ALPHA_C_MASK 0x0E000000
#define AD_ALPHA_C_SHIFT 25
#define AD_BLUE_C_MASK 0x01800000
#define AD_BLUE_C_SHIFT 23
#define AD_GREEN_C_MASK 0x00600000
#define AD_GREEN_C_SHIFT 21
#define AD_RED_C_MASK 0x00180000
#define AD_RED_C_SHIFT 19
#define AD_PALETTE 0x00040000
#define AD_PIXEL_S_MASK 0x00030000
#define AD_PIXEL_S_SHIFT 16
#define AD_COMP_3_MASK 0x0000F000
#define AD_COMP_3_SHIFT 12
#define AD_COMP_2_MASK 0x00000F00
#define AD_COMP_2_SHIFT 8
#define AD_COMP_1_MASK 0x000000F0
#define AD_COMP_1_SHIFT 4
#define AD_COMP_0_MASK 0x0000000F
#define AD_COMP_0_SHIFT 0
#define MAKE_AD(alpha, red, blue, green, size, c0, c1, c2, c3) \
cpu_to_le32(AD_BYTE_F | (alpha << AD_ALPHA_C_SHIFT) | \
(blue << AD_BLUE_C_SHIFT) | (green << AD_GREEN_C_SHIFT) | \
(red << AD_RED_C_SHIFT) | (c3 << AD_COMP_3_SHIFT) | \
(c2 << AD_COMP_2_SHIFT) | (c1 << AD_COMP_1_SHIFT) | \
(c0 << AD_COMP_0_SHIFT) | (size << AD_PIXEL_S_SHIFT))
unsigned int mpc8610hpcd_get_pixel_format(unsigned int bits_per_pixel,
int monitor_port)
{
static const unsigned long pixelformat[][3] = {
{
MAKE_AD(3, 0, 2, 1, 3, 8, 8, 8, 8),
MAKE_AD(4, 2, 0, 1, 2, 8, 8, 8, 0),
MAKE_AD(4, 0, 2, 1, 1, 5, 6, 5, 0)
},
{
MAKE_AD(3, 2, 0, 1, 3, 8, 8, 8, 8),
MAKE_AD(4, 0, 2, 1, 2, 8, 8, 8, 0),
MAKE_AD(4, 2, 0, 1, 1, 5, 6, 5, 0)
},
};
unsigned int arch_monitor;
/* The DVI port is mis-wired on revision 1 of this board. */
arch_monitor = ((*pixis_arch == 0x01) && (monitor_port == 0))? 0 : 1;
switch (bits_per_pixel) {
case 32:
return pixelformat[arch_monitor][0];
case 24:
return pixelformat[arch_monitor][1];
case 16:
return pixelformat[arch_monitor][2];
default:
pr_err("fsl-diu: unsupported pixel depth %u\n", bits_per_pixel);
return 0;
}
}
void mpc8610hpcd_set_gamma_table(int monitor_port, char *gamma_table_base)
{
int i;
if (monitor_port == 2) { /* dual link LVDS */
for (i = 0; i < 256*3; i++)
gamma_table_base[i] = (gamma_table_base[i] << 2) |
((gamma_table_base[i] >> 6) & 0x03);
}
}
#define PX_BRDCFG0_DVISEL (1 << 3)
#define PX_BRDCFG0_DLINK (1 << 4)
#define PX_BRDCFG0_DIU_MASK (PX_BRDCFG0_DVISEL | PX_BRDCFG0_DLINK)
void mpc8610hpcd_set_monitor_port(int monitor_port)
{
static const u8 bdcfg[] = {
PX_BRDCFG0_DVISEL | PX_BRDCFG0_DLINK,
PX_BRDCFG0_DLINK,
0,
};
if (monitor_port < 3)
clrsetbits_8(pixis_bdcfg0, PX_BRDCFG0_DIU_MASK,
bdcfg[monitor_port]);
}
void mpc8610hpcd_set_pixel_clock(unsigned int pixclock)
{
u32 __iomem *clkdvdr;
u32 temp;
/* variables for pixel clock calcs */
ulong bestval, bestfreq, speed_ccb, minpixclock, maxpixclock;
ulong pixval;
long err;
int i;
clkdvdr = ioremap(get_immrbase() + 0xe0800, sizeof(u32));
if (!clkdvdr) {
printk(KERN_ERR "Err: can't map clock divider register!\n");
return;
}
/* Pixel Clock configuration */
speed_ccb = fsl_get_sys_freq();
/* Calculate the pixel clock with the smallest error */
/* calculate the following in steps to avoid overflow */
pr_debug("DIU pixclock in ps - %d\n", pixclock);
temp = 1000000000/pixclock;
temp *= 1000;
pixclock = temp;
pr_debug("DIU pixclock freq - %u\n", pixclock);
temp = pixclock * 5 / 100;
pr_debug("deviation = %d\n", temp);
minpixclock = pixclock - temp;
maxpixclock = pixclock + temp;
pr_debug("DIU minpixclock - %lu\n", minpixclock);
pr_debug("DIU maxpixclock - %lu\n", maxpixclock);
pixval = speed_ccb/pixclock;
pr_debug("DIU pixval = %lu\n", pixval);
err = 100000000;
bestval = pixval;
pr_debug("DIU bestval = %lu\n", bestval);
bestfreq = 0;
for (i = -1; i <= 1; i++) {
temp = speed_ccb / ((pixval+i) + 1);
pr_debug("DIU test pixval i= %d, pixval=%lu, temp freq. = %u\n",
i, pixval, temp);
if ((temp < minpixclock) || (temp > maxpixclock))
pr_debug("DIU exceeds monitor range (%lu to %lu)\n",
minpixclock, maxpixclock);
else if (abs(temp - pixclock) < err) {
pr_debug("Entered the else if block %d\n", i);
err = abs(temp - pixclock);
bestval = pixval+i;
bestfreq = temp;
}
}
pr_debug("DIU chose = %lx\n", bestval);
pr_debug("DIU error = %ld\n NomPixClk ", err);
pr_debug("DIU: Best Freq = %lx\n", bestfreq);
/* Modify PXCLK in GUTS CLKDVDR */
pr_debug("DIU: Current value of CLKDVDR = 0x%08x\n", (*clkdvdr));
temp = (*clkdvdr) & 0x2000FFFF;
*clkdvdr = temp; /* turn off clock */
*clkdvdr = temp | 0x80000000 | (((bestval) & 0x1F) << 16);
pr_debug("DIU: Modified value of CLKDVDR = 0x%08x\n", (*clkdvdr));
iounmap(clkdvdr);
}
ssize_t mpc8610hpcd_show_monitor_port(int monitor_port, char *buf)
{
return snprintf(buf, PAGE_SIZE,
"%c0 - DVI\n"
"%c1 - Single link LVDS\n"
"%c2 - Dual link LVDS\n",
monitor_port == 0 ? '*' : ' ',
monitor_port == 1 ? '*' : ' ',
monitor_port == 2 ? '*' : ' ');
}
int mpc8610hpcd_set_sysfs_monitor_port(int val)
{
return val < 3 ? val : 0;
}
#endif
static void __init mpc86xx_hpcd_setup_arch(void)
{
struct resource r;
struct device_node *np;
unsigned char *pixis;
if (ppc_md.progress)
ppc_md.progress("mpc86xx_hpcd_setup_arch()", 0);
#ifdef CONFIG_PCI
for_each_node_by_type(np, "pci") {
if (of_device_is_compatible(np, "fsl,mpc8610-pci")
|| of_device_is_compatible(np, "fsl,mpc8641-pcie")) {
struct resource rsrc;
of_address_to_resource(np, 0, &rsrc);
if ((rsrc.start & 0xfffff) == 0xa000)
fsl_add_bridge(np, 1);
else
fsl_add_bridge(np, 0);
}
}
#endif
#if defined(CONFIG_FB_FSL_DIU) || defined(CONFIG_FB_FSL_DIU_MODULE)
diu_ops.get_pixel_format = mpc8610hpcd_get_pixel_format;
diu_ops.set_gamma_table = mpc8610hpcd_set_gamma_table;
diu_ops.set_monitor_port = mpc8610hpcd_set_monitor_port;
diu_ops.set_pixel_clock = mpc8610hpcd_set_pixel_clock;
diu_ops.show_monitor_port = mpc8610hpcd_show_monitor_port;
diu_ops.set_sysfs_monitor_port = mpc8610hpcd_set_sysfs_monitor_port;
#endif
pixis_node = of_find_compatible_node(NULL, NULL, "fsl,fpga-pixis");
if (pixis_node) {
of_address_to_resource(pixis_node, 0, &r);
of_node_put(pixis_node);
pixis = ioremap(r.start, 32);
if (!pixis) {
printk(KERN_ERR "Err: can't map FPGA cfg register!\n");
return;
}
pixis_bdcfg0 = pixis + 8;
pixis_arch = pixis + 1;
} else
printk(KERN_ERR "Err: "
"can't find device node 'fsl,fpga-pixis'\n");
printk("MPC86xx HPCD board from Freescale Semiconductor\n");
}
/*
* Called very early, device-tree isn't unflattened
*/
static int __init mpc86xx_hpcd_probe(void)
{
unsigned long root = of_get_flat_dt_root();
if (of_flat_dt_is_compatible(root, "fsl,MPC8610HPCD"))
return 1; /* Looks good */
return 0;
}
static long __init mpc86xx_time_init(void)
{
unsigned int temp;
/* Set the time base to zero */
mtspr(SPRN_TBWL, 0);
mtspr(SPRN_TBWU, 0);
temp = mfspr(SPRN_HID0);
temp |= HID0_TBEN;
mtspr(SPRN_HID0, temp);
asm volatile("isync");
return 0;
}
define_machine(mpc86xx_hpcd) {
.name = "MPC86xx HPCD",
.probe = mpc86xx_hpcd_probe,
.setup_arch = mpc86xx_hpcd_setup_arch,
.init_IRQ = mpc86xx_init_irq,
.get_irq = mpic_get_irq,
.restart = fsl_rstcr_restart,
.time_init = mpc86xx_time_init,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
.pcibios_fixup_bus = fsl_pcibios_fixup_bus,
};
| gpl-2.0 |
morristech/GT-I9300-JB-3.0.y | fs/ocfs2/journal.c | 2953 | 57637 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* journal.c
*
* Defines functions of journalling api
*
* Copyright (C) 2003, 2004 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 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 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/kthread.h>
#include <linux/time.h>
#include <linux/random.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "blockcheck.h"
#include "dir.h"
#include "dlmglue.h"
#include "extent_map.h"
#include "heartbeat.h"
#include "inode.h"
#include "journal.h"
#include "localalloc.h"
#include "slot_map.h"
#include "super.h"
#include "sysfile.h"
#include "uptodate.h"
#include "quota.h"
#include "buffer_head_io.h"
#include "ocfs2_trace.h"
DEFINE_SPINLOCK(trans_inc_lock);
#define ORPHAN_SCAN_SCHEDULE_TIMEOUT 300000
static int ocfs2_force_read_journal(struct inode *inode);
static int ocfs2_recover_node(struct ocfs2_super *osb,
int node_num, int slot_num);
static int __ocfs2_recovery_thread(void *arg);
static int ocfs2_commit_cache(struct ocfs2_super *osb);
static int __ocfs2_wait_on_mount(struct ocfs2_super *osb, int quota);
static int ocfs2_journal_toggle_dirty(struct ocfs2_super *osb,
int dirty, int replayed);
static int ocfs2_trylock_journal(struct ocfs2_super *osb,
int slot_num);
static int ocfs2_recover_orphans(struct ocfs2_super *osb,
int slot);
static int ocfs2_commit_thread(void *arg);
static void ocfs2_queue_recovery_completion(struct ocfs2_journal *journal,
int slot_num,
struct ocfs2_dinode *la_dinode,
struct ocfs2_dinode *tl_dinode,
struct ocfs2_quota_recovery *qrec);
static inline int ocfs2_wait_on_mount(struct ocfs2_super *osb)
{
return __ocfs2_wait_on_mount(osb, 0);
}
static inline int ocfs2_wait_on_quotas(struct ocfs2_super *osb)
{
return __ocfs2_wait_on_mount(osb, 1);
}
/*
* This replay_map is to track online/offline slots, so we could recover
* offline slots during recovery and mount
*/
enum ocfs2_replay_state {
REPLAY_UNNEEDED = 0, /* Replay is not needed, so ignore this map */
REPLAY_NEEDED, /* Replay slots marked in rm_replay_slots */
REPLAY_DONE /* Replay was already queued */
};
struct ocfs2_replay_map {
unsigned int rm_slots;
enum ocfs2_replay_state rm_state;
unsigned char rm_replay_slots[0];
};
void ocfs2_replay_map_set_state(struct ocfs2_super *osb, int state)
{
if (!osb->replay_map)
return;
/* If we've already queued the replay, we don't have any more to do */
if (osb->replay_map->rm_state == REPLAY_DONE)
return;
osb->replay_map->rm_state = state;
}
int ocfs2_compute_replay_slots(struct ocfs2_super *osb)
{
struct ocfs2_replay_map *replay_map;
int i, node_num;
/* If replay map is already set, we don't do it again */
if (osb->replay_map)
return 0;
replay_map = kzalloc(sizeof(struct ocfs2_replay_map) +
(osb->max_slots * sizeof(char)), GFP_KERNEL);
if (!replay_map) {
mlog_errno(-ENOMEM);
return -ENOMEM;
}
spin_lock(&osb->osb_lock);
replay_map->rm_slots = osb->max_slots;
replay_map->rm_state = REPLAY_UNNEEDED;
/* set rm_replay_slots for offline slot(s) */
for (i = 0; i < replay_map->rm_slots; i++) {
if (ocfs2_slot_to_node_num_locked(osb, i, &node_num) == -ENOENT)
replay_map->rm_replay_slots[i] = 1;
}
osb->replay_map = replay_map;
spin_unlock(&osb->osb_lock);
return 0;
}
void ocfs2_queue_replay_slots(struct ocfs2_super *osb)
{
struct ocfs2_replay_map *replay_map = osb->replay_map;
int i;
if (!replay_map)
return;
if (replay_map->rm_state != REPLAY_NEEDED)
return;
for (i = 0; i < replay_map->rm_slots; i++)
if (replay_map->rm_replay_slots[i])
ocfs2_queue_recovery_completion(osb->journal, i, NULL,
NULL, NULL);
replay_map->rm_state = REPLAY_DONE;
}
void ocfs2_free_replay_slots(struct ocfs2_super *osb)
{
struct ocfs2_replay_map *replay_map = osb->replay_map;
if (!osb->replay_map)
return;
kfree(replay_map);
osb->replay_map = NULL;
}
int ocfs2_recovery_init(struct ocfs2_super *osb)
{
struct ocfs2_recovery_map *rm;
mutex_init(&osb->recovery_lock);
osb->disable_recovery = 0;
osb->recovery_thread_task = NULL;
init_waitqueue_head(&osb->recovery_event);
rm = kzalloc(sizeof(struct ocfs2_recovery_map) +
osb->max_slots * sizeof(unsigned int),
GFP_KERNEL);
if (!rm) {
mlog_errno(-ENOMEM);
return -ENOMEM;
}
rm->rm_entries = (unsigned int *)((char *)rm +
sizeof(struct ocfs2_recovery_map));
osb->recovery_map = rm;
return 0;
}
/* we can't grab the goofy sem lock from inside wait_event, so we use
* memory barriers to make sure that we'll see the null task before
* being woken up */
static int ocfs2_recovery_thread_running(struct ocfs2_super *osb)
{
mb();
return osb->recovery_thread_task != NULL;
}
void ocfs2_recovery_exit(struct ocfs2_super *osb)
{
struct ocfs2_recovery_map *rm;
/* disable any new recovery threads and wait for any currently
* running ones to exit. Do this before setting the vol_state. */
mutex_lock(&osb->recovery_lock);
osb->disable_recovery = 1;
mutex_unlock(&osb->recovery_lock);
wait_event(osb->recovery_event, !ocfs2_recovery_thread_running(osb));
/* At this point, we know that no more recovery threads can be
* launched, so wait for any recovery completion work to
* complete. */
flush_workqueue(ocfs2_wq);
/*
* Now that recovery is shut down, and the osb is about to be
* freed, the osb_lock is not taken here.
*/
rm = osb->recovery_map;
/* XXX: Should we bug if there are dirty entries? */
kfree(rm);
}
static int __ocfs2_recovery_map_test(struct ocfs2_super *osb,
unsigned int node_num)
{
int i;
struct ocfs2_recovery_map *rm = osb->recovery_map;
assert_spin_locked(&osb->osb_lock);
for (i = 0; i < rm->rm_used; i++) {
if (rm->rm_entries[i] == node_num)
return 1;
}
return 0;
}
/* Behaves like test-and-set. Returns the previous value */
static int ocfs2_recovery_map_set(struct ocfs2_super *osb,
unsigned int node_num)
{
struct ocfs2_recovery_map *rm = osb->recovery_map;
spin_lock(&osb->osb_lock);
if (__ocfs2_recovery_map_test(osb, node_num)) {
spin_unlock(&osb->osb_lock);
return 1;
}
/* XXX: Can this be exploited? Not from o2dlm... */
BUG_ON(rm->rm_used >= osb->max_slots);
rm->rm_entries[rm->rm_used] = node_num;
rm->rm_used++;
spin_unlock(&osb->osb_lock);
return 0;
}
static void ocfs2_recovery_map_clear(struct ocfs2_super *osb,
unsigned int node_num)
{
int i;
struct ocfs2_recovery_map *rm = osb->recovery_map;
spin_lock(&osb->osb_lock);
for (i = 0; i < rm->rm_used; i++) {
if (rm->rm_entries[i] == node_num)
break;
}
if (i < rm->rm_used) {
/* XXX: be careful with the pointer math */
memmove(&(rm->rm_entries[i]), &(rm->rm_entries[i + 1]),
(rm->rm_used - i - 1) * sizeof(unsigned int));
rm->rm_used--;
}
spin_unlock(&osb->osb_lock);
}
static int ocfs2_commit_cache(struct ocfs2_super *osb)
{
int status = 0;
unsigned int flushed;
struct ocfs2_journal *journal = NULL;
journal = osb->journal;
/* Flush all pending commits and checkpoint the journal. */
down_write(&journal->j_trans_barrier);
flushed = atomic_read(&journal->j_num_trans);
trace_ocfs2_commit_cache_begin(flushed);
if (flushed == 0) {
up_write(&journal->j_trans_barrier);
goto finally;
}
jbd2_journal_lock_updates(journal->j_journal);
status = jbd2_journal_flush(journal->j_journal);
jbd2_journal_unlock_updates(journal->j_journal);
if (status < 0) {
up_write(&journal->j_trans_barrier);
mlog_errno(status);
goto finally;
}
ocfs2_inc_trans_id(journal);
flushed = atomic_read(&journal->j_num_trans);
atomic_set(&journal->j_num_trans, 0);
up_write(&journal->j_trans_barrier);
trace_ocfs2_commit_cache_end(journal->j_trans_id, flushed);
ocfs2_wake_downconvert_thread(osb);
wake_up(&journal->j_checkpointed);
finally:
return status;
}
handle_t *ocfs2_start_trans(struct ocfs2_super *osb, int max_buffs)
{
journal_t *journal = osb->journal->j_journal;
handle_t *handle;
BUG_ON(!osb || !osb->journal->j_journal);
if (ocfs2_is_hard_readonly(osb))
return ERR_PTR(-EROFS);
BUG_ON(osb->journal->j_state == OCFS2_JOURNAL_FREE);
BUG_ON(max_buffs <= 0);
/* Nested transaction? Just return the handle... */
if (journal_current_handle())
return jbd2_journal_start(journal, max_buffs);
down_read(&osb->journal->j_trans_barrier);
handle = jbd2_journal_start(journal, max_buffs);
if (IS_ERR(handle)) {
up_read(&osb->journal->j_trans_barrier);
mlog_errno(PTR_ERR(handle));
if (is_journal_aborted(journal)) {
ocfs2_abort(osb->sb, "Detected aborted journal");
handle = ERR_PTR(-EROFS);
}
} else {
if (!ocfs2_mount_local(osb))
atomic_inc(&(osb->journal->j_num_trans));
}
return handle;
}
int ocfs2_commit_trans(struct ocfs2_super *osb,
handle_t *handle)
{
int ret, nested;
struct ocfs2_journal *journal = osb->journal;
BUG_ON(!handle);
nested = handle->h_ref > 1;
ret = jbd2_journal_stop(handle);
if (ret < 0)
mlog_errno(ret);
if (!nested)
up_read(&journal->j_trans_barrier);
return ret;
}
/*
* 'nblocks' is what you want to add to the current transaction.
*
* This might call jbd2_journal_restart() which will commit dirty buffers
* and then restart the transaction. Before calling
* ocfs2_extend_trans(), any changed blocks should have been
* dirtied. After calling it, all blocks which need to be changed must
* go through another set of journal_access/journal_dirty calls.
*
* WARNING: This will not release any semaphores or disk locks taken
* during the transaction, so make sure they were taken *before*
* start_trans or we'll have ordering deadlocks.
*
* WARNING2: Note that we do *not* drop j_trans_barrier here. This is
* good because transaction ids haven't yet been recorded on the
* cluster locks associated with this handle.
*/
int ocfs2_extend_trans(handle_t *handle, int nblocks)
{
int status, old_nblocks;
BUG_ON(!handle);
BUG_ON(nblocks < 0);
if (!nblocks)
return 0;
old_nblocks = handle->h_buffer_credits;
trace_ocfs2_extend_trans(old_nblocks, nblocks);
#ifdef CONFIG_OCFS2_DEBUG_FS
status = 1;
#else
status = jbd2_journal_extend(handle, nblocks);
if (status < 0) {
mlog_errno(status);
goto bail;
}
#endif
if (status > 0) {
trace_ocfs2_extend_trans_restart(old_nblocks + nblocks);
status = jbd2_journal_restart(handle,
old_nblocks + nblocks);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
status = 0;
bail:
return status;
}
struct ocfs2_triggers {
struct jbd2_buffer_trigger_type ot_triggers;
int ot_offset;
};
static inline struct ocfs2_triggers *to_ocfs2_trigger(struct jbd2_buffer_trigger_type *triggers)
{
return container_of(triggers, struct ocfs2_triggers, ot_triggers);
}
static void ocfs2_frozen_trigger(struct jbd2_buffer_trigger_type *triggers,
struct buffer_head *bh,
void *data, size_t size)
{
struct ocfs2_triggers *ot = to_ocfs2_trigger(triggers);
/*
* We aren't guaranteed to have the superblock here, so we
* must unconditionally compute the ecc data.
* __ocfs2_journal_access() will only set the triggers if
* metaecc is enabled.
*/
ocfs2_block_check_compute(data, size, data + ot->ot_offset);
}
/*
* Quota blocks have their own trigger because the struct ocfs2_block_check
* offset depends on the blocksize.
*/
static void ocfs2_dq_frozen_trigger(struct jbd2_buffer_trigger_type *triggers,
struct buffer_head *bh,
void *data, size_t size)
{
struct ocfs2_disk_dqtrailer *dqt =
ocfs2_block_dqtrailer(size, data);
/*
* We aren't guaranteed to have the superblock here, so we
* must unconditionally compute the ecc data.
* __ocfs2_journal_access() will only set the triggers if
* metaecc is enabled.
*/
ocfs2_block_check_compute(data, size, &dqt->dq_check);
}
/*
* Directory blocks also have their own trigger because the
* struct ocfs2_block_check offset depends on the blocksize.
*/
static void ocfs2_db_frozen_trigger(struct jbd2_buffer_trigger_type *triggers,
struct buffer_head *bh,
void *data, size_t size)
{
struct ocfs2_dir_block_trailer *trailer =
ocfs2_dir_trailer_from_size(size, data);
/*
* We aren't guaranteed to have the superblock here, so we
* must unconditionally compute the ecc data.
* __ocfs2_journal_access() will only set the triggers if
* metaecc is enabled.
*/
ocfs2_block_check_compute(data, size, &trailer->db_check);
}
static void ocfs2_abort_trigger(struct jbd2_buffer_trigger_type *triggers,
struct buffer_head *bh)
{
mlog(ML_ERROR,
"ocfs2_abort_trigger called by JBD2. bh = 0x%lx, "
"bh->b_blocknr = %llu\n",
(unsigned long)bh,
(unsigned long long)bh->b_blocknr);
/* We aren't guaranteed to have the superblock here - but if we
* don't, it'll just crash. */
ocfs2_error(bh->b_assoc_map->host->i_sb,
"JBD2 has aborted our journal, ocfs2 cannot continue\n");
}
static struct ocfs2_triggers di_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
.ot_offset = offsetof(struct ocfs2_dinode, i_check),
};
static struct ocfs2_triggers eb_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
.ot_offset = offsetof(struct ocfs2_extent_block, h_check),
};
static struct ocfs2_triggers rb_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
.ot_offset = offsetof(struct ocfs2_refcount_block, rf_check),
};
static struct ocfs2_triggers gd_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
.ot_offset = offsetof(struct ocfs2_group_desc, bg_check),
};
static struct ocfs2_triggers db_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_db_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
};
static struct ocfs2_triggers xb_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
.ot_offset = offsetof(struct ocfs2_xattr_block, xb_check),
};
static struct ocfs2_triggers dq_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_dq_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
};
static struct ocfs2_triggers dr_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
.ot_offset = offsetof(struct ocfs2_dx_root_block, dr_check),
};
static struct ocfs2_triggers dl_triggers = {
.ot_triggers = {
.t_frozen = ocfs2_frozen_trigger,
.t_abort = ocfs2_abort_trigger,
},
.ot_offset = offsetof(struct ocfs2_dx_leaf, dl_check),
};
static int __ocfs2_journal_access(handle_t *handle,
struct ocfs2_caching_info *ci,
struct buffer_head *bh,
struct ocfs2_triggers *triggers,
int type)
{
int status;
struct ocfs2_super *osb =
OCFS2_SB(ocfs2_metadata_cache_get_super(ci));
BUG_ON(!ci || !ci->ci_ops);
BUG_ON(!handle);
BUG_ON(!bh);
trace_ocfs2_journal_access(
(unsigned long long)ocfs2_metadata_cache_owner(ci),
(unsigned long long)bh->b_blocknr, type, bh->b_size);
/* we can safely remove this assertion after testing. */
if (!buffer_uptodate(bh)) {
mlog(ML_ERROR, "giving me a buffer that's not uptodate!\n");
mlog(ML_ERROR, "b_blocknr=%llu\n",
(unsigned long long)bh->b_blocknr);
BUG();
}
/* Set the current transaction information on the ci so
* that the locking code knows whether it can drop it's locks
* on this ci or not. We're protected from the commit
* thread updating the current transaction id until
* ocfs2_commit_trans() because ocfs2_start_trans() took
* j_trans_barrier for us. */
ocfs2_set_ci_lock_trans(osb->journal, ci);
ocfs2_metadata_cache_io_lock(ci);
switch (type) {
case OCFS2_JOURNAL_ACCESS_CREATE:
case OCFS2_JOURNAL_ACCESS_WRITE:
status = jbd2_journal_get_write_access(handle, bh);
break;
case OCFS2_JOURNAL_ACCESS_UNDO:
status = jbd2_journal_get_undo_access(handle, bh);
break;
default:
status = -EINVAL;
mlog(ML_ERROR, "Unknown access type!\n");
}
if (!status && ocfs2_meta_ecc(osb) && triggers)
jbd2_journal_set_triggers(bh, &triggers->ot_triggers);
ocfs2_metadata_cache_io_unlock(ci);
if (status < 0)
mlog(ML_ERROR, "Error %d getting %d access to buffer!\n",
status, type);
return status;
}
int ocfs2_journal_access_di(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &di_triggers, type);
}
int ocfs2_journal_access_eb(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &eb_triggers, type);
}
int ocfs2_journal_access_rb(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &rb_triggers,
type);
}
int ocfs2_journal_access_gd(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &gd_triggers, type);
}
int ocfs2_journal_access_db(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &db_triggers, type);
}
int ocfs2_journal_access_xb(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &xb_triggers, type);
}
int ocfs2_journal_access_dq(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &dq_triggers, type);
}
int ocfs2_journal_access_dr(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &dr_triggers, type);
}
int ocfs2_journal_access_dl(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, &dl_triggers, type);
}
int ocfs2_journal_access(handle_t *handle, struct ocfs2_caching_info *ci,
struct buffer_head *bh, int type)
{
return __ocfs2_journal_access(handle, ci, bh, NULL, type);
}
void ocfs2_journal_dirty(handle_t *handle, struct buffer_head *bh)
{
int status;
trace_ocfs2_journal_dirty((unsigned long long)bh->b_blocknr);
status = jbd2_journal_dirty_metadata(handle, bh);
BUG_ON(status);
}
#define OCFS2_DEFAULT_COMMIT_INTERVAL (HZ * JBD2_DEFAULT_MAX_COMMIT_AGE)
void ocfs2_set_journal_params(struct ocfs2_super *osb)
{
journal_t *journal = osb->journal->j_journal;
unsigned long commit_interval = OCFS2_DEFAULT_COMMIT_INTERVAL;
if (osb->osb_commit_interval)
commit_interval = osb->osb_commit_interval;
write_lock(&journal->j_state_lock);
journal->j_commit_interval = commit_interval;
if (osb->s_mount_opt & OCFS2_MOUNT_BARRIER)
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
write_unlock(&journal->j_state_lock);
}
int ocfs2_journal_init(struct ocfs2_journal *journal, int *dirty)
{
int status = -1;
struct inode *inode = NULL; /* the journal inode */
journal_t *j_journal = NULL;
struct ocfs2_dinode *di = NULL;
struct buffer_head *bh = NULL;
struct ocfs2_super *osb;
int inode_lock = 0;
BUG_ON(!journal);
osb = journal->j_osb;
/* already have the inode for our journal */
inode = ocfs2_get_system_file_inode(osb, JOURNAL_SYSTEM_INODE,
osb->slot_num);
if (inode == NULL) {
status = -EACCES;
mlog_errno(status);
goto done;
}
if (is_bad_inode(inode)) {
mlog(ML_ERROR, "access error (bad inode)\n");
iput(inode);
inode = NULL;
status = -EACCES;
goto done;
}
SET_INODE_JOURNAL(inode);
OCFS2_I(inode)->ip_open_count++;
/* Skip recovery waits here - journal inode metadata never
* changes in a live cluster so it can be considered an
* exception to the rule. */
status = ocfs2_inode_lock_full(inode, &bh, 1, OCFS2_META_LOCK_RECOVERY);
if (status < 0) {
if (status != -ERESTARTSYS)
mlog(ML_ERROR, "Could not get lock on journal!\n");
goto done;
}
inode_lock = 1;
di = (struct ocfs2_dinode *)bh->b_data;
if (inode->i_size < OCFS2_MIN_JOURNAL_SIZE) {
mlog(ML_ERROR, "Journal file size (%lld) is too small!\n",
inode->i_size);
status = -EINVAL;
goto done;
}
trace_ocfs2_journal_init(inode->i_size,
(unsigned long long)inode->i_blocks,
OCFS2_I(inode)->ip_clusters);
/* call the kernels journal init function now */
j_journal = jbd2_journal_init_inode(inode);
if (j_journal == NULL) {
mlog(ML_ERROR, "Linux journal layer error\n");
status = -EINVAL;
goto done;
}
trace_ocfs2_journal_init_maxlen(j_journal->j_maxlen);
*dirty = (le32_to_cpu(di->id1.journal1.ij_flags) &
OCFS2_JOURNAL_DIRTY_FL);
journal->j_journal = j_journal;
journal->j_inode = inode;
journal->j_bh = bh;
ocfs2_set_journal_params(osb);
journal->j_state = OCFS2_JOURNAL_LOADED;
status = 0;
done:
if (status < 0) {
if (inode_lock)
ocfs2_inode_unlock(inode, 1);
brelse(bh);
if (inode) {
OCFS2_I(inode)->ip_open_count--;
iput(inode);
}
}
return status;
}
static void ocfs2_bump_recovery_generation(struct ocfs2_dinode *di)
{
le32_add_cpu(&(di->id1.journal1.ij_recovery_generation), 1);
}
static u32 ocfs2_get_recovery_generation(struct ocfs2_dinode *di)
{
return le32_to_cpu(di->id1.journal1.ij_recovery_generation);
}
static int ocfs2_journal_toggle_dirty(struct ocfs2_super *osb,
int dirty, int replayed)
{
int status;
unsigned int flags;
struct ocfs2_journal *journal = osb->journal;
struct buffer_head *bh = journal->j_bh;
struct ocfs2_dinode *fe;
fe = (struct ocfs2_dinode *)bh->b_data;
/* The journal bh on the osb always comes from ocfs2_journal_init()
* and was validated there inside ocfs2_inode_lock_full(). It's a
* code bug if we mess it up. */
BUG_ON(!OCFS2_IS_VALID_DINODE(fe));
flags = le32_to_cpu(fe->id1.journal1.ij_flags);
if (dirty)
flags |= OCFS2_JOURNAL_DIRTY_FL;
else
flags &= ~OCFS2_JOURNAL_DIRTY_FL;
fe->id1.journal1.ij_flags = cpu_to_le32(flags);
if (replayed)
ocfs2_bump_recovery_generation(fe);
ocfs2_compute_meta_ecc(osb->sb, bh->b_data, &fe->i_check);
status = ocfs2_write_block(osb, bh, INODE_CACHE(journal->j_inode));
if (status < 0)
mlog_errno(status);
return status;
}
/*
* If the journal has been kmalloc'd it needs to be freed after this
* call.
*/
void ocfs2_journal_shutdown(struct ocfs2_super *osb)
{
struct ocfs2_journal *journal = NULL;
int status = 0;
struct inode *inode = NULL;
int num_running_trans = 0;
BUG_ON(!osb);
journal = osb->journal;
if (!journal)
goto done;
inode = journal->j_inode;
if (journal->j_state != OCFS2_JOURNAL_LOADED)
goto done;
/* need to inc inode use count - jbd2_journal_destroy will iput. */
if (!igrab(inode))
BUG();
num_running_trans = atomic_read(&(osb->journal->j_num_trans));
trace_ocfs2_journal_shutdown(num_running_trans);
/* Do a commit_cache here. It will flush our journal, *and*
* release any locks that are still held.
* set the SHUTDOWN flag and release the trans lock.
* the commit thread will take the trans lock for us below. */
journal->j_state = OCFS2_JOURNAL_IN_SHUTDOWN;
/* The OCFS2_JOURNAL_IN_SHUTDOWN will signal to commit_cache to not
* drop the trans_lock (which we want to hold until we
* completely destroy the journal. */
if (osb->commit_task) {
/* Wait for the commit thread */
trace_ocfs2_journal_shutdown_wait(osb->commit_task);
kthread_stop(osb->commit_task);
osb->commit_task = NULL;
}
BUG_ON(atomic_read(&(osb->journal->j_num_trans)) != 0);
if (ocfs2_mount_local(osb)) {
jbd2_journal_lock_updates(journal->j_journal);
status = jbd2_journal_flush(journal->j_journal);
jbd2_journal_unlock_updates(journal->j_journal);
if (status < 0)
mlog_errno(status);
}
if (status == 0) {
/*
* Do not toggle if flush was unsuccessful otherwise
* will leave dirty metadata in a "clean" journal
*/
status = ocfs2_journal_toggle_dirty(osb, 0, 0);
if (status < 0)
mlog_errno(status);
}
/* Shutdown the kernel journal system */
jbd2_journal_destroy(journal->j_journal);
journal->j_journal = NULL;
OCFS2_I(inode)->ip_open_count--;
/* unlock our journal */
ocfs2_inode_unlock(inode, 1);
brelse(journal->j_bh);
journal->j_bh = NULL;
journal->j_state = OCFS2_JOURNAL_FREE;
// up_write(&journal->j_trans_barrier);
done:
if (inode)
iput(inode);
}
static void ocfs2_clear_journal_error(struct super_block *sb,
journal_t *journal,
int slot)
{
int olderr;
olderr = jbd2_journal_errno(journal);
if (olderr) {
mlog(ML_ERROR, "File system error %d recorded in "
"journal %u.\n", olderr, slot);
mlog(ML_ERROR, "File system on device %s needs checking.\n",
sb->s_id);
jbd2_journal_ack_err(journal);
jbd2_journal_clear_err(journal);
}
}
int ocfs2_journal_load(struct ocfs2_journal *journal, int local, int replayed)
{
int status = 0;
struct ocfs2_super *osb;
BUG_ON(!journal);
osb = journal->j_osb;
status = jbd2_journal_load(journal->j_journal);
if (status < 0) {
mlog(ML_ERROR, "Failed to load journal!\n");
goto done;
}
ocfs2_clear_journal_error(osb->sb, journal->j_journal, osb->slot_num);
status = ocfs2_journal_toggle_dirty(osb, 1, replayed);
if (status < 0) {
mlog_errno(status);
goto done;
}
/* Launch the commit thread */
if (!local) {
osb->commit_task = kthread_run(ocfs2_commit_thread, osb,
"ocfs2cmt");
if (IS_ERR(osb->commit_task)) {
status = PTR_ERR(osb->commit_task);
osb->commit_task = NULL;
mlog(ML_ERROR, "unable to launch ocfs2commit thread, "
"error=%d", status);
goto done;
}
} else
osb->commit_task = NULL;
done:
return status;
}
/* 'full' flag tells us whether we clear out all blocks or if we just
* mark the journal clean */
int ocfs2_journal_wipe(struct ocfs2_journal *journal, int full)
{
int status;
BUG_ON(!journal);
status = jbd2_journal_wipe(journal->j_journal, full);
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = ocfs2_journal_toggle_dirty(journal->j_osb, 0, 0);
if (status < 0)
mlog_errno(status);
bail:
return status;
}
static int ocfs2_recovery_completed(struct ocfs2_super *osb)
{
int empty;
struct ocfs2_recovery_map *rm = osb->recovery_map;
spin_lock(&osb->osb_lock);
empty = (rm->rm_used == 0);
spin_unlock(&osb->osb_lock);
return empty;
}
void ocfs2_wait_for_recovery(struct ocfs2_super *osb)
{
wait_event(osb->recovery_event, ocfs2_recovery_completed(osb));
}
/*
* JBD Might read a cached version of another nodes journal file. We
* don't want this as this file changes often and we get no
* notification on those changes. The only way to be sure that we've
* got the most up to date version of those blocks then is to force
* read them off disk. Just searching through the buffer cache won't
* work as there may be pages backing this file which are still marked
* up to date. We know things can't change on this file underneath us
* as we have the lock by now :)
*/
static int ocfs2_force_read_journal(struct inode *inode)
{
int status = 0;
int i;
u64 v_blkno, p_blkno, p_blocks, num_blocks;
#define CONCURRENT_JOURNAL_FILL 32ULL
struct buffer_head *bhs[CONCURRENT_JOURNAL_FILL];
memset(bhs, 0, sizeof(struct buffer_head *) * CONCURRENT_JOURNAL_FILL);
num_blocks = ocfs2_blocks_for_bytes(inode->i_sb, inode->i_size);
v_blkno = 0;
while (v_blkno < num_blocks) {
status = ocfs2_extent_map_get_blocks(inode, v_blkno,
&p_blkno, &p_blocks, NULL);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (p_blocks > CONCURRENT_JOURNAL_FILL)
p_blocks = CONCURRENT_JOURNAL_FILL;
/* We are reading journal data which should not
* be put in the uptodate cache */
status = ocfs2_read_blocks_sync(OCFS2_SB(inode->i_sb),
p_blkno, p_blocks, bhs);
if (status < 0) {
mlog_errno(status);
goto bail;
}
for(i = 0; i < p_blocks; i++) {
brelse(bhs[i]);
bhs[i] = NULL;
}
v_blkno += p_blocks;
}
bail:
for(i = 0; i < CONCURRENT_JOURNAL_FILL; i++)
brelse(bhs[i]);
return status;
}
struct ocfs2_la_recovery_item {
struct list_head lri_list;
int lri_slot;
struct ocfs2_dinode *lri_la_dinode;
struct ocfs2_dinode *lri_tl_dinode;
struct ocfs2_quota_recovery *lri_qrec;
};
/* Does the second half of the recovery process. By this point, the
* node is marked clean and can actually be considered recovered,
* hence it's no longer in the recovery map, but there's still some
* cleanup we can do which shouldn't happen within the recovery thread
* as locking in that context becomes very difficult if we are to take
* recovering nodes into account.
*
* NOTE: This function can and will sleep on recovery of other nodes
* during cluster locking, just like any other ocfs2 process.
*/
void ocfs2_complete_recovery(struct work_struct *work)
{
int ret = 0;
struct ocfs2_journal *journal =
container_of(work, struct ocfs2_journal, j_recovery_work);
struct ocfs2_super *osb = journal->j_osb;
struct ocfs2_dinode *la_dinode, *tl_dinode;
struct ocfs2_la_recovery_item *item, *n;
struct ocfs2_quota_recovery *qrec;
LIST_HEAD(tmp_la_list);
trace_ocfs2_complete_recovery(
(unsigned long long)OCFS2_I(journal->j_inode)->ip_blkno);
spin_lock(&journal->j_lock);
list_splice_init(&journal->j_la_cleanups, &tmp_la_list);
spin_unlock(&journal->j_lock);
list_for_each_entry_safe(item, n, &tmp_la_list, lri_list) {
list_del_init(&item->lri_list);
ocfs2_wait_on_quotas(osb);
la_dinode = item->lri_la_dinode;
tl_dinode = item->lri_tl_dinode;
qrec = item->lri_qrec;
trace_ocfs2_complete_recovery_slot(item->lri_slot,
la_dinode ? le64_to_cpu(la_dinode->i_blkno) : 0,
tl_dinode ? le64_to_cpu(tl_dinode->i_blkno) : 0,
qrec);
if (la_dinode) {
ret = ocfs2_complete_local_alloc_recovery(osb,
la_dinode);
if (ret < 0)
mlog_errno(ret);
kfree(la_dinode);
}
if (tl_dinode) {
ret = ocfs2_complete_truncate_log_recovery(osb,
tl_dinode);
if (ret < 0)
mlog_errno(ret);
kfree(tl_dinode);
}
ret = ocfs2_recover_orphans(osb, item->lri_slot);
if (ret < 0)
mlog_errno(ret);
if (qrec) {
ret = ocfs2_finish_quota_recovery(osb, qrec,
item->lri_slot);
if (ret < 0)
mlog_errno(ret);
/* Recovery info is already freed now */
}
kfree(item);
}
trace_ocfs2_complete_recovery_end(ret);
}
/* NOTE: This function always eats your references to la_dinode and
* tl_dinode, either manually on error, or by passing them to
* ocfs2_complete_recovery */
static void ocfs2_queue_recovery_completion(struct ocfs2_journal *journal,
int slot_num,
struct ocfs2_dinode *la_dinode,
struct ocfs2_dinode *tl_dinode,
struct ocfs2_quota_recovery *qrec)
{
struct ocfs2_la_recovery_item *item;
item = kmalloc(sizeof(struct ocfs2_la_recovery_item), GFP_NOFS);
if (!item) {
/* Though we wish to avoid it, we are in fact safe in
* skipping local alloc cleanup as fsck.ocfs2 is more
* than capable of reclaiming unused space. */
if (la_dinode)
kfree(la_dinode);
if (tl_dinode)
kfree(tl_dinode);
if (qrec)
ocfs2_free_quota_recovery(qrec);
mlog_errno(-ENOMEM);
return;
}
INIT_LIST_HEAD(&item->lri_list);
item->lri_la_dinode = la_dinode;
item->lri_slot = slot_num;
item->lri_tl_dinode = tl_dinode;
item->lri_qrec = qrec;
spin_lock(&journal->j_lock);
list_add_tail(&item->lri_list, &journal->j_la_cleanups);
queue_work(ocfs2_wq, &journal->j_recovery_work);
spin_unlock(&journal->j_lock);
}
/* Called by the mount code to queue recovery the last part of
* recovery for it's own and offline slot(s). */
void ocfs2_complete_mount_recovery(struct ocfs2_super *osb)
{
struct ocfs2_journal *journal = osb->journal;
if (ocfs2_is_hard_readonly(osb))
return;
/* No need to queue up our truncate_log as regular cleanup will catch
* that */
ocfs2_queue_recovery_completion(journal, osb->slot_num,
osb->local_alloc_copy, NULL, NULL);
ocfs2_schedule_truncate_log_flush(osb, 0);
osb->local_alloc_copy = NULL;
osb->dirty = 0;
/* queue to recover orphan slots for all offline slots */
ocfs2_replay_map_set_state(osb, REPLAY_NEEDED);
ocfs2_queue_replay_slots(osb);
ocfs2_free_replay_slots(osb);
}
void ocfs2_complete_quota_recovery(struct ocfs2_super *osb)
{
if (osb->quota_rec) {
ocfs2_queue_recovery_completion(osb->journal,
osb->slot_num,
NULL,
NULL,
osb->quota_rec);
osb->quota_rec = NULL;
}
}
static int __ocfs2_recovery_thread(void *arg)
{
int status, node_num, slot_num;
struct ocfs2_super *osb = arg;
struct ocfs2_recovery_map *rm = osb->recovery_map;
int *rm_quota = NULL;
int rm_quota_used = 0, i;
struct ocfs2_quota_recovery *qrec;
status = ocfs2_wait_on_mount(osb);
if (status < 0) {
goto bail;
}
rm_quota = kzalloc(osb->max_slots * sizeof(int), GFP_NOFS);
if (!rm_quota) {
status = -ENOMEM;
goto bail;
}
restart:
status = ocfs2_super_lock(osb, 1);
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = ocfs2_compute_replay_slots(osb);
if (status < 0)
mlog_errno(status);
/* queue recovery for our own slot */
ocfs2_queue_recovery_completion(osb->journal, osb->slot_num, NULL,
NULL, NULL);
spin_lock(&osb->osb_lock);
while (rm->rm_used) {
/* It's always safe to remove entry zero, as we won't
* clear it until ocfs2_recover_node() has succeeded. */
node_num = rm->rm_entries[0];
spin_unlock(&osb->osb_lock);
slot_num = ocfs2_node_num_to_slot(osb, node_num);
trace_ocfs2_recovery_thread_node(node_num, slot_num);
if (slot_num == -ENOENT) {
status = 0;
goto skip_recovery;
}
/* It is a bit subtle with quota recovery. We cannot do it
* immediately because we have to obtain cluster locks from
* quota files and we also don't want to just skip it because
* then quota usage would be out of sync until some node takes
* the slot. So we remember which nodes need quota recovery
* and when everything else is done, we recover quotas. */
for (i = 0; i < rm_quota_used && rm_quota[i] != slot_num; i++);
if (i == rm_quota_used)
rm_quota[rm_quota_used++] = slot_num;
status = ocfs2_recover_node(osb, node_num, slot_num);
skip_recovery:
if (!status) {
ocfs2_recovery_map_clear(osb, node_num);
} else {
mlog(ML_ERROR,
"Error %d recovering node %d on device (%u,%u)!\n",
status, node_num,
MAJOR(osb->sb->s_dev), MINOR(osb->sb->s_dev));
mlog(ML_ERROR, "Volume requires unmount.\n");
}
spin_lock(&osb->osb_lock);
}
spin_unlock(&osb->osb_lock);
trace_ocfs2_recovery_thread_end(status);
/* Refresh all journal recovery generations from disk */
status = ocfs2_check_journals_nolocks(osb);
status = (status == -EROFS) ? 0 : status;
if (status < 0)
mlog_errno(status);
/* Now it is right time to recover quotas... We have to do this under
* superblock lock so that no one can start using the slot (and crash)
* before we recover it */
for (i = 0; i < rm_quota_used; i++) {
qrec = ocfs2_begin_quota_recovery(osb, rm_quota[i]);
if (IS_ERR(qrec)) {
status = PTR_ERR(qrec);
mlog_errno(status);
continue;
}
ocfs2_queue_recovery_completion(osb->journal, rm_quota[i],
NULL, NULL, qrec);
}
ocfs2_super_unlock(osb, 1);
/* queue recovery for offline slots */
ocfs2_queue_replay_slots(osb);
bail:
mutex_lock(&osb->recovery_lock);
if (!status && !ocfs2_recovery_completed(osb)) {
mutex_unlock(&osb->recovery_lock);
goto restart;
}
ocfs2_free_replay_slots(osb);
osb->recovery_thread_task = NULL;
mb(); /* sync with ocfs2_recovery_thread_running */
wake_up(&osb->recovery_event);
mutex_unlock(&osb->recovery_lock);
if (rm_quota)
kfree(rm_quota);
/* no one is callint kthread_stop() for us so the kthread() api
* requires that we call do_exit(). And it isn't exported, but
* complete_and_exit() seems to be a minimal wrapper around it. */
complete_and_exit(NULL, status);
return status;
}
void ocfs2_recovery_thread(struct ocfs2_super *osb, int node_num)
{
mutex_lock(&osb->recovery_lock);
trace_ocfs2_recovery_thread(node_num, osb->node_num,
osb->disable_recovery, osb->recovery_thread_task,
osb->disable_recovery ?
-1 : ocfs2_recovery_map_set(osb, node_num));
if (osb->disable_recovery)
goto out;
if (osb->recovery_thread_task)
goto out;
osb->recovery_thread_task = kthread_run(__ocfs2_recovery_thread, osb,
"ocfs2rec");
if (IS_ERR(osb->recovery_thread_task)) {
mlog_errno((int)PTR_ERR(osb->recovery_thread_task));
osb->recovery_thread_task = NULL;
}
out:
mutex_unlock(&osb->recovery_lock);
wake_up(&osb->recovery_event);
}
static int ocfs2_read_journal_inode(struct ocfs2_super *osb,
int slot_num,
struct buffer_head **bh,
struct inode **ret_inode)
{
int status = -EACCES;
struct inode *inode = NULL;
BUG_ON(slot_num >= osb->max_slots);
inode = ocfs2_get_system_file_inode(osb, JOURNAL_SYSTEM_INODE,
slot_num);
if (!inode || is_bad_inode(inode)) {
mlog_errno(status);
goto bail;
}
SET_INODE_JOURNAL(inode);
status = ocfs2_read_inode_block_full(inode, bh, OCFS2_BH_IGNORE_CACHE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = 0;
bail:
if (inode) {
if (status || !ret_inode)
iput(inode);
else
*ret_inode = inode;
}
return status;
}
/* Does the actual journal replay and marks the journal inode as
* clean. Will only replay if the journal inode is marked dirty. */
static int ocfs2_replay_journal(struct ocfs2_super *osb,
int node_num,
int slot_num)
{
int status;
int got_lock = 0;
unsigned int flags;
struct inode *inode = NULL;
struct ocfs2_dinode *fe;
journal_t *journal = NULL;
struct buffer_head *bh = NULL;
u32 slot_reco_gen;
status = ocfs2_read_journal_inode(osb, slot_num, &bh, &inode);
if (status) {
mlog_errno(status);
goto done;
}
fe = (struct ocfs2_dinode *)bh->b_data;
slot_reco_gen = ocfs2_get_recovery_generation(fe);
brelse(bh);
bh = NULL;
/*
* As the fs recovery is asynchronous, there is a small chance that
* another node mounted (and recovered) the slot before the recovery
* thread could get the lock. To handle that, we dirty read the journal
* inode for that slot to get the recovery generation. If it is
* different than what we expected, the slot has been recovered.
* If not, it needs recovery.
*/
if (osb->slot_recovery_generations[slot_num] != slot_reco_gen) {
trace_ocfs2_replay_journal_recovered(slot_num,
osb->slot_recovery_generations[slot_num], slot_reco_gen);
osb->slot_recovery_generations[slot_num] = slot_reco_gen;
status = -EBUSY;
goto done;
}
/* Continue with recovery as the journal has not yet been recovered */
status = ocfs2_inode_lock_full(inode, &bh, 1, OCFS2_META_LOCK_RECOVERY);
if (status < 0) {
trace_ocfs2_replay_journal_lock_err(status);
if (status != -ERESTARTSYS)
mlog(ML_ERROR, "Could not lock journal!\n");
goto done;
}
got_lock = 1;
fe = (struct ocfs2_dinode *) bh->b_data;
flags = le32_to_cpu(fe->id1.journal1.ij_flags);
slot_reco_gen = ocfs2_get_recovery_generation(fe);
if (!(flags & OCFS2_JOURNAL_DIRTY_FL)) {
trace_ocfs2_replay_journal_skip(node_num);
/* Refresh recovery generation for the slot */
osb->slot_recovery_generations[slot_num] = slot_reco_gen;
goto done;
}
/* we need to run complete recovery for offline orphan slots */
ocfs2_replay_map_set_state(osb, REPLAY_NEEDED);
mlog(ML_NOTICE, "Recovering node %d from slot %d on device (%u,%u)\n",
node_num, slot_num,
MAJOR(osb->sb->s_dev), MINOR(osb->sb->s_dev));
OCFS2_I(inode)->ip_clusters = le32_to_cpu(fe->i_clusters);
status = ocfs2_force_read_journal(inode);
if (status < 0) {
mlog_errno(status);
goto done;
}
journal = jbd2_journal_init_inode(inode);
if (journal == NULL) {
mlog(ML_ERROR, "Linux journal layer error\n");
status = -EIO;
goto done;
}
status = jbd2_journal_load(journal);
if (status < 0) {
mlog_errno(status);
if (!igrab(inode))
BUG();
jbd2_journal_destroy(journal);
goto done;
}
ocfs2_clear_journal_error(osb->sb, journal, slot_num);
/* wipe the journal */
jbd2_journal_lock_updates(journal);
status = jbd2_journal_flush(journal);
jbd2_journal_unlock_updates(journal);
if (status < 0)
mlog_errno(status);
/* This will mark the node clean */
flags = le32_to_cpu(fe->id1.journal1.ij_flags);
flags &= ~OCFS2_JOURNAL_DIRTY_FL;
fe->id1.journal1.ij_flags = cpu_to_le32(flags);
/* Increment recovery generation to indicate successful recovery */
ocfs2_bump_recovery_generation(fe);
osb->slot_recovery_generations[slot_num] =
ocfs2_get_recovery_generation(fe);
ocfs2_compute_meta_ecc(osb->sb, bh->b_data, &fe->i_check);
status = ocfs2_write_block(osb, bh, INODE_CACHE(inode));
if (status < 0)
mlog_errno(status);
if (!igrab(inode))
BUG();
jbd2_journal_destroy(journal);
done:
/* drop the lock on this nodes journal */
if (got_lock)
ocfs2_inode_unlock(inode, 1);
if (inode)
iput(inode);
brelse(bh);
return status;
}
/*
* Do the most important parts of node recovery:
* - Replay it's journal
* - Stamp a clean local allocator file
* - Stamp a clean truncate log
* - Mark the node clean
*
* If this function completes without error, a node in OCFS2 can be
* said to have been safely recovered. As a result, failure during the
* second part of a nodes recovery process (local alloc recovery) is
* far less concerning.
*/
static int ocfs2_recover_node(struct ocfs2_super *osb,
int node_num, int slot_num)
{
int status = 0;
struct ocfs2_dinode *la_copy = NULL;
struct ocfs2_dinode *tl_copy = NULL;
trace_ocfs2_recover_node(node_num, slot_num, osb->node_num);
/* Should not ever be called to recover ourselves -- in that
* case we should've called ocfs2_journal_load instead. */
BUG_ON(osb->node_num == node_num);
status = ocfs2_replay_journal(osb, node_num, slot_num);
if (status < 0) {
if (status == -EBUSY) {
trace_ocfs2_recover_node_skip(slot_num, node_num);
status = 0;
goto done;
}
mlog_errno(status);
goto done;
}
/* Stamp a clean local alloc file AFTER recovering the journal... */
status = ocfs2_begin_local_alloc_recovery(osb, slot_num, &la_copy);
if (status < 0) {
mlog_errno(status);
goto done;
}
/* An error from begin_truncate_log_recovery is not
* serious enough to warrant halting the rest of
* recovery. */
status = ocfs2_begin_truncate_log_recovery(osb, slot_num, &tl_copy);
if (status < 0)
mlog_errno(status);
/* Likewise, this would be a strange but ultimately not so
* harmful place to get an error... */
status = ocfs2_clear_slot(osb, slot_num);
if (status < 0)
mlog_errno(status);
/* This will kfree the memory pointed to by la_copy and tl_copy */
ocfs2_queue_recovery_completion(osb->journal, slot_num, la_copy,
tl_copy, NULL);
status = 0;
done:
return status;
}
/* Test node liveness by trylocking his journal. If we get the lock,
* we drop it here. Return 0 if we got the lock, -EAGAIN if node is
* still alive (we couldn't get the lock) and < 0 on error. */
static int ocfs2_trylock_journal(struct ocfs2_super *osb,
int slot_num)
{
int status, flags;
struct inode *inode = NULL;
inode = ocfs2_get_system_file_inode(osb, JOURNAL_SYSTEM_INODE,
slot_num);
if (inode == NULL) {
mlog(ML_ERROR, "access error\n");
status = -EACCES;
goto bail;
}
if (is_bad_inode(inode)) {
mlog(ML_ERROR, "access error (bad inode)\n");
iput(inode);
inode = NULL;
status = -EACCES;
goto bail;
}
SET_INODE_JOURNAL(inode);
flags = OCFS2_META_LOCK_RECOVERY | OCFS2_META_LOCK_NOQUEUE;
status = ocfs2_inode_lock_full(inode, NULL, 1, flags);
if (status < 0) {
if (status != -EAGAIN)
mlog_errno(status);
goto bail;
}
ocfs2_inode_unlock(inode, 1);
bail:
if (inode)
iput(inode);
return status;
}
/* Call this underneath ocfs2_super_lock. It also assumes that the
* slot info struct has been updated from disk. */
int ocfs2_mark_dead_nodes(struct ocfs2_super *osb)
{
unsigned int node_num;
int status, i;
u32 gen;
struct buffer_head *bh = NULL;
struct ocfs2_dinode *di;
/* This is called with the super block cluster lock, so we
* know that the slot map can't change underneath us. */
for (i = 0; i < osb->max_slots; i++) {
/* Read journal inode to get the recovery generation */
status = ocfs2_read_journal_inode(osb, i, &bh, NULL);
if (status) {
mlog_errno(status);
goto bail;
}
di = (struct ocfs2_dinode *)bh->b_data;
gen = ocfs2_get_recovery_generation(di);
brelse(bh);
bh = NULL;
spin_lock(&osb->osb_lock);
osb->slot_recovery_generations[i] = gen;
trace_ocfs2_mark_dead_nodes(i,
osb->slot_recovery_generations[i]);
if (i == osb->slot_num) {
spin_unlock(&osb->osb_lock);
continue;
}
status = ocfs2_slot_to_node_num_locked(osb, i, &node_num);
if (status == -ENOENT) {
spin_unlock(&osb->osb_lock);
continue;
}
if (__ocfs2_recovery_map_test(osb, node_num)) {
spin_unlock(&osb->osb_lock);
continue;
}
spin_unlock(&osb->osb_lock);
/* Ok, we have a slot occupied by another node which
* is not in the recovery map. We trylock his journal
* file here to test if he's alive. */
status = ocfs2_trylock_journal(osb, i);
if (!status) {
/* Since we're called from mount, we know that
* the recovery thread can't race us on
* setting / checking the recovery bits. */
ocfs2_recovery_thread(osb, node_num);
} else if ((status < 0) && (status != -EAGAIN)) {
mlog_errno(status);
goto bail;
}
}
status = 0;
bail:
return status;
}
/*
* Scan timer should get fired every ORPHAN_SCAN_SCHEDULE_TIMEOUT. Add some
* randomness to the timeout to minimize multple nodes firing the timer at the
* same time.
*/
static inline unsigned long ocfs2_orphan_scan_timeout(void)
{
unsigned long time;
get_random_bytes(&time, sizeof(time));
time = ORPHAN_SCAN_SCHEDULE_TIMEOUT + (time % 5000);
return msecs_to_jiffies(time);
}
/*
* ocfs2_queue_orphan_scan calls ocfs2_queue_recovery_completion for
* every slot, queuing a recovery of the slot on the ocfs2_wq thread. This
* is done to catch any orphans that are left over in orphan directories.
*
* ocfs2_queue_orphan_scan gets called every ORPHAN_SCAN_SCHEDULE_TIMEOUT
* seconds. It gets an EX lock on os_lockres and checks sequence number
* stored in LVB. If the sequence number has changed, it means some other
* node has done the scan. This node skips the scan and tracks the
* sequence number. If the sequence number didn't change, it means a scan
* hasn't happened. The node queues a scan and increments the
* sequence number in the LVB.
*/
void ocfs2_queue_orphan_scan(struct ocfs2_super *osb)
{
struct ocfs2_orphan_scan *os;
int status, i;
u32 seqno = 0;
os = &osb->osb_orphan_scan;
if (atomic_read(&os->os_state) == ORPHAN_SCAN_INACTIVE)
goto out;
trace_ocfs2_queue_orphan_scan_begin(os->os_count, os->os_seqno,
atomic_read(&os->os_state));
status = ocfs2_orphan_scan_lock(osb, &seqno);
if (status < 0) {
if (status != -EAGAIN)
mlog_errno(status);
goto out;
}
/* Do no queue the tasks if the volume is being umounted */
if (atomic_read(&os->os_state) == ORPHAN_SCAN_INACTIVE)
goto unlock;
if (os->os_seqno != seqno) {
os->os_seqno = seqno;
goto unlock;
}
for (i = 0; i < osb->max_slots; i++)
ocfs2_queue_recovery_completion(osb->journal, i, NULL, NULL,
NULL);
/*
* We queued a recovery on orphan slots, increment the sequence
* number and update LVB so other node will skip the scan for a while
*/
seqno++;
os->os_count++;
os->os_scantime = CURRENT_TIME;
unlock:
ocfs2_orphan_scan_unlock(osb, seqno);
out:
trace_ocfs2_queue_orphan_scan_end(os->os_count, os->os_seqno,
atomic_read(&os->os_state));
return;
}
/* Worker task that gets fired every ORPHAN_SCAN_SCHEDULE_TIMEOUT millsec */
void ocfs2_orphan_scan_work(struct work_struct *work)
{
struct ocfs2_orphan_scan *os;
struct ocfs2_super *osb;
os = container_of(work, struct ocfs2_orphan_scan,
os_orphan_scan_work.work);
osb = os->os_osb;
mutex_lock(&os->os_lock);
ocfs2_queue_orphan_scan(osb);
if (atomic_read(&os->os_state) == ORPHAN_SCAN_ACTIVE)
queue_delayed_work(ocfs2_wq, &os->os_orphan_scan_work,
ocfs2_orphan_scan_timeout());
mutex_unlock(&os->os_lock);
}
void ocfs2_orphan_scan_stop(struct ocfs2_super *osb)
{
struct ocfs2_orphan_scan *os;
os = &osb->osb_orphan_scan;
if (atomic_read(&os->os_state) == ORPHAN_SCAN_ACTIVE) {
atomic_set(&os->os_state, ORPHAN_SCAN_INACTIVE);
mutex_lock(&os->os_lock);
cancel_delayed_work(&os->os_orphan_scan_work);
mutex_unlock(&os->os_lock);
}
}
void ocfs2_orphan_scan_init(struct ocfs2_super *osb)
{
struct ocfs2_orphan_scan *os;
os = &osb->osb_orphan_scan;
os->os_osb = osb;
os->os_count = 0;
os->os_seqno = 0;
mutex_init(&os->os_lock);
INIT_DELAYED_WORK(&os->os_orphan_scan_work, ocfs2_orphan_scan_work);
}
void ocfs2_orphan_scan_start(struct ocfs2_super *osb)
{
struct ocfs2_orphan_scan *os;
os = &osb->osb_orphan_scan;
os->os_scantime = CURRENT_TIME;
if (ocfs2_is_hard_readonly(osb) || ocfs2_mount_local(osb))
atomic_set(&os->os_state, ORPHAN_SCAN_INACTIVE);
else {
atomic_set(&os->os_state, ORPHAN_SCAN_ACTIVE);
queue_delayed_work(ocfs2_wq, &os->os_orphan_scan_work,
ocfs2_orphan_scan_timeout());
}
}
struct ocfs2_orphan_filldir_priv {
struct inode *head;
struct ocfs2_super *osb;
};
static int ocfs2_orphan_filldir(void *priv, const char *name, int name_len,
loff_t pos, u64 ino, unsigned type)
{
struct ocfs2_orphan_filldir_priv *p = priv;
struct inode *iter;
if (name_len == 1 && !strncmp(".", name, 1))
return 0;
if (name_len == 2 && !strncmp("..", name, 2))
return 0;
/* Skip bad inodes so that recovery can continue */
iter = ocfs2_iget(p->osb, ino,
OCFS2_FI_FLAG_ORPHAN_RECOVERY, 0);
if (IS_ERR(iter))
return 0;
trace_ocfs2_orphan_filldir((unsigned long long)OCFS2_I(iter)->ip_blkno);
/* No locking is required for the next_orphan queue as there
* is only ever a single process doing orphan recovery. */
OCFS2_I(iter)->ip_next_orphan = p->head;
p->head = iter;
return 0;
}
static int ocfs2_queue_orphans(struct ocfs2_super *osb,
int slot,
struct inode **head)
{
int status;
struct inode *orphan_dir_inode = NULL;
struct ocfs2_orphan_filldir_priv priv;
loff_t pos = 0;
priv.osb = osb;
priv.head = *head;
orphan_dir_inode = ocfs2_get_system_file_inode(osb,
ORPHAN_DIR_SYSTEM_INODE,
slot);
if (!orphan_dir_inode) {
status = -ENOENT;
mlog_errno(status);
return status;
}
mutex_lock(&orphan_dir_inode->i_mutex);
status = ocfs2_inode_lock(orphan_dir_inode, NULL, 0);
if (status < 0) {
mlog_errno(status);
goto out;
}
status = ocfs2_dir_foreach(orphan_dir_inode, &pos, &priv,
ocfs2_orphan_filldir);
if (status) {
mlog_errno(status);
goto out_cluster;
}
*head = priv.head;
out_cluster:
ocfs2_inode_unlock(orphan_dir_inode, 0);
out:
mutex_unlock(&orphan_dir_inode->i_mutex);
iput(orphan_dir_inode);
return status;
}
static int ocfs2_orphan_recovery_can_continue(struct ocfs2_super *osb,
int slot)
{
int ret;
spin_lock(&osb->osb_lock);
ret = !osb->osb_orphan_wipes[slot];
spin_unlock(&osb->osb_lock);
return ret;
}
static void ocfs2_mark_recovering_orphan_dir(struct ocfs2_super *osb,
int slot)
{
spin_lock(&osb->osb_lock);
/* Mark ourselves such that new processes in delete_inode()
* know to quit early. */
ocfs2_node_map_set_bit(osb, &osb->osb_recovering_orphan_dirs, slot);
while (osb->osb_orphan_wipes[slot]) {
/* If any processes are already in the middle of an
* orphan wipe on this dir, then we need to wait for
* them. */
spin_unlock(&osb->osb_lock);
wait_event_interruptible(osb->osb_wipe_event,
ocfs2_orphan_recovery_can_continue(osb, slot));
spin_lock(&osb->osb_lock);
}
spin_unlock(&osb->osb_lock);
}
static void ocfs2_clear_recovering_orphan_dir(struct ocfs2_super *osb,
int slot)
{
ocfs2_node_map_clear_bit(osb, &osb->osb_recovering_orphan_dirs, slot);
}
/*
* Orphan recovery. Each mounted node has it's own orphan dir which we
* must run during recovery. Our strategy here is to build a list of
* the inodes in the orphan dir and iget/iput them. The VFS does
* (most) of the rest of the work.
*
* Orphan recovery can happen at any time, not just mount so we have a
* couple of extra considerations.
*
* - We grab as many inodes as we can under the orphan dir lock -
* doing iget() outside the orphan dir risks getting a reference on
* an invalid inode.
* - We must be sure not to deadlock with other processes on the
* system wanting to run delete_inode(). This can happen when they go
* to lock the orphan dir and the orphan recovery process attempts to
* iget() inside the orphan dir lock. This can be avoided by
* advertising our state to ocfs2_delete_inode().
*/
static int ocfs2_recover_orphans(struct ocfs2_super *osb,
int slot)
{
int ret = 0;
struct inode *inode = NULL;
struct inode *iter;
struct ocfs2_inode_info *oi;
trace_ocfs2_recover_orphans(slot);
ocfs2_mark_recovering_orphan_dir(osb, slot);
ret = ocfs2_queue_orphans(osb, slot, &inode);
ocfs2_clear_recovering_orphan_dir(osb, slot);
/* Error here should be noted, but we want to continue with as
* many queued inodes as we've got. */
if (ret)
mlog_errno(ret);
while (inode) {
oi = OCFS2_I(inode);
trace_ocfs2_recover_orphans_iput(
(unsigned long long)oi->ip_blkno);
iter = oi->ip_next_orphan;
spin_lock(&oi->ip_lock);
/* The remote delete code may have set these on the
* assumption that the other node would wipe them
* successfully. If they are still in the node's
* orphan dir, we need to reset that state. */
oi->ip_flags &= ~(OCFS2_INODE_DELETED|OCFS2_INODE_SKIP_DELETE);
/* Set the proper information to get us going into
* ocfs2_delete_inode. */
oi->ip_flags |= OCFS2_INODE_MAYBE_ORPHANED;
spin_unlock(&oi->ip_lock);
iput(inode);
inode = iter;
}
return ret;
}
static int __ocfs2_wait_on_mount(struct ocfs2_super *osb, int quota)
{
/* This check is good because ocfs2 will wait on our recovery
* thread before changing it to something other than MOUNTED
* or DISABLED. */
wait_event(osb->osb_mount_event,
(!quota && atomic_read(&osb->vol_state) == VOLUME_MOUNTED) ||
atomic_read(&osb->vol_state) == VOLUME_MOUNTED_QUOTAS ||
atomic_read(&osb->vol_state) == VOLUME_DISABLED);
/* If there's an error on mount, then we may never get to the
* MOUNTED flag, but this is set right before
* dismount_volume() so we can trust it. */
if (atomic_read(&osb->vol_state) == VOLUME_DISABLED) {
trace_ocfs2_wait_on_mount(VOLUME_DISABLED);
mlog(0, "mount error, exiting!\n");
return -EBUSY;
}
return 0;
}
static int ocfs2_commit_thread(void *arg)
{
int status;
struct ocfs2_super *osb = arg;
struct ocfs2_journal *journal = osb->journal;
/* we can trust j_num_trans here because _should_stop() is only set in
* shutdown and nobody other than ourselves should be able to start
* transactions. committing on shutdown might take a few iterations
* as final transactions put deleted inodes on the list */
while (!(kthread_should_stop() &&
atomic_read(&journal->j_num_trans) == 0)) {
wait_event_interruptible(osb->checkpoint_event,
atomic_read(&journal->j_num_trans)
|| kthread_should_stop());
status = ocfs2_commit_cache(osb);
if (status < 0)
mlog_errno(status);
if (kthread_should_stop() && atomic_read(&journal->j_num_trans)){
mlog(ML_KTHREAD,
"commit_thread: %u transactions pending on "
"shutdown\n",
atomic_read(&journal->j_num_trans));
}
}
return 0;
}
/* Reads all the journal inodes without taking any cluster locks. Used
* for hard readonly access to determine whether any journal requires
* recovery. Also used to refresh the recovery generation numbers after
* a journal has been recovered by another node.
*/
int ocfs2_check_journals_nolocks(struct ocfs2_super *osb)
{
int ret = 0;
unsigned int slot;
struct buffer_head *di_bh = NULL;
struct ocfs2_dinode *di;
int journal_dirty = 0;
for(slot = 0; slot < osb->max_slots; slot++) {
ret = ocfs2_read_journal_inode(osb, slot, &di_bh, NULL);
if (ret) {
mlog_errno(ret);
goto out;
}
di = (struct ocfs2_dinode *) di_bh->b_data;
osb->slot_recovery_generations[slot] =
ocfs2_get_recovery_generation(di);
if (le32_to_cpu(di->id1.journal1.ij_flags) &
OCFS2_JOURNAL_DIRTY_FL)
journal_dirty = 1;
brelse(di_bh);
di_bh = NULL;
}
out:
if (journal_dirty)
ret = -EROFS;
return ret;
}
| gpl-2.0 |
flar2/m8-GPE-5.0.1 | net/irda/ircomm/ircomm_tty.c | 4489 | 39081 | /*********************************************************************
*
* Filename: ircomm_tty.c
* Version: 1.0
* Description: IrCOMM serial TTY driver
* Status: Experimental.
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Sun Jun 6 21:00:56 1999
* Modified at: Wed Feb 23 00:09:02 2000
* Modified by: Dag Brattli <dagb@cs.uit.no>
* Sources: serial.c and previous IrCOMM work by Takahide Higuchi
*
* Copyright (c) 1999-2000 Dag Brattli, All Rights Reserved.
* Copyright (c) 2000-2003 Jean Tourrilhes <jt@hpl.hp.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/module.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/termios.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/interrupt.h>
#include <linux/device.h> /* for MODULE_ALIAS_CHARDEV_MAJOR */
#include <asm/uaccess.h>
#include <net/irda/irda.h>
#include <net/irda/irmod.h>
#include <net/irda/ircomm_core.h>
#include <net/irda/ircomm_param.h>
#include <net/irda/ircomm_tty_attach.h>
#include <net/irda/ircomm_tty.h>
static int ircomm_tty_open(struct tty_struct *tty, struct file *filp);
static void ircomm_tty_close(struct tty_struct * tty, struct file *filp);
static int ircomm_tty_write(struct tty_struct * tty,
const unsigned char *buf, int count);
static int ircomm_tty_write_room(struct tty_struct *tty);
static void ircomm_tty_throttle(struct tty_struct *tty);
static void ircomm_tty_unthrottle(struct tty_struct *tty);
static int ircomm_tty_chars_in_buffer(struct tty_struct *tty);
static void ircomm_tty_flush_buffer(struct tty_struct *tty);
static void ircomm_tty_send_xchar(struct tty_struct *tty, char ch);
static void ircomm_tty_wait_until_sent(struct tty_struct *tty, int timeout);
static void ircomm_tty_hangup(struct tty_struct *tty);
static void ircomm_tty_do_softint(struct work_struct *work);
static void ircomm_tty_shutdown(struct ircomm_tty_cb *self);
static void ircomm_tty_stop(struct tty_struct *tty);
static int ircomm_tty_data_indication(void *instance, void *sap,
struct sk_buff *skb);
static int ircomm_tty_control_indication(void *instance, void *sap,
struct sk_buff *skb);
static void ircomm_tty_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd);
#ifdef CONFIG_PROC_FS
static const struct file_operations ircomm_tty_proc_fops;
#endif /* CONFIG_PROC_FS */
static struct tty_driver *driver;
static hashbin_t *ircomm_tty = NULL;
static const struct tty_operations ops = {
.open = ircomm_tty_open,
.close = ircomm_tty_close,
.write = ircomm_tty_write,
.write_room = ircomm_tty_write_room,
.chars_in_buffer = ircomm_tty_chars_in_buffer,
.flush_buffer = ircomm_tty_flush_buffer,
.ioctl = ircomm_tty_ioctl, /* ircomm_tty_ioctl.c */
.tiocmget = ircomm_tty_tiocmget, /* ircomm_tty_ioctl.c */
.tiocmset = ircomm_tty_tiocmset, /* ircomm_tty_ioctl.c */
.throttle = ircomm_tty_throttle,
.unthrottle = ircomm_tty_unthrottle,
.send_xchar = ircomm_tty_send_xchar,
.set_termios = ircomm_tty_set_termios,
.stop = ircomm_tty_stop,
.start = ircomm_tty_start,
.hangup = ircomm_tty_hangup,
.wait_until_sent = ircomm_tty_wait_until_sent,
#ifdef CONFIG_PROC_FS
.proc_fops = &ircomm_tty_proc_fops,
#endif /* CONFIG_PROC_FS */
};
/*
* Function ircomm_tty_init()
*
* Init IrCOMM TTY layer/driver
*
*/
static int __init ircomm_tty_init(void)
{
driver = alloc_tty_driver(IRCOMM_TTY_PORTS);
if (!driver)
return -ENOMEM;
ircomm_tty = hashbin_new(HB_LOCK);
if (ircomm_tty == NULL) {
IRDA_ERROR("%s(), can't allocate hashbin!\n", __func__);
put_tty_driver(driver);
return -ENOMEM;
}
driver->driver_name = "ircomm";
driver->name = "ircomm";
driver->major = IRCOMM_TTY_MAJOR;
driver->minor_start = IRCOMM_TTY_MINOR;
driver->type = TTY_DRIVER_TYPE_SERIAL;
driver->subtype = SERIAL_TYPE_NORMAL;
driver->init_termios = tty_std_termios;
driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
driver->flags = TTY_DRIVER_REAL_RAW;
tty_set_operations(driver, &ops);
if (tty_register_driver(driver)) {
IRDA_ERROR("%s(): Couldn't register serial driver\n",
__func__);
put_tty_driver(driver);
return -1;
}
return 0;
}
static void __exit __ircomm_tty_cleanup(struct ircomm_tty_cb *self)
{
IRDA_DEBUG(0, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
ircomm_tty_shutdown(self);
self->magic = 0;
kfree(self);
}
/*
* Function ircomm_tty_cleanup ()
*
* Remove IrCOMM TTY layer/driver
*
*/
static void __exit ircomm_tty_cleanup(void)
{
int ret;
IRDA_DEBUG(4, "%s()\n", __func__ );
ret = tty_unregister_driver(driver);
if (ret) {
IRDA_ERROR("%s(), failed to unregister driver\n",
__func__);
return;
}
hashbin_delete(ircomm_tty, (FREE_FUNC) __ircomm_tty_cleanup);
put_tty_driver(driver);
}
/*
* Function ircomm_startup (self)
*
*
*
*/
static int ircomm_tty_startup(struct ircomm_tty_cb *self)
{
notify_t notify;
int ret = -ENODEV;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return -1;);
/* Check if already open */
if (test_and_set_bit(ASYNC_B_INITIALIZED, &self->flags)) {
IRDA_DEBUG(2, "%s(), already open so break out!\n", __func__ );
return 0;
}
/* Register with IrCOMM */
irda_notify_init(¬ify);
/* These callbacks we must handle ourselves */
notify.data_indication = ircomm_tty_data_indication;
notify.udata_indication = ircomm_tty_control_indication;
notify.flow_indication = ircomm_tty_flow_indication;
/* Use the ircomm_tty interface for these ones */
notify.disconnect_indication = ircomm_tty_disconnect_indication;
notify.connect_confirm = ircomm_tty_connect_confirm;
notify.connect_indication = ircomm_tty_connect_indication;
strlcpy(notify.name, "ircomm_tty", sizeof(notify.name));
notify.instance = self;
if (!self->ircomm) {
self->ircomm = ircomm_open(¬ify, self->service_type,
self->line);
}
if (!self->ircomm)
goto err;
self->slsap_sel = self->ircomm->slsap_sel;
/* Connect IrCOMM link with remote device */
ret = ircomm_tty_attach_cable(self);
if (ret < 0) {
IRDA_ERROR("%s(), error attaching cable!\n", __func__);
goto err;
}
return 0;
err:
clear_bit(ASYNC_B_INITIALIZED, &self->flags);
return ret;
}
/*
* Function ircomm_block_til_ready (self, filp)
*
*
*
*/
static int ircomm_tty_block_til_ready(struct ircomm_tty_cb *self,
struct file *filp)
{
DECLARE_WAITQUEUE(wait, current);
int retval;
int do_clocal = 0, extra_count = 0;
unsigned long flags;
struct tty_struct *tty;
IRDA_DEBUG(2, "%s()\n", __func__ );
tty = self->tty;
/*
* If non-blocking mode is set, or the port is not enabled,
* then make the check up front and then exit.
*/
if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){
/* nonblock mode is set or port is not enabled */
self->flags |= ASYNC_NORMAL_ACTIVE;
IRDA_DEBUG(1, "%s(), O_NONBLOCK requested!\n", __func__ );
return 0;
}
if (tty->termios->c_cflag & CLOCAL) {
IRDA_DEBUG(1, "%s(), doing CLOCAL!\n", __func__ );
do_clocal = 1;
}
/* Wait for carrier detect and the line to become
* free (i.e., not in use by the callout). While we are in
* this loop, self->open_count is dropped by one, so that
* mgsl_close() knows when to free things. We restore it upon
* exit, either normal or abnormal.
*/
retval = 0;
add_wait_queue(&self->open_wait, &wait);
IRDA_DEBUG(2, "%s(%d):block_til_ready before block on %s open_count=%d\n",
__FILE__,__LINE__, tty->driver->name, self->open_count );
/* As far as I can see, we protect open_count - Jean II */
spin_lock_irqsave(&self->spinlock, flags);
if (!tty_hung_up_p(filp)) {
extra_count = 1;
self->open_count--;
}
spin_unlock_irqrestore(&self->spinlock, flags);
self->blocked_open++;
while (1) {
if (tty->termios->c_cflag & CBAUD) {
/* Here, we use to lock those two guys, but
* as ircomm_param_request() does it itself,
* I don't see the point (and I see the deadlock).
* Jean II */
self->settings.dte |= IRCOMM_RTS + IRCOMM_DTR;
ircomm_param_request(self, IRCOMM_DTE, TRUE);
}
current->state = TASK_INTERRUPTIBLE;
if (tty_hung_up_p(filp) ||
!test_bit(ASYNC_B_INITIALIZED, &self->flags)) {
retval = (self->flags & ASYNC_HUP_NOTIFY) ?
-EAGAIN : -ERESTARTSYS;
break;
}
/*
* Check if link is ready now. Even if CLOCAL is
* specified, we cannot return before the IrCOMM link is
* ready
*/
if (!test_bit(ASYNC_B_CLOSING, &self->flags) &&
(do_clocal || (self->settings.dce & IRCOMM_CD)) &&
self->state == IRCOMM_TTY_READY)
{
break;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
IRDA_DEBUG(1, "%s(%d):block_til_ready blocking on %s open_count=%d\n",
__FILE__,__LINE__, tty->driver->name, self->open_count );
schedule();
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(&self->open_wait, &wait);
if (extra_count) {
/* ++ is not atomic, so this should be protected - Jean II */
spin_lock_irqsave(&self->spinlock, flags);
self->open_count++;
spin_unlock_irqrestore(&self->spinlock, flags);
}
self->blocked_open--;
IRDA_DEBUG(1, "%s(%d):block_til_ready after blocking on %s open_count=%d\n",
__FILE__,__LINE__, tty->driver->name, self->open_count);
if (!retval)
self->flags |= ASYNC_NORMAL_ACTIVE;
return retval;
}
/*
* Function ircomm_tty_open (tty, filp)
*
* This routine is called when a particular tty device is opened. This
* routine is mandatory; if this routine is not filled in, the attempted
* open will fail with ENODEV.
*/
static int ircomm_tty_open(struct tty_struct *tty, struct file *filp)
{
struct ircomm_tty_cb *self;
unsigned int line = tty->index;
unsigned long flags;
int ret;
IRDA_DEBUG(2, "%s()\n", __func__ );
/* Check if instance already exists */
self = hashbin_lock_find(ircomm_tty, line, NULL);
if (!self) {
/* No, so make new instance */
self = kzalloc(sizeof(struct ircomm_tty_cb), GFP_KERNEL);
if (self == NULL) {
IRDA_ERROR("%s(), kmalloc failed!\n", __func__);
return -ENOMEM;
}
self->magic = IRCOMM_TTY_MAGIC;
self->flow = FLOW_STOP;
self->line = line;
INIT_WORK(&self->tqueue, ircomm_tty_do_softint);
self->max_header_size = IRCOMM_TTY_HDR_UNINITIALISED;
self->max_data_size = IRCOMM_TTY_DATA_UNINITIALISED;
self->close_delay = 5*HZ/10;
self->closing_wait = 30*HZ;
/* Init some important stuff */
init_timer(&self->watchdog_timer);
init_waitqueue_head(&self->open_wait);
init_waitqueue_head(&self->close_wait);
spin_lock_init(&self->spinlock);
/*
* Force TTY into raw mode by default which is usually what
* we want for IrCOMM and IrLPT. This way applications will
* not have to twiddle with printcap etc.
*
* Note this is completely usafe and doesn't work properly
*/
tty->termios->c_iflag = 0;
tty->termios->c_oflag = 0;
/* Insert into hash */
hashbin_insert(ircomm_tty, (irda_queue_t *) self, line, NULL);
}
/* ++ is not atomic, so this should be protected - Jean II */
spin_lock_irqsave(&self->spinlock, flags);
self->open_count++;
tty->driver_data = self;
self->tty = tty;
spin_unlock_irqrestore(&self->spinlock, flags);
IRDA_DEBUG(1, "%s(), %s%d, count = %d\n", __func__ , tty->driver->name,
self->line, self->open_count);
/* Not really used by us, but lets do it anyway */
self->tty->low_latency = (self->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
/*
* If the port is the middle of closing, bail out now
*/
if (tty_hung_up_p(filp) ||
test_bit(ASYNC_B_CLOSING, &self->flags)) {
/* Hm, why are we blocking on ASYNC_CLOSING if we
* do return -EAGAIN/-ERESTARTSYS below anyway?
* IMHO it's either not needed in the first place
* or for some reason we need to make sure the async
* closing has been finished - if so, wouldn't we
* probably better sleep uninterruptible?
*/
if (wait_event_interruptible(self->close_wait, !test_bit(ASYNC_B_CLOSING, &self->flags))) {
IRDA_WARNING("%s - got signal while blocking on ASYNC_CLOSING!\n",
__func__);
return -ERESTARTSYS;
}
#ifdef SERIAL_DO_RESTART
return (self->flags & ASYNC_HUP_NOTIFY) ?
-EAGAIN : -ERESTARTSYS;
#else
return -EAGAIN;
#endif
}
/* Check if this is a "normal" ircomm device, or an irlpt device */
if (line < 0x10) {
self->service_type = IRCOMM_3_WIRE | IRCOMM_9_WIRE;
self->settings.service_type = IRCOMM_9_WIRE; /* 9 wire as default */
/* Jan Kiszka -> add DSR/RI -> Conform to IrCOMM spec */
self->settings.dce = IRCOMM_CTS | IRCOMM_CD | IRCOMM_DSR | IRCOMM_RI; /* Default line settings */
IRDA_DEBUG(2, "%s(), IrCOMM device\n", __func__ );
} else {
IRDA_DEBUG(2, "%s(), IrLPT device\n", __func__ );
self->service_type = IRCOMM_3_WIRE_RAW;
self->settings.service_type = IRCOMM_3_WIRE_RAW; /* Default */
}
ret = ircomm_tty_startup(self);
if (ret)
return ret;
ret = ircomm_tty_block_til_ready(self, filp);
if (ret) {
IRDA_DEBUG(2,
"%s(), returning after block_til_ready with %d\n", __func__ ,
ret);
return ret;
}
return 0;
}
/*
* Function ircomm_tty_close (tty, filp)
*
* This routine is called when a particular tty device is closed.
*
*/
static void ircomm_tty_close(struct tty_struct *tty, struct file *filp)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned long flags;
IRDA_DEBUG(0, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
spin_lock_irqsave(&self->spinlock, flags);
if (tty_hung_up_p(filp)) {
spin_unlock_irqrestore(&self->spinlock, flags);
IRDA_DEBUG(0, "%s(), returning 1\n", __func__ );
return;
}
if ((tty->count == 1) && (self->open_count != 1)) {
/*
* Uh, oh. tty->count is 1, which means that the tty
* structure will be freed. state->count should always
* be one in these conditions. If it's greater than
* one, we've got real problems, since it means the
* serial port won't be shutdown.
*/
IRDA_DEBUG(0, "%s(), bad serial port count; "
"tty->count is 1, state->count is %d\n", __func__ ,
self->open_count);
self->open_count = 1;
}
if (--self->open_count < 0) {
IRDA_ERROR("%s(), bad serial port count for ttys%d: %d\n",
__func__, self->line, self->open_count);
self->open_count = 0;
}
if (self->open_count) {
spin_unlock_irqrestore(&self->spinlock, flags);
IRDA_DEBUG(0, "%s(), open count > 0\n", __func__ );
return;
}
/* Hum... Should be test_and_set_bit ??? - Jean II */
set_bit(ASYNC_B_CLOSING, &self->flags);
/* We need to unlock here (we were unlocking at the end of this
* function), because tty_wait_until_sent() may schedule.
* I don't know if the rest should be protected somehow,
* so someone should check. - Jean II */
spin_unlock_irqrestore(&self->spinlock, flags);
/*
* Now we wait for the transmit buffer to clear; and we notify
* the line discipline to only process XON/XOFF characters.
*/
tty->closing = 1;
if (self->closing_wait != ASYNC_CLOSING_WAIT_NONE)
tty_wait_until_sent_from_close(tty, self->closing_wait);
ircomm_tty_shutdown(self);
tty_driver_flush_buffer(tty);
tty_ldisc_flush(tty);
tty->closing = 0;
self->tty = NULL;
if (self->blocked_open) {
if (self->close_delay)
schedule_timeout_interruptible(self->close_delay);
wake_up_interruptible(&self->open_wait);
}
self->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
wake_up_interruptible(&self->close_wait);
}
/*
* Function ircomm_tty_flush_buffer (tty)
*
*
*
*/
static void ircomm_tty_flush_buffer(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
/*
* Let do_softint() do this to avoid race condition with
* do_softint() ;-)
*/
schedule_work(&self->tqueue);
}
/*
* Function ircomm_tty_do_softint (work)
*
* We use this routine to give the write wakeup to the user at at a
* safe time (as fast as possible after write have completed). This
* can be compared to the Tx interrupt.
*/
static void ircomm_tty_do_softint(struct work_struct *work)
{
struct ircomm_tty_cb *self =
container_of(work, struct ircomm_tty_cb, tqueue);
struct tty_struct *tty;
unsigned long flags;
struct sk_buff *skb, *ctrl_skb;
IRDA_DEBUG(2, "%s()\n", __func__ );
if (!self || self->magic != IRCOMM_TTY_MAGIC)
return;
tty = self->tty;
if (!tty)
return;
/* Unlink control buffer */
spin_lock_irqsave(&self->spinlock, flags);
ctrl_skb = self->ctrl_skb;
self->ctrl_skb = NULL;
spin_unlock_irqrestore(&self->spinlock, flags);
/* Flush control buffer if any */
if(ctrl_skb) {
if(self->flow == FLOW_START)
ircomm_control_request(self->ircomm, ctrl_skb);
/* Drop reference count - see ircomm_ttp_data_request(). */
dev_kfree_skb(ctrl_skb);
}
if (tty->hw_stopped)
return;
/* Unlink transmit buffer */
spin_lock_irqsave(&self->spinlock, flags);
skb = self->tx_skb;
self->tx_skb = NULL;
spin_unlock_irqrestore(&self->spinlock, flags);
/* Flush transmit buffer if any */
if (skb) {
ircomm_tty_do_event(self, IRCOMM_TTY_DATA_REQUEST, skb, NULL);
/* Drop reference count - see ircomm_ttp_data_request(). */
dev_kfree_skb(skb);
}
/* Check if user (still) wants to be waken up */
tty_wakeup(tty);
}
/*
* Function ircomm_tty_write (tty, buf, count)
*
* This routine is called by the kernel to write a series of characters
* to the tty device. The characters may come from user space or kernel
* space. This routine will return the number of characters actually
* accepted for writing. This routine is mandatory.
*/
static int ircomm_tty_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned long flags;
struct sk_buff *skb;
int tailroom = 0;
int len = 0;
int size;
IRDA_DEBUG(2, "%s(), count=%d, hw_stopped=%d\n", __func__ , count,
tty->hw_stopped);
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return -1;);
/* We may receive packets from the TTY even before we have finished
* our setup. Not cool.
* The problem is that we don't know the final header and data size
* to create the proper skb, so any skb we would create would have
* bogus header and data size, so need care.
* We use a bogus header size to safely detect this condition.
* Another problem is that hw_stopped was set to 0 way before it
* should be, so we would drop this skb. It should now be fixed.
* One option is to not accept data until we are properly setup.
* But, I suspect that when it happens, the ppp line discipline
* just "drops" the data, which might screw up connect scripts.
* The second option is to create a "safe skb", with large header
* and small size (see ircomm_tty_open() for values).
* We just need to make sure that when the real values get filled,
* we don't mess up the original "safe skb" (see tx_data_size).
* Jean II */
if (self->max_header_size == IRCOMM_TTY_HDR_UNINITIALISED) {
IRDA_DEBUG(1, "%s() : not initialised\n", __func__);
#ifdef IRCOMM_NO_TX_BEFORE_INIT
/* We didn't consume anything, TTY will retry */
return 0;
#endif
}
if (count < 1)
return 0;
/* Protect our manipulation of self->tx_skb and related */
spin_lock_irqsave(&self->spinlock, flags);
/* Fetch current transmit buffer */
skb = self->tx_skb;
/*
* Send out all the data we get, possibly as multiple fragmented
* frames, but this will only happen if the data is larger than the
* max data size. The normal case however is just the opposite, and
* this function may be called multiple times, and will then actually
* defragment the data and send it out as one packet as soon as
* possible, but at a safer point in time
*/
while (count) {
size = count;
/* Adjust data size to the max data size */
if (size > self->max_data_size)
size = self->max_data_size;
/*
* Do we already have a buffer ready for transmit, or do
* we need to allocate a new frame
*/
if (skb) {
/*
* Any room for more data at the end of the current
* transmit buffer? Cannot use skb_tailroom, since
* dev_alloc_skb gives us a larger skb than we
* requested
* Note : use tx_data_size, because max_data_size
* may have changed and we don't want to overwrite
* the skb. - Jean II
*/
if ((tailroom = (self->tx_data_size - skb->len)) > 0) {
/* Adjust data to tailroom */
if (size > tailroom)
size = tailroom;
} else {
/*
* Current transmit frame is full, so break
* out, so we can send it as soon as possible
*/
break;
}
} else {
/* Prepare a full sized frame */
skb = alloc_skb(self->max_data_size+
self->max_header_size,
GFP_ATOMIC);
if (!skb) {
spin_unlock_irqrestore(&self->spinlock, flags);
return -ENOBUFS;
}
skb_reserve(skb, self->max_header_size);
self->tx_skb = skb;
/* Remember skb size because max_data_size may
* change later on - Jean II */
self->tx_data_size = self->max_data_size;
}
/* Copy data */
memcpy(skb_put(skb,size), buf + len, size);
count -= size;
len += size;
}
spin_unlock_irqrestore(&self->spinlock, flags);
/*
* Schedule a new thread which will transmit the frame as soon
* as possible, but at a safe point in time. We do this so the
* "user" can give us data multiple times, as PPP does (because of
* its 256 byte tx buffer). We will then defragment and send out
* all this data as one single packet.
*/
schedule_work(&self->tqueue);
return len;
}
/*
* Function ircomm_tty_write_room (tty)
*
* This routine returns the numbers of characters the tty driver will
* accept for queuing to be written. This number is subject to change as
* output buffers get emptied, or if the output flow control is acted.
*/
static int ircomm_tty_write_room(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned long flags;
int ret;
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return -1;);
#ifdef IRCOMM_NO_TX_BEFORE_INIT
/* max_header_size tells us if the channel is initialised or not. */
if (self->max_header_size == IRCOMM_TTY_HDR_UNINITIALISED)
/* Don't bother us yet */
return 0;
#endif
/* Check if we are allowed to transmit any data.
* hw_stopped is the regular flow control.
* Jean II */
if (tty->hw_stopped)
ret = 0;
else {
spin_lock_irqsave(&self->spinlock, flags);
if (self->tx_skb)
ret = self->tx_data_size - self->tx_skb->len;
else
ret = self->max_data_size;
spin_unlock_irqrestore(&self->spinlock, flags);
}
IRDA_DEBUG(2, "%s(), ret=%d\n", __func__ , ret);
return ret;
}
/*
* Function ircomm_tty_wait_until_sent (tty, timeout)
*
* This routine waits until the device has written out all of the
* characters in its transmitter FIFO.
*/
static void ircomm_tty_wait_until_sent(struct tty_struct *tty, int timeout)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned long orig_jiffies, poll_time;
unsigned long flags;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
orig_jiffies = jiffies;
/* Set poll time to 200 ms */
poll_time = IRDA_MIN(timeout, msecs_to_jiffies(200));
spin_lock_irqsave(&self->spinlock, flags);
while (self->tx_skb && self->tx_skb->len) {
spin_unlock_irqrestore(&self->spinlock, flags);
schedule_timeout_interruptible(poll_time);
spin_lock_irqsave(&self->spinlock, flags);
if (signal_pending(current))
break;
if (timeout && time_after(jiffies, orig_jiffies + timeout))
break;
}
spin_unlock_irqrestore(&self->spinlock, flags);
current->state = TASK_RUNNING;
}
/*
* Function ircomm_tty_throttle (tty)
*
* This routine notifies the tty driver that input buffers for the line
* discipline are close to full, and it should somehow signal that no
* more characters should be sent to the tty.
*/
static void ircomm_tty_throttle(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
/* Software flow control? */
if (I_IXOFF(tty))
ircomm_tty_send_xchar(tty, STOP_CHAR(tty));
/* Hardware flow control? */
if (tty->termios->c_cflag & CRTSCTS) {
self->settings.dte &= ~IRCOMM_RTS;
self->settings.dte |= IRCOMM_DELTA_RTS;
ircomm_param_request(self, IRCOMM_DTE, TRUE);
}
ircomm_flow_request(self->ircomm, FLOW_STOP);
}
/*
* Function ircomm_tty_unthrottle (tty)
*
* This routine notifies the tty drivers that it should signals that
* characters can now be sent to the tty without fear of overrunning the
* input buffers of the line disciplines.
*/
static void ircomm_tty_unthrottle(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
/* Using software flow control? */
if (I_IXOFF(tty)) {
ircomm_tty_send_xchar(tty, START_CHAR(tty));
}
/* Using hardware flow control? */
if (tty->termios->c_cflag & CRTSCTS) {
self->settings.dte |= (IRCOMM_RTS|IRCOMM_DELTA_RTS);
ircomm_param_request(self, IRCOMM_DTE, TRUE);
IRDA_DEBUG(1, "%s(), FLOW_START\n", __func__ );
}
ircomm_flow_request(self->ircomm, FLOW_START);
}
/*
* Function ircomm_tty_chars_in_buffer (tty)
*
* Indicates if there are any data in the buffer
*
*/
static int ircomm_tty_chars_in_buffer(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned long flags;
int len = 0;
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return -1;);
spin_lock_irqsave(&self->spinlock, flags);
if (self->tx_skb)
len = self->tx_skb->len;
spin_unlock_irqrestore(&self->spinlock, flags);
return len;
}
static void ircomm_tty_shutdown(struct ircomm_tty_cb *self)
{
unsigned long flags;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
IRDA_DEBUG(0, "%s()\n", __func__ );
if (!test_and_clear_bit(ASYNC_B_INITIALIZED, &self->flags))
return;
ircomm_tty_detach_cable(self);
spin_lock_irqsave(&self->spinlock, flags);
del_timer(&self->watchdog_timer);
/* Free parameter buffer */
if (self->ctrl_skb) {
dev_kfree_skb(self->ctrl_skb);
self->ctrl_skb = NULL;
}
/* Free transmit buffer */
if (self->tx_skb) {
dev_kfree_skb(self->tx_skb);
self->tx_skb = NULL;
}
if (self->ircomm) {
ircomm_close(self->ircomm);
self->ircomm = NULL;
}
spin_unlock_irqrestore(&self->spinlock, flags);
}
/*
* Function ircomm_tty_hangup (tty)
*
* This routine notifies the tty driver that it should hangup the tty
* device.
*
*/
static void ircomm_tty_hangup(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned long flags;
IRDA_DEBUG(0, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
/* ircomm_tty_flush_buffer(tty); */
ircomm_tty_shutdown(self);
/* I guess we need to lock here - Jean II */
spin_lock_irqsave(&self->spinlock, flags);
self->flags &= ~ASYNC_NORMAL_ACTIVE;
self->tty = NULL;
self->open_count = 0;
spin_unlock_irqrestore(&self->spinlock, flags);
wake_up_interruptible(&self->open_wait);
}
/*
* Function ircomm_tty_send_xchar (tty, ch)
*
* This routine is used to send a high-priority XON/XOFF character to
* the device.
*/
static void ircomm_tty_send_xchar(struct tty_struct *tty, char ch)
{
IRDA_DEBUG(0, "%s(), not impl\n", __func__ );
}
/*
* Function ircomm_tty_start (tty)
*
* This routine notifies the tty driver that it resume sending
* characters to the tty device.
*/
void ircomm_tty_start(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
ircomm_flow_request(self->ircomm, FLOW_START);
}
/*
* Function ircomm_tty_stop (tty)
*
* This routine notifies the tty driver that it should stop outputting
* characters to the tty device.
*/
static void ircomm_tty_stop(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
ircomm_flow_request(self->ircomm, FLOW_STOP);
}
/*
* Function ircomm_check_modem_status (self)
*
* Check for any changes in the DCE's line settings. This function should
* be called whenever the dce parameter settings changes, to update the
* flow control settings and other things
*/
void ircomm_tty_check_modem_status(struct ircomm_tty_cb *self)
{
struct tty_struct *tty;
int status;
IRDA_DEBUG(0, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
tty = self->tty;
status = self->settings.dce;
if (status & IRCOMM_DCE_DELTA_ANY) {
/*wake_up_interruptible(&self->delta_msr_wait);*/
}
if ((self->flags & ASYNC_CHECK_CD) && (status & IRCOMM_DELTA_CD)) {
IRDA_DEBUG(2,
"%s(), ircomm%d CD now %s...\n", __func__ , self->line,
(status & IRCOMM_CD) ? "on" : "off");
if (status & IRCOMM_CD) {
wake_up_interruptible(&self->open_wait);
} else {
IRDA_DEBUG(2,
"%s(), Doing serial hangup..\n", __func__ );
if (tty)
tty_hangup(tty);
/* Hangup will remote the tty, so better break out */
return;
}
}
if (self->flags & ASYNC_CTS_FLOW) {
if (tty->hw_stopped) {
if (status & IRCOMM_CTS) {
IRDA_DEBUG(2,
"%s(), CTS tx start...\n", __func__ );
tty->hw_stopped = 0;
/* Wake up processes blocked on open */
wake_up_interruptible(&self->open_wait);
schedule_work(&self->tqueue);
return;
}
} else {
if (!(status & IRCOMM_CTS)) {
IRDA_DEBUG(2,
"%s(), CTS tx stop...\n", __func__ );
tty->hw_stopped = 1;
}
}
}
}
/*
* Function ircomm_tty_data_indication (instance, sap, skb)
*
* Handle incoming data, and deliver it to the line discipline
*
*/
static int ircomm_tty_data_indication(void *instance, void *sap,
struct sk_buff *skb)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) instance;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return -1;);
IRDA_ASSERT(skb != NULL, return -1;);
if (!self->tty) {
IRDA_DEBUG(0, "%s(), no tty!\n", __func__ );
return 0;
}
/*
* If we receive data when hardware is stopped then something is wrong.
* We try to poll the peers line settings to check if we are up todate.
* Devices like WinCE can do this, and since they don't send any
* params, we can just as well declare the hardware for running.
*/
if (self->tty->hw_stopped && (self->flow == FLOW_START)) {
IRDA_DEBUG(0, "%s(), polling for line settings!\n", __func__ );
ircomm_param_request(self, IRCOMM_POLL, TRUE);
/* We can just as well declare the hardware for running */
ircomm_tty_send_initial_parameters(self);
ircomm_tty_link_established(self);
}
/*
* Use flip buffer functions since the code may be called from interrupt
* context
*/
tty_insert_flip_string(self->tty, skb->data, skb->len);
tty_flip_buffer_push(self->tty);
/* No need to kfree_skb - see ircomm_ttp_data_indication() */
return 0;
}
/*
* Function ircomm_tty_control_indication (instance, sap, skb)
*
* Parse all incoming parameters (easy!)
*
*/
static int ircomm_tty_control_indication(void *instance, void *sap,
struct sk_buff *skb)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) instance;
int clen;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return -1;);
IRDA_ASSERT(skb != NULL, return -1;);
clen = skb->data[0];
irda_param_extract_all(self, skb->data+1, IRDA_MIN(skb->len-1, clen),
&ircomm_param_info);
/* No need to kfree_skb - see ircomm_control_indication() */
return 0;
}
/*
* Function ircomm_tty_flow_indication (instance, sap, cmd)
*
* This function is called by IrTTP when it wants us to slow down the
* transmission of data. We just mark the hardware as stopped, and wait
* for IrTTP to notify us that things are OK again.
*/
static void ircomm_tty_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) instance;
struct tty_struct *tty;
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return;);
tty = self->tty;
switch (cmd) {
case FLOW_START:
IRDA_DEBUG(2, "%s(), hw start!\n", __func__ );
tty->hw_stopped = 0;
/* ircomm_tty_do_softint will take care of the rest */
schedule_work(&self->tqueue);
break;
default: /* If we get here, something is very wrong, better stop */
case FLOW_STOP:
IRDA_DEBUG(2, "%s(), hw stopped!\n", __func__ );
tty->hw_stopped = 1;
break;
}
self->flow = cmd;
}
#ifdef CONFIG_PROC_FS
static void ircomm_tty_line_info(struct ircomm_tty_cb *self, struct seq_file *m)
{
char sep;
seq_printf(m, "State: %s\n", ircomm_tty_state[self->state]);
seq_puts(m, "Service type: ");
if (self->service_type & IRCOMM_9_WIRE)
seq_puts(m, "9_WIRE");
else if (self->service_type & IRCOMM_3_WIRE)
seq_puts(m, "3_WIRE");
else if (self->service_type & IRCOMM_3_WIRE_RAW)
seq_puts(m, "3_WIRE_RAW");
else
seq_puts(m, "No common service type!\n");
seq_putc(m, '\n');
seq_printf(m, "Port name: %s\n", self->settings.port_name);
seq_printf(m, "DTE status:");
sep = ' ';
if (self->settings.dte & IRCOMM_RTS) {
seq_printf(m, "%cRTS", sep);
sep = '|';
}
if (self->settings.dte & IRCOMM_DTR) {
seq_printf(m, "%cDTR", sep);
sep = '|';
}
seq_putc(m, '\n');
seq_puts(m, "DCE status:");
sep = ' ';
if (self->settings.dce & IRCOMM_CTS) {
seq_printf(m, "%cCTS", sep);
sep = '|';
}
if (self->settings.dce & IRCOMM_DSR) {
seq_printf(m, "%cDSR", sep);
sep = '|';
}
if (self->settings.dce & IRCOMM_CD) {
seq_printf(m, "%cCD", sep);
sep = '|';
}
if (self->settings.dce & IRCOMM_RI) {
seq_printf(m, "%cRI", sep);
sep = '|';
}
seq_putc(m, '\n');
seq_puts(m, "Configuration: ");
if (!self->settings.null_modem)
seq_puts(m, "DTE <-> DCE\n");
else
seq_puts(m, "DTE <-> DTE (null modem emulation)\n");
seq_printf(m, "Data rate: %d\n", self->settings.data_rate);
seq_puts(m, "Flow control:");
sep = ' ';
if (self->settings.flow_control & IRCOMM_XON_XOFF_IN) {
seq_printf(m, "%cXON_XOFF_IN", sep);
sep = '|';
}
if (self->settings.flow_control & IRCOMM_XON_XOFF_OUT) {
seq_printf(m, "%cXON_XOFF_OUT", sep);
sep = '|';
}
if (self->settings.flow_control & IRCOMM_RTS_CTS_IN) {
seq_printf(m, "%cRTS_CTS_IN", sep);
sep = '|';
}
if (self->settings.flow_control & IRCOMM_RTS_CTS_OUT) {
seq_printf(m, "%cRTS_CTS_OUT", sep);
sep = '|';
}
if (self->settings.flow_control & IRCOMM_DSR_DTR_IN) {
seq_printf(m, "%cDSR_DTR_IN", sep);
sep = '|';
}
if (self->settings.flow_control & IRCOMM_DSR_DTR_OUT) {
seq_printf(m, "%cDSR_DTR_OUT", sep);
sep = '|';
}
if (self->settings.flow_control & IRCOMM_ENQ_ACK_IN) {
seq_printf(m, "%cENQ_ACK_IN", sep);
sep = '|';
}
if (self->settings.flow_control & IRCOMM_ENQ_ACK_OUT) {
seq_printf(m, "%cENQ_ACK_OUT", sep);
sep = '|';
}
seq_putc(m, '\n');
seq_puts(m, "Flags:");
sep = ' ';
if (self->flags & ASYNC_CTS_FLOW) {
seq_printf(m, "%cASYNC_CTS_FLOW", sep);
sep = '|';
}
if (self->flags & ASYNC_CHECK_CD) {
seq_printf(m, "%cASYNC_CHECK_CD", sep);
sep = '|';
}
if (self->flags & ASYNC_INITIALIZED) {
seq_printf(m, "%cASYNC_INITIALIZED", sep);
sep = '|';
}
if (self->flags & ASYNC_LOW_LATENCY) {
seq_printf(m, "%cASYNC_LOW_LATENCY", sep);
sep = '|';
}
if (self->flags & ASYNC_CLOSING) {
seq_printf(m, "%cASYNC_CLOSING", sep);
sep = '|';
}
if (self->flags & ASYNC_NORMAL_ACTIVE) {
seq_printf(m, "%cASYNC_NORMAL_ACTIVE", sep);
sep = '|';
}
seq_putc(m, '\n');
seq_printf(m, "Role: %s\n", self->client ? "client" : "server");
seq_printf(m, "Open count: %d\n", self->open_count);
seq_printf(m, "Max data size: %d\n", self->max_data_size);
seq_printf(m, "Max header size: %d\n", self->max_header_size);
if (self->tty)
seq_printf(m, "Hardware: %s\n",
self->tty->hw_stopped ? "Stopped" : "Running");
}
static int ircomm_tty_proc_show(struct seq_file *m, void *v)
{
struct ircomm_tty_cb *self;
unsigned long flags;
spin_lock_irqsave(&ircomm_tty->hb_spinlock, flags);
self = (struct ircomm_tty_cb *) hashbin_get_first(ircomm_tty);
while (self != NULL) {
if (self->magic != IRCOMM_TTY_MAGIC)
break;
ircomm_tty_line_info(self, m);
self = (struct ircomm_tty_cb *) hashbin_get_next(ircomm_tty);
}
spin_unlock_irqrestore(&ircomm_tty->hb_spinlock, flags);
return 0;
}
static int ircomm_tty_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, ircomm_tty_proc_show, NULL);
}
static const struct file_operations ircomm_tty_proc_fops = {
.owner = THIS_MODULE,
.open = ircomm_tty_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_PROC_FS */
MODULE_AUTHOR("Dag Brattli <dagb@cs.uit.no>");
MODULE_DESCRIPTION("IrCOMM serial TTY driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(IRCOMM_TTY_MAJOR);
module_init(ircomm_tty_init);
module_exit(ircomm_tty_cleanup);
| gpl-2.0 |
nmacs/lm3s-linux | tools/perf/util/usage.c | 4745 | 1690 | /*
* GIT - The information manager from hell
*
* Copyright (C) Linus Torvalds, 2005
*/
#include "util.h"
static void report(const char *prefix, const char *err, va_list params)
{
char msg[1024];
vsnprintf(msg, sizeof(msg), err, params);
fprintf(stderr, " %s%s\n", prefix, msg);
}
static NORETURN void usage_builtin(const char *err)
{
fprintf(stderr, "\n Usage: %s\n", err);
exit(129);
}
static NORETURN void die_builtin(const char *err, va_list params)
{
report(" Fatal: ", err, params);
exit(128);
}
static void error_builtin(const char *err, va_list params)
{
report(" Error: ", err, params);
}
static void warn_builtin(const char *warn, va_list params)
{
report(" Warning: ", warn, params);
}
/* If we are in a dlopen()ed .so write to a global variable would segfault
* (ugh), so keep things static. */
static void (*usage_routine)(const char *err) NORETURN = usage_builtin;
static void (*die_routine)(const char *err, va_list params) NORETURN = die_builtin;
static void (*error_routine)(const char *err, va_list params) = error_builtin;
static void (*warn_routine)(const char *err, va_list params) = warn_builtin;
void set_die_routine(void (*routine)(const char *err, va_list params) NORETURN)
{
die_routine = routine;
}
void usage(const char *err)
{
usage_routine(err);
}
void die(const char *err, ...)
{
va_list params;
va_start(params, err);
die_routine(err, params);
va_end(params);
}
int error(const char *err, ...)
{
va_list params;
va_start(params, err);
error_routine(err, params);
va_end(params);
return -1;
}
void warning(const char *warn, ...)
{
va_list params;
va_start(params, warn);
warn_routine(warn, params);
va_end(params);
}
| gpl-2.0 |
Tesla-M-Devices/android_kernel_motorola_msm8226 | arch/x86/platform/olpc/olpc-xo15-sci.c | 4745 | 5531 | /*
* Support for OLPC XO-1.5 System Control Interrupts (SCI)
*
* Copyright (C) 2009-2010 One Laptop per Child
*
* 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/device.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/power_supply.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include <asm/olpc.h>
#define DRV_NAME "olpc-xo15-sci"
#define PFX DRV_NAME ": "
#define XO15_SCI_CLASS DRV_NAME
#define XO15_SCI_DEVICE_NAME "OLPC XO-1.5 SCI"
static unsigned long xo15_sci_gpe;
static bool lid_wake_on_close;
/*
* The normal ACPI LID wakeup behavior is wake-on-open, but not
* wake-on-close. This is implemented as standard by the XO-1.5 DSDT.
*
* We provide here a sysfs attribute that will additionally enable
* wake-on-close behavior. This is useful (e.g.) when we oportunistically
* suspend with the display running; if the lid is then closed, we want to
* wake up to turn the display off.
*
* This is controlled through a custom method in the XO-1.5 DSDT.
*/
static int set_lid_wake_behavior(bool wake_on_close)
{
struct acpi_object_list arg_list;
union acpi_object arg;
acpi_status status;
arg_list.count = 1;
arg_list.pointer = &arg;
arg.type = ACPI_TYPE_INTEGER;
arg.integer.value = wake_on_close;
status = acpi_evaluate_object(NULL, "\\_SB.PCI0.LID.LIDW", &arg_list, NULL);
if (ACPI_FAILURE(status)) {
pr_warning(PFX "failed to set lid behavior\n");
return 1;
}
lid_wake_on_close = wake_on_close;
return 0;
}
static ssize_t
lid_wake_on_close_show(struct kobject *s, struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", lid_wake_on_close);
}
static ssize_t lid_wake_on_close_store(struct kobject *s,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
unsigned int val;
if (sscanf(buf, "%u", &val) != 1)
return -EINVAL;
set_lid_wake_behavior(!!val);
return n;
}
static struct kobj_attribute lid_wake_on_close_attr =
__ATTR(lid_wake_on_close, 0644,
lid_wake_on_close_show,
lid_wake_on_close_store);
static void battery_status_changed(void)
{
struct power_supply *psy = power_supply_get_by_name("olpc-battery");
if (psy) {
power_supply_changed(psy);
put_device(psy->dev);
}
}
static void ac_status_changed(void)
{
struct power_supply *psy = power_supply_get_by_name("olpc-ac");
if (psy) {
power_supply_changed(psy);
put_device(psy->dev);
}
}
static void process_sci_queue(void)
{
u16 data;
int r;
do {
r = olpc_ec_sci_query(&data);
if (r || !data)
break;
pr_debug(PFX "SCI 0x%x received\n", data);
switch (data) {
case EC_SCI_SRC_BATERR:
case EC_SCI_SRC_BATSOC:
case EC_SCI_SRC_BATTERY:
case EC_SCI_SRC_BATCRIT:
battery_status_changed();
break;
case EC_SCI_SRC_ACPWR:
ac_status_changed();
break;
}
} while (data);
if (r)
pr_err(PFX "Failed to clear SCI queue");
}
static void process_sci_queue_work(struct work_struct *work)
{
process_sci_queue();
}
static DECLARE_WORK(sci_work, process_sci_queue_work);
static u32 xo15_sci_gpe_handler(acpi_handle gpe_device, u32 gpe, void *context)
{
schedule_work(&sci_work);
return ACPI_INTERRUPT_HANDLED | ACPI_REENABLE_GPE;
}
static int xo15_sci_add(struct acpi_device *device)
{
unsigned long long tmp;
acpi_status status;
int r;
if (!device)
return -EINVAL;
strcpy(acpi_device_name(device), XO15_SCI_DEVICE_NAME);
strcpy(acpi_device_class(device), XO15_SCI_CLASS);
/* Get GPE bit assignment (EC events). */
status = acpi_evaluate_integer(device->handle, "_GPE", NULL, &tmp);
if (ACPI_FAILURE(status))
return -EINVAL;
xo15_sci_gpe = tmp;
status = acpi_install_gpe_handler(NULL, xo15_sci_gpe,
ACPI_GPE_EDGE_TRIGGERED,
xo15_sci_gpe_handler, device);
if (ACPI_FAILURE(status))
return -ENODEV;
dev_info(&device->dev, "Initialized, GPE = 0x%lx\n", xo15_sci_gpe);
r = sysfs_create_file(&device->dev.kobj, &lid_wake_on_close_attr.attr);
if (r)
goto err_sysfs;
/* Flush queue, and enable all SCI events */
process_sci_queue();
olpc_ec_mask_write(EC_SCI_SRC_ALL);
acpi_enable_gpe(NULL, xo15_sci_gpe);
/* Enable wake-on-EC */
if (device->wakeup.flags.valid)
device_init_wakeup(&device->dev, true);
return 0;
err_sysfs:
acpi_remove_gpe_handler(NULL, xo15_sci_gpe, xo15_sci_gpe_handler);
cancel_work_sync(&sci_work);
return r;
}
static int xo15_sci_remove(struct acpi_device *device, int type)
{
acpi_disable_gpe(NULL, xo15_sci_gpe);
acpi_remove_gpe_handler(NULL, xo15_sci_gpe, xo15_sci_gpe_handler);
cancel_work_sync(&sci_work);
sysfs_remove_file(&device->dev.kobj, &lid_wake_on_close_attr.attr);
return 0;
}
static int xo15_sci_resume(struct acpi_device *device)
{
/* Enable all EC events */
olpc_ec_mask_write(EC_SCI_SRC_ALL);
/* Power/battery status might have changed */
battery_status_changed();
ac_status_changed();
return 0;
}
static const struct acpi_device_id xo15_sci_device_ids[] = {
{"XO15EC", 0},
{"", 0},
};
static struct acpi_driver xo15_sci_drv = {
.name = DRV_NAME,
.class = XO15_SCI_CLASS,
.ids = xo15_sci_device_ids,
.ops = {
.add = xo15_sci_add,
.remove = xo15_sci_remove,
.resume = xo15_sci_resume,
},
};
static int __init xo15_sci_init(void)
{
return acpi_bus_register_driver(&xo15_sci_drv);
}
device_initcall(xo15_sci_init);
| gpl-2.0 |
dastin1015/android_kernel_samsung_d710 | arch/s390/appldata/appldata_mem.c | 7305 | 4142 | /*
* arch/s390/appldata/appldata_mem.c
*
* Data gathering module for Linux-VM Monitor Stream, Stage 1.
* Collects data related to memory management.
*
* Copyright (C) 2003,2006 IBM Corporation, IBM Deutschland Entwicklung GmbH.
*
* Author: Gerald Schaefer <gerald.schaefer@de.ibm.com>
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kernel_stat.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <asm/io.h>
#include "appldata.h"
#define P2K(x) ((x) << (PAGE_SHIFT - 10)) /* Converts #Pages to KB */
/*
* Memory data
*
* This is accessed as binary data by z/VM. If changes to it can't be avoided,
* the structure version (product ID, see appldata_base.c) needs to be changed
* as well and all documentation and z/VM applications using it must be
* updated.
*
* The record layout is documented in the Linux for zSeries Device Drivers
* book:
* http://oss.software.ibm.com/developerworks/opensource/linux390/index.shtml
*/
static struct appldata_mem_data {
u64 timestamp;
u32 sync_count_1; /* after VM collected the record data, */
u32 sync_count_2; /* sync_count_1 and sync_count_2 should be the
same. If not, the record has been updated on
the Linux side while VM was collecting the
(possibly corrupt) data */
u64 pgpgin; /* data read from disk */
u64 pgpgout; /* data written to disk */
u64 pswpin; /* pages swapped in */
u64 pswpout; /* pages swapped out */
u64 sharedram; /* sharedram is currently set to 0 */
u64 totalram; /* total main memory size */
u64 freeram; /* free main memory size */
u64 totalhigh; /* total high memory size */
u64 freehigh; /* free high memory size */
u64 bufferram; /* memory reserved for buffers, free cache */
u64 cached; /* size of (used) cache, w/o buffers */
u64 totalswap; /* total swap space size */
u64 freeswap; /* free swap space */
// New in 2.6 -->
u64 pgalloc; /* page allocations */
u64 pgfault; /* page faults (major+minor) */
u64 pgmajfault; /* page faults (major only) */
// <-- New in 2.6
} __attribute__((packed)) appldata_mem_data;
/*
* appldata_get_mem_data()
*
* gather memory data
*/
static void appldata_get_mem_data(void *data)
{
/*
* don't put large structures on the stack, we are
* serialized through the appldata_ops_mutex and can use static
*/
static struct sysinfo val;
unsigned long ev[NR_VM_EVENT_ITEMS];
struct appldata_mem_data *mem_data;
mem_data = data;
mem_data->sync_count_1++;
all_vm_events(ev);
mem_data->pgpgin = ev[PGPGIN] >> 1;
mem_data->pgpgout = ev[PGPGOUT] >> 1;
mem_data->pswpin = ev[PSWPIN];
mem_data->pswpout = ev[PSWPOUT];
mem_data->pgalloc = ev[PGALLOC_NORMAL];
mem_data->pgalloc += ev[PGALLOC_DMA];
mem_data->pgfault = ev[PGFAULT];
mem_data->pgmajfault = ev[PGMAJFAULT];
si_meminfo(&val);
mem_data->sharedram = val.sharedram;
mem_data->totalram = P2K(val.totalram);
mem_data->freeram = P2K(val.freeram);
mem_data->totalhigh = P2K(val.totalhigh);
mem_data->freehigh = P2K(val.freehigh);
mem_data->bufferram = P2K(val.bufferram);
mem_data->cached = P2K(global_page_state(NR_FILE_PAGES)
- val.bufferram);
si_swapinfo(&val);
mem_data->totalswap = P2K(val.totalswap);
mem_data->freeswap = P2K(val.freeswap);
mem_data->timestamp = get_clock();
mem_data->sync_count_2++;
}
static struct appldata_ops ops = {
.name = "mem",
.record_nr = APPLDATA_RECORD_MEM_ID,
.size = sizeof(struct appldata_mem_data),
.callback = &appldata_get_mem_data,
.data = &appldata_mem_data,
.owner = THIS_MODULE,
.mod_lvl = {0xF0, 0xF0}, /* EBCDIC "00" */
};
/*
* appldata_mem_init()
*
* init_data, register ops
*/
static int __init appldata_mem_init(void)
{
return appldata_register_ops(&ops);
}
/*
* appldata_mem_exit()
*
* unregister ops
*/
static void __exit appldata_mem_exit(void)
{
appldata_unregister_ops(&ops);
}
module_init(appldata_mem_init);
module_exit(appldata_mem_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Gerald Schaefer");
MODULE_DESCRIPTION("Linux-VM Monitor Stream, MEMORY statistics");
| gpl-2.0 |
Marvellousteam/android_kernel_htc_msm7227 | arch/mn10300/lib/usercopy.c | 12681 | 3548 | /* MN10300 Userspace accessor functions
*
* Copyright (C) 2007 Matsushita Electric Industrial Co., Ltd.
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <asm/uaccess.h>
unsigned long
__generic_copy_to_user(void *to, const void *from, unsigned long n)
{
if (access_ok(VERIFY_WRITE, to, n))
__copy_user(to, from, n);
return n;
}
unsigned long
__generic_copy_from_user(void *to, const void *from, unsigned long n)
{
if (access_ok(VERIFY_READ, from, n))
__copy_user_zeroing(to, from, n);
return n;
}
/*
* Copy a null terminated string from userspace.
*/
#define __do_strncpy_from_user(dst, src, count, res) \
do { \
int w; \
asm volatile( \
" mov %1,%0\n" \
" cmp 0,%1\n" \
" beq 2f\n" \
"0:\n" \
" movbu (%5),%2\n" \
"1:\n" \
" movbu %2,(%6)\n" \
" inc %5\n" \
" inc %6\n" \
" cmp 0,%2\n" \
" beq 2f\n" \
" add -1,%1\n" \
" bne 0b\n" \
"2:\n" \
" sub %1,%0\n" \
"3:\n" \
" .section .fixup,\"ax\"\n" \
"4:\n" \
" mov %3,%0\n" \
" jmp 3b\n" \
" .previous\n" \
" .section __ex_table,\"a\"\n" \
" .balign 4\n" \
" .long 0b,4b\n" \
" .long 1b,4b\n" \
" .previous" \
:"=&r"(res), "=r"(count), "=&r"(w) \
:"i"(-EFAULT), "1"(count), "a"(src), "a"(dst) \
: "memory", "cc"); \
} while (0)
long
__strncpy_from_user(char *dst, const char *src, long count)
{
long res;
__do_strncpy_from_user(dst, src, count, res);
return res;
}
long
strncpy_from_user(char *dst, const char *src, long count)
{
long res = -EFAULT;
if (access_ok(VERIFY_READ, src, 1))
__do_strncpy_from_user(dst, src, count, res);
return res;
}
/*
* Clear a userspace memory
*/
#define __do_clear_user(addr, size) \
do { \
int w; \
asm volatile( \
" cmp 0,%0\n" \
" beq 1f\n" \
" clr %1\n" \
"0: movbu %1,(%3,%2)\n" \
" inc %3\n" \
" cmp %0,%3\n" \
" bne 0b\n" \
"1:\n" \
" sub %3,%0\n" \
"2:\n" \
".section .fixup,\"ax\"\n" \
"3: jmp 2b\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
" .balign 4\n" \
" .long 0b,3b\n" \
".previous\n" \
: "+r"(size), "=&r"(w) \
: "a"(addr), "d"(0) \
: "memory", "cc"); \
} while (0)
unsigned long
__clear_user(void *to, unsigned long n)
{
__do_clear_user(to, n);
return n;
}
unsigned long
clear_user(void *to, unsigned long n)
{
if (access_ok(VERIFY_WRITE, to, n))
__do_clear_user(to, n);
return n;
}
/*
* Return the size of a string (including the ending 0)
*
* Return 0 on exception, a value greater than N if too long
*/
long strnlen_user(const char *s, long n)
{
unsigned long res, w;
if (!__addr_ok(s))
return 0;
if (n < 0 || n + (u_long) s > current_thread_info()->addr_limit.seg)
n = current_thread_info()->addr_limit.seg - (u_long)s;
asm volatile(
"0: cmp %4,%0\n"
" beq 2f\n"
"1: movbu (%0,%3),%1\n"
" inc %0\n"
" cmp 0,%1\n"
" beq 3f\n"
" bra 0b\n"
"2: clr %0\n"
"3:\n"
".section .fixup,\"ax\"\n"
"4: jmp 2b\n"
".previous\n"
".section __ex_table,\"a\"\n"
" .balign 4\n"
" .long 1b,4b\n"
".previous\n"
:"=d"(res), "=&r"(w)
:"0"(0), "a"(s), "r"(n)
: "memory", "cc");
return res;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.